session.go 47 KB

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