session.go 37 KB

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