session.go 39 KB

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