session.go 42 KB

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