session.go 8.4 KB

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