session.go 34 KB

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