session.go 27 KB

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