Movatterモバイル変換


[0]ホーム

URL:


gocql

packagemodule
v1.7.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2024 License:Apache-2.0Imports:38Imported by:3,415

Details

Repository

github.com/gocql/gocql

Links

README

Apache Cassandra GoCQL Driver

!Join the chat at https://the-asf.slack.com/archives/C05LPRVNZV1go buildGoDoc

Package gocql implements a fast and robust Cassandra client for theGo programming language.

Project Website:https://cassandra.apache.org
API documentation:https://godoc.org/github.com/gocql/gocql
Discussions:https://cassandra.apache.org/_/community.html#discussions

Supported Versions

The following matrix shows the versions of Go and Cassandra that are tested with the integration test suite as part of the CI build:

Go/Cassandra4.0.x4.1.x
1.22yesyes
1.23yesyes

Gocql has been tested in production against many versions of Cassandra. Due to limits in our CI setup we onlytest against the latest 2 GA releases.

Sunsetting Model

In general, the Cassandra community will focus on supporting the current and previous versions of Go. gocql may still work with older versions of Go, but official support for these versions will have been sunset.

Installation

go get github.com/gocql/gocql

Features

  • Modern Cassandra client using the native transport
  • Automatic type conversions between Cassandra and Go
    • Support for all common types including sets, lists and maps
    • Custom types can implement aMarshaler andUnmarshaler interface
    • Strict type conversions without any loss of precision
    • Built-In support for UUIDs (version 1 and 4)
  • Support for logged, unlogged and counter batches
  • Cluster management
    • Automatic reconnect on connection failures with exponential falloff
    • Round robin distribution of queries to different hosts
    • Round robin distribution of queries to different connections on a host
    • Each connection can execute up to n concurrent queries (whereby n is the limit set by the protocol version the client chooses to use)
    • Optional automatic discovery of nodes
    • Policy based connection pool with token aware and round-robin policy implementations
  • Support for password authentication
  • Iteration over paged results with configurable page size
  • Support for TLS/SSL
  • Optional frame compression (using snappy)
  • Automatic query preparation
  • Support for query tracing
  • Support for Cassandra 2.1+binary protocol version 3
    • Support for up to 32768 streams
    • Support for tuple types
    • Support for client side timestamps by default
    • Support for UDTs via a custom marshaller or struct tags
  • Support for Cassandra 3.0+binary protocol version 4
  • An API to access the schema metadata of a given keyspace

Performance

While the driver strives to be highly performant, there are cases where it is difficult to test and verify. The driver is builtwith maintainability and code readability in mind first and then performance and features, as such every now and then performancemay degrade, if this occurs please report and issue and it will be looked at and remedied. The only time the driver copies data fromits read buffer is when it Unmarshal's data into supplied types.

Some tips for getting more performance from the driver:

  • Use the TokenAware policy
  • Use many goroutines when doing inserts, the driver is asynchronous but provides a synchronous API, it can execute many queries concurrently
  • Tune query page size
  • Reading data from the network to unmarshal will incur a large amount of allocations, this can adversely affect the garbage collector, tuneGOGC
  • Close iterators after use to recycle byte buffers

Important Default Keyspace Changes

gocql no longer supports executing "use " statements to simplify the library. The user still has theability to define the default keyspace for connections but now the keyspace can only be defined before asession is created. Queries can still access keyspaces by indicating the keyspace in the query:

SELECT * FROM example2.table;

Example of correct usage:

cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")cluster.Keyspace = "example"...session, err := cluster.CreateSession()

Example of incorrect usage:

cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")cluster.Keyspace = "example"...session, err := cluster.CreateSession()if err = session.Query("use example2").Exec(); err != nil {log.Fatal(err)}

This will result in an err being returned from the session.Query line as the user is trying to execute a "use"statement.

Example

Seepackage documentation.

Data Binding

There are various ways to bind application level data structures to CQL statements:

  • You can write the data binding by hand, as outlined in the Tweet example. This provides you with the greatest flexibility, but it does mean that you need to keep your application code in sync with your Cassandra schema.
  • You can dynamically marshal an entire query result into an[]map[string]interface{} using theSliceMap() API. This returns a slice of row maps keyed by CQL column names. This method requires no special interaction with the gocql API, but it does require your application to be able to deal with a key value view of your data.
  • As a refinement on theSliceMap() API you can also callMapScan() which returnsmap[string]interface{} instances in a row by row fashion.
  • TheBind() API provides a client app with a low level mechanism to introspect query meta data and extract appropriate field values from application level data structures.
  • Thegocqlx package is an idiomatic extension to gocql that provides usability features. With gocqlx you can bind the query parameters from maps and structs, use named query parameters (:identifier) and scan the query results into structs and slices. It comes with a fluent and flexible CQL query builder that supports full CQL spec, including BATCH statements and custom functions.
  • Building on top of the gocql driver,cqlr adds the ability to auto-bind a CQL iterator to a struct or to bind a struct to an INSERT statement.
  • Another external project that layers on top of gocql iscqlc which generates gocql compliant code from your Cassandra schema so that you can write type safe CQL statements in Go with a natural query syntax.
  • gocassa is an external project that layers on top of gocql to provide convenient query building and data binding.
  • gocqltable provides an ORM-style convenience layer to make CRUD operations with gocql easier.

Ecosystem

The following community maintained tools are known to integrate with gocql:

  • gocqlx is a gocql extension that automates data binding, adds named queries support, provides flexible query builders and plays well with gocql.
  • journey is a migration tool with Cassandra support.
  • negronicql is gocql middleware for Negroni.
  • cqlr adds the ability to auto-bind a CQL iterator to a struct or to bind a struct to an INSERT statement.
  • cqlc generates gocql compliant code from your Cassandra schema so that you can write type safe CQL statements in Go with a natural query syntax.
  • gocassa provides query building, adds data binding, and provides easy-to-use "recipe" tables for common query use-cases.
  • gocqltable is a wrapper around gocql that aims to simplify common operations.
  • gockle provides simple, mockable interfaces that wrap gocql types
  • scylladb is a fast Apache Cassandra-compatible NoSQL database
  • go-cql-driver is an CQL driver conforming to the built-in database/sql interface. It is good for simple use cases where the database/sql interface is wanted. The CQL driver is a wrapper around this project.

Other Projects

  • gocqldriver is the predecessor of gocql based on Go'sdatabase/sql package. This project isn't maintained anymore, because Cassandra wasn't a good fit for the traditionaldatabase/sql API. Use this package instead.

SEO

For some reason, when you Googlegolang cassandra, this project doesn't feature very highly in the result list. But if you Googlego cassandra, then we're a bit higher up the list. So this is note to try to convince Google that golang is an alias for Go.

Documentation

Overview

Package gocql implements a fast and robust Cassandra driver for theGo programming language.

Connecting to the cluster

Pass a list of initial node IP addresses to NewCluster to create a new cluster configuration:

cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")

Port can be specified as part of the address, the above is equivalent to:

cluster := gocql.NewCluster("192.168.1.1:9042", "192.168.1.2:9042", "192.168.1.3:9042")

It is recommended to use the value set in the Cassandra config for broadcast_address or listen_address,an IP address not a domain name. This is because events from Cassandra will use the configured IPaddress, which is used to index connected hosts. If the domain name specified resolves to more than 1 IP addressthen the driver may connect multiple times to the same host, and will not mark the node being down or up from events.

Then you can customize more options (see ClusterConfig):

cluster.Keyspace = "example"cluster.Consistency = gocql.Quorumcluster.ProtoVersion = 4

The driver tries to automatically detect the protocol version to use if not set, but you might want to set theprotocol version explicitly, as it's not defined which version will be used in certain situations (for exampleduring upgrade of the cluster when some of the nodes support different set of protocol versions than other nodes).

The driver advertises the module name and version in the STARTUP message, so servers are able to detect the version.If you use replace directive in go.mod, the driver will send information about the replacement module instead.

When ready, create a session from the configuration. Don't forget to Close the session once you are done with it:

session, err := cluster.CreateSession()if err != nil {return err}defer session.Close()

Authentication

CQL protocol uses a SASL-based authentication mechanism and so consists of an exchange of server challenges andclient response pairs. The details of the exchanged messages depend on the authenticator used.

To use authentication, set ClusterConfig.Authenticator or ClusterConfig.AuthProvider.

PasswordAuthenticator is provided to use for username/password authentication:

 cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3") cluster.Authenticator = gocql.PasswordAuthenticator{Username: "user",Password: "password" } session, err := cluster.CreateSession() if err != nil { return err } defer session.Close()

Transport layer security

It is possible to secure traffic between the client and server with TLS.

To use TLS, set the ClusterConfig.SslOpts field. SslOptions embeds *tls.Config so you can set that directly.There are also helpers to load keys/certificates from files.

Warning: Due to historical reasons, the SslOptions is insecure by default, so you need to set EnableHostVerificationto true if no Config is set. Most users should set SslOptions.Config to a *tls.Config.SslOptions and Config.InsecureSkipVerify interact as follows:

Config.InsecureSkipVerify | EnableHostVerification | ResultConfig is nil             | false                  | do not verify hostConfig is nil             | true                   | verify hostfalse                     | false                  | verify hosttrue                      | false                  | do not verify hostfalse                     | true                   | verify hosttrue                      | true                   | verify host

For example:

cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")cluster.SslOpts = &gocql.SslOptions{EnableHostVerification: true,}session, err := cluster.CreateSession()if err != nil {return err}defer session.Close()

Data-center awareness and query routing

To route queries to local DC first, use DCAwareRoundRobinPolicy. For example, if the datacenter youwant to primarily connect is called dc1 (as configured in the database):

cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")cluster.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy("dc1")

The driver can route queries to nodes that hold data replicas based on partition key (preferring local DC).

cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")cluster.PoolConfig.HostSelectionPolicy = gocql.TokenAwareHostPolicy(gocql.DCAwareRoundRobinPolicy("dc1"))

Note that TokenAwareHostPolicy can take options such as gocql.ShuffleReplicas and gocql.NonLocalReplicasFallback.

We recommend running with a token aware host policy in production for maximum performance.

The driver can only use token-aware routing for queries where all partition key columns are query parameters.For example, instead of

session.Query("select value from mytable where pk1 = 'abc' AND pk2 = ?", "def")

use

session.Query("select value from mytable where pk1 = ? AND pk2 = ?", "abc", "def")

Rack-level awareness

The DCAwareRoundRobinPolicy can be replaced with RackAwareRoundRobinPolicy, which takes two parameters, datacenter and rack.

Instead of dividing hosts with two tiers (local datacenter and remote datacenters) it divides hosts into three(the local rack, the rest of the local datacenter, and everything else).

RackAwareRoundRobinPolicy can be combined with TokenAwareHostPolicy in the same way as DCAwareRoundRobinPolicy.

Executing queries

Create queries with Session.Query. Query values must not be reused between different executions and must not bemodified after starting execution of the query.

To execute a query without reading results, use Query.Exec:

 err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,"me", gocql.TimeUUID(), "hello world").WithContext(ctx).Exec()

Single row can be read by calling Query.Scan:

 err := session.Query(`SELECT id, text FROM tweet WHERE timeline = ? LIMIT 1`,"me").WithContext(ctx).Consistency(gocql.One).Scan(&id, &text)

Multiple rows can be read using Iter.Scanner:

 scanner := session.Query(`SELECT id, text FROM tweet WHERE timeline = ?`, "me").WithContext(ctx).Iter().Scanner() for scanner.Next() { var ( id gocql.UUIDtext string ) err = scanner.Scan(&id, &text) if err != nil { log.Fatal(err) } fmt.Println("Tweet:", id, text) } // scanner.Err() closes the iterator, so scanner nor iter should be used afterwards. if err := scanner.Err(); err != nil { log.Fatal(err) }

See Example for complete example.

Prepared statements

The driver automatically prepares DML queries (SELECT/INSERT/UPDATE/DELETE/BATCH statements) and maintains a cacheof prepared statements.CQL protocol does not support preparing other query types.

When using CQL protocol >= 4, it is possible to use gocql.UnsetValue as the bound value of a column.This will cause the database to ignore writing the column.The main advantage is the ability to keep the same prepared statement even when you don'twant to update some fields, where before you needed to make another prepared statement.

Executing multiple queries concurrently

Session is safe to use from multiple goroutines, so to execute multiple concurrent queries, just execute themfrom several worker goroutines. Gocql provides synchronously-looking API (as recommended for Go APIs) and the queriesare executed asynchronously at the protocol level.

results := make(chan error, 2)go func() {results <- session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,"me", gocql.TimeUUID(), "hello world 1").Exec()}()go func() {results <- session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,"me", gocql.TimeUUID(), "hello world 2").Exec()}()

Nulls

Null values are are unmarshalled as zero value of the type. If you need to distinguish for example between textcolumn being null and empty string, you can unmarshal into *string variable instead of string.

