session.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 len(iter.rows) == 0 {
  145. return ErrNotFound
  146. }
  147. iter.Scan(dest...)
  148. return iter.Close()
  149. }
  150. // Iter represents an iterator that can be used to iterate over all rows that
  151. // were returned by a query. The iterator might send additional queries to the
  152. // database during the iteration if paging was enabled.
  153. type Iter struct {
  154. err error
  155. pos int
  156. rows [][][]byte
  157. columns []ColumnInfo
  158. next *nextIter
  159. }
  160. // Columns returns the name and type of the selected columns.
  161. func (iter *Iter) Columns() []ColumnInfo {
  162. return iter.columns
  163. }
  164. // Scan consumes the next row of the iterator and copies the columns of the
  165. // current row into the values pointed at by dest. Scan might send additional
  166. // queries to the database to retrieve the next set of rows if paging was
  167. // enabled.
  168. //
  169. // Scan returns true if the row was successfully unmarshaled or false if the
  170. // end of the result set was reached or if an error occurred. Close should
  171. // be called afterwards to retrieve any potential errors.
  172. func (iter *Iter) Scan(dest ...interface{}) bool {
  173. if iter.err != nil {
  174. return false
  175. }
  176. if iter.pos >= len(iter.rows) {
  177. if iter.next != nil {
  178. *iter = *iter.next.fetch()
  179. return iter.Scan(dest...)
  180. }
  181. return false
  182. }
  183. if iter.next != nil && iter.pos == iter.next.pos {
  184. go iter.next.fetch()
  185. }
  186. if len(dest) != len(iter.columns) {
  187. iter.err = errors.New("count mismatch")
  188. return false
  189. }
  190. for i := 0; i < len(iter.columns); i++ {
  191. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  192. if err != nil {
  193. iter.err = err
  194. return false
  195. }
  196. }
  197. iter.pos++
  198. return true
  199. }
  200. // Close closes the iterator and returns any errors that happened during
  201. // the query or the iteration.
  202. func (iter *Iter) Close() error {
  203. return iter.err
  204. }
  205. type nextIter struct {
  206. qry Query
  207. pos int
  208. once sync.Once
  209. next *Iter
  210. }
  211. func (n *nextIter) fetch() *Iter {
  212. n.once.Do(func() {
  213. n.next = n.qry.session.executeQuery(&n.qry)
  214. })
  215. return n.next
  216. }
  217. type Batch struct {
  218. Type BatchType
  219. Entries []BatchEntry
  220. Cons Consistency
  221. }
  222. func NewBatch(typ BatchType) *Batch {
  223. return &Batch{Type: typ}
  224. }
  225. func (b *Batch) Query(stmt string, args ...interface{}) {
  226. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  227. }
  228. type BatchType int
  229. const (
  230. LoggedBatch BatchType = 0
  231. UnloggedBatch BatchType = 1
  232. CounterBatch BatchType = 2
  233. )
  234. type BatchEntry struct {
  235. Stmt string
  236. Args []interface{}
  237. }
  238. type Consistency int
  239. const (
  240. Any Consistency = 1 + iota
  241. One
  242. Two
  243. Three
  244. Quorum
  245. All
  246. LocalQuorum
  247. EachQuorum
  248. Serial
  249. LocalSerial
  250. )
  251. var consinstencyNames = []string{
  252. 0: "default",
  253. Any: "any",
  254. One: "one",
  255. Two: "two",
  256. Three: "three",
  257. Quorum: "quorum",
  258. All: "all",
  259. LocalQuorum: "localquorum",
  260. EachQuorum: "eachquorum",
  261. Serial: "serial",
  262. LocalSerial: "localserial",
  263. }
  264. func (c Consistency) String() string {
  265. return consinstencyNames[c]
  266. }
  267. type ColumnInfo struct {
  268. Keyspace string
  269. Table string
  270. Name string
  271. TypeInfo *TypeInfo
  272. }
  273. // Tracer is the interface implemented by query tracers. Tracers have the
  274. // ability to obtain a detailed event log of all events that happened during
  275. // the execution of a query from Cassandra. Gathering this information might
  276. // be essential for debugging and optimizing queries, but this feature should
  277. // not be used on production systems with very high load.
  278. type Tracer interface {
  279. Trace(traceId []byte)
  280. }
  281. type traceWriter struct {
  282. session *Session
  283. w io.Writer
  284. mu sync.Mutex
  285. }
  286. // NewTraceWriter returns a simple Tracer implementation that outputs
  287. // the event log in a textual format.
  288. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  289. return traceWriter{session: session, w: w}
  290. }
  291. func (t traceWriter) Trace(traceId []byte) {
  292. var (
  293. coordinator string
  294. duration int
  295. )
  296. t.session.Query(`SELECT coordinator, duration
  297. FROM system_traces.sessions
  298. WHERE session_id = ?`, traceId).
  299. Consistency(One).Scan(&coordinator, &duration)
  300. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  301. FROM system_traces.events
  302. WHERE session_id = ?`, traceId).
  303. Consistency(One).Iter()
  304. var (
  305. timestamp time.Time
  306. activity string
  307. source string
  308. elapsed int
  309. )
  310. t.mu.Lock()
  311. defer t.mu.Unlock()
  312. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  313. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  314. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  315. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  316. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  317. }
  318. if err := iter.Close(); err != nil {
  319. fmt.Fprintln(t.w, "Error:", err)
  320. }
  321. }
  322. type Error struct {
  323. Code int
  324. Message string
  325. }
  326. func (e Error) Error() string {
  327. return e.Message
  328. }
  329. var (
  330. ErrNotFound = errors.New("not found")
  331. ErrUnavailable = errors.New("unavailable")
  332. ErrProtocol = errors.New("protocol error")
  333. ErrUnsupported = errors.New("feature not supported")
  334. )