session.go 32 KB

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