session.go 48 KB

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