session.go 10 KB

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