session.go 35 KB

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