session.go 33 KB

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