session.go 13 KB

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