session.go 31 KB

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