session.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. type Iter struct {
  100. err error
  101. pos int
  102. rows [][][]byte
  103. columns []ColumnInfo
  104. qry *Query
  105. pageState []byte
  106. }
  107. func (iter *Iter) Columns() []ColumnInfo {
  108. return iter.columns
  109. }
  110. func (iter *Iter) Scan(dest ...interface{}) bool {
  111. if iter.err != nil {
  112. return false
  113. }
  114. if iter.pos >= len(iter.rows) {
  115. if len(iter.pageState) > 0 {
  116. qry := *iter.qry
  117. qry.pageState = iter.pageState
  118. *iter = *iter.qry.session.executeQuery(&qry)
  119. return iter.Scan(dest...)
  120. }
  121. return false
  122. }
  123. if len(dest) != len(iter.columns) {
  124. iter.err = errors.New("count mismatch")
  125. return false
  126. }
  127. for i := 0; i < len(iter.columns); i++ {
  128. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  129. if err != nil {
  130. iter.err = err
  131. return false
  132. }
  133. }
  134. iter.pos++
  135. return true
  136. }
  137. func (iter *Iter) Close() error {
  138. return iter.err
  139. }
  140. type Batch struct {
  141. Type BatchType
  142. Entries []BatchEntry
  143. Cons Consistency
  144. }
  145. func NewBatch(typ BatchType) *Batch {
  146. return &Batch{Type: typ}
  147. }
  148. func (b *Batch) Query(stmt string, args ...interface{}) {
  149. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  150. }
  151. type BatchType int
  152. const (
  153. LoggedBatch BatchType = 0
  154. UnloggedBatch BatchType = 1
  155. CounterBatch BatchType = 2
  156. )
  157. type BatchEntry struct {
  158. Stmt string
  159. Args []interface{}
  160. }
  161. type Consistency int
  162. const (
  163. Any Consistency = 1 + iota
  164. One
  165. Two
  166. Three
  167. Quorum
  168. All
  169. LocalQuorum
  170. EachQuorum
  171. Serial
  172. LocalSerial
  173. )
  174. var consinstencyNames = []string{
  175. 0: "default",
  176. Any: "any",
  177. One: "one",
  178. Two: "two",
  179. Three: "three",
  180. Quorum: "quorum",
  181. All: "all",
  182. LocalQuorum: "localquorum",
  183. EachQuorum: "eachquorum",
  184. Serial: "serial",
  185. LocalSerial: "localserial",
  186. }
  187. func (c Consistency) String() string {
  188. return consinstencyNames[c]
  189. }
  190. type ColumnInfo struct {
  191. Keyspace string
  192. Table string
  193. Name string
  194. TypeInfo *TypeInfo
  195. }
  196. // Tracer is the interface implemented by query tracers. Tracers have the
  197. // ability to obtain a detailed event log of all events that happened during
  198. // the execution of a query from Cassandra. Gathering this information might
  199. // be essential for debugging and optimizing queries, but this feature should
  200. // not be used on production systems with very high load.
  201. type Tracer interface {
  202. Trace(traceId []byte)
  203. }
  204. type traceWriter struct {
  205. session *Session
  206. w io.Writer
  207. mu sync.Mutex
  208. }
  209. // NewTraceWriter returns a simple Tracer implementation that outputs
  210. // the event log in a textual format.
  211. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  212. return traceWriter{session: session, w: w}
  213. }
  214. func (t traceWriter) Trace(traceId []byte) {
  215. var (
  216. coordinator string
  217. duration int
  218. )
  219. t.session.Query(`SELECT coordinator, duration
  220. FROM system_traces.sessions
  221. WHERE session_id = ?`, traceId).
  222. Consistency(One).Scan(&coordinator, &duration)
  223. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  224. FROM system_traces.events
  225. WHERE session_id = ?`, traceId).
  226. Consistency(One).Iter()
  227. var (
  228. timestamp time.Time
  229. activity string
  230. source string
  231. elapsed int
  232. )
  233. t.mu.Lock()
  234. defer t.mu.Unlock()
  235. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  236. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  237. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  238. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  239. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  240. }
  241. if err := iter.Close(); err != nil {
  242. fmt.Fprintln(t.w, "Error:", err)
  243. }
  244. }
  245. type Error struct {
  246. Code int
  247. Message string
  248. }
  249. func (e Error) Error() string {
  250. return e.Message
  251. }
  252. var (
  253. ErrNotFound = errors.New("not found")
  254. ErrUnavailable = errors.New("unavailable")
  255. ErrProtocol = errors.New("protocol error")
  256. ErrUnsupported = errors.New("feature not supported")
  257. )