session.go 15 KB

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