session.go 39 KB

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