session.go 51 KB

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