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