session.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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. "bytes"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "log"
  12. "net"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "time"
  18. "unicode"
  19. "golang.org/x/net/context"
  20. "github.com/gocql/gocql/internal/lru"
  21. )
  22. // Session is the interface used by users to interact with the database.
  23. //
  24. // It's safe for concurrent use by multiple goroutines and a typical usage
  25. // scenario is to have one global session object to interact with the
  26. // whole Cassandra cluster.
  27. //
  28. // This type extends the Node interface by adding a convinient query builder
  29. // and automatically sets a default consinstency level on all operations
  30. // that do not have a consistency level set.
  31. type Session struct {
  32. cons Consistency
  33. pageSize int
  34. prefetch float64
  35. routingKeyInfoCache routingKeyInfoLRU
  36. schemaDescriber *schemaDescriber
  37. trace Tracer
  38. hostSource *ringDescriber
  39. stmtsLRU *preparedLRU
  40. connCfg *ConnConfig
  41. executor *queryExecutor
  42. pool *policyConnPool
  43. policy HostSelectionPolicy
  44. ring ring
  45. metadata clusterMetadata
  46. mu sync.RWMutex
  47. control *controlConn
  48. // event handlers
  49. nodeEvents *eventDeouncer
  50. schemaEvents *eventDeouncer
  51. // ring metadata
  52. hosts []HostInfo
  53. useSystemSchema bool
  54. cfg ClusterConfig
  55. closeMu sync.RWMutex
  56. isClosed bool
  57. }
  58. func addrsToHosts(addrs []string, defaultPort int) ([]*HostInfo, error) {
  59. hosts := make([]*HostInfo, len(addrs))
  60. for i, hostport := range addrs {
  61. // TODO: remove duplication
  62. addr, portStr, err := net.SplitHostPort(JoinHostPort(hostport, defaultPort))
  63. if err != nil {
  64. return nil, fmt.Errorf("NewSession: unable to parse hostport of addr %q: %v", hostport, err)
  65. }
  66. port, err := strconv.Atoi(portStr)
  67. if err != nil {
  68. return nil, fmt.Errorf("NewSession: invalid port for hostport of addr %q: %v", hostport, err)
  69. }
  70. hosts[i] = &HostInfo{peer: addr, port: port, state: NodeUp}
  71. }
  72. return hosts, nil
  73. }
  74. // NewSession wraps an existing Node.
  75. func NewSession(cfg ClusterConfig) (*Session, error) {
  76. //Check that hosts in the ClusterConfig is not empty
  77. if len(cfg.Hosts) < 1 {
  78. return nil, ErrNoHosts
  79. }
  80. s := &Session{
  81. cons: cfg.Consistency,
  82. prefetch: 0.25,
  83. cfg: cfg,
  84. pageSize: cfg.PageSize,
  85. stmtsLRU: &preparedLRU{lru: lru.New(cfg.MaxPreparedStmts)},
  86. }
  87. connCfg, err := connConfig(s)
  88. if err != nil {
  89. s.Close()
  90. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  91. }
  92. s.connCfg = connCfg
  93. s.nodeEvents = newEventDeouncer("NodeEvents", s.handleNodeEvent)
  94. s.schemaEvents = newEventDeouncer("SchemaEvents", s.handleSchemaEvent)
  95. s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)
  96. // I think it might be a good idea to simplify this and make it always discover
  97. // hosts, maybe with more filters.
  98. s.hostSource = &ringDescriber{
  99. session: s,
  100. closeChan: make(chan bool),
  101. }
  102. pool := cfg.PoolConfig.buildPool(s)
  103. if cfg.PoolConfig.HostSelectionPolicy == nil {
  104. cfg.PoolConfig.HostSelectionPolicy = RoundRobinHostPolicy()
  105. }
  106. s.pool = pool
  107. s.policy = cfg.PoolConfig.HostSelectionPolicy
  108. s.executor = &queryExecutor{
  109. pool: pool,
  110. policy: cfg.PoolConfig.HostSelectionPolicy,
  111. }
  112. var hosts []*HostInfo
  113. if !cfg.disableControlConn {
  114. s.control = createControlConn(s)
  115. if err := s.control.connect(cfg.Hosts); err != nil {
  116. s.Close()
  117. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  118. }
  119. // need to setup host source to check for broadcast_address in system.local
  120. localHasRPCAddr, _ := checkSystemLocal(s.control)
  121. s.hostSource.localHasRpcAddr = localHasRPCAddr
  122. var err error
  123. if cfg.DisableInitialHostLookup {
  124. // TODO: we could look at system.local to get token and other metadata
  125. // in this case.
  126. hosts, err = addrsToHosts(cfg.Hosts, cfg.Port)
  127. } else {
  128. hosts, _, err = s.hostSource.GetHosts()
  129. }
  130. if err != nil {
  131. s.Close()
  132. return nil, fmt.Errorf("gocql: unable to create session: %v", err)
  133. }
  134. } else {
  135. // we dont get host info
  136. hosts, err = addrsToHosts(cfg.Hosts, cfg.Port)
  137. }
  138. for _, host := range hosts {
  139. if s.cfg.HostFilter == nil || s.cfg.HostFilter.Accept(host) {
  140. if existingHost, ok := s.ring.addHostIfMissing(host); ok {
  141. existingHost.update(host)
  142. }
  143. s.handleNodeUp(net.ParseIP(host.Peer()), host.Port(), false)
  144. }
  145. }
  146. if cfg.ReconnectInterval > 0 {
  147. go func() {
  148. for !s.Closed() {
  149. time.Sleep(cfg.ReconnectInterval)
  150. hosts := s.ring.allHosts()
  151. // Print session.ring for debug.
  152. if gocqlDebug {
  153. buf := bytes.NewBufferString("Session.ring:")
  154. for _, h := range hosts {
  155. buf.WriteString("[" + h.Peer() + ":" + h.State().String() + "]")
  156. }
  157. log.Println(buf.String())
  158. }
  159. for _, h := range hosts {
  160. if h.IsUp() {
  161. continue
  162. }
  163. s.handleNodeUp(net.ParseIP(h.peer), h.port, true)
  164. }
  165. }
  166. }()
  167. }
  168. // TODO(zariel): we probably dont need this any more as we verify that we
  169. // can connect to one of the endpoints supplied by using the control conn.
  170. // See if there are any connections in the pool
  171. if s.pool.Size() == 0 {
  172. s.Close()
  173. return nil, ErrNoConnectionsStarted
  174. }
  175. s.useSystemSchema = hosts[0].Version().Major >= 3
  176. return s, nil
  177. }
  178. // SetConsistency sets the default consistency level for this session. This
  179. // setting can also be changed on a per-query basis and the default value
  180. // is Quorum.
  181. func (s *Session) SetConsistency(cons Consistency) {
  182. s.mu.Lock()
  183. s.cons = cons
  184. s.mu.Unlock()
  185. }
  186. // SetPageSize sets the default page size for this session. A value <= 0 will
  187. // disable paging. This setting can also be changed on a per-query basis.
  188. func (s *Session) SetPageSize(n int) {
  189. s.mu.Lock()
  190. s.pageSize = n
  191. s.mu.Unlock()
  192. }
  193. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  194. // there are only p*pageSize rows remaining, the next page will be requested
  195. // automatically. This value can also be changed on a per-query basis and
  196. // the default value is 0.25.
  197. func (s *Session) SetPrefetch(p float64) {
  198. s.mu.Lock()
  199. s.prefetch = p
  200. s.mu.Unlock()
  201. }
  202. // SetTrace sets the default tracer for this session. This setting can also
  203. // be changed on a per-query basis.
  204. func (s *Session) SetTrace(trace Tracer) {
  205. s.mu.Lock()
  206. s.trace = trace
  207. s.mu.Unlock()
  208. }
  209. // Query generates a new query object for interacting with the database.
  210. // Further details of the query may be tweaked using the resulting query
  211. // value before the query is executed. Query is automatically prepared
  212. // if it has not previously been executed.
  213. func (s *Session) Query(stmt string, values ...interface{}) *Query {
  214. s.mu.RLock()
  215. qry := &Query{stmt: stmt, values: values, cons: s.cons,
  216. session: s, pageSize: s.pageSize, trace: s.trace,
  217. prefetch: s.prefetch, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  218. defaultTimestamp: s.cfg.DefaultTimestamp,
  219. }
  220. s.mu.RUnlock()
  221. return qry
  222. }
  223. type QueryInfo struct {
  224. Id []byte
  225. Args []ColumnInfo
  226. Rval []ColumnInfo
  227. PKeyColumns []int
  228. }
  229. // Bind generates a new query object based on the query statement passed in.
  230. // The query is automatically prepared if it has not previously been executed.
  231. // The binding callback allows the application to define which query argument
  232. // values will be marshalled as part of the query execution.
  233. // During execution, the meta data of the prepared query will be routed to the
  234. // binding callback, which is responsible for producing the query argument values.
  235. func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
  236. s.mu.RLock()
  237. qry := &Query{stmt: stmt, binding: b, cons: s.cons,
  238. session: s, pageSize: s.pageSize, trace: s.trace,
  239. prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
  240. s.mu.RUnlock()
  241. return qry
  242. }
  243. // Close closes all connections. The session is unusable after this
  244. // operation.
  245. func (s *Session) Close() {
  246. s.closeMu.Lock()
  247. defer s.closeMu.Unlock()
  248. if s.isClosed {
  249. return
  250. }
  251. s.isClosed = true
  252. if s.pool != nil {
  253. s.pool.Close()
  254. }
  255. if s.hostSource != nil {
  256. close(s.hostSource.closeChan)
  257. }
  258. if s.control != nil {
  259. s.control.close()
  260. }
  261. if s.nodeEvents != nil {
  262. s.nodeEvents.stop()
  263. }
  264. if s.schemaEvents != nil {
  265. s.schemaEvents.stop()
  266. }
  267. }
  268. func (s *Session) Closed() bool {
  269. s.closeMu.RLock()
  270. closed := s.isClosed
  271. s.closeMu.RUnlock()
  272. return closed
  273. }
  274. func (s *Session) executeQuery(qry *Query) *Iter {
  275. // fail fast
  276. if s.Closed() {
  277. return &Iter{err: ErrSessionClosed}
  278. }
  279. iter, err := s.executor.executeQuery(qry)
  280. if err != nil {
  281. return &Iter{err: err}
  282. }
  283. if iter == nil {
  284. panic("nil iter")
  285. }
  286. return iter
  287. }
  288. // KeyspaceMetadata returns the schema metadata for the keyspace specified.
  289. func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
  290. // fail fast
  291. if s.Closed() {
  292. return nil, ErrSessionClosed
  293. }
  294. if keyspace == "" {
  295. return nil, ErrNoKeyspace
  296. }
  297. s.mu.Lock()
  298. // lazy-init schemaDescriber
  299. if s.schemaDescriber == nil {
  300. s.schemaDescriber = newSchemaDescriber(s)
  301. }
  302. s.mu.Unlock()
  303. return s.schemaDescriber.getSchema(keyspace)
  304. }
  305. func (s *Session) getConn() *Conn {
  306. hosts := s.ring.allHosts()
  307. var conn *Conn
  308. for _, host := range hosts {
  309. if !host.IsUp() {
  310. continue
  311. }
  312. pool, ok := s.pool.getPool(host.Peer())
  313. if !ok {
  314. continue
  315. }
  316. conn = pool.Pick()
  317. if conn != nil {
  318. return conn
  319. }
  320. }
  321. return nil
  322. }
  323. // returns routing key indexes and type info
  324. func (s *Session) routingKeyInfo(ctx context.Context, stmt string) (*routingKeyInfo, error) {
  325. s.routingKeyInfoCache.mu.Lock()
  326. entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
  327. if cached {
  328. // done accessing the cache
  329. s.routingKeyInfoCache.mu.Unlock()
  330. // the entry is an inflight struct similiar to that used by
  331. // Conn to prepare statements
  332. inflight := entry.(*inflightCachedEntry)
  333. // wait for any inflight work
  334. inflight.wg.Wait()
  335. if inflight.err != nil {
  336. return nil, inflight.err
  337. }
  338. key, _ := inflight.value.(*routingKeyInfo)
  339. return key, nil
  340. }
  341. // create a new inflight entry while the data is created
  342. inflight := new(inflightCachedEntry)
  343. inflight.wg.Add(1)
  344. defer inflight.wg.Done()
  345. s.routingKeyInfoCache.lru.Add(stmt, inflight)
  346. s.routingKeyInfoCache.mu.Unlock()
  347. var (
  348. info *preparedStatment
  349. partitionKey []*ColumnMetadata
  350. )
  351. conn := s.getConn()
  352. if conn == nil {
  353. // TODO: better error?
  354. inflight.err = errors.New("gocql: unable to fetch preapred info: no connection avilable")
  355. return nil, inflight.err
  356. }
  357. // get the query info for the statement
  358. info, inflight.err = conn.prepareStatement(ctx, stmt, nil)
  359. if inflight.err != nil {
  360. // don't cache this error
  361. s.routingKeyInfoCache.Remove(stmt)
  362. return nil, inflight.err
  363. }
  364. // TODO: it would be nice to mark hosts here but as we are not using the policies
  365. // to fetch hosts we cant
  366. if info.request.colCount == 0 {
  367. // no arguments, no routing key, and no error
  368. return nil, nil
  369. }
  370. if len(info.request.pkeyColumns) > 0 {
  371. // proto v4 dont need to calculate primary key columns
  372. types := make([]TypeInfo, len(info.request.pkeyColumns))
  373. for i, col := range info.request.pkeyColumns {
  374. types[i] = info.request.columns[col].TypeInfo
  375. }
  376. routingKeyInfo := &routingKeyInfo{
  377. indexes: info.request.pkeyColumns,
  378. types: types,
  379. }
  380. inflight.value = routingKeyInfo
  381. return routingKeyInfo, nil
  382. }
  383. // get the table metadata
  384. table := info.request.columns[0].Table
  385. var keyspaceMetadata *KeyspaceMetadata
  386. keyspaceMetadata, inflight.err = s.KeyspaceMetadata(info.request.columns[0].Keyspace)
  387. if inflight.err != nil {
  388. // don't cache this error
  389. s.routingKeyInfoCache.Remove(stmt)
  390. return nil, inflight.err
  391. }
  392. tableMetadata, found := keyspaceMetadata.Tables[table]
  393. if !found {
  394. // unlikely that the statement could be prepared and the metadata for
  395. // the table couldn't be found, but this may indicate either a bug
  396. // in the metadata code, or that the table was just dropped.
  397. inflight.err = ErrNoMetadata
  398. // don't cache this error
  399. s.routingKeyInfoCache.Remove(stmt)
  400. return nil, inflight.err
  401. }
  402. partitionKey = tableMetadata.PartitionKey
  403. size := len(partitionKey)
  404. routingKeyInfo := &routingKeyInfo{
  405. indexes: make([]int, size),
  406. types: make([]TypeInfo, size),
  407. }
  408. for keyIndex, keyColumn := range partitionKey {
  409. // set an indicator for checking if the mapping is missing
  410. routingKeyInfo.indexes[keyIndex] = -1
  411. // find the column in the query info
  412. for argIndex, boundColumn := range info.request.columns {
  413. if keyColumn.Name == boundColumn.Name {
  414. // there may be many such bound columns, pick the first
  415. routingKeyInfo.indexes[keyIndex] = argIndex
  416. routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
  417. break
  418. }
  419. }
  420. if routingKeyInfo.indexes[keyIndex] == -1 {
  421. // missing a routing key column mapping
  422. // no routing key, and no error
  423. return nil, nil
  424. }
  425. }
  426. // cache this result
  427. inflight.value = routingKeyInfo
  428. return routingKeyInfo, nil
  429. }
  430. func (b *Batch) execute(conn *Conn) *Iter {
  431. return conn.executeBatch(b)
  432. }
  433. func (s *Session) executeBatch(batch *Batch) *Iter {
  434. // fail fast
  435. if s.Closed() {
  436. return &Iter{err: ErrSessionClosed}
  437. }
  438. // Prevent the execution of the batch if greater than the limit
  439. // Currently batches have a limit of 65536 queries.
  440. // https://datastax-oss.atlassian.net/browse/JAVA-229
  441. if batch.Size() > BatchSizeMaximum {
  442. return &Iter{err: ErrTooManyStmts}
  443. }
  444. iter, err := s.executor.executeQuery(batch)
  445. if err != nil {
  446. return &Iter{err: err}
  447. }
  448. return iter
  449. }
  450. // ExecuteBatch executes a batch operation and returns nil if successful
  451. // otherwise an error is returned describing the failure.
  452. func (s *Session) ExecuteBatch(batch *Batch) error {
  453. iter := s.executeBatch(batch)
  454. return iter.Close()
  455. }
  456. // ExecuteBatchCAS executes a batch operation and returns true if successful and
  457. // an iterator (to scan aditional rows if more than one conditional statement)
  458. // was sent.
  459. // Further scans on the interator must also remember to include
  460. // the applied boolean as the first argument to *Iter.Scan
  461. func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (applied bool, iter *Iter, err error) {
  462. iter = s.executeBatch(batch)
  463. if err := iter.checkErrAndNotFound(); err != nil {
  464. iter.Close()
  465. return false, nil, err
  466. }
  467. if len(iter.Columns()) > 1 {
  468. dest = append([]interface{}{&applied}, dest...)
  469. iter.Scan(dest...)
  470. } else {
  471. iter.Scan(&applied)
  472. }
  473. return applied, iter, nil
  474. }
  475. // MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,
  476. // however it accepts a map rather than a list of arguments for the initial
  477. // scan.
  478. func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error) {
  479. iter = s.executeBatch(batch)
  480. if err := iter.checkErrAndNotFound(); err != nil {
  481. iter.Close()
  482. return false, nil, err
  483. }
  484. iter.MapScan(dest)
  485. applied = dest["[applied]"].(bool)
  486. delete(dest, "[applied]")
  487. // we usually close here, but instead of closing, just returin an error
  488. // if MapScan failed. Although Close just returns err, using Close
  489. // here might be confusing as we are not actually closing the iter
  490. return applied, iter, iter.err
  491. }
  492. func (s *Session) connect(addr string, errorHandler ConnErrorHandler, host *HostInfo) (*Conn, error) {
  493. return Connect(host, addr, s.connCfg, errorHandler, s)
  494. }
  495. // Query represents a CQL statement that can be executed.
  496. type Query struct {
  497. stmt string
  498. values []interface{}
  499. cons Consistency
  500. pageSize int
  501. routingKey []byte
  502. routingKeyBuffer []byte
  503. pageState []byte
  504. prefetch float64
  505. trace Tracer
  506. session *Session
  507. rt RetryPolicy
  508. binding func(q *QueryInfo) ([]interface{}, error)
  509. attempts int
  510. totalLatency int64
  511. serialCons SerialConsistency
  512. defaultTimestamp bool
  513. defaultTimestampValue int64
  514. disableSkipMetadata bool
  515. context context.Context
  516. disableAutoPage bool
  517. }
  518. // String implements the stringer interface.
  519. func (q Query) String() string {
  520. return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
  521. }
  522. //Attempts returns the number of times the query was executed.
  523. func (q *Query) Attempts() int {
  524. return q.attempts
  525. }
  526. //Latency returns the average amount of nanoseconds per attempt of the query.
  527. func (q *Query) Latency() int64 {
  528. if q.attempts > 0 {
  529. return q.totalLatency / int64(q.attempts)
  530. }
  531. return 0
  532. }
  533. // Consistency sets the consistency level for this query. If no consistency
  534. // level have been set, the default consistency level of the cluster
  535. // is used.
  536. func (q *Query) Consistency(c Consistency) *Query {
  537. q.cons = c
  538. return q
  539. }
  540. // GetConsistency returns the currently configured consistency level for
  541. // the query.
  542. func (q *Query) GetConsistency() Consistency {
  543. return q.cons
  544. }
  545. // Trace enables tracing of this query. Look at the documentation of the
  546. // Tracer interface to learn more about tracing.
  547. func (q *Query) Trace(trace Tracer) *Query {
  548. q.trace = trace
  549. return q
  550. }
  551. // PageSize will tell the iterator to fetch the result in pages of size n.
  552. // This is useful for iterating over large result sets, but setting the
  553. // page size too low might decrease the performance. This feature is only
  554. // available in Cassandra 2 and onwards.
  555. func (q *Query) PageSize(n int) *Query {
  556. q.pageSize = n
  557. return q
  558. }
  559. // DefaultTimestamp will enable the with default timestamp flag on the query.
  560. // If enable, this will replace the server side assigned
  561. // timestamp as default timestamp. Note that a timestamp in the query itself
  562. // will still override this timestamp. This is entirely optional.
  563. //
  564. // Only available on protocol >= 3
  565. func (q *Query) DefaultTimestamp(enable bool) *Query {
  566. q.defaultTimestamp = enable
  567. return q
  568. }
  569. // WithTimestamp will enable the with default timestamp flag on the query
  570. // like DefaultTimestamp does. But also allows to define value for timestamp.
  571. // It works the same way as USING TIMESTAMP in the query itself, but
  572. // should not break prepared query optimization
  573. //
  574. // Only available on protocol >= 3
  575. func (q *Query) WithTimestamp(timestamp int64) *Query {
  576. q.DefaultTimestamp(true)
  577. q.defaultTimestampValue = timestamp
  578. return q
  579. }
  580. // RoutingKey sets the routing key to use when a token aware connection
  581. // pool is used to optimize the routing of this query.
  582. func (q *Query) RoutingKey(routingKey []byte) *Query {
  583. q.routingKey = routingKey
  584. return q
  585. }
  586. // WithContext will set the context to use during a query, it will be used to
  587. // timeout when waiting for responses from Cassandra.
  588. func (q *Query) WithContext(ctx context.Context) *Query {
  589. q.context = ctx
  590. return q
  591. }
  592. func (q *Query) execute(conn *Conn) *Iter {
  593. return conn.executeQuery(q)
  594. }
  595. func (q *Query) attempt(d time.Duration) {
  596. q.attempts++
  597. q.totalLatency += d.Nanoseconds()
  598. // TODO: track latencies per host and things as well instead of just total
  599. }
  600. func (q *Query) retryPolicy() RetryPolicy {
  601. return q.rt
  602. }
  603. // GetRoutingKey gets the routing key to use for routing this query. If
  604. // a routing key has not been explicitly set, then the routing key will
  605. // be constructed if possible using the keyspace's schema and the query
  606. // info for this query statement. If the routing key cannot be determined
  607. // then nil will be returned with no error. On any error condition,
  608. // an error description will be returned.
  609. func (q *Query) GetRoutingKey() ([]byte, error) {
  610. if q.routingKey != nil {
  611. return q.routingKey, nil
  612. } else if q.binding != nil && len(q.values) == 0 {
  613. // If this query was created using session.Bind we wont have the query
  614. // values yet, so we have to pass down to the next policy.
  615. // TODO: Remove this and handle this case
  616. return nil, nil
  617. }
  618. // try to determine the routing key
  619. routingKeyInfo, err := q.session.routingKeyInfo(q.context, q.stmt)
  620. if err != nil {
  621. return nil, err
  622. }
  623. if routingKeyInfo == nil {
  624. return nil, nil
  625. }
  626. if len(routingKeyInfo.indexes) == 1 {
  627. // single column routing key
  628. routingKey, err := Marshal(
  629. routingKeyInfo.types[0],
  630. q.values[routingKeyInfo.indexes[0]],
  631. )
  632. if err != nil {
  633. return nil, err
  634. }
  635. return routingKey, nil
  636. }
  637. // We allocate that buffer only once, so that further re-bind/exec of the
  638. // same query don't allocate more memory.
  639. if q.routingKeyBuffer == nil {
  640. q.routingKeyBuffer = make([]byte, 0, 256)
  641. }
  642. // composite routing key
  643. buf := bytes.NewBuffer(q.routingKeyBuffer)
  644. for i := range routingKeyInfo.indexes {
  645. encoded, err := Marshal(
  646. routingKeyInfo.types[i],
  647. q.values[routingKeyInfo.indexes[i]],
  648. )
  649. if err != nil {
  650. return nil, err
  651. }
  652. lenBuf := []byte{0x00, 0x00}
  653. binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
  654. buf.Write(lenBuf)
  655. buf.Write(encoded)
  656. buf.WriteByte(0x00)
  657. }
  658. routingKey := buf.Bytes()
  659. return routingKey, nil
  660. }
  661. func (q *Query) shouldPrepare() bool {
  662. stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
  663. return unicode.IsSpace(r) || r == ';'
  664. }), unicode.IsSpace)
  665. var stmtType string
  666. if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
  667. stmtType = strings.ToLower(stmt[:n])
  668. }
  669. if stmtType == "begin" {
  670. if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
  671. stmtType = strings.ToLower(stmt[n+1:])
  672. }
  673. }
  674. switch stmtType {
  675. case "select", "insert", "update", "delete", "batch":
  676. return true
  677. }
  678. return false
  679. }
  680. // SetPrefetch sets the default threshold for pre-fetching new pages. If
  681. // there are only p*pageSize rows remaining, the next page will be requested
  682. // automatically.
  683. func (q *Query) Prefetch(p float64) *Query {
  684. q.prefetch = p
  685. return q
  686. }
  687. // RetryPolicy sets the policy to use when retrying the query.
  688. func (q *Query) RetryPolicy(r RetryPolicy) *Query {
  689. q.rt = r
  690. return q
  691. }
  692. // Bind sets query arguments of query. This can also be used to rebind new query arguments
  693. // to an existing query instance.
  694. func (q *Query) Bind(v ...interface{}) *Query {
  695. q.values = v
  696. return q
  697. }
  698. // SerialConsistency sets the consistency level for the
  699. // serial phase of conditional updates. That consistency can only be
  700. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  701. // SERIAL. This option will be ignored for anything else that a
  702. // conditional update/insert.
  703. func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
  704. q.serialCons = cons
  705. return q
  706. }
  707. // PageState sets the paging state for the query to resume paging from a specific
  708. // point in time. Setting this will disable to query paging for this query, and
  709. // must be used for all subsequent pages.
  710. func (q *Query) PageState(state []byte) *Query {
  711. q.pageState = state
  712. q.disableAutoPage = true
  713. return q
  714. }
  715. // NoSkipMetadata will override the internal result metadata cache so that the driver does not
  716. // send skip_metadata for queries, this means that the result will always contain
  717. // the metadata to parse the rows and will not reuse the metadata from the prepared
  718. // staement. This should only be used to work around cassandra bugs, such as when using
  719. // CAS operations which do not end in Cas.
  720. //
  721. // See https://issues.apache.org/jira/browse/CASSANDRA-11099
  722. // https://github.com/gocql/gocql/issues/612
  723. func (q *Query) NoSkipMetadata() *Query {
  724. q.disableSkipMetadata = true
  725. return q
  726. }
  727. // Exec executes the query without returning any rows.
  728. func (q *Query) Exec() error {
  729. return q.Iter().Close()
  730. }
  731. func isUseStatement(stmt string) bool {
  732. if len(stmt) < 3 {
  733. return false
  734. }
  735. return strings.ToLower(stmt[0:3]) == "use"
  736. }
  737. // Iter executes the query and returns an iterator capable of iterating
  738. // over all results.
  739. func (q *Query) Iter() *Iter {
  740. if isUseStatement(q.stmt) {
  741. return &Iter{err: ErrUseStmt}
  742. }
  743. return q.session.executeQuery(q)
  744. }
  745. // MapScan executes the query, copies the columns of the first selected
  746. // row into the map pointed at by m and discards the rest. If no rows
  747. // were selected, ErrNotFound is returned.
  748. func (q *Query) MapScan(m map[string]interface{}) error {
  749. iter := q.Iter()
  750. if err := iter.checkErrAndNotFound(); err != nil {
  751. return err
  752. }
  753. iter.MapScan(m)
  754. return iter.Close()
  755. }
  756. // Scan executes the query, copies the columns of the first selected
  757. // row into the values pointed at by dest and discards the rest. If no rows
  758. // were selected, ErrNotFound is returned.
  759. func (q *Query) Scan(dest ...interface{}) error {
  760. iter := q.Iter()
  761. if err := iter.checkErrAndNotFound(); err != nil {
  762. return err
  763. }
  764. iter.Scan(dest...)
  765. return iter.Close()
  766. }
  767. // ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  768. // statement containing an IF clause). If the transaction fails because
  769. // the existing values did not match, the previous values will be stored
  770. // in dest.
  771. func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
  772. q.disableSkipMetadata = true
  773. iter := q.Iter()
  774. if err := iter.checkErrAndNotFound(); err != nil {
  775. return false, err
  776. }
  777. if len(iter.Columns()) > 1 {
  778. dest = append([]interface{}{&applied}, dest...)
  779. iter.Scan(dest...)
  780. } else {
  781. iter.Scan(&applied)
  782. }
  783. return applied, iter.Close()
  784. }
  785. // MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
  786. // statement containing an IF clause). If the transaction fails because
  787. // the existing values did not match, the previous values will be stored
  788. // in dest map.
  789. //
  790. // As for INSERT .. IF NOT EXISTS, previous values will be returned as if
  791. // SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
  792. // column mismatching. MapScanCAS is added to capture them safely.
  793. func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
  794. q.disableSkipMetadata = true
  795. iter := q.Iter()
  796. if err := iter.checkErrAndNotFound(); err != nil {
  797. return false, err
  798. }
  799. iter.MapScan(dest)
  800. applied = dest["[applied]"].(bool)
  801. delete(dest, "[applied]")
  802. return applied, iter.Close()
  803. }
  804. // Iter represents an iterator that can be used to iterate over all rows that
  805. // were returned by a query. The iterator might send additional queries to the
  806. // database during the iteration if paging was enabled.
  807. type Iter struct {
  808. err error
  809. pos int
  810. meta resultMetadata
  811. numRows int
  812. next *nextIter
  813. host *HostInfo
  814. framer *framer
  815. closed int32
  816. }
  817. // Host returns the host which the query was sent to.
  818. func (iter *Iter) Host() *HostInfo {
  819. return iter.host
  820. }
  821. // Columns returns the name and type of the selected columns.
  822. func (iter *Iter) Columns() []ColumnInfo {
  823. return iter.meta.columns
  824. }
  825. func (iter *Iter) readColumn() ([]byte, error) {
  826. return iter.framer.readBytesInternal()
  827. }
  828. // Scan consumes the next row of the iterator and copies the columns of the
  829. // current row into the values pointed at by dest. Use nil as a dest value
  830. // to skip the corresponding column. Scan might send additional queries
  831. // to the database to retrieve the next set of rows if paging was enabled.
  832. //
  833. // Scan returns true if the row was successfully unmarshaled or false if the
  834. // end of the result set was reached or if an error occurred. Close should
  835. // be called afterwards to retrieve any potential errors.
  836. func (iter *Iter) Scan(dest ...interface{}) bool {
  837. if iter.err != nil {
  838. return false
  839. }
  840. if iter.pos >= iter.numRows {
  841. if iter.next != nil {
  842. *iter = *iter.next.fetch()
  843. return iter.Scan(dest...)
  844. }
  845. return false
  846. }
  847. if iter.next != nil && iter.pos == iter.next.pos {
  848. go iter.next.fetch()
  849. }
  850. // currently only support scanning into an expand tuple, such that its the same
  851. // as scanning in more values from a single column
  852. if len(dest) != iter.meta.actualColCount {
  853. iter.err = fmt.Errorf("gocql: not enough columns to scan into: have %d want %d", len(dest), iter.meta.actualColCount)
  854. return false
  855. }
  856. // i is the current position in dest, could posible replace it and just use
  857. // slices of dest
  858. i := 0
  859. for c := range iter.meta.columns {
  860. col := &iter.meta.columns[c]
  861. colBytes, err := iter.readColumn()
  862. if err != nil {
  863. iter.err = err
  864. return false
  865. }
  866. if dest[i] == nil {
  867. i++
  868. continue
  869. }
  870. switch col.TypeInfo.Type() {
  871. case TypeTuple:
  872. // this will panic, actually a bug, please report
  873. tuple := col.TypeInfo.(TupleTypeInfo)
  874. count := len(tuple.Elems)
  875. // here we pass in a slice of the struct which has the number number of
  876. // values as elements in the tuple
  877. iter.err = Unmarshal(col.TypeInfo, colBytes, dest[i:i+count])
  878. i += count
  879. default:
  880. iter.err = Unmarshal(col.TypeInfo, colBytes, dest[i])
  881. i++
  882. }
  883. if iter.err != nil {
  884. return false
  885. }
  886. }
  887. iter.pos++
  888. return true
  889. }
  890. // GetCustomPayload returns any parsed custom payload results if given in the
  891. // response from Cassandra. Note that the result is not a copy.
  892. //
  893. // This additional feature of CQL Protocol v4
  894. // allows additional results and query information to be returned by
  895. // custom QueryHandlers running in your C* cluster.
  896. // See https://datastax.github.io/java-driver/manual/custom_payloads/
  897. func (iter *Iter) GetCustomPayload() map[string][]byte {
  898. return iter.framer.header.customPayload
  899. }
  900. // Close closes the iterator and returns any errors that happened during
  901. // the query or the iteration.
  902. func (iter *Iter) Close() error {
  903. if atomic.CompareAndSwapInt32(&iter.closed, 0, 1) {
  904. if iter.framer != nil {
  905. framerPool.Put(iter.framer)
  906. iter.framer = nil
  907. }
  908. }
  909. return iter.err
  910. }
  911. // WillSwitchPage detects if iterator reached end of current page
  912. // and the next page is available.
  913. func (iter *Iter) WillSwitchPage() bool {
  914. return iter.pos >= iter.numRows && iter.next != nil
  915. }
  916. // checkErrAndNotFound handle error and NotFound in one method.
  917. func (iter *Iter) checkErrAndNotFound() error {
  918. if iter.err != nil {
  919. return iter.err
  920. } else if iter.numRows == 0 {
  921. return ErrNotFound
  922. }
  923. return nil
  924. }
  925. // PageState return the current paging state for a query which can be used for
  926. // subsequent quries to resume paging this point.
  927. func (iter *Iter) PageState() []byte {
  928. return iter.meta.pagingState
  929. }
  930. // NumRows returns the number of rows in this pagination, it will update when new
  931. // pages are fetcehd, it is not the value of the total number of rows this iter
  932. // will return unless there is only a single page returned.
  933. func (iter *Iter) NumRows() int {
  934. return iter.numRows
  935. }
  936. type nextIter struct {
  937. qry Query
  938. pos int
  939. once sync.Once
  940. next *Iter
  941. }
  942. func (n *nextIter) fetch() *Iter {
  943. n.once.Do(func() {
  944. n.next = n.qry.session.executeQuery(&n.qry)
  945. })
  946. return n.next
  947. }
  948. type Batch struct {
  949. Type BatchType
  950. Entries []BatchEntry
  951. Cons Consistency
  952. rt RetryPolicy
  953. attempts int
  954. totalLatency int64
  955. serialCons SerialConsistency
  956. defaultTimestamp bool
  957. context context.Context
  958. }
  959. // NewBatch creates a new batch operation without defaults from the cluster
  960. func NewBatch(typ BatchType) *Batch {
  961. return &Batch{Type: typ}
  962. }
  963. // NewBatch creates a new batch operation using defaults defined in the cluster
  964. func (s *Session) NewBatch(typ BatchType) *Batch {
  965. s.mu.RLock()
  966. batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
  967. Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
  968. s.mu.RUnlock()
  969. return batch
  970. }
  971. // Attempts returns the number of attempts made to execute the batch.
  972. func (b *Batch) Attempts() int {
  973. return b.attempts
  974. }
  975. //Latency returns the average number of nanoseconds to execute a single attempt of the batch.
  976. func (b *Batch) Latency() int64 {
  977. if b.attempts > 0 {
  978. return b.totalLatency / int64(b.attempts)
  979. }
  980. return 0
  981. }
  982. // GetConsistency returns the currently configured consistency level for the batch
  983. // operation.
  984. func (b *Batch) GetConsistency() Consistency {
  985. return b.Cons
  986. }
  987. // Query adds the query to the batch operation
  988. func (b *Batch) Query(stmt string, args ...interface{}) {
  989. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
  990. }
  991. // Bind adds the query to the batch operation and correlates it with a binding callback
  992. // that will be invoked when the batch is executed. The binding callback allows the application
  993. // to define which query argument values will be marshalled as part of the batch execution.
  994. func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
  995. b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
  996. }
  997. func (b *Batch) retryPolicy() RetryPolicy {
  998. return b.rt
  999. }
  1000. // RetryPolicy sets the retry policy to use when executing the batch operation
  1001. func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
  1002. b.rt = r
  1003. return b
  1004. }
  1005. // WithContext will set the context to use during a query, it will be used to
  1006. // timeout when waiting for responses from Cassandra.
  1007. func (b *Batch) WithContext(ctx context.Context) *Batch {
  1008. b.context = ctx
  1009. return b
  1010. }
  1011. // Size returns the number of batch statements to be executed by the batch operation.
  1012. func (b *Batch) Size() int {
  1013. return len(b.Entries)
  1014. }
  1015. // SerialConsistency sets the consistency level for the
  1016. // serial phase of conditional updates. That consistency can only be
  1017. // either SERIAL or LOCAL_SERIAL and if not present, it defaults to
  1018. // SERIAL. This option will be ignored for anything else that a
  1019. // conditional update/insert.
  1020. //
  1021. // Only available for protocol 3 and above
  1022. func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
  1023. b.serialCons = cons
  1024. return b
  1025. }
  1026. // DefaultTimestamp will enable the with default timestamp flag on the query.
  1027. // If enable, this will replace the server side assigned
  1028. // timestamp as default timestamp. Note that a timestamp in the query itself
  1029. // will still override this timestamp. This is entirely optional.
  1030. //
  1031. // Only available on protocol >= 3
  1032. func (b *Batch) DefaultTimestamp(enable bool) *Batch {
  1033. b.defaultTimestamp = enable
  1034. return b
  1035. }
  1036. func (b *Batch) attempt(d time.Duration) {
  1037. b.attempts++
  1038. b.totalLatency += d.Nanoseconds()
  1039. // TODO: track latencies per host and things as well instead of just total
  1040. }
  1041. func (b *Batch) GetRoutingKey() ([]byte, error) {
  1042. // TODO: use the first statement in the batch as the routing key?
  1043. return nil, nil
  1044. }
  1045. type BatchType byte
  1046. const (
  1047. LoggedBatch BatchType = 0
  1048. UnloggedBatch BatchType = 1
  1049. CounterBatch BatchType = 2
  1050. )
  1051. type BatchEntry struct {
  1052. Stmt string
  1053. Args []interface{}
  1054. binding func(q *QueryInfo) ([]interface{}, error)
  1055. }
  1056. type ColumnInfo struct {
  1057. Keyspace string
  1058. Table string
  1059. Name string
  1060. TypeInfo TypeInfo
  1061. }
  1062. func (c ColumnInfo) String() string {
  1063. return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
  1064. }
  1065. // routing key indexes LRU cache
  1066. type routingKeyInfoLRU struct {
  1067. lru *lru.Cache
  1068. mu sync.Mutex
  1069. }
  1070. type routingKeyInfo struct {
  1071. indexes []int
  1072. types []TypeInfo
  1073. }
  1074. func (r *routingKeyInfo) String() string {
  1075. return fmt.Sprintf("routing key index=%v types=%v", r.indexes, r.types)
  1076. }
  1077. func (r *routingKeyInfoLRU) Remove(key string) {
  1078. r.mu.Lock()
  1079. r.lru.Remove(key)
  1080. r.mu.Unlock()
  1081. }
  1082. //Max adjusts the maximum size of the cache and cleans up the oldest records if
  1083. //the new max is lower than the previous value. Not concurrency safe.
  1084. func (r *routingKeyInfoLRU) Max(max int) {
  1085. r.mu.Lock()
  1086. for r.lru.Len() > max {
  1087. r.lru.RemoveOldest()
  1088. }
  1089. r.lru.MaxEntries = max
  1090. r.mu.Unlock()
  1091. }
  1092. type inflightCachedEntry struct {
  1093. wg sync.WaitGroup
  1094. err error
  1095. value interface{}
  1096. }
  1097. // Tracer is the interface implemented by query tracers. Tracers have the
  1098. // ability to obtain a detailed event log of all events that happened during
  1099. // the execution of a query from Cassandra. Gathering this information might
  1100. // be essential for debugging and optimizing queries, but this feature should
  1101. // not be used on production systems with very high load.
  1102. type Tracer interface {
  1103. Trace(traceId []byte)
  1104. }
  1105. type traceWriter struct {
  1106. session *Session
  1107. w io.Writer
  1108. mu sync.Mutex
  1109. }
  1110. // NewTraceWriter returns a simple Tracer implementation that outputs
  1111. // the event log in a textual format.
  1112. func NewTraceWriter(session *Session, w io.Writer) Tracer {
  1113. return &traceWriter{session: session, w: w}
  1114. }
  1115. func (t *traceWriter) Trace(traceId []byte) {
  1116. var (
  1117. coordinator string
  1118. duration int
  1119. )
  1120. iter := t.session.control.query(`SELECT coordinator, duration
  1121. FROM system_traces.sessions
  1122. WHERE session_id = ?`, traceId)
  1123. iter.Scan(&coordinator, &duration)
  1124. if err := iter.Close(); err != nil {
  1125. t.mu.Lock()
  1126. fmt.Fprintln(t.w, "Error:", err)
  1127. t.mu.Unlock()
  1128. return
  1129. }
  1130. var (
  1131. timestamp time.Time
  1132. activity string
  1133. source string
  1134. elapsed int
  1135. )
  1136. fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
  1137. traceId, coordinator, time.Duration(duration)*time.Microsecond)
  1138. t.mu.Lock()
  1139. defer t.mu.Unlock()
  1140. iter = t.session.control.query(`SELECT event_id, activity, source, source_elapsed
  1141. FROM system_traces.events
  1142. WHERE session_id = ?`, traceId)
  1143. for iter.Scan(&timestamp, &activity, &source, &elapsed) {
  1144. fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
  1145. timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
  1146. }
  1147. if err := iter.Close(); err != nil {
  1148. fmt.Fprintln(t.w, "Error:", err)
  1149. }
  1150. }
  1151. type Error struct {
  1152. Code int
  1153. Message string
  1154. }
  1155. func (e Error) Error() string {
  1156. return e.Message
  1157. }
  1158. var (
  1159. ErrNotFound = errors.New("not found")
  1160. ErrUnavailable = errors.New("unavailable")
  1161. ErrUnsupported = errors.New("feature not supported")
  1162. ErrTooManyStmts = errors.New("too many statements")
  1163. ErrUseStmt = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
  1164. ErrSessionClosed = errors.New("session has been closed")
  1165. ErrNoConnections = errors.New("qocql: no hosts available in the pool")
  1166. ErrNoKeyspace = errors.New("no keyspace provided")
  1167. ErrNoMetadata = errors.New("no metadata available")
  1168. )
  1169. type ErrProtocol struct{ error }
  1170. func NewErrProtocol(format string, args ...interface{}) error {
  1171. return ErrProtocol{fmt.Errorf(format, args...)}
  1172. }
  1173. // BatchSizeMaximum is the maximum number of statements a batch operation can have.
  1174. // This limit is set by cassandra and could change in the future.
  1175. const BatchSizeMaximum = 65535