session.go 43 KB

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