session.go 32 KB

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