session.go 32 KB

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