session.go 32 KB

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