session.go 54 KB

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