gocql

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2015 License: BSD-3-Clause, MPL-2.0 Imports: 31 Imported by: 0

README

gocql

Build Status GoDoc

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

Project Website: http://gocql.github.io/
API documentation: http://godoc.org/github.com/gocql/gocql
Discussions: https://groups.google.com/forum/#!forum/gocql

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/Cassandra 1.2.x 2.0.x 2.1.x
1.4 yes yes yes
1.5 yes yes yes

Sunsetting Model

In general, the gocql team will focus on supporting the current and previous versions of Golang. gocql may still work with older versions of Golang, but offical 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 conversations between Cassandra and Go
    • Support for all common types including sets, lists and maps
    • Custom types can implement a Marshaler and Unmarshaler interface
    • Strict type conversations 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
    • Optional support for periodic node discovery via system.peers
    • 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
  • An API to access the schema metadata of a given keyspace

Please visit the Roadmap page to see what is on the horizion.

Important Default Keyspace Changes

gocql no longer supports executing "use " statements to simplfy the library. The user still has the ability to define the default keyspace for connections but now the keyspace can only be defined before a session 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

/* Before you execute the program, Launch `cqlsh` and execute:
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);
*/
package main

import (
	"fmt"
	"log"

	"github.com/gocql/gocql"
)

func main() {
	// connect to the cluster
	cluster := gocql.NewCluster("192.168.1.1", "192.168.1.2", "192.168.1.3")
	cluster.Keyspace = "example"
	cluster.Consistency = gocql.Quorum
	session, _ := cluster.CreateSession()
	defer session.Close()

	// insert a tweet
	if err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,
		"me", gocql.TimeUUID(), "hello world").Exec(); err != nil {
		log.Fatal(err)
	}

	var id gocql.UUID
	var 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").Consistency(gocql.One).Scan(&id, &text); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Tweet:", id, text)

	// list all tweets
	iter := session.Query(`SELECT id, text FROM tweet WHERE timeline = ?`, "me").Iter()
	for iter.Scan(&id, &text) {
		fmt.Println("Tweet:", id, text)
	}
	if err := iter.Close(); err != nil {
		log.Fatal(err)
	}
}

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 the SliceMap() API. This returns a slice of row maps keyed by CQL column mames. 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 the SliceMap() API you can also call MapScan() which returns map[string]interface{} instances in a row by row fashion.
  • The Bind() 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.
  • 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 is cqlc 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.

Ecosphere

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

  • migrate is a migration handling tool written in Go 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 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 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 whilst working the library.

Other Projects

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

SEO

For some reason, when you google golang cassandra, this project doesn't feature very highly in the result list. But if you google go 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.

License

Copyright (c) 2012-2015 The gocql Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

Documentation

Overview

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

Copyright (c) 2012 The gocql Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. This file will be the future home for more policies

The uuid package can be used to generate and parse universally unique identifiers, a standardized format in the form of a 128 bit number.

http://tools.ietf.org/html/rfc4122

Index

Constants

View Source
const (
	PARTITION_KEY  = "partition_key"
	CLUSTERING_KEY = "clustering_key"
	REGULAR        = "regular"
	COMPACT_VALUE  = "compact_value"
)

Column kind values

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 (
	LoggedBatch   BatchType = 0
	UnloggedBatch           = 1
	CounterBatch            = 2
)
View Source
const (
	VariantNCSCompat = 0
	VariantIETF      = 2
	VariantMicrosoft = 6
	VariantFuture    = 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")
)
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/gocql/gocql for explaination.")
	ErrSessionClosed = errors.New("session has been closed")
	ErrNoConnections = errors.New("no connections available")
	ErrNoKeyspace    = errors.New("no keyspace provided")
	ErrNoMetadata    = errors.New("no metadata available")
)
View Source
var (
	ErrFrameTooBig = errors.New("frame length is bigger than the maximum alowed")
)
View Source
var (
	ErrorUDTUnavailable = errors.New("UDT are not available on protocols less than 3, please update config")
)
View Source
var TimeoutLimit int64 = 10

How many timeouts we will allow to occur before the connection is closed and restarted. This is to prevent a single query timeout from killing a connection which may be serving more queries just fine. Default is 10, should not be changed concurrently with queries.

Functions

func JoinHostPort

func JoinHostPort(addr string, port int) string

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

func Marshal

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

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

func NewErrProtocol

func NewErrProtocol(format string, args ...interface{}) error

