session.go 38 KB

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