session.go 32 KB

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