func Unmarshal

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

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

Types

type Authenticator

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

type Batch

type Batch struct {
	Type    BatchType
	Entries []BatchEntry
	Cons    Consistency
	// contains filtered or unexported fields
}

func NewBatch

func NewBatch(typ BatchType) *Batch

NewBatch creates a new batch operation without defaults from the cluster

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(stmt string, bind func(q *QueryInfo) ([]interface{}, error))

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

func (*Batch) DefaultTimestamp

func (b *Batch) DefaultTimestamp(enable bool) *Batch

DefaultTimestamp will enable the with default timestamp flag on the query. If enable, this will replace the server side assigned timestamp as default timestamp. Note that a timestamp in the query itself will 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 batch operation.

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) Query

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

Query adds the query to the batch operation

func (*Batch) RetryPolicy

func (b *Batch) RetryPolicy(r RetryPolicy) *Batch

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

func (*Batch) SerialConsistency

func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch

SerialConsistency sets the consistencyc level for the serial phase of conditional updates. That consitency can only be either SERIAL or LOCAL_SERIAL and if not present, it defaults to SERIAL. This option will be ignored for anything else that a conditional update/insert.

Only available for protocol 3 and above

func (*Batch) Size

func (b *Batch) Size() int

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

type BatchEntry

type BatchEntry struct {
	Stmt string
	Args []interface{}
	// contains filtered or unexported fields
}

type BatchType

type BatchType byte

type ClusterConfig

type ClusterConfig struct {
	Hosts             []string          // addresses for the initial connections
	CQLVersion        string            // CQL version (default: 3.0.0)
	ProtoVersion      int               // version of the native protocol (default: 2)
	Timeout           time.Duration     // connection timeout (default: 600ms)
	Port              int               // port (default: 9042)
	Keyspace          string            // initial keyspace (optional)
	NumConns          int               // number of connections per host (default: 2)
	NumStreams        int               // number of streams per connection (default: max per protocol, either 128 or 32768)
	Consistency       Consistency       // default consistency level (default: Quorum)
	Compressor        Compressor        // compression algorithm (default: nil)
	Authenticator     Authenticator     // authenticator (default: nil)
	RetryPolicy       RetryPolicy       // Default retry policy to use for queries (default: 0)
	SocketKeepalive   time.Duration     // The keepalive period to use, enabled if > 0 (default: 0)
	ConnPoolType      NewPoolFunc       // The function used to create the connection pool for the session (default: NewSimplePool)
	DiscoverHosts     bool              // If set, gocql will attempt to automatically discover other members of the Cassandra cluster (default: false)
	MaxPreparedStmts  int               // Sets the maximum cache size for prepared statements globally for gocql (default: 1000)
	MaxRoutingKeyInfo int               // Sets the maximum cache size for query info about statements for each session (default: 1000)
	PageSize          int               // Default page size to use for created sessions (default: 5000)
	SerialConsistency SerialConsistency // Sets the consistency for the serial part of queries, values can be either SERIAL or LOCAL_SERIAL (default: unset)
	Discovery         DiscoveryConfig
	SslOpts           *SslOptions
	DefaultTimestamp  bool // 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)
}

ClusterConfig is a struct to configure the default cluster implementation of gocoql. It has a varity of attributes that can be used to modify the behavior to fit the most common use cases. Applications that requre a different setup must implement their own cluster.

func NewCluster

func NewCluster(hosts ...string) *ClusterConfig

NewCluster generates a new config for the default cluster implementation.

func (*ClusterConfig) CreateSession

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

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

type CollectionType

type CollectionType struct {
	NativeType
	Key  TypeInfo // only used for TypeMap
	Elem TypeInfo // only used for TypeMap, TypeList and TypeSet
}

func (CollectionType) New

func (t CollectionType) New() interface{}

func (CollectionType) String

func (c CollectionType) String() string

type ColumnIndexMetadata

type ColumnIndexMetadata struct {
	Name    string
	Type    string
	Options map[string]interface{}
}

type ColumnInfo

type ColumnInfo struct {
	Keyspace string
	Table    string
	Name     string
	TypeInfo TypeInfo
}

func (ColumnInfo) String

func (c ColumnInfo) String() string

type ColumnMetadata

type ColumnMetadata struct {
	Keyspace       string
	Table          string
	Name           string
	ComponentIndex int
	Kind           string
	Validator      string
	Type           TypeInfo
	Order          ColumnOrder
	Index          ColumnIndexMetadata
}

