session.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. // Copyright (c) 2012 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import (
  6. "bytes"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "strings"
  12. "sync"
  13. "time"
  14. "unicode"
  15. "github.com/gocql/gocql/internal/lru"
  16. )
  17. // Session is the interface used by users to interact with the database.
  18. //
  19. // It's safe for concurrent use by multiple goroutines and a typical usage
  20. // scenario is to have one global session object to interact with the
  21. // whole Cassandra cluster.
  22. //
  23. // This type extends the Node interface by adding a convinient query builder
  24. // and automatically sets a default consinstency level on all operations
  25. // that do not have a consistency level set.
  26. type Session struct {
  27. pool *policyConnPool
  28. cons Consistency
  29. pageSize int
  30. prefetch float64
  31. routingKeyInfoCache routingKeyInfoLRU
  32. schemaDescriber *schemaDescriber
  33. trace Tracer
  34. hostSource *ringDescriber
  35. ring ring
  36. mu sync.RWMutex
  37. hostFilter HostFilter
  38. control *controlConn
  39. // ring metadata
  40. hosts []HostInfo
  41. cfg ClusterConfig
  42. closeMu sync.RWMutex
  43. isClosed bool
  44. }
  45. // NewSession wraps an existing Node.
  46. func NewSession(cfg ClusterConfig) (*Session, error) {
  47. //Check that hosts in the ClusterConfig is not empty
  48. if len(cfg.Hosts) < 1 {
  49. return nil, ErrNoHosts
  50. }
  51. //Adjust the size of the prepared statements cache to match the latest configuration
  52. stmtsLRU.Lock()
  53. initStmtsLRU(cfg.MaxPreparedStmts)
  54. stmtsLRU.Unlock()
  55. s := &Session{
  56. cons: cfg.Consistency,
  57. prefetch: 0.25,
  58. cfg: cfg,
  59. pageSize: cfg.PageSize,
  60. }
  61. s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
  62. // I think it might be a good idea to simplify this and make it always discover
  63. // hosts, maybe with more filters.
  64. s.hostSource = &ringDescriber{
  65. session: s,
  66. closeChan: make(chan bool),
  67. }
  68. if !cfg.disableControlConn {
  69. s.control = createControlConn(s)
  70. if err := s.control.connect(cfg.Hosts); err != nil {
  71. return nil, err
  72. }
  73. // need to setup host source to check for broadcast_address in system.local
  74. localHasRPCAddr, _ := checkSystemLocal(s.control)
  75. s.hostSource.localHasRpcAddr = localHasRPCAddr
  76. hosts, _, err := s.hostSource.GetHosts()
  77. if err != nil {
  78. s.control.close()
  79. return nil, err
  80. }
  81. pool, err := cfg.PoolConfig.buildPool(s)
  82. if err != nil {
  83. return nil, err
  84. }
  85. s.pool = pool
  86. // TODO(zariel): this should be used to create initial metadata
  87. s.pool.SetHosts(hosts)
  88. } else {
  89. // TODO(zariel): remove branch for creating pools
  90. pool, err := cfg.PoolConfig.buildPool(s)
  91. if err != nil {
  92. return nil, err
  93. }
  94. s.pool = pool
  95. // we dont get host info
  96. hosts := make([]*HostInfo, len(cfg.Hosts))
  97. for i, addr := range cfg.Hosts {
  98. hosts[i] = &HostInfo{peer: addr}
  99. }
  100. s.pool.SetHosts(hosts)
  101. }
  102. // TODO(zariel): we probably dont need this any more as we verify that we
  103. // can connect to one of the endpoints supplied by using the control conn.
  104. // See if there are any connections in the pool
  105. if s.pool.Size() == 0 {
  106. s.Close()
  107. return nil, ErrNoConnectionsStarted
  108. }
  109. return s, nil
  110. }
  111. // SetConsistency sets the default consistency level for this session. This
  112. // setting can also be changed on a per-query basis and the default value
  113. // is Quorum.
  114. func (s *Session) SetConsistency(cons Consistency) {
  115. s.mu.Lock()
  116. s.cons = cons
  117. s.mu.Unlock()
  118. }
  119. // SetPageSize sets the default page size for this session. A value <= 0 will
  120. // disable paging. This setting can also be changed on a per-query basis.
  121. func (s *Session) SetPageSize(n int) {
  122. s.mu.Lock()
  123. s.pageSize = n
  124. s.mu.Unlock()
  125. }
  126. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  127. // there are only p*pageSize rows remaining, the next page will be requested
  128. // automatically. This value can also be changed on a per-query basis and
  129. // the default value is 0.25.
  130. func (s *Session) SetPrefetch(p float64) {
  131. s.mu.Lock()
  132. s.prefetch = p
  133. s.mu.Unlock()
  134. }
  135. // SetTrace sets the default tracer for this session. This setting can also
  136. // be changed on a per-query basis.
  137. func (s *Session) SetTrace(trace Tracer) {
  138. s.mu.Lock()
  139. s.trace = trace
  140. s.mu.Unlock()
  141. }
  142. // Query generates a new query object for interacting with the database.
  143. // Further details of the query may be tweaked using the resulting query
  144. // value before the query is executed. Query is automatically prepared
  145. // if it has not previously been executed.
  146. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  147. s.mu.RLock()
  148. qry := &Query{stmt: stmt, values: values, cons: s.cons,
  149. session: s, pageSize: s.pageSize, trace: s.trace,
  150. prefetch: s.prefetch, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  151. defaultTimestamp: s.cfg.DefaultTimestamp,
  152. }
  153. s.mu.RUnlock()
  154. return qry
  155. }
  156. type QueryInfo struct {
  157. Id []byte
  158. Args []ColumnInfo
  159. Rval []ColumnInfo
  160. PKeyColumns []int
  161. }
  162. // Bind generates a new query object based on the query statement passed in.
  163. // The query is automatically prepared if it has not previously been executed.
  164. // The binding callback allows the application to define which query argument
  165. // values will be marshalled as part of the query execution.
  166. // During execution, the meta data of the prepared query will be routed to the
  167. // binding callback, which is responsible for producing the query argument values.
  168. func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
  169. s.mu.RLock()
  170. qry := &Query{stmt: stmt, binding: b, cons: s.cons,
  171. session: s, pageSize: s.pageSize, trace: s.trace,
  172. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  173. s.mu.RUnlock()
  174. return qry
  175. }
  176. // Close closes all connections. The session is unusable after this
  177. // operation.
  178. func (s *Session) Close() {
  179. s.closeMu.Lock()
  180. defer s.closeMu.Unlock()
  181. if s.isClosed {
  182. return
  183. }
  184. s.isClosed = true
  185. s.pool.Close()
  186. if s.hostSource != nil {
  187. close(s.hostSource.closeChan)
  188. }
  189. if s.control != nil {
  190. s.control.close()
  191. }
  192. }
  193. func (s *Session) Closed() bool {
  194. s.closeMu.RLock()
  195. closed := s.isClosed
  196. s.closeMu.RUnlock()
  197. return closed
  198. }
  199. func (s *Session) executeQuery(qry *Query) *Iter {
  200. // fail fast
  201. if s.Closed() {
  202. return &Iter{err: ErrSessionClosed}
  203. }
  204. var iter *Iter
  205. qry.attempts = 0
  206. qry.totalLatency = 0
  207. for {
  208. host, conn := s.pool.Pick(qry)
  209. //Assign the error unavailable to the iterator
  210. if conn == nil {
  211. if qry.rt == nil || !qry.rt.Attempt(qry) {
  212. iter = &Iter{err: ErrNoConnections}
  213. break
  214. }
  215. continue
  216. }
  217. t := time.Now()
  218. iter = conn.executeQuery(qry)
  219. qry.totalLatency += time.Now().Sub(t).Nanoseconds()
  220. qry.attempts++
  221. //Exit for loop if the query was successful
  222. if iter.err == nil {
  223. host.Mark(iter.err)
  224. break
  225. }
  226. // Mark host as ok
  227. host.Mark(nil)
  228. if qry.rt == nil || !qry.rt.Attempt(qry) {
  229. break
  230. }
  231. }
  232. return iter
  233. }
  234. // KeyspaceMetadata returns the schema metadata for the keyspace specified.
  235. func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
  236. // fail fast
  237. if s.Closed() {
  238. return nil, ErrSessionClosed
  239. }
  240. if keyspace == "" {
  241. return nil, ErrNoKeyspace
  242. }
  243. s.mu.Lock()
  244. // lazy-init schemaDescriber
  245. if s.schemaDescriber == nil {
  246. s.schemaDescriber = newSchemaDescriber(s)
  247. }
  248. s.mu.Unlock()
  249. return s.schemaDescriber.getSchema(keyspace)
  250. }
  251. // returns routing key indexes and type info
  252. func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
  253. s.routingKeyInfoCache.mu.Lock()
  254. entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
  255. if cached {
  256. // done accessing the cache
  257. s.routingKeyInfoCache.mu.Unlock()
  258. // the entry is an inflight struct similiar to that used by
  259. // Conn to prepare statements
  260. inflight := entry.(*inflightCachedEntry)
  261. // wait for any inflight work
  262. inflight.wg.Wait()
  263. if inflight.err != nil {
  264. return nil, inflight.err
  265. }
  266. key, _ := inflight.value.(*routingKeyInfo)
  267. return key, nil
  268. }
  269. // create a new inflight entry while the data is created
  270. inflight := new(inflightCachedEntry)
  271. inflight.wg.Add(1)
  272. defer inflight.wg.Done()
  273. s.routingKeyInfoCache.lru.Add(stmt, inflight)
  274. s.routingKeyInfoCache.mu.Unlock()
  275. var (
  276. info *QueryInfo
  277. partitionKey []*ColumnMetadata
  278. )
  279. // get the query info for the statement
  280. host, conn := s.pool.Pick(nil)
  281. if conn == nil {
  282. // no connections
  283. inflight.err = ErrNoConnections
  284. // don't cache this error
  285. s.routingKeyInfoCache.Remove(stmt)
  286. return nil, inflight.err
  287. }
  288. info, inflight.err = conn.prepareStatement(stmt, nil)
  289. if inflight.err != nil {
  290. // don't cache this error
  291. s.routingKeyInfoCache.Remove(stmt)
  292. host.Mark(inflight.err)
  293. return nil, inflight.err
  294. }
  295. // Mark host as OK
  296. host.Mark(nil)
  297. if len(info.Args) == 0 {
  298. // no arguments, no routing key, and no error
  299. return nil, nil
  300. }
  301. // get the table metadata
  302. table := info.Args[0].Table
  303. var keyspaceMetadata *KeyspaceMetadata
  304. keyspaceMetadata, inflight.err = s.KeyspaceMetadata(s.cfg.Keyspace)
  305. if inflight.err != nil {
  306. // don't cache this error
  307. s.routingKeyInfoCache.Remove(stmt)
  308. return nil, inflight.err
  309. }
  310. tableMetadata, found := keyspaceMetadata.Tables[table]
  311. if !found {
  312. // unlikely that the statement could be prepared and the metadata for
  313. // the table couldn't be found, but this may indicate either a bug
  314. // in the metadata code, or that the table was just dropped.
  315. inflight.err = ErrNoMetadata
  316. // don't cache this error
  317. s.routingKeyInfoCache.Remove(stmt)
  318. return nil, inflight.err
  319. }
  320. partitionKey = tableMetadata.PartitionKey
  321. size := len(partitionKey)
  322. routingKeyInfo := &routingKeyInfo{
  323. indexes: make([]int, size),
  324. types: make([]TypeInfo, size),
  325. }
  326. for keyIndex, keyColumn := range partitionKey {
  327. // set an indicator for checking if the mapping is missing
  328. routingKeyInfo.indexes[keyIndex] = -1
  329. // find the column in the query info
  330. for argIndex, boundColumn := range info.Args {
  331. if keyColumn.Name == boundColumn.Name {
  332. // there may be many such bound columns, pick the first
  333. routingKeyInfo.indexes[keyIndex] = argIndex
  334. routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
  335. break
  336. }
  337. }
  338. if routingKeyInfo.indexes[keyIndex] == -1 {
  339. // missing a routing key column mapping
  340. // no routing key, and no error
  341. return nil, nil
  342. }
  343. }
  344. // cache this result
  345. inflight.value = routingKeyInfo
  346. return routingKeyInfo, nil
  347. }
  348. func (s *Session) executeBatch(batch *Batch) (*Iter, error) {
  349. // fail fast
  350. if s.Closed() {
  351. return nil, ErrSessionClosed
  352. }
  353. // Prevent the execution of the batch if greater than the limit
  354. // Currently batches have a limit of 65536 queries.
  355. // https://datastax-oss.atlassian.net/browse/JAVA-229
  356. if batch.Size() > BatchSizeMaximum {
  357. return nil, ErrTooManyStmts
  358. }
  359. var err error
  360. var iter *Iter
  361. batch.attempts = 0
  362. batch.totalLatency = 0
  363. for {
  364. host, conn := s.pool.Pick(nil)
  365. //Assign the error unavailable and break loop
  366. if conn == nil {
  367. err = ErrNoConnections
  368. break
  369. }
  370. t := time.Now()
  371. iter, err = conn.executeBatch(batch)
  372. batch.totalLatency += time.Now().Sub(t).Nanoseconds()
  373. batch.attempts++
  374. //Exit loop if operation executed correctly
  375. if err == nil {
  376. host.Mark(err)
  377. return iter, err
  378. }
  379. // Mark host as OK
  380. host.Mark(nil)
  381. if batch.rt == nil || !batch.rt.Attempt(batch) {
  382. break
  383. }
  384. }
  385. return nil, err
  386. }
  387. // ExecuteBatch executes a batch operation and returns nil if successful
  388. // otherwise an error is returned describing the failure.
  389. func (s *Session) ExecuteBatch(batch *Batch) error {
  390. _, err := s.executeBatch(batch)
  391. return err
  392. }
  393. // ExecuteBatchCAS executes a batch operation and returns nil if successful and
  394. // an iterator (to scan aditional rows if more than one conditional statement)
  395. // was sent, otherwise an error is returned describing the failure.
  396. // Further scans on the interator must also remember to include
  397. // the applied boolean as the first argument to *Iter.Scan
  398. func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (applied bool, iter *Iter, err error) {
  399. if iter, err := s.executeBatch(batch); err == nil {
  400. if err := iter.checkErrAndNotFound(); err != nil {
  401. return false, nil, err
  402. }
  403. if len(iter.Columns()) > 1 {
  404. dest = append([]interface{}{&applied}, dest...)
  405. iter.Scan(dest...)
  406. } else {
  407. iter.Scan(&applied)
  408. }
  409. return applied, iter, nil
  410. } else {
  411. return false, nil, err
  412. }
  413. }
  414. // MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,
  415. // however it accepts a map rather than a list of arguments for the initial
  416. // scan.
  417. func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
  418. if iter, err := s.executeBatch(batch); err == nil {
  419. if err := iter.checkErrAndNotFound(); err != nil {
  420. return false, nil, err
  421. }
  422. iter.MapScan(dest)
  423. applied = dest["[applied]"].(bool)
  424. delete(dest, "[applied]")
  425. // we usually close here, but instead of closing, just returin an error
  426. // if MapScan failed. Although Close just returns err, using Close
  427. // here might be confusing as we are not actually closing the iter
  428. return applied, iter, iter.err
  429. } else {
  430. return false, nil, err
  431. }
  432. }
  433. // Query represents a CQL statement that can be executed.
  434. type Query struct {
  435. stmt string
  436. values []interface{}
  437. cons Consistency
  438. pageSize int
  439. routingKey []byte
  440. routingKeyBuffer []byte
  441. pageState []byte
  442. prefetch float64
  443. trace Tracer
  444. session *Session
  445. rt RetryPolicy
  446. binding func(q *QueryInfo) ([]interface{}, error)
  447. attempts int
  448. totalLatency int64
  449. serialCons SerialConsistency
  450. defaultTimestamp bool
  451. disableAutoPage bool
  452. }
  453. // String implements the stringer interface.
  454. func (q Query) String() string {
  455. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  456. }
  457. //Attempts returns the number of times the query was executed.
  458. func (q *Query) Attempts() int {
  459. return q.attempts
  460. }
  461. //Latency returns the average amount of nanoseconds per attempt of the query.
  462. func (q *Query) Latency() int64 {
  463. if q.attempts > 0 {
  464. return q.totalLatency / int64(q.attempts)
  465. }
  466. return 0
  467. }
  468. // Consistency sets the consistency level for this query. If no consistency
  469. // level have been set, the default consistency level of the cluster
  470. // is used.
  471. func (q *Query) Consistency(c Consistency) *Query {
  472. q.cons = c
  473. return q
  474. }
  475. // GetConsistency returns the currently configured consistency level for
  476. // the query.
  477. func (q *Query) GetConsistency() Consistency {
  478. return q.cons
  479. }
  480. // Trace enables tracing of this query. Look at the documentation of the
  481. // Tracer interface to learn more about tracing.
  482. func (q *Query) Trace(trace Tracer) *Query {
  483. q.trace = trace
  484. return q
  485. }
  486. // PageSize will tell the iterator to fetch the result in pages of size n.
  487. // This is useful for iterating over large result sets, but setting the
  488. // page size to low might decrease the performance. This feature is only
  489. // available in Cassandra 2 and onwards.
  490. func (q *Query) PageSize(n int) *Query {
  491. q.pageSize = n
  492. return q
  493. }
  494. // DefaultTimestamp will enable the with default timestamp flag on the query.
  495. // If enable, this will replace the server side assigned
  496. // timestamp as default timestamp. Note that a timestamp in the query itself
  497. // will still override this timestamp. This is entirely optional.
  498. //
  499. // Only available on protocol >= 3
  500. func (q *Query) DefaultTimestamp(enable bool) *Query {
  501. q.defaultTimestamp = enable
  502. return q
  503. }
  504. // RoutingKey sets the routing key to use when a token aware connection
  505. // pool is used to optimize the routing of this query.
  506. func (q *Query) RoutingKey(routingKey []byte) *Query {
  507. q.routingKey = routingKey
  508. return q
  509. }
  510. // GetRoutingKey gets the routing key to use for routing this query. If
  511. // a routing key has not been explicitly set, then the routing key will
  512. // be constructed if possible using the keyspace's schema and the query
  513. // info for this query statement. If the routing key cannot be determined
  514. // then nil will be returned with no error. On any error condition,
  515. // an error description will be returned.
  516. func (q *Query) GetRoutingKey() ([]byte, error) {
  517. if q.routingKey != nil {
  518. return q.routingKey, nil
  519. }
  520. // try to determine the routing key
  521. routingKeyInfo, err := q.session.routingKeyInfo(q.stmt)
  522. if err != nil {
  523. return nil, err
  524. }
  525. if routingKeyInfo == nil {
  526. return nil, nil
  527. }
  528. if len(routingKeyInfo.indexes) == 1 {
  529. // single column routing key
  530. routingKey, err := Marshal(
  531. routingKeyInfo.types[0],
  532. q.values[routingKeyInfo.indexes[0]],
  533. )
  534. if err != nil {
  535. return nil, err
  536. }
  537. return routingKey, nil
  538. }
  539. // We allocate that buffer only once, so that further re-bind/exec of the
  540. // same query don't allocate more memory.
  541. if q.routingKeyBuffer == nil {
  542. q.routingKeyBuffer = make([]byte, 0, 256)
  543. }
  544. // composite routing key
  545. buf := bytes.NewBuffer(q.routingKeyBuffer)
  546. for i := range routingKeyInfo.indexes {
  547. encoded, err := Marshal(
  548. routingKeyInfo.types[i],
  549. q.values[routingKeyInfo.indexes[i]],
  550. )
  551. if err != nil {
  552. return nil, err
  553. }
  554. lenBuf := []byte{0x00, 0x00}
  555. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  556. buf.Write(lenBuf)
  557. buf.Write(encoded)
  558. buf.WriteByte(0x00)
  559. }
  560. routingKey := buf.Bytes()
  561. return routingKey, nil
  562. }
  563. func (q *Query) shouldPrepare() bool {
  564. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  565. return unicode.IsSpace(r) || r == ';'
  566. }), unicode.IsSpace)
  567. var stmtType string
  568. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  569. stmtType = strings.ToLower(stmt[:n])
  570. }
  571. if stmtType == "begin" {
  572. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  573. stmtType = strings.ToLower(stmt[n+1:])
  574. }
  575. }
  576. switch stmtType {
  577. case "select", "insert", "update", "delete", "batch":
  578. return true
  579. }
  580. return false
  581. }
  582. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  583. // there are only p*pageSize rows remaining, the next page will be requested
  584. // automatically.
  585. func (q *Query) Prefetch(p float64) *Query {
  586. q.prefetch = p
  587. return q
  588. }
  589. // RetryPolicy sets the policy to use when retrying the query.
  590. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  591. q.rt = r
  592. return q
  593. }
  594. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  595. // to an existing query instance.
  596. func (q *Query) Bind(v ...interface{}) *Query {
  597. q.values = v
  598. return q
  599. }
  600. // SerialConsistency sets the consistencyc level for the
  601. // serial phase of conditional updates. That consitency can only be
  602. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  603. // SERIAL. This option will be ignored for anything else that a
  604. // conditional update/insert.
  605. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  606. q.serialCons = cons
  607. return q
  608. }
  609. // PageState sets the paging state for the query to resume paging from a specific
  610. // point in time. Setting this will disable to query paging for this query, and
  611. // must be used for all subsequent pages.
  612. func (q *Query) PageState(state []byte) *Query {
  613. q.pageState = state
  614. q.disableAutoPage = true
  615. return q
  616. }
  617. // Exec executes the query without returning any rows.
  618. func (q *Query) Exec() error {
  619. iter := q.Iter()
  620. return iter.err
  621. }
  622. func isUseStatement(stmt string) bool {
  623. if len(stmt) < 3 {
  624. return false
  625. }
  626. return strings.ToLower(stmt[0:3]) == "use"
  627. }
  628. // Iter executes the query and returns an iterator capable of iterating
  629. // over all results.
  630. func (q *Query) Iter() *Iter {
  631. if isUseStatement(q.stmt) {
  632. return &Iter{err: ErrUseStmt}
  633. }
  634. return q.session.executeQuery(q)
  635. }
  636. // MapScan executes the query, copies the columns of the first selected
  637. // row into the map pointed at by m and discards the rest. If no rows
  638. // were selected, ErrNotFound is returned.
  639. func (q *Query) MapScan(m map[string]interface{}) error {
  640. iter := q.Iter()
  641. if err := iter.checkErrAndNotFound(); err != nil {
  642. return err
  643. }
  644. iter.MapScan(m)
  645. return iter.Close()
  646. }
  647. // Scan executes the query, copies the columns of the first selected
  648. // row into the values pointed at by dest and discards the rest. If no rows
  649. // were selected, ErrNotFound is returned.
  650. func (q *Query) Scan(dest ...interface{}) error {
  651. iter := q.Iter()
  652. if err := iter.checkErrAndNotFound(); err != nil {
  653. return err
  654. }
  655. iter.Scan(dest...)
  656. return iter.Close()
  657. }
  658. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  659. // statement containing an IF clause). If the transaction fails because
  660. // the existing values did not match, the previous values will be stored
  661. // in dest.
  662. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  663. iter := q.Iter()
  664. if err := iter.checkErrAndNotFound(); err != nil {
  665. return false, err
  666. }
  667. if len(iter.Columns()) > 1 {
  668. dest = append([]interface{}{&applied}, dest...)
  669. iter.Scan(dest...)
  670. } else {
  671. iter.Scan(&applied)
  672. }
  673. return applied, iter.Close()
  674. }
  675. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  676. // statement containing an IF clause). If the transaction fails because
  677. // the existing values did not match, the previous values will be stored
  678. // in dest map.
  679. //
  680. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  681. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  682. // column mismatching. MapScanCAS is added to capture them safely.
  683. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  684. iter := q.Iter()
  685. if err := iter.checkErrAndNotFound(); err != nil {
  686. return false, err
  687. }
  688. iter.MapScan(dest)
  689. applied = dest["[applied]"].(bool)
  690. delete(dest, "[applied]")
  691. return applied, iter.Close()
  692. }
  693. // Iter represents an iterator that can be used to iterate over all rows that
  694. // were returned by a query. The iterator might send additional queries to the
  695. // database during the iteration if paging was enabled.
  696. type Iter struct {
  697. err error
  698. pos int
  699. rows [][][]byte
  700. meta resultMetadata
  701. next *nextIter
  702. framer *framer
  703. once sync.Once
  704. }
  705. // Columns returns the name and type of the selected columns.
  706. func (iter *Iter) Columns() []ColumnInfo {
  707. return iter.meta.columns
  708. }
  709. // Scan consumes the next row of the iterator and copies the columns of the
  710. // current row into the values pointed at by dest. Use nil as a dest value
  711. // to skip the corresponding column. Scan might send additional queries
  712. // to the database to retrieve the next set of rows if paging was enabled.
  713. //
  714. // Scan returns true if the row was successfully unmarshaled or false if the
  715. // end of the result set was reached or if an error occurred. Close should
  716. // be called afterwards to retrieve any potential errors.
  717. func (iter *Iter) Scan(dest ...interface{}) bool {
  718. if iter.err != nil {
  719. return false
  720. }
  721. if iter.pos >= len(iter.rows) {
  722. if iter.next != nil {
  723. *iter = *iter.next.fetch()
  724. return iter.Scan(dest...)
  725. }
  726. return false
  727. }
  728. if iter.next != nil && iter.pos == iter.next.pos {
  729. go iter.next.fetch()
  730. }
  731. // currently only support scanning into an expand tuple, such that its the same
  732. // as scanning in more values from a single column
  733. if len(dest) != iter.meta.actualColCount {
  734. iter.err = errors.New("count mismatch")
  735. return false
  736. }
  737. // i is the current position in dest, could posible replace it and just use
  738. // slices of dest
  739. i := 0
  740. for c, col := range iter.meta.columns {
  741. if dest[i] == nil {
  742. i++
  743. continue
  744. }
  745. switch col.TypeInfo.Type() {
  746. case TypeTuple:
  747. // this will panic, actually a bug, please report
  748. tuple := col.TypeInfo.(TupleTypeInfo)
  749. count := len(tuple.Elems)
  750. // here we pass in a slice of the struct which has the number number of
  751. // values as elements in the tuple
  752. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
  753. i += count
  754. default:
  755. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
  756. i++
  757. }
  758. if iter.err != nil {
  759. return false
  760. }
  761. }
  762. iter.pos++
  763. return true
  764. }
  765. // Close closes the iterator and returns any errors that happened during
  766. // the query or the iteration.
  767. func (iter *Iter) Close() error {
  768. iter.once.Do(func() {
  769. if iter.framer != nil {
  770. framerPool.Put(iter.framer)
  771. iter.framer = nil
  772. }
  773. })
  774. return iter.err
  775. }
  776. // WillSwitchPage detects if iterator reached end of current page
  777. // and the next page is available.
  778. func (iter *Iter) WillSwitchPage() bool {
  779. return iter.pos >= len(iter.rows) && iter.next != nil
  780. }
  781. // checkErrAndNotFound handle error and NotFound in one method.
  782. func (iter *Iter) checkErrAndNotFound() error {
  783. if iter.err != nil {
  784. return iter.err
  785. } else if len(iter.rows) == 0 {
  786. return ErrNotFound
  787. }
  788. return nil
  789. }
  790. // PageState return the current paging state for a query which can be used for
  791. // subsequent quries to resume paging this point.
  792. func (iter *Iter) PageState() []byte {
  793. return iter.meta.pagingState
  794. }
  795. type nextIter struct {
  796. qry Query
  797. pos int
  798. once sync.Once
  799. next *Iter
  800. }
  801. func (n *nextIter) fetch() *Iter {
  802. n.once.Do(func() {
  803. n.next = n.qry.session.executeQuery(&n.qry)
  804. })
  805. return n.next
  806. }
  807. type Batch struct {
  808. Type BatchType
  809. Entries []BatchEntry
  810. Cons Consistency
  811. rt RetryPolicy
  812. attempts int
  813. totalLatency int64
  814. serialCons SerialConsistency
  815. defaultTimestamp bool
  816. }
  817. // NewBatch creates a new batch operation without defaults from the cluster
  818. func NewBatch(typ BatchType) *Batch {
  819. return &Batch{Type: typ}
  820. }
  821. // NewBatch creates a new batch operation using defaults defined in the cluster
  822. func (s *Session) NewBatch(typ BatchType) *Batch {
  823. s.mu.RLock()
  824. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  825. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  826. s.mu.RUnlock()
  827. return batch
  828. }
  829. // Attempts returns the number of attempts made to execute the batch.
  830. func (b *Batch) Attempts() int {
  831. return b.attempts
  832. }
  833. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  834. func (b *Batch) Latency() int64 {
  835. if b.attempts > 0 {
  836. return b.totalLatency / int64(b.attempts)
  837. }
  838. return 0
  839. }
  840. // GetConsistency returns the currently configured consistency level for the batch
  841. // operation.
  842. func (b *Batch) GetConsistency() Consistency {
  843. return b.Cons
  844. }
  845. // Query adds the query to the batch operation
  846. func (b *Batch) Query(stmt string, args ...interface{}) {
  847. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  848. }
  849. // Bind adds the query to the batch operation and correlates it with a binding callback
  850. // that will be invoked when the batch is executed. The binding callback allows the application
  851. // to define which query argument values will be marshalled as part of the batch execution.
  852. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  853. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  854. }
  855. // RetryPolicy sets the retry policy to use when executing the batch operation
  856. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  857. b.rt = r
  858. return b
  859. }
  860. // Size returns the number of batch statements to be executed by the batch operation.
  861. func (b *Batch) Size() int {
  862. return len(b.Entries)
  863. }
  864. // SerialConsistency sets the consistencyc level for the
  865. // serial phase of conditional updates. That consitency can only be
  866. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  867. // SERIAL. This option will be ignored for anything else that a
  868. // conditional update/insert.
  869. //
  870. // Only available for protocol 3 and above
  871. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  872. b.serialCons = cons
  873. return b
  874. }
  875. // DefaultTimestamp will enable the with default timestamp flag on the query.
  876. // If enable, this will replace the server side assigned
  877. // timestamp as default timestamp. Note that a timestamp in the query itself
  878. // will still override this timestamp. This is entirely optional.
  879. //
  880. // Only available on protocol >= 3
  881. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  882. b.defaultTimestamp = enable
  883. return b
  884. }
  885. type BatchType byte
  886. const (
  887. LoggedBatch BatchType = 0
  888. UnloggedBatch BatchType = 1
  889. CounterBatch BatchType = 2
  890. )
  891. type BatchEntry struct {
  892. Stmt string
  893. Args []interface{}
  894. binding func(q *QueryInfo) ([]interface{}, error)
  895. }
  896. type ColumnInfo struct {
  897. Keyspace string
  898. Table string
  899. Name string
  900. TypeInfo TypeInfo
  901. }
  902. func (c ColumnInfo) String() string {
  903. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  904. }
  905. // routing key indexes LRU cache
  906. type routingKeyInfoLRU struct {
  907. lru *lru.Cache
  908. mu sync.Mutex
  909. }
  910. type routingKeyInfo struct {
  911. indexes []int
  912. types []TypeInfo
  913. }
  914. func (r *routingKeyInfoLRU) Remove(key string) {
  915. r.mu.Lock()
  916. r.lru.Remove(key)
  917. r.mu.Unlock()
  918. }
  919. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  920. //the new max is lower than the previous value. Not concurrency safe.
  921. func (r *routingKeyInfoLRU) Max(max int) {
  922. r.mu.Lock()
  923. for r.lru.Len() > max {
  924. r.lru.RemoveOldest()
  925. }
  926. r.lru.MaxEntries = max
  927. r.mu.Unlock()
  928. }
  929. type inflightCachedEntry struct {
  930. wg sync.WaitGroup
  931. err error
  932. value interface{}
  933. }
  934. // Tracer is the interface implemented by query tracers. Tracers have the
  935. // ability to obtain a detailed event log of all events that happened during
  936. // the execution of a query from Cassandra. Gathering this information might
  937. // be essential for debugging and optimizing queries, but this feature should
  938. // not be used on production systems with very high load.
  939. type Tracer interface {
  940. Trace(traceId []byte)
  941. }
  942. type traceWriter struct {
  943. session *Session
  944. w io.Writer
  945. mu sync.Mutex
  946. }
  947. // NewTraceWriter returns a simple Tracer implementation that outputs
  948. // the event log in a textual format.
  949. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  950. return &traceWriter{session: session, w: w}
  951. }
  952. func (t *traceWriter) Trace(traceId []byte) {
  953. var (
  954. coordinator string
  955. duration int
  956. )
  957. iter := t.session.control.query(`SELECT coordinator, duration
  958. FROM system_traces.sessions
  959. WHERE session_id = ?`, traceId)
  960. iter.Scan(&coordinator, &duration)
  961. if err := iter.Close(); err != nil {
  962. t.mu.Lock()
  963. fmt.Fprintln(t.w, "Error:", err)
  964. t.mu.Unlock()
  965. return
  966. }
  967. var (
  968. timestamp time.Time
  969. activity string
  970. source string
  971. elapsed int
  972. )
  973. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  974. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  975. t.mu.Lock()
  976. defer t.mu.Unlock()
  977. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  978. FROM system_traces.events
  979. WHERE session_id = ?`, traceId)
  980. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  981. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  982. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  983. }
  984. if err := iter.Close(); err != nil {
  985. fmt.Fprintln(t.w, "Error:", err)
  986. }
  987. }
  988. type Error struct {
  989. Code int
  990. Message string
  991. }
  992. func (e Error) Error() string {
  993. return e.Message
  994. }
  995. var (
  996. ErrNotFound = errors.New("not found")
  997. ErrUnavailable = errors.New("unavailable")
  998. ErrUnsupported = errors.New("feature not supported")
  999. ErrTooManyStmts = errors.New("too many statements")
  1000. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  1001. ErrSessionClosed = errors.New("session has been closed")
  1002. ErrNoConnections = errors.New("no connections available")
  1003. ErrNoKeyspace = errors.New("no keyspace provided")
  1004. ErrNoMetadata = errors.New("no metadata available")
  1005. )
  1006. type ErrProtocol struct{ error }
  1007. func NewErrProtocol(format string, args ...interface{}) error {
  1008. return ErrProtocol{fmt.Errorf(format, args...)}
  1009. }
  1010. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1011. // This limit is set by cassandra and could change in the future.
  1012. const BatchSizeMaximum = 65535