session.go 50 KB

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