session.go 43 KB

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