session.go 30 KB

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