session.go 18 KB

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