session.go 9.9 KB

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