session.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
  220. if cached {
  221. // done accessing the cache
  222. s.routingKeyInfoCache.mu.Unlock()
  223. // the entry is an inflight struct similiar to that used by
  224. // Conn to prepare statements
  225. inflight := entry.(*inflightCachedEntry)
  226. // wait for any inflight work
  227. inflight.wg.Wait()
  228. if inflight.err != nil {
  229. return nil, inflight.err
  230. }
  231. key, _ := inflight.value.(*routingKeyInfo)
  232. return key, nil
  233. }
  234. // create a new inflight entry while the data is created
  235. inflight := new(inflightCachedEntry)
  236. inflight.wg.Add(1)
  237. defer inflight.wg.Done()
  238. s.routingKeyInfoCache.lru.Add(stmt, inflight)
  239. s.routingKeyInfoCache.mu.Unlock()
  240. var (
  241. prepared *resultPreparedFrame
  242. partitionKey []*ColumnMetadata
  243. )
  244. // get the query info for the statement
  245. conn := s.Pool.Pick(nil)
  246. if conn == nil {
  247. // no connections
  248. inflight.err = ErrNoConnections
  249. // don't cache this error
  250. s.routingKeyInfoCache.Remove(stmt)
  251. return nil, inflight.err
  252. }
  253. prepared, inflight.err = conn.prepareStatement(stmt, nil)
  254. if inflight.err != nil {
  255. // don't cache this error
  256. s.routingKeyInfoCache.Remove(stmt)
  257. return nil, inflight.err
  258. }
  259. if len(prepared.reqMeta.columns) == 0 {
  260. // no arguments, no routing key, and no error
  261. return nil, nil
  262. }
  263. // get the table metadata
  264. table := prepared.reqMeta.columns[0].Table
  265. var keyspaceMetadata *KeyspaceMetadata
  266. keyspaceMetadata, inflight.err = s.KeyspaceMetadata(s.cfg.Keyspace)
  267. if inflight.err != nil {
  268. // don't cache this error
  269. s.routingKeyInfoCache.Remove(stmt)
  270. return nil, inflight.err
  271. }
  272. tableMetadata, found := keyspaceMetadata.Tables[table]
  273. if !found {
  274. // unlikely that the statement could be prepared and the metadata for
  275. // the table couldn't be found, but this may indicate either a bug
  276. // in the metadata code, or that the table was just dropped.
  277. inflight.err = ErrNoMetadata
  278. // don't cache this error
  279. s.routingKeyInfoCache.Remove(stmt)
  280. return nil, inflight.err
  281. }
  282. partitionKey = tableMetadata.PartitionKey
  283. size := len(partitionKey)
  284. routingKeyInfo := &routingKeyInfo{
  285. indexes: make([]int, size),
  286. types: make([]TypeInfo, size),
  287. }
  288. for keyIndex, keyColumn := range partitionKey {
  289. // set an indicator for checking if the mapping is missing
  290. routingKeyInfo.indexes[keyIndex] = -1
  291. // find the column in the query info
  292. for argIndex, boundColumn := range prepared.reqMeta.columns {
  293. if keyColumn.Name == boundColumn.Name {
  294. // there may be many such bound columns, pick the first
  295. routingKeyInfo.indexes[keyIndex] = argIndex
  296. routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
  297. break
  298. }
  299. }
  300. if routingKeyInfo.indexes[keyIndex] == -1 {
  301. // missing a routing key column mapping
  302. // no routing key, and no error
  303. return nil, nil
  304. }
  305. }
  306. // cache this result
  307. inflight.value = routingKeyInfo
  308. return routingKeyInfo, nil
  309. }
  310. // ExecuteBatch executes a batch operation and returns nil if successful
  311. // otherwise an error is returned describing the failure.
  312. func (s *Session) ExecuteBatch(batch *Batch) error {
  313. // fail fast
  314. if s.Closed() {
  315. return ErrSessionClosed
  316. }
  317. // Prevent the execution of the batch if greater than the limit
  318. // Currently batches have a limit of 65536 queries.
  319. // https://datastax-oss.atlassian.net/browse/JAVA-229
  320. if batch.Size() > BatchSizeMaximum {
  321. return ErrTooManyStmts
  322. }
  323. var err error
  324. batch.attempts = 0
  325. batch.totalLatency = 0
  326. for {
  327. conn := s.Pool.Pick(nil)
  328. //Assign the error unavailable and break loop
  329. if conn == nil {
  330. err = ErrNoConnections
  331. break
  332. }
  333. t := time.Now()
  334. err = conn.executeBatch(batch)
  335. batch.totalLatency += time.Now().Sub(t).Nanoseconds()
  336. batch.attempts++
  337. //Exit loop if operation executed correctly
  338. if err == nil {
  339. return nil
  340. }
  341. if batch.rt == nil || !batch.rt.Attempt(batch) {
  342. break
  343. }
  344. }
  345. return err
  346. }
  347. // Query represents a CQL statement that can be executed.
  348. type Query struct {
  349. stmt string
  350. values []interface{}
  351. cons Consistency
  352. pageSize int
  353. routingKey []byte
  354. routingKeyBuffer []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. // We allocate that buffer only once, so that further re-bind/exec of the
  453. // same query don't allocate more memory.
  454. if q.routingKeyBuffer == nil {
  455. q.routingKeyBuffer = make([]byte, 0, 256)
  456. }
  457. // composite routing key
  458. buf := bytes.NewBuffer(q.routingKeyBuffer)
  459. for i := range routingKeyInfo.indexes {
  460. encoded, err := Marshal(
  461. routingKeyInfo.types[i],
  462. q.values[routingKeyInfo.indexes[i]],
  463. )
  464. if err != nil {
  465. return nil, err
  466. }
  467. lenBuf := []byte{0x00, 0x00}
  468. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  469. buf.Write(lenBuf)
  470. buf.Write(encoded)
  471. buf.WriteByte(0x00)
  472. }
  473. routingKey := buf.Bytes()
  474. return routingKey, nil
  475. }
  476. func (q *Query) shouldPrepare() bool {
  477. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  478. return unicode.IsSpace(r) || r == ';'
  479. }), unicode.IsSpace)
  480. var stmtType string
  481. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  482. stmtType = strings.ToLower(stmt[:n])
  483. }
  484. if stmtType == "begin" {
  485. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  486. stmtType = strings.ToLower(stmt[n+1:])
  487. }
  488. }
  489. switch stmtType {
  490. case "select", "insert", "update", "delete", "batch":
  491. return true
  492. }
  493. return false
  494. }
  495. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  496. // there are only p*pageSize rows remaining, the next page will be requested
  497. // automatically.
  498. func (q *Query) Prefetch(p float64) *Query {
  499. q.prefetch = p
  500. return q
  501. }
  502. // RetryPolicy sets the policy to use when retrying the query.
  503. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  504. q.rt = r
  505. return q
  506. }
  507. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  508. // to an existing query instance.
  509. func (q *Query) Bind(v ...interface{}) *Query {
  510. q.values = v
  511. return q
  512. }
  513. // SerialConsistency sets the consistencyc level for the
  514. // serial phase of conditional updates. That consitency can only be
  515. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  516. // SERIAL. This option will be ignored for anything else that a
  517. // conditional update/insert.
  518. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  519. q.serialCons = cons
  520. return q
  521. }
  522. // Exec executes the query without returning any rows.
  523. func (q *Query) Exec() error {
  524. iter := q.Iter()
  525. return iter.err
  526. }
  527. func isUseStatement(stmt string) bool {
  528. if len(stmt) < 3 {
  529. return false
  530. }
  531. return strings.ToLower(stmt[0:3]) == "use"
  532. }
  533. // Iter executes the query and returns an iterator capable of iterating
  534. // over all results.
  535. func (q *Query) Iter() *Iter {
  536. if isUseStatement(q.stmt) {
  537. return &Iter{err: ErrUseStmt}
  538. }
  539. return q.session.executeQuery(q)
  540. }
  541. // MapScan executes the query, copies the columns of the first selected
  542. // row into the map pointed at by m and discards the rest. If no rows
  543. // were selected, ErrNotFound is returned.
  544. func (q *Query) MapScan(m map[string]interface{}) error {
  545. iter := q.Iter()
  546. if err := iter.checkErrAndNotFound(); err != nil {
  547. return err
  548. }
  549. iter.MapScan(m)
  550. return iter.Close()
  551. }
  552. // Scan executes the query, copies the columns of the first selected
  553. // row into the values pointed at by dest and discards the rest. If no rows
  554. // were selected, ErrNotFound is returned.
  555. func (q *Query) Scan(dest ...interface{}) error {
  556. iter := q.Iter()
  557. if err := iter.checkErrAndNotFound(); err != nil {
  558. return err
  559. }
  560. iter.Scan(dest...)
  561. return iter.Close()
  562. }
  563. // ScanCAS 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.
  567. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  568. iter := q.Iter()
  569. if err := iter.checkErrAndNotFound(); err != nil {
  570. return false, err
  571. }
  572. if len(iter.Columns()) > 1 {
  573. dest = append([]interface{}{&applied}, dest...)
  574. iter.Scan(dest...)
  575. } else {
  576. iter.Scan(&applied)
  577. }
  578. return applied, iter.Close()
  579. }
  580. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  581. // statement containing an IF clause). If the transaction fails because
  582. // the existing values did not match, the previous values will be stored
  583. // in dest map.
  584. //
  585. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  586. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  587. // column mismatching. MapScanCAS is added to capture them safely.
  588. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  589. iter := q.Iter()
  590. if err := iter.checkErrAndNotFound(); err != nil {
  591. return false, err
  592. }
  593. iter.MapScan(dest)
  594. applied = dest["[applied]"].(bool)
  595. delete(dest, "[applied]")
  596. return applied, iter.Close()
  597. }
  598. // Iter represents an iterator that can be used to iterate over all rows that
  599. // were returned by a query. The iterator might send additional queries to the
  600. // database during the iteration if paging was enabled.
  601. type Iter struct {
  602. err error
  603. pos int
  604. rows [][][]byte
  605. meta resultMetadata
  606. next *nextIter
  607. }
  608. // Columns returns the name and type of the selected columns.
  609. func (iter *Iter) Columns() []ColumnInfo {
  610. return iter.meta.columns
  611. }
  612. // Scan consumes the next row of the iterator and copies the columns of the
  613. // current row into the values pointed at by dest. Use nil as a dest value
  614. // to skip the corresponding column. Scan might send additional queries
  615. // to the database to retrieve the next set of rows if paging was enabled.
  616. //
  617. // Scan returns true if the row was successfully unmarshaled or false if the
  618. // end of the result set was reached or if an error occurred. Close should
  619. // be called afterwards to retrieve any potential errors.
  620. func (iter *Iter) Scan(dest ...interface{}) bool {
  621. if iter.err != nil {
  622. return false
  623. }
  624. if iter.pos >= len(iter.rows) {
  625. if iter.next != nil {
  626. *iter = *iter.next.fetch()
  627. return iter.Scan(dest...)
  628. }
  629. return false
  630. }
  631. if iter.next != nil && iter.pos == iter.next.pos {
  632. go iter.next.fetch()
  633. }
  634. // currently only support scanning into an expand tuple, such that its the same
  635. // as scanning in more values from a single column
  636. if len(dest) != iter.meta.actualColCount {
  637. iter.err = errors.New("count mismatch")
  638. return false
  639. }
  640. // i is the current position in dest, could posible replace it and just use
  641. // slices of dest
  642. i := 0
  643. for c, col := range iter.meta.columns {
  644. if dest[i] == nil {
  645. i++
  646. continue
  647. }
  648. switch col.TypeInfo.Type() {
  649. case TypeTuple:
  650. // this will panic, actually a bug, please report
  651. tuple := col.TypeInfo.(TupleTypeInfo)
  652. count := len(tuple.Elems)
  653. // here we pass in a slice of the struct which has the number number of
  654. // values as elements in the tuple
  655. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
  656. i += count
  657. default:
  658. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
  659. i++
  660. }
  661. if iter.err != nil {
  662. return false
  663. }
  664. }
  665. iter.pos++
  666. return true
  667. }
  668. // Close closes the iterator and returns any errors that happened during
  669. // the query or the iteration.
  670. func (iter *Iter) Close() error {
  671. return iter.err
  672. }
  673. // checkErrAndNotFound handle error and NotFound in one method.
  674. func (iter *Iter) checkErrAndNotFound() error {
  675. if iter.err != nil {
  676. return iter.err
  677. } else if len(iter.rows) == 0 {
  678. return ErrNotFound
  679. }
  680. return nil
  681. }
  682. type nextIter struct {
  683. qry Query
  684. pos int
  685. once sync.Once
  686. next *Iter
  687. }
  688. func (n *nextIter) fetch() *Iter {
  689. n.once.Do(func() {
  690. n.next = n.qry.session.executeQuery(&n.qry)
  691. })
  692. return n.next
  693. }
  694. type Batch struct {
  695. Type BatchType
  696. Entries []BatchEntry
  697. Cons Consistency
  698. rt RetryPolicy
  699. attempts int
  700. totalLatency int64
  701. serialCons SerialConsistency
  702. defaultTimestamp bool
  703. }
  704. // NewBatch creates a new batch operation without defaults from the cluster
  705. func NewBatch(typ BatchType) *Batch {
  706. return &Batch{Type: typ}
  707. }
  708. // NewBatch creates a new batch operation using defaults defined in the cluster
  709. func (s *Session) NewBatch(typ BatchType) *Batch {
  710. s.mu.RLock()
  711. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  712. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  713. s.mu.RUnlock()
  714. return batch
  715. }
  716. // Attempts returns the number of attempts made to execute the batch.
  717. func (b *Batch) Attempts() int {
  718. return b.attempts
  719. }
  720. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  721. func (b *Batch) Latency() int64 {
  722. if b.attempts > 0 {
  723. return b.totalLatency / int64(b.attempts)
  724. }
  725. return 0
  726. }
  727. // GetConsistency returns the currently configured consistency level for the batch
  728. // operation.
  729. func (b *Batch) GetConsistency() Consistency {
  730. return b.Cons
  731. }
  732. // Query adds the query to the batch operation
  733. func (b *Batch) Query(stmt string, args ...interface{}) {
  734. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  735. }
  736. // Bind adds the query to the batch operation and correlates it with a binding callback
  737. // that will be invoked when the batch is executed. The binding callback allows the application
  738. // to define which query argument values will be marshalled as part of the batch execution.
  739. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  740. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  741. }
  742. // RetryPolicy sets the retry policy to use when executing the batch operation
  743. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  744. b.rt = r
  745. return b
  746. }
  747. // Size returns the number of batch statements to be executed by the batch operation.
  748. func (b *Batch) Size() int {
  749. return len(b.Entries)
  750. }
  751. // SerialConsistency sets the consistencyc level for the
  752. // serial phase of conditional updates. That consitency can only be
  753. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  754. // SERIAL. This option will be ignored for anything else that a
  755. // conditional update/insert.
  756. //
  757. // Only available for protocol 3 and above
  758. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  759. b.serialCons = cons
  760. return b
  761. }
  762. // DefaultTimestamp will enable the with default timestamp flag on the query.
  763. // If enable, this will replace the server side assigned
  764. // timestamp as default timestamp. Note that a timestamp in the query itself
  765. // will still override this timestamp. This is entirely optional.
  766. //
  767. // Only available on protocol >= 3
  768. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  769. b.defaultTimestamp = enable
  770. return b
  771. }
  772. type BatchType byte
  773. const (
  774. LoggedBatch BatchType = 0
  775. UnloggedBatch = 1
  776. CounterBatch = 2
  777. )
  778. type BatchEntry struct {
  779. Stmt string
  780. Args []interface{}
  781. binding func(q *QueryInfo) ([]interface{}, error)
  782. }
  783. type ColumnInfo struct {
  784. Keyspace string
  785. Table string
  786. Name string
  787. TypeInfo TypeInfo
  788. }
  789. func (c ColumnInfo) String() string {
  790. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  791. }
  792. // routing key indexes LRU cache
  793. type routingKeyInfoLRU struct {
  794. lru *lru.Cache
  795. mu sync.Mutex
  796. }
  797. type routingKeyInfo struct {
  798. indexes []int
  799. types []TypeInfo
  800. }
  801. func (r *routingKeyInfoLRU) Remove(key string) {
  802. r.mu.Lock()
  803. r.lru.Remove(key)
  804. r.mu.Unlock()
  805. }
  806. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  807. //the new max is lower than the previous value. Not concurrency safe.
  808. func (r *routingKeyInfoLRU) Max(max int) {
  809. r.mu.Lock()
  810. for r.lru.Len() > max {
  811. r.lru.RemoveOldest()
  812. }
  813. r.lru.MaxEntries = max
  814. r.mu.Unlock()
  815. }
  816. type inflightCachedEntry struct {
  817. wg sync.WaitGroup
  818. err error
  819. value interface{}
  820. }
  821. // Tracer is the interface implemented by query tracers. Tracers have the
  822. // ability to obtain a detailed event log of all events that happened during
  823. // the execution of a query from Cassandra. Gathering this information might
  824. // be essential for debugging and optimizing queries, but this feature should
  825. // not be used on production systems with very high load.
  826. type Tracer interface {
  827. Trace(traceId []byte)
  828. }
  829. type traceWriter struct {
  830. session *Session
  831. w io.Writer
  832. mu sync.Mutex
  833. }
  834. // NewTraceWriter returns a simple Tracer implementation that outputs
  835. // the event log in a textual format.
  836. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  837. return &traceWriter{session: session, w: w}
  838. }
  839. func (t *traceWriter) Trace(traceId []byte) {
  840. var (
  841. coordinator string
  842. duration int
  843. )
  844. t.session.Query(`SELECT coordinator, duration
  845. FROM system_traces.sessions
  846. WHERE session_id = ?`, traceId).
  847. Consistency(One).Scan(&coordinator, &duration)
  848. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  849. FROM system_traces.events
  850. WHERE session_id = ?`, traceId).
  851. Consistency(One).Iter()
  852. var (
  853. timestamp time.Time
  854. activity string
  855. source string
  856. elapsed int
  857. )
  858. t.mu.Lock()
  859. defer t.mu.Unlock()
  860. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  861. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  862. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  863. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  864. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  865. }
  866. if err := iter.Close(); err != nil {
  867. fmt.Fprintln(t.w, "Error:", err)
  868. }
  869. }
  870. type Error struct {
  871. Code int
  872. Message string
  873. }
  874. func (e Error) Error() string {
  875. return e.Message
  876. }
  877. var (
  878. ErrNotFound = errors.New("not found")
  879. ErrUnavailable = errors.New("unavailable")
  880. ErrUnsupported = errors.New("feature not supported")
  881. ErrTooManyStmts = errors.New("too many statements")
  882. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  883. ErrSessionClosed = errors.New("session has been closed")
  884. ErrNoConnections = errors.New("no connections available")
  885. ErrNoKeyspace = errors.New("no keyspace provided")
  886. ErrNoMetadata = errors.New("no metadata available")
  887. )
  888. type ErrProtocol struct{ error }
  889. func NewErrProtocol(format string, args ...interface{}) error {
  890. return ErrProtocol{fmt.Errorf(format, args...)}
  891. }
  892. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  893. // This limit is set by cassandra and could change in the future.
  894. const BatchSizeMaximum = 65535