schema metadata for a column

type ColumnOrder

type ColumnOrder bool

the ordering of the column with regard to its comparator

const (
	ASC  ColumnOrder = false
	DESC             = true
)

type Compressor

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

type Conn

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

Conn is a single connection to a Cassandra node. It can be used to execute queries, but users are usually advised to use a more reliable, higher level API.

func Connect

func Connect(addr string, cfg ConnConfig, errorHandler ConnErrorHandler) (*Conn, error)

Connect establishes a connection to a Cassandra node. You must also call the Serve method before you can execute any queries.

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) (n int, err error)

func (*Conn) UseKeyspace

func (c *Conn) UseKeyspace(keyspace string) error

func (*Conn) Write

func (c *Conn) Write(p []byte) (int, error)

type ConnConfig

type ConnConfig struct {
	ProtoVersion  int
	CQLVersion    string
	Timeout       time.Duration
	NumStreams    int
	Compressor    Compressor
	Authenticator Authenticator
	Keepalive     time.Duration
	// contains filtered or unexported fields
}

type ConnErrorHandler

type ConnErrorHandler interface {
	HandleError(conn *Conn, err error, closed bool)
}

type ConnSelectionPolicy

type ConnSelectionPolicy interface {
	SetConns(conns []*Conn)
	Pick(*Query) *Conn
}

ConnSelectionPolicy is an interface for selecting an appropriate connection for executing a query

func NewRoundRobinConnPolicy

func NewRoundRobinConnPolicy() ConnSelectionPolicy

type ConnectionPool

type ConnectionPool interface {
	SetHosts
	Pick(*Query) *Conn
	Size() int
	Close()
}

ConnectionPool represents the interface gocql will use to work with a collection of connections.

Purpose

The connection pool in gocql opens and closes connections as well as selects an available connection for gocql to execute a query against. The pool is also responsible for handling connection errors that are caught by the connection experiencing the error.

A connection pool should make a copy of the variables used from the ClusterConfig provided to the pool upon creation. ClusterConfig is a pointer and can be modified after the creation of the pool. This can lead to issues with variables being modified outside the expectations of the ConnectionPool type.

Example of Single Connection Pool:

type SingleConnection struct {
	conn *Conn
	cfg *ClusterConfig
}

func NewSingleConnection(cfg *ClusterConfig) ConnectionPool {
	addr := JoinHostPort(cfg.Hosts[0], cfg.Port)

	connCfg := ConnConfig{
		ProtoVersion:  cfg.ProtoVersion,
		CQLVersion:    cfg.CQLVersion,
		Timeout:       cfg.Timeout,
		NumStreams:    cfg.NumStreams,
		Compressor:    cfg.Compressor,
		Authenticator: cfg.Authenticator,
		Keepalive:     cfg.SocketKeepalive,
	}
	pool := SingleConnection{cfg:cfg}
	pool.conn = Connect(addr,connCfg,pool)
	return &pool
}

func (s *SingleConnection) HandleError(conn *Conn, err error, closed bool) {
	if closed {
		connCfg := ConnConfig{
			ProtoVersion:  cfg.ProtoVersion,
			CQLVersion:    cfg.CQLVersion,
			Timeout:       cfg.Timeout,
			NumStreams:    cfg.NumStreams,
			Compressor:    cfg.Compressor,
			Authenticator: cfg.Authenticator,
			Keepalive:     cfg.SocketKeepalive,
		}
		s.conn = Connect(conn.Address(),connCfg,s)
	}
}

func (s *SingleConnection) Pick(qry *Query) *Conn {
	if s.conn.isClosed {
		return nil
	}
	return s.conn
}

func (s *SingleConnection) Size() int {
	return 1
}

func (s *SingleConnection) Close() {
	s.conn.Close()
}

This is a very simple example of a type that exposes the connection pool interface. To assign this type as the connection pool to use you would assign it to the ClusterConfig like so:

cluster := NewCluster("127.0.0.1")
cluster.ConnPoolType = NewSingleConnection
...
session, err := cluster.CreateSession()

To see a more complete example of a ConnectionPool implementation please see the SimplePool type.

func NewPolicyConnPool

func NewPolicyConnPool(
	cfg *ClusterConfig,
	hostPolicy HostSelectionPolicy,
	connPolicy func() ConnSelectionPolicy,
) (ConnectionPool, error)

