session.go 43 KB

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