session.go 42 KB

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