session.go 39 KB

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