session.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047
  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 int
  587. TotalLatency int64
  588. }
  589. type queryMetrics struct {
  590. l sync.RWMutex
  591. m map[string]*hostMetrics
  592. // totalAttempts is total number of attempts.
  593. // Equal to sum of all hostMetrics' Attempts.
  594. totalAttempts int
  595. }
  596. // preFilledQueryMetrics initializes new queryMetrics based on per-host supplied data.
  597. func preFilledQueryMetrics(m map[string]*hostMetrics) *queryMetrics {
  598. qm := &queryMetrics{m: m}
  599. for _, hm := range qm.m {
  600. qm.totalAttempts += hm.Attempts
  601. }
  602. return qm
  603. }
  604. // hostMetricsLocked gets or creates host metrics for given host.
  605. func (qm *queryMetrics) hostMetrics(host *HostInfo) *hostMetrics {
  606. qm.l.Lock()
  607. metrics := qm.hostMetricsLocked(host)
  608. qm.l.Unlock()
  609. return metrics
  610. }
  611. // hostMetricsLocked gets or creates host metrics for given host.
  612. // It must be called only while holding qm.l lock.
  613. func (qm *queryMetrics) hostMetricsLocked(host *HostInfo) *hostMetrics {
  614. metrics, exists := qm.m[host.ConnectAddress().String()]
  615. if !exists {
  616. // if the host is not in the map, it means it's been accessed for the first time
  617. metrics = &hostMetrics{}
  618. qm.m[host.ConnectAddress().String()] = metrics
  619. }
  620. return metrics
  621. }
  622. // attempts returns the number of times the query was executed.
  623. func (qm *queryMetrics) attempts() int {
  624. qm.l.Lock()
  625. attempts := qm.totalAttempts
  626. qm.l.Unlock()
  627. return attempts
  628. }
  629. // addAttempts adds given number of attempts and returns previous total attempts.
  630. func (qm *queryMetrics) addAttempts(i int, host *HostInfo) int {
  631. qm.l.Lock()
  632. hostMetric := qm.hostMetricsLocked(host)
  633. hostMetric.Attempts += i
  634. attempts := qm.totalAttempts
  635. qm.totalAttempts += i
  636. qm.l.Unlock()
  637. return attempts
  638. }
  639. func (qm *queryMetrics) latency() int64 {
  640. qm.l.Lock()
  641. var (
  642. attempts int
  643. latency int64
  644. )
  645. for _, metric := range qm.m {
  646. attempts += metric.Attempts
  647. latency += metric.TotalLatency
  648. }
  649. qm.l.Unlock()
  650. if attempts > 0 {
  651. return latency / int64(attempts)
  652. }
  653. return 0
  654. }
  655. func (qm *queryMetrics) addLatency(l int64, host *HostInfo) {
  656. qm.l.Lock()
  657. hostMetric := qm.hostMetricsLocked(host)
  658. hostMetric.TotalLatency += l
  659. qm.l.Unlock()
  660. }
  661. // Query represents a CQL statement that can be executed.
  662. type Query struct {
  663. stmt string
  664. values []interface{}
  665. cons Consistency
  666. pageSize int
  667. routingKey []byte
  668. pageState []byte
  669. prefetch float64
  670. trace Tracer
  671. observer QueryObserver
  672. session *Session
  673. rt RetryPolicy
  674. spec SpeculativeExecutionPolicy
  675. binding func(q *QueryInfo) ([]interface{}, error)
  676. serialCons SerialConsistency
  677. defaultTimestamp bool
  678. defaultTimestampValue int64
  679. disableSkipMetadata bool
  680. context context.Context
  681. idempotent bool
  682. customPayload map[string][]byte
  683. metrics *queryMetrics
  684. disableAutoPage bool
  685. // getKeyspace is field so that it can be overriden in tests
  686. getKeyspace func() string
  687. // used by control conn queries to prevent triggering a write to systems
  688. // tables in AWS MCS see
  689. skipPrepare bool
  690. }
  691. func (q *Query) defaultsFromSession() {
  692. s := q.session
  693. s.mu.RLock()
  694. q.cons = s.cons
  695. q.pageSize = s.pageSize
  696. q.trace = s.trace
  697. q.observer = s.queryObserver
  698. q.prefetch = s.prefetch
  699. q.rt = s.cfg.RetryPolicy
  700. q.serialCons = s.cfg.SerialConsistency
  701. q.defaultTimestamp = s.cfg.DefaultTimestamp
  702. q.idempotent = s.cfg.DefaultIdempotence
  703. q.metrics = &queryMetrics{m: make(map[string]*hostMetrics)}
  704. q.spec = &NonSpeculativeExecution{}
  705. s.mu.RUnlock()
  706. }
  707. // Statement returns the statement that was used to generate this query.
  708. func (q Query) Statement() string {
  709. return q.stmt
  710. }
  711. // String implements the stringer interface.
  712. func (q Query) String() string {
  713. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  714. }
  715. //Attempts returns the number of times the query was executed.
  716. func (q *Query) Attempts() int {
  717. return q.metrics.attempts()
  718. }
  719. func (q *Query) AddAttempts(i int, host *HostInfo) {
  720. q.metrics.addAttempts(i, host)
  721. }
  722. //Latency returns the average amount of nanoseconds per attempt of the query.
  723. func (q *Query) Latency() int64 {
  724. return q.metrics.latency()
  725. }
  726. func (q *Query) AddLatency(l int64, host *HostInfo) {
  727. q.metrics.addLatency(l, host)
  728. }
  729. // Consistency sets the consistency level for this query. If no consistency
  730. // level have been set, the default consistency level of the cluster
  731. // is used.
  732. func (q *Query) Consistency(c Consistency) *Query {
  733. q.cons = c
  734. return q
  735. }
  736. // GetConsistency returns the currently configured consistency level for
  737. // the query.
  738. func (q *Query) GetConsistency() Consistency {
  739. return q.cons
  740. }
  741. // Same as Consistency but without a return value
  742. func (q *Query) SetConsistency(c Consistency) {
  743. q.cons = c
  744. }
  745. // CustomPayload sets the custom payload level for this query.
  746. func (q *Query) CustomPayload(customPayload map[string][]byte) *Query {
  747. q.customPayload = customPayload
  748. return q
  749. }
  750. func (q *Query) Context() context.Context {
  751. if q.context == nil {
  752. return context.Background()
  753. }
  754. return q.context
  755. }
  756. // Trace enables tracing of this query. Look at the documentation of the
  757. // Tracer interface to learn more about tracing.
  758. func (q *Query) Trace(trace Tracer) *Query {
  759. q.trace = trace
  760. return q
  761. }
  762. // Observer enables query-level observer on this query.
  763. // The provided observer will be called every time this query is executed.
  764. func (q *Query) Observer(observer QueryObserver) *Query {
  765. q.observer = observer
  766. return q
  767. }
  768. // PageSize will tell the iterator to fetch the result in pages of size n.
  769. // This is useful for iterating over large result sets, but setting the
  770. // page size too low might decrease the performance. This feature is only
  771. // available in Cassandra 2 and onwards.
  772. func (q *Query) PageSize(n int) *Query {
  773. q.pageSize = n
  774. return q
  775. }
  776. // DefaultTimestamp will enable the with default timestamp flag on the query.
  777. // If enable, this will replace the server side assigned
  778. // timestamp as default timestamp. Note that a timestamp in the query itself
  779. // will still override this timestamp. This is entirely optional.
  780. //
  781. // Only available on protocol >= 3
  782. func (q *Query) DefaultTimestamp(enable bool) *Query {
  783. q.defaultTimestamp = enable
  784. return q
  785. }
  786. // WithTimestamp will enable the with default timestamp flag on the query
  787. // like DefaultTimestamp does. But also allows to define value for timestamp.
  788. // It works the same way as USING TIMESTAMP in the query itself, but
  789. // should not break prepared query optimization
  790. //
  791. // Only available on protocol >= 3
  792. func (q *Query) WithTimestamp(timestamp int64) *Query {
  793. q.DefaultTimestamp(true)
  794. q.defaultTimestampValue = timestamp
  795. return q
  796. }
  797. // RoutingKey sets the routing key to use when a token aware connection
  798. // pool is used to optimize the routing of this query.
  799. func (q *Query) RoutingKey(routingKey []byte) *Query {
  800. q.routingKey = routingKey
  801. return q
  802. }
  803. func (q *Query) withContext(ctx context.Context) ExecutableQuery {
  804. // I really wish go had covariant types
  805. return q.WithContext(ctx)
  806. }
  807. // WithContext returns a shallow copy of q with its context
  808. // set to ctx.
  809. //
  810. // The provided context controls the entire lifetime of executing a
  811. // query, queries will be canceled and return once the context is
  812. // canceled.
  813. func (q *Query) WithContext(ctx context.Context) *Query {
  814. q2 := *q
  815. q2.context = ctx
  816. return &q2
  817. }
  818. // Deprecate: does nothing, cancel the context passed to WithContext
  819. func (q *Query) Cancel() {
  820. // TODO: delete
  821. }
  822. func (q *Query) execute(ctx context.Context, conn *Conn) *Iter {
  823. return conn.executeQuery(ctx, q)
  824. }
  825. func (q *Query) attempt(keyspace string, end, start time.Time, iter *Iter, host *HostInfo) {
  826. attempt := q.metrics.addAttempts(1, host)
  827. q.AddLatency(end.Sub(start).Nanoseconds(), host)
  828. if q.observer != nil {
  829. q.observer.ObserveQuery(q.Context(), ObservedQuery{
  830. Keyspace: keyspace,
  831. Statement: q.stmt,
  832. Start: start,
  833. End: end,
  834. Rows: iter.numRows,
  835. Host: host,
  836. Metrics: q.metrics.hostMetrics(host),
  837. Err: iter.err,
  838. Attempt: attempt,
  839. })
  840. }
  841. }
  842. func (q *Query) retryPolicy() RetryPolicy {
  843. return q.rt
  844. }
  845. // Keyspace returns the keyspace the query will be executed against.
  846. func (q *Query) Keyspace() string {
  847. if q.getKeyspace != nil {
  848. return q.getKeyspace()
  849. }
  850. if q.session == nil {
  851. return ""
  852. }
  853. // TODO(chbannis): this should be parsed from the query or we should let
  854. // this be set by users.
  855. return q.session.cfg.Keyspace
  856. }
  857. // GetRoutingKey gets the routing key to use for routing this query. If
  858. // a routing key has not been explicitly set, then the routing key will
  859. // be constructed if possible using the keyspace's schema and the query
  860. // info for this query statement. If the routing key cannot be determined
  861. // then nil will be returned with no error. On any error condition,
  862. // an error description will be returned.
  863. func (q *Query) GetRoutingKey() ([]byte, error) {
  864. if q.routingKey != nil {
  865. return q.routingKey, nil
  866. } else if q.binding != nil && len(q.values) == 0 {
  867. // If this query was created using session.Bind we wont have the query
  868. // values yet, so we have to pass down to the next policy.
  869. // TODO: Remove this and handle this case
  870. return nil, nil
  871. }
  872. // try to determine the routing key
  873. routingKeyInfo, err := q.session.routingKeyInfo(q.Context(), q.stmt)
  874. if err != nil {
  875. return nil, err
  876. }
  877. return createRoutingKey(routingKeyInfo, q.values)
  878. }
  879. func (q *Query) shouldPrepare() bool {
  880. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  881. return unicode.IsSpace(r) || r == ';'
  882. }), unicode.IsSpace)
  883. var stmtType string
  884. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  885. stmtType = strings.ToLower(stmt[:n])
  886. }
  887. if stmtType == "begin" {
  888. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  889. stmtType = strings.ToLower(stmt[n+1:])
  890. }
  891. }
  892. switch stmtType {
  893. case "select", "insert", "update", "delete", "batch":
  894. return true
  895. }
  896. return false
  897. }
  898. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  899. // there are only p*pageSize rows remaining, the next page will be requested
  900. // automatically.
  901. func (q *Query) Prefetch(p float64) *Query {
  902. q.prefetch = p
  903. return q
  904. }
  905. // RetryPolicy sets the policy to use when retrying the query.
  906. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  907. q.rt = r
  908. return q
  909. }
  910. // SetSpeculativeExecutionPolicy sets the execution policy
  911. func (q *Query) SetSpeculativeExecutionPolicy(sp SpeculativeExecutionPolicy) *Query {
  912. q.spec = sp
  913. return q
  914. }
  915. // speculativeExecutionPolicy fetches the policy
  916. func (q *Query) speculativeExecutionPolicy() SpeculativeExecutionPolicy {
  917. return q.spec
  918. }
  919. func (q *Query) IsIdempotent() bool {
  920. return q.idempotent
  921. }
  922. // Idempotent marks the query as being idempotent or not depending on
  923. // the value.
  924. func (q *Query) Idempotent(value bool) *Query {
  925. q.idempotent = value
  926. return q
  927. }
  928. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  929. // to an existing query instance.
  930. func (q *Query) Bind(v ...interface{}) *Query {
  931. q.values = v
  932. q.pageState = nil
  933. return q
  934. }
  935. // SerialConsistency sets the consistency level for the
  936. // serial phase of conditional updates. That consistency can only be
  937. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  938. // SERIAL. This option will be ignored for anything else that a
  939. // conditional update/insert.
  940. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  941. q.serialCons = cons
  942. return q
  943. }
  944. // PageState sets the paging state for the query to resume paging from a specific
  945. // point in time. Setting this will disable to query paging for this query, and
  946. // must be used for all subsequent pages.
  947. func (q *Query) PageState(state []byte) *Query {
  948. q.pageState = state
  949. q.disableAutoPage = true
  950. return q
  951. }
  952. // NoSkipMetadata will override the internal result metadata cache so that the driver does not
  953. // send skip_metadata for queries, this means that the result will always contain
  954. // the metadata to parse the rows and will not reuse the metadata from the prepared
  955. // staement. This should only be used to work around cassandra bugs, such as when using
  956. // CAS operations which do not end in Cas.
  957. //
  958. // See https://issues.apache.org/jira/browse/CASSANDRA-11099
  959. // https://github.com/gocql/gocql/issues/612
  960. func (q *Query) NoSkipMetadata() *Query {
  961. q.disableSkipMetadata = true
  962. return q
  963. }
  964. // Exec executes the query without returning any rows.
  965. func (q *Query) Exec() error {
  966. return q.Iter().Close()
  967. }
  968. func isUseStatement(stmt string) bool {
  969. if len(stmt) < 3 {
  970. return false
  971. }
  972. return strings.EqualFold(stmt[0:3], "use")
  973. }
  974. // Iter executes the query and returns an iterator capable of iterating
  975. // over all results.
  976. func (q *Query) Iter() *Iter {
  977. if isUseStatement(q.stmt) {
  978. return &Iter{err: ErrUseStmt}
  979. }
  980. return q.session.executeQuery(q)
  981. }
  982. // MapScan executes the query, copies the columns of the first selected
  983. // row into the map pointed at by m and discards the rest. If no rows
  984. // were selected, ErrNotFound is returned.
  985. func (q *Query) MapScan(m map[string]interface{}) error {
  986. iter := q.Iter()
  987. if err := iter.checkErrAndNotFound(); err != nil {
  988. return err
  989. }
  990. iter.MapScan(m)
  991. return iter.Close()
  992. }
  993. // Scan executes the query, copies the columns of the first selected
  994. // row into the values pointed at by dest and discards the rest. If no rows
  995. // were selected, ErrNotFound is returned.
  996. func (q *Query) Scan(dest ...interface{}) error {
  997. iter := q.Iter()
  998. if err := iter.checkErrAndNotFound(); err != nil {
  999. return err
  1000. }
  1001. iter.Scan(dest...)
  1002. return iter.Close()
  1003. }
  1004. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  1005. // statement containing an IF clause). If the transaction fails because
  1006. // the existing values did not match, the previous values will be stored
  1007. // in dest.
  1008. func (q *Query) ScanCAS(dest ...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. if len(iter.Columns()) > 1 {
  1015. dest = append([]interface{}{&applied}, dest...)
  1016. iter.Scan(dest...)
  1017. } else {
  1018. iter.Scan(&applied)
  1019. }
  1020. return applied, iter.Close()
  1021. }
  1022. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  1023. // statement containing an IF clause). If the transaction fails because
  1024. // the existing values did not match, the previous values will be stored
  1025. // in dest map.
  1026. //
  1027. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  1028. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  1029. // column mismatching. MapScanCAS is added to capture them safely.
  1030. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  1031. q.disableSkipMetadata = true
  1032. iter := q.Iter()
  1033. if err := iter.checkErrAndNotFound(); err != nil {
  1034. return false, err
  1035. }
  1036. iter.MapScan(dest)
  1037. applied = dest["[applied]"].(bool)
  1038. delete(dest, "[applied]")
  1039. return applied, iter.Close()
  1040. }
  1041. // Release releases a query back into a pool of queries. Released Queries
  1042. // cannot be reused.
  1043. //
  1044. // Example:
  1045. // qry := session.Query("SELECT * FROM my_table")
  1046. // qry.Exec()
  1047. // qry.Release()
  1048. func (q *Query) Release() {
  1049. q.reset()
  1050. queryPool.Put(q)
  1051. }
  1052. // reset zeroes out all fields of a query so that it can be safely pooled.
  1053. func (q *Query) reset() {
  1054. *q = Query{}
  1055. }
  1056. // Iter represents an iterator that can be used to iterate over all rows that
  1057. // were returned by a query. The iterator might send additional queries to the
  1058. // database during the iteration if paging was enabled.
  1059. type Iter struct {
  1060. err error
  1061. pos int
  1062. meta resultMetadata
  1063. numRows int
  1064. next *nextIter
  1065. host *HostInfo
  1066. framer *framer
  1067. closed int32
  1068. }
  1069. // Host returns the host which the query was sent to.
  1070. func (iter *Iter) Host() *HostInfo {
  1071. return iter.host
  1072. }
  1073. // Columns returns the name and type of the selected columns.
  1074. func (iter *Iter) Columns() []ColumnInfo {
  1075. return iter.meta.columns
  1076. }
  1077. type Scanner interface {
  1078. // Next advances the row pointer to point at the next row, the row is valid until
  1079. // the next call of Next. It returns true if there is a row which is available to be
  1080. // scanned into with Scan.
  1081. // Next must be called before every call to Scan.
  1082. Next() bool
  1083. // Scan copies the current row's columns into dest. If the length of dest does not equal
  1084. // the number of columns returned in the row an error is returned. If an error is encountered
  1085. // when unmarshalling a column into the value in dest an error is returned and the row is invalidated
  1086. // until the next call to Next.
  1087. // Next must be called before calling Scan, if it is not an error is returned.
  1088. Scan(...interface{}) error
  1089. // Err returns the if there was one during iteration that resulted in iteration being unable to complete.
  1090. // Err will also release resources held by the iterator, the Scanner should not used after being called.
  1091. Err() error
  1092. }
  1093. type iterScanner struct {
  1094. iter *Iter
  1095. cols [][]byte
  1096. valid bool
  1097. }
  1098. func (is *iterScanner) Next() bool {
  1099. iter := is.iter
  1100. if iter.err != nil {
  1101. return false
  1102. }
  1103. if iter.pos >= iter.numRows {
  1104. if iter.next != nil {
  1105. is.iter = iter.next.fetch()
  1106. return is.Next()
  1107. }
  1108. return false
  1109. }
  1110. for i := 0; i < len(is.cols); i++ {
  1111. col, err := iter.readColumn()
  1112. if err != nil {
  1113. iter.err = err
  1114. return false
  1115. }
  1116. is.cols[i] = col
  1117. }
  1118. iter.pos++
  1119. is.valid = true
  1120. return true
  1121. }
  1122. func scanColumn(p []byte, col ColumnInfo, dest []interface{}) (int, error) {
  1123. if dest[0] == nil {
  1124. return 1, nil
  1125. }
  1126. if col.TypeInfo.Type() == TypeTuple {
  1127. // this will panic, actually a bug, please report
  1128. tuple := col.TypeInfo.(TupleTypeInfo)
  1129. count := len(tuple.Elems)
  1130. // here we pass in a slice of the struct which has the number number of
  1131. // values as elements in the tuple
  1132. if err := Unmarshal(col.TypeInfo, p, dest[:count]); err != nil {
  1133. return 0, err
  1134. }
  1135. return count, nil
  1136. } else {
  1137. if err := Unmarshal(col.TypeInfo, p, dest[0]); err != nil {
  1138. return 0, err
  1139. }
  1140. return 1, nil
  1141. }
  1142. }
  1143. func (is *iterScanner) Scan(dest ...interface{}) error {
  1144. if !is.valid {
  1145. return errors.New("gocql: Scan called without calling Next")
  1146. }
  1147. iter := is.iter
  1148. // currently only support scanning into an expand tuple, such that its the same
  1149. // as scanning in more values from a single column
  1150. if len(dest) != iter.meta.actualColCount {
  1151. return fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  1152. }
  1153. // i is the current position in dest, could posible replace it and just use
  1154. // slices of dest
  1155. i := 0
  1156. var err error
  1157. for _, col := range iter.meta.columns {
  1158. var n int
  1159. n, err = scanColumn(is.cols[i], col, dest[i:])
  1160. if err != nil {
  1161. break
  1162. }
  1163. i += n
  1164. }
  1165. is.valid = false
  1166. return err
  1167. }
  1168. func (is *iterScanner) Err() error {
  1169. iter := is.iter
  1170. is.iter = nil
  1171. is.cols = nil
  1172. is.valid = false
  1173. return iter.Close()
  1174. }
  1175. // Scanner returns a row Scanner which provides an interface to scan rows in a manner which is
  1176. // similar to database/sql. The iter should NOT be used again after calling this method.
  1177. func (iter *Iter) Scanner() Scanner {
  1178. if iter == nil {
  1179. return nil
  1180. }
  1181. return &iterScanner{iter: iter, cols: make([][]byte, len(iter.meta.columns))}
  1182. }
  1183. func (iter *Iter) readColumn() ([]byte, error) {
  1184. return iter.framer.readBytesInternal()
  1185. }
  1186. // Scan consumes the next row of the iterator and copies the columns of the
  1187. // current row into the values pointed at by dest. Use nil as a dest value
  1188. // to skip the corresponding column. Scan might send additional queries
  1189. // to the database to retrieve the next set of rows if paging was enabled.
  1190. //
  1191. // Scan returns true if the row was successfully unmarshaled or false if the
  1192. // end of the result set was reached or if an error occurred. Close should
  1193. // be called afterwards to retrieve any potential errors.
  1194. func (iter *Iter) Scan(dest ...interface{}) bool {
  1195. if iter.err != nil {
  1196. return false
  1197. }
  1198. if iter.pos >= iter.numRows {
  1199. if iter.next != nil {
  1200. *iter = *iter.next.fetch()
  1201. return iter.Scan(dest...)
  1202. }
  1203. return false
  1204. }
  1205. if iter.next != nil && iter.pos >= iter.next.pos {
  1206. go iter.next.fetch()
  1207. }
  1208. // currently only support scanning into an expand tuple, such that its the same
  1209. // as scanning in more values from a single column
  1210. if len(dest) != iter.meta.actualColCount {
  1211. iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  1212. return false
  1213. }
  1214. // i is the current position in dest, could posible replace it and just use
  1215. // slices of dest
  1216. i := 0
  1217. for _, col := range iter.meta.columns {
  1218. colBytes, err := iter.readColumn()
  1219. if err != nil {
  1220. iter.err = err
  1221. return false
  1222. }
  1223. n, err := scanColumn(colBytes, col, dest[i:])
  1224. if err != nil {
  1225. iter.err = err
  1226. return false
  1227. }
  1228. i += n
  1229. }
  1230. iter.pos++
  1231. return true
  1232. }
  1233. // GetCustomPayload returns any parsed custom payload results if given in the
  1234. // response from Cassandra. Note that the result is not a copy.
  1235. //
  1236. // This additional feature of CQL Protocol v4
  1237. // allows additional results and query information to be returned by
  1238. // custom QueryHandlers running in your C* cluster.
  1239. // See https://datastax.github.io/java-driver/manual/custom_payloads/
  1240. func (iter *Iter) GetCustomPayload() map[string][]byte {
  1241. return iter.framer.customPayload
  1242. }
  1243. // Warnings returns any warnings generated if given in the response from Cassandra.
  1244. //
  1245. // This is only available starting with CQL Protocol v4.
  1246. func (iter *Iter) Warnings() []string {
  1247. if iter.framer != nil {
  1248. return iter.framer.header.warnings
  1249. }
  1250. return nil
  1251. }
  1252. // Close closes the iterator and returns any errors that happened during
  1253. // the query or the iteration.
  1254. func (iter *Iter) Close() error {
  1255. if atomic.CompareAndSwapInt32(&iter.closed, 0, 1) {
  1256. if iter.framer != nil {
  1257. iter.framer = nil
  1258. }
  1259. }
  1260. return iter.err
  1261. }
  1262. // WillSwitchPage detects if iterator reached end of current page
  1263. // and the next page is available.
  1264. func (iter *Iter) WillSwitchPage() bool {
  1265. return iter.pos >= iter.numRows && iter.next != nil
  1266. }
  1267. // checkErrAndNotFound handle error and NotFound in one method.
  1268. func (iter *Iter) checkErrAndNotFound() error {
  1269. if iter.err != nil {
  1270. return iter.err
  1271. } else if iter.numRows == 0 {
  1272. return ErrNotFound
  1273. }
  1274. return nil
  1275. }
  1276. // PageState return the current paging state for a query which can be used for
  1277. // subsequent queries to resume paging this point.
  1278. func (iter *Iter) PageState() []byte {
  1279. return iter.meta.pagingState
  1280. }
  1281. // NumRows returns the number of rows in this pagination, it will update when new
  1282. // pages are fetched, it is not the value of the total number of rows this iter
  1283. // will return unless there is only a single page returned.
  1284. func (iter *Iter) NumRows() int {
  1285. return iter.numRows
  1286. }
  1287. type nextIter struct {
  1288. qry *Query
  1289. pos int
  1290. once sync.Once
  1291. next *Iter
  1292. }
  1293. func (n *nextIter) fetch() *Iter {
  1294. n.once.Do(func() {
  1295. n.next = n.qry.session.executeQuery(n.qry)
  1296. })
  1297. return n.next
  1298. }
  1299. type Batch struct {
  1300. Type BatchType
  1301. Entries []BatchEntry
  1302. Cons Consistency
  1303. routingKey []byte
  1304. routingKeyBuffer []byte
  1305. CustomPayload map[string][]byte
  1306. rt RetryPolicy
  1307. spec SpeculativeExecutionPolicy
  1308. observer BatchObserver
  1309. session *Session
  1310. serialCons SerialConsistency
  1311. defaultTimestamp bool
  1312. defaultTimestampValue int64
  1313. context context.Context
  1314. cancelBatch func()
  1315. keyspace string
  1316. metrics *queryMetrics
  1317. }
  1318. // NewBatch creates a new batch operation without defaults from the cluster
  1319. //
  1320. // Deprecated: use session.NewBatch instead
  1321. func NewBatch(typ BatchType) *Batch {
  1322. return &Batch{
  1323. Type: typ,
  1324. metrics: &queryMetrics{m: make(map[string]*hostMetrics)},
  1325. spec: &NonSpeculativeExecution{},
  1326. }
  1327. }
  1328. // NewBatch creates a new batch operation using defaults defined in the cluster
  1329. func (s *Session) NewBatch(typ BatchType) *Batch {
  1330. s.mu.RLock()
  1331. batch := &Batch{
  1332. Type: typ,
  1333. rt: s.cfg.RetryPolicy,
  1334. serialCons: s.cfg.SerialConsistency,
  1335. observer: s.batchObserver,
  1336. session: s,
  1337. Cons: s.cons,
  1338. defaultTimestamp: s.cfg.DefaultTimestamp,
  1339. keyspace: s.cfg.Keyspace,
  1340. metrics: &queryMetrics{m: make(map[string]*hostMetrics)},
  1341. spec: &NonSpeculativeExecution{},
  1342. }
  1343. s.mu.RUnlock()
  1344. return batch
  1345. }
  1346. // Observer enables batch-level observer on this batch.
  1347. // The provided observer will be called every time this batched query is executed.
  1348. func (b *Batch) Observer(observer BatchObserver) *Batch {
  1349. b.observer = observer
  1350. return b
  1351. }
  1352. func (b *Batch) Keyspace() string {
  1353. return b.keyspace
  1354. }
  1355. // Attempts returns the number of attempts made to execute the batch.
  1356. func (b *Batch) Attempts() int {
  1357. return b.metrics.attempts()
  1358. }
  1359. func (b *Batch) AddAttempts(i int, host *HostInfo) {
  1360. b.metrics.addAttempts(i, host)
  1361. }
  1362. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  1363. func (b *Batch) Latency() int64 {
  1364. return b.metrics.latency()
  1365. }
  1366. func (b *Batch) AddLatency(l int64, host *HostInfo) {
  1367. b.metrics.addLatency(l, host)
  1368. }
  1369. // GetConsistency returns the currently configured consistency level for the batch
  1370. // operation.
  1371. func (b *Batch) GetConsistency() Consistency {
  1372. return b.Cons
  1373. }
  1374. // SetConsistency sets the currently configured consistency level for the batch
  1375. // operation.
  1376. func (b *Batch) SetConsistency(c Consistency) {
  1377. b.Cons = c
  1378. }
  1379. func (b *Batch) Context() context.Context {
  1380. if b.context == nil {
  1381. return context.Background()
  1382. }
  1383. return b.context
  1384. }
  1385. func (b *Batch) IsIdempotent() bool {
  1386. for _, entry := range b.Entries {
  1387. if !entry.Idempotent {
  1388. return false
  1389. }
  1390. }
  1391. return true
  1392. }
  1393. func (b *Batch) speculativeExecutionPolicy() SpeculativeExecutionPolicy {
  1394. return b.spec
  1395. }
  1396. func (b *Batch) SpeculativeExecutionPolicy(sp SpeculativeExecutionPolicy) *Batch {
  1397. b.spec = sp
  1398. return b
  1399. }
  1400. // Query adds the query to the batch operation
  1401. func (b *Batch) Query(stmt string, args ...interface{}) {
  1402. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  1403. }
  1404. // Bind adds the query to the batch operation and correlates it with a binding callback
  1405. // that will be invoked when the batch is executed. The binding callback allows the application
  1406. // to define which query argument values will be marshalled as part of the batch execution.
  1407. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  1408. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  1409. }
  1410. func (b *Batch) retryPolicy() RetryPolicy {
  1411. return b.rt
  1412. }
  1413. // RetryPolicy sets the retry policy to use when executing the batch operation
  1414. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  1415. b.rt = r
  1416. return b
  1417. }
  1418. func (b *Batch) withContext(ctx context.Context) ExecutableQuery {
  1419. return b.WithContext(ctx)
  1420. }
  1421. // WithContext returns a shallow copy of b with its context
  1422. // set to ctx.
  1423. //
  1424. // The provided context controls the entire lifetime of executing a
  1425. // query, queries will be canceled and return once the context is
  1426. // canceled.
  1427. func (b *Batch) WithContext(ctx context.Context) *Batch {
  1428. b2 := *b
  1429. b2.context = ctx
  1430. return &b2
  1431. }
  1432. // Deprecate: does nothing, cancel the context passed to WithContext
  1433. func (*Batch) Cancel() {
  1434. // TODO: delete
  1435. }
  1436. // Size returns the number of batch statements to be executed by the batch operation.
  1437. func (b *Batch) Size() int {
  1438. return len(b.Entries)
  1439. }
  1440. // SerialConsistency sets the consistency level for the
  1441. // serial phase of conditional updates. That consistency can only be
  1442. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  1443. // SERIAL. This option will be ignored for anything else that a
  1444. // conditional update/insert.
  1445. //
  1446. // Only available for protocol 3 and above
  1447. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  1448. b.serialCons = cons
  1449. return b
  1450. }
  1451. // DefaultTimestamp will enable the with default timestamp flag on the query.
  1452. // If enable, this will replace the server side assigned
  1453. // timestamp as default timestamp. Note that a timestamp in the query itself
  1454. // will still override this timestamp. This is entirely optional.
  1455. //
  1456. // Only available on protocol >= 3
  1457. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  1458. b.defaultTimestamp = enable
  1459. return b
  1460. }
  1461. // WithTimestamp will enable the with default timestamp flag on the query
  1462. // like DefaultTimestamp does. But also allows to define value for timestamp.
  1463. // It works the same way as USING TIMESTAMP in the query itself, but
  1464. // should not break prepared query optimization
  1465. //
  1466. // Only available on protocol >= 3
  1467. func (b *Batch) WithTimestamp(timestamp int64) *Batch {
  1468. b.DefaultTimestamp(true)
  1469. b.defaultTimestampValue = timestamp
  1470. return b
  1471. }
  1472. func (b *Batch) attempt(keyspace string, end, start time.Time, iter *Iter, host *HostInfo) {
  1473. b.AddAttempts(1, host)
  1474. b.AddLatency(end.Sub(start).Nanoseconds(), host)
  1475. if b.observer == nil {
  1476. return
  1477. }
  1478. statements := make([]string, len(b.Entries))
  1479. for i, entry := range b.Entries {
  1480. statements[i] = entry.Stmt
  1481. }
  1482. b.observer.ObserveBatch(b.Context(), ObservedBatch{
  1483. Keyspace: keyspace,
  1484. Statements: statements,
  1485. Start: start,
  1486. End: end,
  1487. // Rows not used in batch observations // TODO - might be able to support it when using BatchCAS
  1488. Host: host,
  1489. Metrics: b.metrics.hostMetrics(host),
  1490. Err: iter.err,
  1491. })
  1492. }
  1493. func (b *Batch) GetRoutingKey() ([]byte, error) {
  1494. if b.routingKey != nil {
  1495. return b.routingKey, nil
  1496. }
  1497. if len(b.Entries) == 0 {
  1498. return nil, nil
  1499. }
  1500. entry := b.Entries[0]
  1501. if entry.binding != nil {
  1502. // bindings do not have the values let's skip it like Query does.
  1503. return nil, nil
  1504. }
  1505. // try to determine the routing key
  1506. routingKeyInfo, err := b.session.routingKeyInfo(b.Context(), entry.Stmt)
  1507. if err != nil {
  1508. return nil, err
  1509. }
  1510. return createRoutingKey(routingKeyInfo, entry.Args)
  1511. }
  1512. func createRoutingKey(routingKeyInfo *routingKeyInfo, values []interface{}) ([]byte, error) {
  1513. if routingKeyInfo == nil {
  1514. return nil, nil
  1515. }
  1516. if len(routingKeyInfo.indexes) == 1 {
  1517. // single column routing key
  1518. routingKey, err := Marshal(
  1519. routingKeyInfo.types[0],
  1520. values[routingKeyInfo.indexes[0]],
  1521. )
  1522. if err != nil {
  1523. return nil, err
  1524. }
  1525. return routingKey, nil
  1526. }
  1527. // composite routing key
  1528. buf := bytes.NewBuffer(make([]byte, 0, 256))
  1529. for i := range routingKeyInfo.indexes {
  1530. encoded, err := Marshal(
  1531. routingKeyInfo.types[i],
  1532. values[routingKeyInfo.indexes[i]],
  1533. )
  1534. if err != nil {
  1535. return nil, err
  1536. }
  1537. lenBuf := []byte{0x00, 0x00}
  1538. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  1539. buf.Write(lenBuf)
  1540. buf.Write(encoded)
  1541. buf.WriteByte(0x00)
  1542. }
  1543. routingKey := buf.Bytes()
  1544. return routingKey, nil
  1545. }
  1546. type BatchType byte
  1547. const (
  1548. LoggedBatch BatchType = 0
  1549. UnloggedBatch BatchType = 1
  1550. CounterBatch BatchType = 2
  1551. )
  1552. type BatchEntry struct {
  1553. Stmt string
  1554. Args []interface{}
  1555. Idempotent bool
  1556. binding func(q *QueryInfo) ([]interface{}, error)
  1557. }
  1558. type ColumnInfo struct {
  1559. Keyspace string
  1560. Table string
  1561. Name string
  1562. TypeInfo TypeInfo
  1563. }
  1564. func (c ColumnInfo) String() string {
  1565. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  1566. }
  1567. // routing key indexes LRU cache
  1568. type routingKeyInfoLRU struct {
  1569. lru *lru.Cache
  1570. mu sync.Mutex
  1571. }
  1572. type routingKeyInfo struct {
  1573. indexes []int
  1574. types []TypeInfo
  1575. }
  1576. func (r *routingKeyInfo) String() string {
  1577. return fmt.Sprintf("routing key index=%v types=%v", r.indexes, r.types)
  1578. }
  1579. func (r *routingKeyInfoLRU) Remove(key string) {
  1580. r.mu.Lock()
  1581. r.lru.Remove(key)
  1582. r.mu.Unlock()
  1583. }
  1584. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  1585. //the new max is lower than the previous value. Not concurrency safe.
  1586. func (r *routingKeyInfoLRU) Max(max int) {
  1587. r.mu.Lock()
  1588. for r.lru.Len() > max {
  1589. r.lru.RemoveOldest()
  1590. }
  1591. r.lru.MaxEntries = max
  1592. r.mu.Unlock()
  1593. }
  1594. type inflightCachedEntry struct {
  1595. wg sync.WaitGroup
  1596. err error
  1597. value interface{}
  1598. }
  1599. // Tracer is the interface implemented by query tracers. Tracers have the
  1600. // ability to obtain a detailed event log of all events that happened during
  1601. // the execution of a query from Cassandra. Gathering this information might
  1602. // be essential for debugging and optimizing queries, but this feature should
  1603. // not be used on production systems with very high load.
  1604. type Tracer interface {
  1605. Trace(traceId []byte)
  1606. }
  1607. type traceWriter struct {
  1608. session *Session
  1609. w io.Writer
  1610. mu sync.Mutex
  1611. }
  1612. // NewTraceWriter returns a simple Tracer implementation that outputs
  1613. // the event log in a textual format.
  1614. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  1615. return &traceWriter{session: session, w: w}
  1616. }
  1617. func (t *traceWriter) Trace(traceId []byte) {
  1618. var (
  1619. coordinator string
  1620. duration int
  1621. )
  1622. iter := t.session.control.query(`SELECT coordinator, duration
  1623. FROM system_traces.sessions
  1624. WHERE session_id = ?`, traceId)
  1625. iter.Scan(&coordinator, &duration)
  1626. if err := iter.Close(); err != nil {
  1627. t.mu.Lock()
  1628. fmt.Fprintln(t.w, "Error:", err)
  1629. t.mu.Unlock()
  1630. return
  1631. }
  1632. var (
  1633. timestamp time.Time
  1634. activity string
  1635. source string
  1636. elapsed int
  1637. )
  1638. t.mu.Lock()
  1639. defer t.mu.Unlock()
  1640. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1641. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1642. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1643. FROM system_traces.events
  1644. WHERE session_id = ?`, traceId)
  1645. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1646. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1647. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1648. }
  1649. if err := iter.Close(); err != nil {
  1650. fmt.Fprintln(t.w, "Error:", err)
  1651. }
  1652. }
  1653. type ObservedQuery struct {
  1654. Keyspace string
  1655. Statement string
  1656. Start time.Time // time immediately before the query was called
  1657. End time.Time // time immediately after the query returned
  1658. // Rows is the number of rows in the current iter.
  1659. // In paginated queries, rows from previous scans are not counted.
  1660. // Rows is not used in batch queries and remains at the default value
  1661. Rows int
  1662. // Host is the informations about the host that performed the query
  1663. Host *HostInfo
  1664. // The metrics per this host
  1665. Metrics *hostMetrics
  1666. // Err is the error in the query.
  1667. // It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil error
  1668. Err error
  1669. // Attempt is the index of attempt at executing this query.
  1670. // The first attempt is number zero and any retries have non-zero attempt number.
  1671. Attempt int
  1672. }
  1673. // QueryObserver is the interface implemented by query observers / stat collectors.
  1674. //
  1675. // Experimental, this interface and use may change
  1676. type QueryObserver interface {
  1677. // ObserveQuery gets called on every query to cassandra, including all queries in an iterator when paging is enabled.
  1678. // It doesn't get called if there is no query because the session is closed or there are no connections available.
  1679. // The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.
  1680. ObserveQuery(context.Context, ObservedQuery)
  1681. }
  1682. type ObservedBatch struct {
  1683. Keyspace string
  1684. Statements []string
  1685. Start time.Time // time immediately before the batch query was called
  1686. End time.Time // time immediately after the batch query returned
  1687. // Host is the informations about the host that performed the batch
  1688. Host *HostInfo
  1689. // Err is the error in the batch query.
  1690. // It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil error
  1691. Err error
  1692. // The metrics per this host
  1693. Metrics *hostMetrics
  1694. }
  1695. // BatchObserver is the interface implemented by batch observers / stat collectors.
  1696. type BatchObserver interface {
  1697. // ObserveBatch gets called on every batch query to cassandra.
  1698. // It also gets called once for each query in a batch.
  1699. // It doesn't get called if there is no query because the session is closed or there are no connections available.
  1700. // The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.
  1701. // Unlike QueryObserver.ObserveQuery it does no reporting on rows read.
  1702. ObserveBatch(context.Context, ObservedBatch)
  1703. }
  1704. type ObservedConnect struct {
  1705. // Host is the information about the host about to connect
  1706. Host *HostInfo
  1707. Start time.Time // time immediately before the dial is called
  1708. End time.Time // time immediately after the dial returned
  1709. // Err is the connection error (if any)
  1710. Err error
  1711. }
  1712. // ConnectObserver is the interface implemented by connect observers / stat collectors.
  1713. type ConnectObserver interface {
  1714. // ObserveConnect gets called when a new connection to cassandra is made.
  1715. ObserveConnect(ObservedConnect)
  1716. }
  1717. type Error struct {
  1718. Code int
  1719. Message string
  1720. }
  1721. func (e Error) Error() string {
  1722. return e.Message
  1723. }
  1724. var (
  1725. ErrNotFound = errors.New("not found")
  1726. ErrUnavailable = errors.New("unavailable")
  1727. ErrUnsupported = errors.New("feature not supported")
  1728. ErrTooManyStmts = errors.New("too many statements")
  1729. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explanation.")
  1730. ErrSessionClosed = errors.New("session has been closed")
  1731. ErrNoConnections = errors.New("gocql: no hosts available in the pool")
  1732. ErrNoKeyspace = errors.New("no keyspace provided")
  1733. ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist")
  1734. ErrNoMetadata = errors.New("no metadata available")
  1735. )
  1736. type ErrProtocol struct{ error }
  1737. func NewErrProtocol(format string, args ...interface{}) error {
  1738. return ErrProtocol{fmt.Errorf(format, args...)}
  1739. }
  1740. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1741. // This limit is set by cassandra and could change in the future.
  1742. const BatchSizeMaximum = 65535