session.go 31 KB

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