session.go 48 KB

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