session.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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/internal/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 *policyConnPool
  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. hostFilter HostFilter
  37. control *controlConn
  38. // ring metadata
  39. hosts []HostInfo
  40. cfg ClusterConfig
  41. closeMu sync.RWMutex
  42. isClosed bool
  43. }
  44. // NewSession wraps an existing Node.
  45. func NewSession(cfg ClusterConfig) (*Session, error) {
  46. //Check that hosts in the ClusterConfig is not empty
  47. if len(cfg.Hosts) < 1 {
  48. return nil, ErrNoHosts
  49. }
  50. //Adjust the size of the prepared statements cache to match the latest configuration
  51. stmtsLRU.Lock()
  52. initStmtsLRU(cfg.MaxPreparedStmts)
  53. stmtsLRU.Unlock()
  54. s := &Session{
  55. cons: cfg.Consistency,
  56. prefetch: 0.25,
  57. cfg: cfg,
  58. pageSize: cfg.PageSize,
  59. }
  60. s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
  61. // I think it might be a good idea to simplify this and make it always discover
  62. // hosts, maybe with more filters.
  63. s.hostSource = &ringDescriber{
  64. session: s,
  65. closeChan: make(chan bool),
  66. }
  67. if !cfg.disableControlConn {
  68. s.control = createControlConn(s)
  69. if err := s.control.connect(cfg.Hosts); err != nil {
  70. return nil, err
  71. }
  72. // need to setup host source to check for broadcast_address in system.local
  73. localHasRPCAddr, _ := checkSystemLocal(s.control)
  74. s.hostSource.localHasRpcAddr = localHasRPCAddr
  75. hosts, _, err := s.hostSource.GetHosts()
  76. if err != nil {
  77. s.control.close()
  78. return nil, err
  79. }
  80. pool, err := cfg.PoolConfig.buildPool(s)
  81. if err != nil {
  82. return nil, err
  83. }
  84. s.pool = pool
  85. // TODO(zariel): this should be used to create initial metadata
  86. s.pool.SetHosts(hosts)
  87. } else {
  88. // TODO(zariel): remove branch for creating pools
  89. pool, err := cfg.PoolConfig.buildPool(s)
  90. if err != nil {
  91. return nil, err
  92. }
  93. s.pool = pool
  94. }
  95. // TODO(zariel): we probably dont need this any more as we verify that we
  96. // can connect to one of the endpoints supplied by using the control conn.
  97. // See if there are any connections in the pool
  98. if s.pool.Size() == 0 {
  99. s.Close()
  100. return nil, ErrNoConnectionsStarted
  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. // WillSwitchPage detects if iterator reached end of current page
  770. // and the next page is available.
  771. func (iter *Iter) WillSwitchPage() bool {
  772. return iter.pos >= len(iter.rows) && iter.next != nil
  773. }
  774. // checkErrAndNotFound handle error and NotFound in one method.
  775. func (iter *Iter) checkErrAndNotFound() error {
  776. if iter.err != nil {
  777. return iter.err
  778. } else if len(iter.rows) == 0 {
  779. return ErrNotFound
  780. }
  781. return nil
  782. }
  783. // PageState return the current paging state for a query which can be used for
  784. // subsequent quries to resume paging this point.
  785. func (iter *Iter) PageState() []byte {
  786. return iter.meta.pagingState
  787. }
  788. type nextIter struct {
  789. qry Query
  790. pos int
  791. once sync.Once
  792. next *Iter
  793. }
  794. func (n *nextIter) fetch() *Iter {
  795. n.once.Do(func() {
  796. n.next = n.qry.session.executeQuery(&n.qry)
  797. })
  798. return n.next
  799. }
  800. type Batch struct {
  801. Type BatchType
  802. Entries []BatchEntry
  803. Cons Consistency
  804. rt RetryPolicy
  805. attempts int
  806. totalLatency int64
  807. serialCons SerialConsistency
  808. defaultTimestamp bool
  809. }
  810. // NewBatch creates a new batch operation without defaults from the cluster
  811. func NewBatch(typ BatchType) *Batch {
  812. return &Batch{Type: typ}
  813. }
  814. // NewBatch creates a new batch operation using defaults defined in the cluster
  815. func (s *Session) NewBatch(typ BatchType) *Batch {
  816. s.mu.RLock()
  817. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  818. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  819. s.mu.RUnlock()
  820. return batch
  821. }
  822. // Attempts returns the number of attempts made to execute the batch.
  823. func (b *Batch) Attempts() int {
  824. return b.attempts
  825. }
  826. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  827. func (b *Batch) Latency() int64 {
  828. if b.attempts > 0 {
  829. return b.totalLatency / int64(b.attempts)
  830. }
  831. return 0
  832. }
  833. // GetConsistency returns the currently configured consistency level for the batch
  834. // operation.
  835. func (b *Batch) GetConsistency() Consistency {
  836. return b.Cons
  837. }
  838. // Query adds the query to the batch operation
  839. func (b *Batch) Query(stmt string, args ...interface{}) {
  840. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  841. }
  842. // Bind adds the query to the batch operation and correlates it with a binding callback
  843. // that will be invoked when the batch is executed. The binding callback allows the application
  844. // to define which query argument values will be marshalled as part of the batch execution.
  845. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  846. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  847. }
  848. // RetryPolicy sets the retry policy to use when executing the batch operation
  849. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  850. b.rt = r
  851. return b
  852. }
  853. // Size returns the number of batch statements to be executed by the batch operation.
  854. func (b *Batch) Size() int {
  855. return len(b.Entries)
  856. }
  857. // SerialConsistency sets the consistencyc level for the
  858. // serial phase of conditional updates. That consitency can only be
  859. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  860. // SERIAL. This option will be ignored for anything else that a
  861. // conditional update/insert.
  862. //
  863. // Only available for protocol 3 and above
  864. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  865. b.serialCons = cons
  866. return b
  867. }
  868. // DefaultTimestamp will enable the with default timestamp flag on the query.
  869. // If enable, this will replace the server side assigned
  870. // timestamp as default timestamp. Note that a timestamp in the query itself
  871. // will still override this timestamp. This is entirely optional.
  872. //
  873. // Only available on protocol >= 3
  874. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  875. b.defaultTimestamp = enable
  876. return b
  877. }
  878. type BatchType byte
  879. const (
  880. LoggedBatch BatchType = 0
  881. UnloggedBatch BatchType = 1
  882. CounterBatch BatchType = 2
  883. )
  884. type BatchEntry struct {
  885. Stmt string
  886. Args []interface{}
  887. binding func(q *QueryInfo) ([]interface{}, error)
  888. }
  889. type ColumnInfo struct {
  890. Keyspace string
  891. Table string
  892. Name string
  893. TypeInfo TypeInfo
  894. }
  895. func (c ColumnInfo) String() string {
  896. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  897. }
  898. // routing key indexes LRU cache
  899. type routingKeyInfoLRU struct {
  900. lru *lru.Cache
  901. mu sync.Mutex
  902. }
  903. type routingKeyInfo struct {
  904. indexes []int
  905. types []TypeInfo
  906. }
  907. func (r *routingKeyInfoLRU) Remove(key string) {
  908. r.mu.Lock()
  909. r.lru.Remove(key)
  910. r.mu.Unlock()
  911. }
  912. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  913. //the new max is lower than the previous value. Not concurrency safe.
  914. func (r *routingKeyInfoLRU) Max(max int) {
  915. r.mu.Lock()
  916. for r.lru.Len() > max {
  917. r.lru.RemoveOldest()
  918. }
  919. r.lru.MaxEntries = max
  920. r.mu.Unlock()
  921. }
  922. type inflightCachedEntry struct {
  923. wg sync.WaitGroup
  924. err error
  925. value interface{}
  926. }
  927. // Tracer is the interface implemented by query tracers. Tracers have the
  928. // ability to obtain a detailed event log of all events that happened during
  929. // the execution of a query from Cassandra. Gathering this information might
  930. // be essential for debugging and optimizing queries, but this feature should
  931. // not be used on production systems with very high load.
  932. type Tracer interface {
  933. Trace(traceId []byte)
  934. }
  935. type traceWriter struct {
  936. session *Session
  937. w io.Writer
  938. mu sync.Mutex
  939. }
  940. // NewTraceWriter returns a simple Tracer implementation that outputs
  941. // the event log in a textual format.
  942. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  943. return &traceWriter{session: session, w: w}
  944. }
  945. func (t *traceWriter) Trace(traceId []byte) {
  946. var (
  947. coordinator string
  948. duration int
  949. )
  950. iter := t.session.control.query(`SELECT coordinator, duration
  951. FROM system_traces.sessions
  952. WHERE session_id = ?`, traceId)
  953. iter.Scan(&coordinator, &duration)
  954. if err := iter.Close(); err != nil {
  955. t.mu.Lock()
  956. fmt.Fprintln(t.w, "Error:", err)
  957. t.mu.Unlock()
  958. return
  959. }
  960. var (
  961. timestamp time.Time
  962. activity string
  963. source string
  964. elapsed int
  965. )
  966. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  967. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  968. t.mu.Lock()
  969. defer t.mu.Unlock()
  970. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  971. FROM system_traces.events
  972. WHERE session_id = ?`, traceId)
  973. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  974. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  975. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  976. }
  977. if err := iter.Close(); err != nil {
  978. fmt.Fprintln(t.w, "Error:", err)
  979. }
  980. }
  981. type Error struct {
  982. Code int
  983. Message string
  984. }
  985. func (e Error) Error() string {
  986. return e.Message
  987. }
  988. var (
  989. ErrNotFound = errors.New("not found")
  990. ErrUnavailable = errors.New("unavailable")
  991. ErrUnsupported = errors.New("feature not supported")
  992. ErrTooManyStmts = errors.New("too many statements")
  993. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  994. ErrSessionClosed = errors.New("session has been closed")
  995. ErrNoConnections = errors.New("no connections available")
  996. ErrNoKeyspace = errors.New("no keyspace provided")
  997. ErrNoMetadata = errors.New("no metadata available")
  998. )
  999. type ErrProtocol struct{ error }
  1000. func NewErrProtocol(format string, args ...interface{}) error {
  1001. return ErrProtocol{fmt.Errorf(format, args...)}
  1002. }
  1003. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1004. // This limit is set by cassandra and could change in the future.
  1005. const BatchSizeMaximum = 65535