session.go 32 KB

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