session.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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(iter.columns); i++ {
  218. if dest[i] == nil {
  219. continue
  220. }
  221. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  222. if err != nil {
  223. iter.err = err
  224. return false
  225. }
  226. }
  227. iter.pos++
  228. return true
  229. }
  230. // Close closes the iterator and returns any errors that happened during
  231. // the query or the iteration.
  232. func (iter *Iter) Close() error {
  233. return iter.err
  234. }
  235. type nextIter struct {
  236. qry Query
  237. pos int
  238. once sync.Once
  239. next *Iter
  240. }
  241. func (n *nextIter) fetch() *Iter {
  242. n.once.Do(func() {
  243. n.next = n.qry.session.executeQuery(&n.qry)
  244. })
  245. return n.next
  246. }
  247. type Batch struct {
  248. Type BatchType
  249. Entries []BatchEntry
  250. Cons Consistency
  251. }
  252. func NewBatch(typ BatchType) *Batch {
  253. return &Batch{Type: typ}
  254. }
  255. func (b *Batch) Query(stmt string, args ...interface{}) {
  256. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  257. }
  258. type BatchType int
  259. const (
  260. LoggedBatch BatchType = 0
  261. UnloggedBatch BatchType = 1
  262. CounterBatch BatchType = 2
  263. )
  264. type BatchEntry struct {
  265. Stmt string
  266. Args []interface{}
  267. }
  268. type Consistency int
  269. const (
  270. Any Consistency = 1 + iota
  271. One
  272. Two
  273. Three
  274. Quorum
  275. All
  276. LocalQuorum
  277. EachQuorum
  278. Serial
  279. LocalSerial
  280. )
  281. var consinstencyNames = []string{
  282. 0: "default",
  283. Any: "any",
  284. One: "one",
  285. Two: "two",
  286. Three: "three",
  287. Quorum: "quorum",
  288. All: "all",
  289. LocalQuorum: "localquorum",
  290. EachQuorum: "eachquorum",
  291. Serial: "serial",
  292. LocalSerial: "localserial",
  293. }
  294. func (c Consistency) String() string {
  295. return consinstencyNames[c]
  296. }
  297. type ColumnInfo struct {
  298. Keyspace string
  299. Table string
  300. Name string
  301. TypeInfo *TypeInfo
  302. }
  303. // Tracer is the interface implemented by query tracers. Tracers have the
  304. // ability to obtain a detailed event log of all events that happened during
  305. // the execution of a query from Cassandra. Gathering this information might
  306. // be essential for debugging and optimizing queries, but this feature should
  307. // not be used on production systems with very high load.
  308. type Tracer interface {
  309. Trace(traceId []byte)
  310. }
  311. type traceWriter struct {
  312. session *Session
  313. w io.Writer
  314. mu sync.Mutex
  315. }
  316. // NewTraceWriter returns a simple Tracer implementation that outputs
  317. // the event log in a textual format.
  318. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  319. return traceWriter{session: session, w: w}
  320. }
  321. func (t traceWriter) Trace(traceId []byte) {
  322. var (
  323. coordinator string
  324. duration int
  325. )
  326. t.session.Query(`SELECT coordinator, duration
  327. FROM system_traces.sessions
  328. WHERE session_id = ?`, traceId).
  329. Consistency(One).Scan(&coordinator, &duration)
  330. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  331. FROM system_traces.events
  332. WHERE session_id = ?`, traceId).
  333. Consistency(One).Iter()
  334. var (
  335. timestamp time.Time
  336. activity string
  337. source string
  338. elapsed int
  339. )
  340. t.mu.Lock()
  341. defer t.mu.Unlock()
  342. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  343. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  344. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  345. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  346. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  347. }
  348. if err := iter.Close(); err != nil {
  349. fmt.Fprintln(t.w, "Error:", err)
  350. }
  351. }
  352. type Error struct {
  353. Code int
  354. Message string
  355. }
  356. func (e Error) Error() string {
  357. return e.Message
  358. }
  359. var (
  360. ErrNotFound = errors.New("not found")
  361. ErrUnavailable = errors.New("unavailable")
  362. ErrProtocol = errors.New("protocol error")
  363. ErrUnsupported = errors.New("feature not supported")
  364. )