session.go 39 KB

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