session.go 18 KB

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