session.go 34 KB

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