Creates a policy based connection pool. This func isn't meant to be directly used as a NewPoolFunc in ClusterConfig, instead a func should be created which satisfies the NewPoolFunc type, which calls this func with the desired hostPolicy and connPolicy; see NewRoundRobinConnPool or NewTokenAwareConnPool for examples.

func NewRoundRobinConnPool

func NewRoundRobinConnPool(cfg *ClusterConfig) (ConnectionPool, error)

NewRoundRobinConnPool creates a connection pool which selects hosts by round-robin, and then selects a connection for that host by round-robin.

func NewSimplePool

func NewSimplePool(cfg *ClusterConfig) (ConnectionPool, error)

NewSimplePool is the function used by gocql to create the simple connection pool. This is the default if no other pool type is specified.

func NewTokenAwareConnPool

func NewTokenAwareConnPool(cfg *ClusterConfig) (ConnectionPool, error)

NewTokenAwareConnPool creates a connection pool which selects hosts by a token aware policy, and then selects a connection for that host by round-robin.

type Consistency

type Consistency uint16
const (
	Any         Consistency = 0x00
	One         Consistency = 0x01
	Two         Consistency = 0x02
	Three       Consistency = 0x03
	Quorum      Consistency = 0x04
	All         Consistency = 0x05
	LocalQuorum Consistency = 0x06
	EachQuorum  Consistency = 0x07
	LocalOne    Consistency = 0x0A
)

func (Consistency) String

func (c Consistency) String() string

type DiscoveryConfig

type DiscoveryConfig struct {
	// If not empty will filter all discoverred hosts to a single Data Centre (default: "")
	DcFilter string
	// If not empty will filter all discoverred hosts to a single Rack (default: "")
	RackFilter string
	// The interval to check for new hosts (default: 30s)
	Sleep time.Duration
}

To enable periodic node discovery enable DiscoverHosts in ClusterConfig

type ErrProtocol

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

type Error

type Error struct {
	Code    int
	Message string
}

func (Error) Error

func (e Error) Error() string

type HostInfo

type HostInfo struct {
	Peer       string
	DataCenter string
	Rack       string
	HostId     string
	Tokens     []string
}

type HostSelectionPolicy

type HostSelectionPolicy interface {
	SetHosts
	SetPartitioner
	//Pick returns an iteration function over selected hosts
	Pick(*Query) NextHost
}

HostSelectionPolicy is an interface for selecting the most appropriate host to execute a given query.

func NewRoundRobinHostPolicy

func NewRoundRobinHostPolicy() HostSelectionPolicy

NewRoundRobinHostPolicy is a round-robin load balancing policy

func NewTokenAwareHostPolicy

func NewTokenAwareHostPolicy(fallback HostSelectionPolicy) HostSelectionPolicy

NewTokenAwareHostPolicy is a token aware host selection policy

type Iter

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

Iter represents an iterator that can be used to iterate over all rows that were returned by a query. The iterator might send additional queries to the database 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 during the query or the iteration.

func (*Iter) Columns

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

Columns returns the name and type of the selected columns.

func (*Iter) MapScan

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

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

func (*Iter) PageState added in v0.3.0

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

PageState return the current paging state for a query which can be used for subsequent quries 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 the current row into the values pointed at by dest. Use nil as a dest value to skip the corresponding column. Scan might send additional queries to 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 the end of the result set was reached or if an error occurred. Close should be called afterwards to retrieve any potential errors.

func (*Iter) SliceMap

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

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

type KeyspaceMetadata

type KeyspaceMetadata struct {
	Name            string
	DurableWrites   bool
	StrategyClass   string
	StrategyOptions map[string]interface{}
	Tables          map[string]*TableMetadata
}

schema metadata for a keyspace

type MarshalError

type MarshalError string

func (MarshalError) Error

func (m MarshalError) Error() string

type Marshaler

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

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

type NativeType

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

func (NativeType) Custom

func (s NativeType) Custom() string

func (NativeType) New

func (t NativeType) New() interface{}

func (NativeType) String

func (s NativeType) String() string

func (NativeType) Type

func (s NativeType) Type() Type

func (NativeType) Version

func (s NativeType) Version() byte

type NewPoolFunc

type NewPoolFunc func(*ClusterConfig) (ConnectionPool, error)

NewPoolFunc is the type used by ClusterConfig to create a pool of a specific type.

type NextHost

type NextHost func() *HostInfo

