session.go 39 KB

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