session.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. "sync"
  10. "time"
  11. )
  12. // Session is the interface used by users to interact with the database.
  13. //
  14. // It's safe for concurrent use by multiple goroutines and a typical usage
  15. // scenario is to have one global session object to interact with the
  16. // whole Cassandra cluster.
  17. //
  18. // This type extends the Node interface by adding a convinient query builder
  19. // and automatically sets a default consinstency level on all operations
  20. // that do not have a consistency level set.
  21. type Session struct {
  22. Node Node
  23. cons Consistency
  24. pageSize int
  25. prefetch float64
  26. trace Tracer
  27. mu sync.RWMutex
  28. cfg ClusterConfig
  29. }
  30. // NewSession wraps an existing Node.
  31. func NewSession(c *clusterImpl) *Session {
  32. return &Session{Node: c, cons: Quorum, prefetch: 0.25, cfg: c.cfg}
  33. }
  34. // SetConsistency sets the default consistency level for this session. This
  35. // setting can also be changed on a per-query basis and the default value
  36. // is Quorum.
  37. func (s *Session) SetConsistency(cons Consistency) {
  38. s.mu.Lock()
  39. s.cons = cons
  40. s.mu.Unlock()
  41. }
  42. // SetPageSize sets the default page size for this session. A value <= 0 will
  43. // disable paging. This setting can also be changed on a per-query basis.
  44. func (s *Session) SetPageSize(n int) {
  45. s.mu.Lock()
  46. s.pageSize = n
  47. s.mu.Unlock()
  48. }
  49. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  50. // there are only p*pageSize rows remaining, the next page will be requested
  51. // automatically. This value can also be changed on a per-query basis and
  52. // the default value is 0.25.
  53. func (s *Session) SetPrefetch(p float64) {
  54. s.mu.Lock()
  55. s.prefetch = p
  56. s.mu.Unlock()
  57. }
  58. // SetTrace sets the default tracer for this session. This setting can also
  59. // be changed on a per-query basis.
  60. func (s *Session) SetTrace(trace Tracer) {
  61. s.mu.Lock()
  62. s.trace = trace
  63. s.mu.Unlock()
  64. }
  65. // Query generates a new query object for interacting with the database.
  66. // Further details of the query may be tweaked using the resulting query
  67. // value before the query is executed.
  68. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  69. s.mu.RLock()
  70. qry := &Query{stmt: stmt, values: values, cons: s.cons,
  71. session: s, pageSize: s.pageSize, trace: s.trace,
  72. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  73. s.mu.RUnlock()
  74. return qry
  75. }
  76. // Close closes all connections. The session is unusable after this
  77. // operation.
  78. func (s *Session) Close() {
  79. s.Node.Close()
  80. }
  81. func (s *Session) executeQuery(qry *Query) *Iter {
  82. var itr *Iter
  83. count := 0
  84. for count <= qry.rt.NumRetries {
  85. conn := s.Node.Pick(nil)
  86. //Assign the error unavailable to the iterator
  87. if conn == nil {
  88. itr = &Iter{err: ErrUnavailable}
  89. break
  90. }
  91. itr = conn.executeQuery(qry)
  92. //Exit for loop if the query was successful
  93. if itr.err == nil {
  94. break
  95. }
  96. count++
  97. }
  98. return itr
  99. }
  100. // ExecuteBatch executes a batch operation and returns nil if successful
  101. // otherwise an error is returned describing the failure.
  102. func (s *Session) ExecuteBatch(batch *Batch) error {
  103. // Prevent the execution of the batch if greater than the limit
  104. // Currently batches have a limit of 65536 queries.
  105. // https://datastax-oss.atlassian.net/browse/JAVA-229
  106. if batch.Size() > BatchSizeMaximum {
  107. return ErrTooManyStmts
  108. }
  109. var err error
  110. count := 0
  111. for count <= batch.rt.NumRetries {
  112. conn := s.Node.Pick(nil)
  113. //Assign the error unavailable and break loop
  114. if conn == nil {
  115. err = ErrUnavailable
  116. break
  117. }
  118. err = conn.executeBatch(batch)
  119. //Exit loop if operation executed correctly
  120. if err == nil {
  121. break
  122. }
  123. count++
  124. }
  125. return err
  126. }
  127. // Query represents a CQL statement that can be executed.
  128. type Query struct {
  129. stmt string
  130. values []interface{}
  131. cons Consistency
  132. pageSize int
  133. pageState []byte
  134. prefetch float64
  135. trace Tracer
  136. session *Session
  137. rt RetryPolicy
  138. }
  139. // Consistency sets the consistency level for this query. If no consistency
  140. // level have been set, the default consistency level of the cluster
  141. // is used.
  142. func (q *Query) Consistency(c Consistency) *Query {
  143. q.cons = c
  144. return q
  145. }
  146. // Trace enables tracing of this query. Look at the documentation of the
  147. // Tracer interface to learn more about tracing.
  148. func (q *Query) Trace(trace Tracer) *Query {
  149. q.trace = trace
  150. return q
  151. }
  152. // PageSize will tell the iterator to fetch the result in pages of size n.
  153. // This is useful for iterating over large result sets, but setting the
  154. // page size to low might decrease the performance. This feature is only
  155. // available in Cassandra 2 and onwards.
  156. func (q *Query) PageSize(n int) *Query {
  157. q.pageSize = n
  158. return q
  159. }
  160. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  161. // there are only p*pageSize rows remaining, the next page will be requested
  162. // automatically.
  163. func (q *Query) Prefetch(p float64) *Query {
  164. q.prefetch = p
  165. return q
  166. }
  167. // RetryPolicy sets the policy to use when retrying the query.
  168. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  169. q.rt = r
  170. return q
  171. }
  172. // Exec executes the query without returning any rows.
  173. func (q *Query) Exec() error {
  174. iter := q.session.executeQuery(q)
  175. return iter.err
  176. }
  177. // Iter executes the query and returns an iterator capable of iterating
  178. // over all results.
  179. func (q *Query) Iter() *Iter {
  180. return q.session.executeQuery(q)
  181. }
  182. // Scan executes the query, copies the columns of the first selected
  183. // row into the values pointed at by dest and discards the rest. If no rows
  184. // were selected, ErrNotFound is returned.
  185. func (q *Query) Scan(dest ...interface{}) error {
  186. iter := q.Iter()
  187. if iter.err != nil {
  188. return iter.err
  189. }
  190. if len(iter.rows) == 0 {
  191. return ErrNotFound
  192. }
  193. iter.Scan(dest...)
  194. return iter.Close()
  195. }
  196. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  197. // statement containing an IF clause). If the transaction fails because
  198. // the existing values did not match, the previos values will be stored
  199. // in dest.
  200. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  201. iter := q.Iter()
  202. if iter.err != nil {
  203. return false, iter.err
  204. }
  205. if len(iter.rows) == 0 {
  206. return false, ErrNotFound
  207. }
  208. if len(iter.Columns()) > 1 {
  209. dest = append([]interface{}{&applied}, dest...)
  210. iter.Scan(dest...)
  211. } else {
  212. iter.Scan(&applied)
  213. }
  214. return applied, iter.Close()
  215. }
  216. // Iter represents an iterator that can be used to iterate over all rows that
  217. // were returned by a query. The iterator might send additional queries to the
  218. // database during the iteration if paging was enabled.
  219. type Iter struct {
  220. err error
  221. pos int
  222. rows [][][]byte
  223. columns []ColumnInfo
  224. next *nextIter
  225. }
  226. // Columns returns the name and type of the selected columns.
  227. func (iter *Iter) Columns() []ColumnInfo {
  228. return iter.columns
  229. }
  230. // Scan consumes the next row of the iterator and copies the columns of the
  231. // current row into the values pointed at by dest. Use nil as a dest value
  232. // to skip the corresponding column. Scan might send additional queries
  233. // to the database to retrieve the next set of rows if paging was enabled.
  234. //
  235. // Scan returns true if the row was successfully unmarshaled or false if the
  236. // end of the result set was reached or if an error occurred. Close should
  237. // be called afterwards to retrieve any potential errors.
  238. func (iter *Iter) Scan(dest ...interface{}) bool {
  239. if iter.err != nil {
  240. return false
  241. }
  242. if iter.pos >= len(iter.rows) {
  243. if iter.next != nil {
  244. *iter = *iter.next.fetch()
  245. return iter.Scan(dest...)
  246. }
  247. return false
  248. }
  249. if iter.next != nil && iter.pos == iter.next.pos {
  250. go iter.next.fetch()
  251. }
  252. if len(dest) != len(iter.columns) {
  253. iter.err = errors.New("count mismatch")
  254. return false
  255. }
  256. for i := 0; i < len(iter.columns); i++ {
  257. if dest[i] == nil {
  258. continue
  259. }
  260. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  261. if err != nil {
  262. iter.err = err
  263. return false
  264. }
  265. }
  266. iter.pos++
  267. return true
  268. }
  269. // Close closes the iterator and returns any errors that happened during
  270. // the query or the iteration.
  271. func (iter *Iter) Close() error {
  272. return iter.err
  273. }
  274. type nextIter struct {
  275. qry Query
  276. pos int
  277. once sync.Once
  278. next *Iter
  279. }
  280. func (n *nextIter) fetch() *Iter {
  281. n.once.Do(func() {
  282. n.next = n.qry.session.executeQuery(&n.qry)
  283. })
  284. return n.next
  285. }
  286. type Batch struct {
  287. Type BatchType
  288. Entries []BatchEntry
  289. Cons Consistency
  290. rt RetryPolicy
  291. }
  292. // NewBatch creates a new batch operation without defaults from the cluster
  293. func NewBatch(typ BatchType) *Batch {
  294. return &Batch{Type: typ}
  295. }
  296. // NewBatch creates a new batch operation using defaults defined in the cluster
  297. func (s *Session) NewBatch(typ BatchType) *Batch {
  298. return &Batch{Type: typ, rt: s.cfg.RetryPolicy}
  299. }
  300. // Query adds the query to the batch operation
  301. func (b *Batch) Query(stmt string, args ...interface{}) {
  302. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  303. }
  304. // RetryPolicy sets the retry policy to use when executing the batch operation
  305. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  306. b.rt = r
  307. return b
  308. }
  309. // Size returns the number of batch statements to be executed by the batch operation.
  310. func (b *Batch) Size() int {
  311. return len(b.Entries)
  312. }
  313. type BatchType int
  314. const (
  315. LoggedBatch BatchType = 0
  316. UnloggedBatch BatchType = 1
  317. CounterBatch BatchType = 2
  318. )
  319. type BatchEntry struct {
  320. Stmt string
  321. Args []interface{}
  322. }
  323. type Consistency int
  324. const (
  325. Any Consistency = 1 + iota
  326. One
  327. Two
  328. Three
  329. Quorum
  330. All
  331. LocalQuorum
  332. EachQuorum
  333. Serial
  334. LocalSerial
  335. )
  336. var consinstencyNames = []string{
  337. 0: "default",
  338. Any: "any",
  339. One: "one",
  340. Two: "two",
  341. Three: "three",
  342. Quorum: "quorum",
  343. All: "all",
  344. LocalQuorum: "localquorum",
  345. EachQuorum: "eachquorum",
  346. Serial: "serial",
  347. LocalSerial: "localserial",
  348. }
  349. func (c Consistency) String() string {
  350. return consinstencyNames[c]
  351. }
  352. type ColumnInfo struct {
  353. Keyspace string
  354. Table string
  355. Name string
  356. TypeInfo *TypeInfo
  357. }
  358. // Tracer is the interface implemented by query tracers. Tracers have the
  359. // ability to obtain a detailed event log of all events that happened during
  360. // the execution of a query from Cassandra. Gathering this information might
  361. // be essential for debugging and optimizing queries, but this feature should
  362. // not be used on production systems with very high load.
  363. type Tracer interface {
  364. Trace(traceId []byte)
  365. }
  366. type traceWriter struct {
  367. session *Session
  368. w io.Writer
  369. mu sync.Mutex
  370. }
  371. // NewTraceWriter returns a simple Tracer implementation that outputs
  372. // the event log in a textual format.
  373. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  374. return traceWriter{session: session, w: w}
  375. }
  376. func (t traceWriter) Trace(traceId []byte) {
  377. var (
  378. coordinator string
  379. duration int
  380. )
  381. t.session.Query(`SELECT coordinator, duration
  382. FROM system_traces.sessions
  383. WHERE session_id = ?`, traceId).
  384. Consistency(One).Scan(&coordinator, &duration)
  385. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  386. FROM system_traces.events
  387. WHERE session_id = ?`, traceId).
  388. Consistency(One).Iter()
  389. var (
  390. timestamp time.Time
  391. activity string
  392. source string
  393. elapsed int
  394. )
  395. t.mu.Lock()
  396. defer t.mu.Unlock()
  397. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  398. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  399. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  400. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  401. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  402. }
  403. if err := iter.Close(); err != nil {
  404. fmt.Fprintln(t.w, "Error:", err)
  405. }
  406. }
  407. type Error struct {
  408. Code int
  409. Message string
  410. }
  411. func (e Error) Error() string {
  412. return e.Message
  413. }
  414. var (
  415. ErrNotFound = errors.New("not found")
  416. ErrUnavailable = errors.New("unavailable")
  417. ErrProtocol = errors.New("protocol error")
  418. ErrUnsupported = errors.New("feature not supported")
  419. ErrTooManyStmts = errors.New("too many statements")
  420. )
  421. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  422. // This limit is set by cassandra and could change in the future.
  423. const BatchSizeMaximum = 65535