NextHost is an iteration function over picked hosts

type Node

type Node interface {
	Pick(qry *Query) *Conn
	Close()
}

type PasswordAuthenticator

type PasswordAuthenticator struct {
	Username string
	Password string
}

func (PasswordAuthenticator) Challenge

func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error)

func (PasswordAuthenticator) Success

func (p PasswordAuthenticator) Success(data []byte) error

type Query

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

Query represents a CQL statement that can be executed.

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 arguments to an existing query instance.

func (*Query) Consistency

func (q *Query) Consistency(c Consistency) *Query

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

func (*Query) DefaultTimestamp

func (q *Query) DefaultTimestamp(enable bool) *Query

DefaultTimestamp will enable the with default timestamp flag on the query. If enable, this will replace the server side assigned timestamp as default timestamp. Note that a timestamp in the query itself will 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 for the query.

func (*Query) GetRoutingKey

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

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

func (*Query) Iter

func (q *Query) Iter() *Iter

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

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 selected row into the map pointed at by m and discards the rest. If no rows were selected, ErrNotFound is returned.

func (*Query) MapScanCAS

func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error)

MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT statement containing an IF clause). If the transaction fails because the existing values did not match, the previous values will be stored in dest map.

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

func (*Query) PageSize

func (q *Query) PageSize(n int) *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 the page size to low might decrease the performance. This feature is only available in Cassandra 2 and onwards.

func (*Query) PageState added in v0.3.0

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

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

func (*Query) Prefetch

func (q *Query) Prefetch(p float64) *Query

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

func (*Query) RetryPolicy

func (q *Query) RetryPolicy(r RetryPolicy) *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 connection pool 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 selected row into the values pointed at by dest and discards the rest. If no rows were selected, ErrNotFound is returned.

func (*Query) ScanCAS

func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error)

ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT statement containing an IF clause). If the transaction fails because the existing values did not match, the previous values will be stored in dest.

func (*Query) SerialConsistency

func (q *Query) SerialConsistency(cons SerialConsistency) *Query

SerialConsistency sets the consistencyc level for the serial phase of conditional updates. That consitency can only be either SERIAL or LOCAL_SERIAL and if not present, it defaults to SERIAL. This option will be ignored for anything else that a conditional update/insert.

func (Query) String added in v0.3.0

func (q Query) String() string

String implements the stringer interface.

func (*Query) Trace

func (q *Query) Trace(trace Tracer) *Query

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

type QueryInfo

type QueryInfo struct {
	Id   []byte
	Args []ColumnInfo
	Rval []ColumnInfo
}

type RequestErrAlreadyExists

