session.go 42 KB

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