session.go 43 KB

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