session.go 24 KB

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