session.go 37 KB

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