session.go 55 KB

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