session.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  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. "context"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "net"
  13. "strings"
  14. "sync"
  15. "sync/atomic"
  16. "time"
  17. "unicode"
  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. var hosts []*HostInfo
  64. for _, hostport := range addrs {
  65. host, err := hostInfo(hostport, defaultPort)
  66. if err != nil {
  67. // Try other hosts if unable to resolve DNS name
  68. if _, ok := err.(*net.DNSError); ok {
  69. Logger.Printf("gocql: dns error: %v\n", err)
  70. continue
  71. }
  72. return nil, err
  73. }
  74. hosts = append(hosts, host)
  75. }
  76. if len(hosts) == 0 {
  77. return nil, errors.New("failed to resolve any of the provided hostnames")
  78. }
  79. return hosts, nil
  80. }
  81. // NewSession wraps an existing Node.
  82. func NewSession(cfg ClusterConfig) (*Session, error) {
  83. // Check that hosts in the ClusterConfig is not empty
  84. if len(cfg.Hosts) < 1 {
  85. return nil, ErrNoHosts
  86. }
  87. s := &Session{
  88. cons: cfg.Consistency,
  89. prefetch: 0.25,
  90. cfg: cfg,
  91. pageSize: cfg.PageSize,
  92. stmtsLRU: &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
  93. quit: make(chan struct{}),
  94. }
  95. s.nodeEvents = newEventDebouncer("NodeEvents", s.handleNodeEvent)
  96. s.schemaEvents = newEventDebouncer("SchemaEvents", s.handleSchemaEvent)
  97. s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
  98. s.hostSource = &ringDescriber{
  99. session: s,
  100. }
  101. if cfg.PoolConfig.HostSelectionPolicy == nil {
  102. cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
  103. }
  104. s.pool = cfg.PoolConfig.buildPool(s)
  105. s.policy = cfg.PoolConfig.HostSelectionPolicy
  106. s.executor = &queryExecutor{
  107. pool: s.pool,
  108. policy: cfg.PoolConfig.HostSelectionPolicy,
  109. }
  110. //Check the TLS Config before trying to connect to anything external
  111. connCfg, err := connConfig(&s.cfg)
  112. if err != nil {
  113. //TODO: Return a typed error
  114. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  115. }
  116. s.connCfg = connCfg
  117. if err := s.init(); err != nil {
  118. s.Close()
  119. if err == ErrNoConnectionsStarted {
  120. //This error used to be generated inside NewSession & returned directly
  121. //Forward it on up to be backwards compatible
  122. return nil, ErrNoConnectionsStarted
  123. } else {
  124. // TODO(zariel): dont wrap this error in fmt.Errorf, return a typed error
  125. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  126. }
  127. }
  128. return s, nil
  129. }
  130. func (s *Session) init() error {
  131. hosts, err := addrsToHosts(s.cfg.Hosts, s.cfg.Port)
  132. if err != nil {
  133. return err
  134. }
  135. if !s.cfg.disableControlConn {
  136. s.control = createControlConn(s)
  137. if s.cfg.ProtoVersion == 0 {
  138. proto, err := s.control.discoverProtocol(hosts)
  139. if err != nil {
  140. return fmt.Errorf("unable to discover protocol version: %v", err)
  141. } else if proto == 0 {
  142. return errors.New("unable to discovery protocol version")
  143. }
  144. // TODO(zariel): we really only need this in 1 place
  145. s.cfg.ProtoVersion = proto
  146. s.connCfg.ProtoVersion = proto
  147. }
  148. if err := s.control.connect(hosts); err != nil {
  149. return err
  150. }
  151. if !s.cfg.DisableInitialHostLookup {
  152. var partitioner string
  153. hosts, partitioner, err = s.hostSource.GetHosts()
  154. if err != nil {
  155. return err
  156. }
  157. s.policy.SetPartitioner(partitioner)
  158. }
  159. }
  160. for _, host := range hosts {
  161. host = s.ring.addOrUpdate(host)
  162. s.handleNodeUp(host.ConnectAddress(), host.Port(), false)
  163. }
  164. // TODO(zariel): we probably dont need this any more as we verify that we
  165. // can connect to one of the endpoints supplied by using the control conn.
  166. // See if there are any connections in the pool
  167. if s.cfg.ReconnectInterval > 0 {
  168. go s.reconnectDownedHosts(s.cfg.ReconnectInterval)
  169. }
  170. // If we disable the initial host lookup, we need to still check if the
  171. // cluster is using the newer system schema or not... however, if control
  172. // connection is disable, we really have no choice, so we just make our
  173. // best guess...
  174. if !s.cfg.disableControlConn && s.cfg.DisableInitialHostLookup {
  175. newer, _ := checkSystemSchema(s.control)
  176. s.useSystemSchema = newer
  177. } else {
  178. s.useSystemSchema = hosts[0].Version().Major >= 3
  179. }
  180. if s.pool.Size() == 0 {
  181. return ErrNoConnectionsStarted
  182. }
  183. return nil
  184. }
  185. func (s *Session) reconnectDownedHosts(intv time.Duration) {
  186. reconnectTicker := time.NewTicker(intv)
  187. defer reconnectTicker.Stop()
  188. for {
  189. select {
  190. case <-reconnectTicker.C:
  191. hosts := s.ring.allHosts()
  192. // Print session.ring for debug.
  193. if gocqlDebug {
  194. buf := bytes.NewBufferString("Session.ring:")
  195. for _, h := range hosts {
  196. buf.WriteString("[" + h.ConnectAddress().String() + ":" + h.State().String() + "]")
  197. }
  198. Logger.Println(buf.String())
  199. }
  200. for _, h := range hosts {
  201. if h.IsUp() {
  202. continue
  203. }
  204. s.handleNodeUp(h.ConnectAddress(), h.Port(), true)
  205. }
  206. case <-s.quit:
  207. return
  208. }
  209. }
  210. }
  211. // SetConsistency sets the default consistency level for this session. This
  212. // setting can also be changed on a per-query basis and the default value
  213. // is Quorum.
  214. func (s *Session) SetConsistency(cons Consistency) {
  215. s.mu.Lock()
  216. s.cons = cons
  217. s.mu.Unlock()
  218. }
  219. // SetPageSize sets the default page size for this session. A value <= 0 will
  220. // disable paging. This setting can also be changed on a per-query basis.
  221. func (s *Session) SetPageSize(n int) {
  222. s.mu.Lock()
  223. s.pageSize = n
  224. s.mu.Unlock()
  225. }
  226. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  227. // there are only p*pageSize rows remaining, the next page will be requested
  228. // automatically. This value can also be changed on a per-query basis and
  229. // the default value is 0.25.
  230. func (s *Session) SetPrefetch(p float64) {
  231. s.mu.Lock()
  232. s.prefetch = p
  233. s.mu.Unlock()
  234. }
  235. // SetTrace sets the default tracer for this session. This setting can also
  236. // be changed on a per-query basis.
  237. func (s *Session) SetTrace(trace Tracer) {
  238. s.mu.Lock()
  239. s.trace = trace
  240. s.mu.Unlock()
  241. }
  242. // Query generates a new query object for interacting with the database.
  243. // Further details of the query may be tweaked using the resulting query
  244. // value before the query is executed. Query is automatically prepared
  245. // if it has not previously been executed.
  246. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  247. s.mu.RLock()
  248. qry := queryPool.Get().(*Query)
  249. qry.stmt = stmt
  250. qry.values = values
  251. qry.cons = s.cons
  252. qry.session = s
  253. qry.pageSize = s.pageSize
  254. qry.trace = s.trace
  255. qry.prefetch = s.prefetch
  256. qry.rt = s.cfg.RetryPolicy
  257. qry.serialCons = s.cfg.SerialConsistency
  258. qry.defaultTimestamp = s.cfg.DefaultTimestamp
  259. s.mu.RUnlock()
  260. return qry
  261. }
  262. type QueryInfo struct {
  263. Id []byte
  264. Args []ColumnInfo
  265. Rval []ColumnInfo
  266. PKeyColumns []int
  267. }
  268. // Bind generates a new query object based on the query statement passed in.
  269. // The query is automatically prepared if it has not previously been executed.
  270. // The binding callback allows the application to define which query argument
  271. // values will be marshalled as part of the query execution.
  272. // During execution, the meta data of the prepared query will be routed to the
  273. // binding callback, which is responsible for producing the query argument values.
  274. func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
  275. s.mu.RLock()
  276. qry := &Query{stmt: stmt, binding: b, cons: s.cons,
  277. session: s, pageSize: s.pageSize, trace: s.trace,
  278. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  279. s.mu.RUnlock()
  280. return qry
  281. }
  282. // Close closes all connections. The session is unusable after this
  283. // operation.
  284. func (s *Session) Close() {
  285. s.closeMu.Lock()
  286. defer s.closeMu.Unlock()
  287. if s.isClosed {
  288. return
  289. }
  290. s.isClosed = true
  291. if s.pool != nil {
  292. s.pool.Close()
  293. }
  294. if s.control != nil {
  295. s.control.close()
  296. }
  297. if s.nodeEvents != nil {
  298. s.nodeEvents.stop()
  299. }
  300. if s.schemaEvents != nil {
  301. s.schemaEvents.stop()
  302. }
  303. if s.quit != nil {
  304. close(s.quit)
  305. }
  306. }
  307. func (s *Session) Closed() bool {
  308. s.closeMu.RLock()
  309. closed := s.isClosed
  310. s.closeMu.RUnlock()
  311. return closed
  312. }
  313. func (s *Session) executeQuery(qry *Query) *Iter {
  314. // fail fast
  315. if s.Closed() {
  316. return &Iter{err: ErrSessionClosed}
  317. }
  318. iter, err := s.executor.executeQuery(qry)
  319. if err != nil {
  320. return &Iter{err: err}
  321. }
  322. if iter == nil {
  323. panic("nil iter")
  324. }
  325. return iter
  326. }
  327. // KeyspaceMetadata returns the schema metadata for the keyspace specified. Returns an error if the keyspace does not exist.
  328. func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
  329. // fail fast
  330. if s.Closed() {
  331. return nil, ErrSessionClosed
  332. }
  333. if keyspace == "" {
  334. return nil, ErrNoKeyspace
  335. }
  336. s.mu.Lock()
  337. // lazy-init schemaDescriber
  338. if s.schemaDescriber == nil {
  339. s.schemaDescriber = newSchemaDescriber(s)
  340. }
  341. s.mu.Unlock()
  342. return s.schemaDescriber.getSchema(keyspace)
  343. }
  344. func (s *Session) getConn() *Conn {
  345. hosts := s.ring.allHosts()
  346. var conn *Conn
  347. for _, host := range hosts {
  348. if !host.IsUp() {
  349. continue
  350. }
  351. pool, ok := s.pool.getPool(host)
  352. if !ok {
  353. continue
  354. }
  355. conn = pool.Pick()
  356. if conn != nil {
  357. return conn
  358. }
  359. }
  360. return nil
  361. }
  362. // returns routing key indexes and type info
  363. func (s *Session) routingKeyInfo(ctx context.Context, stmt string) (*routingKeyInfo, error) {
  364. s.routingKeyInfoCache.mu.Lock()
  365. entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
  366. if cached {
  367. // done accessing the cache
  368. s.routingKeyInfoCache.mu.Unlock()
  369. // the entry is an inflight struct similar to that used by
  370. // Conn to prepare statements
  371. inflight := entry.(*inflightCachedEntry)
  372. // wait for any inflight work
  373. inflight.wg.Wait()
  374. if inflight.err != nil {
  375. return nil, inflight.err
  376. }
  377. key, _ := inflight.value.(*routingKeyInfo)
  378. return key, nil
  379. }
  380. // create a new inflight entry while the data is created
  381. inflight := new(inflightCachedEntry)
  382. inflight.wg.Add(1)
  383. defer inflight.wg.Done()
  384. s.routingKeyInfoCache.lru.Add(stmt, inflight)
  385. s.routingKeyInfoCache.mu.Unlock()
  386. var (
  387. info *preparedStatment
  388. partitionKey []*ColumnMetadata
  389. )
  390. conn := s.getConn()
  391. if conn == nil {
  392. // TODO: better error?
  393. inflight.err = errors.New("gocql: unable to fetch prepared info: no connection available")
  394. return nil, inflight.err
  395. }
  396. // get the query info for the statement
  397. info, inflight.err = conn.prepareStatement(ctx, stmt, nil)
  398. if inflight.err != nil {
  399. // don't cache this error
  400. s.routingKeyInfoCache.Remove(stmt)
  401. return nil, inflight.err
  402. }
  403. // TODO: it would be nice to mark hosts here but as we are not using the policies
  404. // to fetch hosts we cant
  405. if info.request.colCount == 0 {
  406. // no arguments, no routing key, and no error
  407. return nil, nil
  408. }
  409. if len(info.request.pkeyColumns) > 0 {
  410. // proto v4 dont need to calculate primary key columns
  411. types := make([]TypeInfo, len(info.request.pkeyColumns))
  412. for i, col := range info.request.pkeyColumns {
  413. types[i] = info.request.columns[col].TypeInfo
  414. }
  415. routingKeyInfo := &routingKeyInfo{
  416. indexes: info.request.pkeyColumns,
  417. types: types,
  418. }
  419. inflight.value = routingKeyInfo
  420. return routingKeyInfo, nil
  421. }
  422. // get the table metadata
  423. table := info.request.columns[0].Table
  424. var keyspaceMetadata *KeyspaceMetadata
  425. keyspaceMetadata, inflight.err = s.KeyspaceMetadata(info.request.columns[0].Keyspace)
  426. if inflight.err != nil {
  427. // don't cache this error
  428. s.routingKeyInfoCache.Remove(stmt)
  429. return nil, inflight.err
  430. }
  431. tableMetadata, found := keyspaceMetadata.Tables[table]
  432. if !found {
  433. // unlikely that the statement could be prepared and the metadata for
  434. // the table couldn't be found, but this may indicate either a bug
  435. // in the metadata code, or that the table was just dropped.
  436. inflight.err = ErrNoMetadata
  437. // don't cache this error
  438. s.routingKeyInfoCache.Remove(stmt)
  439. return nil, inflight.err
  440. }
  441. partitionKey = tableMetadata.PartitionKey
  442. size := len(partitionKey)
  443. routingKeyInfo := &routingKeyInfo{
  444. indexes: make([]int, size),
  445. types: make([]TypeInfo, size),
  446. }
  447. for keyIndex, keyColumn := range partitionKey {
  448. // set an indicator for checking if the mapping is missing
  449. routingKeyInfo.indexes[keyIndex] = -1
  450. // find the column in the query info
  451. for argIndex, boundColumn := range info.request.columns {
  452. if keyColumn.Name == boundColumn.Name {
  453. // there may be many such bound columns, pick the first
  454. routingKeyInfo.indexes[keyIndex] = argIndex
  455. routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
  456. break
  457. }
  458. }
  459. if routingKeyInfo.indexes[keyIndex] == -1 {
  460. // missing a routing key column mapping
  461. // no routing key, and no error
  462. return nil, nil
  463. }
  464. }
  465. // cache this result
  466. inflight.value = routingKeyInfo
  467. return routingKeyInfo, nil
  468. }
  469. func (b *Batch) execute(conn *Conn) *Iter {
  470. return conn.executeBatch(b)
  471. }
  472. func (s *Session) executeBatch(batch *Batch) *Iter {
  473. // fail fast
  474. if s.Closed() {
  475. return &Iter{err: ErrSessionClosed}
  476. }
  477. // Prevent the execution of the batch if greater than the limit
  478. // Currently batches have a limit of 65536 queries.
  479. // https://datastax-oss.atlassian.net/browse/JAVA-229
  480. if batch.Size() > BatchSizeMaximum {
  481. return &Iter{err: ErrTooManyStmts}
  482. }
  483. iter, err := s.executor.executeQuery(batch)
  484. if err != nil {
  485. return &Iter{err: err}
  486. }
  487. return iter
  488. }
  489. // ExecuteBatch executes a batch operation and returns nil if successful
  490. // otherwise an error is returned describing the failure.
  491. func (s *Session) ExecuteBatch(batch *Batch) error {
  492. iter := s.executeBatch(batch)
  493. return iter.Close()
  494. }
  495. // ExecuteBatchCAS executes a batch operation and returns true if successful and
  496. // an iterator (to scan aditional rows if more than one conditional statement)
  497. // was sent.
  498. // Further scans on the interator must also remember to include
  499. // the applied boolean as the first argument to *Iter.Scan
  500. func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (applied bool, iter *Iter, err error) {
  501. iter = s.executeBatch(batch)
  502. if err := iter.checkErrAndNotFound(); err != nil {
  503. iter.Close()
  504. return false, nil, err
  505. }
  506. if len(iter.Columns()) > 1 {
  507. dest = append([]interface{}{&applied}, dest...)
  508. iter.Scan(dest...)
  509. } else {
  510. iter.Scan(&applied)
  511. }
  512. return applied, iter, nil
  513. }
  514. // MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,
  515. // however it accepts a map rather than a list of arguments for the initial
  516. // scan.
  517. func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
  518. iter = s.executeBatch(batch)
  519. if err := iter.checkErrAndNotFound(); err != nil {
  520. iter.Close()
  521. return false, nil, err
  522. }
  523. iter.MapScan(dest)
  524. applied = dest["[applied]"].(bool)
  525. delete(dest, "[applied]")
  526. // we usually close here, but instead of closing, just returin an error
  527. // if MapScan failed. Although Close just returns err, using Close
  528. // here might be confusing as we are not actually closing the iter
  529. return applied, iter, iter.err
  530. }
  531. func (s *Session) connect(host *HostInfo, errorHandler ConnErrorHandler) (*Conn, error) {
  532. return Connect(host, s.connCfg, errorHandler, s)
  533. }
  534. // Query represents a CQL statement that can be executed.
  535. type Query struct {
  536. stmt string
  537. values []interface{}
  538. cons Consistency
  539. pageSize int
  540. routingKey []byte
  541. routingKeyBuffer []byte
  542. pageState []byte
  543. prefetch float64
  544. trace Tracer
  545. session *Session
  546. rt RetryPolicy
  547. binding func(q *QueryInfo) ([]interface{}, error)
  548. attempts int
  549. totalLatency int64
  550. serialCons SerialConsistency
  551. defaultTimestamp bool
  552. defaultTimestampValue int64
  553. disableSkipMetadata bool
  554. context context.Context
  555. disableAutoPage bool
  556. }
  557. // String implements the stringer interface.
  558. func (q Query) String() string {
  559. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  560. }
  561. //Attempts returns the number of times the query was executed.
  562. func (q *Query) Attempts() int {
  563. return q.attempts
  564. }
  565. //Latency returns the average amount of nanoseconds per attempt of the query.
  566. func (q *Query) Latency() int64 {
  567. if q.attempts > 0 {
  568. return q.totalLatency / int64(q.attempts)
  569. }
  570. return 0
  571. }
  572. // Consistency sets the consistency level for this query. If no consistency
  573. // level have been set, the default consistency level of the cluster
  574. // is used.
  575. func (q *Query) Consistency(c Consistency) *Query {
  576. q.cons = c
  577. return q
  578. }
  579. // GetConsistency returns the currently configured consistency level for
  580. // the query.
  581. func (q *Query) GetConsistency() Consistency {
  582. return q.cons
  583. }
  584. // Trace enables tracing of this query. Look at the documentation of the
  585. // Tracer interface to learn more about tracing.
  586. func (q *Query) Trace(trace Tracer) *Query {
  587. q.trace = trace
  588. return q
  589. }
  590. // PageSize will tell the iterator to fetch the result in pages of size n.
  591. // This is useful for iterating over large result sets, but setting the
  592. // page size too low might decrease the performance. This feature is only
  593. // available in Cassandra 2 and onwards.
  594. func (q *Query) PageSize(n int) *Query {
  595. q.pageSize = n
  596. return q
  597. }
  598. // DefaultTimestamp will enable the with default timestamp flag on the query.
  599. // If enable, this will replace the server side assigned
  600. // timestamp as default timestamp. Note that a timestamp in the query itself
  601. // will still override this timestamp. This is entirely optional.
  602. //
  603. // Only available on protocol >= 3
  604. func (q *Query) DefaultTimestamp(enable bool) *Query {
  605. q.defaultTimestamp = enable
  606. return q
  607. }
  608. // WithTimestamp will enable the with default timestamp flag on the query
  609. // like DefaultTimestamp does. But also allows to define value for timestamp.
  610. // It works the same way as USING TIMESTAMP in the query itself, but
  611. // should not break prepared query optimization
  612. //
  613. // Only available on protocol >= 3
  614. func (q *Query) WithTimestamp(timestamp int64) *Query {
  615. q.DefaultTimestamp(true)
  616. q.defaultTimestampValue = timestamp
  617. return q
  618. }
  619. // RoutingKey sets the routing key to use when a token aware connection
  620. // pool is used to optimize the routing of this query.
  621. func (q *Query) RoutingKey(routingKey []byte) *Query {
  622. q.routingKey = routingKey
  623. return q
  624. }
  625. // WithContext will set the context to use during a query, it will be used to
  626. // timeout when waiting for responses from Cassandra.
  627. func (q *Query) WithContext(ctx context.Context) *Query {
  628. q.context = ctx
  629. return q
  630. }
  631. func (q *Query) execute(conn *Conn) *Iter {
  632. return conn.executeQuery(q)
  633. }
  634. func (q *Query) attempt(d time.Duration) {
  635. q.attempts++
  636. q.totalLatency += d.Nanoseconds()
  637. // TODO: track latencies per host and things as well instead of just total
  638. }
  639. func (q *Query) retryPolicy() RetryPolicy {
  640. return q.rt
  641. }
  642. // GetRoutingKey gets the routing key to use for routing this query. If
  643. // a routing key has not been explicitly set, then the routing key will
  644. // be constructed if possible using the keyspace's schema and the query
  645. // info for this query statement. If the routing key cannot be determined
  646. // then nil will be returned with no error. On any error condition,
  647. // an error description will be returned.
  648. func (q *Query) GetRoutingKey() ([]byte, error) {
  649. if q.routingKey != nil {
  650. return q.routingKey, nil
  651. } else if q.binding != nil && len(q.values) == 0 {
  652. // If this query was created using session.Bind we wont have the query
  653. // values yet, so we have to pass down to the next policy.
  654. // TODO: Remove this and handle this case
  655. return nil, nil
  656. }
  657. // try to determine the routing key
  658. routingKeyInfo, err := q.session.routingKeyInfo(q.context, q.stmt)
  659. if err != nil {
  660. return nil, err
  661. }
  662. if routingKeyInfo == nil {
  663. return nil, nil
  664. }
  665. if len(routingKeyInfo.indexes) == 1 {
  666. // single column routing key
  667. routingKey, err := Marshal(
  668. routingKeyInfo.types[0],
  669. q.values[routingKeyInfo.indexes[0]],
  670. )
  671. if err != nil {
  672. return nil, err
  673. }
  674. return routingKey, nil
  675. }
  676. // We allocate that buffer only once, so that further re-bind/exec of the
  677. // same query don't allocate more memory.
  678. if q.routingKeyBuffer == nil {
  679. q.routingKeyBuffer = make([]byte, 0, 256)
  680. }
  681. // composite routing key
  682. buf := bytes.NewBuffer(q.routingKeyBuffer)
  683. for i := range routingKeyInfo.indexes {
  684. encoded, err := Marshal(
  685. routingKeyInfo.types[i],
  686. q.values[routingKeyInfo.indexes[i]],
  687. )
  688. if err != nil {
  689. return nil, err
  690. }
  691. lenBuf := []byte{0x00, 0x00}
  692. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  693. buf.Write(lenBuf)
  694. buf.Write(encoded)
  695. buf.WriteByte(0x00)
  696. }
  697. routingKey := buf.Bytes()
  698. return routingKey, nil
  699. }
  700. func (q *Query) shouldPrepare() bool {
  701. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  702. return unicode.IsSpace(r) || r == ';'
  703. }), unicode.IsSpace)
  704. var stmtType string
  705. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  706. stmtType = strings.ToLower(stmt[:n])
  707. }
  708. if stmtType == "begin" {
  709. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  710. stmtType = strings.ToLower(stmt[n+1:])
  711. }
  712. }
  713. switch stmtType {
  714. case "select", "insert", "update", "delete", "batch":
  715. return true
  716. }
  717. return false
  718. }
  719. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  720. // there are only p*pageSize rows remaining, the next page will be requested
  721. // automatically.
  722. func (q *Query) Prefetch(p float64) *Query {
  723. q.prefetch = p
  724. return q
  725. }
  726. // RetryPolicy sets the policy to use when retrying the query.
  727. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  728. q.rt = r
  729. return q
  730. }
  731. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  732. // to an existing query instance.
  733. func (q *Query) Bind(v ...interface{}) *Query {
  734. q.values = v
  735. return q
  736. }
  737. // SerialConsistency sets the consistency level for the
  738. // serial phase of conditional updates. That consistency can only be
  739. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  740. // SERIAL. This option will be ignored for anything else that a
  741. // conditional update/insert.
  742. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  743. q.serialCons = cons
  744. return q
  745. }
  746. // PageState sets the paging state for the query to resume paging from a specific
  747. // point in time. Setting this will disable to query paging for this query, and
  748. // must be used for all subsequent pages.
  749. func (q *Query) PageState(state []byte) *Query {
  750. q.pageState = state
  751. q.disableAutoPage = true
  752. return q
  753. }
  754. // NoSkipMetadata will override the internal result metadata cache so that the driver does not
  755. // send skip_metadata for queries, this means that the result will always contain
  756. // the metadata to parse the rows and will not reuse the metadata from the prepared
  757. // staement. This should only be used to work around cassandra bugs, such as when using
  758. // CAS operations which do not end in Cas.
  759. //
  760. // See https://issues.apache.org/jira/browse/CASSANDRA-11099
  761. // https://github.com/gocql/gocql/issues/612
  762. func (q *Query) NoSkipMetadata() *Query {
  763. q.disableSkipMetadata = true
  764. return q
  765. }
  766. // Exec executes the query without returning any rows.
  767. func (q *Query) Exec() error {
  768. return q.Iter().Close()
  769. }
  770. func isUseStatement(stmt string) bool {
  771. if len(stmt) < 3 {
  772. return false
  773. }
  774. return strings.ToLower(stmt[0:3]) == "use"
  775. }
  776. // Iter executes the query and returns an iterator capable of iterating
  777. // over all results.
  778. func (q *Query) Iter() *Iter {
  779. if isUseStatement(q.stmt) {
  780. return &Iter{err: ErrUseStmt}
  781. }
  782. return q.session.executeQuery(q)
  783. }
  784. // MapScan executes the query, copies the columns of the first selected
  785. // row into the map pointed at by m and discards the rest. If no rows
  786. // were selected, ErrNotFound is returned.
  787. func (q *Query) MapScan(m map[string]interface{}) error {
  788. iter := q.Iter()
  789. if err := iter.checkErrAndNotFound(); err != nil {
  790. return err
  791. }
  792. iter.MapScan(m)
  793. return iter.Close()
  794. }
  795. // Scan executes the query, copies the columns of the first selected
  796. // row into the values pointed at by dest and discards the rest. If no rows
  797. // were selected, ErrNotFound is returned.
  798. func (q *Query) Scan(dest ...interface{}) error {
  799. iter := q.Iter()
  800. if err := iter.checkErrAndNotFound(); err != nil {
  801. return err
  802. }
  803. iter.Scan(dest...)
  804. return iter.Close()
  805. }
  806. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  807. // statement containing an IF clause). If the transaction fails because
  808. // the existing values did not match, the previous values will be stored
  809. // in dest.
  810. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  811. q.disableSkipMetadata = true
  812. iter := q.Iter()
  813. if err := iter.checkErrAndNotFound(); err != nil {
  814. return false, err
  815. }
  816. if len(iter.Columns()) > 1 {
  817. dest = append([]interface{}{&applied}, dest...)
  818. iter.Scan(dest...)
  819. } else {
  820. iter.Scan(&applied)
  821. }
  822. return applied, iter.Close()
  823. }
  824. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  825. // statement containing an IF clause). If the transaction fails because
  826. // the existing values did not match, the previous values will be stored
  827. // in dest map.
  828. //
  829. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  830. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  831. // column mismatching. MapScanCAS is added to capture them safely.
  832. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  833. q.disableSkipMetadata = true
  834. iter := q.Iter()
  835. if err := iter.checkErrAndNotFound(); err != nil {
  836. return false, err
  837. }
  838. iter.MapScan(dest)
  839. applied = dest["[applied]"].(bool)
  840. delete(dest, "[applied]")
  841. return applied, iter.Close()
  842. }
  843. // Release releases a query back into a pool of queries. Released Queries
  844. // cannot be reused.
  845. //
  846. // Example:
  847. // qry := session.Query("SELECT * FROM my_table")
  848. // qry.Exec()
  849. // qry.Release()
  850. func (q *Query) Release() {
  851. q.reset()
  852. queryPool.Put(q)
  853. }
  854. // reset zeroes out all fields of a query so that it can be safely pooled.
  855. func (q *Query) reset() {
  856. q.stmt = ""
  857. q.values = nil
  858. q.cons = 0
  859. q.pageSize = 0
  860. q.routingKey = nil
  861. q.routingKeyBuffer = nil
  862. q.pageState = nil
  863. q.prefetch = 0
  864. q.trace = nil
  865. q.session = nil
  866. q.rt = nil
  867. q.binding = nil
  868. q.attempts = 0
  869. q.totalLatency = 0
  870. q.serialCons = 0
  871. q.defaultTimestamp = false
  872. q.disableSkipMetadata = false
  873. q.disableAutoPage = false
  874. q.context = nil
  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 explanation.")
  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. ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist")
  1351. ErrNoMetadata = errors.New("no metadata available")
  1352. )
  1353. type ErrProtocol struct{ error }
  1354. func NewErrProtocol(format string, args ...interface{}) error {
  1355. return ErrProtocol{fmt.Errorf(format, args...)}
  1356. }
  1357. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1358. // This limit is set by cassandra and could change in the future.
  1359. const BatchSizeMaximum = 65535