session.go 24 KB

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