session.go 37 KB

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