session.go 10 KB

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