session.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. }
  21. // NewSession wraps an existing Node.
  22. func NewSession(node Node) *Session {
  23. return &Session{Node: node, Cons: Quorum}
  24. }
  25. // Query generates a new query object for interacting with the database.
  26. // Further details of the query may be tweaked using the resulting query
  27. // value before the query is executed.
  28. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  29. return &Query{stmt: stmt, values: values, cons: s.Cons, session: s}
  30. }
  31. // Close closes all connections. The session is unusable after this
  32. // operation.
  33. func (s *Session) Close() {
  34. s.Node.Close()
  35. }
  36. func (s *Session) executeQuery(qry *Query) *Iter {
  37. conn := s.Node.Pick(nil)
  38. if conn == nil {
  39. return &Iter{qry: qry, err: ErrUnavailable}
  40. }
  41. return conn.executeQuery(qry)
  42. }
  43. func (s *Session) ExecuteBatch(batch *Batch) error {
  44. conn := s.Node.Pick(nil)
  45. if conn == nil {
  46. return ErrUnavailable
  47. }
  48. return conn.executeBatch(batch)
  49. }
  50. // Query represents a CQL statement that can be executed.
  51. type Query struct {
  52. stmt string
  53. values []interface{}
  54. cons Consistency
  55. pageSize int
  56. pageState []byte
  57. trace Tracer
  58. session *Session
  59. }
  60. // Consistency sets the consistency level for this query. If no consistency
  61. // level have been set, the default consistency level of the cluster
  62. // is used.
  63. func (q *Query) Consistency(c Consistency) *Query {
  64. q.cons = c
  65. return q
  66. }
  67. // Trace enables tracing of this query. Look at the documentation of the
  68. // Tracer interface to learn more about tracing.
  69. func (q *Query) Trace(trace Tracer) *Query {
  70. q.trace = trace
  71. return q
  72. }
  73. // PageSize will tell the iterator to fetch the result in pages of size n.
  74. // This is useful for iterating over large result sets, but setting the
  75. // page size to low might decrease the performance. This feature is only
  76. // available in Cassandra 2 and onwards.
  77. func (q *Query) PageSize(n int) *Query {
  78. q.pageSize = n
  79. return q
  80. }
  81. // Exec executes the query without returning any rows.
  82. func (q *Query) Exec() error {
  83. iter := q.session.executeQuery(q)
  84. return iter.err
  85. }
  86. // Iter executes the query and returns an iterator capable of iterating
  87. // over all results.
  88. func (q *Query) Iter() *Iter {
  89. return q.session.executeQuery(q)
  90. }
  91. // Scan executes the query, copies the columns of the first selected
  92. // row into the values pointed at by dest and discards the rest. If no rows
  93. // were selected, ErrNotFound is returned.
  94. func (q *Query) Scan(dest ...interface{}) error {
  95. iter := q.Iter()
  96. iter.Scan(dest...)
  97. return iter.Close()
  98. }
  99. // Iter represents an iterator that can be used to iterate over all rows that
  100. // were returned by a query. The iterator might send additional queries to the
  101. // database during the iteration if paging was enabled.
  102. type Iter struct {
  103. err error
  104. pos int
  105. rows [][][]byte
  106. columns []ColumnInfo
  107. qry *Query
  108. pageState []byte
  109. }
  110. // Columns returns the name and type of the selected columns.
  111. func (iter *Iter) Columns() []ColumnInfo {
  112. return iter.columns
  113. }
  114. // Scan consumes the next row of the iterator and copies the columns of the
  115. // current row into the values pointed at by dest. Scan might send additional
  116. // queries to the database to retrieve the next set of rows if paging was
  117. // enabled.
  118. //
  119. // Scan returns true if the row was successfully unmarshaled or false if the
  120. // end of the result set was reached or if an error occurred. Close should
  121. // be called afterwards to retrieve any potential errors.
  122. func (iter *Iter) Scan(dest ...interface{}) bool {
  123. if iter.err != nil {
  124. return false
  125. }
  126. if iter.pos >= len(iter.rows) {
  127. if len(iter.pageState) > 0 {
  128. qry := *iter.qry
  129. qry.pageState = iter.pageState
  130. *iter = *iter.qry.session.executeQuery(&qry)
  131. return iter.Scan(dest...)
  132. }
  133. return false
  134. }
  135. if len(dest) != len(iter.columns) {
  136. iter.err = errors.New("count mismatch")
  137. return false
  138. }
  139. for i := 0; i < len(iter.columns); i++ {
  140. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  141. if err != nil {
  142. iter.err = err
  143. return false
  144. }
  145. }
  146. iter.pos++
  147. return true
  148. }
  149. // Close closes the iterator and returns any errors that happened during
  150. // the query or the iteration.
  151. func (iter *Iter) Close() error {
  152. return iter.err
  153. }
  154. type Batch struct {
  155. Type BatchType
  156. Entries []BatchEntry
  157. Cons Consistency
  158. }
  159. func NewBatch(typ BatchType) *Batch {
  160. return &Batch{Type: typ}
  161. }
  162. func (b *Batch) Query(stmt string, args ...interface{}) {
  163. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  164. }
  165. type BatchType int
  166. const (
  167. LoggedBatch BatchType = 0
  168. UnloggedBatch BatchType = 1
  169. CounterBatch BatchType = 2
  170. )
  171. type BatchEntry struct {
  172. Stmt string
  173. Args []interface{}
  174. }
  175. type Consistency int
  176. const (
  177. Any Consistency = 1 + iota
  178. One
  179. Two
  180. Three
  181. Quorum
  182. All
  183. LocalQuorum
  184. EachQuorum
  185. Serial
  186. LocalSerial
  187. )
  188. var consinstencyNames = []string{
  189. 0: "default",
  190. Any: "any",
  191. One: "one",
  192. Two: "two",
  193. Three: "three",
  194. Quorum: "quorum",
  195. All: "all",
  196. LocalQuorum: "localquorum",
  197. EachQuorum: "eachquorum",
  198. Serial: "serial",
  199. LocalSerial: "localserial",
  200. }
  201. func (c Consistency) String() string {
  202. return consinstencyNames[c]
  203. }
  204. type ColumnInfo struct {
  205. Keyspace string
  206. Table string
  207. Name string
  208. TypeInfo *TypeInfo
  209. }
  210. // Tracer is the interface implemented by query tracers. Tracers have the
  211. // ability to obtain a detailed event log of all events that happened during
  212. // the execution of a query from Cassandra. Gathering this information might
  213. // be essential for debugging and optimizing queries, but this feature should
  214. // not be used on production systems with very high load.
  215. type Tracer interface {
  216. Trace(traceId []byte)
  217. }
  218. type traceWriter struct {
  219. session *Session
  220. w io.Writer
  221. mu sync.Mutex
  222. }
  223. // NewTraceWriter returns a simple Tracer implementation that outputs
  224. // the event log in a textual format.
  225. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  226. return traceWriter{session: session, w: w}
  227. }
  228. func (t traceWriter) Trace(traceId []byte) {
  229. var (
  230. coordinator string
  231. duration int
  232. )
  233. t.session.Query(`SELECT coordinator, duration
  234. FROM system_traces.sessions
  235. WHERE session_id = ?`, traceId).
  236. Consistency(One).Scan(&coordinator, &duration)
  237. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  238. FROM system_traces.events
  239. WHERE session_id = ?`, traceId).
  240. Consistency(One).Iter()
  241. var (
  242. timestamp time.Time
  243. activity string
  244. source string
  245. elapsed int
  246. )
  247. t.mu.Lock()
  248. defer t.mu.Unlock()
  249. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  250. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  251. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  252. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  253. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  254. }
  255. if err := iter.Close(); err != nil {
  256. fmt.Fprintln(t.w, "Error:", err)
  257. }
  258. }
  259. type Error struct {
  260. Code int
  261. Message string
  262. }
  263. func (e Error) Error() string {
  264. return e.Message
  265. }
  266. var (
  267. ErrNotFound = errors.New("not found")
  268. ErrUnavailable = errors.New("unavailable")
  269. ErrProtocol = errors.New("protocol error")
  270. ErrUnsupported = errors.New("feature not supported")
  271. )