session.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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.Buffer{}
  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. binary.Write(buf, binary.BigEndian, int16(len(encoded)))
  463. buf.Write(encoded)
  464. buf.WriteByte(0x00)
  465. }
  466. routingKey := buf.Bytes()
  467. return routingKey, nil
  468. }
  469. func (q *Query) shouldPrepare() bool {
  470. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  471. return unicode.IsSpace(r) || r == ';'
  472. }), unicode.IsSpace)
  473. var stmtType string
  474. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  475. stmtType = strings.ToLower(stmt[:n])
  476. }
  477. if stmtType == "begin" {
  478. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  479. stmtType = strings.ToLower(stmt[n+1:])
  480. }
  481. }
  482. switch stmtType {
  483. case "select", "insert", "update", "delete", "batch":
  484. return true
  485. }
  486. return false
  487. }
  488. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  489. // there are only p*pageSize rows remaining, the next page will be requested
  490. // automatically.
  491. func (q *Query) Prefetch(p float64) *Query {
  492. q.prefetch = p
  493. return q
  494. }
  495. // RetryPolicy sets the policy to use when retrying the query.
  496. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  497. q.rt = r
  498. return q
  499. }
  500. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  501. // to an existing query instance.
  502. func (q *Query) Bind(v ...interface{}) *Query {
  503. q.values = v
  504. return q
  505. }
  506. // SerialConsistency sets the consistencyc level for the
  507. // serial phase of conditional updates. That consitency can only be
  508. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  509. // SERIAL. This option will be ignored for anything else that a
  510. // conditional update/insert.
  511. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  512. q.serialCons = cons
  513. return q
  514. }
  515. // Exec executes the query without returning any rows.
  516. func (q *Query) Exec() error {
  517. iter := q.Iter()
  518. return iter.err
  519. }
  520. func isUseStatement(stmt string) bool {
  521. if len(stmt) < 3 {
  522. return false
  523. }
  524. return strings.ToLower(stmt[0:3]) == "use"
  525. }
  526. // Iter executes the query and returns an iterator capable of iterating
  527. // over all results.
  528. func (q *Query) Iter() *Iter {
  529. if isUseStatement(q.stmt) {
  530. return &Iter{err: ErrUseStmt}
  531. }
  532. return q.session.executeQuery(q)
  533. }
  534. // MapScan executes the query, copies the columns of the first selected
  535. // row into the map pointed at by m and discards the rest. If no rows
  536. // were selected, ErrNotFound is returned.
  537. func (q *Query) MapScan(m map[string]interface{}) error {
  538. iter := q.Iter()
  539. if err := iter.checkErrAndNotFound(); err != nil {
  540. return err
  541. }
  542. iter.MapScan(m)
  543. return iter.Close()
  544. }
  545. // Scan executes the query, copies the columns of the first selected
  546. // row into the values pointed at by dest and discards the rest. If no rows
  547. // were selected, ErrNotFound is returned.
  548. func (q *Query) Scan(dest ...interface{}) error {
  549. iter := q.Iter()
  550. if err := iter.checkErrAndNotFound(); err != nil {
  551. return err
  552. }
  553. iter.Scan(dest...)
  554. return iter.Close()
  555. }
  556. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  557. // statement containing an IF clause). If the transaction fails because
  558. // the existing values did not match, the previous values will be stored
  559. // in dest.
  560. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  561. iter := q.Iter()
  562. if err := iter.checkErrAndNotFound(); err != nil {
  563. return false, err
  564. }
  565. if len(iter.Columns()) > 1 {
  566. dest = append([]interface{}{&applied}, dest...)
  567. iter.Scan(dest...)
  568. } else {
  569. iter.Scan(&applied)
  570. }
  571. return applied, iter.Close()
  572. }
  573. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  574. // statement containing an IF clause). If the transaction fails because
  575. // the existing values did not match, the previous values will be stored
  576. // in dest map.
  577. //
  578. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  579. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  580. // column mismatching. MapScanCAS is added to capture them safely.
  581. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  582. iter := q.Iter()
  583. if err := iter.checkErrAndNotFound(); err != nil {
  584. return false, err
  585. }
  586. iter.MapScan(dest)
  587. applied = dest["[applied]"].(bool)
  588. delete(dest, "[applied]")
  589. return applied, iter.Close()
  590. }
  591. // Iter represents an iterator that can be used to iterate over all rows that
  592. // were returned by a query. The iterator might send additional queries to the
  593. // database during the iteration if paging was enabled.
  594. type Iter struct {
  595. err error
  596. pos int
  597. rows [][][]byte
  598. meta resultMetadata
  599. next *nextIter
  600. }
  601. // Columns returns the name and type of the selected columns.
  602. func (iter *Iter) Columns() []ColumnInfo {
  603. return iter.meta.columns
  604. }
  605. // Scan consumes the next row of the iterator and copies the columns of the
  606. // current row into the values pointed at by dest. Use nil as a dest value
  607. // to skip the corresponding column. Scan might send additional queries
  608. // to the database to retrieve the next set of rows if paging was enabled.
  609. //
  610. // Scan returns true if the row was successfully unmarshaled or false if the
  611. // end of the result set was reached or if an error occurred. Close should
  612. // be called afterwards to retrieve any potential errors.
  613. func (iter *Iter) Scan(dest ...interface{}) bool {
  614. if iter.err != nil {
  615. return false
  616. }
  617. if iter.pos >= len(iter.rows) {
  618. if iter.next != nil {
  619. *iter = *iter.next.fetch()
  620. return iter.Scan(dest...)
  621. }
  622. return false
  623. }
  624. if iter.next != nil && iter.pos == iter.next.pos {
  625. go iter.next.fetch()
  626. }
  627. // currently only support scanning into an expand tuple, such that its the same
  628. // as scanning in more values from a single column
  629. if len(dest) != iter.meta.actualColCount {
  630. iter.err = errors.New("count mismatch")
  631. return false
  632. }
  633. // i is the current position in dest, could posible replace it and just use
  634. // slices of dest
  635. i := 0
  636. for c, col := range iter.meta.columns {
  637. if dest[i] == nil {
  638. i++
  639. continue
  640. }
  641. switch col.TypeInfo.Type() {
  642. case TypeTuple:
  643. // this will panic, actually a bug, please report
  644. tuple := col.TypeInfo.(TupleTypeInfo)
  645. count := len(tuple.Elems)
  646. // here we pass in a slice of the struct which has the number number of
  647. // values as elements in the tuple
  648. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
  649. i += count
  650. default:
  651. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
  652. i++
  653. }
  654. if iter.err != nil {
  655. return false
  656. }
  657. }
  658. iter.pos++
  659. return true
  660. }
  661. // Close closes the iterator and returns any errors that happened during
  662. // the query or the iteration.
  663. func (iter *Iter) Close() error {
  664. return iter.err
  665. }
  666. // checkErrAndNotFound handle error and NotFound in one method.
  667. func (iter *Iter) checkErrAndNotFound() error {
  668. if iter.err != nil {
  669. return iter.err
  670. } else if len(iter.rows) == 0 {
  671. return ErrNotFound
  672. }
  673. return nil
  674. }
  675. type nextIter struct {
  676. qry Query
  677. pos int
  678. once sync.Once
  679. next *Iter
  680. }
  681. func (n *nextIter) fetch() *Iter {
  682. n.once.Do(func() {
  683. n.next = n.qry.session.executeQuery(&n.qry)
  684. })
  685. return n.next
  686. }
  687. type Batch struct {
  688. Type BatchType
  689. Entries []BatchEntry
  690. Cons Consistency
  691. rt RetryPolicy
  692. attempts int
  693. totalLatency int64
  694. serialCons SerialConsistency
  695. defaultTimestamp bool
  696. }
  697. // NewBatch creates a new batch operation without defaults from the cluster
  698. func NewBatch(typ BatchType) *Batch {
  699. return &Batch{Type: typ}
  700. }
  701. // NewBatch creates a new batch operation using defaults defined in the cluster
  702. func (s *Session) NewBatch(typ BatchType) *Batch {
  703. s.mu.RLock()
  704. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  705. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  706. s.mu.RUnlock()
  707. return batch
  708. }
  709. // Attempts returns the number of attempts made to execute the batch.
  710. func (b *Batch) Attempts() int {
  711. return b.attempts
  712. }
  713. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  714. func (b *Batch) Latency() int64 {
  715. if b.attempts > 0 {
  716. return b.totalLatency / int64(b.attempts)
  717. }
  718. return 0
  719. }
  720. // GetConsistency returns the currently configured consistency level for the batch
  721. // operation.
  722. func (b *Batch) GetConsistency() Consistency {
  723. return b.Cons
  724. }
  725. // Query adds the query to the batch operation
  726. func (b *Batch) Query(stmt string, args ...interface{}) {
  727. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  728. }
  729. // Bind adds the query to the batch operation and correlates it with a binding callback
  730. // that will be invoked when the batch is executed. The binding callback allows the application
  731. // to define which query argument values will be marshalled as part of the batch execution.
  732. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  733. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  734. }
  735. // RetryPolicy sets the retry policy to use when executing the batch operation
  736. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  737. b.rt = r
  738. return b
  739. }
  740. // Size returns the number of batch statements to be executed by the batch operation.
  741. func (b *Batch) Size() int {
  742. return len(b.Entries)
  743. }
  744. // SerialConsistency sets the consistencyc level for the
  745. // serial phase of conditional updates. That consitency can only be
  746. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  747. // SERIAL. This option will be ignored for anything else that a
  748. // conditional update/insert.
  749. //
  750. // Only available for protocol 3 and above
  751. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  752. b.serialCons = cons
  753. return b
  754. }
  755. // DefaultTimestamp will enable the with default timestamp flag on the query.
  756. // If enable, this will replace the server side assigned
  757. // timestamp as default timestamp. Note that a timestamp in the query itself
  758. // will still override this timestamp. This is entirely optional.
  759. //
  760. // Only available on protocol >= 3
  761. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  762. b.defaultTimestamp = enable
  763. return b
  764. }
  765. type BatchType byte
  766. const (
  767. LoggedBatch BatchType = 0
  768. UnloggedBatch = 1
  769. CounterBatch = 2
  770. )
  771. type BatchEntry struct {
  772. Stmt string
  773. Args []interface{}
  774. binding func(q *QueryInfo) ([]interface{}, error)
  775. }
  776. type ColumnInfo struct {
  777. Keyspace string
  778. Table string
  779. Name string
  780. TypeInfo TypeInfo
  781. }
  782. func (c ColumnInfo) String() string {
  783. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  784. }
  785. // routing key indexes LRU cache
  786. type routingKeyInfoLRU struct {
  787. lru *lru.Cache
  788. mu sync.Mutex
  789. }
  790. type routingKeyInfo struct {
  791. indexes []int
  792. types []TypeInfo
  793. }
  794. func (r *routingKeyInfoLRU) Remove(key string) {
  795. r.mu.Lock()
  796. r.lru.Remove(key)
  797. r.mu.Unlock()
  798. }
  799. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  800. //the new max is lower than the previous value. Not concurrency safe.
  801. func (r *routingKeyInfoLRU) Max(max int) {
  802. r.mu.Lock()
  803. for r.lru.Len() > max {
  804. r.lru.RemoveOldest()
  805. }
  806. r.lru.MaxEntries = max
  807. r.mu.Unlock()
  808. }
  809. type inflightCachedEntry struct {
  810. wg sync.WaitGroup
  811. err error
  812. value interface{}
  813. }
  814. // Tracer is the interface implemented by query tracers. Tracers have the
  815. // ability to obtain a detailed event log of all events that happened during
  816. // the execution of a query from Cassandra. Gathering this information might
  817. // be essential for debugging and optimizing queries, but this feature should
  818. // not be used on production systems with very high load.
  819. type Tracer interface {
  820. Trace(traceId []byte)
  821. }
  822. type traceWriter struct {
  823. session *Session
  824. w io.Writer
  825. mu sync.Mutex
  826. }
  827. // NewTraceWriter returns a simple Tracer implementation that outputs
  828. // the event log in a textual format.
  829. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  830. return &traceWriter{session: session, w: w}
  831. }
  832. func (t *traceWriter) Trace(traceId []byte) {
  833. var (
  834. coordinator string
  835. duration int
  836. )
  837. t.session.Query(`SELECT coordinator, duration
  838. FROM system_traces.sessions
  839. WHERE session_id = ?`, traceId).
  840. Consistency(One).Scan(&coordinator, &duration)
  841. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  842. FROM system_traces.events
  843. WHERE session_id = ?`, traceId).
  844. Consistency(One).Iter()
  845. var (
  846. timestamp time.Time
  847. activity string
  848. source string
  849. elapsed int
  850. )
  851. t.mu.Lock()
  852. defer t.mu.Unlock()
  853. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  854. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  855. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  856. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  857. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  858. }
  859. if err := iter.Close(); err != nil {
  860. fmt.Fprintln(t.w, "Error:", err)
  861. }
  862. }
  863. type Error struct {
  864. Code int
  865. Message string
  866. }
  867. func (e Error) Error() string {
  868. return e.Message
  869. }
  870. var (
  871. ErrNotFound = errors.New("not found")
  872. ErrUnavailable = errors.New("unavailable")
  873. ErrUnsupported = errors.New("feature not supported")
  874. ErrTooManyStmts = errors.New("too many statements")
  875. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  876. ErrSessionClosed = errors.New("session has been closed")
  877. ErrNoConnections = errors.New("no connections available")
  878. ErrNoKeyspace = errors.New("no keyspace provided")
  879. ErrNoMetadata = errors.New("no metadata available")
  880. )
  881. type ErrProtocol struct{ error }
  882. func NewErrProtocol(format string, args ...interface{}) error {
  883. return ErrProtocol{fmt.Errorf(format, args...)}
  884. }
  885. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  886. // This limit is set by cassandra and could change in the future.
  887. const BatchSizeMaximum = 65535