session.go 47 KB

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