session.go 42 KB

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