session.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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/golang/groupcache/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. cacheKey := s.cfg.Keyspace + stmt
  220. entry, cached := s.routingKeyInfoCache.lru.Get(cacheKey)
  221. if cached {
  222. // done accessing the cache
  223. s.routingKeyInfoCache.mu.Unlock()
  224. // the entry is an inflight struct similiar to that used by
  225. // Conn to prepare statements
  226. inflight := entry.(*inflightCachedEntry)
  227. // wait for any inflight work
  228. inflight.wg.Wait()
  229. if inflight.err != nil {
  230. return nil, inflight.err
  231. }
  232. key, _ := inflight.value.(*routingKeyInfo)
  233. return key, nil
  234. }
  235. // create a new inflight entry while the data is created
  236. inflight := new(inflightCachedEntry)
  237. inflight.wg.Add(1)
  238. defer inflight.wg.Done()
  239. s.routingKeyInfoCache.lru.Add(cacheKey, inflight)
  240. s.routingKeyInfoCache.mu.Unlock()
  241. var (
  242. prepared *resultPreparedFrame
  243. partitionKey []*ColumnMetadata
  244. )
  245. // get the query info for the statement
  246. conn := s.Pool.Pick(nil)
  247. if conn == nil {
  248. // no connections
  249. inflight.err = ErrNoConnections
  250. // don't cache this error
  251. s.routingKeyInfoCache.Remove(cacheKey)
  252. return nil, inflight.err
  253. }
  254. prepared, inflight.err = conn.prepareStatement(stmt, nil)
  255. if inflight.err != nil {
  256. // don't cache this error
  257. s.routingKeyInfoCache.Remove(cacheKey)
  258. return nil, inflight.err
  259. }
  260. if len(prepared.reqMeta.columns) == 0 {
  261. // no arguments, no routing key, and no error
  262. return nil, nil
  263. }
  264. // get the table metadata
  265. table := prepared.reqMeta.columns[0].Table
  266. var keyspaceMetadata *KeyspaceMetadata
  267. keyspaceMetadata, inflight.err = s.KeyspaceMetadata(s.cfg.Keyspace)
  268. if inflight.err != nil {
  269. // don't cache this error
  270. s.routingKeyInfoCache.Remove(cacheKey)
  271. return nil, inflight.err
  272. }
  273. tableMetadata, found := keyspaceMetadata.Tables[table]
  274. if !found {
  275. // unlikely that the statement could be prepared and the metadata for
  276. // the table couldn't be found, but this may indicate either a bug
  277. // in the metadata code, or that the table was just dropped.
  278. inflight.err = ErrNoMetadata
  279. // don't cache this error
  280. s.routingKeyInfoCache.Remove(cacheKey)
  281. return nil, inflight.err
  282. }
  283. partitionKey = tableMetadata.PartitionKey
  284. size := len(partitionKey)
  285. routingKeyInfo := &routingKeyInfo{
  286. indexes: make([]int, size),
  287. types: make([]TypeInfo, size),
  288. }
  289. for keyIndex, keyColumn := range partitionKey {
  290. // set an indicator for checking if the mapping is missing
  291. routingKeyInfo.indexes[keyIndex] = -1
  292. // find the column in the query info
  293. for argIndex, boundColumn := range prepared.reqMeta.columns {
  294. if keyColumn.Name == boundColumn.Name {
  295. // there may be many such bound columns, pick the first
  296. routingKeyInfo.indexes[keyIndex] = argIndex
  297. routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
  298. break
  299. }
  300. }
  301. if routingKeyInfo.indexes[keyIndex] == -1 {
  302. // missing a routing key column mapping
  303. // no routing key, and no error
  304. return nil, nil
  305. }
  306. }
  307. // cache this result
  308. inflight.value = routingKeyInfo
  309. return routingKeyInfo, nil
  310. }
  311. // ExecuteBatch executes a batch operation and returns nil if successful
  312. // otherwise an error is returned describing the failure.
  313. func (s *Session) ExecuteBatch(batch *Batch) error {
  314. // fail fast
  315. if s.Closed() {
  316. return ErrSessionClosed
  317. }
  318. // Prevent the execution of the batch if greater than the limit
  319. // Currently batches have a limit of 65536 queries.
  320. // https://datastax-oss.atlassian.net/browse/JAVA-229
  321. if batch.Size() > BatchSizeMaximum {
  322. return ErrTooManyStmts
  323. }
  324. var err error
  325. batch.attempts = 0
  326. batch.totalLatency = 0
  327. for {
  328. conn := s.Pool.Pick(nil)
  329. //Assign the error unavailable and break loop
  330. if conn == nil {
  331. err = ErrNoConnections
  332. break
  333. }
  334. t := time.Now()
  335. err = conn.executeBatch(batch)
  336. batch.totalLatency += time.Now().Sub(t).Nanoseconds()
  337. batch.attempts++
  338. //Exit loop if operation executed correctly
  339. if err == nil {
  340. return nil
  341. }
  342. if batch.rt == nil || !batch.rt.Attempt(batch) {
  343. break
  344. }
  345. }
  346. return err
  347. }
  348. // Query represents a CQL statement that can be executed.
  349. type Query struct {
  350. stmt string
  351. values []interface{}
  352. cons Consistency
  353. pageSize int
  354. routingKey []byte
  355. pageState []byte
  356. prefetch float64
  357. trace Tracer
  358. session *Session
  359. rt RetryPolicy
  360. binding func(q *QueryInfo) ([]interface{}, error)
  361. attempts int
  362. totalLatency int64
  363. serialCons SerialConsistency
  364. defaultTimestamp bool
  365. }
  366. // String implements the stringer interface.
  367. func (q Query) String() string {
  368. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  369. }
  370. //Attempts returns the number of times the query was executed.
  371. func (q *Query) Attempts() int {
  372. return q.attempts
  373. }
  374. //Latency returns the average amount of nanoseconds per attempt of the query.
  375. func (q *Query) Latency() int64 {
  376. if q.attempts > 0 {
  377. return q.totalLatency / int64(q.attempts)
  378. }
  379. return 0
  380. }
  381. // Consistency sets the consistency level for this query. If no consistency
  382. // level have been set, the default consistency level of the cluster
  383. // is used.
  384. func (q *Query) Consistency(c Consistency) *Query {
  385. q.cons = c
  386. return q
  387. }
  388. // GetConsistency returns the currently configured consistency level for
  389. // the query.
  390. func (q *Query) GetConsistency() Consistency {
  391. return q.cons
  392. }
  393. // Trace enables tracing of this query. Look at the documentation of the
  394. // Tracer interface to learn more about tracing.
  395. func (q *Query) Trace(trace Tracer) *Query {
  396. q.trace = trace
  397. return q
  398. }
  399. // PageSize will tell the iterator to fetch the result in pages of size n.
  400. // This is useful for iterating over large result sets, but setting the
  401. // page size to low might decrease the performance. This feature is only
  402. // available in Cassandra 2 and onwards.
  403. func (q *Query) PageSize(n int) *Query {
  404. q.pageSize = n
  405. return q
  406. }
  407. // DefaultTimestamp will enable the with default timestamp flag on the query.
  408. // If enable, this will replace the server side assigned
  409. // timestamp as default timestamp. Note that a timestamp in the query itself
  410. // will still override this timestamp. This is entirely optional.
  411. //
  412. // Only available on protocol >= 3
  413. func (q *Query) DefaultTimestamp(enable bool) *Query {
  414. q.defaultTimestamp = enable
  415. return q
  416. }
  417. // RoutingKey sets the routing key to use when a token aware connection
  418. // pool is used to optimize the routing of this query.
  419. func (q *Query) RoutingKey(routingKey []byte) *Query {
  420. q.routingKey = routingKey
  421. return q
  422. }
  423. // GetRoutingKey gets the routing key to use for routing this query. If
  424. // a routing key has not been explicitly set, then the routing key will
  425. // be constructed if possible using the keyspace's schema and the query
  426. // info for this query statement. If the routing key cannot be determined
  427. // then nil will be returned with no error. On any error condition,
  428. // an error description will be returned.
  429. func (q *Query) GetRoutingKey() ([]byte, error) {
  430. if q.routingKey != nil {
  431. return q.routingKey, nil
  432. }
  433. // try to determine the routing key
  434. routingKeyInfo, err := q.session.routingKeyInfo(q.stmt)
  435. if err != nil {
  436. return nil, err
  437. }
  438. if routingKeyInfo == nil {
  439. return nil, nil
  440. }
  441. if len(routingKeyInfo.indexes) == 1 {
  442. // single column routing key
  443. routingKey, err := Marshal(
  444. routingKeyInfo.types[0],
  445. q.values[routingKeyInfo.indexes[0]],
  446. )
  447. if err != nil {
  448. return nil, err
  449. }
  450. return routingKey, nil
  451. }
  452. // composite routing key
  453. buf := bytes.NewBuffer(make([]byte, 0, 256))
  454. for i := range routingKeyInfo.indexes {
  455. encoded, err := Marshal(
  456. routingKeyInfo.types[i],
  457. q.values[routingKeyInfo.indexes[i]],
  458. )
  459. if err != nil {
  460. return nil, err
  461. }
  462. lenBuf := []byte{0x00, 0x00}
  463. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  464. buf.Write(lenBuf)
  465. buf.Write(encoded)
  466. buf.WriteByte(0x00)
  467. }
  468. routingKey := buf.Bytes()
  469. return routingKey, nil
  470. }
  471. func (q *Query) shouldPrepare() bool {
  472. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  473. return unicode.IsSpace(r) || r == ';'
  474. }), unicode.IsSpace)
  475. var stmtType string
  476. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  477. stmtType = strings.ToLower(stmt[:n])
  478. }
  479. if stmtType == "begin" {
  480. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  481. stmtType = strings.ToLower(stmt[n+1:])
  482. }
  483. }
  484. switch stmtType {
  485. case "select", "insert", "update", "delete", "batch":
  486. return true
  487. }
  488. return false
  489. }
  490. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  491. // there are only p*pageSize rows remaining, the next page will be requested
  492. // automatically.
  493. func (q *Query) Prefetch(p float64) *Query {
  494. q.prefetch = p
  495. return q
  496. }
  497. // RetryPolicy sets the policy to use when retrying the query.
  498. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  499. q.rt = r
  500. return q
  501. }
  502. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  503. // to an existing query instance.
  504. func (q *Query) Bind(v ...interface{}) *Query {
  505. q.values = v
  506. return q
  507. }
  508. // SerialConsistency sets the consistencyc level for the
  509. // serial phase of conditional updates. That consitency can only be
  510. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  511. // SERIAL. This option will be ignored for anything else that a
  512. // conditional update/insert.
  513. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  514. q.serialCons = cons
  515. return q
  516. }
  517. // Exec executes the query without returning any rows.
  518. func (q *Query) Exec() error {
  519. iter := q.Iter()
  520. return iter.err
  521. }
  522. // Iter executes the query and returns an iterator capable of iterating
  523. // over all results.
  524. func (q *Query) Iter() *Iter {
  525. if strings.Index(strings.ToLower(q.stmt), "use") == 0 {
  526. return &Iter{err: ErrUseStmt}
  527. }
  528. return q.session.executeQuery(q)
  529. }
  530. // MapScan executes the query, copies the columns of the first selected
  531. // row into the map pointed at by m and discards the rest. If no rows
  532. // were selected, ErrNotFound is returned.
  533. func (q *Query) MapScan(m map[string]interface{}) error {
  534. iter := q.Iter()
  535. if err := iter.checkErrAndNotFound(); err != nil {
  536. return err
  537. }
  538. iter.MapScan(m)
  539. return iter.Close()
  540. }
  541. // Scan executes the query, copies the columns of the first selected
  542. // row into the values pointed at by dest and discards the rest. If no rows
  543. // were selected, ErrNotFound is returned.
  544. func (q *Query) Scan(dest ...interface{}) error {
  545. iter := q.Iter()
  546. if err := iter.checkErrAndNotFound(); err != nil {
  547. return err
  548. }
  549. iter.Scan(dest...)
  550. return iter.Close()
  551. }
  552. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  553. // statement containing an IF clause). If the transaction fails because
  554. // the existing values did not match, the previous values will be stored
  555. // in dest.
  556. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  557. iter := q.Iter()
  558. if err := iter.checkErrAndNotFound(); err != nil {
  559. return false, err
  560. }
  561. if len(iter.Columns()) > 1 {
  562. dest = append([]interface{}{&applied}, dest...)
  563. iter.Scan(dest...)
  564. } else {
  565. iter.Scan(&applied)
  566. }
  567. return applied, iter.Close()
  568. }
  569. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  570. // statement containing an IF clause). If the transaction fails because
  571. // the existing values did not match, the previous values will be stored
  572. // in dest map.
  573. //
  574. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  575. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  576. // column mismatching. MapScanCAS is added to capture them safely.
  577. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  578. iter := q.Iter()
  579. if err := iter.checkErrAndNotFound(); err != nil {
  580. return false, err
  581. }
  582. iter.MapScan(dest)
  583. applied = dest["[applied]"].(bool)
  584. delete(dest, "[applied]")
  585. return applied, iter.Close()
  586. }
  587. // Iter represents an iterator that can be used to iterate over all rows that
  588. // were returned by a query. The iterator might send additional queries to the
  589. // database during the iteration if paging was enabled.
  590. type Iter struct {
  591. err error
  592. pos int
  593. rows [][][]byte
  594. meta resultMetadata
  595. next *nextIter
  596. }
  597. // Columns returns the name and type of the selected columns.
  598. func (iter *Iter) Columns() []ColumnInfo {
  599. return iter.meta.columns
  600. }
  601. // Scan consumes the next row of the iterator and copies the columns of the
  602. // current row into the values pointed at by dest. Use nil as a dest value
  603. // to skip the corresponding column. Scan might send additional queries
  604. // to the database to retrieve the next set of rows if paging was enabled.
  605. //
  606. // Scan returns true if the row was successfully unmarshaled or false if the
  607. // end of the result set was reached or if an error occurred. Close should
  608. // be called afterwards to retrieve any potential errors.
  609. func (iter *Iter) Scan(dest ...interface{}) bool {
  610. if iter.err != nil {
  611. return false
  612. }
  613. if iter.pos >= len(iter.rows) {
  614. if iter.next != nil {
  615. *iter = *iter.next.fetch()
  616. return iter.Scan(dest...)
  617. }
  618. return false
  619. }
  620. if iter.next != nil && iter.pos == iter.next.pos {
  621. go iter.next.fetch()
  622. }
  623. // currently only support scanning into an expand tuple, such that its the same
  624. // as scanning in more values from a single column
  625. if len(dest) != iter.meta.actualColCount {
  626. iter.err = errors.New("count mismatch")
  627. return false
  628. }
  629. // i is the current position in dest, could posible replace it and just use
  630. // slices of dest
  631. i := 0
  632. for c, col := range iter.meta.columns {
  633. if dest[i] == nil {
  634. i++
  635. continue
  636. }
  637. switch col.TypeInfo.Type() {
  638. case TypeTuple:
  639. // this will panic, actually a bug, please report
  640. tuple := col.TypeInfo.(TupleTypeInfo)
  641. count := len(tuple.Elems)
  642. // here we pass in a slice of the struct which has the number number of
  643. // values as elements in the tuple
  644. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
  645. i += count
  646. default:
  647. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
  648. i++
  649. }
  650. if iter.err != nil {
  651. return false
  652. }
  653. }
  654. iter.pos++
  655. return true
  656. }
  657. // Close closes the iterator and returns any errors that happened during
  658. // the query or the iteration.
  659. func (iter *Iter) Close() error {
  660. return iter.err
  661. }
  662. // checkErrAndNotFound handle error and NotFound in one method.
  663. func (iter *Iter) checkErrAndNotFound() error {
  664. if iter.err != nil {
  665. return iter.err
  666. } else if len(iter.rows) == 0 {
  667. return ErrNotFound
  668. }
  669. return nil
  670. }
  671. type nextIter struct {
  672. qry Query
  673. pos int
  674. once sync.Once
  675. next *Iter
  676. }
  677. func (n *nextIter) fetch() *Iter {
  678. n.once.Do(func() {
  679. n.next = n.qry.session.executeQuery(&n.qry)
  680. })
  681. return n.next
  682. }
  683. type Batch struct {
  684. Type BatchType
  685. Entries []BatchEntry
  686. Cons Consistency
  687. rt RetryPolicy
  688. attempts int
  689. totalLatency int64
  690. serialCons SerialConsistency
  691. defaultTimestamp bool
  692. }
  693. // NewBatch creates a new batch operation without defaults from the cluster
  694. func NewBatch(typ BatchType) *Batch {
  695. return &Batch{Type: typ}
  696. }
  697. // NewBatch creates a new batch operation using defaults defined in the cluster
  698. func (s *Session) NewBatch(typ BatchType) *Batch {
  699. s.mu.RLock()
  700. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  701. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  702. s.mu.RUnlock()
  703. return batch
  704. }
  705. // Attempts returns the number of attempts made to execute the batch.
  706. func (b *Batch) Attempts() int {
  707. return b.attempts
  708. }
  709. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  710. func (b *Batch) Latency() int64 {
  711. if b.attempts > 0 {
  712. return b.totalLatency / int64(b.attempts)
  713. }
  714. return 0
  715. }
  716. // GetConsistency returns the currently configured consistency level for the batch
  717. // operation.
  718. func (b *Batch) GetConsistency() Consistency {
  719. return b.Cons
  720. }
  721. // Query adds the query to the batch operation
  722. func (b *Batch) Query(stmt string, args ...interface{}) {
  723. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  724. }
  725. // Bind adds the query to the batch operation and correlates it with a binding callback
  726. // that will be invoked when the batch is executed. The binding callback allows the application
  727. // to define which query argument values will be marshalled as part of the batch execution.
  728. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  729. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  730. }
  731. // RetryPolicy sets the retry policy to use when executing the batch operation
  732. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  733. b.rt = r
  734. return b
  735. }
  736. // Size returns the number of batch statements to be executed by the batch operation.
  737. func (b *Batch) Size() int {
  738. return len(b.Entries)
  739. }
  740. // SerialConsistency sets the consistencyc level for the
  741. // serial phase of conditional updates. That consitency can only be
  742. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  743. // SERIAL. This option will be ignored for anything else that a
  744. // conditional update/insert.
  745. //
  746. // Only available for protocol 3 and above
  747. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  748. b.serialCons = cons
  749. return b
  750. }
  751. // DefaultTimestamp will enable the with default timestamp flag on the query.
  752. // If enable, this will replace the server side assigned
  753. // timestamp as default timestamp. Note that a timestamp in the query itself
  754. // will still override this timestamp. This is entirely optional.
  755. //
  756. // Only available on protocol >= 3
  757. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  758. b.defaultTimestamp = enable
  759. return b
  760. }
  761. type BatchType byte
  762. const (
  763. LoggedBatch BatchType = 0
  764. UnloggedBatch = 1
  765. CounterBatch = 2
  766. )
  767. type BatchEntry struct {
  768. Stmt string
  769. Args []interface{}
  770. binding func(q *QueryInfo) ([]interface{}, error)
  771. }
  772. type ColumnInfo struct {
  773. Keyspace string
  774. Table string
  775. Name string
  776. TypeInfo TypeInfo
  777. }
  778. func (c ColumnInfo) String() string {
  779. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  780. }
  781. // routing key indexes LRU cache
  782. type routingKeyInfoLRU struct {
  783. lru *lru.Cache
  784. mu sync.Mutex
  785. }
  786. type routingKeyInfo struct {
  787. indexes []int
  788. types []TypeInfo
  789. }
  790. func (r *routingKeyInfoLRU) Remove(key string) {
  791. r.mu.Lock()
  792. r.lru.Remove(key)
  793. r.mu.Unlock()
  794. }
  795. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  796. //the new max is lower than the previous value. Not concurrency safe.
  797. func (r *routingKeyInfoLRU) Max(max int) {
  798. r.mu.Lock()
  799. for r.lru.Len() > max {
  800. r.lru.RemoveOldest()
  801. }
  802. r.lru.MaxEntries = max
  803. r.mu.Unlock()
  804. }
  805. type inflightCachedEntry struct {
  806. wg sync.WaitGroup
  807. err error
  808. value interface{}
  809. }
  810. // Tracer is the interface implemented by query tracers. Tracers have the
  811. // ability to obtain a detailed event log of all events that happened during
  812. // the execution of a query from Cassandra. Gathering this information might
  813. // be essential for debugging and optimizing queries, but this feature should
  814. // not be used on production systems with very high load.
  815. type Tracer interface {
  816. Trace(traceId []byte)
  817. }
  818. type traceWriter struct {
  819. session *Session
  820. w io.Writer
  821. mu sync.Mutex
  822. }
  823. // NewTraceWriter returns a simple Tracer implementation that outputs
  824. // the event log in a textual format.
  825. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  826. return &traceWriter{session: session, w: w}
  827. }
  828. func (t *traceWriter) Trace(traceId []byte) {
  829. var (
  830. coordinator string
  831. duration int
  832. )
  833. t.session.Query(`SELECT coordinator, duration
  834. FROM system_traces.sessions
  835. WHERE session_id = ?`, traceId).
  836. Consistency(One).Scan(&coordinator, &duration)
  837. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  838. FROM system_traces.events
  839. WHERE session_id = ?`, traceId).
  840. Consistency(One).Iter()
  841. var (
  842. timestamp time.Time
  843. activity string
  844. source string
  845. elapsed int
  846. )
  847. t.mu.Lock()
  848. defer t.mu.Unlock()
  849. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  850. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  851. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  852. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  853. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  854. }
  855. if err := iter.Close(); err != nil {
  856. fmt.Fprintln(t.w, "Error:", err)
  857. }
  858. }
  859. type Error struct {
  860. Code int
  861. Message string
  862. }
  863. func (e Error) Error() string {
  864. return e.Message
  865. }
  866. var (
  867. ErrNotFound = errors.New("not found")
  868. ErrUnavailable = errors.New("unavailable")
  869. ErrUnsupported = errors.New("feature not supported")
  870. ErrTooManyStmts = errors.New("too many statements")
  871. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  872. ErrSessionClosed = errors.New("session has been closed")
  873. ErrNoConnections = errors.New("no connections available")
  874. ErrNoKeyspace = errors.New("no keyspace provided")
  875. ErrNoMetadata = errors.New("no metadata available")
  876. )
  877. type ErrProtocol struct{ error }
  878. func NewErrProtocol(format string, args ...interface{}) error {
  879. return ErrProtocol{fmt.Errorf(format, args...)}
  880. }
  881. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  882. // This limit is set by cassandra and could change in the future.
  883. const BatchSizeMaximum = 65535