type RequestErrAlreadyExists struct {
	Keyspace string
	Table    string
	// 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

type RequestErrFunctionFailure added in v0.3.0

type RequestErrFunctionFailure struct {
	Keyspace string
	Function string
	ArgTypes []string
	// contains filtered or unexported fields
}

func (RequestErrFunctionFailure) Code added in v0.3.0

func (e RequestErrFunctionFailure) Code() int

func (RequestErrFunctionFailure) Error added in v0.3.0

func (e RequestErrFunctionFailure) Error() string

func (RequestErrFunctionFailure) Message added in v0.3.0

func (e RequestErrFunctionFailure) Message() string

func (RequestErrFunctionFailure) String added in v0.3.0

func (e RequestErrFunctionFailure) String() string

type RequestErrReadFailure added in v0.3.0

type RequestErrReadFailure struct {
	Consistency Consistency
	Received    int
	BlockFor    int
	NumFailures int
	DataPresent bool
	// contains filtered or unexported fields
}

func (RequestErrReadFailure) Code added in v0.3.0

func (e RequestErrReadFailure) Code() int

func (RequestErrReadFailure) Error added in v0.3.0

func (e RequestErrReadFailure) Error() string

func (RequestErrReadFailure) Message added in v0.3.0

func (e RequestErrReadFailure) Message() string

func (RequestErrReadFailure) String added in v0.3.0

func (e RequestErrReadFailure) String() string

type RequestErrReadTimeout

type RequestErrReadTimeout struct {
	Consistency Consistency
	Received    int
	BlockFor    int
	DataPresent byte
	// 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

type RequestErrUnavailable

type RequestErrUnavailable struct {
	Consistency Consistency
	Required    int
	Alive       int
	// 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

type RequestErrUnprepared

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

type RequestErrWriteTimeout

type RequestErrWriteTimeout struct {
	Consistency Consistency
	Received    int
	BlockFor    int
	WriteType   string
	// 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

type RequestError

type RequestError interface {
	Code() int
	Message() string
	Error() string
}

type RetryPolicy

type RetryPolicy interface {
	Attempt(RetryableQuery) bool
}

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

See SimpleRetryPolicy as an example of implementing and using a RetryPolicy interface.

type RetryableQuery

type RetryableQuery interface {
	Attempts() int
	GetConsistency() Consistency
}

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

type RoundRobin

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

func NewRoundRobin

func NewRoundRobin() *RoundRobin

func (*RoundRobin) AddNode

func (r *RoundRobin) AddNode(node Node)

func (*RoundRobin) Close

func (r *RoundRobin) Close()

func (*RoundRobin) Pick

func (r *RoundRobin) Pick(qry *Query) *Conn

func (*RoundRobin) RemoveNode

func (r *RoundRobin) RemoveNode(node Node)

func (*RoundRobin) Size

func (r *RoundRobin) Size() int

type RowData

type RowData struct {
	Columns []string
	Values  []interface{}
}

type SerialConsistency

type SerialConsistency uint16
const (
	Serial      SerialConsistency = 0x08
	LocalSerial SerialConsistency = 0x09
)

func (SerialConsistency) String

func (s SerialConsistency) String() string

type Session

type Session struct {
	Pool ConnectionPool
	// 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 usage scenario is to have one global session object to interact with the whole Cassandra cluster.

This type extends the Node interface by adding a convinient query builder and automatically sets a default consinstency level on all operations that do not have a consistency level set.

func NewSession

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

NewSession wraps an existing Node.

func (*Session) Bind

func (s *Session) Bind(stmt string, 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 argument values will be marshalled as part of the query execution. During execution, the meta data of the prepared query will be routed to the binding 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 this operation.

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 successful otherwise an error is returned describing the failure.

func (*Session) KeyspaceMetadata

func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error)

KeyspaceMetadata returns the schema metadata for the keyspace specified.

func (*Session) NewBatch

func (s *Session) NewBatch(typ BatchType) *Batch

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

func (*Session) Query

func (s *Session) Query(stmt string, 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 query value before the query is executed. Query is automatically prepared if it has not previously been executed.

func (*Session) SetConsistency

func (s *Session) SetConsistency(cons Consistency)

SetConsistency sets the default consistency level for this session. This setting can also be changed on a per-query basis and the default value is Quorum.

func (*Session) SetPageSize

func (s *Session) SetPageSize(n int)

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

func (*Session) SetPrefetch

func (s *Session) SetPrefetch(p float64)

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

func (*Session) SetTrace

func (s *Session) SetTrace(trace Tracer)

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

type SetHosts

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

interface to implement to receive the host information

type SetPartitioner

type SetPartitioner interface {
	SetPartitioner(partitioner string)
}

interface to implement to receive the partitioner value

type SimplePool

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

SimplePool is the current implementation of the connection pool inside gocql. This pool is meant to be a simple default used by gocql so users can get up and running quickly.

func (*SimplePool) Close

func (c *SimplePool) Close()

Close kills the pool and all associated connections.

func (*SimplePool) HandleError

func (c *SimplePool) HandleError(conn *Conn, err error, closed bool)

HandleError is called by a Connection object to report to the pool an error has occured. Logic is then executed within the pool to clean up the erroroneous connection and try to top off the pool.

func (*SimplePool) Pick

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

Pick selects a connection to be used by the query.

func (*SimplePool) SetHosts

func (c *SimplePool) SetHosts(hosts []HostInfo)

func (*SimplePool) Size

func (p *SimplePool) Size() int

Size returns the number of connections currently active in the pool

type SimpleRetryPolicy

type SimpleRetryPolicy struct {
	NumRetries int //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 cluster
cluster.RetryPolicy = &gocql.SimpleRetryPolicy{NumRetries: 3}

//Assign to a query
query.RetryPolicy(&gocql.SimpleRetryPolicy{NumRetries: 1})

func (*SimpleRetryPolicy) Attempt

func (s *SimpleRetryPolicy) Attempt(q RetryableQuery) bool

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

type SnappyCompressor

type SnappyCompressor struct{}

SnappyCompressor implements the Compressor interface and can be used to compress incoming and outgoing frames. The snappy compression algorithm aims for very high speeds and reasonable compression.

func (SnappyCompressor) Decode

func (s SnappyCompressor) Decode(data []byte) ([]byte, error)

func (SnappyCompressor) Encode

func (s SnappyCompressor) Encode(data []byte) ([]byte, error)

func (SnappyCompressor) Name

func (s SnappyCompressor) Name() string

type SslOptions

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 certificate
	CertPath string
	KeyPath  string
	CaPath   string //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 InSecureSkipVerify
	// See InSecureSkipVerify in http://golang.org/pkg/crypto/tls/ for more info
	EnableHostVerification bool
}

type TableMetadata

type TableMetadata struct {
	Keyspace          string
	Name              string
	KeyValidator      string
	Comparator        string
	DefaultValidator  string
	KeyAliases        []string
	ColumnAliases     []string
	ValueAlias        string
	PartitionKey      []*ColumnMetadata
	ClusteringColumns []*ColumnMetadata
	Columns           map[string]*ColumnMetadata
	OrderedColumns    []string
}

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

type Tracer

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

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

func NewTraceWriter

func NewTraceWriter(session *Session, w io.Writer) Tracer

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

type TupleTypeInfo

type TupleTypeInfo struct {
	NativeType
	Elems []TypeInfo
}

type Type

type Type int

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

const (
	TypeCustom    Type = 0x0000
	TypeAscii     Type = 0x0001
	TypeBigInt    Type = 0x0002
	TypeBlob      Type = 0x0003
	TypeBoolean   Type = 0x0004
	TypeCounter   Type = 0x0005
	TypeDecimal   Type = 0x0006
	TypeDouble    Type = 0x0007
	TypeFloat     Type = 0x0008
	TypeInt       Type = 0x0009
	TypeTimestamp Type = 0x000B
	TypeUUID      Type = 0x000C
	TypeVarchar   Type = 0x000D
	TypeVarint    Type = 0x000E
	TypeTimeUUID  Type = 0x000F
	TypeInet      Type = 0x0010
	TypeList      Type = 0x0020
	TypeMap       Type = 0x0021
	TypeSet       Type = 0x0022
	TypeUDT       Type = 0x0030
	TypeTuple     Type = 0x0031
)

func (Type) String

func (t Type) String() string

String returns the name of the identifier.

type TypeInfo

type TypeInfo interface {
	Type() Type
	Version() byte
	Custom() string

	// New creates a pointer to an empty version of whatever type
	// is referenced by the TypeInfo receiver
	New() interface{}
}

TypeInfo describes a Cassandra specific data type.

type UDTField

type UDTField struct {
	Name string
	Type TypeInfo
}

type UDTMarshaler

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(name string, info TypeInfo) ([]byte, error)
}

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

type UDTTypeInfo

type UDTTypeInfo struct {
	NativeType
	KeySpace string
	Name     string
	Elements []UDTField
}

func (UDTTypeInfo) String

func (u UDTTypeInfo) String() string

type UDTUnmarshaler

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(name string, info TypeInfo, data []byte) error
}

UDTUnmarshaler should be implemented by users wanting to implement custom UDT unmarshaling.

type UUID

type UUID [16]byte

func ParseUUID

func ParseUUID(input string) (UUID, error)

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

func RandomUUID

func RandomUUID() (UUID, error)

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

func TimeUUID

func TimeUUID() UUID

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

func UUIDFromBytes

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

UUIDFromBytes converts a raw byte slice to an UUID.

func UUIDFromTime

func UUIDFromTime(aTime time.Time) UUID

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

func (UUID) Bytes

func (u UUID) Bytes() []byte

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

func (UUID) MarshalJSON

func (u UUID) MarshalJSON() ([]byte, error)

Marshaling for JSON

func (UUID) Node

func (u UUID) Node() []byte

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

func (UUID) String

func (u UUID) String() string

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

func (UUID) Time

func (u UUID) Time() time.Time

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

func (UUID) Timestamp

func (u UUID) 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) Variant

func (u UUID) Variant() int

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

func (UUID) Version

func (u UUID) Version() int

Version extracts the version of this UUID variant. The RFC 4122 describes five kinds of UUIDs.

type UnmarshalError

type UnmarshalError string

func (UnmarshalError) Error

func (m UnmarshalError) Error() string

type Unmarshaler

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

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

Directories

Path Synopsis
Package lru implements an LRU cache.
Package lru implements an LRU cache.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL