session.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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 *preparedStatment
  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 info.request.colCount == 0 {
  322. // no arguments, no routing key, and no error
  323. return nil, nil
  324. }
  325. // get the table metadata
  326. table := info.request.columns[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.request.columns {
  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. isCAS bool
  481. disableAutoPage bool
  482. }
  483. // String implements the stringer interface.
  484. func (q Query) String() string {
  485. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  486. }
  487. //Attempts returns the number of times the query was executed.
  488. func (q *Query) Attempts() int {
  489. return q.attempts
  490. }
  491. //Latency returns the average amount of nanoseconds per attempt of the query.
  492. func (q *Query) Latency() int64 {
  493. if q.attempts > 0 {
  494. return q.totalLatency / int64(q.attempts)
  495. }
  496. return 0
  497. }
  498. // Consistency sets the consistency level for this query. If no consistency
  499. // level have been set, the default consistency level of the cluster
  500. // is used.
  501. func (q *Query) Consistency(c Consistency) *Query {
  502. q.cons = c
  503. return q
  504. }
  505. // GetConsistency returns the currently configured consistency level for
  506. // the query.
  507. func (q *Query) GetConsistency() Consistency {
  508. return q.cons
  509. }
  510. // Trace enables tracing of this query. Look at the documentation of the
  511. // Tracer interface to learn more about tracing.
  512. func (q *Query) Trace(trace Tracer) *Query {
  513. q.trace = trace
  514. return q
  515. }
  516. // PageSize will tell the iterator to fetch the result in pages of size n.
  517. // This is useful for iterating over large result sets, but setting the
  518. // page size to low might decrease the performance. This feature is only
  519. // available in Cassandra 2 and onwards.
  520. func (q *Query) PageSize(n int) *Query {
  521. q.pageSize = n
  522. return q
  523. }
  524. // DefaultTimestamp will enable the with default timestamp flag on the query.
  525. // If enable, this will replace the server side assigned
  526. // timestamp as default timestamp. Note that a timestamp in the query itself
  527. // will still override this timestamp. This is entirely optional.
  528. //
  529. // Only available on protocol >= 3
  530. func (q *Query) DefaultTimestamp(enable bool) *Query {
  531. q.defaultTimestamp = enable
  532. return q
  533. }
  534. // RoutingKey sets the routing key to use when a token aware connection
  535. // pool is used to optimize the routing of this query.
  536. func (q *Query) RoutingKey(routingKey []byte) *Query {
  537. q.routingKey = routingKey
  538. return q
  539. }
  540. // GetRoutingKey gets the routing key to use for routing this query. If
  541. // a routing key has not been explicitly set, then the routing key will
  542. // be constructed if possible using the keyspace's schema and the query
  543. // info for this query statement. If the routing key cannot be determined
  544. // then nil will be returned with no error. On any error condition,
  545. // an error description will be returned.
  546. func (q *Query) GetRoutingKey() ([]byte, error) {
  547. if q.routingKey != nil {
  548. return q.routingKey, nil
  549. }
  550. // try to determine the routing key
  551. routingKeyInfo, err := q.session.routingKeyInfo(q.stmt)
  552. if err != nil {
  553. return nil, err
  554. }
  555. if routingKeyInfo == nil {
  556. return nil, nil
  557. }
  558. if len(routingKeyInfo.indexes) == 1 {
  559. // single column routing key
  560. routingKey, err := Marshal(
  561. routingKeyInfo.types[0],
  562. q.values[routingKeyInfo.indexes[0]],
  563. )
  564. if err != nil {
  565. return nil, err
  566. }
  567. return routingKey, nil
  568. }
  569. // We allocate that buffer only once, so that further re-bind/exec of the
  570. // same query don't allocate more memory.
  571. if q.routingKeyBuffer == nil {
  572. q.routingKeyBuffer = make([]byte, 0, 256)
  573. }
  574. // composite routing key
  575. buf := bytes.NewBuffer(q.routingKeyBuffer)
  576. for i := range routingKeyInfo.indexes {
  577. encoded, err := Marshal(
  578. routingKeyInfo.types[i],
  579. q.values[routingKeyInfo.indexes[i]],
  580. )
  581. if err != nil {
  582. return nil, err
  583. }
  584. lenBuf := []byte{0x00, 0x00}
  585. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  586. buf.Write(lenBuf)
  587. buf.Write(encoded)
  588. buf.WriteByte(0x00)
  589. }
  590. routingKey := buf.Bytes()
  591. return routingKey, nil
  592. }
  593. func (q *Query) shouldPrepare() bool {
  594. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  595. return unicode.IsSpace(r) || r == ';'
  596. }), unicode.IsSpace)
  597. var stmtType string
  598. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  599. stmtType = strings.ToLower(stmt[:n])
  600. }
  601. if stmtType == "begin" {
  602. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  603. stmtType = strings.ToLower(stmt[n+1:])
  604. }
  605. }
  606. switch stmtType {
  607. case "select", "insert", "update", "delete", "batch":
  608. return true
  609. }
  610. return false
  611. }
  612. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  613. // there are only p*pageSize rows remaining, the next page will be requested
  614. // automatically.
  615. func (q *Query) Prefetch(p float64) *Query {
  616. q.prefetch = p
  617. return q
  618. }
  619. // RetryPolicy sets the policy to use when retrying the query.
  620. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  621. q.rt = r
  622. return q
  623. }
  624. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  625. // to an existing query instance.
  626. func (q *Query) Bind(v ...interface{}) *Query {
  627. q.values = v
  628. return q
  629. }
  630. // SerialConsistency sets the consistencyc level for the
  631. // serial phase of conditional updates. That consitency can only be
  632. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  633. // SERIAL. This option will be ignored for anything else that a
  634. // conditional update/insert.
  635. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  636. q.serialCons = cons
  637. return q
  638. }
  639. // PageState sets the paging state for the query to resume paging from a specific
  640. // point in time. Setting this will disable to query paging for this query, and
  641. // must be used for all subsequent pages.
  642. func (q *Query) PageState(state []byte) *Query {
  643. q.pageState = state
  644. q.disableAutoPage = true
  645. return q
  646. }
  647. // Exec executes the query without returning any rows.
  648. func (q *Query) Exec() error {
  649. iter := q.Iter()
  650. return iter.Close()
  651. }
  652. func isUseStatement(stmt string) bool {
  653. if len(stmt) < 3 {
  654. return false
  655. }
  656. return strings.ToLower(stmt[0:3]) == "use"
  657. }
  658. // Iter executes the query and returns an iterator capable of iterating
  659. // over all results.
  660. func (q *Query) Iter() *Iter {
  661. if isUseStatement(q.stmt) {
  662. return &Iter{err: ErrUseStmt}
  663. }
  664. return q.session.executeQuery(q)
  665. }
  666. // MapScan executes the query, copies the columns of the first selected
  667. // row into the map pointed at by m and discards the rest. If no rows
  668. // were selected, ErrNotFound is returned.
  669. func (q *Query) MapScan(m map[string]interface{}) error {
  670. iter := q.Iter()
  671. if err := iter.checkErrAndNotFound(); err != nil {
  672. return err
  673. }
  674. iter.MapScan(m)
  675. return iter.Close()
  676. }
  677. // Scan executes the query, copies the columns of the first selected
  678. // row into the values pointed at by dest and discards the rest. If no rows
  679. // were selected, ErrNotFound is returned.
  680. func (q *Query) Scan(dest ...interface{}) error {
  681. iter := q.Iter()
  682. if err := iter.checkErrAndNotFound(); err != nil {
  683. return err
  684. }
  685. iter.Scan(dest...)
  686. return iter.Close()
  687. }
  688. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  689. // statement containing an IF clause). If the transaction fails because
  690. // the existing values did not match, the previous values will be stored
  691. // in dest.
  692. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  693. q.isCAS = true
  694. iter := q.Iter()
  695. if err := iter.checkErrAndNotFound(); err != nil {
  696. return false, err
  697. }
  698. if len(iter.Columns()) > 1 {
  699. dest = append([]interface{}{&applied}, dest...)
  700. iter.Scan(dest...)
  701. } else {
  702. iter.Scan(&applied)
  703. }
  704. return applied, iter.Close()
  705. }
  706. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  707. // statement containing an IF clause). If the transaction fails because
  708. // the existing values did not match, the previous values will be stored
  709. // in dest map.
  710. //
  711. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  712. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  713. // column mismatching. MapScanCAS is added to capture them safely.
  714. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  715. q.isCAS = true
  716. iter := q.Iter()
  717. if err := iter.checkErrAndNotFound(); err != nil {
  718. return false, err
  719. }
  720. iter.MapScan(dest)
  721. applied = dest["[applied]"].(bool)
  722. delete(dest, "[applied]")
  723. return applied, iter.Close()
  724. }
  725. // Iter represents an iterator that can be used to iterate over all rows that
  726. // were returned by a query. The iterator might send additional queries to the
  727. // database during the iteration if paging was enabled.
  728. type Iter struct {
  729. err error
  730. pos int
  731. rows [][][]byte
  732. meta resultMetadata
  733. next *nextIter
  734. host *HostInfo
  735. framer *framer
  736. once sync.Once
  737. }
  738. // Host returns the host which the query was sent to.
  739. func (iter *Iter) Host() *HostInfo {
  740. return iter.host
  741. }
  742. // Columns returns the name and type of the selected columns.
  743. func (iter *Iter) Columns() []ColumnInfo {
  744. return iter.meta.columns
  745. }
  746. // Scan consumes the next row of the iterator and copies the columns of the
  747. // current row into the values pointed at by dest. Use nil as a dest value
  748. // to skip the corresponding column. Scan might send additional queries
  749. // to the database to retrieve the next set of rows if paging was enabled.
  750. //
  751. // Scan returns true if the row was successfully unmarshaled or false if the
  752. // end of the result set was reached or if an error occurred. Close should
  753. // be called afterwards to retrieve any potential errors.
  754. func (iter *Iter) Scan(dest ...interface{}) bool {
  755. if iter.err != nil {
  756. return false
  757. }
  758. if iter.pos >= len(iter.rows) {
  759. if iter.next != nil {
  760. *iter = *iter.next.fetch()
  761. return iter.Scan(dest...)
  762. }
  763. return false
  764. }
  765. if iter.next != nil && iter.pos == iter.next.pos {
  766. go iter.next.fetch()
  767. }
  768. // currently only support scanning into an expand tuple, such that its the same
  769. // as scanning in more values from a single column
  770. if len(dest) != iter.meta.actualColCount {
  771. iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  772. return false
  773. }
  774. // i is the current position in dest, could posible replace it and just use
  775. // slices of dest
  776. i := 0
  777. for c, col := range iter.meta.columns {
  778. if dest[i] == nil {
  779. i++
  780. continue
  781. }
  782. switch col.TypeInfo.Type() {
  783. case TypeTuple:
  784. // this will panic, actually a bug, please report
  785. tuple := col.TypeInfo.(TupleTypeInfo)
  786. count := len(tuple.Elems)
  787. // here we pass in a slice of the struct which has the number number of
  788. // values as elements in the tuple
  789. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
  790. i += count
  791. default:
  792. iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
  793. i++
  794. }
  795. if iter.err != nil {
  796. return false
  797. }
  798. }
  799. iter.pos++
  800. return true
  801. }
  802. // Close closes the iterator and returns any errors that happened during
  803. // the query or the iteration.
  804. func (iter *Iter) Close() error {
  805. iter.once.Do(func() {
  806. if iter.framer != nil {
  807. framerPool.Put(iter.framer)
  808. iter.framer = nil
  809. }
  810. })
  811. return iter.err
  812. }
  813. // WillSwitchPage detects if iterator reached end of current page
  814. // and the next page is available.
  815. func (iter *Iter) WillSwitchPage() bool {
  816. return iter.pos >= len(iter.rows) && iter.next != nil
  817. }
  818. // checkErrAndNotFound handle error and NotFound in one method.
  819. func (iter *Iter) checkErrAndNotFound() error {
  820. if iter.err != nil {
  821. return iter.err
  822. } else if len(iter.rows) == 0 {
  823. return ErrNotFound
  824. }
  825. return nil
  826. }
  827. // PageState return the current paging state for a query which can be used for
  828. // subsequent quries to resume paging this point.
  829. func (iter *Iter) PageState() []byte {
  830. return iter.meta.pagingState
  831. }
  832. type nextIter struct {
  833. qry Query
  834. pos int
  835. once sync.Once
  836. next *Iter
  837. }
  838. func (n *nextIter) fetch() *Iter {
  839. n.once.Do(func() {
  840. n.next = n.qry.session.executeQuery(&n.qry)
  841. })
  842. return n.next
  843. }
  844. type Batch struct {
  845. Type BatchType
  846. Entries []BatchEntry
  847. Cons Consistency
  848. rt RetryPolicy
  849. attempts int
  850. totalLatency int64
  851. serialCons SerialConsistency
  852. defaultTimestamp bool
  853. }
  854. // NewBatch creates a new batch operation without defaults from the cluster
  855. func NewBatch(typ BatchType) *Batch {
  856. return &Batch{Type: typ}
  857. }
  858. // NewBatch creates a new batch operation using defaults defined in the cluster
  859. func (s *Session) NewBatch(typ BatchType) *Batch {
  860. s.mu.RLock()
  861. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  862. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  863. s.mu.RUnlock()
  864. return batch
  865. }
  866. // Attempts returns the number of attempts made to execute the batch.
  867. func (b *Batch) Attempts() int {
  868. return b.attempts
  869. }
  870. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  871. func (b *Batch) Latency() int64 {
  872. if b.attempts > 0 {
  873. return b.totalLatency / int64(b.attempts)
  874. }
  875. return 0
  876. }
  877. // GetConsistency returns the currently configured consistency level for the batch
  878. // operation.
  879. func (b *Batch) GetConsistency() Consistency {
  880. return b.Cons
  881. }
  882. // Query adds the query to the batch operation
  883. func (b *Batch) Query(stmt string, args ...interface{}) {
  884. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  885. }
  886. // Bind adds the query to the batch operation and correlates it with a binding callback
  887. // that will be invoked when the batch is executed. The binding callback allows the application
  888. // to define which query argument values will be marshalled as part of the batch execution.
  889. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  890. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  891. }
  892. // RetryPolicy sets the retry policy to use when executing the batch operation
  893. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  894. b.rt = r
  895. return b
  896. }
  897. // Size returns the number of batch statements to be executed by the batch operation.
  898. func (b *Batch) Size() int {
  899. return len(b.Entries)
  900. }
  901. // SerialConsistency sets the consistencyc level for the
  902. // serial phase of conditional updates. That consitency can only be
  903. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  904. // SERIAL. This option will be ignored for anything else that a
  905. // conditional update/insert.
  906. //
  907. // Only available for protocol 3 and above
  908. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  909. b.serialCons = cons
  910. return b
  911. }
  912. // DefaultTimestamp will enable the with default timestamp flag on the query.
  913. // If enable, this will replace the server side assigned
  914. // timestamp as default timestamp. Note that a timestamp in the query itself
  915. // will still override this timestamp. This is entirely optional.
  916. //
  917. // Only available on protocol >= 3
  918. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  919. b.defaultTimestamp = enable
  920. return b
  921. }
  922. type BatchType byte
  923. const (
  924. LoggedBatch BatchType = 0
  925. UnloggedBatch BatchType = 1
  926. CounterBatch BatchType = 2
  927. )
  928. type BatchEntry struct {
  929. Stmt string
  930. Args []interface{}
  931. binding func(q *QueryInfo) ([]interface{}, error)
  932. }
  933. type ColumnInfo struct {
  934. Keyspace string
  935. Table string
  936. Name string
  937. TypeInfo TypeInfo
  938. }
  939. func (c ColumnInfo) String() string {
  940. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  941. }
  942. // routing key indexes LRU cache
  943. type routingKeyInfoLRU struct {
  944. lru *lru.Cache
  945. mu sync.Mutex
  946. }
  947. type routingKeyInfo struct {
  948. indexes []int
  949. types []TypeInfo
  950. }
  951. func (r *routingKeyInfoLRU) Remove(key string) {
  952. r.mu.Lock()
  953. r.lru.Remove(key)
  954. r.mu.Unlock()
  955. }
  956. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  957. //the new max is lower than the previous value. Not concurrency safe.
  958. func (r *routingKeyInfoLRU) Max(max int) {
  959. r.mu.Lock()
  960. for r.lru.Len() > max {
  961. r.lru.RemoveOldest()
  962. }
  963. r.lru.MaxEntries = max
  964. r.mu.Unlock()
  965. }
  966. type inflightCachedEntry struct {
  967. wg sync.WaitGroup
  968. err error
  969. value interface{}
  970. }
  971. // Tracer is the interface implemented by query tracers. Tracers have the
  972. // ability to obtain a detailed event log of all events that happened during
  973. // the execution of a query from Cassandra. Gathering this information might
  974. // be essential for debugging and optimizing queries, but this feature should
  975. // not be used on production systems with very high load.
  976. type Tracer interface {
  977. Trace(traceId []byte)
  978. }
  979. type traceWriter struct {
  980. session *Session
  981. w io.Writer
  982. mu sync.Mutex
  983. }
  984. // NewTraceWriter returns a simple Tracer implementation that outputs
  985. // the event log in a textual format.
  986. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  987. return &traceWriter{session: session, w: w}
  988. }
  989. func (t *traceWriter) Trace(traceId []byte) {
  990. var (
  991. coordinator string
  992. duration int
  993. )
  994. iter := t.session.control.query(`SELECT coordinator, duration
  995. FROM system_traces.sessions
  996. WHERE session_id = ?`, traceId)
  997. iter.Scan(&coordinator, &duration)
  998. if err := iter.Close(); err != nil {
  999. t.mu.Lock()
  1000. fmt.Fprintln(t.w, "Error:", err)
  1001. t.mu.Unlock()
  1002. return
  1003. }
  1004. var (
  1005. timestamp time.Time
  1006. activity string
  1007. source string
  1008. elapsed int
  1009. )
  1010. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1011. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1012. t.mu.Lock()
  1013. defer t.mu.Unlock()
  1014. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1015. FROM system_traces.events
  1016. WHERE session_id = ?`, traceId)
  1017. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1018. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1019. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1020. }
  1021. if err := iter.Close(); err != nil {
  1022. fmt.Fprintln(t.w, "Error:", err)
  1023. }
  1024. }
  1025. type Error struct {
  1026. Code int
  1027. Message string
  1028. }
  1029. func (e Error) Error() string {
  1030. return e.Message
  1031. }
  1032. var (
  1033. ErrNotFound = errors.New("not found")
  1034. ErrUnavailable = errors.New("unavailable")
  1035. ErrUnsupported = errors.New("feature not supported")
  1036. ErrTooManyStmts = errors.New("too many statements")
  1037. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  1038. ErrSessionClosed = errors.New("session has been closed")
  1039. ErrNoConnections = errors.New("no connections available")
  1040. ErrNoKeyspace = errors.New("no keyspace provided")
  1041. ErrNoMetadata = errors.New("no metadata available")
  1042. )
  1043. type ErrProtocol struct{ error }
  1044. func NewErrProtocol(format string, args ...interface{}) error {
  1045. return ErrProtocol{fmt.Errorf(format, args...)}
  1046. }
  1047. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1048. // This limit is set by cassandra and could change in the future.
  1049. const BatchSizeMaximum = 65535