session.go 27 KB

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