session.go 54 KB

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