session.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. "errors"
  7. "fmt"
  8. "io"
  9. "strings"
  10. "sync"
  11. "time"
  12. "unicode"
  13. )
  14. // Session is the interface used by users to interact with the database.
  15. //
  16. // It's safe for concurrent use by multiple goroutines and a typical usage
  17. // scenario is to have one global session object to interact with the
  18. // whole Cassandra cluster.
  19. //
  20. // This type extends the Node interface by adding a convinient query builder
  21. // and automatically sets a default consinstency level on all operations
  22. // that do not have a consistency level set.
  23. type Session struct {
  24. Pool ConnectionPool
  25. cons Consistency
  26. pageSize int
  27. prefetch float64
  28. schemaDescriber *schemaDescriber
  29. trace Tracer
  30. mu sync.RWMutex
  31. cfg ClusterConfig
  32. closeMu sync.RWMutex
  33. isClosed bool
  34. }
  35. // NewSession wraps an existing Node.
  36. func NewSession(p ConnectionPool, c ClusterConfig) *Session {
  37. return &Session{Pool: p, cons: Quorum, prefetch: 0.25, cfg: c}
  38. }
  39. // SetConsistency sets the default consistency level for this session. This
  40. // setting can also be changed on a per-query basis and the default value
  41. // is Quorum.
  42. func (s *Session) SetConsistency(cons Consistency) {
  43. s.mu.Lock()
  44. s.cons = cons
  45. s.mu.Unlock()
  46. }
  47. // SetPageSize sets the default page size for this session. A value <= 0 will
  48. // disable paging. This setting can also be changed on a per-query basis.
  49. func (s *Session) SetPageSize(n int) {
  50. s.mu.Lock()
  51. s.pageSize = n
  52. s.mu.Unlock()
  53. }
  54. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  55. // there are only p*pageSize rows remaining, the next page will be requested
  56. // automatically. This value can also be changed on a per-query basis and
  57. // the default value is 0.25.
  58. func (s *Session) SetPrefetch(p float64) {
  59. s.mu.Lock()
  60. s.prefetch = p
  61. s.mu.Unlock()
  62. }
  63. // SetTrace sets the default tracer for this session. This setting can also
  64. // be changed on a per-query basis.
  65. func (s *Session) SetTrace(trace Tracer) {
  66. s.mu.Lock()
  67. s.trace = trace
  68. s.mu.Unlock()
  69. }
  70. // Query generates a new query object for interacting with the database.
  71. // Further details of the query may be tweaked using the resulting query
  72. // value before the query is executed. Query is automatically prepared
  73. // if it has not previously been executed.
  74. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  75. s.mu.RLock()
  76. qry := &Query{stmt: stmt, values: values, cons: s.cons,
  77. session: s, pageSize: s.pageSize, trace: s.trace,
  78. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  79. s.mu.RUnlock()
  80. return qry
  81. }
  82. // Bind generates a new query object based on the query statement passed in.
  83. // The query is automatically prepared if it has not previously been executed.
  84. // The binding callback allows the application to define which query argument
  85. // values will be marshalled as part of the query execution.
  86. // During execution, the meta data of the prepared query will be routed to the
  87. // binding callback, which is responsible for producing the query argument values.
  88. func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
  89. s.mu.RLock()
  90. qry := &Query{stmt: stmt, binding: b, cons: s.cons,
  91. session: s, pageSize: s.pageSize, trace: s.trace,
  92. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  93. s.mu.RUnlock()
  94. return qry
  95. }
  96. // Close closes all connections. The session is unusable after this
  97. // operation.
  98. func (s *Session) Close() {
  99. s.closeMu.Lock()
  100. defer s.closeMu.Unlock()
  101. if s.isClosed {
  102. return
  103. }
  104. s.isClosed = true
  105. s.Pool.Close()
  106. }
  107. func (s *Session) Closed() bool {
  108. s.closeMu.RLock()
  109. closed := s.isClosed
  110. s.closeMu.RUnlock()
  111. return closed
  112. }
  113. func (s *Session) executeQuery(qry *Query) *Iter {
  114. // fail fast
  115. if s.Closed() {
  116. return &Iter{err: ErrSessionClosed}
  117. }
  118. var iter *Iter
  119. qry.attempts = 0
  120. qry.totalLatency = 0
  121. for {
  122. conn := s.Pool.Pick(qry)
  123. //Assign the error unavailable to the iterator
  124. if conn == nil {
  125. iter = &Iter{err: ErrNoConnections}
  126. break
  127. }
  128. t := time.Now()
  129. iter = conn.executeQuery(qry)
  130. qry.totalLatency += time.Now().Sub(t).Nanoseconds()
  131. qry.attempts++
  132. //Exit for loop if the query was successful
  133. if iter.err == nil {
  134. break
  135. }
  136. if qry.rt == nil || !qry.rt.Attempt(qry) {
  137. break
  138. }
  139. }
  140. return iter
  141. }
  142. // Returns the schema metadata for the keyspace of this session including
  143. // table and column schema metadata.
  144. func (s *Session) KeyspaceMetadata() (*KeyspaceMetadata, error) {
  145. s.mu.Lock()
  146. if s.schemaDescriber == nil {
  147. s.schemaDescriber = &schemaDescriber{session: s}
  148. }
  149. s.mu.Unlock()
  150. return s.schemaDescriber.getSchema()
  151. }
  152. // ExecuteBatch executes a batch operation and returns nil if successful
  153. // otherwise an error is returned describing the failure.
  154. func (s *Session) ExecuteBatch(batch *Batch) error {
  155. // fail fast
  156. if s.Closed() {
  157. return ErrSessionClosed
  158. }
  159. // Prevent the execution of the batch if greater than the limit
  160. // Currently batches have a limit of 65536 queries.
  161. // https://datastax-oss.atlassian.net/browse/JAVA-229
  162. if batch.Size() > BatchSizeMaximum {
  163. return ErrTooManyStmts
  164. }
  165. var err error
  166. batch.attempts = 0
  167. batch.totalLatency = 0
  168. for {
  169. conn := s.Pool.Pick(nil)
  170. //Assign the error unavailable and break loop
  171. if conn == nil {
  172. err = ErrNoConnections
  173. break
  174. }
  175. t := time.Now()
  176. err = conn.executeBatch(batch)
  177. batch.totalLatency += time.Now().Sub(t).Nanoseconds()
  178. batch.attempts++
  179. //Exit loop if operation executed correctly
  180. if err == nil {
  181. return nil
  182. }
  183. if batch.rt == nil || !batch.rt.Attempt(batch) {
  184. break
  185. }
  186. }
  187. return err
  188. }
  189. // Query represents a CQL statement that can be executed.
  190. type Query struct {
  191. stmt string
  192. values []interface{}
  193. cons Consistency
  194. pageSize int
  195. pageState []byte
  196. prefetch float64
  197. trace Tracer
  198. session *Session
  199. rt RetryPolicy
  200. binding func(q *QueryInfo) ([]interface{}, error)
  201. attempts int
  202. totalLatency int64
  203. }
  204. //Attempts returns the number of times the query was executed.
  205. func (q *Query) Attempts() int {
  206. return q.attempts
  207. }
  208. //Latency returns the average amount of nanoseconds per attempt of the query.
  209. func (q *Query) Latency() int64 {
  210. if q.attempts > 0 {
  211. return q.totalLatency / int64(q.attempts)
  212. }
  213. return 0
  214. }
  215. // Consistency sets the consistency level for this query. If no consistency
  216. // level have been set, the default consistency level of the cluster
  217. // is used.
  218. func (q *Query) Consistency(c Consistency) *Query {
  219. q.cons = c
  220. return q
  221. }
  222. // GetConsistency returns the currently configured consistency level for
  223. // the query.
  224. func (q *Query) GetConsistency() Consistency {
  225. return q.cons
  226. }
  227. // Trace enables tracing of this query. Look at the documentation of the
  228. // Tracer interface to learn more about tracing.
  229. func (q *Query) Trace(trace Tracer) *Query {
  230. q.trace = trace
  231. return q
  232. }
  233. // PageSize will tell the iterator to fetch the result in pages of size n.
  234. // This is useful for iterating over large result sets, but setting the
  235. // page size to low might decrease the performance. This feature is only
  236. // available in Cassandra 2 and onwards.
  237. func (q *Query) PageSize(n int) *Query {
  238. q.pageSize = n
  239. return q
  240. }
  241. func (q *Query) shouldPrepare() bool {
  242. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  243. return unicode.IsSpace(r) || r == ';'
  244. }), unicode.IsSpace)
  245. var stmtType string
  246. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  247. stmtType = strings.ToLower(stmt[:n])
  248. }
  249. if stmtType == "begin" {
  250. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  251. stmtType = strings.ToLower(stmt[n+1:])
  252. }
  253. }
  254. switch stmtType {
  255. case "select", "insert", "update", "delete", "batch":
  256. return true
  257. }
  258. return false
  259. }
  260. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  261. // there are only p*pageSize rows remaining, the next page will be requested
  262. // automatically.
  263. func (q *Query) Prefetch(p float64) *Query {
  264. q.prefetch = p
  265. return q
  266. }
  267. // RetryPolicy sets the policy to use when retrying the query.
  268. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  269. q.rt = r
  270. return q
  271. }
  272. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  273. // to an existing query instance.
  274. func (q *Query) Bind(v ...interface{}) *Query {
  275. q.values = v
  276. return q
  277. }
  278. // Exec executes the query without returning any rows.
  279. func (q *Query) Exec() error {
  280. iter := q.Iter()
  281. return iter.err
  282. }
  283. // Iter executes the query and returns an iterator capable of iterating
  284. // over all results.
  285. func (q *Query) Iter() *Iter {
  286. if strings.Index(strings.ToLower(q.stmt), "use") == 0 {
  287. return &Iter{err: ErrUseStmt}
  288. }
  289. return q.session.executeQuery(q)
  290. }
  291. // MapScan executes the query, copies the columns of the first selected
  292. // row into the map pointed at by m and discards the rest. If no rows
  293. // were selected, ErrNotFound is returned.
  294. func (q *Query) MapScan(m map[string]interface{}) error {
  295. iter := q.Iter()
  296. if err := iter.checkErrAndNotFound(); err != nil {
  297. return err
  298. }
  299. iter.MapScan(m)
  300. return iter.Close()
  301. }
  302. // Scan executes the query, copies the columns of the first selected
  303. // row into the values pointed at by dest and discards the rest. If no rows
  304. // were selected, ErrNotFound is returned.
  305. func (q *Query) Scan(dest ...interface{}) error {
  306. iter := q.Iter()
  307. if err := iter.checkErrAndNotFound(); err != nil {
  308. return err
  309. }
  310. iter.Scan(dest...)
  311. return iter.Close()
  312. }
  313. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  314. // statement containing an IF clause). If the transaction fails because
  315. // the existing values did not match, the previous values will be stored
  316. // in dest.
  317. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  318. iter := q.Iter()
  319. if err := iter.checkErrAndNotFound(); err != nil {
  320. return false, err
  321. }
  322. if len(iter.Columns()) > 1 {
  323. dest = append([]interface{}{&applied}, dest...)
  324. iter.Scan(dest...)
  325. } else {
  326. iter.Scan(&applied)
  327. }
  328. return applied, iter.Close()
  329. }
  330. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  331. // statement containing an IF clause). If the transaction fails because
  332. // the existing values did not match, the previous values will be stored
  333. // in dest map.
  334. //
  335. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  336. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  337. // column mismatching. MapScanCAS is added to capture them safely.
  338. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  339. iter := q.Iter()
  340. if err := iter.checkErrAndNotFound(); err != nil {
  341. return false, err
  342. }
  343. iter.MapScan(dest)
  344. applied = dest["[applied]"].(bool)
  345. delete(dest, "[applied]")
  346. return applied, iter.Close()
  347. }
  348. // Iter represents an iterator that can be used to iterate over all rows that
  349. // were returned by a query. The iterator might send additional queries to the
  350. // database during the iteration if paging was enabled.
  351. type Iter struct {
  352. err error
  353. pos int
  354. rows [][][]byte
  355. columns []ColumnInfo
  356. next *nextIter
  357. }
  358. // Columns returns the name and type of the selected columns.
  359. func (iter *Iter) Columns() []ColumnInfo {
  360. return iter.columns
  361. }
  362. // Scan consumes the next row of the iterator and copies the columns of the
  363. // current row into the values pointed at by dest. Use nil as a dest value
  364. // to skip the corresponding column. Scan might send additional queries
  365. // to the database to retrieve the next set of rows if paging was enabled.
  366. //
  367. // Scan returns true if the row was successfully unmarshaled or false if the
  368. // end of the result set was reached or if an error occurred. Close should
  369. // be called afterwards to retrieve any potential errors.
  370. func (iter *Iter) Scan(dest ...interface{}) bool {
  371. if iter.err != nil {
  372. return false
  373. }
  374. if iter.pos >= len(iter.rows) {
  375. if iter.next != nil {
  376. *iter = *iter.next.fetch()
  377. return iter.Scan(dest...)
  378. }
  379. return false
  380. }
  381. if iter.next != nil && iter.pos == iter.next.pos {
  382. go iter.next.fetch()
  383. }
  384. if len(dest) != len(iter.columns) {
  385. iter.err = errors.New("count mismatch")
  386. return false
  387. }
  388. for i := 0; i < len(iter.columns); i++ {
  389. if dest[i] == nil {
  390. continue
  391. }
  392. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  393. if err != nil {
  394. iter.err = err
  395. return false
  396. }
  397. }
  398. iter.pos++
  399. return true
  400. }
  401. // Close closes the iterator and returns any errors that happened during
  402. // the query or the iteration.
  403. func (iter *Iter) Close() error {
  404. return iter.err
  405. }
  406. // checkErrAndNotFound handle error and NotFound in one method.
  407. func (iter *Iter) checkErrAndNotFound() error {
  408. if iter.err != nil {
  409. return iter.err
  410. } else if len(iter.rows) == 0 {
  411. return ErrNotFound
  412. }
  413. return nil
  414. }
  415. type nextIter struct {
  416. qry Query
  417. pos int
  418. once sync.Once
  419. next *Iter
  420. }
  421. func (n *nextIter) fetch() *Iter {
  422. n.once.Do(func() {
  423. n.next = n.qry.session.executeQuery(&n.qry)
  424. })
  425. return n.next
  426. }
  427. type Batch struct {
  428. Type BatchType
  429. Entries []BatchEntry
  430. Cons Consistency
  431. rt RetryPolicy
  432. attempts int
  433. totalLatency int64
  434. }
  435. // NewBatch creates a new batch operation without defaults from the cluster
  436. func NewBatch(typ BatchType) *Batch {
  437. return &Batch{Type: typ}
  438. }
  439. // NewBatch creates a new batch operation using defaults defined in the cluster
  440. func (s *Session) NewBatch(typ BatchType) *Batch {
  441. return &Batch{Type: typ, rt: s.cfg.RetryPolicy}
  442. }
  443. // Attempts returns the number of attempts made to execute the batch.
  444. func (b *Batch) Attempts() int {
  445. return b.attempts
  446. }
  447. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  448. func (b *Batch) Latency() int64 {
  449. if b.attempts > 0 {
  450. return b.totalLatency / int64(b.attempts)
  451. }
  452. return 0
  453. }
  454. // GetConsistency returns the currently configured consistency level for the batch
  455. // operation.
  456. func (b *Batch) GetConsistency() Consistency {
  457. return b.Cons
  458. }
  459. // Query adds the query to the batch operation
  460. func (b *Batch) Query(stmt string, args ...interface{}) {
  461. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  462. }
  463. // Bind adds the query to the batch operation and correlates it with a binding callback
  464. // that will be invoked when the batch is executed. The binding callback allows the application
  465. // to define which query argument values will be marshalled as part of the batch execution.
  466. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  467. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  468. }
  469. // RetryPolicy sets the retry policy to use when executing the batch operation
  470. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  471. b.rt = r
  472. return b
  473. }
  474. // Size returns the number of batch statements to be executed by the batch operation.
  475. func (b *Batch) Size() int {
  476. return len(b.Entries)
  477. }
  478. type BatchType int
  479. const (
  480. LoggedBatch BatchType = 0
  481. UnloggedBatch BatchType = 1
  482. CounterBatch BatchType = 2
  483. )
  484. type BatchEntry struct {
  485. Stmt string
  486. Args []interface{}
  487. binding func(q *QueryInfo) ([]interface{}, error)
  488. }
  489. type Consistency int
  490. const (
  491. Any Consistency = 1 + iota
  492. One
  493. Two
  494. Three
  495. Quorum
  496. All
  497. LocalQuorum
  498. EachQuorum
  499. Serial
  500. LocalSerial
  501. LocalOne
  502. )
  503. var ConsistencyNames = []string{
  504. 0: "default",
  505. Any: "any",
  506. One: "one",
  507. Two: "two",
  508. Three: "three",
  509. Quorum: "quorum",
  510. All: "all",
  511. LocalQuorum: "localquorum",
  512. EachQuorum: "eachquorum",
  513. Serial: "serial",
  514. LocalSerial: "localserial",
  515. LocalOne: "localone",
  516. }
  517. func (c Consistency) String() string {
  518. return ConsistencyNames[c]
  519. }
  520. type ColumnInfo struct {
  521. Keyspace string
  522. Table string
  523. Name string
  524. TypeInfo *TypeInfo
  525. }
  526. // Tracer is the interface implemented by query tracers. Tracers have the
  527. // ability to obtain a detailed event log of all events that happened during
  528. // the execution of a query from Cassandra. Gathering this information might
  529. // be essential for debugging and optimizing queries, but this feature should
  530. // not be used on production systems with very high load.
  531. type Tracer interface {
  532. Trace(traceId []byte)
  533. }
  534. type traceWriter struct {
  535. session *Session
  536. w io.Writer
  537. mu sync.Mutex
  538. }
  539. // NewTraceWriter returns a simple Tracer implementation that outputs
  540. // the event log in a textual format.
  541. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  542. return &traceWriter{session: session, w: w}
  543. }
  544. func (t *traceWriter) Trace(traceId []byte) {
  545. var (
  546. coordinator string
  547. duration int
  548. )
  549. t.session.Query(`SELECT coordinator, duration
  550. FROM system_traces.sessions
  551. WHERE session_id = ?`, traceId).
  552. Consistency(One).Scan(&coordinator, &duration)
  553. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  554. FROM system_traces.events
  555. WHERE session_id = ?`, traceId).
  556. Consistency(One).Iter()
  557. var (
  558. timestamp time.Time
  559. activity string
  560. source string
  561. elapsed int
  562. )
  563. t.mu.Lock()
  564. defer t.mu.Unlock()
  565. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  566. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  567. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  568. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  569. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  570. }
  571. if err := iter.Close(); err != nil {
  572. fmt.Fprintln(t.w, "Error:", err)
  573. }
  574. }
  575. type Error struct {
  576. Code int
  577. Message string
  578. }
  579. func (e Error) Error() string {
  580. return e.Message
  581. }
  582. var (
  583. ErrNotFound = errors.New("not found")
  584. ErrUnavailable = errors.New("unavailable")
  585. ErrUnsupported = errors.New("feature not supported")
  586. ErrTooManyStmts = errors.New("too many statements")
  587. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  588. ErrSessionClosed = errors.New("session has been closed")
  589. ErrNoConnections = errors.New("no connections available")
  590. )
  591. type ErrProtocol struct{ error }
  592. func NewErrProtocol(format string, args ...interface{}) error {
  593. return ErrProtocol{fmt.Errorf(format, args...)}
  594. }
  595. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  596. // This limit is set by cassandra and could change in the future.
  597. const BatchSizeMaximum = 65535