session.go 42 KB

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