session.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. "strings"
  10. "sync"
  11. "time"
  12. "unicode"
  13. )
  14. // Session is the interface used by users to interact with the database.
  15. //
  16. // It's safe for concurrent use by multiple goroutines and a typical usage
  17. // scenario is to have one global session object to interact with the
  18. // whole Cassandra cluster.
  19. //
  20. // This type extends the Node interface by adding a convinient query builder
  21. // and automatically sets a default consinstency level on all operations
  22. // that do not have a consistency level set.
  23. type Session struct {
  24. Node Node
  25. cons Consistency
  26. pageSize int
  27. prefetch float64
  28. trace Tracer
  29. mu sync.RWMutex
  30. cfg ClusterConfig
  31. closeMu sync.RWMutex
  32. isClosed bool
  33. }
  34. // NewSession wraps an existing Node.
  35. func NewSession(c *clusterImpl) *Session {
  36. return &Session{Node: c, cons: Quorum, prefetch: 0.25, cfg: c.cfg}
  37. }
  38. // SetConsistency sets the default consistency level for this session. This
  39. // setting can also be changed on a per-query basis and the default value
  40. // is Quorum.
  41. func (s *Session) SetConsistency(cons Consistency) {
  42. s.mu.Lock()
  43. s.cons = cons
  44. s.mu.Unlock()
  45. }
  46. // SetPageSize sets the default page size for this session. A value <= 0 will
  47. // disable paging. This setting can also be changed on a per-query basis.
  48. func (s *Session) SetPageSize(n int) {
  49. s.mu.Lock()
  50. s.pageSize = n
  51. s.mu.Unlock()
  52. }
  53. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  54. // there are only p*pageSize rows remaining, the next page will be requested
  55. // automatically. This value can also be changed on a per-query basis and
  56. // the default value is 0.25.
  57. func (s *Session) SetPrefetch(p float64) {
  58. s.mu.Lock()
  59. s.prefetch = p
  60. s.mu.Unlock()
  61. }
  62. // SetTrace sets the default tracer for this session. This setting can also
  63. // be changed on a per-query basis.
  64. func (s *Session) SetTrace(trace Tracer) {
  65. s.mu.Lock()
  66. s.trace = trace
  67. s.mu.Unlock()
  68. }
  69. // Query generates a new query object for interacting with the database.
  70. // Further details of the query may be tweaked using the resulting query
  71. // value before the query is executed.
  72. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  73. s.mu.RLock()
  74. qry := &Query{stmt: stmt, values: values, cons: s.cons,
  75. session: s, pageSize: s.pageSize, trace: s.trace,
  76. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  77. s.mu.RUnlock()
  78. return qry
  79. }
  80. // Close closes all connections. The session is unusable after this
  81. // operation.
  82. func (s *Session) Close() {
  83. s.closeMu.Lock()
  84. defer s.closeMu.Unlock()
  85. if s.isClosed {
  86. return
  87. }
  88. s.isClosed = true
  89. s.Node.Close()
  90. }
  91. func (s *Session) Closed() bool {
  92. s.closeMu.RLock()
  93. closed := s.isClosed
  94. s.closeMu.RUnlock()
  95. return closed
  96. }
  97. func (s *Session) executeQuery(qry *Query) *Iter {
  98. // fail fast
  99. if s.Closed() {
  100. return &Iter{err: ErrSessionClosed}
  101. }
  102. var iter *Iter
  103. for count := 0; count <= qry.rt.NumRetries; count++ {
  104. conn := s.Node.Pick(qry)
  105. //Assign the error unavailable to the iterator
  106. if conn == nil {
  107. iter = &Iter{err: ErrNoConnections}
  108. break
  109. }
  110. iter = conn.executeQuery(qry)
  111. //Exit for loop if the query was successful
  112. if iter.err == nil {
  113. break
  114. }
  115. }
  116. return iter
  117. }
  118. // ExecuteBatch executes a batch operation and returns nil if successful
  119. // otherwise an error is returned describing the failure.
  120. func (s *Session) ExecuteBatch(batch *Batch) error {
  121. // fail fast
  122. if s.Closed() {
  123. return ErrSessionClosed
  124. }
  125. // Prevent the execution of the batch if greater than the limit
  126. // Currently batches have a limit of 65536 queries.
  127. // https://datastax-oss.atlassian.net/browse/JAVA-229
  128. if batch.Size() > BatchSizeMaximum {
  129. return ErrTooManyStmts
  130. }
  131. var err error
  132. for count := 0; count <= batch.rt.NumRetries; count++ {
  133. conn := s.Node.Pick(nil)
  134. //Assign the error unavailable and break loop
  135. if conn == nil {
  136. err = ErrNoConnections
  137. break
  138. }
  139. err = conn.executeBatch(batch)
  140. //Exit loop if operation executed correctly
  141. if err == nil {
  142. return nil
  143. }
  144. }
  145. return err
  146. }
  147. // Query represents a CQL statement that can be executed.
  148. type Query struct {
  149. stmt string
  150. values []interface{}
  151. cons Consistency
  152. pageSize int
  153. pageState []byte
  154. prefetch float64
  155. trace Tracer
  156. session *Session
  157. rt RetryPolicy
  158. }
  159. // Consistency sets the consistency level for this query. If no consistency
  160. // level have been set, the default consistency level of the cluster
  161. // is used.
  162. func (q *Query) Consistency(c Consistency) *Query {
  163. q.cons = c
  164. return q
  165. }
  166. // Trace enables tracing of this query. Look at the documentation of the
  167. // Tracer interface to learn more about tracing.
  168. func (q *Query) Trace(trace Tracer) *Query {
  169. q.trace = trace
  170. return q
  171. }
  172. // PageSize will tell the iterator to fetch the result in pages of size n.
  173. // This is useful for iterating over large result sets, but setting the
  174. // page size to low might decrease the performance. This feature is only
  175. // available in Cassandra 2 and onwards.
  176. func (q *Query) PageSize(n int) *Query {
  177. q.pageSize = n
  178. return q
  179. }
  180. func (q *Query) shouldPrepare() bool {
  181. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  182. return unicode.IsSpace(r) || r == ';'
  183. }), unicode.IsSpace)
  184. var stmtType string
  185. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  186. stmtType = strings.ToLower(stmt[:n])
  187. }
  188. if stmtType == "begin" {
  189. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  190. stmtType = strings.ToLower(stmt[n+1:])
  191. }
  192. }
  193. switch stmtType {
  194. case "select", "insert", "update", "delete", "batch":
  195. return true
  196. }
  197. return false
  198. }
  199. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  200. // there are only p*pageSize rows remaining, the next page will be requested
  201. // automatically.
  202. func (q *Query) Prefetch(p float64) *Query {
  203. q.prefetch = p
  204. return q
  205. }
  206. // RetryPolicy sets the policy to use when retrying the query.
  207. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  208. q.rt = r
  209. return q
  210. }
  211. // Exec executes the query without returning any rows.
  212. func (q *Query) Exec() error {
  213. iter := q.Iter()
  214. return iter.err
  215. }
  216. // Iter executes the query and returns an iterator capable of iterating
  217. // over all results.
  218. func (q *Query) Iter() *Iter {
  219. if strings.Index(strings.ToLower(q.stmt), "use") == 0 {
  220. return &Iter{err: ErrUseStmt}
  221. }
  222. return q.session.executeQuery(q)
  223. }
  224. // Scan executes the query, copies the columns of the first selected
  225. // row into the values pointed at by dest and discards the rest. If no rows
  226. // were selected, ErrNotFound is returned.
  227. func (q *Query) Scan(dest ...interface{}) error {
  228. iter := q.Iter()
  229. if iter.err != nil {
  230. return iter.err
  231. }
  232. if len(iter.rows) == 0 {
  233. return ErrNotFound
  234. }
  235. iter.Scan(dest...)
  236. return iter.Close()
  237. }
  238. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  239. // statement containing an IF clause). If the transaction fails because
  240. // the existing values did not match, the previos values will be stored
  241. // in dest.
  242. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  243. iter := q.Iter()
  244. if iter.err != nil {
  245. return false, iter.err
  246. }
  247. if len(iter.rows) == 0 {
  248. return false, ErrNotFound
  249. }
  250. if len(iter.Columns()) > 1 {
  251. dest = append([]interface{}{&applied}, dest...)
  252. iter.Scan(dest...)
  253. } else {
  254. iter.Scan(&applied)
  255. }
  256. return applied, iter.Close()
  257. }
  258. // Iter represents an iterator that can be used to iterate over all rows that
  259. // were returned by a query. The iterator might send additional queries to the
  260. // database during the iteration if paging was enabled.
  261. type Iter struct {
  262. err error
  263. pos int
  264. rows [][][]byte
  265. columns []ColumnInfo
  266. next *nextIter
  267. }
  268. // Columns returns the name and type of the selected columns.
  269. func (iter *Iter) Columns() []ColumnInfo {
  270. return iter.columns
  271. }
  272. // Scan consumes the next row of the iterator and copies the columns of the
  273. // current row into the values pointed at by dest. Use nil as a dest value
  274. // to skip the corresponding column. Scan might send additional queries
  275. // to the database to retrieve the next set of rows if paging was enabled.
  276. //
  277. // Scan returns true if the row was successfully unmarshaled or false if the
  278. // end of the result set was reached or if an error occurred. Close should
  279. // be called afterwards to retrieve any potential errors.
  280. func (iter *Iter) Scan(dest ...interface{}) bool {
  281. if iter.err != nil {
  282. return false
  283. }
  284. if iter.pos >= len(iter.rows) {
  285. if iter.next != nil {
  286. *iter = *iter.next.fetch()
  287. return iter.Scan(dest...)
  288. }
  289. return false
  290. }
  291. if iter.next != nil && iter.pos == iter.next.pos {
  292. go iter.next.fetch()
  293. }
  294. if len(dest) != len(iter.columns) {
  295. iter.err = errors.New("count mismatch")
  296. return false
  297. }
  298. for i := 0; i < len(iter.columns); i++ {
  299. if dest[i] == nil {
  300. continue
  301. }
  302. err := Unmarshal(iter.columns[i].TypeInfo, iter.rows[iter.pos][i], dest[i])
  303. if err != nil {
  304. iter.err = err
  305. return false
  306. }
  307. }
  308. iter.pos++
  309. return true
  310. }
  311. // Close closes the iterator and returns any errors that happened during
  312. // the query or the iteration.
  313. func (iter *Iter) Close() error {
  314. return iter.err
  315. }
  316. type nextIter struct {
  317. qry Query
  318. pos int
  319. once sync.Once
  320. next *Iter
  321. }
  322. func (n *nextIter) fetch() *Iter {
  323. n.once.Do(func() {
  324. n.next = n.qry.session.executeQuery(&n.qry)
  325. })
  326. return n.next
  327. }
  328. type Batch struct {
  329. Type BatchType
  330. Entries []BatchEntry
  331. Cons Consistency
  332. rt RetryPolicy
  333. }
  334. // NewBatch creates a new batch operation without defaults from the cluster
  335. func NewBatch(typ BatchType) *Batch {
  336. return &Batch{Type: typ}
  337. }
  338. // NewBatch creates a new batch operation using defaults defined in the cluster
  339. func (s *Session) NewBatch(typ BatchType) *Batch {
  340. return &Batch{Type: typ, rt: s.cfg.RetryPolicy}
  341. }
  342. // Query adds the query to the batch operation
  343. func (b *Batch) Query(stmt string, args ...interface{}) {
  344. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  345. }
  346. // RetryPolicy sets the retry policy to use when executing the batch operation
  347. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  348. b.rt = r
  349. return b
  350. }
  351. // Size returns the number of batch statements to be executed by the batch operation.
  352. func (b *Batch) Size() int {
  353. return len(b.Entries)
  354. }
  355. type BatchType int
  356. const (
  357. LoggedBatch BatchType = 0
  358. UnloggedBatch BatchType = 1
  359. CounterBatch BatchType = 2
  360. )
  361. type BatchEntry struct {
  362. Stmt string
  363. Args []interface{}
  364. }
  365. type Consistency int
  366. const (
  367. Any Consistency = 1 + iota
  368. One
  369. Two
  370. Three
  371. Quorum
  372. All
  373. LocalQuorum
  374. EachQuorum
  375. Serial
  376. LocalSerial
  377. )
  378. var consinstencyNames = []string{
  379. 0: "default",
  380. Any: "any",
  381. One: "one",
  382. Two: "two",
  383. Three: "three",
  384. Quorum: "quorum",
  385. All: "all",
  386. LocalQuorum: "localquorum",
  387. EachQuorum: "eachquorum",
  388. Serial: "serial",
  389. LocalSerial: "localserial",
  390. }
  391. func (c Consistency) String() string {
  392. return consinstencyNames[c]
  393. }
  394. type ColumnInfo struct {
  395. Keyspace string
  396. Table string
  397. Name string
  398. TypeInfo *TypeInfo
  399. }
  400. // Tracer is the interface implemented by query tracers. Tracers have the
  401. // ability to obtain a detailed event log of all events that happened during
  402. // the execution of a query from Cassandra. Gathering this information might
  403. // be essential for debugging and optimizing queries, but this feature should
  404. // not be used on production systems with very high load.
  405. type Tracer interface {
  406. Trace(traceId []byte)
  407. }
  408. type traceWriter struct {
  409. session *Session
  410. w io.Writer
  411. mu sync.Mutex
  412. }
  413. // NewTraceWriter returns a simple Tracer implementation that outputs
  414. // the event log in a textual format.
  415. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  416. return traceWriter{session: session, w: w}
  417. }
  418. func (t traceWriter) Trace(traceId []byte) {
  419. var (
  420. coordinator string
  421. duration int
  422. )
  423. t.session.Query(`SELECT coordinator, duration
  424. FROM system_traces.sessions
  425. WHERE session_id = ?`, traceId).
  426. Consistency(One).Scan(&coordinator, &duration)
  427. iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
  428. FROM system_traces.events
  429. WHERE session_id = ?`, traceId).
  430. Consistency(One).Iter()
  431. var (
  432. timestamp time.Time
  433. activity string
  434. source string
  435. elapsed int
  436. )
  437. t.mu.Lock()
  438. defer t.mu.Unlock()
  439. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  440. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  441. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  442. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  443. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  444. }
  445. if err := iter.Close(); err != nil {
  446. fmt.Fprintln(t.w, "Error:", err)
  447. }
  448. }
  449. type Error struct {
  450. Code int
  451. Message string
  452. }
  453. func (e Error) Error() string {
  454. return e.Message
  455. }
  456. var (
  457. ErrNotFound = errors.New("not found")
  458. ErrUnavailable = errors.New("unavailable")
  459. ErrUnsupported = errors.New("feature not supported")
  460. ErrTooManyStmts = errors.New("too many statements")
  461. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  462. ErrSessionClosed = errors.New("session has been closed")
  463. ErrNoConnections = errors.New("no connections available")
  464. )
  465. type ErrProtocol struct{ error }
  466. func NewErrProtocol(format string, args ...interface{}) error {
  467. return ErrProtocol{fmt.Errorf(format, args...)}
  468. }
  469. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  470. // This limit is set by cassandra and could change in the future.
  471. const BatchSizeMaximum = 65535