session.go 11 KB

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