session.go 26 KB

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