session.go 34 KB

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