session.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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. q.reset()
  826. pool.Put(q)
  827. }
  828. // reset zeroes out all fields of a query so that it can be safely pooled.
  829. func (q *Query) reset() {
  830. q.stmt = ""
  831. q.values = nil
  832. q.cons = 0
  833. q.pageSize = 0
  834. q.routingKey = nil
  835. q.routingKeyBuffer = nil
  836. q.pageState = nil
  837. q.prefetch = 0
  838. q.trace = nil
  839. q.session = nil
  840. q.rt = nil
  841. q.binding = nil
  842. q.attempts = 0
  843. q.totalLatency = 0
  844. q.serialCons = 0
  845. q.defaultTimestamp = false
  846. q.disableSkipMetadata = false
  847. q.disableAutoPage = false
  848. }
  849. // Iter represents an iterator that can be used to iterate over all rows that
  850. // were returned by a query. The iterator might send additional queries to the
  851. // database during the iteration if paging was enabled.
  852. type Iter struct {
  853. err error
  854. pos int
  855. meta resultMetadata
  856. numRows int
  857. next *nextIter
  858. host *HostInfo
  859. framer *framer
  860. closed int32
  861. }
  862. // Host returns the host which the query was sent to.
  863. func (iter *Iter) Host() *HostInfo {
  864. return iter.host
  865. }
  866. // Columns returns the name and type of the selected columns.
  867. func (iter *Iter) Columns() []ColumnInfo {
  868. return iter.meta.columns
  869. }
  870. func (iter *Iter) readColumn() ([]byte, error) {
  871. return iter.framer.readBytesInternal()
  872. }
  873. // Scan consumes the next row of the iterator and copies the columns of the
  874. // current row into the values pointed at by dest. Use nil as a dest value
  875. // to skip the corresponding column. Scan might send additional queries
  876. // to the database to retrieve the next set of rows if paging was enabled.
  877. //
  878. // Scan returns true if the row was successfully unmarshaled or false if the
  879. // end of the result set was reached or if an error occurred. Close should
  880. // be called afterwards to retrieve any potential errors.
  881. func (iter *Iter) Scan(dest ...interface{}) bool {
  882. if iter.err != nil {
  883. return false
  884. }
  885. if iter.pos >= iter.numRows {
  886. if iter.next != nil {
  887. *iter = *iter.next.fetch()
  888. return iter.Scan(dest...)
  889. }
  890. return false
  891. }
  892. if iter.next != nil && iter.pos == iter.next.pos {
  893. go iter.next.fetch()
  894. }
  895. // currently only support scanning into an expand tuple, such that its the same
  896. // as scanning in more values from a single column
  897. if len(dest) != iter.meta.actualColCount {
  898. iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  899. return false
  900. }
  901. // i is the current position in dest, could posible replace it and just use
  902. // slices of dest
  903. i := 0
  904. for c := range iter.meta.columns {
  905. col := &iter.meta.columns[c]
  906. colBytes, err := iter.readColumn()
  907. if err != nil {
  908. iter.err = err
  909. return false
  910. }
  911. if dest[i] == nil {
  912. i++
  913. continue
  914. }
  915. switch col.TypeInfo.Type() {
  916. case TypeTuple:
  917. // this will panic, actually a bug, please report
  918. tuple := col.TypeInfo.(TupleTypeInfo)
  919. count := len(tuple.Elems)
  920. // here we pass in a slice of the struct which has the number number of
  921. // values as elements in the tuple
  922. iter.err = Unmarshal(col.TypeInfo, colBytes, dest[i:i+count])
  923. i += count
  924. default:
  925. iter.err = Unmarshal(col.TypeInfo, colBytes, dest[i])
  926. i++
  927. }
  928. if iter.err != nil {
  929. return false
  930. }
  931. }
  932. iter.pos++
  933. return true
  934. }
  935. // GetCustomPayload returns any parsed custom payload results if given in the
  936. // response from Cassandra. Note that the result is not a copy.
  937. //
  938. // This additional feature of CQL Protocol v4
  939. // allows additional results and query information to be returned by
  940. // custom QueryHandlers running in your C* cluster.
  941. // See https://datastax.github.io/java-driver/manual/custom_payloads/
  942. func (iter *Iter) GetCustomPayload() map[string][]byte {
  943. return iter.framer.header.customPayload
  944. }
  945. // Close closes the iterator and returns any errors that happened during
  946. // the query or the iteration.
  947. func (iter *Iter) Close() error {
  948. if atomic.CompareAndSwapInt32(&iter.closed, 0, 1) {
  949. if iter.framer != nil {
  950. framerPool.Put(iter.framer)
  951. iter.framer = nil
  952. }
  953. }
  954. return iter.err
  955. }
  956. // WillSwitchPage detects if iterator reached end of current page
  957. // and the next page is available.
  958. func (iter *Iter) WillSwitchPage() bool {
  959. return iter.pos >= iter.numRows && iter.next != nil
  960. }
  961. // checkErrAndNotFound handle error and NotFound in one method.
  962. func (iter *Iter) checkErrAndNotFound() error {
  963. if iter.err != nil {
  964. return iter.err
  965. } else if iter.numRows == 0 {
  966. return ErrNotFound
  967. }
  968. return nil
  969. }
  970. // PageState return the current paging state for a query which can be used for
  971. // subsequent quries to resume paging this point.
  972. func (iter *Iter) PageState() []byte {
  973. return iter.meta.pagingState
  974. }
  975. // NumRows returns the number of rows in this pagination, it will update when new
  976. // pages are fetcehd, it is not the value of the total number of rows this iter
  977. // will return unless there is only a single page returned.
  978. func (iter *Iter) NumRows() int {
  979. return iter.numRows
  980. }
  981. type nextIter struct {
  982. qry Query
  983. pos int
  984. once sync.Once
  985. next *Iter
  986. }
  987. func (n *nextIter) fetch() *Iter {
  988. n.once.Do(func() {
  989. n.next = n.qry.session.executeQuery(&n.qry)
  990. })
  991. return n.next
  992. }
  993. type Batch struct {
  994. Type BatchType
  995. Entries []BatchEntry
  996. Cons Consistency
  997. rt RetryPolicy
  998. attempts int
  999. totalLatency int64
  1000. serialCons SerialConsistency
  1001. defaultTimestamp bool
  1002. context context.Context
  1003. }
  1004. // NewBatch creates a new batch operation without defaults from the cluster
  1005. func NewBatch(typ BatchType) *Batch {
  1006. return &Batch{Type: typ}
  1007. }
  1008. // NewBatch creates a new batch operation using defaults defined in the cluster
  1009. func (s *Session) NewBatch(typ BatchType) *Batch {
  1010. s.mu.RLock()
  1011. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  1012. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  1013. s.mu.RUnlock()
  1014. return batch
  1015. }
  1016. // Attempts returns the number of attempts made to execute the batch.
  1017. func (b *Batch) Attempts() int {
  1018. return b.attempts
  1019. }
  1020. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  1021. func (b *Batch) Latency() int64 {
  1022. if b.attempts > 0 {
  1023. return b.totalLatency / int64(b.attempts)
  1024. }
  1025. return 0
  1026. }
  1027. // GetConsistency returns the currently configured consistency level for the batch
  1028. // operation.
  1029. func (b *Batch) GetConsistency() Consistency {
  1030. return b.Cons
  1031. }
  1032. // Query adds the query to the batch operation
  1033. func (b *Batch) Query(stmt string, args ...interface{}) {
  1034. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  1035. }
  1036. // Bind adds the query to the batch operation and correlates it with a binding callback
  1037. // that will be invoked when the batch is executed. The binding callback allows the application
  1038. // to define which query argument values will be marshalled as part of the batch execution.
  1039. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  1040. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  1041. }
  1042. func (b *Batch) retryPolicy() RetryPolicy {
  1043. return b.rt
  1044. }
  1045. // RetryPolicy sets the retry policy to use when executing the batch operation
  1046. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  1047. b.rt = r
  1048. return b
  1049. }
  1050. // WithContext will set the context to use during a query, it will be used to
  1051. // timeout when waiting for responses from Cassandra.
  1052. func (b *Batch) WithContext(ctx context.Context) *Batch {
  1053. b.context = ctx
  1054. return b
  1055. }
  1056. // Size returns the number of batch statements to be executed by the batch operation.
  1057. func (b *Batch) Size() int {
  1058. return len(b.Entries)
  1059. }
  1060. // SerialConsistency sets the consistency level for the
  1061. // serial phase of conditional updates. That consistency can only be
  1062. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  1063. // SERIAL. This option will be ignored for anything else that a
  1064. // conditional update/insert.
  1065. //
  1066. // Only available for protocol 3 and above
  1067. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  1068. b.serialCons = cons
  1069. return b
  1070. }
  1071. // DefaultTimestamp will enable the with default timestamp flag on the query.
  1072. // If enable, this will replace the server side assigned
  1073. // timestamp as default timestamp. Note that a timestamp in the query itself
  1074. // will still override this timestamp. This is entirely optional.
  1075. //
  1076. // Only available on protocol >= 3
  1077. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  1078. b.defaultTimestamp = enable
  1079. return b
  1080. }
  1081. func (b *Batch) attempt(d time.Duration) {
  1082. b.attempts++
  1083. b.totalLatency += d.Nanoseconds()
  1084. // TODO: track latencies per host and things as well instead of just total
  1085. }
  1086. func (b *Batch) GetRoutingKey() ([]byte, error) {
  1087. // TODO: use the first statement in the batch as the routing key?
  1088. return nil, nil
  1089. }
  1090. type BatchType byte
  1091. const (
  1092. LoggedBatch BatchType = 0
  1093. UnloggedBatch BatchType = 1
  1094. CounterBatch BatchType = 2
  1095. )
  1096. type BatchEntry struct {
  1097. Stmt string
  1098. Args []interface{}
  1099. binding func(q *QueryInfo) ([]interface{}, error)
  1100. }
  1101. type ColumnInfo struct {
  1102. Keyspace string
  1103. Table string
  1104. Name string
  1105. TypeInfo TypeInfo
  1106. }
  1107. func (c ColumnInfo) String() string {
  1108. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  1109. }
  1110. // routing key indexes LRU cache
  1111. type routingKeyInfoLRU struct {
  1112. lru *lru.Cache
  1113. mu sync.Mutex
  1114. }
  1115. type routingKeyInfo struct {
  1116. indexes []int
  1117. types []TypeInfo
  1118. }
  1119. func (r *routingKeyInfo) String() string {
  1120. return fmt.Sprintf("routing key index=%v types=%v", r.indexes, r.types)
  1121. }
  1122. func (r *routingKeyInfoLRU) Remove(key string) {
  1123. r.mu.Lock()
  1124. r.lru.Remove(key)
  1125. r.mu.Unlock()
  1126. }
  1127. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  1128. //the new max is lower than the previous value. Not concurrency safe.
  1129. func (r *routingKeyInfoLRU) Max(max int) {
  1130. r.mu.Lock()
  1131. for r.lru.Len() > max {
  1132. r.lru.RemoveOldest()
  1133. }
  1134. r.lru.MaxEntries = max
  1135. r.mu.Unlock()
  1136. }
  1137. type inflightCachedEntry struct {
  1138. wg sync.WaitGroup
  1139. err error
  1140. value interface{}
  1141. }
  1142. // Tracer is the interface implemented by query tracers. Tracers have the
  1143. // ability to obtain a detailed event log of all events that happened during
  1144. // the execution of a query from Cassandra. Gathering this information might
  1145. // be essential for debugging and optimizing queries, but this feature should
  1146. // not be used on production systems with very high load.
  1147. type Tracer interface {
  1148. Trace(traceId []byte)
  1149. }
  1150. type traceWriter struct {
  1151. session *Session
  1152. w io.Writer
  1153. mu sync.Mutex
  1154. }
  1155. // NewTraceWriter returns a simple Tracer implementation that outputs
  1156. // the event log in a textual format.
  1157. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  1158. return &traceWriter{session: session, w: w}
  1159. }
  1160. func (t *traceWriter) Trace(traceId []byte) {
  1161. var (
  1162. coordinator string
  1163. duration int
  1164. )
  1165. iter := t.session.control.query(`SELECT coordinator, duration
  1166. FROM system_traces.sessions
  1167. WHERE session_id = ?`, traceId)
  1168. iter.Scan(&coordinator, &duration)
  1169. if err := iter.Close(); err != nil {
  1170. t.mu.Lock()
  1171. fmt.Fprintln(t.w, "Error:", err)
  1172. t.mu.Unlock()
  1173. return
  1174. }
  1175. var (
  1176. timestamp time.Time
  1177. activity string
  1178. source string
  1179. elapsed int
  1180. )
  1181. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1182. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1183. t.mu.Lock()
  1184. defer t.mu.Unlock()
  1185. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1186. FROM system_traces.events
  1187. WHERE session_id = ?`, traceId)
  1188. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1189. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1190. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1191. }
  1192. if err := iter.Close(); err != nil {
  1193. fmt.Fprintln(t.w, "Error:", err)
  1194. }
  1195. }
  1196. type Error struct {
  1197. Code int
  1198. Message string
  1199. }
  1200. func (e Error) Error() string {
  1201. return e.Message
  1202. }
  1203. var (
  1204. ErrNotFound = errors.New("not found")
  1205. ErrUnavailable = errors.New("unavailable")
  1206. ErrUnsupported = errors.New("feature not supported")
  1207. ErrTooManyStmts = errors.New("too many statements")
  1208. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  1209. ErrSessionClosed = errors.New("session has been closed")
  1210. ErrNoConnections = errors.New("qocql: no hosts available in the pool")
  1211. ErrNoKeyspace = errors.New("no keyspace provided")
  1212. ErrNoMetadata = errors.New("no metadata available")
  1213. )
  1214. type ErrProtocol struct{ error }
  1215. func NewErrProtocol(format string, args ...interface{}) error {
  1216. return ErrProtocol{fmt.Errorf(format, args...)}
  1217. }
  1218. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1219. // This limit is set by cassandra and could change in the future.
  1220. const BatchSizeMaximum = 65535