session.go 35 KB

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