session.go 43 KB

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