session.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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. 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. //Attempts returns the number of times the query was executed.
  367. func (q *Query) Attempts() int {
  368. return q.attempts
  369. }
  370. //Latency returns the average amount of nanoseconds per attempt of the query.
  371. func (q *Query) Latency() int64 {
  372. if q.attempts > 0 {
  373. return q.totalLatency / int64(q.attempts)
  374. }
  375. return 0
  376. }
  377. // Consistency sets the consistency level for this query. If no consistency
  378. // level have been set, the default consistency level of the cluster
  379. // is used.
  380. func (q *Query) Consistency(c Consistency) *Query {
  381. q.cons = c
  382. return q
  383. }
  384. // GetConsistency returns the currently configured consistency level for
  385. // the query.
  386. func (q *Query) GetConsistency() Consistency {
  387. return q.cons
  388. }
  389. // Trace enables tracing of this query. Look at the documentation of the
  390. // Tracer interface to learn more about tracing.
  391. func (q *Query) Trace(trace Tracer) *Query {
  392. q.trace = trace
  393. return q
  394. }
  395. // PageSize will tell the iterator to fetch the result in pages of size n.
  396. // This is useful for iterating over large result sets, but setting the
  397. // page size to low might decrease the performance. This feature is only
  398. // available in Cassandra 2 and onwards.
  399. func (q *Query) PageSize(n int) *Query {
  400. q.pageSize = n
  401. return q
  402. }
  403. // DefaultTimestamp will enable the with default timestamp flag on the query.
  404. // If enable, this will replace the server side assigned
  405. // timestamp as default timestamp. Note that a timestamp in the query itself
  406. // will still override this timestamp. This is entirely optional.
  407. //
  408. // Only available on protocol >= 3
  409. func (q *Query) DefaultTimestamp(enable bool) *Query {
  410. q.defaultTimestamp = enable
  411. return q
  412. }
  413. // RoutingKey sets the routing key to use when a token aware connection
  414. // pool is used to optimize the routing of this query.
  415. func (q *Query) RoutingKey(routingKey []byte) *Query {
  416. q.routingKey = routingKey
  417. return q
  418. }
  419. // GetRoutingKey gets the routing key to use for routing this query. If
  420. // a routing key has not been explicitly set, then the routing key will
  421. // be constructed if possible using the keyspace's schema and the query
  422. // info for this query statement. If the routing key cannot be determined
  423. // then nil will be returned with no error. On any error condition,
  424. // an error description will be returned.
  425. func (q *Query) GetRoutingKey() ([]byte, error) {
  426. if q.routingKey != nil {
  427. return q.routingKey, nil
  428. }
  429. // try to determine the routing key
  430. routingKeyInfo, err := q.session.routingKeyInfo(q.stmt)
  431. if err != nil {
  432. return nil, err
  433. }
  434. if routingKeyInfo == nil {
  435. return nil, nil
  436. }
  437. if len(routingKeyInfo.indexes) == 1 {
  438. // single column routing key
  439. routingKey, err := Marshal(
  440. routingKeyInfo.types[0],
  441. q.values[routingKeyInfo.indexes[0]],
  442. )
  443. if err != nil {
  444. return nil, err
  445. }
  446. return routingKey, nil
  447. }
  448. // composite routing key
  449. buf := &bytes.Buffer{}
  450. for i := range routingKeyInfo.indexes {
  451. encoded, err := Marshal(
  452. routingKeyInfo.types[i],
  453. q.values[routingKeyInfo.indexes[i]],
  454. )
  455. if err != nil {
  456. return nil, err
  457. }
  458. binary.Write(buf, binary.BigEndian, int16(len(encoded)))
  459. buf.Write(encoded)
  460. buf.WriteByte(0x00)
  461. }
  462. routingKey := buf.Bytes()
  463. return routingKey, nil
  464. }
  465. func (q *Query) shouldPrepare() bool {
  466. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  467. return unicode.IsSpace(r) || r == ';'
  468. }), unicode.IsSpace)
  469. var stmtType string
  470. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  471. stmtType = strings.ToLower(stmt[:n])
  472. }
  473. if stmtType == "begin" {
  474. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  475. stmtType = strings.ToLower(stmt[n+1:])
  476. }
  477. }
  478. switch stmtType {
  479. case "select", "insert", "update", "delete", "batch":
  480. return true
  481. }
  482. return false
  483. }
  484. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  485. // there are only p*pageSize rows remaining, the next page will be requested
  486. // automatically.
  487. func (q *Query) Prefetch(p float64) *Query {
  488. q.prefetch = p
  489. return q
  490. }
  491. // RetryPolicy sets the policy to use when retrying the query.
  492. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  493. q.rt = r
  494. return q
  495. }
  496. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  497. // to an existing query instance.
  498. func (q *Query) Bind(v ...interface{}) *Query {
  499. q.values = v
  500. return q
  501. }
  502. // SerialConsistency sets the consistencyc level for the
  503. // serial phase of conditional updates. That consitency can only be
  504. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  505. // SERIAL. This option will be ignored for anything else that a
  506. // conditional update/insert.
  507. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  508. q.serialCons = cons
  509. return q
  510. }
  511. // Exec executes the query without returning any rows.
  512. func (q *Query) Exec() error {
  513. iter := q.Iter()
  514. return iter.err
  515. }
  516. // Iter executes the query and returns an iterator capable of iterating
  517. // over all results.
  518. func (q *Query) Iter() *Iter {
  519. if strings.Index(strings.ToLower(q.stmt), "use") == 0 {
  520. return &Iter{err: ErrUseStmt}
  521. }
  522. return q.session.executeQuery(q)
  523. }
  524. // MapScan executes the query, copies the columns of the first selected
  525. // row into the map pointed at by m and discards the rest. If no rows
  526. // were selected, ErrNotFound is returned.
  527. func (q *Query) MapScan(m map[string]interface{}) error {
  528. iter := q.Iter()
  529. if err := iter.checkErrAndNotFound(); err != nil {
  530. return err
  531. }
  532. iter.MapScan(m)
  533. return iter.Close()
  534. }
  535. // Scan executes the query, copies the columns of the first selected
  536. // row into the values pointed at by dest and discards the rest. If no rows
  537. // were selected, ErrNotFound is returned.
  538. func (q *Query) Scan(dest ...interface{}) error {
  539. iter := q.Iter()
  540. if err := iter.checkErrAndNotFound(); err != nil {
  541. return err
  542. }
  543. iter.Scan(dest...)
  544. return iter.Close()
  545. }
  546. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  547. // statement containing an IF clause). If the transaction fails because
  548. // the existing values did not match, the previous values will be stored
  549. // in dest.
  550. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  551. iter := q.Iter()
  552. if err := iter.checkErrAndNotFound(); err != nil {
  553. return false, err
  554. }
  555. if len(iter.Columns()) > 1 {
  556. dest = append([]interface{}{&applied}, dest...)
  557. iter.Scan(dest...)
  558. } else {
  559. iter.Scan(&applied)
  560. }
  561. return applied, iter.Close()
  562. }
  563. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  564. // statement containing an IF clause). If the transaction fails because
  565. // the existing values did not match, the previous values will be stored
  566. // in dest map.
  567. //
  568. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  569. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  570. // column mismatching. MapScanCAS is added to capture them safely.
  571. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  572. iter := q.Iter()
  573. if err := iter.checkErrAndNotFound(); err != nil {
  574. return false, err
  575. }
  576. iter.MapScan(dest)
  577. applied = dest["[applied]"].(bool)
  578. delete(dest, "[applied]")
  579. return applied, iter.Close()
  580. }
  581. // Iter represents an iterator that can be used to iterate over all rows that
  582. // were returned by a query. The iterator might send additional queries to the
  583. // database during the iteration if paging was enabled.
  584. type Iter struct {
  585. err error
  586. pos int
  587. rows [][][]byte
  588. meta resultMetadata
  589. next *nextIter
  590. }
  591. // Columns returns the name and type of the selected columns.
  592. func (iter *Iter) Columns() []ColumnInfo {
  593. return iter.meta.columns
  594. }
  595. // Scan consumes the next row of the iterator and copies the columns of the
  596. // current row into the values pointed at by dest. Use nil as a dest value
  597. // to skip the corresponding column. Scan might send additional queries
  598. // to the database to retrieve the next set of rows if paging was enabled.
  599. //
  600. // Scan returns true if the row was successfully unmarshaled or false if the
  601. // end of the result set was reached or if an error occurred. Close should
  602. // be called afterwards to retrieve any potential errors.
  603. func (iter *Iter) Scan(dest ...interface{}) bool {
  604. if iter.err != nil {
  605. return false
  606. }
  607. if iter.pos >= len(iter.rows) {
  608. if iter.next != nil {
  609. *iter = *iter.next.fetch()
  610. return iter.Scan(dest...)
  611. }
  612. return false
  613. }
  614. if iter.next != nil && iter.pos == iter.next.pos {
  615. go iter.next.fetch()
  616. }
  617. // currently only support scanning into an expand tuple, such that its the same
  618. // as scanning in more values from a single column
  619. if len(dest) != iter.meta.actualColCount {
  620. iter.err = errors.New("count mismatch")
  621. return false
  622. }
  623. // i is the current position in dest, could posible replace it and just use
  624. // slices of dest
  625. i := 0
  626. for c, col := range iter.meta.columns {
  627. if dest[i] == nil {
  628. i++
  629. continue
  630. }
  631. switch col.TypeInfo.Type() {
  632. case TypeTuple:
  633. // this will panic, actually a bug, please report
  634. tuple := col.TypeInfo.(TupleTypeInfo)
  635. count := len(tuple.Elems)
  636. // here we pass in a slice of the struct which has the number number of
  637. // values as elements in the tuple
  638. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
  639. i += count
  640. default:
  641. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
  642. i++
  643. }
  644. if iter.err != nil {
  645. return false
  646. }
  647. }
  648. iter.pos++
  649. return true
  650. }
  651. // Close closes the iterator and returns any errors that happened during
  652. // the query or the iteration.
  653. func (iter *Iter) Close() error {
  654. return iter.err
  655. }
  656. // checkErrAndNotFound handle error and NotFound in one method.
  657. func (iter *Iter) checkErrAndNotFound() error {
  658. if iter.err != nil {
  659. return iter.err
  660. } else if len(iter.rows) == 0 {
  661. return ErrNotFound
  662. }
  663. return nil
  664. }
  665. type nextIter struct {
  666. qry Query
  667. pos int
  668. once sync.Once
  669. next *Iter
  670. }
  671. func (n *nextIter) fetch() *Iter {
  672. n.once.Do(func() {
  673. n.next = n.qry.session.executeQuery(&n.qry)
  674. })
  675. return n.next
  676. }
  677. type Batch struct {
  678. Type BatchType
  679. Entries []BatchEntry
  680. Cons Consistency
  681. rt RetryPolicy
  682. attempts int
  683. totalLatency int64
  684. serialCons SerialConsistency
  685. defaultTimestamp bool
  686. }
  687. // NewBatch creates a new batch operation without defaults from the cluster
  688. func NewBatch(typ BatchType) *Batch {
  689. return &Batch{Type: typ}
  690. }
  691. // NewBatch creates a new batch operation using defaults defined in the cluster
  692. func (s *Session) NewBatch(typ BatchType) *Batch {
  693. s.mu.RLock()
  694. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  695. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  696. s.mu.RUnlock()
  697. return batch
  698. }
  699. // Attempts returns the number of attempts made to execute the batch.
  700. func (b *Batch) Attempts() int {
  701. return b.attempts
  702. }
  703. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  704. func (b *Batch) Latency() int64 {
  705. if b.attempts > 0 {
  706. return b.totalLatency / int64(b.attempts)
  707. }
  708. return 0
  709. }
  710. // GetConsistency returns the currently configured consistency level for the batch
  711. // operation.
  712. func (b *Batch) GetConsistency() Consistency {
  713. return b.Cons
  714. }
  715. // Query adds the query to the batch operation
  716. func (b *Batch) Query(stmt string, args ...interface{}) {
  717. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  718. }
  719. // Bind adds the query to the batch operation and correlates it with a binding callback
  720. // that will be invoked when the batch is executed. The binding callback allows the application
  721. // to define which query argument values will be marshalled as part of the batch execution.
  722. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  723. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  724. }
  725. // RetryPolicy sets the retry policy to use when executing the batch operation
  726. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  727. b.rt = r
  728. return b
  729. }
  730. // Size returns the number of batch statements to be executed by the batch operation.
  731. func (b *Batch) Size() int {
  732. return len(b.Entries)
  733. }
  734. // SerialConsistency sets the consistencyc level for the
  735. // serial phase of conditional updates. That consitency can only be
  736. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  737. // SERIAL. This option will be ignored for anything else that a
  738. // conditional update/insert.
  739. //
  740. // Only available for protocol 3 and above
  741. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  742. b.serialCons = cons
  743. return b
  744. }
  745. // DefaultTimestamp will enable the with default timestamp flag on the query.
  746. // If enable, this will replace the server side assigned
  747. // timestamp as default timestamp. Note that a timestamp in the query itself
  748. // will still override this timestamp. This is entirely optional.
  749. //
  750. // Only available on protocol >= 3
  751. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  752. b.defaultTimestamp = enable
  753. return b
  754. }
  755. type BatchType byte
  756. const (
  757. LoggedBatch BatchType = 0
  758. UnloggedBatch = 1
  759. CounterBatch = 2
  760. )
  761. type BatchEntry struct {
  762. Stmt string
  763. Args []interface{}
  764. binding func(q *QueryInfo) ([]interface{}, error)
  765. }
  766. type ColumnInfo struct {
  767. Keyspace string
  768. Table string
  769. Name string
  770. TypeInfo TypeInfo
  771. }
  772. func (c ColumnInfo) String() string {
  773. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  774. }
  775. // routing key indexes LRU cache
  776. type routingKeyInfoLRU struct {
  777. lru *lru.Cache
  778. mu sync.Mutex
  779. }
  780. type routingKeyInfo struct {
  781. indexes []int
  782. types []TypeInfo
  783. }
  784. func (r *routingKeyInfoLRU) Remove(key string) {
  785. r.mu.Lock()
  786. r.lru.Remove(key)
  787. r.mu.Unlock()
  788. }
  789. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  790. //the new max is lower than the previous value. Not concurrency safe.
  791. func (r *routingKeyInfoLRU) Max(max int) {
  792. r.mu.Lock()
  793. for r.lru.Len() > max {
  794. r.lru.RemoveOldest()
  795. }
  796. r.lru.MaxEntries = max
  797. r.mu.Unlock()
  798. }
  799. type inflightCachedEntry struct {
  800. wg sync.WaitGroup
  801. err error
  802. value interface{}
  803. }
  804. // Tracer is the interface implemented by query tracers. Tracers have the
  805. // ability to obtain a detailed event log of all events that happened during
  806. // the execution of a query from Cassandra. Gathering this information might
  807. // be essential for debugging and optimizing queries, but this feature should
  808. // not be used on production systems with very high load.
  809. type Tracer interface {
  810. Trace(traceId []byte)
  811. }
  812. type traceWriter struct {
  813. session *Session
  814. w io.Writer
  815. mu sync.Mutex
  816. }
  817. // NewTraceWriter returns a simple Tracer implementation that outputs
  818. // the event log in a textual format.
  819. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  820. return &traceWriter{session: session, w: w}
  821. }
  822. func (t *traceWriter) Trace(traceId []byte) {
  823. var (
  824. coordinator string
  825. duration int
  826. )
  827. t.session.Query(`SELECT coordinator, duration
  828. FROM system_traces.sessions
  829. WHERE session_id = ?`, traceId).
  830. Consistency(One).Scan(&coordinator, &duration)
  831. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  832. FROM system_traces.events
  833. WHERE session_id = ?`, traceId).
  834. Consistency(One).Iter()
  835. var (
  836. timestamp time.Time
  837. activity string
  838. source string
  839. elapsed int
  840. )
  841. t.mu.Lock()
  842. defer t.mu.Unlock()
  843. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  844. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  845. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  846. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  847. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  848. }
  849. if err := iter.Close(); err != nil {
  850. fmt.Fprintln(t.w, "Error:", err)
  851. }
  852. }
  853. type Error struct {
  854. Code int
  855. Message string
  856. }
  857. func (e Error) Error() string {
  858. return e.Message
  859. }
  860. var (
  861. ErrNotFound = errors.New("not found")
  862. ErrUnavailable = errors.New("unavailable")
  863. ErrUnsupported = errors.New("feature not supported")
  864. ErrTooManyStmts = errors.New("too many statements")
  865. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  866. ErrSessionClosed = errors.New("session has been closed")
  867. ErrNoConnections = errors.New("no connections available")
  868. ErrNoKeyspace = errors.New("no keyspace provided")
  869. ErrNoMetadata = errors.New("no metadata available")
  870. )
  871. type ErrProtocol struct{ error }
  872. func NewErrProtocol(format string, args ...interface{}) error {
  873. return ErrProtocol{fmt.Errorf(format, args...)}
  874. }
  875. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  876. // This limit is set by cassandra and could change in the future.
  877. const BatchSizeMaximum = 65535