session.go 42 KB

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