session.go 43 KB

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