session.go 33 KB

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