session.go 33 KB

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