session.go 42 KB

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