session.go 34 KB

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