session.go 42 KB

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