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.ConnectAddress(), host.Port(), s.connCfg, errorHandler)
  537. }
  538. // Query represents a CQL statement that can be executed.
  539. type Query struct {
  540. stmt string
  541. values []interface{}
  542. cons Consistency
  543. pageSize int
  544. routingKey []byte
  545. routingKeyBuffer []byte
  546. pageState []byte
  547. prefetch float64
  548. trace Tracer
  549. observer QueryObserver
  550. session *Session
  551. rt RetryPolicy
  552. binding func(q *QueryInfo) ([]interface{}, error)
  553. attempts int
  554. totalLatency int64
  555. serialCons SerialConsistency
  556. defaultTimestamp bool
  557. defaultTimestampValue int64
  558. disableSkipMetadata bool
  559. context context.Context
  560. idempotent bool
  561. disableAutoPage bool
  562. }
  563. func (q *Query) defaultsFromSession() {
  564. s := q.session
  565. s.mu.RLock()
  566. q.cons = s.cons
  567. q.pageSize = s.pageSize
  568. q.trace = s.trace
  569. q.observer = s.queryObserver
  570. q.prefetch = s.prefetch
  571. q.rt = s.cfg.RetryPolicy
  572. q.serialCons = s.cfg.SerialConsistency
  573. q.defaultTimestamp = s.cfg.DefaultTimestamp
  574. q.idempotent = s.cfg.DefaultIdempotence
  575. s.mu.RUnlock()
  576. }
  577. // 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. }
  961. func (is *iterScanner) Next() bool {
  962. iter := is.iter
  963. if iter.err != nil {
  964. return false
  965. }
  966. if iter.pos >= iter.numRows {
  967. if iter.next != nil {
  968. is.iter = iter.next.fetch()
  969. return is.Next()
  970. }
  971. return false
  972. }
  973. cols := make([][]byte, len(iter.meta.columns))
  974. for i := 0; i < len(cols); i++ {
  975. col, err := iter.readColumn()
  976. if err != nil {
  977. iter.err = err
  978. return false
  979. }
  980. cols[i] = col
  981. }
  982. is.cols = cols
  983. iter.pos++
  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.cols == nil {
  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.cols = nil
  1030. return err
  1031. }
  1032. func (is *iterScanner) Err() error {
  1033. iter := is.iter
  1034. is.iter = nil
  1035. is.cols = nil
  1036. return iter.Close()
  1037. }
  1038. // Scanner returns a row Scanner which provides an interface to scan rows in a manner which is
  1039. // similar to database/sql. The iter should NOT be used again after calling this method.
  1040. func (iter *Iter) Scanner() Scanner {
  1041. if iter == nil {
  1042. return nil
  1043. }
  1044. return &iterScanner{iter: iter}
  1045. }
  1046. func (iter *Iter) readColumn() ([]byte, error) {
  1047. return iter.framer.readBytesInternal()
  1048. }
  1049. // Scan consumes the next row of the iterator and copies the columns of the
  1050. // current row into the values pointed at by dest. Use nil as a dest value
  1051. // to skip the corresponding column. Scan might send additional queries
  1052. // to the database to retrieve the next set of rows if paging was enabled.
  1053. //
  1054. // Scan returns true if the row was successfully unmarshaled or false if the
  1055. // end of the result set was reached or if an error occurred. Close should
  1056. // be called afterwards to retrieve any potential errors.
  1057. func (iter *Iter) Scan(dest ...interface{}) bool {
  1058. if iter.err != nil {
  1059. return false
  1060. }
  1061. if iter.pos >= iter.numRows {
  1062. if iter.next != nil {
  1063. *iter = *iter.next.fetch()
  1064. return iter.Scan(dest...)
  1065. }
  1066. return false
  1067. }
  1068. if iter.next != nil && iter.pos == iter.next.pos {
  1069. go iter.next.fetch()
  1070. }
  1071. // currently only support scanning into an expand tuple, such that its the same
  1072. // as scanning in more values from a single column
  1073. if len(dest) != iter.meta.actualColCount {
  1074. iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  1075. return false
  1076. }
  1077. // i is the current position in dest, could posible replace it and just use
  1078. // slices of dest
  1079. i := 0
  1080. for _, col := range iter.meta.columns {
  1081. colBytes, err := iter.readColumn()
  1082. if err != nil {
  1083. iter.err = err
  1084. return false
  1085. }
  1086. n, err := scanColumn(colBytes, col, dest[i:])
  1087. if err != nil {
  1088. iter.err = err
  1089. return false
  1090. }
  1091. i += n
  1092. }
  1093. iter.pos++
  1094. return true
  1095. }
  1096. // GetCustomPayload returns any parsed custom payload results if given in the
  1097. // response from Cassandra. Note that the result is not a copy.
  1098. //
  1099. // This additional feature of CQL Protocol v4
  1100. // allows additional results and query information to be returned by
  1101. // custom QueryHandlers running in your C* cluster.
  1102. // See https://datastax.github.io/java-driver/manual/custom_payloads/
  1103. func (iter *Iter) GetCustomPayload() map[string][]byte {
  1104. return iter.framer.header.customPayload
  1105. }
  1106. // Warnings returns any warnings generated if given in the response from Cassandra.
  1107. //
  1108. // This is only available starting with CQL Protocol v4.
  1109. func (iter *Iter) Warnings() []string {
  1110. if iter.framer != nil {
  1111. return iter.framer.header.warnings
  1112. }
  1113. return nil
  1114. }
  1115. // Close closes the iterator and returns any errors that happened during
  1116. // the query or the iteration.
  1117. func (iter *Iter) Close() error {
  1118. if atomic.CompareAndSwapInt32(&iter.closed, 0, 1) {
  1119. if iter.framer != nil {
  1120. iter.framer = nil
  1121. }
  1122. }
  1123. return iter.err
  1124. }
  1125. // WillSwitchPage detects if iterator reached end of current page
  1126. // and the next page is available.
  1127. func (iter *Iter) WillSwitchPage() bool {
  1128. return iter.pos >= iter.numRows && iter.next != nil
  1129. }
  1130. // checkErrAndNotFound handle error and NotFound in one method.
  1131. func (iter *Iter) checkErrAndNotFound() error {
  1132. if iter.err != nil {
  1133. return iter.err
  1134. } else if iter.numRows == 0 {
  1135. return ErrNotFound
  1136. }
  1137. return nil
  1138. }
  1139. // PageState return the current paging state for a query which can be used for
  1140. // subsequent quries to resume paging this point.
  1141. func (iter *Iter) PageState() []byte {
  1142. return iter.meta.pagingState
  1143. }
  1144. // NumRows returns the number of rows in this pagination, it will update when new
  1145. // pages are fetched, it is not the value of the total number of rows this iter
  1146. // will return unless there is only a single page returned.
  1147. func (iter *Iter) NumRows() int {
  1148. return iter.numRows
  1149. }
  1150. type nextIter struct {
  1151. qry Query
  1152. pos int
  1153. once sync.Once
  1154. next *Iter
  1155. conn *Conn
  1156. }
  1157. func (n *nextIter) fetch() *Iter {
  1158. n.once.Do(func() {
  1159. iter := n.qry.session.executor.attemptQuery(&n.qry, n.conn)
  1160. if iter != nil && iter.err == nil {
  1161. n.next = iter
  1162. } else {
  1163. n.next = n.qry.session.executeQuery(&n.qry)
  1164. }
  1165. })
  1166. return n.next
  1167. }
  1168. type Batch struct {
  1169. Type BatchType
  1170. Entries []BatchEntry
  1171. Cons Consistency
  1172. rt RetryPolicy
  1173. observer BatchObserver
  1174. attempts int
  1175. totalLatency int64
  1176. serialCons SerialConsistency
  1177. defaultTimestamp bool
  1178. defaultTimestampValue int64
  1179. context context.Context
  1180. keyspace string
  1181. }
  1182. // NewBatch creates a new batch operation without defaults from the cluster
  1183. //
  1184. // Depreicated: use session.NewBatch instead
  1185. func NewBatch(typ BatchType) *Batch {
  1186. return &Batch{Type: typ}
  1187. }
  1188. // NewBatch creates a new batch operation using defaults defined in the cluster
  1189. func (s *Session) NewBatch(typ BatchType) *Batch {
  1190. s.mu.RLock()
  1191. batch := &Batch{
  1192. Type: typ,
  1193. rt: s.cfg.RetryPolicy,
  1194. serialCons: s.cfg.SerialConsistency,
  1195. observer: s.batchObserver,
  1196. Cons: s.cons,
  1197. defaultTimestamp: s.cfg.DefaultTimestamp,
  1198. keyspace: s.cfg.Keyspace,
  1199. }
  1200. s.mu.RUnlock()
  1201. return batch
  1202. }
  1203. // Observer enables batch-level observer on this batch.
  1204. // The provided observer will be called every time this batched query is executed.
  1205. func (b *Batch) Observer(observer BatchObserver) *Batch {
  1206. b.observer = observer
  1207. return b
  1208. }
  1209. func (b *Batch) Keyspace() string {
  1210. return b.keyspace
  1211. }
  1212. // Attempts returns the number of attempts made to execute the batch.
  1213. func (b *Batch) Attempts() int {
  1214. return b.attempts
  1215. }
  1216. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  1217. func (b *Batch) Latency() int64 {
  1218. if b.attempts > 0 {
  1219. return b.totalLatency / int64(b.attempts)
  1220. }
  1221. return 0
  1222. }
  1223. // GetConsistency returns the currently configured consistency level for the batch
  1224. // operation.
  1225. func (b *Batch) GetConsistency() Consistency {
  1226. return b.Cons
  1227. }
  1228. // SetConsistency sets the currently configured consistency level for the batch
  1229. // operation.
  1230. func (b *Batch) SetConsistency(c Consistency) {
  1231. b.Cons = c
  1232. }
  1233. // Query adds the query to the batch operation
  1234. func (b *Batch) Query(stmt string, args ...interface{}) {
  1235. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  1236. }
  1237. // Bind adds the query to the batch operation and correlates it with a binding callback
  1238. // that will be invoked when the batch is executed. The binding callback allows the application
  1239. // to define which query argument values will be marshalled as part of the batch execution.
  1240. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  1241. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  1242. }
  1243. func (b *Batch) retryPolicy() RetryPolicy {
  1244. return b.rt
  1245. }
  1246. // RetryPolicy sets the retry policy to use when executing the batch operation
  1247. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  1248. b.rt = r
  1249. return b
  1250. }
  1251. // WithContext will set the context to use during a query, it will be used to
  1252. // timeout when waiting for responses from Cassandra.
  1253. func (b *Batch) WithContext(ctx context.Context) *Batch {
  1254. b.context = ctx
  1255. return b
  1256. }
  1257. // Size returns the number of batch statements to be executed by the batch operation.
  1258. func (b *Batch) Size() int {
  1259. return len(b.Entries)
  1260. }
  1261. // SerialConsistency sets the consistency level for the
  1262. // serial phase of conditional updates. That consistency can only be
  1263. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  1264. // SERIAL. This option will be ignored for anything else that a
  1265. // conditional update/insert.
  1266. //
  1267. // Only available for protocol 3 and above
  1268. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  1269. b.serialCons = cons
  1270. return b
  1271. }
  1272. // DefaultTimestamp will enable the with default timestamp flag on the query.
  1273. // If enable, this will replace the server side assigned
  1274. // timestamp as default timestamp. Note that a timestamp in the query itself
  1275. // will still override this timestamp. This is entirely optional.
  1276. //
  1277. // Only available on protocol >= 3
  1278. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  1279. b.defaultTimestamp = enable
  1280. return b
  1281. }
  1282. // WithTimestamp will enable the with default timestamp flag on the query
  1283. // like DefaultTimestamp does. But also allows to define value for timestamp.
  1284. // It works the same way as USING TIMESTAMP in the query itself, but
  1285. // should not break prepared query optimization
  1286. //
  1287. // Only available on protocol >= 3
  1288. func (b *Batch) WithTimestamp(timestamp int64) *Batch {
  1289. b.DefaultTimestamp(true)
  1290. b.defaultTimestampValue = timestamp
  1291. return b
  1292. }
  1293. func (b *Batch) attempt(keyspace string, end, start time.Time, iter *Iter) {
  1294. b.attempts++
  1295. b.totalLatency += end.Sub(start).Nanoseconds()
  1296. // TODO: track latencies per host and things as well instead of just total
  1297. if b.observer == nil {
  1298. return
  1299. }
  1300. statements := make([]string, len(b.Entries))
  1301. for i, entry := range b.Entries {
  1302. statements[i] = entry.Stmt
  1303. }
  1304. b.observer.ObserveBatch(b.context, ObservedBatch{
  1305. Keyspace: keyspace,
  1306. Statements: statements,
  1307. Start: start,
  1308. End: end,
  1309. // Rows not used in batch observations // TODO - might be able to support it when using BatchCAS
  1310. Err: iter.err,
  1311. })
  1312. }
  1313. func (b *Batch) GetRoutingKey() ([]byte, error) {
  1314. // TODO: use the first statement in the batch as the routing key?
  1315. return nil, nil
  1316. }
  1317. type BatchType byte
  1318. const (
  1319. LoggedBatch BatchType = 0
  1320. UnloggedBatch BatchType = 1
  1321. CounterBatch BatchType = 2
  1322. )
  1323. type BatchEntry struct {
  1324. Stmt string
  1325. Args []interface{}
  1326. binding func(q *QueryInfo) ([]interface{}, error)
  1327. }
  1328. type ColumnInfo struct {
  1329. Keyspace string
  1330. Table string
  1331. Name string
  1332. TypeInfo TypeInfo
  1333. }
  1334. func (c ColumnInfo) String() string {
  1335. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  1336. }
  1337. // routing key indexes LRU cache
  1338. type routingKeyInfoLRU struct {
  1339. lru *lru.Cache
  1340. mu sync.Mutex
  1341. }
  1342. type routingKeyInfo struct {
  1343. indexes []int
  1344. types []TypeInfo
  1345. }
  1346. func (r *routingKeyInfo) String() string {
  1347. return fmt.Sprintf("routing key index=%v types=%v", r.indexes, r.types)
  1348. }
  1349. func (r *routingKeyInfoLRU) Remove(key string) {
  1350. r.mu.Lock()
  1351. r.lru.Remove(key)
  1352. r.mu.Unlock()
  1353. }
  1354. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  1355. //the new max is lower than the previous value. Not concurrency safe.
  1356. func (r *routingKeyInfoLRU) Max(max int) {
  1357. r.mu.Lock()
  1358. for r.lru.Len() > max {
  1359. r.lru.RemoveOldest()
  1360. }
  1361. r.lru.MaxEntries = max
  1362. r.mu.Unlock()
  1363. }
  1364. type inflightCachedEntry struct {
  1365. wg sync.WaitGroup
  1366. err error
  1367. value interface{}
  1368. }
  1369. // Tracer is the interface implemented by query tracers. Tracers have the
  1370. // ability to obtain a detailed event log of all events that happened during
  1371. // the execution of a query from Cassandra. Gathering this information might
  1372. // be essential for debugging and optimizing queries, but this feature should
  1373. // not be used on production systems with very high load.
  1374. type Tracer interface {
  1375. Trace(traceId []byte)
  1376. }
  1377. type traceWriter struct {
  1378. session *Session
  1379. w io.Writer
  1380. mu sync.Mutex
  1381. }
  1382. // NewTraceWriter returns a simple Tracer implementation that outputs
  1383. // the event log in a textual format.
  1384. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  1385. return &traceWriter{session: session, w: w}
  1386. }
  1387. func (t *traceWriter) Trace(traceId []byte) {
  1388. var (
  1389. coordinator string
  1390. duration int
  1391. )
  1392. iter := t.session.control.query(`SELECT coordinator, duration
  1393. FROM system_traces.sessions
  1394. WHERE session_id = ?`, traceId)
  1395. iter.Scan(&coordinator, &duration)
  1396. if err := iter.Close(); err != nil {
  1397. t.mu.Lock()
  1398. fmt.Fprintln(t.w, "Error:", err)
  1399. t.mu.Unlock()
  1400. return
  1401. }
  1402. var (
  1403. timestamp time.Time
  1404. activity string
  1405. source string
  1406. elapsed int
  1407. )
  1408. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1409. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1410. t.mu.Lock()
  1411. defer t.mu.Unlock()
  1412. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1413. FROM system_traces.events
  1414. WHERE session_id = ?`, traceId)
  1415. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1416. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1417. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1418. }
  1419. if err := iter.Close(); err != nil {
  1420. fmt.Fprintln(t.w, "Error:", err)
  1421. }
  1422. }
  1423. type ObservedQuery struct {
  1424. Keyspace string
  1425. Statement string
  1426. Start time.Time // time immediately before the query was called
  1427. End time.Time // time immediately after the query returned
  1428. // Rows is the number of rows in the current iter.
  1429. // In paginated queries, rows from previous scans are not counted.
  1430. // Rows is not used in batch queries and remains at the default value
  1431. Rows int
  1432. // Err is the error in the query.
  1433. // It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil error
  1434. Err error
  1435. }
  1436. // QueryObserver is the interface implemented by query observers / stat collectors.
  1437. //
  1438. // Experimental, this interface and use may change
  1439. type QueryObserver interface {
  1440. // ObserveQuery gets called on every query to cassandra, including all queries in an iterator when paging is enabled.
  1441. // It doesn't get called if there is no query because the session is closed or there are no connections available.
  1442. // The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.
  1443. ObserveQuery(context.Context, ObservedQuery)
  1444. }
  1445. type ObservedBatch struct {
  1446. Keyspace string
  1447. Statements []string
  1448. Start time.Time // time immediately before the batch query was called
  1449. End time.Time // time immediately after the batch query returned
  1450. // Err is the error in the batch query.
  1451. // It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil error
  1452. Err error
  1453. }
  1454. // BatchObserver is the interface implemented by batch observers / stat collectors.
  1455. type BatchObserver interface {
  1456. // ObserveBatch gets called on every batch query to cassandra.
  1457. // It also gets called once for each query in a batch.
  1458. // It doesn't get called if there is no query because the session is closed or there are no connections available.
  1459. // The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.
  1460. // Unlike QueryObserver.ObserveQuery it does no reporting on rows read.
  1461. ObserveBatch(context.Context, ObservedBatch)
  1462. }
  1463. type Error struct {
  1464. Code int
  1465. Message string
  1466. }
  1467. func (e Error) Error() string {
  1468. return e.Message
  1469. }
  1470. var (
  1471. ErrNotFound = errors.New("not found")
  1472. ErrUnavailable = errors.New("unavailable")
  1473. ErrUnsupported = errors.New("feature not supported")
  1474. ErrTooManyStmts = errors.New("too many statements")
  1475. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explanation.")
  1476. ErrSessionClosed = errors.New("session has been closed")
  1477. ErrNoConnections = errors.New("gocql: no hosts available in the pool")
  1478. ErrNoKeyspace = errors.New("no keyspace provided")
  1479. ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist")
  1480. ErrNoMetadata = errors.New("no metadata available")
  1481. )
  1482. type ErrProtocol struct{ error }
  1483. func NewErrProtocol(format string, args ...interface{}) error {
  1484. return ErrProtocol{fmt.Errorf(format, args...)}
  1485. }
  1486. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1487. // This limit is set by cassandra and could change in the future.
  1488. const BatchSizeMaximum = 65535