session.go 42 KB

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