var text *stringerr := scanner.Scan(&text)if err != nil {// handle error}if text != nil {// not null}else {// null}

See Example_nulls for full example.

Reusing slices

The driver reuses backing memory of slices when unmarshalling. This is an optimization so that a buffer does notneed to be allocated for every processed row. However, you need to be careful when storing the slices to othermemory structures.

scanner := session.Query(`SELECT myints FROM table WHERE pk = ?`, "key").WithContext(ctx).Iter().Scanner()var myInts []intfor scanner.Next() {// This scan reuses backing store of myInts for each row.err = scanner.Scan(&myInts)if err != nil {log.Fatal(err)}}

When you want to save the data for later use, pass a new slice every time. A common pattern is to declare theslice variable within the scanner loop:

scanner := session.Query(`SELECT myints FROM table WHERE pk = ?`, "key").WithContext(ctx).Iter().Scanner()for scanner.Next() {var myInts []int// This scan always gets pointer to fresh myInts slice, so does not reuse memory.err = scanner.Scan(&myInts)if err != nil {log.Fatal(err)}}

Paging

The driver supports paging of results with automatic prefetch, see ClusterConfig.PageSize, Session.SetPrefetch,Query.PageSize, and Query.Prefetch.

It is also possible to control the paging manually with Query.PageState (this disables automatic prefetch).Manual paging is useful if you want to store the page state externally, for example in a URL to allow usersbrowse pages in a result. You might want to sign/encrypt the paging state when exposing it externally sinceit contains data from primary keys.

Paging state is specific to the CQL protocol version and the exact query used. It is meant as opaque state thatshould not be modified. If you send paging state from different query or protocol version, then the behaviouris not defined (you might get unexpected results or an error from the server). For example, do not send paging statereturned by node using protocol version 3 to a node using protocol version 4. Also, when using protocol version 4,paging state between Cassandra 2.2 and 3.0 is incompatible (https://issues.apache.org/jira/browse/CASSANDRA-10880).

The driver does not check whether the paging state is from the same protocol version/statement.You might want to validate yourself as this could be a problem if you store paging state externally.For example, if you store paging state in a URL, the URLs might become broken when you upgrade your cluster.

Call Query.PageState(nil) to fetch just the first page of the query results. Pass the page state returned byIter.PageState to Query.PageState of a subsequent query to get the next page. If the length of slice returnedby Iter.PageState is zero, there are no more pages available (or an error occurred).

Using too low values of PageSize will negatively affect performance, a value below 100 is probably too low.While Cassandra returns exactly PageSize items (except for last page) in a page currently, the protocol authorsexplicitly reserved the right to return smaller or larger amount of items in a page for performance reasons, so don'trely on the page having the exact count of items.

See Example_paging for an example of manual paging.

Dynamic list of columns

There are certain situations when you don't know the list of columns in advance, mainly when the query is suppliedby the user. Iter.Columns, Iter.RowData, Iter.MapScan and Iter.SliceMap can be used to handle this case.

See Example_dynamicColumns.

Batches

The CQL protocol supports sending batches of DML statements (INSERT/UPDATE/DELETE) and so does gocql.Use Session.NewBatch to create a new batch and then fill-in details of individual queries.Then execute the batch with Session.ExecuteBatch.

Logged batches ensure atomicity, either all or none of the operations in the batch will succeed, but they haveoverhead to ensure this property.Unlogged batches don't have the overhead of logged batches, but don't guarantee atomicity.Updates of counters are handled specially by Cassandra so batches of counter updates have to use CounterBatch type.A counter batch can only contain statements to update counters.

For unlogged batches it is recommended to send only single-partition batches (i.e. all statements in the batch shouldinvolve only a single partition).Multi-partition batch needs to be split by the coordinator node and re-sent tocorrect nodes.With single-partition batches you can send the batch directly to the node for the partition without incurring theadditional network hop.

It is also possible to pass entire BEGIN BATCH .. APPLY BATCH statement to Query.Exec.There are differences how those are executed.BEGIN BATCH statement passed to Query.Exec is prepared as a whole in a single statement.Session.ExecuteBatch prepares individual statements in the batch.If you have variable-length batches using the same statement, using Session.ExecuteBatch is more efficient.

See Example_batch for an example.

Lightweight transactions

Query.ScanCAS or Query.MapScanCAS can be used to execute a single-statement lightweight transaction (anINSERT/UPDATE .. IF statement) and reading its result. See example for Query.MapScanCAS.

Multiple-statement lightweight transactions can be executed as a logged batch that contains at least one conditionalstatement. All the conditions must return true for the batch to be applied. You can use Session.ExecuteBatchCAS andSession.MapExecuteBatchCAS when executing the batch to learn about the result of the LWT. See example forSession.MapExecuteBatchCAS.

Retries and speculative execution

Queries can be marked as idempotent. Marking the query as idempotent tells the driver that the query can be executedmultiple times without affecting its result. Non-idempotent queries are not eligible for retrying nor speculativeexecution.

Idempotent queries are retried in case of errors based on the configured RetryPolicy.

Queries can be retried even before they fail by setting a SpeculativeExecutionPolicy. The policy cancause the driver to retry on a different node if the query is taking longer than a specified delay even before thedriver receives an error or timeout from the server. When a query is speculatively executed, the original executionis still executing. The two parallel executions of the query race to return a result, the first received result willbe returned.

User-defined types

UDTs can be mapped (un)marshaled from/to map[string]interface{} a Go struct (or a type implementingUDTUnmarshaler, UDTMarshaler, Unmarshaler or Marshaler interfaces).

For structs, cql tag can be used to specify the CQL field name to be mapped to a struct field:

type MyUDT struct {FieldA int32 `cql:"a"`FieldB string `cql:"b"`}

See Example_userDefinedTypesMap, Example_userDefinedTypesStruct, ExampleUDTMarshaler, ExampleUDTUnmarshaler.

Metrics and tracing

It is possible to provide observer implementations that could be used to gather metrics:

  • QueryObserver for monitoring individual queries.
  • BatchObserver for monitoring batch queries.
  • ConnectObserver for monitoring new connections from the driver to the database.
  • FrameHeaderObserver for monitoring individual protocol frames.

CQL protocol also supports tracing of queries. When enabled, the database will write information aboutinternal events that happened during execution of the query. You can use Query.Trace to request tracing and receivethe session ID that the database used to store the trace information in system_traces.sessions andsystem_traces.events tables. NewTraceWriter returns an implementation of Tracer that writes the events to a writer.Gathering trace information might be essential for debugging and optimizing queries, but writing traces has overhead,so this feature should not be used on production systems with very high load unless you know what you are doing.

Example
package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.tweet(timeline text, id UUID, text text, PRIMARY KEY(id));create index on example.tweet(timeline);*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.Consistency = gocql.Quorum// connect to the clustersession, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()// insert a tweetif err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,"me", gocql.TimeUUID(), "hello world").WithContext(ctx).Exec(); err != nil {log.Fatal(err)}var id gocql.UUIDvar text string/* Search for a specific set of records whose 'timeline' column matches * the value 'me'. The secondary index that we created earlier will be * used for optimizing the search */if err := session.Query(`SELECT id, text FROM tweet WHERE timeline = ? LIMIT 1`,"me").WithContext(ctx).Consistency(gocql.One).Scan(&id, &text); err != nil {log.Fatal(err)}fmt.Println("Tweet:", id, text)fmt.Println()// list all tweetsscanner := session.Query(`SELECT id, text FROM tweet WHERE timeline = ?`,"me").WithContext(ctx).Iter().Scanner()for scanner.Next() {err = scanner.Scan(&id, &text)if err != nil {log.Fatal(err)}fmt.Println("Tweet:", id, text)}// scanner.Err() closes the iterator, so scanner nor iter should be used afterwards.if err := scanner.Err(); err != nil {log.Fatal(err)}// Tweet: cad53821-3731-11eb-971c-708bcdaada84 hello world//// Tweet: cad53821-3731-11eb-971c-708bcdaada84 hello world// Tweet: d577ab85-3731-11eb-81eb-708bcdaada84 hello world}
Output:

Example (Batch)

Example_batch demonstrates how to execute a batch of statements.

package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.batches(pk int, ck int, description text, PRIMARY KEY(pk, ck));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()b := session.NewBatch(gocql.UnloggedBatch).WithContext(ctx)b.Entries = append(b.Entries, gocql.BatchEntry{Stmt:       "INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)",Args:       []interface{}{1, 2, "1.2"},Idempotent: true,})b.Entries = append(b.Entries, gocql.BatchEntry{Stmt:       "INSERT INTO example.batches (pk, ck, description) VALUES (?, ?, ?)",Args:       []interface{}{1, 3, "1.3"},Idempotent: true,})err = session.ExecuteBatch(b)if err != nil {log.Fatal(err)}scanner := session.Query("SELECT pk, ck, description FROM example.batches").Iter().Scanner()for scanner.Next() {var pk, ck int32var description stringerr = scanner.Scan(&pk, &ck, &description)if err != nil {log.Fatal(err)}fmt.Println(pk, ck, description)}// 1 2 1.2// 1 3 1.3}
Output:

Example (DynamicColumns)

Example_dynamicColumns demonstrates how to handle dynamic column list.

package mainimport ("context""fmt""log""os""reflect""text/tabwriter"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.table1(pk text, ck int, value1 text, value2 int, PRIMARY KEY(pk, ck));insert into example.table1 (pk, ck, value1, value2) values ('a', 1, 'b', 2);insert into example.table1 (pk, ck, value1, value2) values ('c', 3, 'd', 4);insert into example.table1 (pk, ck, value1, value2) values ('c', 5, null, null);create table example.table2(pk int, value1 timestamp, PRIMARY KEY(pk));insert into example.table2 (pk, value1) values (1, '2020-01-02 03:04:05');*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()printQuery := func(ctx context.Context, session *gocql.Session, stmt string, values ...interface{}) error {iter := session.Query(stmt, values...).WithContext(ctx).Iter()fmt.Println(stmt)w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ',0)for i, columnInfo := range iter.Columns() {if i > 0 {fmt.Fprint(w, "\t| ")}fmt.Fprintf(w, "%s (%s)", columnInfo.Name, columnInfo.TypeInfo)}for {rd, err := iter.RowData()if err != nil {return err}if !iter.Scan(rd.Values...) {break}fmt.Fprint(w, "\n")for i, val := range rd.Values {if i > 0 {fmt.Fprint(w, "\t| ")}fmt.Fprint(w, reflect.Indirect(reflect.ValueOf(val)).Interface())}}fmt.Fprint(w, "\n")w.Flush()fmt.Println()return iter.Close()}ctx := context.Background()err = printQuery(ctx, session, "SELECT * FROM table1")if err != nil {log.Fatal(err)}err = printQuery(ctx, session, "SELECT value2, pk, ck FROM table1")if err != nil {log.Fatal(err)}err = printQuery(ctx, session, "SELECT * FROM table2")if err != nil {log.Fatal(err)}// SELECT * FROM table1// pk (varchar) | ck (int) | value1 (varchar) | value2 (int)// a            | 1        | b                | 2// c            | 3        | d                | 4// c            | 5        |                  | 0//// SELECT value2, pk, ck FROM table1// value2 (int) | pk (varchar) | ck (int)// 2            | a            | 1// 4            | c            | 3// 0            | c            | 5//// SELECT * FROM table2// pk (int) | value1 (timestamp)// 1        | 2020-01-02 03:04:05 +0000 UTC}
Output:

Example (MarshalerUnmarshaler)

Example_marshalerUnmarshaler demonstrates how to implement a Marshaler and Unmarshaler.

/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* * Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40 * Copyright (c) 2016, The Gocql authors, * provided under the BSD-3-Clause License. * See the NOTICE file distributed with this work for additional information. */package mainimport ("context""fmt""log""strconv""strings"gocql "github.com/gocql/gocql")// MyMarshaler implements Marshaler and Unmarshaler.// It represents a version number stored as string.type MyMarshaler struct {major, minor, patch int}func (m MyMarshaler) MarshalCQL(info gocql.TypeInfo) ([]byte, error) {return gocql.Marshal(info, fmt.Sprintf("%d.%d.%d", m.major, m.minor, m.patch))}func (m *MyMarshaler) UnmarshalCQL(info gocql.TypeInfo, data []byte) error {var s stringerr := gocql.Unmarshal(info, data, &s)if err != nil {return err}parts := strings.SplitN(s, ".", 3)if len(parts) != 3 {return fmt.Errorf("parse version %q: %d parts instead of 3", s, len(parts))}major, err := strconv.Atoi(parts[0])if err != nil {return fmt.Errorf("parse version %q major number: %v", s, err)}minor, err := strconv.Atoi(parts[1])if err != nil {return fmt.Errorf("parse version %q minor number: %v", s, err)}patch, err := strconv.Atoi(parts[2])if err != nil {return fmt.Errorf("parse version %q patch number: %v", s, err)}m.major = majorm.minor = minorm.patch = patchreturn nil}// Example_marshalerUnmarshaler demonstrates how to implement a Marshaler and Unmarshaler.func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.my_marshaler_table(pk int, value text, PRIMARY KEY(pk));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()value := MyMarshaler{major: 1,minor: 2,patch: 3,}err = session.Query("INSERT INTO example.my_marshaler_table (pk, value) VALUES (?, ?)",1, value).WithContext(ctx).Exec()if err != nil {log.Fatal(err)}var stringValue stringerr = session.Query("SELECT value FROM example.my_marshaler_table WHERE pk = 1").WithContext(ctx).Scan(&stringValue)if err != nil {log.Fatal(err)}fmt.Println(stringValue)var unmarshaledValue MyMarshalererr = session.Query("SELECT value FROM example.my_marshaler_table WHERE pk = 1").WithContext(ctx).Scan(&unmarshaledValue)if err != nil {log.Fatal(err)}fmt.Println(unmarshaledValue)// 1.2.3// {1 2 3}}
Output:

Example (Nulls)

Example_nulls demonstrates how to distinguish between null and zero value when needed.

Null values are unmarshalled as zero value of the type. If you need to distinguish for example between textcolumn being null and empty string, you can unmarshal into *string field.

package mainimport ("fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.stringvals(id int, value text, PRIMARY KEY(id));insert into example.stringvals (id, value) values (1, null);insert into example.stringvals (id, value) values (2, '');insert into example.stringvals (id, value) values (3, 'hello');*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()scanner := session.Query(`SELECT id, value FROM stringvals`).Iter().Scanner()for scanner.Next() {var (id  int32val *string)err := scanner.Scan(&id, &val)if err != nil {log.Fatal(err)}if val != nil {fmt.Printf("Row %d is %q\n", id, *val)} else {fmt.Printf("Row %d is null\n", id)}}err = scanner.Err()if err != nil {log.Fatal(err)}// Row 1 is null// Row 2 is ""// Row 3 is "hello"}
Output:

Example (Paging)

Example_paging demonstrates how to manually fetch pages and use page state.

See also package documentation about paging.

package mainimport ("fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.itoa(id int, description text, PRIMARY KEY(id));insert into example.itoa (id, description) values (1, 'one');insert into example.itoa (id, description) values (2, 'two');insert into example.itoa (id, description) values (3, 'three');insert into example.itoa (id, description) values (4, 'four');insert into example.itoa (id, description) values (5, 'five');insert into example.itoa (id, description) values (6, 'six');*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()var pageState []bytefor {// We use PageSize(2) for the sake of example, use larger values in production (default is 5000) for performance// reasons.iter := session.Query(`SELECT id, description FROM itoa`).PageSize(2).PageState(pageState).Iter()nextPageState := iter.PageState()scanner := iter.Scanner()for scanner.Next() {var (id          intdescription string)err = scanner.Scan(&id, &description)if err != nil {log.Fatal(err)}fmt.Println(id, description)}err = scanner.Err()if err != nil {log.Fatal(err)}fmt.Printf("next page state: %+v\n", nextPageState)if len(nextPageState) == 0 {break}pageState = nextPageState}// 5 five// 1 one// next page state: [4 0 0 0 1 0 240 127 255 255 253 0]// 2 two// 4 four// next page state: [4 0 0 0 4 0 240 127 255 255 251 0]// 6 six// 3 three// next page state: [4 0 0 0 3 0 240 127 255 255 249 0]// next page state: []}
Output:

Example (Set)

Example_set demonstrates how to use sets.

package mainimport ("fmt""log""sort"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.sets(id int, value set<text>, PRIMARY KEY(id));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()err = session.Query(`UPDATE sets SET value=? WHERE id=1`, []string{"alpha", "beta", "gamma"}).Exec()if err != nil {log.Fatal(err)}err = session.Query(`UPDATE sets SET value=value+? WHERE id=1`, "epsilon").Exec()if err != nil {// This does not work because the ? expects a set, not a single item.fmt.Printf("expected error: %v\n", err)}err = session.Query(`UPDATE sets SET value=value+? WHERE id=1`, []string{"delta"}).Exec()if err != nil {log.Fatal(err)}// map[x]struct{} is supported too.toRemove := map[string]struct{}{"alpha": {},"gamma": {},}err = session.Query(`UPDATE sets SET value=value-? WHERE id=1`, toRemove).Exec()if err != nil {log.Fatal(err)}scanner := session.Query(`SELECT id, value FROM sets`).Iter().Scanner()for scanner.Next() {var (id  int32val []string)err := scanner.Scan(&id, &val)if err != nil {log.Fatal(err)}sort.Strings(val)fmt.Printf("Row %d is %v\n", id, val)}err = scanner.Err()if err != nil {log.Fatal(err)}// expected error: can not marshal string into set(varchar)// Row 1 is [beta delta]}
Output:

Example (UserDefinedTypesMap)

Example_userDefinedTypesMap demonstrates how to work with user-defined types as maps.See also Example_userDefinedTypesStruct and examples for UDTMarshaler and UDTUnmarshaler if you want to map to structs.

package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create type example.my_udt (field_a text, field_b int);create table example.my_udt_table(pk int, value frozen<my_udt>, PRIMARY KEY(pk));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()value := map[string]interface{}{"field_a": "a value","field_b": 42,}err = session.Query("INSERT INTO example.my_udt_table (pk, value) VALUES (?, ?)",1, value).WithContext(ctx).Exec()if err != nil {log.Fatal(err)}var readValue map[string]interface{}err = session.Query("SELECT value FROM example.my_udt_table WHERE pk = 1").WithContext(ctx).Scan(&readValue)if err != nil {log.Fatal(err)}fmt.Println(readValue["field_a"])fmt.Println(readValue["field_b"])// a value// 42}
Output:

Example (UserDefinedTypesStruct)

Example_userDefinedTypesStruct demonstrates how to work with user-defined types as structs.See also examples for UDTMarshaler and UDTUnmarshaler if you need more control/better performance.

/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* * Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40 * Copyright (c) 2016, The Gocql authors, * provided under the BSD-3-Clause License. * See the NOTICE file distributed with this work for additional information. */package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")type MyUDT struct {FieldA string `cql:"field_a"`FieldB int32  `cql:"field_b"`}// Example_userDefinedTypesStruct demonstrates how to work with user-defined types as structs.// See also examples for UDTMarshaler and UDTUnmarshaler if you need more control/better performance.func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create type example.my_udt (field_a text, field_b int);create table example.my_udt_table(pk int, value frozen<my_udt>, PRIMARY KEY(pk));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()value := MyUDT{FieldA: "a value",FieldB: 42,}err = session.Query("INSERT INTO example.my_udt_table (pk, value) VALUES (?, ?)",1, value).WithContext(ctx).Exec()if err != nil {log.Fatal(err)}var readValue MyUDTerr = session.Query("SELECT value FROM example.my_udt_table WHERE pk = 1").WithContext(ctx).Scan(&readValue)if err != nil {log.Fatal(err)}fmt.Println(readValue.FieldA)fmt.Println(readValue.FieldB)// a value// 42}
Output:

Index

Examples

Constants

View Source
const (// ErrCodeServer indicates unexpected error on server-side.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1246-L1247ErrCodeServer = 0x0000// ErrCodeProtocol indicates a protocol violation by some client message.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1248-L1250ErrCodeProtocol = 0x000A// ErrCodeCredentials indicates missing required authentication.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1251-L1254ErrCodeCredentials = 0x0100// ErrCodeUnavailable indicates unavailable error.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1255-L1265ErrCodeUnavailable = 0x1000// ErrCodeOverloaded returned in case of request on overloaded node coordinator.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1266-L1267ErrCodeOverloaded = 0x1001// ErrCodeBootstrapping returned from the coordinator node in bootstrapping phase.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1268-L1269ErrCodeBootstrapping = 0x1002// ErrCodeTruncate indicates truncation exception.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1270ErrCodeTruncate = 0x1003// ErrCodeWriteTimeout returned in case of timeout during the request write.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1271-L1304ErrCodeWriteTimeout = 0x1100// ErrCodeReadTimeout returned in case of timeout during the request read.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1305-L1321ErrCodeReadTimeout = 0x1200// ErrCodeReadFailure indicates request read error which is not covered by ErrCodeReadTimeout.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1322-L1340ErrCodeReadFailure = 0x1300// ErrCodeFunctionFailure indicates an error in user-defined function.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1341-L1347ErrCodeFunctionFailure = 0x1400// ErrCodeWriteFailure indicates request write error which is not covered by ErrCodeWriteTimeout.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1348-L1385ErrCodeWriteFailure = 0x1500// ErrCodeCDCWriteFailure is defined, but not yet documented in CQLv5 protocol.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1386ErrCodeCDCWriteFailure = 0x1600// ErrCodeCASWriteUnknown indicates only partially completed CAS operation.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1387-L1397ErrCodeCASWriteUnknown = 0x1700// ErrCodeSyntax indicates the syntax error in the query.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1399ErrCodeSyntax = 0x2000// ErrCodeUnauthorized indicates access rights violation by user on performed operation.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1400-L1401ErrCodeUnauthorized = 0x2100// ErrCodeInvalid indicates invalid query error which is not covered by ErrCodeSyntax.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1402ErrCodeInvalid = 0x2200// ErrCodeConfig indicates the configuration error.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1403ErrCodeConfig = 0x2300// ErrCodeAlreadyExists is returned for the requests creating the existing keyspace/table.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1404-L1413ErrCodeAlreadyExists = 0x2400// ErrCodeUnprepared returned from the host for prepared statement which is unknown.//// Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1414-L1417ErrCodeUnprepared = 0x2500)

See CQL Binary Protocol v5, section 8 for more details.https://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec

View Source
const (NodeUp nodeState =iotaNodeDown)
View Source
const (DEFAULT_KEY_ALIAS    = "key"DEFAULT_COLUMN_ALIAS = "column"DEFAULT_VALUE_ALIAS  = "value")

default alias values

View Source
const (REVERSED_TYPE   = "org.apache.cassandra.db.marshal.ReversedType"COMPOSITE_TYPE  = "org.apache.cassandra.db.marshal.CompositeType"COLLECTION_TYPE = "org.apache.cassandra.db.marshal.ColumnToCollectionType"LIST_TYPE       = "org.apache.cassandra.db.marshal.ListType"SET_TYPE        = "org.apache.cassandra.db.marshal.SetType"MAP_TYPE        = "org.apache.cassandra.db.marshal.MapType")
View Source
const (VariantNCSCompat = 0VariantIETF      = 2VariantMicrosoft = 6VariantFuture    = 7)
View Source
const BatchSizeMaximum = 65535

BatchSizeMaximum is the maximum number of statements a batch operation can have.This limit is set by cassandra and could change in the future.

Variables

View Source
var (ErrNoHosts              =errors.New("no hosts provided")ErrNoConnectionsStarted =errors.New("no connections were made when creating the session")ErrHostQueryFailed      =errors.New("unable to populate Hosts"))
View Source
var (ErrQueryArgLength    =errors.New("gocql: query argument length mismatch")ErrTimeoutNoResponse =errors.New("gocql: no response received from cassandra within timeout period")ErrTooManyTimeouts   =errors.New("gocql: too many query timeouts on the connection")ErrConnectionClosed  =errors.New("gocql: connection closed waiting for response")ErrNoStreams         =errors.New("gocql: no streams available on connection"))
View Source
var (ErrNotFound             =errors.New("not found")ErrUnavailable          =errors.New("unavailable")ErrUnsupported          =errors.New("feature not supported")ErrTooManyStmts         =errors.New("too many statements")ErrUseStmt              =errors.New("use statements aren't supported. Please see https://github.com/apache/cassandra-gocql-driver for explanation.")ErrSessionClosed        =errors.New("session has been closed")ErrNoConnections        =errors.New("gocql: no hosts available in the pool")ErrNoKeyspace           =errors.New("no keyspace provided")ErrKeyspaceDoesNotExist =errors.New("keyspace does not exist")ErrNoMetadata           =errors.New("no metadata available"))
View Source
var ErrCannotFindHost =errors.New("cannot find host")
View Source
var (ErrFrameTooBig =errors.New("frame length is bigger than the maximum allowed"))
View Source
var ErrHostAlreadyExists =errors.New("host already exists")
View Source
var ErrUnknownRetryType =errors.New("unknown retry type returned by retry policy")

ErrUnknownRetryType is returned if the retry policy returns a retry typeunknown to the query executor.

View Source
var (ErrorUDTUnavailable =errors.New("UDT are not available on protocols less than 3, please update config"))
View Source
var TimeoutLimitint64 = 0

If not zero, how many timeouts we will allow to occur before the connection is closedand restarted. This is to prevent a single query timeout from killing a connectionwhich may be serving more queries just fine.Default is 0, should not be changed concurrently with queries.

Deprecated.

View Source
var UnsetValue = unsetColumn{}

UnsetValue represents a value used in a query binding that will be ignored by Cassandra.

By setting a field to the unset value Cassandra will ignore the write completely.The main advantage is the ability to keep the same prepared statement even when you don'twant to update some fields, where before you needed to make another prepared statement.

UnsetValue is only available when using the version 4 of the protocol.

Functions

funcJoinHostPort

func JoinHostPort(addrstring, portint)string

JoinHostPort is a utility to return an address string that can be usedby `gocql.Conn` to form a connection with a host.

funcLookupIP

func LookupIP(hoststring) ([]net.IP,error)

funcMarshal

func Marshal(infoTypeInfo, value interface{}) ([]byte,error)

Marshal returns the CQL encoding of the value for the Cassandrainternal type described by the info parameter.

nil is serialized as CQL null.If value implements Marshaler, its MarshalCQL method is called to marshal the data.If value is a pointer, the pointed-to value is marshaled.

Supported conversions are as follows, other type combinations may be added in the future:

CQL type                    | Go type (value)    | Notevarchar, ascii, blob, text  | string, []byte     |boolean                     | bool               |tinyint, smallint, int      | integer types      |tinyint, smallint, int      | string             | formatted as base 10 numberbigint, counter             | integer types      |bigint, counter             | big.Int            |bigint, counter             | string             | formatted as base 10 numberfloat                       | float32            |double                      | float64            |decimal                     | inf.Dec            |time                        | int64              | nanoseconds since start of daytime                        | time.Duration      | duration since start of daytimestamp                   | int64              | milliseconds since Unix epochtimestamp                   | time.Time          |list, set                   | slice, array       |list, set                   | map[X]struct{}     |map                         | map[X]Y            |uuid, timeuuid              | gocql.UUID         |uuid, timeuuid              | [16]byte           | raw UUID bytesuuid, timeuuid              | []byte             | raw UUID bytes, length must be 16 bytesuuid, timeuuid              | string             | hex representation, see ParseUUIDvarint                      | integer types      |varint                      | big.Int            |varint                      | string             | value of number in decimal notationinet                        | net.IP             |inet                        | string             | IPv4 or IPv6 address stringtuple                       | slice, array       |tuple                       | struct             | fields are marshaled in order of declarationuser-defined type           | gocql.UDTMarshaler | MarshalUDT is calleduser-defined type           | map[string]interface{} |user-defined type           | struct             | struct fields' cql tags are used for column namesdate                        | int64              | milliseconds since Unix epoch to start of day (in UTC)date                        | time.Time          | start of day (in UTC)date                        | string             | parsed using "2006-01-02" formatduration                    | int64              | duration in nanosecondsduration                    | time.Duration      |duration                    | gocql.Duration     |duration                    | string             | parsed with time.ParseDuration

funcNamedValue

func NamedValue(namestring, value interface{}) interface{}

NamedValue produce a value which will bind to the named parameter in a query

funcNewErrProtocol

func NewErrProtocol(formatstring, args ...interface{})error

funcNonLocalReplicasFallback

func NonLocalReplicasFallback() func(policy *tokenAwareHostPolicy)

NonLocalReplicasFallback enables fallback to replicas that are not considered local.

TokenAwareHostPolicy used with DCAwareHostPolicy fallback first selects replicas by partition key in local DC, thenfalls back to other nodes in the local DC. Enabling NonLocalReplicasFallback causes TokenAwareHostPolicyto first select replicas by partition key in local DC, then replicas by partition key in remote DCs and fall backto other nodes in local DC.

funcShuffleReplicas

func ShuffleReplicas() func(*tokenAwareHostPolicy)

funcSingleHostReadyPolicy

func SingleHostReadyPolicy(pHostSelectionPolicy) *singleHostReadyPolicy

SingleHostReadyPolicy wraps a HostSelectionPolicy and returns Ready after asingle host has been added via HostUp

funcTupleColumnName

func TupleColumnName(cstring, nint)string

TupeColumnName will return the column name of a tuple value in a column namedc at index n. It should be used if a specific element within a tuple is neededto be extracted from a map returned from SliceMap or MapScan.

funcUnmarshal

func Unmarshal(infoTypeInfo, data []byte, value interface{})error

Unmarshal parses the CQL encoded data based on the info parameter thatdescribes the Cassandra internal data type and stores the result in thevalue pointed by value.

If value implements Unmarshaler, it's UnmarshalCQL method is called tounmarshal the data.If value is a pointer to pointer, it is set to nil if the CQL value isnull. Otherwise, nulls are unmarshalled as zero value.

Supported conversions are as follows, other type combinations may be added in the future:

CQL type                                | Go type (value)         | Notevarchar, ascii, blob, text              | *string                 |varchar, ascii, blob, text              | *[]byte                 | non-nil buffer is reusedbool                                    | *bool                   |tinyint, smallint, int, bigint, counter | *integer types          |tinyint, smallint, int, bigint, counter | *big.Int                |tinyint, smallint, int, bigint, counter | *string                 | formatted as base 10 numberfloat                                   | *float32                |double                                  | *float64                |decimal                                 | *inf.Dec                |time                                    | *int64                  | nanoseconds since start of daytime                                    | *time.Duration          |timestamp                               | *int64                  | milliseconds since Unix epochtimestamp                               | *time.Time              |list, set                               | *slice, *array          |map                                     | *map[X]Y                |uuid, timeuuid                          | *string                 | see UUID.Stringuuid, timeuuid                          | *[]byte                 | raw UUID bytesuuid, timeuuid                          | *gocql.UUID             |timeuuid                                | *time.Time              | timestamp of the UUIDinet                                    | *net.IP                 |inet                                    | *string                 | IPv4 or IPv6 address stringtuple                                   | *slice, *array          |tuple                                   | *struct                 | struct fields are set in order of declarationuser-defined types                      | gocql.UDTUnmarshaler    | UnmarshalUDT is calleduser-defined types                      | *map[string]interface{} |user-defined types                      | *struct                 | cql tag is used to determine field namedate                                    | *time.Time              | time of beginning of the day (in UTC)date                                    | *string                 | formatted with 2006-01-02 formatduration                                | *gocql.Duration         |

Types

typeAddressTranslator

type AddressTranslator interface {// Translate will translate the provided address and/or port to another// address and/or port. If no translation is possible, Translate will return the// address and port provided to it.Translate(addrnet.IP, portint) (net.IP,int)}

AddressTranslator provides a way to translate node addresses (and ports) that arediscovered or received as a node event. This can be useful in an ec2 environment,for instance, to translate public IPs to private IPs.

funcIdentityTranslator

func IdentityTranslator()AddressTranslator

IdentityTranslator will do nothing but return what it was provided. It is essentially a no-op.

typeAddressTranslatorFunc

type AddressTranslatorFunc func(addrnet.IP, portint) (net.IP,int)

func (AddressTranslatorFunc)Translate

func (fnAddressTranslatorFunc) Translate(addrnet.IP, portint) (net.IP,int)

typeAggregateMetadata

type AggregateMetadata struct {KeyspacestringNamestringArgumentTypes []TypeInfoFinalFuncFunctionMetadataInitCondstringReturnTypeTypeInfoStateFuncFunctionMetadataStateTypeTypeInfo// contains filtered or unexported fields}

AggregateMetadata holds metadata for aggregate constructs

typeAuthenticator

type Authenticator interface {Challenge(req []byte) (resp []byte, authAuthenticator, errerror)Success(data []byte)error}

typeBatch

type Batch struct {TypeBatchTypeEntries []BatchEntryConsConsistencyCustomPayload map[string][]byte// contains filtered or unexported fields}

funcNewBatchdeprecated

func NewBatch(typBatchType) *Batch

NewBatch creates a new batch operation without defaults from the cluster

Deprecated: use session.NewBatch instead

func (*Batch)AddAttempts

func (b *Batch) AddAttempts(iint, host *HostInfo)

func (*Batch)AddLatency

func (b *Batch) AddLatency(lint64, host *HostInfo)

func (*Batch)Attempts

func (b *Batch) Attempts()int

Attempts returns the number of attempts made to execute the batch.

func (*Batch)Bind

func (b *Batch) Bind(stmtstring, bind func(q *QueryInfo) ([]interface{},error))

Bind adds the query to the batch operation and correlates it with a binding callbackthat will be invoked when the batch is executed. The binding callback allows the applicationto define which query argument values will be marshalled as part of the batch execution.

func (*Batch)Cancel

func (*Batch) Cancel()

Deprecate: does nothing, cancel the context passed to WithContext

func (*Batch)Context

func (b *Batch) Context()context.Context

func (*Batch)DefaultTimestamp

func (b *Batch) DefaultTimestamp(enablebool) *Batch

DefaultTimestamp will enable the with default timestamp flag on the query.If enable, this will replace the server side assignedtimestamp as default timestamp. Note that a timestamp in the query itselfwill still override this timestamp. This is entirely optional.

Only available on protocol >= 3

func (*Batch)GetConsistency

func (b *Batch) GetConsistency()Consistency

GetConsistency returns the currently configured consistency level for the batchoperation.

func (*Batch)GetRoutingKey

func (b *Batch) GetRoutingKey() ([]byte,error)

func (*Batch)IsIdempotent

func (b *Batch) IsIdempotent()bool

func (*Batch)Keyspace

func (b *Batch) Keyspace()string

func (*Batch)Latency

func (b *Batch) Latency()int64

Latency returns the average number of nanoseconds to execute a single attempt of the batch.

func (*Batch)Observer

func (b *Batch) Observer(observerBatchObserver) *Batch

Observer enables batch-level observer on this batch.The provided observer will be called every time this batched query is executed.

func (*Batch)Query

func (b *Batch) Query(stmtstring, args ...interface{})

Query adds the query to the batch operation

func (*Batch)RetryPolicy

func (b *Batch) RetryPolicy(rRetryPolicy) *Batch

RetryPolicy sets the retry policy to use when executing the batch operation

func (*Batch)SerialConsistency

func (b *Batch) SerialConsistency(consSerialConsistency) *Batch

SerialConsistency sets the consistency level for theserial phase of conditional updates. That consistency can only beeither SERIAL or LOCAL_SERIAL and if not present, it defaults toSERIAL. This option will be ignored for anything else that aconditional update/insert.

Only available for protocol 3 and above

func (*Batch)SetConsistency

func (b *Batch) SetConsistency(cConsistency)

SetConsistency sets the currently configured consistency level for the batchoperation.

func (*Batch)Size

func (b *Batch) Size()int

Size returns the number of batch statements to be executed by the batch operation.

func (*Batch)SpeculativeExecutionPolicy

func (b *Batch) SpeculativeExecutionPolicy(spSpeculativeExecutionPolicy) *Batch

func (*Batch)Tableadded inv1.6.0

func (b *Batch) Table()string

Batch has no reasonable eqivalent of Query.Table().

func (*Batch)Trace

func (b *Batch) Trace(traceTracer) *Batch

Trace enables tracing of this batch. Look at the documentation of theTracer interface to learn more about tracing.

func (*Batch)WithContext

func (b *Batch) WithContext(ctxcontext.Context) *Batch

WithContext returns a shallow copy of b with its contextset to ctx.

The provided context controls the entire lifetime of executing aquery, queries will be canceled and return once the context iscanceled.

func (*Batch)WithTimestamp

func (b *Batch) WithTimestamp(timestampint64) *Batch

WithTimestamp will enable the with default timestamp flag on the querylike DefaultTimestamp does. But also allows to define value for timestamp.It works the same way as USING TIMESTAMP in the query itself, butshould not break prepared query optimization.

Only available on protocol >= 3

typeBatchEntry

type BatchEntry struct {StmtstringArgs       []interface{}Idempotentbool// contains filtered or unexported fields}

typeBatchObserver

type BatchObserver interface {// ObserveBatch gets called on every batch query to cassandra.// It also gets called once for each query in a batch.// It doesn't get called if there is no query because the session is closed or there are no connections available.// The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.// Unlike QueryObserver.ObserveQuery it does no reporting on rows read.ObserveBatch(context.Context,ObservedBatch)}

BatchObserver is the interface implemented by batch observers / stat collectors.

typeBatchType

type BatchTypebyte
const (LoggedBatchBatchType = 0UnloggedBatchBatchType = 1CounterBatchBatchType = 2)

typeClusterConfig

type ClusterConfig struct {// addresses for the initial connections. It is recommended to use the value set in// the Cassandra config for broadcast_address or listen_address, an IP address not// a domain name. This is because events from Cassandra will use the configured IP// address, which is used to index connected hosts. If the domain name specified// resolves to more than 1 IP address then the driver may connect multiple times to// the same host, and will not mark the node being down or up from events.Hosts []string// CQL version (default: 3.0.0)CQLVersionstring// ProtoVersion sets the version of the native protocol to use, this will// enable features in the driver for specific protocol versions, generally this// should be set to a known version (2,3,4) for the cluster being connected to.//// If it is 0 or unset (the default) then the driver will attempt to discover the// highest supported protocol for the cluster. In clusters with nodes of different// versions the protocol selected is not defined (ie, it can be any of the supported in the cluster)ProtoVersionint// Timeout limits the time spent on the client side while executing a query.// Specifically, query or batch execution will return an error if the client does not receive a response// from the server within the Timeout period.// Timeout is also used to configure the read timeout on the underlying network connection.// Client Timeout should always be higher than the request timeouts configured on the server,// so that retries don't overload the server.// Timeout has a default value of 11 seconds, which is higher than default server timeout for most query types.// Timeout is not applied to requests during initial connection setup, see ConnectTimeout.Timeouttime.Duration// ConnectTimeout limits the time spent during connection setup.// During initial connection setup, internal queries, AUTH requests will return an error if the client// does not receive a response within the ConnectTimeout period.// ConnectTimeout is applied to the connection setup queries independently.// ConnectTimeout also limits the duration of dialing a new TCP connection// in case there is no Dialer nor HostDialer configured.// ConnectTimeout has a default value of 11 seconds.ConnectTimeouttime.Duration// WriteTimeout limits the time the driver waits to write a request to a network connection.// WriteTimeout should be lower than or equal to Timeout.// WriteTimeout defaults to the value of Timeout.WriteTimeouttime.Duration// Port used when dialing.// Default: 9042Portint// Initial keyspace. Optional.Keyspacestring// Number of connections per host.// Default: 2NumConnsint// Default consistency level.// Default: QuorumConsistencyConsistency// Compression algorithm.// Default: nilCompressorCompressor// Default: nilAuthenticatorAuthenticator// An Authenticator factory. Can be used to create alternative authenticators.// Default: nilAuthProvider func(h *HostInfo) (Authenticator,error)// Default retry policy to use for queries.// Default: no retries.RetryPolicyRetryPolicy// ConvictionPolicy decides whether to mark host as down based on the error and host info.// Default: SimpleConvictionPolicyConvictionPolicyConvictionPolicy// Default reconnection policy to use for reconnecting before trying to mark host as down.ReconnectionPolicyReconnectionPolicy// The keepalive period to use, enabled if > 0 (default: 0)// SocketKeepalive is used to set up the default dialer and is ignored if Dialer or HostDialer is provided.SocketKeepalivetime.Duration// Maximum cache size for prepared statements globally for gocql.// Default: 1000MaxPreparedStmtsint// Maximum cache size for query info about statements for each session.// Default: 1000MaxRoutingKeyInfoint// Default page size to use for created sessions.// Default: 5000PageSizeint// Consistency for the serial part of queries, values can be either SERIAL or LOCAL_SERIAL.// Default: unsetSerialConsistencySerialConsistency// SslOpts configures TLS use when HostDialer is not set.// SslOpts is ignored if HostDialer is set.SslOpts *SslOptions// Sends a client side timestamp for all requests which overrides the timestamp at which it arrives at the server.// Default: true, only enabled for protocol 3 and above.DefaultTimestampbool// PoolConfig configures the underlying connection pool, allowing the// configuration of host selection and connection selection policies.PoolConfigPoolConfig// If not zero, gocql attempt to reconnect known DOWN nodes in every ReconnectInterval.ReconnectIntervaltime.Duration// The maximum amount of time to wait for schema agreement in a cluster after// receiving a schema change frame. (default: 60s)MaxWaitSchemaAgreementtime.Duration// HostFilter will filter all incoming events for host, any which don't pass// the filter will be ignored. If set will take precedence over any options set// via DiscoveryHostFilterHostFilter// AddressTranslator will translate addresses found on peer discovery and/or// node change events.AddressTranslatorAddressTranslator// If IgnorePeerAddr is true and the address in system.peers does not match// the supplied host by either initial hosts or discovered via events then the// host will be replaced with the supplied address.//// For example if an event comes in with host=10.0.0.1 but when looking up that// address in system.local or system.peers returns 127.0.0.1, the peer will be// set to 10.0.0.1 which is what will be used to connect to.IgnorePeerAddrbool// If DisableInitialHostLookup then the driver will not attempt to get host info// from the system.peers table, this will mean that the driver will connect to// hosts supplied and will not attempt to lookup the hosts information, this will// mean that data_centre, rack and token information will not be available and as// such host filtering and token aware query routing will not be available.DisableInitialHostLookupbool// Configure events the driver will register forEvents struct {// disable registering for status events (node up/down)DisableNodeStatusEventsbool// disable registering for topology events (node added/removed/moved)DisableTopologyEventsbool// disable registering for schema events (keyspace/table/function removed/created/updated)DisableSchemaEventsbool}// DisableSkipMetadata will override the internal result metadata cache so that the driver does not// send skip_metadata for queries, this means that the result will always contain// the metadata to parse the rows and will not reuse the metadata from the prepared// statement.//// Seehttps://issues.apache.org/jira/browse/CASSANDRA-10786DisableSkipMetadatabool// QueryObserver will set the provided query observer on all queries created from this session.// Use it to collect metrics / stats from queries by providing an implementation of QueryObserver.QueryObserverQueryObserver// BatchObserver will set the provided batch observer on all queries created from this session.// Use it to collect metrics / stats from batch queries by providing an implementation of BatchObserver.BatchObserverBatchObserver// ConnectObserver will set the provided connect observer on all queries// created from this session.ConnectObserverConnectObserver// FrameHeaderObserver will set the provided frame header observer on all frames' headers created from this session.// Use it to collect metrics / stats from frames by providing an implementation of FrameHeaderObserver.FrameHeaderObserverFrameHeaderObserver// StreamObserver will be notified of stream state changes.// This can be used to track in-flight protocol requests and responses.StreamObserverStreamObserver// Default idempotence for queriesDefaultIdempotencebool// The time to wait for frames before flushing the frames connection to Cassandra.// Can help reduce syscall overhead by making less calls to write. Set to 0 to// disable.//// (default: 200 microseconds)WriteCoalesceWaitTimetime.Duration// Dialer will be used to establish all connections created for this Cluster.// If not provided, a default dialer configured with ConnectTimeout will be used.// Dialer is ignored if HostDialer is provided.DialerDialer// HostDialer will be used to establish all connections for this Cluster.// If not provided, Dialer will be used instead.HostDialerHostDialer// Logger for this ClusterConfig.// If not specified, defaults to the global gocql.Logger.LoggerStdLogger// contains filtered or unexported fields}

ClusterConfig is a struct to configure the default cluster implementationof gocql. It has a variety of attributes that can be used to modify thebehavior to fit the most common use cases. Applications that require adifferent setup must implement their own cluster.

funcNewCluster

func NewCluster(hosts ...string) *ClusterConfig

NewCluster generates a new config for the default cluster implementation.

The supplied hosts are used to initially connect to the cluster then the rest ofthe ring will be automatically discovered. It is recommended to use the value set inthe Cassandra config for broadcast_address or listen_address, an IP address nota domain name. This is because events from Cassandra will use the configured IPaddress, which is used to index connected hosts. If the domain name specifiedresolves to more than 1 IP address then the driver may connect multiple times tothe same host, and will not mark the node being down or up from events.

func (*ClusterConfig)CreateSession

func (cfg *ClusterConfig) CreateSession() (*Session,error)

CreateSession initializes the cluster based on this config and returns asession object that can be used to interact with the database.

typeCollectionType

type CollectionType struct {NativeTypeKeyTypeInfo// only used for TypeMapElemTypeInfo// only used for TypeMap, TypeList and TypeSet}

func (CollectionType)New

func (tCollectionType) New() interface{}

func (CollectionType)NewWithErroradded inv1.1.0

func (tCollectionType) NewWithError() (interface{},error)

func (CollectionType)String

func (cCollectionType) String()string

typeColumnIndexMetadata

type ColumnIndexMetadata struct {NamestringTypestringOptions map[string]interface{}}

typeColumnInfo

type ColumnInfo struct {KeyspacestringTablestringNamestringTypeInfoTypeInfo}

func (ColumnInfo)String

func (cColumnInfo) String()string

typeColumnKind

type ColumnKindint
const (ColumnUnkownKindColumnKind =iotaColumnPartitionKeyColumnClusteringKeyColumnRegularColumnCompactColumnStatic)

func (ColumnKind)String

func (cColumnKind) String()string

func (*ColumnKind)UnmarshalCQL

func (c *ColumnKind) UnmarshalCQL(typTypeInfo, p []byte)error

typeColumnMetadata

type ColumnMetadata struct {KeyspacestringTablestringNamestringComponentIndexintKindColumnKindValidatorstringTypeTypeInfoClusteringOrderstringOrderColumnOrderIndexColumnIndexMetadata}

schema metadata for a column

typeColumnOrder

type ColumnOrderbool

the ordering of the column with regard to its comparator

typeCompressor

type Compressor interface {Name()stringEncode(data []byte) ([]byte,error)Decode(data []byte) ([]byte,error)}

typeConn

type Conn struct {// contains filtered or unexported fields}

Conn is a single connection to a Cassandra node. It can be used to executequeries, but users are usually advised to use a more reliable, higherlevel API.

func (*Conn)Address

func (c *Conn) Address()string

func (*Conn)AvailableStreams

func (c *Conn) AvailableStreams()int

func (*Conn)Close

func (c *Conn) Close()

func (*Conn)Closed

func (c *Conn) Closed()bool

func (*Conn)Pick

func (c *Conn) Pick(qry *Query) *Conn

func (*Conn)Read

func (c *Conn) Read(p []byte) (nint, errerror)

func (*Conn)UseKeyspace

func (c *Conn) UseKeyspace(keyspacestring)error

func (*Conn)Write

func (c *Conn) Write(p []byte) (nint, errerror)

typeConnConfig

type ConnConfig struct {ProtoVersionintCQLVersionstringTimeouttime.DurationWriteTimeouttime.DurationConnectTimeouttime.DurationDialerDialerHostDialerHostDialerCompressorCompressorAuthenticatorAuthenticatorAuthProvider   func(h *HostInfo) (Authenticator,error)Keepalivetime.DurationLoggerStdLogger// contains filtered or unexported fields}

typeConnErrorHandler

type ConnErrorHandler interface {HandleError(conn *Conn, errerror, closedbool)}

typeConnectObserver

type ConnectObserver interface {// ObserveConnect gets called when a new connection to cassandra is made.ObserveConnect(ObservedConnect)}

ConnectObserver is the interface implemented by connect observers / stat collectors.

typeConsistency

type Consistencyuint16
const (AnyConsistency = 0x00OneConsistency = 0x01TwoConsistency = 0x02ThreeConsistency = 0x03QuorumConsistency = 0x04AllConsistency = 0x05LocalQuorumConsistency = 0x06EachQuorumConsistency = 0x07LocalOneConsistency = 0x0A)

funcMustParseConsistency

func MustParseConsistency(sstring) (Consistency,error)

MustParseConsistency is the same as ParseConsistency except it returnsan error (never). It is kept here since breaking changes are not good.DEPRECATED: use ParseConsistency if you want a panic on parse error.

funcParseConsistency

func ParseConsistency(sstring)Consistency

funcParseConsistencyWrapper

func ParseConsistencyWrapper(sstring) (consistencyConsistency, errerror)

ParseConsistencyWrapper wraps gocql.ParseConsistency to provide an errreturn instead of a panic

func (Consistency)MarshalText

func (cConsistency) MarshalText() (text []byte, errerror)

func (Consistency)String

func (cConsistency) String()string

func (*Consistency)UnmarshalText

func (c *Consistency) UnmarshalText(text []byte)error

typeConstantReconnectionPolicy

type ConstantReconnectionPolicy struct {MaxRetriesintIntervaltime.Duration}

ConstantReconnectionPolicy has simple logic for returning a fixed reconnection interval.

Examples of usage:

cluster.ReconnectionPolicy = &gocql.ConstantReconnectionPolicy{MaxRetries: 10, Interval: 8 * time.Second}

func (*ConstantReconnectionPolicy)GetInterval

func (c *ConstantReconnectionPolicy) GetInterval(currentRetryint)time.Duration

func (*ConstantReconnectionPolicy)GetMaxRetries

func (c *ConstantReconnectionPolicy) GetMaxRetries()int

typeConvictionPolicy

type ConvictionPolicy interface {// Implementations should return `true` if the host should be convicted, `false` otherwise.AddFailure(errorerror, host *HostInfo)bool//Implementations should clear out any convictions or state regarding the host.Reset(host *HostInfo)}

ConvictionPolicy interface is used by gocql to determine if a host should bemarked as DOWN based on the error and host info

typeDialedHostadded inv1.2.0

type DialedHost struct {// Conn used to communicate with the server.Connnet.Conn// DisableCoalesce disables write coalescing for the Conn.// If true, the effect is the same as if WriteCoalesceWaitTime was configured to 0.DisableCoalescebool}

DialedHost contains information about established connection to a host.

funcWrapTLSadded inv1.2.0

func WrapTLS(ctxcontext.Context, connnet.Conn, addrstring, tlsConfig *tls.Config) (*DialedHost,error)

WrapTLS optionally wraps a net.Conn connected to addr with the given tlsConfig.If the tlsConfig is nil, conn is not wrapped into a TLS session, so is insecure.If the tlsConfig does not have server name set, it is updated based on the default gocql rules.

typeDialer

type Dialer interface {DialContext(ctxcontext.Context, network, addrstring) (net.Conn,error)}

typeDowngradingConsistencyRetryPolicy

type DowngradingConsistencyRetryPolicy struct {ConsistencyLevelsToTry []Consistency}

func (*DowngradingConsistencyRetryPolicy)Attempt

func (*DowngradingConsistencyRetryPolicy)GetRetryType

typeDuration

type Duration struct {Monthsint32Daysint32Nanosecondsint64}

typeErrProtocol

type ErrProtocol struct {// contains filtered or unexported fields}

typeError

type Error struct {CodeintMessagestring}

func (Error)Error

func (eError) Error()string

typeErrorMap

type ErrorMap map[string]uint16

typeExecutableQuery

type ExecutableQuery interface {GetRoutingKey() ([]byte,error)Keyspace()stringTable()stringIsIdempotent()boolRetryableQuery// contains filtered or unexported methods}

typeExponentialBackoffRetryPolicy

type ExponentialBackoffRetryPolicy struct {NumRetriesintMin, Maxtime.Duration}

ExponentialBackoffRetryPolicy sleeps between attempts

func (*ExponentialBackoffRetryPolicy)Attempt

func (*ExponentialBackoffRetryPolicy)GetRetryType

typeExponentialReconnectionPolicy

type ExponentialReconnectionPolicy struct {MaxRetriesintInitialIntervaltime.DurationMaxIntervaltime.Duration}

ExponentialReconnectionPolicy returns a growing reconnection interval.

func (*ExponentialReconnectionPolicy)GetInterval

func (e *ExponentialReconnectionPolicy) GetInterval(currentRetryint)time.Duration

func (*ExponentialReconnectionPolicy)GetMaxRetries

func (e *ExponentialReconnectionPolicy) GetMaxRetries()int

typeFrameHeaderObserver

type FrameHeaderObserver interface {// ObserveFrameHeader gets called on every received frame header.ObserveFrameHeader(context.Context,ObservedFrameHeader)}

FrameHeaderObserver is the interface implemented by frame observers / stat collectors.

Experimental, this interface and use may change

typeFunctionMetadata

type FunctionMetadata struct {KeyspacestringNamestringArgumentTypes     []TypeInfoArgumentNames     []stringBodystringCalledOnNullInputboolLanguagestringReturnTypeTypeInfo}

FunctionMetadata holds metadata for function constructs

typeHostDialeradded inv1.2.0

type HostDialer interface {// DialHost establishes a connection to the host.// The returned connection must be directly usable for CQL protocol,// specifically DialHost is responsible also for setting up the TLS session if needed.// DialHost should disable write coalescing if the returned net.Conn does not support writev.// As of Go 1.18, only plain TCP connections support writev, TLS sessions should disable coalescing.// You can use WrapTLS helper function if you don't need to override the TLS setup.DialHost(ctxcontext.Context, host *HostInfo) (*DialedHost,error)}

HostDialer allows customizing connection to cluster nodes.

typeHostFilter

type HostFilter interface {// Called when a new host is discovered, returning true will cause the host// to be added to the pools.Accept(host *HostInfo)bool}

HostFilter interface is used when a host is discovered via server sent events.

funcAcceptAllFilter

func AcceptAllFilter()HostFilter

AcceptAllFilter will accept all hosts

funcDataCentreHostFilter

func DataCentreHostFilter(dataCentrestring)HostFilter

DataCentreHostFilter filters all hosts such that they are in the same data centreas the supplied data centre.

funcDenyAllFilter

func DenyAllFilter()HostFilter

funcWhiteListHostFilter

func WhiteListHostFilter(hosts ...string)HostFilter

WhiteListHostFilter filters incoming hosts by checking that their address isin the initial hosts whitelist.

typeHostFilterFunc

type HostFilterFunc func(host *HostInfo)bool

HostFilterFunc converts a func(host HostInfo) bool into a HostFilter

func (HostFilterFunc)Accept

func (fnHostFilterFunc) Accept(host *HostInfo)bool

typeHostInfo

type HostInfo struct {// contains filtered or unexported fields}

func (*HostInfo)BroadcastAddress

func (h *HostInfo) BroadcastAddress()net.IP

func (*HostInfo)ClusterName

func (h *HostInfo) ClusterName()string

func (*HostInfo)ConnectAddress

func (h *HostInfo) ConnectAddress()net.IP

Returns the address that should be used to connect to the host.If you wish to override this, use an AddressTranslator oruse a HostFilter to SetConnectAddress()

func (*HostInfo)ConnectAddressAndPortadded inv1.4.0

func (h *HostInfo) ConnectAddressAndPort()string

func (*HostInfo)DSEVersion

func (h *HostInfo) DSEVersion()string

func (*HostInfo)DataCenter

func (h *HostInfo) DataCenter()string

func (*HostInfo)Equal

func (h *HostInfo) Equal(host *HostInfo)bool

func (*HostInfo)Graph

func (h *HostInfo) Graph()bool

func (*HostInfo)HostID

func (h *HostInfo) HostID()string

func (*HostInfo)HostnameAndPort

func (h *HostInfo) HostnameAndPort()string

func (*HostInfo)IsUp

func (h *HostInfo) IsUp()bool

func (*HostInfo)ListenAddress

func (h *HostInfo) ListenAddress()net.IP

func (*HostInfo)Partitioner

func (h *HostInfo) Partitioner()string

func (*HostInfo)Peer

func (h *HostInfo) Peer()net.IP

func (*HostInfo)Port

func (h *HostInfo) Port()int

func (*HostInfo)PreferredIP

func (h *HostInfo) PreferredIP()net.IP

func (*HostInfo)RPCAddress

func (h *HostInfo) RPCAddress()net.IP

func (*HostInfo)Rack

func (h *HostInfo) Rack()string

func (*HostInfo)SetConnectAddress

func (h *HostInfo) SetConnectAddress(addressnet.IP) *HostInfo

func (*HostInfo)SetHostIDadded inv1.2.0

func (h *HostInfo) SetHostID(hostIDstring)

func (*HostInfo)State

func (h *HostInfo) State() nodeState

func (*HostInfo)String

func (h *HostInfo) String()string

func (*HostInfo)Tokens

func (h *HostInfo) Tokens() []string

func (*HostInfo)Version

func (h *HostInfo) Version() cassVersion

func (*HostInfo)WorkLoad

func (h *HostInfo) WorkLoad()string

typeHostSelectionPolicy

type HostSelectionPolicy interface {HostStateNotifierSetPartitionerKeyspaceChanged(KeyspaceUpdateEvent)Init(*Session)IsLocal(host *HostInfo)bool// Pick returns an iteration function over selected hosts.// Multiple attempts of a single query execution won't call the returned NextHost function concurrently,// so it's safe to have internal state without additional synchronization as long as every call to Pick returns// a different instance of NextHost.Pick(ExecutableQuery)NextHost}

HostSelectionPolicy is an interface for selectingthe most appropriate host to execute a given query.HostSelectionPolicy instances cannot be shared between sessions.

funcDCAwareRoundRobinPolicy

func DCAwareRoundRobinPolicy(localDCstring)HostSelectionPolicy

DCAwareRoundRobinPolicy is a host selection policies which will prioritize andreturn hosts which are in the local datacentre before returning hosts in allother datercentres

funcHostPoolHostPolicy

func HostPoolHostPolicy(hp hostpool.HostPool)HostSelectionPolicy

HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool libraryto distribute queries between hosts and prevent sending queries tounresponsive hosts. When creating the host pool that is passed to the policyuse an empty slice of hosts as the hostpool will be populated later by gocql.See below for examples of usage:

// Create host selection policy using a simple host poolcluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))// Create host selection policy using an epsilon greedy poolcluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(    hostpool.NewEpsilonGreedy(nil, 0, &hostpool.LinearEpsilonValueCalculator{}),)

funcRackAwareRoundRobinPolicyadded inv1.3.0

func RackAwareRoundRobinPolicy(localDCstring, localRackstring)HostSelectionPolicy

funcRoundRobinHostPolicy

func RoundRobinHostPolicy()HostSelectionPolicy

RoundRobinHostPolicy is a round-robin load balancing policy, where each hostis tried sequentially for each query.

funcTokenAwareHostPolicy

func TokenAwareHostPolicy(fallbackHostSelectionPolicy, opts ...func(*tokenAwareHostPolicy))HostSelectionPolicy

TokenAwareHostPolicy is a token aware host selection policy, where hosts areselected based on the partition key, so queries are sent to the host whichowns the partition. Fallback is used when routing information is not available.

typeHostStateNotifier

type HostStateNotifier interface {AddHost(host *HostInfo)RemoveHost(host *HostInfo)HostUp(host *HostInfo)HostDown(host *HostInfo)}

typeHostTiereradded inv1.3.0

type HostTierer interface {// HostTier returns an integer specifying how far a host is from the client.// Tier must start at 0.// The value is used to prioritize closer hosts during host selection.// For example this could be:// 0 - local rack, 1 - local DC, 2 - remote DC// or:// 0 - local DC, 1 - remote DCHostTier(host *HostInfo)uint// This function returns the maximum possible host tierMaxHostTier()uint}

typeIter

type Iter struct {// contains filtered or unexported fields}

Iter represents an iterator that can be used to iterate over all rows thatwere returned by a query. The iterator might send additional queries to thedatabase during the iteration if paging was enabled.

func (*Iter)Close

func (iter *Iter) Close()error

Close closes the iterator and returns any errors that happened duringthe query or the iteration.

func (*Iter)Columns

func (iter *Iter) Columns() []ColumnInfo

Columns returns the name and type of the selected columns.

func (*Iter)GetCustomPayload

func (iter *Iter) GetCustomPayload() map[string][]byte

GetCustomPayload returns any parsed custom payload results if given in theresponse from Cassandra. Note that the result is not a copy.

This additional feature of CQL Protocol v4allows additional results and query information to be returned bycustom QueryHandlers running in your C* cluster.Seehttps://datastax.github.io/java-driver/manual/custom_payloads/

func (*Iter)Host

func (iter *Iter) Host() *HostInfo

Host returns the host which the query was sent to.

func (*Iter)MapScan

func (iter *Iter) MapScan(m map[string]interface{})bool

MapScan takes a map[string]interface{} and populates it with a rowthat is returned from cassandra.

Each call to MapScan() must be called with a new map object.During the call to MapScan() any pointers in the existing mapare replaced with non pointer types before the call returns

iter := session.Query(`SELECT * FROM mytable`).Iter()for {// New map each iterationrow := make(map[string]interface{})if !iter.MapScan(row) {break}// Do things with rowif fullname, ok := row["fullname"]; ok {fmt.Printf("Full Name: %s\n", fullname)}}

You can also pass pointers in the map before each call

var fullName FullName // Implements gocql.Unmarshaler and gocql.Marshaler interfacesvar address net.IPvar age intiter := session.Query(`SELECT * FROM scan_map_table`).Iter()for {// New map each iterationrow := map[string]interface{}{"fullname": &fullName,"age":      &age,"address":  &address,}if !iter.MapScan(row) {break}fmt.Printf("First: %s Age: %d Address: %q\n", fullName.FirstName, age, address)}

func (*Iter)NumRows

func (iter *Iter) NumRows()int

NumRows returns the number of rows in this pagination, it will update when newpages are fetched, it is not the value of the total number of rows this iterwill return unless there is only a single page returned.

func (*Iter)PageState

func (iter *Iter) PageState() []byte

PageState return the current paging state for a query which can be used forsubsequent queries to resume paging this point.

func (*Iter)RowData

func (iter *Iter) RowData() (RowData,error)

func (*Iter)Scan

func (iter *Iter) Scan(dest ...interface{})bool

Scan consumes the next row of the iterator and copies the columns of thecurrent row into the values pointed at by dest. Use nil as a dest valueto skip the corresponding column. Scan might send additional queriesto the database to retrieve the next set of rows if paging was enabled.

Scan returns true if the row was successfully unmarshaled or false if theend of the result set was reached or if an error occurred. Close shouldbe called afterwards to retrieve any potential errors.

func (*Iter)Scanner

func (iter *Iter) Scanner()Scanner

Scanner returns a row Scanner which provides an interface to scan rows in a manner which issimilar to database/sql. The iter should NOT be used again after calling this method.

func (*Iter)SliceMap

func (iter *Iter) SliceMap() ([]map[string]interface{},error)

SliceMap is a helper function to make the API easier to usereturns the data from the query in the form of []map[string]interface{}

func (*Iter)Warnings

func (iter *Iter) Warnings() []string

Warnings returns any warnings generated if given in the response from Cassandra.

This is only available starting with CQL Protocol v4.

func (*Iter)WillSwitchPage

func (iter *Iter) WillSwitchPage()bool

WillSwitchPage detects if iterator reached end of current pageand the next page is available.

typeKeyspaceMetadata

type KeyspaceMetadata struct {NamestringDurableWritesboolStrategyClassstringStrategyOptions map[string]interface{}Tables          map[string]*TableMetadataFunctions       map[string]*FunctionMetadataAggregates      map[string]*AggregateMetadata// Deprecated: use the MaterializedViews field for views and UserTypes field for udts instead.Views             map[string]*ViewMetadataMaterializedViews map[string]*MaterializedViewMetadataUserTypes         map[string]*UserTypeMetadata}

schema metadata for a keyspace

typeKeyspaceUpdateEvent

type KeyspaceUpdateEvent struct {KeyspacestringChangestring}

typeMarshalError

type MarshalErrorstring

func (MarshalError)Error

func (mMarshalError) Error()string

typeMarshaler

type Marshaler interface {MarshalCQL(infoTypeInfo) ([]byte,error)}

Marshaler is the interface implemented by objects that can marshalthemselves into values understood by Cassandra.

typeMaterializedViewMetadata

type MaterializedViewMetadata struct {KeyspacestringNamestringBaseTableIdUUIDBaseTable               *TableMetadataBloomFilterFpChancefloat64Caching                 map[string]stringCommentstringCompaction              map[string]stringCompression             map[string]stringCrcCheckChancefloat64DcLocalReadRepairChancefloat64DefaultTimeToLiveintExtensions              map[string]stringGcGraceSecondsintIdUUIDIncludeAllColumnsboolMaxIndexIntervalintMemtableFlushPeriodInMsintMinIndexIntervalintReadRepairChancefloat64SpeculativeRetrystring// contains filtered or unexported fields}

MaterializedViewMetadata holds the metadata for materialized views.

typeNativeType

type NativeType struct {// contains filtered or unexported fields}

funcNewNativeType

func NewNativeType(protobyte, typType, customstring)NativeType

func (NativeType)Custom

func (sNativeType) Custom()string

func (NativeType)New

func (tNativeType) New() interface{}

func (NativeType)NewWithErroradded inv1.1.0

func (tNativeType) NewWithError() (interface{},error)

func (NativeType)String

func (sNativeType) String()string

func (NativeType)Type

func (sNativeType) Type()Type

func (NativeType)Version

func (sNativeType) Version()byte

typeNextHost

type NextHost func()SelectedHost

NextHost is an iteration function over picked hosts

typeNonSpeculativeExecution

type NonSpeculativeExecution struct{}

func (NonSpeculativeExecution)Attempts

func (spNonSpeculativeExecution) Attempts()int

func (NonSpeculativeExecution)Delay

typeObservedBatch

type ObservedBatch struct {KeyspacestringStatements []string// Values holds a slice of bound values for each statement.// Values[i] are bound values passed to Statements[i].// Do not modify the values here, they are shared with multiple goroutines.Values [][]interface{}Starttime.Time// time immediately before the batch query was calledEndtime.Time// time immediately after the batch query returned// Host is the informations about the host that performed the batchHost *HostInfo// Err is the error in the batch query.// It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil errorErrerror// The metrics per this hostMetrics *hostMetrics// Attempt is the index of attempt at executing this query.// The first attempt is number zero and any retries have non-zero attempt number.Attemptint}

typeObservedConnect

type ObservedConnect struct {// Host is the information about the host about to connectHost *HostInfoStarttime.Time// time immediately before the dial is calledEndtime.Time// time immediately after the dial returned// Err is the connection error (if any)Errerror}

typeObservedFrameHeader

type ObservedFrameHeader struct {Version protoVersionFlagsbyteStreamint16Opcode  frameOpLengthint32// StartHeader is the time we started reading the frame header off the network connection.Starttime.Time// EndHeader is the time we finished reading the frame header off the network connection.Endtime.Time// Host is Host of the connection the frame header was read from.Host *HostInfo}

func (ObservedFrameHeader)String

func (fObservedFrameHeader) String()string

typeObservedQuery

type ObservedQuery struct {KeyspacestringStatementstring// Values holds a slice of bound values for the query.// Do not modify the values here, they are shared with multiple goroutines.Values []interface{}Starttime.Time// time immediately before the query was calledEndtime.Time// time immediately after the query returned// Rows is the number of rows in the current iter.// In paginated queries, rows from previous scans are not counted.// Rows is not used in batch queries and remains at the default valueRowsint// Host is the informations about the host that performed the queryHost *HostInfo// The metrics per this hostMetrics *hostMetrics// Err is the error in the query.// It only tracks network errors or errors of bad cassandra syntax, in particular selects with no match return nil errorErrerror// Attempt is the index of attempt at executing this query.// The first attempt is number zero and any retries have non-zero attempt number.Attemptint}

typeObservedStreamadded inv1.1.0

type ObservedStream struct {// Host of the connection used to send the stream.Host *HostInfo}

ObservedStream observes a single request/response stream.

typePasswordAuthenticator

type PasswordAuthenticator struct {UsernamestringPasswordstringAllowedAuthenticators []string}

func (PasswordAuthenticator)Challenge

func (pPasswordAuthenticator) Challenge(req []byte) ([]byte,Authenticator,error)

func (PasswordAuthenticator)Success

func (pPasswordAuthenticator) Success(data []byte)error

typePoolConfig

type PoolConfig struct {// HostSelectionPolicy sets the policy for selecting which host to use for a// given query (default: RoundRobinHostPolicy())// It is not supported to use a single HostSelectionPolicy in multiple sessions// (even if you close the old session before using in a new session).HostSelectionPolicyHostSelectionPolicy}

PoolConfig configures the connection pool used by the driver, it defaults tousing a round-robin host selection policy and a round-robin connection selectionpolicy for each host.

typeQuery

type Query struct {// contains filtered or unexported fields}

Query represents a CQL statement that can be executed.

func (*Query)AddAttempts

func (q *Query) AddAttempts(iint, host *HostInfo)

func (*Query)AddLatency

func (q *Query) AddLatency(lint64, host *HostInfo)

func (*Query)Attempts

func (q *Query) Attempts()int

Attempts returns the number of times the query was executed.

func (*Query)Bind

func (q *Query) Bind(v ...interface{}) *Query

Bind sets query arguments of query. This can also be used to rebind new query argumentsto an existing query instance.

func (*Query)Cancel

func (q *Query) Cancel()

Deprecate: does nothing, cancel the context passed to WithContext

func (*Query)Consistency

func (q *Query) Consistency(cConsistency) *Query

Consistency sets the consistency level for this query. If no consistencylevel have been set, the default consistency level of the clusteris used.

func (*Query)Context

func (q *Query) Context()context.Context

func (*Query)CustomPayload

func (q *Query) CustomPayload(customPayload map[string][]byte) *Query

CustomPayload sets the custom payload level for this query.

func (*Query)DefaultTimestamp

func (q *Query) DefaultTimestamp(enablebool) *Query

DefaultTimestamp will enable the with default timestamp flag on the query.If enable, this will replace the server side assignedtimestamp as default timestamp. Note that a timestamp in the query itselfwill still override this timestamp. This is entirely optional.

Only available on protocol >= 3

func (*Query)Exec

func (q *Query) Exec()error

Exec executes the query without returning any rows.

func (*Query)GetConsistency

func (q *Query) GetConsistency()Consistency

GetConsistency returns the currently configured consistency level forthe query.

func (*Query)GetRoutingKey

func (q *Query) GetRoutingKey() ([]byte,error)

GetRoutingKey gets the routing key to use for routing this query. Ifa routing key has not been explicitly set, then the routing key willbe constructed if possible using the keyspace's schema and the queryinfo for this query statement. If the routing key cannot be determinedthen nil will be returned with no error. On any error condition,an error description will be returned.

func (*Query)Idempotent

func (q *Query) Idempotent(valuebool) *Query

Idempotent marks the query as being idempotent or not depending onthe value.Non-idempotent query won't be retried.See "Retries and speculative execution" in package docs for more details.

func (*Query)IsIdempotent

func (q *Query) IsIdempotent()bool

IsIdempotent returns whether the query is marked as idempotent.Non-idempotent query won't be retried.See "Retries and speculative execution" in package docs for more details.

func (*Query)Iter

func (q *Query) Iter() *Iter

Iter executes the query and returns an iterator capable of iteratingover all results.

func (*Query)Keyspace

func (q *Query) Keyspace()string

Keyspace returns the keyspace the query will be executed against.

func (*Query)Latency

func (q *Query) Latency()int64

Latency returns the average amount of nanoseconds per attempt of the query.

func (*Query)MapScan

func (q *Query) MapScan(m map[string]interface{})error

MapScan executes the query, copies the columns of the first selectedrow into the map pointed at by m and discards the rest. If no rowswere selected, ErrNotFound is returned.

func (*Query)MapScanCAS

func (q *Query) MapScanCAS(dest map[string]interface{}) (appliedbool, errerror)

MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERTstatement containing an IF clause). If the transaction fails becausethe existing values did not match, the previous values will be storedin dest map.

As for INSERT .. IF NOT EXISTS, previous values will be returned as ifSELECT * FROM. So using ScanCAS with INSERT is inherently prone tocolumn mismatching. MapScanCAS is added to capture them safely.

Example

ExampleQuery_MapScanCAS demonstrates how to execute a single-statement lightweight transaction.

package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.my_lwt_table(pk int, version int, value text, PRIMARY KEY(pk));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()err = session.Query("INSERT INTO example.my_lwt_table (pk, version, value) VALUES (?, ?, ?)",1, 1, "a").WithContext(ctx).Exec()if err != nil {log.Fatal(err)}m := make(map[string]interface{})applied, err := session.Query("UPDATE example.my_lwt_table SET value = ? WHERE pk = ? IF version = ?","b", 1, 0).WithContext(ctx).MapScanCAS(m)if err != nil {log.Fatal(err)}fmt.Println(applied, m)var value stringerr = session.Query("SELECT value FROM example.my_lwt_table WHERE pk = ?", 1).WithContext(ctx).Scan(&value)if err != nil {log.Fatal(err)}fmt.Println(value)m = make(map[string]interface{})applied, err = session.Query("UPDATE example.my_lwt_table SET value = ? WHERE pk = ? IF version = ?","b", 1, 1).WithContext(ctx).MapScanCAS(m)if err != nil {log.Fatal(err)}fmt.Println(applied, m)var value2 stringerr = session.Query("SELECT value FROM example.my_lwt_table WHERE pk = ?", 1).WithContext(ctx).Scan(&value2)if err != nil {log.Fatal(err)}fmt.Println(value2)// false map[version:1]// a// true map[]// b}
Output:

func (*Query)NoSkipMetadata

func (q *Query) NoSkipMetadata() *Query

NoSkipMetadata will override the internal result metadata cache so that the driver does notsend skip_metadata for queries, this means that the result will always containthe metadata to parse the rows and will not reuse the metadata from the preparedstatement. This should only be used to work around cassandra bugs, such as when usingCAS operations which do not end in Cas.

Seehttps://issues.apache.org/jira/browse/CASSANDRA-11099https://github.com/apache/cassandra-gocql-driver/issues/612

func (*Query)Observer

func (q *Query) Observer(observerQueryObserver) *Query

Observer enables query-level observer on this query.The provided observer will be called every time this query is executed.

func (*Query)PageSize

func (q *Query) PageSize(nint) *Query

PageSize will tell the iterator to fetch the result in pages of size n.This is useful for iterating over large result sets, but setting thepage size too low might decrease the performance. This feature is onlyavailable in Cassandra 2 and onwards.

func (*Query)PageState

func (q *Query) PageState(state []byte) *Query

PageState sets the paging state for the query to resume paging from a specificpoint in time. Setting this will disable to query paging for this query, andmust be used for all subsequent pages.

func (*Query)Prefetch

func (q *Query) Prefetch(pfloat64) *Query

SetPrefetch sets the default threshold for pre-fetching new pages. Ifthere are only p*pageSize rows remaining, the next page will be requestedautomatically.

func (*Query)Release

func (q *Query) Release()

Release releases a query back into a pool of queries. Released Queriescannot be reused.

Example:

qry := session.Query("SELECT * FROM my_table")qry.Exec()qry.Release()

func (*Query)RetryPolicy

func (q *Query) RetryPolicy(rRetryPolicy) *Query

RetryPolicy sets the policy to use when retrying the query.

func (*Query)RoutingKey

func (q *Query) RoutingKey(routingKey []byte) *Query

RoutingKey sets the routing key to use when a token aware connectionpool is used to optimize the routing of this query.

func (*Query)Scan

func (q *Query) Scan(dest ...interface{})error

Scan executes the query, copies the columns of the first selectedrow into the values pointed at by dest and discards the rest. If no rowswere selected, ErrNotFound is returned.

func (*Query)ScanCAS

func (q *Query) ScanCAS(dest ...interface{}) (appliedbool, errerror)

ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERTstatement containing an IF clause). If the transaction fails becausethe existing values did not match, the previous values will be storedin dest.

As for INSERT .. IF NOT EXISTS, previous values will be returned as ifSELECT * FROM. So using ScanCAS with INSERT is inherently prone tocolumn mismatching. Use MapScanCAS to capture them safely.

func (*Query)SerialConsistency

func (q *Query) SerialConsistency(consSerialConsistency) *Query

SerialConsistency sets the consistency level for theserial phase of conditional updates. That consistency can only beeither SERIAL or LOCAL_SERIAL and if not present, it defaults toSERIAL. This option will be ignored for anything else that aconditional update/insert.

func (*Query)SetConsistency

func (q *Query) SetConsistency(cConsistency)

Same as Consistency but without a return value

func (*Query)SetSpeculativeExecutionPolicy

func (q *Query) SetSpeculativeExecutionPolicy(spSpeculativeExecutionPolicy) *Query

SetSpeculativeExecutionPolicy sets the execution policy

func (Query)Statement

func (qQuery) Statement()string

Statement returns the statement that was used to generate this query.

func (Query)String

func (qQuery) String()string

String implements the stringer interface.

func (*Query)Tableadded inv1.6.0

func (q *Query) Table()string

Table returns name of the table the query will be executed against.

func (*Query)Trace

func (q *Query) Trace(traceTracer) *Query

Trace enables tracing of this query. Look at the documentation of theTracer interface to learn more about tracing.

func (Query)Valuesadded inv1.5.0

func (qQuery) Values() []interface{}

Values returns the values passed in via Bind.This can be used by a wrapper type that needs to access the bound values.

func (*Query)WithContext

func (q *Query) WithContext(ctxcontext.Context) *Query

WithContext returns a shallow copy of q with its contextset to ctx.

The provided context controls the entire lifetime of executing aquery, queries will be canceled and return once the context iscanceled.

func (*Query)WithTimestamp

func (q *Query) WithTimestamp(timestampint64) *Query

WithTimestamp will enable the with default timestamp flag on the querylike DefaultTimestamp does. But also allows to define value for timestamp.It works the same way as USING TIMESTAMP in the query itself, butshould not break prepared query optimization.

Only available on protocol >= 3

typeQueryInfo

type QueryInfo struct {Id          []byteArgs        []ColumnInfoRval        []ColumnInfoPKeyColumns []int}

typeQueryObserver

type QueryObserver interface {// ObserveQuery gets called on every query to cassandra, including all queries in an iterator when paging is enabled.// It doesn't get called if there is no query because the session is closed or there are no connections available.// The error reported only shows query errors, i.e. if a SELECT is valid but finds no matches it will be nil.ObserveQuery(context.Context,ObservedQuery)}

QueryObserver is the interface implemented by query observers / stat collectors.

Experimental, this interface and use may change

typeReadyPolicy

type ReadyPolicy interface {Ready()bool}

ReadyPolicy defines a policy for when a HostSelectionPolicy can be used. Aftereach host connects during session initialization, the Ready method will becalled. If you only need a single Host to be up you can wrap aHostSelectionPolicy policy with SingleHostReadyPolicy.

typeReconnectionPolicy

type ReconnectionPolicy interface {GetInterval(currentRetryint)time.DurationGetMaxRetries()int}

ReconnectionPolicy interface is used by gocql to determine if reconnectioncan be attempted after connection error. The interface allows gocql usersto implement their own logic to determine how to attempt reconnection.

typeRequestErrAlreadyExists

type RequestErrAlreadyExists struct {KeyspacestringTablestring// contains filtered or unexported fields}

func (RequestErrAlreadyExists)Code

func (e RequestErrAlreadyExists) Code()int

func (RequestErrAlreadyExists)Error

func (e RequestErrAlreadyExists) Error()string

func (RequestErrAlreadyExists)Message

func (e RequestErrAlreadyExists) Message()string

func (RequestErrAlreadyExists)String

func (e RequestErrAlreadyExists) String()string

typeRequestErrCASWriteUnknown

type RequestErrCASWriteUnknown struct {ConsistencyConsistencyReceivedintBlockForint// contains filtered or unexported fields}

RequestErrCASWriteUnknown is distinct error for ErrCodeCasWriteUnknown.

Seehttps://github.com/apache/cassandra/blob/7337fc0/doc/native_protocol_v5.spec#L1387-L1397

func (RequestErrCASWriteUnknown)Code

func (e RequestErrCASWriteUnknown) Code()int

func (RequestErrCASWriteUnknown)Error

func (e RequestErrCASWriteUnknown) Error()string

func (RequestErrCASWriteUnknown)Message

func (e RequestErrCASWriteUnknown) Message()string

func (RequestErrCASWriteUnknown)String

func (e RequestErrCASWriteUnknown) String()string

typeRequestErrCDCWriteFailure

type RequestErrCDCWriteFailure struct {// contains filtered or unexported fields}

func (RequestErrCDCWriteFailure)Code

func (e RequestErrCDCWriteFailure) Code()int

func (RequestErrCDCWriteFailure)Error

func (e RequestErrCDCWriteFailure) Error()string

func (RequestErrCDCWriteFailure)Message

func (e RequestErrCDCWriteFailure) Message()string

func (RequestErrCDCWriteFailure)String

func (e RequestErrCDCWriteFailure) String()string

typeRequestErrFunctionFailure

type RequestErrFunctionFailure struct {KeyspacestringFunctionstringArgTypes []string// contains filtered or unexported fields}

func (RequestErrFunctionFailure)Code

func (e RequestErrFunctionFailure) Code()int

func (RequestErrFunctionFailure)Error

func (e RequestErrFunctionFailure) Error()string

func (RequestErrFunctionFailure)Message

func (e RequestErrFunctionFailure) Message()string

func (RequestErrFunctionFailure)String

func (e RequestErrFunctionFailure) String()string

typeRequestErrReadFailure

type RequestErrReadFailure struct {ConsistencyConsistencyReceivedintBlockForintNumFailuresintDataPresentboolErrorMapErrorMap// contains filtered or unexported fields}

func (RequestErrReadFailure)Code

func (e RequestErrReadFailure) Code()int

func (RequestErrReadFailure)Error

func (e RequestErrReadFailure) Error()string

func (RequestErrReadFailure)Message

func (e RequestErrReadFailure) Message()string

func (RequestErrReadFailure)String

func (e RequestErrReadFailure) String()string

typeRequestErrReadTimeout

type RequestErrReadTimeout struct {ConsistencyConsistencyReceivedintBlockForintDataPresentbyte// contains filtered or unexported fields}

func (RequestErrReadTimeout)Code

func (e RequestErrReadTimeout) Code()int

func (RequestErrReadTimeout)Error

func (e RequestErrReadTimeout) Error()string

func (RequestErrReadTimeout)Message

func (e RequestErrReadTimeout) Message()string

func (RequestErrReadTimeout)String

func (e RequestErrReadTimeout) String()string

typeRequestErrUnavailable

type RequestErrUnavailable struct {ConsistencyConsistencyRequiredintAliveint// contains filtered or unexported fields}

func (RequestErrUnavailable)Code

func (e RequestErrUnavailable) Code()int

func (RequestErrUnavailable)Error

func (e RequestErrUnavailable) Error()string

func (RequestErrUnavailable)Message

func (e RequestErrUnavailable) Message()string

func (*RequestErrUnavailable)String

func (e *RequestErrUnavailable) String()string

typeRequestErrUnprepared

type RequestErrUnprepared struct {StatementId []byte// contains filtered or unexported fields}

func (RequestErrUnprepared)Code

func (e RequestErrUnprepared) Code()int

func (RequestErrUnprepared)Error

func (e RequestErrUnprepared) Error()string

func (RequestErrUnprepared)Message

func (e RequestErrUnprepared) Message()string

func (RequestErrUnprepared)String

func (e RequestErrUnprepared) String()string

typeRequestErrWriteFailure

type RequestErrWriteFailure struct {ConsistencyConsistencyReceivedintBlockForintNumFailuresintWriteTypestringErrorMapErrorMap// contains filtered or unexported fields}

func (RequestErrWriteFailure)Code

func (e RequestErrWriteFailure) Code()int

func (RequestErrWriteFailure)Error

func (e RequestErrWriteFailure) Error()string

func (RequestErrWriteFailure)Message

func (e RequestErrWriteFailure) Message()string

func (RequestErrWriteFailure)String

func (e RequestErrWriteFailure) String()string

typeRequestErrWriteTimeout

type RequestErrWriteTimeout struct {ConsistencyConsistencyReceivedintBlockForintWriteTypestring// contains filtered or unexported fields}

func (RequestErrWriteTimeout)Code

func (e RequestErrWriteTimeout) Code()int

func (RequestErrWriteTimeout)Error

func (e RequestErrWriteTimeout) Error()string

func (RequestErrWriteTimeout)Message

func (e RequestErrWriteTimeout) Message()string

func (RequestErrWriteTimeout)String

func (e RequestErrWriteTimeout) String()string

typeRequestError

type RequestError interface {Code()intMessage()stringError()string}

typeRetryPolicy

type RetryPolicy interface {Attempt(RetryableQuery)boolGetRetryType(error)RetryType}

RetryPolicy interface is used by gocql to determine if a query can be attemptedagain after a retryable error has been received. The interface allows gocqlusers to implement their own logic to determine if a query can be attemptedagain.

See SimpleRetryPolicy as an example of implementing and using a RetryPolicyinterface.

typeRetryType

type RetryTypeuint16
const (RetryRetryType = 0x00// retry on same connectionRetryNextHostRetryType = 0x01// retry on another connectionIgnoreRetryType = 0x02// ignore error and return resultRethrowRetryType = 0x03// raise error and stop retrying)

typeRetryableQuery

type RetryableQuery interface {Attempts()intSetConsistency(cConsistency)GetConsistency()ConsistencyContext()context.Context}

RetryableQuery is an interface that represents a query or batch statement thatexposes the correct functions for the retry policy logic to evaluate correctly.

typeRowData

type RowData struct {Columns []stringValues  []interface{}}

typeScanner

type Scanner interface {// Next advances the row pointer to point at the next row, the row is valid until// the next call of Next. It returns true if there is a row which is available to be// scanned into with Scan.// Next must be called before every call to Scan.Next()bool// Scan copies the current row's columns into dest. If the length of dest does not equal// the number of columns returned in the row an error is returned. If an error is encountered// when unmarshalling a column into the value in dest an error is returned and the row is invalidated// until the next call to Next.// Next must be called before calling Scan, if it is not an error is returned.Scan(...interface{})error// Err returns the if there was one during iteration that resulted in iteration being unable to complete.// Err will also release resources held by the iterator, the Scanner should not used after being called.Err()error}

typeSelectedHost

type SelectedHost interface {Info() *HostInfoMark(error)}

SelectedHost is an interface returned when picking a host from a hostselection policy.

typeSerialConsistency

type SerialConsistencyuint16
const (SerialSerialConsistency = 0x08LocalSerialSerialConsistency = 0x09)

func (SerialConsistency)MarshalText

func (sSerialConsistency) MarshalText() (text []byte, errerror)

func (SerialConsistency)String

func (sSerialConsistency) String()string

func (*SerialConsistency)UnmarshalText

func (s *SerialConsistency) UnmarshalText(text []byte)error

typeSession

type Session struct {// contains filtered or unexported fields}

Session is the interface used by users to interact with the database.

It's safe for concurrent use by multiple goroutines and a typical usagescenario is to have one global session object to interact with thewhole Cassandra cluster.

This type extends the Node interface by adding a convenient query builderand automatically sets a default consistency level on all operationsthat do not have a consistency level set.

funcNewSession

func NewSession(cfgClusterConfig) (*Session,error)

NewSession wraps an existing Node.

func (*Session)AwaitSchemaAgreement

func (s *Session) AwaitSchemaAgreement(ctxcontext.Context)error

AwaitSchemaAgreement will wait until schema versions across all nodes in thecluster are the same (as seen from the point of view of the control connection).The maximum amount of time this takes is governedby the MaxWaitSchemaAgreement setting in the configuration (default: 60s).AwaitSchemaAgreement returns an error in case schema versions are not the sameafter the timeout specified in MaxWaitSchemaAgreement elapses.

func (*Session)Bind

func (s *Session) Bind(stmtstring, b func(q *QueryInfo) ([]interface{},error)) *Query

Bind generates a new query object based on the query statement passed in.The query is automatically prepared if it has not previously been executed.The binding callback allows the application to define which query argumentvalues will be marshalled as part of the query execution.During execution, the meta data of the prepared query will be routed to thebinding callback, which is responsible for producing the query argument values.

func (*Session)Close

func (s *Session) Close()

Close closes all connections. The session is unusable after thisoperation.

func (*Session)Closed

func (s *Session) Closed()bool

func (*Session)ExecuteBatch

func (s *Session) ExecuteBatch(batch *Batch)error

ExecuteBatch executes a batch operation and returns nil if successfulotherwise an error is returned describing the failure.

func (*Session)ExecuteBatchCAS

func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (appliedbool, iter *Iter, errerror)

ExecuteBatchCAS executes a batch operation and returns true if successful andan iterator (to scan additional rows if more than one conditional statement)was sent.Further scans on the interator must also remember to includethe applied boolean as the first argument to *Iter.Scan

func (*Session)KeyspaceMetadata

func (s *Session) KeyspaceMetadata(keyspacestring) (*KeyspaceMetadata,error)

KeyspaceMetadata returns the schema metadata for the keyspace specified. Returns an error if the keyspace does not exist.

func (*Session)MapExecuteBatchCAS

func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (appliedbool, iter *Iter, errerror)

MapExecuteBatchCAS executes a batch operation much like ExecuteBatchCAS,however it accepts a map rather than a list of arguments for the initialscan.

Example

ExampleSession_MapExecuteBatchCAS demonstrates how to execute a batch lightweight transaction.

package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create table example.my_lwt_batch_table(pk text, ck text, version int, value text, PRIMARY KEY(pk, ck));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()err = session.Query("INSERT INTO example.my_lwt_batch_table (pk, ck, version, value) VALUES (?, ?, ?, ?)","pk1", "ck1", 1, "a").WithContext(ctx).Exec()if err != nil {log.Fatal(err)}err = session.Query("INSERT INTO example.my_lwt_batch_table (pk, ck, version, value) VALUES (?, ?, ?, ?)","pk1", "ck2", 1, "A").WithContext(ctx).Exec()if err != nil {log.Fatal(err)}executeBatch := func(ck2Version int) {b := session.NewBatch(gocql.LoggedBatch)b.Entries = append(b.Entries, gocql.BatchEntry{Stmt: "UPDATE my_lwt_batch_table SET value=? WHERE pk=? AND ck=? IF version=?",Args: []interface{}{"b", "pk1", "ck1", 1},})b.Entries = append(b.Entries, gocql.BatchEntry{Stmt: "UPDATE my_lwt_batch_table SET value=? WHERE pk=? AND ck=? IF version=?",Args: []interface{}{"B", "pk1", "ck2", ck2Version},})m := make(map[string]interface{})applied, iter, err := session.MapExecuteBatchCAS(b.WithContext(ctx), m)if err != nil {log.Fatal(err)}fmt.Println(applied, m)m = make(map[string]interface{})for iter.MapScan(m) {fmt.Println(m)m = make(map[string]interface{})}if err := iter.Close(); err != nil {log.Fatal(err)}}printState := func() {scanner := session.Query("SELECT ck, value FROM example.my_lwt_batch_table WHERE pk = ?", "pk1").WithContext(ctx).Iter().Scanner()for scanner.Next() {var ck, value stringerr = scanner.Scan(&ck, &value)if err != nil {log.Fatal(err)}fmt.Println(ck, value)}if err := scanner.Err(); err != nil {log.Fatal(err)}}executeBatch(0)printState()executeBatch(1)printState()// false map[ck:ck1 pk:pk1 version:1]// map[[applied]:false ck:ck2 pk:pk1 version:1]// ck1 a// ck2 A// true map[]// ck1 b// ck2 B}
Output:

func (*Session)NewBatch

func (s *Session) NewBatch(typBatchType) *Batch

NewBatch creates a new batch operation using defaults defined in the cluster

func (*Session)Query

func (s *Session) Query(stmtstring, values ...interface{}) *Query

Query generates a new query object for interacting with the database.Further details of the query may be tweaked using the resulting queryvalue before the query is executed. Query is automatically preparedif it has not previously been executed.

func (*Session)SetConsistency

func (s *Session) SetConsistency(consConsistency)

SetConsistency sets the default consistency level for this session. Thissetting can also be changed on a per-query basis and the default valueis Quorum.

func (*Session)SetPageSize

func (s *Session) SetPageSize(nint)

SetPageSize sets the default page size for this session. A value <= 0 willdisable paging. This setting can also be changed on a per-query basis.

func (*Session)SetPrefetch

func (s *Session) SetPrefetch(pfloat64)

SetPrefetch sets the default threshold for pre-fetching new pages. Ifthere are only p*pageSize rows remaining, the next page will be requestedautomatically. This value can also be changed on a per-query basis andthe default value is 0.25.

func (*Session)SetTrace

func (s *Session) SetTrace(traceTracer)

SetTrace sets the default tracer for this session. This setting can alsobe changed on a per-query basis.

typeSetHosts

type SetHosts interface {SetHosts(hosts []*HostInfo)}

interface to implement to receive the host information

typeSetPartitioner

type SetPartitioner interface {SetPartitioner(partitionerstring)}

interface to implement to receive the partitioner value

typeSimpleConvictionPolicy

type SimpleConvictionPolicy struct {}

SimpleConvictionPolicy implements a ConvictionPolicy which convicts all hostsregardless of error

func (*SimpleConvictionPolicy)AddFailure

func (e *SimpleConvictionPolicy) AddFailure(errorerror, host *HostInfo)bool

func (*SimpleConvictionPolicy)Reset

func (e *SimpleConvictionPolicy) Reset(host *HostInfo)

typeSimpleRetryPolicy

type SimpleRetryPolicy struct {NumRetriesint//Number of times to retry a query}

SimpleRetryPolicy has simple logic for attempting a query a fixed number of times.

See below for examples of usage:

//Assign to the clustercluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}//Assign to a queryquery.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})

func (*SimpleRetryPolicy)Attempt

Attempt tells gocql to attempt the query again based on query.Attempts being lessthan the NumRetries defined in the policy.

func (*SimpleRetryPolicy)GetRetryType

func (s *SimpleRetryPolicy) GetRetryType(errerror)RetryType

typeSimpleSpeculativeExecution

type SimpleSpeculativeExecution struct {NumAttemptsintTimeoutDelaytime.Duration}

func (*SimpleSpeculativeExecution)Attempts

func (sp *SimpleSpeculativeExecution) Attempts()int

func (*SimpleSpeculativeExecution)Delay

typeSnappyCompressor

type SnappyCompressor struct{}

SnappyCompressor implements the Compressor interface and can be used tocompress incoming and outgoing frames. The snappy compression algorithmaims for very high speeds and reasonable compression.

func (SnappyCompressor)Decode

func (sSnappyCompressor) Decode(data []byte) ([]byte,error)

func (SnappyCompressor)Encode

func (sSnappyCompressor) Encode(data []byte) ([]byte,error)

func (SnappyCompressor)Name

func (sSnappyCompressor) Name()string

typeSpeculativeExecutionPolicy

type SpeculativeExecutionPolicy interface {Attempts()intDelay()time.Duration}

typeSslOptions

type SslOptions struct {*tls.Config// CertPath and KeyPath are optional depending on server// config, but both fields must be omitted to avoid using a// client certificateCertPathstringKeyPathstringCaPathstring//optional depending on server config// If you want to verify the hostname and server cert (like a wildcard for cass cluster) then you should turn this// on.// This option is basically the inverse of tls.Config.InsecureSkipVerify.// See InsecureSkipVerify inhttp://golang.org/pkg/crypto/tls/ for more info.//// See SslOptions documentation to see how EnableHostVerification interacts with the provided tls.Config.EnableHostVerificationbool}

SslOptions configures TLS use.

Warning: Due to historical reasons, the SslOptions is insecure by default, so you need to set EnableHostVerificationto true if no Config is set. Most users should set SslOptions.Config to a *tls.Config.SslOptions and Config.InsecureSkipVerify interact as follows:

Config.InsecureSkipVerify | EnableHostVerification | ResultConfig is nil             | false                  | do not verify hostConfig is nil             | true                   | verify hostfalse                     | false                  | verify hosttrue                      | false                  | do not verify hostfalse                     | true                   | verify hosttrue                      | true                   | verify host

typeStdLogger

type StdLogger interface {Print(v ...interface{})Printf(formatstring, v ...interface{})Println(v ...interface{})}
var LoggerStdLogger = &defaultLogger{}

Logger for logging messages.Deprecated: Use ClusterConfig.Logger instead.

typeStreamObserveradded inv1.1.0

type StreamObserver interface {// StreamContext is called before creating a new stream.// ctx is context passed to Session.Query / Session.Batch,// but might also be an internal context (for example// for internal requests that use control connection).// StreamContext might return nil if it is not interested// in the details of this stream.// StreamContext is called before the stream is created// and the returned StreamObserverContext might be discarded// without any methods called on the StreamObserverContext if// creation of the stream fails.// Note that if you don't need to track per-stream data,// you can always return the same StreamObserverContext.StreamContext(ctxcontext.Context)StreamObserverContext}

StreamObserver is notified about request/response pairs.Streams are created for executing queries/batches orinternal requests to the database and might live longer thanexecution of the query - the stream is still tracked untilresponse arrives so that stream IDs are not reused.

typeStreamObserverContextadded inv1.1.0

type StreamObserverContext interface {// StreamStarted is called when the stream is started.// This happens just before a request is written to the wire.StreamStarted(observedStreamObservedStream)// StreamAbandoned is called when we stop waiting for response.// This happens when the underlying network connection is closed.// StreamFinished won't be called if StreamAbandoned is.StreamAbandoned(observedStreamObservedStream)// StreamFinished is called when we receive a response for the stream.StreamFinished(observedStreamObservedStream)}

StreamObserverContext is notified about state of a stream.A stream is started every time a request is written to the serverand is finished when a response is received.It is abandoned when the underlying network connection is closedbefore receiving a response.

typeTableMetadata

type TableMetadata struct {KeyspacestringNamestringKeyValidatorstringComparatorstringDefaultValidatorstringKeyAliases        []stringColumnAliases     []stringValueAliasstringPartitionKey      []*ColumnMetadataClusteringColumns []*ColumnMetadataColumns           map[string]*ColumnMetadataOrderedColumns    []string}

schema metadata for a table (a.k.a. column family)

typeTracer

type Tracer interface {Trace(traceId []byte)}

Tracer is the interface implemented by query tracers. Tracers have theability to obtain a detailed event log of all events that happened duringthe execution of a query from Cassandra. Gathering this information mightbe essential for debugging and optimizing queries, but this feature shouldnot be used on production systems with very high load.

funcNewTraceWriter

func NewTraceWriter(session *Session, wio.Writer)Tracer

NewTraceWriter returns a simple Tracer implementation that outputsthe event log in a textual format.

typeTupleTypeInfo

type TupleTypeInfo struct {NativeTypeElems []TypeInfo}

func (TupleTypeInfo)New

func (tTupleTypeInfo) New() interface{}

func (TupleTypeInfo)NewWithErroradded inv1.1.0

func (tTupleTypeInfo) NewWithError() (interface{},error)

func (TupleTypeInfo)String

func (tTupleTypeInfo) String()string

typeType

type Typeint

String returns a human readable name for the Cassandra datatypedescribed by t.Type is the identifier of a Cassandra internal datatype.

const (TypeCustomType = 0x0000TypeAsciiType = 0x0001TypeBigIntType = 0x0002TypeBlobType = 0x0003TypeBooleanType = 0x0004TypeCounterType = 0x0005TypeDecimalType = 0x0006TypeDoubleType = 0x0007TypeFloatType = 0x0008TypeIntType = 0x0009TypeTextType = 0x000ATypeTimestampType = 0x000BTypeUUIDType = 0x000CTypeVarcharType = 0x000DTypeVarintType = 0x000ETypeTimeUUIDType = 0x000FTypeInetType = 0x0010TypeDateType = 0x0011TypeTimeType = 0x0012TypeSmallIntType = 0x0013TypeTinyIntType = 0x0014TypeDurationType = 0x0015TypeListType = 0x0020TypeMapType = 0x0021TypeSetType = 0x0022TypeUDTType = 0x0030TypeTupleType = 0x0031)

func (Type)String

func (tType) String()string

String returns the name of the identifier.

typeTypeInfo

type TypeInfo interface {Type()TypeVersion()byteCustom()string// New creates a pointer to an empty version of whatever type// is referenced by the TypeInfo receiver.//// If there is no corresponding Go type for the CQL type, New panics.//// Deprecated: Use NewWithError instead.New() interface{}// NewWithError creates a pointer to an empty version of whatever type// is referenced by the TypeInfo receiver.//// If there is no corresponding Go type for the CQL type, NewWithError returns an error.NewWithError() (interface{},error)}

TypeInfo describes a Cassandra specific data type.

typeUDTField

type UDTField struct {NamestringTypeTypeInfo}

typeUDTMarshaler

type UDTMarshaler interface {// MarshalUDT will be called for each field in the the UDT returned by Cassandra,// the implementor should marshal the type to return by for example calling// Marshal.MarshalUDT(namestring, infoTypeInfo) ([]byte,error)}

UDTMarshaler is an interface which should be implemented by users wishing tohandle encoding UDT types to sent to Cassandra. Note: due to current implentationsmethods defined for this interface must be value receivers not pointer receivers.

Example

ExampleUDTMarshaler demonstrates how to implement a UDTMarshaler.

/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* * Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40 * Copyright (c) 2016, The Gocql authors, * provided under the BSD-3-Clause License. * See the NOTICE file distributed with this work for additional information. */package mainimport ("context""log"gocql "github.com/gocql/gocql")// MyUDTMarshaler implements UDTMarshaler.type MyUDTMarshaler struct {fieldA stringfieldB int32}// MarshalUDT marshals the selected field to bytes.func (m MyUDTMarshaler) MarshalUDT(name string, info gocql.TypeInfo) ([]byte, error) {switch name {case "field_a":return gocql.Marshal(info, m.fieldA)case "field_b":return gocql.Marshal(info, m.fieldB)default:// If you want to be strict and return error un unknown field, you can do so here instead.// Returning nil, nil will set the value of unknown fields to null, which might be handy if you want// to be forward-compatible when a new field is added to the UDT.return nil, nil}}// ExampleUDTMarshaler demonstrates how to implement a UDTMarshaler.func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create type example.my_udt (field_a text, field_b int);create table example.my_udt_table(pk int, value frozen<my_udt>, PRIMARY KEY(pk));*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()value := MyUDTMarshaler{fieldA: "a value",fieldB: 42,}err = session.Query("INSERT INTO example.my_udt_table (pk, value) VALUES (?, ?)",1, value).WithContext(ctx).Exec()if err != nil {log.Fatal(err)}}
Output:

typeUDTTypeInfo

type UDTTypeInfo struct {NativeTypeKeySpacestringNamestringElements []UDTField}

func (UDTTypeInfo)New

func (uUDTTypeInfo) New() interface{}

func (UDTTypeInfo)NewWithErroradded inv1.1.0

func (uUDTTypeInfo) NewWithError() (interface{},error)

func (UDTTypeInfo)String

func (uUDTTypeInfo) String()string

typeUDTUnmarshaler

type UDTUnmarshaler interface {// UnmarshalUDT will be called for each field in the UDT return by Cassandra,// the implementor should unmarshal the data into the value of their chosing,// for example by calling Unmarshal.UnmarshalUDT(namestring, infoTypeInfo, data []byte)error}

UDTUnmarshaler should be implemented by users wanting to implement customUDT unmarshaling.

Example

ExampleUDTUnmarshaler demonstrates how to implement a UDTUnmarshaler.

/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* * Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40 * Copyright (c) 2016, The Gocql authors, * provided under the BSD-3-Clause License. * See the NOTICE file distributed with this work for additional information. */package mainimport ("context""fmt""log"gocql "github.com/gocql/gocql")// MyUDTUnmarshaler implements UDTUnmarshaler.type MyUDTUnmarshaler struct {fieldA stringfieldB int32}// UnmarshalUDT unmarshals the field identified by name into MyUDTUnmarshaler.func (m *MyUDTUnmarshaler) UnmarshalUDT(name string, info gocql.TypeInfo, data []byte) error {switch name {case "field_a":return gocql.Unmarshal(info, data, &m.fieldA)case "field_b":return gocql.Unmarshal(info, data, &m.fieldB)default:// If you want to be strict and return error un unknown field, you can do so here instead.// Returning nil will ignore unknown fields, which might be handy if you want// to be forward-compatible when a new field is added to the UDT.return nil}}// ExampleUDTUnmarshaler demonstrates how to implement a UDTUnmarshaler.func main() {/* The example assumes the following CQL was used to setup the keyspace:create keyspace example with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };create type example.my_udt (field_a text, field_b int);create table example.my_udt_table(pk int, value frozen<my_udt>, PRIMARY KEY(pk));insert into example.my_udt_table (pk, value) values (1, {field_a: 'a value', field_b: 42});*/cluster := gocql.NewCluster("localhost:9042")cluster.Keyspace = "example"cluster.ProtoVersion = 4session, err := cluster.CreateSession()if err != nil {log.Fatal(err)}defer session.Close()ctx := context.Background()var value MyUDTUnmarshalererr = session.Query("SELECT value FROM example.my_udt_table WHERE pk = 1").WithContext(ctx).Scan(&value)if err != nil {log.Fatal(err)}fmt.Println(value.fieldA)fmt.Println(value.fieldB)// a value// 42}
Output:

typeUUID

type UUID [16]byte

funcMaxTimeUUID

func MaxTimeUUID(ttime.Time)UUID

MaxTimeUUID generates a "fake" time based UUID (version 1) which will bethe biggest possible UUID generated for the provided timestamp.

UUIDs generated by this function are not unique and are mostly suitable onlyin queries to select a time range of a Cassandra's TimeUUID column.

funcMinTimeUUID

func MinTimeUUID(ttime.Time)UUID

MinTimeUUID generates a "fake" time based UUID (version 1) which will bethe smallest possible UUID generated for the provided timestamp.

UUIDs generated by this function are not unique and are mostly suitable onlyin queries to select a time range of a Cassandra's TimeUUID column.

funcMustRandomUUIDadded inv1.2.0

func MustRandomUUID()UUID

funcParseUUID

func ParseUUID(inputstring) (UUID,error)

ParseUUID parses a 32 digit hexadecimal number (that might contain hypens)representing an UUID.

funcRandomUUID

func RandomUUID() (UUID,error)

RandomUUID generates a totally random UUID (version 4) as described inRFC 4122.

funcTimeUUID

func TimeUUID()UUID

TimeUUID generates a new time based UUID (version 1) using the currenttime as the timestamp.

funcTimeUUIDWith

func TimeUUIDWith(tint64, clockuint32, node []byte)UUID

TimeUUIDWith generates a new time based UUID (version 1) as described inRFC4122 with given parameters. t is the number of 100's of nanosecondssince 15 Oct 1582 (60bits). clock is the number of clock sequence (14bits).node is a slice to gurarantee the uniqueness of the UUID (up to 6bytes).Note: calling this function does not increment the static clock sequence.

funcUUIDFromBytes

func UUIDFromBytes(input []byte) (UUID,error)

UUIDFromBytes converts a raw byte slice to an UUID.

funcUUIDFromTime

func UUIDFromTime(ttime.Time)UUID

UUIDFromTime generates a new time based UUID (version 1) as described inRFC 4122. This UUID contains the MAC address of the node that generatedthe UUID, the given timestamp and a sequence number.

func (UUID)Bytes

func (uUUID) Bytes() []byte

Bytes returns the raw byte slice for this UUID. A UUID is always 128 bits(16 bytes) long.

func (UUID)Clock

func (uUUID) Clock()uint32

Clock extracts the clock sequence of this UUID. It will return zero if theUUID is not a time based UUID (version 1).

func (UUID)MarshalJSON

func (uUUID) MarshalJSON() ([]byte,error)

Marshaling for JSON

func (UUID)MarshalText

func (uUUID) MarshalText() ([]byte,error)

func (UUID)Node

func (uUUID) Node() []byte

Node extracts the MAC address of the node who generated this UUID. It willreturn nil if the UUID is not a time based UUID (version 1).

func (UUID)String

func (uUUID) String()string

String returns the UUID in it's canonical form, a 32 digit hexadecimalnumber in the form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.

func (UUID)Time

func (uUUID) Time()time.Time

Time is like Timestamp, except that it returns a time.Time.

func (UUID)Timestamp

func (uUUID) Timestamp()int64

Timestamp extracts the timestamp information from a time based UUID(version 1).

func (*UUID)UnmarshalJSON

func (u *UUID) UnmarshalJSON(data []byte)error

Unmarshaling for JSON

func (*UUID)UnmarshalText

func (u *UUID) UnmarshalText(text []byte) (errerror)

func (UUID)Variant

func (uUUID) Variant()int

Variant returns the variant of this UUID. This package will only generateUUIDs in the IETF variant.

func (UUID)Version

func (uUUID) Version()int

Version extracts the version of this UUID variant. TheRFC 4122 describesfive kinds of UUIDs.

typeUnmarshalError

type UnmarshalErrorstring

func (UnmarshalError)Error

func (mUnmarshalError) Error()string

typeUnmarshaler

type Unmarshaler interface {UnmarshalCQL(infoTypeInfo, data []byte)error}

Unmarshaler is the interface implemented by objects that can unmarshala Cassandra specific description of themselves.

typeUserTypeMetadata

type UserTypeMetadata struct {KeyspacestringNamestringFieldNames []stringFieldTypes []TypeInfo}

typeViewMetadata

type ViewMetadata struct {KeyspacestringNamestringFieldNames []stringFieldTypes []TypeInfo}

ViewMetadata holds the metadata for views.Deprecated: this is kept for backwards compatibility issues. Use MaterializedViewMetadata.

Source Files

View all Source files

Directories

PathSynopsis
internal
lz4module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp