session.go 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  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 s.dial(host.ConnectAddress(), host.Port(), s.connCfg, errorHandler)
  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 advances the row pointer to point at the next row, the row is valid until
  904. // the next call of Next. It returns true if there is a row which is available to be
  905. // scanned into with Scan.
  906. // Next must be called before every call to Scan.
  907. Next() bool
  908. // Scan copies the current row's columns into dest. If the length of dest does not equal
  909. // the number of columns returned in the row an error is returned. If an error is encountered
  910. // when unmarshalling a column into the value in dest an error is returned and the row is invalidated
  911. // until the next call to Next.
  912. // Next must be called before calling Scan, if it is not an error is returned.
  913. Scan(...interface{}) error
  914. // Err returns the if there was one during iteration that resulted in iteration being unable to complete.
  915. // Err will also release resources held by the iterator, the Scanner should not used after being called.
  916. Err() error
  917. }
  918. type iterScanner struct {
  919. iter *Iter
  920. cols [][]byte
  921. }
  922. func (is *iterScanner) Next() bool {
  923. iter := is.iter
  924. if iter.err != nil {
  925. return false
  926. }
  927. if iter.pos >= iter.numRows {
  928. if iter.next != nil {
  929. is.iter = iter.next.fetch()
  930. return is.Next()
  931. }
  932. return false
  933. }
  934. cols := make([][]byte, len(iter.meta.columns))
  935. for i := 0; i < len(cols); i++ {
  936. col, err := iter.readColumn()
  937. if err != nil {
  938. iter.err = err
  939. return false
  940. }
  941. cols[i] = col
  942. }
  943. is.cols = cols
  944. iter.pos++
  945. return true
  946. }
  947. func scanColumn(p []byte, col ColumnInfo, dest []interface{}) (int, error) {
  948. if dest[0] == nil {
  949. return 1, nil
  950. }
  951. if col.TypeInfo.Type() == TypeTuple {
  952. // this will panic, actually a bug, please report
  953. tuple := col.TypeInfo.(TupleTypeInfo)
  954. count := len(tuple.Elems)
  955. // here we pass in a slice of the struct which has the number number of
  956. // values as elements in the tuple
  957. if err := Unmarshal(col.TypeInfo, p, dest[:count]); err != nil {
  958. return 0, err
  959. }
  960. return count, nil
  961. } else {
  962. if err := Unmarshal(col.TypeInfo, p, dest[0]); err != nil {
  963. return 0, err
  964. }
  965. return 1, nil
  966. }
  967. }
  968. func (is *iterScanner) Scan(dest ...interface{}) error {
  969. if is.cols == nil {
  970. return errors.New("gocql: Scan called without calling Next")
  971. }
  972. iter := is.iter
  973. // currently only support scanning into an expand tuple, such that its the same
  974. // as scanning in more values from a single column
  975. if len(dest) != iter.meta.actualColCount {
  976. return fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  977. }
  978. // i is the current position in dest, could posible replace it and just use
  979. // slices of dest
  980. i := 0
  981. var err error
  982. for _, col := range iter.meta.columns {
  983. var n int
  984. n, err = scanColumn(is.cols[i], col, dest[i:])
  985. if err != nil {
  986. break
  987. }
  988. i += n
  989. }
  990. is.cols = nil
  991. return err
  992. }
  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. conn *Conn
  1118. }
  1119. func (n *nextIter) fetch() *Iter {
  1120. n.once.Do(func() {
  1121. iter := n.qry.session.executor.attemptQuery(&n.qry, n.conn)
  1122. if iter != nil && iter.err == nil {
  1123. n.next = iter
  1124. } else {
  1125. n.next = n.qry.session.executeQuery(&n.qry)
  1126. }
  1127. })
  1128. return n.next
  1129. }
  1130. type Batch struct {
  1131. Type BatchType
  1132. Entries []BatchEntry
  1133. Cons Consistency
  1134. rt RetryPolicy
  1135. attempts int
  1136. totalLatency int64
  1137. serialCons SerialConsistency
  1138. defaultTimestamp bool
  1139. defaultTimestampValue int64
  1140. context context.Context
  1141. }
  1142. // NewBatch creates a new batch operation without defaults from the cluster
  1143. func NewBatch(typ BatchType) *Batch {
  1144. return &Batch{Type: typ}
  1145. }
  1146. // NewBatch creates a new batch operation using defaults defined in the cluster
  1147. func (s *Session) NewBatch(typ BatchType) *Batch {
  1148. s.mu.RLock()
  1149. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  1150. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  1151. s.mu.RUnlock()
  1152. return batch
  1153. }
  1154. // Attempts returns the number of attempts made to execute the batch.
  1155. func (b *Batch) Attempts() int {
  1156. return b.attempts
  1157. }
  1158. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  1159. func (b *Batch) Latency() int64 {
  1160. if b.attempts > 0 {
  1161. return b.totalLatency / int64(b.attempts)
  1162. }
  1163. return 0
  1164. }
  1165. // GetConsistency returns the currently configured consistency level for the batch
  1166. // operation.
  1167. func (b *Batch) GetConsistency() Consistency {
  1168. return b.Cons
  1169. }
  1170. // Query adds the query to the batch operation
  1171. func (b *Batch) Query(stmt string, args ...interface{}) {
  1172. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  1173. }
  1174. // Bind adds the query to the batch operation and correlates it with a binding callback
  1175. // that will be invoked when the batch is executed. The binding callback allows the application
  1176. // to define which query argument values will be marshalled as part of the batch execution.
  1177. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  1178. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  1179. }
  1180. func (b *Batch) retryPolicy() RetryPolicy {
  1181. return b.rt
  1182. }
  1183. // RetryPolicy sets the retry policy to use when executing the batch operation
  1184. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  1185. b.rt = r
  1186. return b
  1187. }
  1188. // WithContext will set the context to use during a query, it will be used to
  1189. // timeout when waiting for responses from Cassandra.
  1190. func (b *Batch) WithContext(ctx context.Context) *Batch {
  1191. b.context = ctx
  1192. return b
  1193. }
  1194. // Size returns the number of batch statements to be executed by the batch operation.
  1195. func (b *Batch) Size() int {
  1196. return len(b.Entries)
  1197. }
  1198. // SerialConsistency sets the consistency level for the
  1199. // serial phase of conditional updates. That consistency can only be
  1200. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  1201. // SERIAL. This option will be ignored for anything else that a
  1202. // conditional update/insert.
  1203. //
  1204. // Only available for protocol 3 and above
  1205. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  1206. b.serialCons = cons
  1207. return b
  1208. }
  1209. // DefaultTimestamp will enable the with default timestamp flag on the query.
  1210. // If enable, this will replace the server side assigned
  1211. // timestamp as default timestamp. Note that a timestamp in the query itself
  1212. // will still override this timestamp. This is entirely optional.
  1213. //
  1214. // Only available on protocol >= 3
  1215. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  1216. b.defaultTimestamp = enable
  1217. return b
  1218. }
  1219. // WithTimestamp will enable the with default timestamp flag on the query
  1220. // like DefaultTimestamp does. But also allows to define value for timestamp.
  1221. // It works the same way as USING TIMESTAMP in the query itself, but
  1222. // should not break prepared query optimization
  1223. //
  1224. // Only available on protocol >= 3
  1225. func (b *Batch) WithTimestamp(timestamp int64) *Batch {
  1226. b.DefaultTimestamp(true)
  1227. b.defaultTimestampValue = timestamp
  1228. return b
  1229. }
  1230. func (b *Batch) attempt(d time.Duration) {
  1231. b.attempts++
  1232. b.totalLatency += d.Nanoseconds()
  1233. // TODO: track latencies per host and things as well instead of just total
  1234. }
  1235. func (b *Batch) GetRoutingKey() ([]byte, error) {
  1236. // TODO: use the first statement in the batch as the routing key?
  1237. return nil, nil
  1238. }
  1239. type BatchType byte
  1240. const (
  1241. LoggedBatch BatchType = 0
  1242. UnloggedBatch BatchType = 1
  1243. CounterBatch BatchType = 2
  1244. )
  1245. type BatchEntry struct {
  1246. Stmt string
  1247. Args []interface{}
  1248. binding func(q *QueryInfo) ([]interface{}, error)
  1249. }
  1250. type ColumnInfo struct {
  1251. Keyspace string
  1252. Table string
  1253. Name string
  1254. TypeInfo TypeInfo
  1255. }
  1256. func (c ColumnInfo) String() string {
  1257. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  1258. }
  1259. // routing key indexes LRU cache
  1260. type routingKeyInfoLRU struct {
  1261. lru *lru.Cache
  1262. mu sync.Mutex
  1263. }
  1264. type routingKeyInfo struct {
  1265. indexes []int
  1266. types []TypeInfo
  1267. }
  1268. func (r *routingKeyInfo) String() string {
  1269. return fmt.Sprintf("routing key index=%v types=%v", r.indexes, r.types)
  1270. }
  1271. func (r *routingKeyInfoLRU) Remove(key string) {
  1272. r.mu.Lock()
  1273. r.lru.Remove(key)
  1274. r.mu.Unlock()
  1275. }
  1276. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  1277. //the new max is lower than the previous value. Not concurrency safe.
  1278. func (r *routingKeyInfoLRU) Max(max int) {
  1279. r.mu.Lock()
  1280. for r.lru.Len() > max {
  1281. r.lru.RemoveOldest()
  1282. }
  1283. r.lru.MaxEntries = max
  1284. r.mu.Unlock()
  1285. }
  1286. type inflightCachedEntry struct {
  1287. wg sync.WaitGroup
  1288. err error
  1289. value interface{}
  1290. }
  1291. // Tracer is the interface implemented by query tracers. Tracers have the
  1292. // ability to obtain a detailed event log of all events that happened during
  1293. // the execution of a query from Cassandra. Gathering this information might
  1294. // be essential for debugging and optimizing queries, but this feature should
  1295. // not be used on production systems with very high load.
  1296. type Tracer interface {
  1297. Trace(traceId []byte)
  1298. }
  1299. type traceWriter struct {
  1300. session *Session
  1301. w io.Writer
  1302. mu sync.Mutex
  1303. }
  1304. // NewTraceWriter returns a simple Tracer implementation that outputs
  1305. // the event log in a textual format.
  1306. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  1307. return &traceWriter{session: session, w: w}
  1308. }
  1309. func (t *traceWriter) Trace(traceId []byte) {
  1310. var (
  1311. coordinator string
  1312. duration int
  1313. )
  1314. iter := t.session.control.query(`SELECT coordinator, duration
  1315. FROM system_traces.sessions
  1316. WHERE session_id = ?`, traceId)
  1317. iter.Scan(&coordinator, &duration)
  1318. if err := iter.Close(); err != nil {
  1319. t.mu.Lock()
  1320. fmt.Fprintln(t.w, "Error:", err)
  1321. t.mu.Unlock()
  1322. return
  1323. }
  1324. var (
  1325. timestamp time.Time
  1326. activity string
  1327. source string
  1328. elapsed int
  1329. )
  1330. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1331. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1332. t.mu.Lock()
  1333. defer t.mu.Unlock()
  1334. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1335. FROM system_traces.events
  1336. WHERE session_id = ?`, traceId)
  1337. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1338. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1339. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1340. }
  1341. if err := iter.Close(); err != nil {
  1342. fmt.Fprintln(t.w, "Error:", err)
  1343. }
  1344. }
  1345. type Error struct {
  1346. Code int
  1347. Message string
  1348. }
  1349. func (e Error) Error() string {
  1350. return e.Message
  1351. }
  1352. var (
  1353. ErrNotFound = errors.New("not found")
  1354. ErrUnavailable = errors.New("unavailable")
  1355. ErrUnsupported = errors.New("feature not supported")
  1356. ErrTooManyStmts = errors.New("too many statements")
  1357. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explanation.")
  1358. ErrSessionClosed = errors.New("session has been closed")
  1359. ErrNoConnections = errors.New("gocql: no hosts available in the pool")
  1360. ErrNoKeyspace = errors.New("no keyspace provided")
  1361. ErrKeyspaceDoesNotExist = errors.New("keyspace does not exist")
  1362. ErrNoMetadata = errors.New("no metadata available")
  1363. )
  1364. type ErrProtocol struct{ error }
  1365. func NewErrProtocol(format string, args ...interface{}) error {
  1366. return ErrProtocol{fmt.Errorf(format, args...)}
  1367. }
  1368. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1369. // This limit is set by cassandra and could change in the future.
  1370. const BatchSizeMaximum = 65535