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. queryPool *sync.Pool
  58. }
  59. func addrsToHosts(addrs []string, defaultPort int) ([]*HostInfo, error) {
  60. hosts := make([]*HostInfo, len(addrs))
  61. for i, hostport := range addrs {
  62. // TODO: remove duplication
  63. addr, portStr, err := net.SplitHostPort(JoinHostPort(hostport, defaultPort))
  64. if err != nil {
  65. return nil, fmt.Errorf("NewSession: unable to parse hostport of addr %q: %v", hostport, err)
  66. }
  67. port, err := strconv.Atoi(portStr)
  68. if err != nil {
  69. return nil, fmt.Errorf("NewSession: invalid port for hostport of addr %q: %v", hostport, err)
  70. }
  71. hosts[i] = &HostInfo{peer: addr, port: port, state: NodeUp}
  72. }
  73. return hosts, nil
  74. }
  75. // NewSession wraps an existing Node.
  76. func NewSession(cfg ClusterConfig) (*Session, error) {
  77. //Check that hosts in the ClusterConfig is not empty
  78. if len(cfg.Hosts) < 1 {
  79. return nil, ErrNoHosts
  80. }
  81. s := &Session{
  82. cons: cfg.Consistency,
  83. prefetch: 0.25,
  84. cfg: cfg,
  85. pageSize: cfg.PageSize,
  86. stmtsLRU: &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
  87. queryPool: &sync.Pool{New: func() interface{} { return new(Query) }},
  88. }
  89. connCfg, err := connConfig(s)
  90. if err != nil {
  91. s.Close()
  92. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  93. }
  94. s.connCfg = connCfg
  95. s.nodeEvents = newEventDeouncer("NodeEvents", s.handleNodeEvent)
  96. s.schemaEvents = newEventDeouncer("SchemaEvents", s.handleSchemaEvent)
  97. s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
  98. // I think it might be a good idea to simplify this and make it always discover
  99. // hosts, maybe with more filters.
  100. s.hostSource = &ringDescriber{
  101. session: s,
  102. closeChan: make(chan bool),
  103. }
  104. pool := cfg.PoolConfig.buildPool(s)
  105. if cfg.PoolConfig.HostSelectionPolicy == nil {
  106. cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
  107. }
  108. s.pool = pool
  109. s.policy = cfg.PoolConfig.HostSelectionPolicy
  110. s.executor = &queryExecutor{
  111. pool: pool,
  112. policy: cfg.PoolConfig.HostSelectionPolicy,
  113. }
  114. var hosts []*HostInfo
  115. if !cfg.disableControlConn {
  116. s.control = createControlConn(s)
  117. if err := s.control.connect(cfg.Hosts); err != nil {
  118. s.Close()
  119. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  120. }
  121. // need to setup host source to check for broadcast_address in system.local
  122. localHasRPCAddr, _ := checkSystemLocal(s.control)
  123. s.hostSource.localHasRpcAddr = localHasRPCAddr
  124. var err error
  125. if cfg.DisableInitialHostLookup {
  126. // TODO: we could look at system.local to get token and other metadata
  127. // in this case.
  128. hosts, err = addrsToHosts(cfg.Hosts, cfg.Port)
  129. } else {
  130. hosts, _, err = s.hostSource.GetHosts()
  131. }
  132. if err != nil {
  133. s.Close()
  134. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  135. }
  136. } else {
  137. // we dont get host info
  138. hosts, err = addrsToHosts(cfg.Hosts, cfg.Port)
  139. }
  140. for _, host := range hosts {
  141. if s.cfg.HostFilter == nil || s.cfg.HostFilter.Accept(host) {
  142. if existingHost, ok := s.ring.addHostIfMissing(host); ok {
  143. existingHost.update(host)
  144. }
  145. s.handleNodeUp(net.ParseIP(host.Peer()), host.Port(), false)
  146. }
  147. }
  148. if cfg.ReconnectInterval > 0 {
  149. go s.reconnectDownedHosts(cfg.ReconnectInterval)
  150. }
  151. // TODO(zariel): we probably dont need this any more as we verify that we
  152. // can connect to one of the endpoints supplied by using the control conn.
  153. // See if there are any connections in the pool
  154. if s.pool.Size() == 0 {
  155. s.Close()
  156. return nil, ErrNoConnectionsStarted
  157. }
  158. s.useSystemSchema = hosts[0].Version().Major >= 3
  159. return s, nil
  160. }
  161. func (s *Session) reconnectDownedHosts(intv time.Duration) {
  162. for !s.Closed() {
  163. time.Sleep(intv)
  164. hosts := s.ring.allHosts()
  165. // Print session.ring for debug.
  166. if gocqlDebug {
  167. buf := bytes.NewBufferString("Session.ring:")
  168. for _, h := range hosts {
  169. buf.WriteString("[" + h.Peer() + ":" + h.State().String() + "]")
  170. }
  171. log.Println(buf.String())
  172. }
  173. for _, h := range hosts {
  174. if h.IsUp() {
  175. continue
  176. }
  177. s.handleNodeUp(net.ParseIP(h.Peer()), h.Port(), true)
  178. }
  179. }
  180. }
  181. // SetConsistency sets the default consistency level for this session. This
  182. // setting can also be changed on a per-query basis and the default value
  183. // is Quorum.
  184. func (s *Session) SetConsistency(cons Consistency) {
  185. s.mu.Lock()
  186. s.cons = cons
  187. s.mu.Unlock()
  188. }
  189. // SetPageSize sets the default page size for this session. A value <= 0 will
  190. // disable paging. This setting can also be changed on a per-query basis.
  191. func (s *Session) SetPageSize(n int) {
  192. s.mu.Lock()
  193. s.pageSize = n
  194. s.mu.Unlock()
  195. }
  196. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  197. // there are only p*pageSize rows remaining, the next page will be requested
  198. // automatically. This value can also be changed on a per-query basis and
  199. // the default value is 0.25.
  200. func (s *Session) SetPrefetch(p float64) {
  201. s.mu.Lock()
  202. s.prefetch = p
  203. s.mu.Unlock()
  204. }
  205. // SetTrace sets the default tracer for this session. This setting can also
  206. // be changed on a per-query basis.
  207. func (s *Session) SetTrace(trace Tracer) {
  208. s.mu.Lock()
  209. s.trace = trace
  210. s.mu.Unlock()
  211. }
  212. // Query generates a new query object for interacting with the database.
  213. // Further details of the query may be tweaked using the resulting query
  214. // value before the query is executed. Query is automatically prepared
  215. // if it has not previously been executed.
  216. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  217. s.mu.RLock()
  218. qry := s.queryPool.Get().(*Query)
  219. qry.stmt = stmt
  220. qry.values = values
  221. qry.cons = s.cons
  222. qry.session = s
  223. qry.pageSize = s.pageSize
  224. qry.trace = s.trace
  225. qry.prefetch = s.prefetch
  226. qry.rt = s.cfg.RetryPolicy
  227. qry.serialCons = s.cfg.SerialConsistency
  228. qry.defaultTimestamp = s.cfg.DefaultTimestamp
  229. s.mu.RUnlock()
  230. return qry
  231. }
  232. type QueryInfo struct {
  233. Id []byte
  234. Args []ColumnInfo
  235. Rval []ColumnInfo
  236. PKeyColumns []int
  237. }
  238. // Bind generates a new query object based on the query statement passed in.
  239. // The query is automatically prepared if it has not previously been executed.
  240. // The binding callback allows the application to define which query argument
  241. // values will be marshalled as part of the query execution.
  242. // During execution, the meta data of the prepared query will be routed to the
  243. // binding callback, which is responsible for producing the query argument values.
  244. func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
  245. s.mu.RLock()
  246. qry := &Query{stmt: stmt, binding: b, cons: s.cons,
  247. session: s, pageSize: s.pageSize, trace: s.trace,
  248. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  249. s.mu.RUnlock()
  250. return qry
  251. }
  252. // Close closes all connections. The session is unusable after this
  253. // operation.
  254. func (s *Session) Close() {
  255. s.closeMu.Lock()
  256. defer s.closeMu.Unlock()
  257. if s.isClosed {
  258. return
  259. }
  260. s.isClosed = true
  261. if s.pool != nil {
  262. s.pool.Close()
  263. }
  264. if s.hostSource != nil {
  265. close(s.hostSource.closeChan)
  266. }
  267. if s.control != nil {
  268. s.control.close()
  269. }
  270. if s.nodeEvents != nil {
  271. s.nodeEvents.stop()
  272. }
  273. if s.schemaEvents != nil {
  274. s.schemaEvents.stop()
  275. }
  276. }
  277. func (s *Session) Closed() bool {
  278. s.closeMu.RLock()
  279. closed := s.isClosed
  280. s.closeMu.RUnlock()
  281. return closed
  282. }
  283. func (s *Session) executeQuery(qry *Query) *Iter {
  284. // fail fast
  285. if s.Closed() {
  286. return &Iter{err: ErrSessionClosed}
  287. }
  288. iter, err := s.executor.executeQuery(qry)
  289. if err != nil {
  290. return &Iter{err: err}
  291. }
  292. if iter == nil {
  293. panic("nil iter")
  294. }
  295. return iter
  296. }
  297. // KeyspaceMetadata returns the schema metadata for the keyspace specified.
  298. func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
  299. // fail fast
  300. if s.Closed() {
  301. return nil, ErrSessionClosed
  302. }
  303. if keyspace == "" {
  304. return nil, ErrNoKeyspace
  305. }
  306. s.mu.Lock()
  307. // lazy-init schemaDescriber
  308. if s.schemaDescriber == nil {
  309. s.schemaDescriber = newSchemaDescriber(s)
  310. }
  311. s.mu.Unlock()
  312. return s.schemaDescriber.getSchema(keyspace)
  313. }
  314. func (s *Session) getConn() *Conn {
  315. hosts := s.ring.allHosts()
  316. var conn *Conn
  317. for _, host := range hosts {
  318. if !host.IsUp() {
  319. continue
  320. }
  321. pool, ok := s.pool.getPool(host.Peer())
  322. if !ok {
  323. continue
  324. }
  325. conn = pool.Pick()
  326. if conn != nil {
  327. return conn
  328. }
  329. }
  330. return nil
  331. }
  332. // returns routing key indexes and type info
  333. func (s *Session) routingKeyInfo(ctx context.Context, stmt string) (*routingKeyInfo, error) {
  334. s.routingKeyInfoCache.mu.Lock()
  335. entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
  336. if cached {
  337. // done accessing the cache
  338. s.routingKeyInfoCache.mu.Unlock()
  339. // the entry is an inflight struct similiar to that used by
  340. // Conn to prepare statements
  341. inflight := entry.(*inflightCachedEntry)
  342. // wait for any inflight work
  343. inflight.wg.Wait()
  344. if inflight.err != nil {
  345. return nil, inflight.err
  346. }
  347. key, _ := inflight.value.(*routingKeyInfo)
  348. return key, nil
  349. }
  350. // create a new inflight entry while the data is created
  351. inflight := new(inflightCachedEntry)
  352. inflight.wg.Add(1)
  353. defer inflight.wg.Done()
  354. s.routingKeyInfoCache.lru.Add(stmt, inflight)
  355. s.routingKeyInfoCache.mu.Unlock()
  356. var (
  357. info *preparedStatment
  358. partitionKey []*ColumnMetadata
  359. )
  360. conn := s.getConn()
  361. if conn == nil {
  362. // TODO: better error?
  363. inflight.err = errors.New("gocql: unable to fetch preapred info: no connection avilable")
  364. return nil, inflight.err
  365. }
  366. // get the query info for the statement
  367. info, inflight.err = conn.prepareStatement(ctx, stmt, nil)
  368. if inflight.err != nil {
  369. // don't cache this error
  370. s.routingKeyInfoCache.Remove(stmt)
  371. return nil, inflight.err
  372. }
  373. // TODO: it would be nice to mark hosts here but as we are not using the policies
  374. // to fetch hosts we cant
  375. if info.request.colCount == 0 {
  376. // no arguments, no routing key, and no error
  377. return nil, nil
  378. }
  379. if len(info.request.pkeyColumns) > 0 {
  380. // proto v4 dont need to calculate primary key columns
  381. types := make([]TypeInfo, len(info.request.pkeyColumns))
  382. for i, col := range info.request.pkeyColumns {
  383. types[i] = info.request.columns[col].TypeInfo
  384. }
  385. routingKeyInfo := &routingKeyInfo{
  386. indexes: info.request.pkeyColumns,
  387. types: types,
  388. }
  389. inflight.value = routingKeyInfo
  390. return routingKeyInfo, nil
  391. }
  392. // get the table metadata
  393. table := info.request.columns[0].Table
  394. var keyspaceMetadata *KeyspaceMetadata
  395. keyspaceMetadata, inflight.err = s.KeyspaceMetadata(info.request.columns[0].Keyspace)
  396. if inflight.err != nil {
  397. // don't cache this error
  398. s.routingKeyInfoCache.Remove(stmt)
  399. return nil, inflight.err
  400. }
  401. tableMetadata, found := keyspaceMetadata.Tables[table]
  402. if !found {
  403. // unlikely that the statement could be prepared and the metadata for
  404. // the table couldn't be found, but this may indicate either a bug
  405. // in the metadata code, or that the table was just dropped.
  406. inflight.err = ErrNoMetadata
  407. // don't cache this error
  408. s.routingKeyInfoCache.Remove(stmt)
  409. return nil, inflight.err
  410. }
  411. partitionKey = tableMetadata.PartitionKey
  412. size := len(partitionKey)
  413. routingKeyInfo := &routingKeyInfo{
  414. indexes: make([]int, size),
  415. types: make([]TypeInfo, size),
  416. }
  417. for keyIndex, keyColumn := range partitionKey {
  418. // set an indicator for checking if the mapping is missing
  419. routingKeyInfo.indexes[keyIndex] = -1
  420. // find the column in the query info
  421. for argIndex, boundColumn := range info.request.columns {
  422. if keyColumn.Name == boundColumn.Name {
  423. // there may be many such bound columns, pick the first
  424. routingKeyInfo.indexes[keyIndex] = argIndex
  425. routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
  426. break
  427. }
  428. }
  429. if routingKeyInfo.indexes[keyIndex] == -1 {
  430. // missing a routing key column mapping
  431. // no routing key, and no error
  432. return nil, nil
  433. }
  434. }
  435. // cache this result
  436. inflight.value = routingKeyInfo
  437. return routingKeyInfo, nil
  438. }
  439. func (b *Batch) execute(conn *Conn) *Iter {
  440. return conn.executeBatch(b)
  441. }
  442. func (s *Session) executeBatch(batch *Batch) *Iter {
  443. // fail fast
  444. if s.Closed() {
  445. return &Iter{err: ErrSessionClosed}
  446. }
  447. // Prevent the execution of the batch if greater than the limit
  448. // Currently batches have a limit of 65536 queries.
  449. // https://datastax-oss.atlassian.net/browse/JAVA-229
  450. if batch.Size() > BatchSizeMaximum {
  451. return &Iter{err: ErrTooManyStmts}
  452. }
  453. iter, err := s.executor.executeQuery(batch)
  454. if err != nil {
  455. return &Iter{err: err}
  456. }
  457. return iter
  458. }
  459. // ExecuteBatch executes a batch operation and returns nil if successful
  460. // otherwise an error is returned describing the failure.
  461. func (s *Session) ExecuteBatch(batch *Batch) error {
  462. iter := s.executeBatch(batch)
  463. return iter.Close()
  464. }
  465. // ExecuteBatchCAS executes a batch operation and returns true if successful and
  466. // an iterator (to scan aditional rows if more than one conditional statement)
  467. // was sent.
  468. // Further scans on the interator must also remember to include
  469. // the applied boolean as the first argument to *Iter.Scan
  470. func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (applied bool, iter *Iter, err error) {
  471. iter = s.executeBatch(batch)
  472. if err := iter.checkErrAndNotFound(); err != nil {
  473. iter.Close()
  474. return false, nil, err
  475. }
  476. if len(iter.Columns()) > 1 {
  477. dest = append([]interface{}{&applied}, dest...)
  478. iter.Scan(dest...)
  479. } else {
  480. iter.Scan(&applied)
  481. }
  482. return applied, iter, nil
  483. }
  484. // MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,
  485. // however it accepts a map rather than a list of arguments for the initial
  486. // scan.
  487. func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
  488. iter = s.executeBatch(batch)
  489. if err := iter.checkErrAndNotFound(); err != nil {
  490. iter.Close()
  491. return false, nil, err
  492. }
  493. iter.MapScan(dest)
  494. applied = dest["[applied]"].(bool)
  495. delete(dest, "[applied]")
  496. // we usually close here, but instead of closing, just returin an error
  497. // if MapScan failed. Although Close just returns err, using Close
  498. // here might be confusing as we are not actually closing the iter
  499. return applied, iter, iter.err
  500. }
  501. func (s *Session) connect(addr string, errorHandler ConnErrorHandler, host *HostInfo) (*Conn, error) {
  502. return Connect(host, addr, s.connCfg, errorHandler, s)
  503. }
  504. // Query represents a CQL statement that can be executed.
  505. type Query struct {
  506. stmt string
  507. values []interface{}
  508. cons Consistency
  509. pageSize int
  510. routingKey []byte
  511. routingKeyBuffer []byte
  512. pageState []byte
  513. prefetch float64
  514. trace Tracer
  515. session *Session
  516. rt RetryPolicy
  517. binding func(q *QueryInfo) ([]interface{}, error)
  518. attempts int
  519. totalLatency int64
  520. serialCons SerialConsistency
  521. defaultTimestamp bool
  522. defaultTimestampValue int64
  523. disableSkipMetadata bool
  524. context context.Context
  525. disableAutoPage bool
  526. }
  527. // String implements the stringer interface.
  528. func (q Query) String() string {
  529. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  530. }
  531. //Attempts returns the number of times the query was executed.
  532. func (q *Query) Attempts() int {
  533. return q.attempts
  534. }
  535. //Latency returns the average amount of nanoseconds per attempt of the query.
  536. func (q *Query) Latency() int64 {
  537. if q.attempts > 0 {
  538. return q.totalLatency / int64(q.attempts)
  539. }
  540. return 0
  541. }
  542. // Consistency sets the consistency level for this query. If no consistency
  543. // level have been set, the default consistency level of the cluster
  544. // is used.
  545. func (q *Query) Consistency(c Consistency) *Query {
  546. q.cons = c
  547. return q
  548. }
  549. // GetConsistency returns the currently configured consistency level for
  550. // the query.
  551. func (q *Query) GetConsistency() Consistency {
  552. return q.cons
  553. }
  554. // Trace enables tracing of this query. Look at the documentation of the
  555. // Tracer interface to learn more about tracing.
  556. func (q *Query) Trace(trace Tracer) *Query {
  557. q.trace = trace
  558. return q
  559. }
  560. // PageSize will tell the iterator to fetch the result in pages of size n.
  561. // This is useful for iterating over large result sets, but setting the
  562. // page size too low might decrease the performance. This feature is only
  563. // available in Cassandra 2 and onwards.
  564. func (q *Query) PageSize(n int) *Query {
  565. q.pageSize = n
  566. return q
  567. }
  568. // DefaultTimestamp will enable the with default timestamp flag on the query.
  569. // If enable, this will replace the server side assigned
  570. // timestamp as default timestamp. Note that a timestamp in the query itself
  571. // will still override this timestamp. This is entirely optional.
  572. //
  573. // Only available on protocol >= 3
  574. func (q *Query) DefaultTimestamp(enable bool) *Query {
  575. q.defaultTimestamp = enable
  576. return q
  577. }
  578. // WithTimestamp will enable the with default timestamp flag on the query
  579. // like DefaultTimestamp does. But also allows to define value for timestamp.
  580. // It works the same way as USING TIMESTAMP in the query itself, but
  581. // should not break prepared query optimization
  582. //
  583. // Only available on protocol >= 3
  584. func (q *Query) WithTimestamp(timestamp int64) *Query {
  585. q.DefaultTimestamp(true)
  586. q.defaultTimestampValue = timestamp
  587. return q
  588. }
  589. // RoutingKey sets the routing key to use when a token aware connection
  590. // pool is used to optimize the routing of this query.
  591. func (q *Query) RoutingKey(routingKey []byte) *Query {
  592. q.routingKey = routingKey
  593. return q
  594. }
  595. // WithContext will set the context to use during a query, it will be used to
  596. // timeout when waiting for responses from Cassandra.
  597. func (q *Query) WithContext(ctx context.Context) *Query {
  598. q.context = ctx
  599. return q
  600. }
  601. func (q *Query) execute(conn *Conn) *Iter {
  602. return conn.executeQuery(q)
  603. }
  604. func (q *Query) attempt(d time.Duration) {
  605. q.attempts++
  606. q.totalLatency += d.Nanoseconds()
  607. // TODO: track latencies per host and things as well instead of just total
  608. }
  609. func (q *Query) retryPolicy() RetryPolicy {
  610. return q.rt
  611. }
  612. // GetRoutingKey gets the routing key to use for routing this query. If
  613. // a routing key has not been explicitly set, then the routing key will
  614. // be constructed if possible using the keyspace's schema and the query
  615. // info for this query statement. If the routing key cannot be determined
  616. // then nil will be returned with no error. On any error condition,
  617. // an error description will be returned.
  618. func (q *Query) GetRoutingKey() ([]byte, error) {
  619. if q.routingKey != nil {
  620. return q.routingKey, nil
  621. } else if q.binding != nil && len(q.values) == 0 {
  622. // If this query was created using session.Bind we wont have the query
  623. // values yet, so we have to pass down to the next policy.
  624. // TODO: Remove this and handle this case
  625. return nil, nil
  626. }
  627. // try to determine the routing key
  628. routingKeyInfo, err := q.session.routingKeyInfo(q.context, q.stmt)
  629. if err != nil {
  630. return nil, err
  631. }
  632. if routingKeyInfo == nil {
  633. return nil, nil
  634. }
  635. if len(routingKeyInfo.indexes) == 1 {
  636. // single column routing key
  637. routingKey, err := Marshal(
  638. routingKeyInfo.types[0],
  639. q.values[routingKeyInfo.indexes[0]],
  640. )
  641. if err != nil {
  642. return nil, err
  643. }
  644. return routingKey, nil
  645. }
  646. // We allocate that buffer only once, so that further re-bind/exec of the
  647. // same query don't allocate more memory.
  648. if q.routingKeyBuffer == nil {
  649. q.routingKeyBuffer = make([]byte, 0, 256)
  650. }
  651. // composite routing key
  652. buf := bytes.NewBuffer(q.routingKeyBuffer)
  653. for i := range routingKeyInfo.indexes {
  654. encoded, err := Marshal(
  655. routingKeyInfo.types[i],
  656. q.values[routingKeyInfo.indexes[i]],
  657. )
  658. if err != nil {
  659. return nil, err
  660. }
  661. lenBuf := []byte{0x00, 0x00}
  662. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  663. buf.Write(lenBuf)
  664. buf.Write(encoded)
  665. buf.WriteByte(0x00)
  666. }
  667. routingKey := buf.Bytes()
  668. return routingKey, nil
  669. }
  670. func (q *Query) shouldPrepare() bool {
  671. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  672. return unicode.IsSpace(r) || r == ';'
  673. }), unicode.IsSpace)
  674. var stmtType string
  675. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  676. stmtType = strings.ToLower(stmt[:n])
  677. }
  678. if stmtType == "begin" {
  679. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  680. stmtType = strings.ToLower(stmt[n+1:])
  681. }
  682. }
  683. switch stmtType {
  684. case "select", "insert", "update", "delete", "batch":
  685. return true
  686. }
  687. return false
  688. }
  689. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  690. // there are only p*pageSize rows remaining, the next page will be requested
  691. // automatically.
  692. func (q *Query) Prefetch(p float64) *Query {
  693. q.prefetch = p
  694. return q
  695. }
  696. // RetryPolicy sets the policy to use when retrying the query.
  697. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  698. q.rt = r
  699. return q
  700. }
  701. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  702. // to an existing query instance.
  703. func (q *Query) Bind(v ...interface{}) *Query {
  704. q.values = v
  705. return q
  706. }
  707. // SerialConsistency sets the consistency level for the
  708. // serial phase of conditional updates. That consistency can only be
  709. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  710. // SERIAL. This option will be ignored for anything else that a
  711. // conditional update/insert.
  712. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  713. q.serialCons = cons
  714. return q
  715. }
  716. // PageState sets the paging state for the query to resume paging from a specific
  717. // point in time. Setting this will disable to query paging for this query, and
  718. // must be used for all subsequent pages.
  719. func (q *Query) PageState(state []byte) *Query {
  720. q.pageState = state
  721. q.disableAutoPage = true
  722. return q
  723. }
  724. // NoSkipMetadata will override the internal result metadata cache so that the driver does not
  725. // send skip_metadata for queries, this means that the result will always contain
  726. // the metadata to parse the rows and will not reuse the metadata from the prepared
  727. // staement. This should only be used to work around cassandra bugs, such as when using
  728. // CAS operations which do not end in Cas.
  729. //
  730. // See https://issues.apache.org/jira/browse/CASSANDRA-11099
  731. // https://github.com/gocql/gocql/issues/612
  732. func (q *Query) NoSkipMetadata() *Query {
  733. q.disableSkipMetadata = true
  734. return q
  735. }
  736. // Exec executes the query without returning any rows.
  737. func (q *Query) Exec() error {
  738. return q.Iter().Close()
  739. }
  740. func isUseStatement(stmt string) bool {
  741. if len(stmt) < 3 {
  742. return false
  743. }
  744. return strings.ToLower(stmt[0:3]) == "use"
  745. }
  746. // Iter executes the query and returns an iterator capable of iterating
  747. // over all results.
  748. func (q *Query) Iter() *Iter {
  749. if isUseStatement(q.stmt) {
  750. return &Iter{err: ErrUseStmt}
  751. }
  752. return q.session.executeQuery(q)
  753. }
  754. // MapScan executes the query, copies the columns of the first selected
  755. // row into the map pointed at by m and discards the rest. If no rows
  756. // were selected, ErrNotFound is returned.
  757. func (q *Query) MapScan(m map[string]interface{}) error {
  758. iter := q.Iter()
  759. if err := iter.checkErrAndNotFound(); err != nil {
  760. return err
  761. }
  762. iter.MapScan(m)
  763. return iter.Close()
  764. }
  765. // Scan executes the query, copies the columns of the first selected
  766. // row into the values pointed at by dest and discards the rest. If no rows
  767. // were selected, ErrNotFound is returned.
  768. func (q *Query) Scan(dest ...interface{}) error {
  769. iter := q.Iter()
  770. if err := iter.checkErrAndNotFound(); err != nil {
  771. return err
  772. }
  773. iter.Scan(dest...)
  774. return iter.Close()
  775. }
  776. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  777. // statement containing an IF clause). If the transaction fails because
  778. // the existing values did not match, the previous values will be stored
  779. // in dest.
  780. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  781. q.disableSkipMetadata = true
  782. iter := q.Iter()
  783. if err := iter.checkErrAndNotFound(); err != nil {
  784. return false, err
  785. }
  786. if len(iter.Columns()) > 1 {
  787. dest = append([]interface{}{&applied}, dest...)
  788. iter.Scan(dest...)
  789. } else {
  790. iter.Scan(&applied)
  791. }
  792. return applied, iter.Close()
  793. }
  794. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  795. // statement containing an IF clause). If the transaction fails because
  796. // the existing values did not match, the previous values will be stored
  797. // in dest map.
  798. //
  799. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  800. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  801. // column mismatching. MapScanCAS is added to capture them safely.
  802. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  803. q.disableSkipMetadata = true
  804. iter := q.Iter()
  805. if err := iter.checkErrAndNotFound(); err != nil {
  806. return false, err
  807. }
  808. iter.MapScan(dest)
  809. applied = dest["[applied]"].(bool)
  810. delete(dest, "[applied]")
  811. return applied, iter.Close()
  812. }
  813. // Release releases a query back into a pool of queries. Released Queries
  814. // cannot be reused.
  815. //
  816. // Example:
  817. // qry := session.Query("SELECT * FROM my_table")
  818. // qry.Exec()
  819. // qry.Release()
  820. func (q *Query) Release() {
  821. if q == nil || q.session == nil || q.session.queryPool == nil {
  822. return
  823. }
  824. pool := q.session.queryPool
  825. pool.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