session.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  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, 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. // Statement returns the statement that was used to generate this query.
  578. func (q Query) Statement() string {
  579. return q.stmt
  580. }
  581. // String implements the stringer interface.
  582. func (q Query) String() string {
  583. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  584. }
  585. //Attempts returns the number of times the query was executed.
  586. func (q *Query) Attempts() int {
  587. return q.attempts
  588. }
  589. //Latency returns the average amount of nanoseconds per attempt of the query.
  590. func (q *Query) Latency() int64 {
  591. if q.attempts > 0 {
  592. return q.totalLatency / int64(q.attempts)
  593. }
  594. return 0
  595. }
  596. // Consistency sets the consistency level for this query. If no consistency
  597. // level have been set, the default consistency level of the cluster
  598. // is used.
  599. func (q *Query) Consistency(c Consistency) *Query {
  600. q.cons = c
  601. return q
  602. }
  603. // GetConsistency returns the currently configured consistency level for
  604. // the query.
  605. func (q *Query) GetConsistency() Consistency {
  606. return q.cons
  607. }
  608. // Same as Consistency but without a return value
  609. func (q *Query) SetConsistency(c Consistency) {
  610. q.cons = c
  611. }
  612. // Trace enables tracing of this query. Look at the documentation of the
  613. // Tracer interface to learn more about tracing.
  614. func (q *Query) Trace(trace Tracer) *Query {
  615. q.trace = trace
  616. return q
  617. }
  618. // Observer enables query-level observer on this query.
  619. // The provided observer will be called every time this query is executed.
  620. func (q *Query) Observer(observer QueryObserver) *Query {
  621. q.observer = observer
  622. return q
  623. }
  624. // PageSize will tell the iterator to fetch the result in pages of size n.
  625. // This is useful for iterating over large result sets, but setting the
  626. // page size too low might decrease the performance. This feature is only
  627. // available in Cassandra 2 and onwards.
  628. func (q *Query) PageSize(n int) *Query {
  629. q.pageSize = n
  630. return q
  631. }
  632. // DefaultTimestamp will enable the with default timestamp flag on the query.
  633. // If enable, this will replace the server side assigned
  634. // timestamp as default timestamp. Note that a timestamp in the query itself
  635. // will still override this timestamp. This is entirely optional.
  636. //
  637. // Only available on protocol >= 3
  638. func (q *Query) DefaultTimestamp(enable bool) *Query {
  639. q.defaultTimestamp = enable
  640. return q
  641. }
  642. // WithTimestamp will enable the with default timestamp flag on the query
  643. // like DefaultTimestamp does. But also allows to define value for timestamp.
  644. // It works the same way as USING TIMESTAMP in the query itself, but
  645. // should not break prepared query optimization
  646. //
  647. // Only available on protocol >= 3
  648. func (q *Query) WithTimestamp(timestamp int64) *Query {
  649. q.DefaultTimestamp(true)
  650. q.defaultTimestampValue = timestamp
  651. return q
  652. }
  653. // RoutingKey sets the routing key to use when a token aware connection
  654. // pool is used to optimize the routing of this query.
  655. func (q *Query) RoutingKey(routingKey []byte) *Query {
  656. q.routingKey = routingKey
  657. return q
  658. }
  659. // WithContext will set the context to use during a query, it will be used to
  660. // timeout when waiting for responses from Cassandra.
  661. func (q *Query) WithContext(ctx context.Context) *Query {
  662. q.context = ctx
  663. return q
  664. }
  665. func (q *Query) execute(conn *Conn) *Iter {
  666. return conn.executeQuery(q)
  667. }
  668. func (q *Query) attempt(keyspace string, end, start time.Time, iter *Iter) {
  669. q.attempts++
  670. q.totalLatency += end.Sub(start).Nanoseconds()
  671. // TODO: track latencies per host and things as well instead of just total
  672. if q.observer != nil {
  673. q.observer.ObserveQuery(q.context, ObservedQuery{
  674. Keyspace: keyspace,
  675. Statement: q.stmt,
  676. Start: start,
  677. End: end,
  678. Rows: iter.numRows,
  679. Err: iter.err,
  680. })
  681. }
  682. }
  683. func (q *Query) retryPolicy() RetryPolicy {
  684. return q.rt
  685. }
  686. // Keyspace returns the keyspace the query will be executed against.
  687. func (q *Query) Keyspace() string {
  688. if q.session == nil {
  689. return ""
  690. }
  691. // TODO(chbannis): this should be parsed from the query or we should let
  692. // this be set by users.
  693. return q.session.cfg.Keyspace
  694. }
  695. // GetRoutingKey gets the routing key to use for routing this query. If
  696. // a routing key has not been explicitly set, then the routing key will
  697. // be constructed if possible using the keyspace's schema and the query
  698. // info for this query statement. If the routing key cannot be determined
  699. // then nil will be returned with no error. On any error condition,
  700. // an error description will be returned.
  701. func (q *Query) GetRoutingKey() ([]byte, error) {
  702. if q.routingKey != nil {
  703. return q.routingKey, nil
  704. } else if q.binding != nil && len(q.values) == 0 {
  705. // If this query was created using session.Bind we wont have the query
  706. // values yet, so we have to pass down to the next policy.
  707. // TODO: Remove this and handle this case
  708. return nil, nil
  709. }
  710. // try to determine the routing key
  711. routingKeyInfo, err := q.session.routingKeyInfo(q.context, q.stmt)
  712. if err != nil {
  713. return nil, err
  714. }
  715. if routingKeyInfo == nil {
  716. return nil, nil
  717. }
  718. if len(routingKeyInfo.indexes) == 1 {
  719. // single column routing key
  720. routingKey, err := Marshal(
  721. routingKeyInfo.types[0],
  722. q.values[routingKeyInfo.indexes[0]],
  723. )
  724. if err != nil {
  725. return nil, err
  726. }
  727. return routingKey, nil
  728. }
  729. // We allocate that buffer only once, so that further re-bind/exec of the
  730. // same query don't allocate more memory.
  731. if q.routingKeyBuffer == nil {
  732. q.routingKeyBuffer = make([]byte, 0, 256)
  733. }
  734. // composite routing key
  735. buf := bytes.NewBuffer(q.routingKeyBuffer)
  736. for i := range routingKeyInfo.indexes {
  737. encoded, err := Marshal(
  738. routingKeyInfo.types[i],
  739. q.values[routingKeyInfo.indexes[i]],
  740. )
  741. if err != nil {
  742. return nil, err
  743. }
  744. lenBuf := []byte{0x00, 0x00}
  745. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  746. buf.Write(lenBuf)
  747. buf.Write(encoded)
  748. buf.WriteByte(0x00)
  749. }
  750. routingKey := buf.Bytes()
  751. return routingKey, nil
  752. }
  753. func (q *Query) shouldPrepare() bool {
  754. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  755. return unicode.IsSpace(r) || r == ';'
  756. }), unicode.IsSpace)
  757. var stmtType string
  758. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  759. stmtType = strings.ToLower(stmt[:n])
  760. }
  761. if stmtType == "begin" {
  762. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  763. stmtType = strings.ToLower(stmt[n+1:])
  764. }
  765. }
  766. switch stmtType {
  767. case "select", "insert", "update", "delete", "batch":
  768. return true
  769. }
  770. return false
  771. }
  772. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  773. // there are only p*pageSize rows remaining, the next page will be requested
  774. // automatically.
  775. func (q *Query) Prefetch(p float64) *Query {
  776. q.prefetch = p
  777. return q
  778. }
  779. // RetryPolicy sets the policy to use when retrying the query.
  780. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  781. q.rt = r
  782. return q
  783. }
  784. func (q *Query) IsIdempotent() bool {
  785. return q.idempotent
  786. }
  787. // Idempontent marks the query as being idempontent or not depending on
  788. // the value.
  789. func (q *Query) Idempontent(value bool) *Query {
  790. q.idempotent = value
  791. return q
  792. }
  793. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  794. // to an existing query instance.
  795. func (q *Query) Bind(v ...interface{}) *Query {
  796. q.values = v
  797. return q
  798. }
  799. // SerialConsistency sets the consistency level for the
  800. // serial phase of conditional updates. That consistency can only be
  801. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  802. // SERIAL. This option will be ignored for anything else that a
  803. // conditional update/insert.
  804. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  805. q.serialCons = cons
  806. return q
  807. }
  808. // PageState sets the paging state for the query to resume paging from a specific
  809. // point in time. Setting this will disable to query paging for this query, and
  810. // must be used for all subsequent pages.
  811. func (q *Query) PageState(state []byte) *Query {
  812. q.pageState = state
  813. q.disableAutoPage = true
  814. return q
  815. }
  816. // NoSkipMetadata will override the internal result metadata cache so that the driver does not
  817. // send skip_metadata for queries, this means that the result will always contain
  818. // the metadata to parse the rows and will not reuse the metadata from the prepared
  819. // staement. This should only be used to work around cassandra bugs, such as when using
  820. // CAS operations which do not end in Cas.
  821. //
  822. // See https://issues.apache.org/jira/browse/CASSANDRA-11099
  823. // https://github.com/gocql/gocql/issues/612
  824. func (q *Query) NoSkipMetadata() *Query {
  825. q.disableSkipMetadata = true
  826. return q
  827. }
  828. // Exec executes the query without returning any rows.
  829. func (q *Query) Exec() error {
  830. return q.Iter().Close()
  831. }
  832. func isUseStatement(stmt string) bool {
  833. if len(stmt) < 3 {
  834. return false
  835. }
  836. return strings.EqualFold(stmt[0:3], "use")
  837. }
  838. // Iter executes the query and returns an iterator capable of iterating
  839. // over all results.
  840. func (q *Query) Iter() *Iter {
  841. if isUseStatement(q.stmt) {
  842. return &Iter{err: ErrUseStmt}
  843. }
  844. return q.session.executeQuery(q)
  845. }
  846. // MapScan executes the query, copies the columns of the first selected
  847. // row into the map pointed at by m and discards the rest. If no rows
  848. // were selected, ErrNotFound is returned.
  849. func (q *Query) MapScan(m map[string]interface{}) error {
  850. iter := q.Iter()
  851. if err := iter.checkErrAndNotFound(); err != nil {
  852. return err
  853. }
  854. iter.MapScan(m)
  855. return iter.Close()
  856. }
  857. // Scan executes the query, copies the columns of the first selected
  858. // row into the values pointed at by dest and discards the rest. If no rows
  859. // were selected, ErrNotFound is returned.
  860. func (q *Query) Scan(dest ...interface{}) error {
  861. iter := q.Iter()
  862. if err := iter.checkErrAndNotFound(); err != nil {
  863. return err
  864. }
  865. iter.Scan(dest...)
  866. return iter.Close()
  867. }
  868. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  869. // statement containing an IF clause). If the transaction fails because
  870. // the existing values did not match, the previous values will be stored
  871. // in dest.
  872. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  873. q.disableSkipMetadata = true
  874. iter := q.Iter()
  875. if err := iter.checkErrAndNotFound(); err != nil {
  876. return false, err
  877. }
  878. if len(iter.Columns()) > 1 {
  879. dest = append([]interface{}{&applied}, dest...)
  880. iter.Scan(dest...)
  881. } else {
  882. iter.Scan(&applied)
  883. }
  884. return applied, iter.Close()
  885. }
  886. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  887. // statement containing an IF clause). If the transaction fails because
  888. // the existing values did not match, the previous values will be stored
  889. // in dest map.
  890. //
  891. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  892. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  893. // column mismatching. MapScanCAS is added to capture them safely.
  894. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  895. q.disableSkipMetadata = true
  896. iter := q.Iter()
  897. if err := iter.checkErrAndNotFound(); err != nil {
  898. return false, err
  899. }
  900. iter.MapScan(dest)
  901. applied = dest["[applied]"].(bool)
  902. delete(dest, "[applied]")
  903. return applied, iter.Close()
  904. }
  905. // Release releases a query back into a pool of queries. Released Queries
  906. // cannot be reused.
  907. //
  908. // Example:
  909. // qry := session.Query("SELECT * FROM my_table")
  910. // qry.Exec()
  911. // qry.Release()
  912. func (q *Query) Release() {
  913. q.reset()
  914. queryPool.Put(q)
  915. }
  916. // reset zeroes out all fields of a query so that it can be safely pooled.
  917. func (q *Query) reset() {
  918. *q = Query{}
  919. }
  920. // Iter represents an iterator that can be used to iterate over all rows that
  921. // were returned by a query. The iterator might send additional queries to the
  922. // database during the iteration if paging was enabled.
  923. type Iter struct {
  924. err error
  925. pos int
  926. meta resultMetadata
  927. numRows int
  928. next *nextIter
  929. host *HostInfo
  930. framer *framer
  931. closed int32
  932. }
  933. // Host returns the host which the query was sent to.
  934. func (iter *Iter) Host() *HostInfo {
  935. return iter.host
  936. }
  937. // Columns returns the name and type of the selected columns.
  938. func (iter *Iter) Columns() []ColumnInfo {
  939. return iter.meta.columns
  940. }
  941. type Scanner interface {
  942. // Next advances the row pointer to point at the next row, the row is valid until
  943. // the next call of Next. It returns true if there is a row which is available to be
  944. // scanned into with Scan.
  945. // Next must be called before every call to Scan.
  946. Next() bool
  947. // Scan copies the current row's columns into dest. If the length of dest does not equal
  948. // the number of columns returned in the row an error is returned. If an error is encountered
  949. // when unmarshalling a column into the value in dest an error is returned and the row is invalidated
  950. // until the next call to Next.
  951. // Next must be called before calling Scan, if it is not an error is returned.
  952. Scan(...interface{}) error
  953. // Err returns the if there was one during iteration that resulted in iteration being unable to complete.
  954. // Err will also release resources held by the iterator, the Scanner should not used after being called.
  955. Err() error
  956. }
  957. type iterScanner struct {
  958. iter *Iter
  959. cols [][]byte
  960. valid bool
  961. }
  962. func (is *iterScanner) Next() bool {
  963. iter := is.iter
  964. if iter.err != nil {
  965. return false
  966. }
  967. if iter.pos >= iter.numRows {
  968. if iter.next != nil {
  969. is.iter = iter.next.fetch()
  970. return is.Next()
  971. }
  972. return false
  973. }
  974. for i := 0; i < len(is.cols); i++ {
  975. col, err := iter.readColumn()
  976. if err != nil {
  977. iter.err = err
  978. return false
  979. }
  980. is.cols[i] = col
  981. }
  982. iter.pos++
  983. is.valid = true
  984. return true
  985. }
  986. func scanColumn(p []byte, col ColumnInfo, dest []interface{}) (int, error) {
  987. if dest[0] == nil {
  988. return 1, nil
  989. }
  990. if col.TypeInfo.Type() == TypeTuple {
  991. // this will panic, actually a bug, please report
  992. tuple := col.TypeInfo.(TupleTypeInfo)
  993. count := len(tuple.Elems)
  994. // here we pass in a slice of the struct which has the number number of
  995. // values as elements in the tuple
  996. if err := Unmarshal(col.TypeInfo, p, dest[:count]); err != nil {
  997. return 0, err
  998. }
  999. return count, nil
  1000. } else {
  1001. if err := Unmarshal(col.TypeInfo, p, dest[0]); err != nil {
  1002. return 0, err
  1003. }
  1004. return 1, nil
  1005. }
  1006. }
  1007. func (is *iterScanner) Scan(dest ...interface{}) error {
  1008. if !is.valid {
  1009. return errors.New("gocql: Scan called without calling Next")
  1010. }
  1011. iter := is.iter
  1012. // currently only support scanning into an expand tuple, such that its the same
  1013. // as scanning in more values from a single column
  1014. if len(dest) != iter.meta.actualColCount {
  1015. return fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  1016. }
  1017. // i is the current position in dest, could posible replace it and just use
  1018. // slices of dest
  1019. i := 0
  1020. var err error
  1021. for _, col := range iter.meta.columns {
  1022. var n int
  1023. n, err = scanColumn(is.cols[i], col, dest[i:])
  1024. if err != nil {
  1025. break
  1026. }
  1027. i += n
  1028. }
  1029. is.valid = false
  1030. return err
  1031. }
  1032. func (is *iterScanner) Err() error {
  1033. iter := is.iter
  1034. is.iter = nil
  1035. is.cols = nil
  1036. is.valid = false
  1037. return iter.Close()
  1038. }
  1039. // Scanner returns a row Scanner which provides an interface to scan rows in a manner which is
  1040. // similar to database/sql. The iter should NOT be used again after calling this method.
  1041. func (iter *Iter) Scanner() Scanner {
  1042. if iter == nil {
  1043. return nil
  1044. }
  1045. return &iterScanner{iter: iter, cols: make([][]byte, len(iter.meta.columns))}
  1046. }
  1047. func (iter *Iter) readColumn() ([]byte, error) {
  1048. return iter.framer.readBytesInternal()
  1049. }
  1050. // Scan consumes the next row of the iterator and copies the columns of the
  1051. // current row into the values pointed at by dest. Use nil as a dest value
  1052. // to skip the corresponding column. Scan might send additional queries
  1053. // to the database to retrieve the next set of rows if paging was enabled.
  1054. //
  1055. // Scan returns true if the row was successfully unmarshaled or false if the
  1056. // end of the result set was reached or if an error occurred. Close should
  1057. // be called afterwards to retrieve any potential errors.
  1058. func (iter *Iter) Scan(dest ...interface{}) bool {
  1059. if iter.err != nil {
  1060. return false
  1061. }
  1062. if iter.pos >= iter.numRows {
  1063. if iter.next != nil {
  1064. *iter = *iter.next.fetch()
  1065. return iter.Scan(dest...)
  1066. }
  1067. return false
  1068. }
  1069. if iter.next != nil && iter.pos == iter.next.pos {
  1070. go iter.next.fetch()
  1071. }
  1072. // currently only support scanning into an expand tuple, such that its the same
  1073. // as scanning in more values from a single column
  1074. if len(dest) != iter.meta.actualColCount {
  1075. iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  1076. return false
  1077. }
  1078. // i is the current position in dest, could posible replace it and just use
  1079. // slices of dest
  1080. i := 0
  1081. for _, col := range iter.meta.columns {
  1082. colBytes, err := iter.readColumn()
  1083. if err != nil {
  1084. iter.err = err
  1085. return false
  1086. }
  1087. n, err := scanColumn(colBytes, col, dest[i:])
  1088. if err != nil {
  1089. iter.err = err
  1090. return false
  1091. }
  1092. i += n
  1093. }
  1094. iter.pos++
  1095. return true
  1096. }
  1097. // GetCustomPayload returns any parsed custom payload results if given in the
  1098. // response from Cassandra. Note that the result is not a copy.
  1099. //
  1100. // This additional feature of CQL Protocol v4
  1101. // allows additional results and query information to be returned by
  1102. // custom QueryHandlers running in your C* cluster.
  1103. // See https://datastax.github.io/java-driver/manual/custom_payloads/
  1104. func (iter *Iter) GetCustomPayload() map[string][]byte {
  1105. return iter.framer.header.customPayload
  1106. }
  1107. // Warnings returns any warnings generated if given in the response from Cassandra.
  1108. //
  1109. // This is only available starting with CQL Protocol v4.
  1110. func (iter *Iter) Warnings() []string {
  1111. if iter.framer != nil {
  1112. return iter.framer.header.warnings
  1113. }
  1114. return nil
  1115. }
  1116. // Close closes the iterator and returns any errors that happened during
  1117. // the query or the iteration.
  1118. func (iter *Iter) Close() error {
  1119. if atomic.CompareAndSwapInt32(&iter.closed, 0, 1) {
  1120. if iter.framer != nil {
  1121. iter.framer = nil
  1122. }
  1123. }
  1124. return iter.err
  1125. }
  1126. // WillSwitchPage detects if iterator reached end of current page
  1127. // and the next page is available.
  1128. func (iter *Iter) WillSwitchPage() bool {
  1129. return iter.pos >= iter.numRows && iter.next != nil
  1130. }
  1131. // checkErrAndNotFound handle error and NotFound in one method.
  1132. func (iter *Iter) checkErrAndNotFound() error {
  1133. if iter.err != nil {
  1134. return iter.err
  1135. } else if iter.numRows == 0 {
  1136. return ErrNotFound
  1137. }
  1138. return nil
  1139. }
  1140. // PageState return the current paging state for a query which can be used for
  1141. // subsequent quries to resume paging this point.
  1142. func (iter *Iter) PageState() []byte {
  1143. return iter.meta.pagingState
  1144. }
  1145. // NumRows returns the number of rows in this pagination, it will update when new
  1146. // pages are fetched, it is not the value of the total number of rows this iter
  1147. // will return unless there is only a single page returned.
  1148. func (iter *Iter) NumRows() int {
  1149. return iter.numRows
  1150. }
  1151. type nextIter struct {
  1152. qry Query
  1153. pos int
  1154. once sync.Once
  1155. next *Iter
  1156. conn *Conn
  1157. }
  1158. func (n *nextIter) fetch() *Iter {
  1159. n.once.Do(func() {
  1160. iter := n.qry.session.executor.attemptQuery(&n.qry, n.conn)
  1161. if iter != nil && iter.err == nil {
  1162. n.next = iter
  1163. } else {
  1164. n.next = n.qry.session.executeQuery(&n.qry)
  1165. }
  1166. })
  1167. return n.next
  1168. }
  1169. type Batch struct {
  1170. Type BatchType
  1171. Entries []BatchEntry
  1172. Cons Consistency
  1173. rt RetryPolicy
  1174. observer BatchObserver
  1175. attempts int
  1176. totalLatency int64
  1177. serialCons SerialConsistency
  1178. defaultTimestamp bool
  1179. defaultTimestampValue int64
  1180. context context.Context
  1181. keyspace string
  1182. }
  1183. // NewBatch creates a new batch operation without defaults from the cluster
  1184. //
  1185. // Depreicated: use session.NewBatch instead
  1186. func NewBatch(typ BatchType) *Batch {
  1187. return &Batch{Type: typ}
  1188. }
  1189. // NewBatch creates a new batch operation using defaults defined in the cluster
  1190. func (s *Session) NewBatch(typ BatchType) *Batch {
  1191. s.mu.RLock()
  1192. batch := &Batch{
  1193. Type: typ,
  1194. rt: s.cfg.RetryPolicy,
  1195. serialCons: s.cfg.SerialConsistency,
  1196. observer: s.batchObserver,
  1197. Cons: s.cons,
  1198. defaultTimestamp: s.cfg.DefaultTimestamp,
  1199. keyspace: s.cfg.Keyspace,
  1200. }
  1201. s.mu.RUnlock()
  1202. return batch
  1203. }
  1204. // Observer enables batch-level observer on this batch.
  1205. // The provided observer will be called every time this batched query is executed.
  1206. func (b *Batch) Observer(observer BatchObserver) *Batch {
  1207. b.observer = observer
  1208. return b
  1209. }
  1210. func (b *Batch) Keyspace() string {
  1211. return b.keyspace
  1212. }
  1213. // Attempts returns the number of attempts made to execute the batch.
  1214. func (b *Batch) Attempts() int {
  1215. return b.attempts
  1216. }
  1217. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  1218. func (b *Batch) Latency() int64 {
  1219. if b.attempts > 0 {
  1220. return b.totalLatency / int64(b.attempts)
  1221. }
  1222. return 0
  1223. }
  1224. // GetConsistency returns the currently configured consistency level for the batch
  1225. // operation.
  1226. func (b *Batch) GetConsistency() Consistency {
  1227. return b.Cons
  1228. }
  1229. // SetConsistency sets the currently configured consistency level for the batch
  1230. // operation.
  1231. func (b *Batch) SetConsistency(c Consistency) {
  1232. b.Cons = c
  1233. }
  1234. // Query adds the query to the batch operation
  1235. func (b *Batch) Query(stmt string, args ...interface{}) {
  1236. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  1237. }
  1238. // Bind adds the query to the batch operation and correlates it with a binding callback
  1239. // that will be invoked when the batch is executed. The binding callback allows the application
  1240. // to define which query argument values will be marshalled as part of the batch execution.
  1241. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  1242. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  1243. }
  1244. func (b *Batch) retryPolicy() RetryPolicy {
  1245. return b.rt
  1246. }
  1247. // RetryPolicy sets the retry policy to use when executing the batch operation
  1248. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  1249. b.rt = r
  1250. return b
  1251. }
  1252. // WithContext will set the context to use during a query, it will be used to
  1253. // timeout when waiting for responses from Cassandra.
  1254. func (b *Batch) WithContext(ctx context.Context) *Batch {
  1255. b.context = ctx
  1256. return b
  1257. }
  1258. // Size returns the number of batch statements to be executed by the batch operation.
  1259. func (b *Batch) Size() int {
  1260. return len(b.Entries)
  1261. }
  1262. // SerialConsistency sets the consistency level for the
  1263. // serial phase of conditional updates. That consistency can only be
  1264. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  1265. // SERIAL. This option will be ignored for anything else that a
  1266. // conditional update/insert.
  1267. //
  1268. // Only available for protocol 3 and above
  1269. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  1270. b.serialCons = cons
  1271. return b
  1272. }
  1273. // DefaultTimestamp will enable the with default timestamp flag on the query.
  1274. // If enable, this will replace the server side assigned
  1275. // timestamp as default timestamp. Note that a timestamp in the query itself
  1276. // will still override this timestamp. This is entirely optional.
  1277. //
  1278. // Only available on protocol >= 3
  1279. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  1280. b.defaultTimestamp = enable
  1281. return b
  1282. }
  1283. // WithTimestamp will enable the with default timestamp flag on the query
  1284. // like DefaultTimestamp does. But also allows to define value for timestamp.
  1285. // It works the same way as USING TIMESTAMP in the query itself, but
  1286. // should not break prepared query optimization
  1287. //
  1288. // Only available on protocol >= 3
  1289. func (b *Batch) WithTimestamp(timestamp int64) *Batch {
  1290. b.DefaultTimestamp(true)
  1291. b.defaultTimestampValue = timestamp
  1292. return b
  1293. }
  1294. func (b *Batch) attempt(keyspace string, end, start time.Time, iter *Iter) {
  1295. b.attempts++
  1296. b.totalLatency += end.Sub(start).Nanoseconds()
  1297. // TODO: track latencies per host and things as well instead of just total
  1298. if b.observer == nil {
  1299. return
  1300. }
  1301. statements := make([]string, len(b.Entries))
  1302. for i, entry := range b.Entries {
  1303. statements[i] = entry.Stmt
  1304. }
  1305. b.observer.ObserveBatch(b.context, ObservedBatch{
  1306. Keyspace: keyspace,
  1307. Statements: statements,
  1308. Start: start,
  1309. End: end,
  1310. // Rows not used in batch observations // TODO - might be able to support it when using BatchCAS
  1311. Err: iter.err,
  1312. })
  1313. }
  1314. func (b *Batch) GetRoutingKey() ([]byte, error) {
  1315. // TODO: use the first statement in the batch as the routing key?
  1316. return nil, nil
  1317. }
  1318. type BatchType byte
  1319. const (
  1320. LoggedBatch BatchType = 0
  1321. UnloggedBatch BatchType = 1
  1322. CounterBatch BatchType = 2
  1323. )
  1324. type BatchEntry struct {
  1325. Stmt string
  1326. Args []interface{}
  1327. binding func(q *QueryInfo) ([]interface{}, error)
  1328. }
  1329. type ColumnInfo struct {
  1330. Keyspace string
  1331. Table string
  1332. Name string
  1333. TypeInfo TypeInfo
  1334. }
  1335. func (c ColumnInfo) String() string {
  1336. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  1337. }
  1338. // routing key indexes LRU cache
  1339. type routingKeyInfoLRU struct {
  1340. lru *lru.Cache
  1341. mu sync.Mutex
  1342. }
  1343. type routingKeyInfo struct {
  1344. indexes []int
  1345. types []TypeInfo
  1346. }
  1347. func (r *routingKeyInfo) String() string {
  1348. return fmt.Sprintf("routing key index=%v types=%v", r.indexes, r.types)
  1349. }
  1350. func (r *routingKeyInfoLRU) Remove(key string) {
  1351. r.mu.Lock()
  1352. r.lru.Remove(key)
  1353. r.mu.Unlock()
  1354. }
  1355. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  1356. //the new max is lower than the previous value. Not concurrency safe.
  1357. func (r *routingKeyInfoLRU) Max(max int) {
  1358. r.mu.Lock()
  1359. for r.lru.Len() > max {
  1360. r.lru.RemoveOldest()
  1361. }
  1362. r.lru.MaxEntries = max
  1363. r.mu.Unlock()
  1364. }
  1365. type inflightCachedEntry struct {
  1366. wg sync.WaitGroup
  1367. err error
  1368. value interface{}
  1369. }
  1370. // Tracer is the interface implemented by query tracers. Tracers have the
  1371. // ability to obtain a detailed event log of all events that happened during
  1372. // the execution of a query from Cassandra. Gathering this information might
  1373. // be essential for debugging and optimizing queries, but this feature should
  1374. // not be used on production systems with very high load.
  1375. type Tracer interface {
  1376. Trace(traceId []byte)
  1377. }
  1378. type traceWriter struct {
  1379. session *Session
  1380. w io.Writer
  1381. mu sync.Mutex
  1382. }
  1383. // NewTraceWriter returns a simple Tracer implementation that outputs
  1384. // the event log in a textual format.
  1385. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  1386. return &traceWriter{session: session, w: w}
  1387. }
  1388. func (t *traceWriter) Trace(traceId []byte) {
  1389. var (
  1390. coordinator string
  1391. duration int
  1392. )
  1393. iter := t.session.control.query(`SELECT coordinator, duration
  1394. FROM system_traces.sessions
  1395. WHERE session_id = ?`, traceId)
  1396. iter.Scan(&coordinator, &duration)
  1397. if err := iter.Close(); err != nil {
  1398. t.mu.Lock()
  1399. fmt.Fprintln(t.w, "Error:", err)
  1400. t.mu.Unlock()
  1401. return
  1402. }
  1403. var (
  1404. timestamp time.Time
  1405. activity string
  1406. source string
  1407. elapsed int
  1408. )
  1409. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1410. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1411. t.mu.Lock()
  1412. defer t.mu.Unlock()
  1413. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1414. FROM system_traces.events
  1415. WHERE session_id = ?`, traceId)
  1416. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1417. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1418. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1419. }
  1420. if err := iter.Close(); err != nil {
  1421. fmt.Fprintln(t.w, "Error:", err)
  1422. }
  1423. }
  1424. type ObservedQuery struct {
  1425. Keyspace string
  1426. Statement string
  1427. Start time.Time // time immediately before the query was called
  1428. End time.Time // time immediately after the query returned
  1429. // Rows is the number of rows in the current iter.
  1430. // In paginated queries, rows from previous scans are not counted.
  1431. // Rows is not used in batch queries and remains at the default value
  1432. Rows int
  1433. // Err is the error in the query.
  1434. // It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil error
  1435. Err error
  1436. }
  1437. // QueryObserver is the interface implemented by query observers / stat collectors.
  1438. //
  1439. // Experimental, this interface and use may change
  1440. type QueryObserver interface {
  1441. // ObserveQuery gets called on every query to cassandra, including all queries in an iterator when paging is enabled.
  1442. // It doesn't get called if there is no query because the session is closed or there are no connections available.
  1443. // The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.
  1444. ObserveQuery(context.Context, ObservedQuery)
  1445. }
  1446. type ObservedBatch struct {
  1447. Keyspace string
  1448. Statements []string
  1449. Start time.Time // time immediately before the batch query was called
  1450. End time.Time // time immediately after the batch query returned
  1451. // Err is the error in the batch query.
  1452. // It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil error
  1453. Err error
  1454. }
  1455. // BatchObserver is the interface implemented by batch observers / stat collectors.
  1456. type BatchObserver interface {
  1457. // ObserveBatch gets called on every batch query to cassandra.
  1458. // It also gets called once for each query in a batch.
  1459. // It doesn't get called if there is no query because the session is closed or there are no connections available.
  1460. // The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.
  1461. // Unlike QueryObserver.ObserveQuery it does no reporting on rows read.
  1462. ObserveBatch(context.Context, ObservedBatch)
  1463. }
  1464. type Error struct {
  1465. Code int
  1466. Message string
  1467. }
  1468. func (e Error) Error() string {
  1469. return e.Message
  1470. }
  1471. var (
  1472. ErrNotFound = errors.New("not found")
  1473. ErrUnavailable = errors.New("unavailable")
  1474. ErrUnsupported = errors.New("feature not supported")
  1475. ErrTooManyStmts = errors.New("too many statements")
  1476. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explanation.")
  1477. ErrSessionClosed = errors.New("session has been closed")
  1478. ErrNoConnections = errors.New("gocql: no hosts available in the pool")
  1479. ErrNoKeyspace = errors.New("no keyspace provided")
  1480. ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist")
  1481. ErrNoMetadata = errors.New("no metadata available")
  1482. )
  1483. type ErrProtocol struct{ error }
  1484. func NewErrProtocol(format string, args ...interface{}) error {
  1485. return ErrProtocol{fmt.Errorf(format, args...)}
  1486. }
  1487. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1488. // This limit is set by cassandra and could change in the future.
  1489. const BatchSizeMaximum = 65535