session.go 33 KB

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