session.go 44 KB

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