session.go 30 KB

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