session.go 56 KB

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