session.go 54 KB

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