session.go 32 KB

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