gocql: github.com/gocql/gocql Index | Files | Directories

package gocql

import "github.com/gocql/gocql"

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

Package Files

address_translators.go cluster.go compressor.go conn.go connectionpool.go control.go debug_off.go doc.go errors.go events.go filters.go frame.go helpers.go host_source.go logger.go marshal.go metadata.go policies.go prepared_cache.go query_executor.go ring.go session.go token.go topology.go uuid.go

Constants

const (
    NodeUp nodeState = iota
    NodeDown
)
const (
    DEFAULT_KEY_ALIAS    = "key"
    DEFAULT_COLUMN_ALIAS = "column"
    DEFAULT_VALUE_ALIAS  = "value"
)

default alias values

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"
)
const (
    VariantNCSCompat = 0
    VariantIETF      = 2
    VariantMicrosoft = 6
    VariantFuture    = 7
)
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

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")
)
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")
)
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 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")
)
var (
    ErrFrameTooBig = errors.New("frame length is bigger than the maximum allowed")
)
var (
    ErrorUDTUnavailable = errors.New("UDT are not available on protocols less than 3, please update config")
)
var TimeoutLimit int64 = 10

If not zero, 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.

func JoinHostPort Uses

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 Uses

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 Uses

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

func TupleColumnName Uses

func TupleColumnName(c string, n int) string

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

func Unmarshal Uses

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.

type AddressTranslator Uses

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(addr net.IP, port int) (net.IP, int)
}

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

func IdentityTranslator Uses

func IdentityTranslator() AddressTranslator

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

type AddressTranslatorFunc Uses

type AddressTranslatorFunc func(addr net.IP, port int) (net.IP, int)

func (AddressTranslatorFunc) Translate Uses

func (fn AddressTranslatorFunc) Translate(addr net.IP, port int) (net.IP, int)

type Authenticator Uses

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

type Batch Uses

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

func NewBatch Uses

func NewBatch(typ BatchType) *Batch

NewBatch creates a new batch operation without defaults from the cluster

func (*Batch) Attempts Uses

func (b *Batch) Attempts() int

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

func (*Batch) Bind Uses

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 Uses

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 Uses

func (b *Batch) GetConsistency() Consistency

GetConsistency returns the currently configured consistency level for the batch operation.

func (*Batch) GetRoutingKey Uses

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

func (*Batch) Latency Uses

func (b *Batch) Latency() int64

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

func (*Batch) Query Uses

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

Query adds the query to the batch operation

func (*Batch) RetryPolicy Uses

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

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

func (*Batch) SerialConsistency Uses

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

SerialConsistency sets the consistency level for the serial phase of conditional updates. That consistency 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 Uses

func (b *Batch) Size() int

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

func (*Batch) WithContext Uses

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

WithContext will set the context to use during a query, it will be used to timeout when waiting for responses from Cassandra.

func (*Batch) WithTimestamp Uses

func (b *Batch) WithTimestamp(timestamp int64) *Batch

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

Only available on protocol >= 3

type BatchEntry Uses

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

type BatchType Uses

type BatchType byte
const (
    LoggedBatch   BatchType = 0
    UnloggedBatch BatchType = 1
    CounterBatch  BatchType = 2
)

type ClusterConfig Uses

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
    CQLVersion string // CQL version (default: 3.0.0)

    // 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)
    ProtoVersion      int
    Timeout           time.Duration     // connection timeout (default: 600ms)
    ConnectTimeout    time.Duration     // initial connection timeout, used during initial dial to server (default: 600ms)
    Port              int               // port (default: 9042)
    Keyspace          string            // initial keyspace (optional)
    NumConns          int               // number of connections per host (default: 2)
    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)
    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)
    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)
    // PoolConfig configures the underlying connection pool, allowing the
    // configuration of host selection and connection selection policies.
    PoolConfig PoolConfig

    // If not zero, gocql attempt to reconnect known DOWN nodes in every ReconnectSleep.
    ReconnectInterval time.Duration

    // The maximum amount of time to wait for schema agreement in a cluster after
    // receiving a schema change frame. (deault: 60s)
    MaxWaitSchemaAgreement time.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 Discovery
    HostFilter HostFilter

    // AddressTranslator will translate addresses found on peer discovery and/or
    // node change events.
    AddressTranslator AddressTranslator

    // 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.
    IgnorePeerAddr bool

    // 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.
    DisableInitialHostLookup bool

    // Configure events the driver will register for
    Events struct {
        // disable registering for status events (node up/down)
        DisableNodeStatusEvents bool
        // disable registering for topology events (node added/removed/moved)
        DisableTopologyEvents bool
        // disable registering for schema events (keyspace/table/function removed/created/updated)
        DisableSchemaEvents bool
    }

    // 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.
    //
    // See https://issues.apache.org/jira/browse/CASSANDRA-10786
    DisableSkipMetadata bool
    // contains filtered or unexported fields
}

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

func NewCluster Uses

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 of the ring will be automatically discovered. 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.

func (*ClusterConfig) CreateSession Uses

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 Uses

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

func (CollectionType) New Uses

func (t CollectionType) New() interface{}

func (CollectionType) String Uses

func (c CollectionType) String() string

type ColumnIndexMetadata Uses

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

type ColumnInfo Uses

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

func (ColumnInfo) String Uses

func (c ColumnInfo) String() string

type ColumnKind Uses

type ColumnKind int
const (
    ColumnUnkownKind ColumnKind = iota
    ColumnPartitionKey
    ColumnClusteringKey
    ColumnRegular
    ColumnCompact
    ColumnStatic
)

func (ColumnKind) String Uses

func (c ColumnKind) String() string

func (*ColumnKind) UnmarshalCQL Uses

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

type ColumnMetadata Uses

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

schema metadata for a column

type ColumnOrder Uses

type ColumnOrder bool

the ordering of the column with regard to its comparator

const (
    ASC  ColumnOrder = false
    DESC             = true
)

type Compressor Uses

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

type Conn Uses

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 Uses

func Connect(host *HostInfo, cfg *ConnConfig, errorHandler ConnErrorHandler, session *Session) (*Conn, error)

Connect establishes a connection to a Cassandra node.

func (*Conn) Address Uses

func (c *Conn) Address() string

func (*Conn) AvailableStreams Uses

func (c *Conn) AvailableStreams() int

func (*Conn) Close Uses

func (c *Conn) Close()

func (*Conn) Closed Uses

func (c *Conn) Closed() bool

func (*Conn) Pick Uses

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

func (*Conn) Read Uses

func (c *Conn) Read(p []byte) (n int, err error)

func (*Conn) UseKeyspace Uses

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

func (*Conn) Write Uses

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

type ConnConfig Uses

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

type ConnErrorHandler Uses

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

type Consistency Uses

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 ParseConsistency Uses

func ParseConsistency(s string) Consistency

func ParseConsistencyWrapper Uses

func ParseConsistencyWrapper(s string) (consistency Consistency, err error)

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

func (Consistency) String Uses

func (c Consistency) String() string

type ErrProtocol Uses

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

type Error Uses

type Error struct {
    Code    int
    Message string
}

func (Error) Error Uses

func (e Error) Error() string

type ExecutableQuery Uses

type ExecutableQuery interface {
    GetRoutingKey() ([]byte, error)
    RetryableQuery
    // contains filtered or unexported methods
}

type HostFilter Uses

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.

func AcceptAllFilter Uses

func AcceptAllFilter() HostFilter

AcceptAllFilter will accept all hosts

func DataCentreHostFilter Uses

func DataCentreHostFilter(dataCentre string) HostFilter

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

func DenyAllFilter Uses

func DenyAllFilter() HostFilter

func WhiteListHostFilter Uses

func WhiteListHostFilter(hosts ...string) HostFilter

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

type HostFilterFunc Uses

type HostFilterFunc func(host *HostInfo) bool

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

func (HostFilterFunc) Accept Uses

func (fn HostFilterFunc) Accept(host *HostInfo) bool

type HostInfo Uses

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

func (*HostInfo) DataCenter Uses

func (h *HostInfo) DataCenter() string

func (*HostInfo) Equal Uses

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

func (*HostInfo) HostID Uses

func (h *HostInfo) HostID() string

func (*HostInfo) IsUp Uses

func (h *HostInfo) IsUp() bool

func (*HostInfo) Peer Uses

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

func (*HostInfo) Port Uses

func (h *HostInfo) Port() int

func (*HostInfo) Rack Uses

func (h *HostInfo) Rack() string

func (*HostInfo) State Uses

func (h *HostInfo) State() nodeState

func (*HostInfo) String Uses

func (h *HostInfo) String() string

func (*HostInfo) Tokens Uses

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

func (*HostInfo) Version Uses

func (h *HostInfo) Version() cassVersion

type HostSelectionPolicy Uses

type HostSelectionPolicy interface {
    HostStateNotifier
    SetPartitioner
    //Pick returns an iteration function over selected hosts
    Pick(ExecutableQuery) NextHost
}

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

func HostPoolHostPolicy Uses

func HostPoolHostPolicy(hp hostpool.HostPool) HostSelectionPolicy

HostPoolHostPolicy is a host policy which uses the bitly/go-hostpool library to distribute queries between hosts and prevent sending queries to unresponsive hosts. When creating the host pool that is passed to the policy use 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 pool
cluster.PoolConfig.HostSelectionPolicy = HostPoolHostPolicy(hostpool.New(nil))

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

func RoundRobinHostPolicy Uses

func RoundRobinHostPolicy() HostSelectionPolicy

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

func TokenAwareHostPolicy Uses

func TokenAwareHostPolicy(fallback HostSelectionPolicy) HostSelectionPolicy

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

type HostStateNotifier Uses

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

type Iter Uses

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 Uses

func (iter *Iter) Close() error

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

func (*Iter) Columns Uses

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

Columns returns the name and type of the selected columns.

func (*Iter) GetCustomPayload Uses

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

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

This additional feature of CQL Protocol v4 allows additional results and query information to be returned by custom QueryHandlers running in your C* cluster. See https://datastax.github.io/java-driver/manual/custom_payloads/

func (*Iter) Host Uses

func (iter *Iter) Host() *HostInfo

Host returns the host which the query was sent to.

func (*Iter) MapScan Uses

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.

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

iter := session.Query(`SELECT * FROM mytable`).Iter()
for {
	// New map each iteration
	row = make(map[string]interface{})
	if !iter.MapScan(row) {
		break
	}
	// Do things with row
	if 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 interfaces
var address net.IP
var age int
iter := session.Query(`SELECT * FROM scan_map_table`).Iter()
for {
	// New map each iteration
	row := 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 Uses

func (iter *Iter) NumRows() int

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

func (*Iter) PageState Uses

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 Uses

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

func (*Iter) Scan Uses

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) Scanner Uses

func (iter *Iter) Scanner() Scanner

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

func (*Iter) SliceMap Uses

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{}

func (*Iter) Warnings Uses

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 Uses

func (iter *Iter) WillSwitchPage() bool

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

type KeyspaceMetadata Uses

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

schema metadata for a keyspace

type MarshalError Uses

type MarshalError string

func (MarshalError) Error Uses

func (m MarshalError) Error() string

type Marshaler Uses

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 Uses

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

func NewNativeType Uses

func NewNativeType(proto byte, typ Type, custom string) NativeType

func (NativeType) Custom Uses

func (s NativeType) Custom() string

func (NativeType) New Uses

func (t NativeType) New() interface{}

func (NativeType) String Uses

func (s NativeType) String() string

func (NativeType) Type Uses

func (s NativeType) Type() Type

func (NativeType) Version Uses

func (s NativeType) Version() byte

type NextHost Uses

type NextHost func() SelectedHost

NextHost is an iteration function over picked hosts

type Node Uses

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

type PasswordAuthenticator Uses

type PasswordAuthenticator struct {
    Username string
    Password string
}

func (PasswordAuthenticator) Challenge Uses

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

func (PasswordAuthenticator) Success Uses

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

type PoolConfig Uses

type PoolConfig struct {
    // HostSelectionPolicy sets the policy for selecting which host to use for a
    // given query (default: RoundRobinHostPolicy())
    HostSelectionPolicy HostSelectionPolicy
}

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

type Query Uses

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

Query represents a CQL statement that can be executed.

func (*Query) Attempts Uses

func (q *Query) Attempts() int

Attempts returns the number of times the query was executed.

func (*Query) Bind Uses

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 Uses

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 Uses

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 Uses

func (q *Query) Exec() error

Exec executes the query without returning any rows.

func (*Query) GetConsistency Uses

func (q *Query) GetConsistency() Consistency

GetConsistency returns the currently configured consistency level for the query.

func (*Query) GetRoutingKey Uses

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 Uses

func (q *Query) Iter() *Iter

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

func (*Query) Latency Uses

func (q *Query) Latency() int64

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

func (*Query) MapScan Uses

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 Uses

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) NoSkipMetadata Uses

func (q *Query) NoSkipMetadata() *Query

NoSkipMetadata 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 staement. This should only be used to work around cassandra bugs, such as when using CAS operations which do not end in Cas.

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

func (*Query) PageSize Uses

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 too low might decrease the performance. This feature is only available in Cassandra 2 and onwards.

func (*Query) PageState Uses

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 Uses

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) Release Uses

func (q *Query) Release()

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

Example:

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

func (*Query) RetryPolicy Uses

func (q *Query) RetryPolicy(r RetryPolicy) *Query

RetryPolicy sets the policy to use when retrying the query.

func (*Query) RoutingKey Uses

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 Uses

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 Uses

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 Uses

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

SerialConsistency sets the consistency level for the serial phase of conditional updates. That consistency 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 Uses

func (q Query) String() string

String implements the stringer interface.

func (*Query) Trace Uses

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.

func (*Query) WithContext Uses

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

WithContext will set the context to use during a query, it will be used to timeout when waiting for responses from Cassandra.

func (*Query) WithTimestamp Uses

func (q *Query) WithTimestamp(timestamp int64) *Query

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

Only available on protocol >= 3

type QueryInfo Uses

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

type RequestErrAlreadyExists Uses

type RequestErrAlreadyExists struct {
    Keyspace string
    Table    string
    // contains filtered or unexported fields
}

func (RequestErrAlreadyExists) Code Uses

func (e RequestErrAlreadyExists) Code() int

func (RequestErrAlreadyExists) Error Uses

func (e RequestErrAlreadyExists) Error() string

func (RequestErrAlreadyExists) Message Uses

func (e RequestErrAlreadyExists) Message() string

func (RequestErrAlreadyExists) String Uses

func (e RequestErrAlreadyExists) String() string

type RequestErrFunctionFailure Uses

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

func (RequestErrFunctionFailure) Code Uses

func (e RequestErrFunctionFailure) Code() int

func (RequestErrFunctionFailure) Error Uses

func (e RequestErrFunctionFailure) Error() string

func (RequestErrFunctionFailure) Message Uses

func (e RequestErrFunctionFailure) Message() string

func (RequestErrFunctionFailure) String Uses

func (e RequestErrFunctionFailure) String() string

type RequestErrReadFailure Uses

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

func (RequestErrReadFailure) Code Uses

func (e RequestErrReadFailure) Code() int

func (RequestErrReadFailure) Error Uses

func (e RequestErrReadFailure) Error() string

func (RequestErrReadFailure) Message Uses

func (e RequestErrReadFailure) Message() string

func (RequestErrReadFailure) String Uses

func (e RequestErrReadFailure) String() string

type RequestErrReadTimeout Uses

type RequestErrReadTimeout struct {
    Consistency Consistency
    Received    int
    BlockFor    int
    DataPresent byte
    // contains filtered or unexported fields
}

func (RequestErrReadTimeout) Code Uses

func (e RequestErrReadTimeout) Code() int

func (RequestErrReadTimeout) Error Uses

func (e RequestErrReadTimeout) Error() string

func (RequestErrReadTimeout) Message Uses

func (e RequestErrReadTimeout) Message() string

func (RequestErrReadTimeout) String Uses

func (e RequestErrReadTimeout) String() string

type RequestErrUnavailable Uses

type RequestErrUnavailable struct {
    Consistency Consistency
    Required    int
    Alive       int
    // contains filtered or unexported fields
}

func (RequestErrUnavailable) Code Uses

func (e RequestErrUnavailable) Code() int

func (RequestErrUnavailable) Error Uses

func (e RequestErrUnavailable) Error() string

func (RequestErrUnavailable) Message Uses

func (e RequestErrUnavailable) Message() string

func (*RequestErrUnavailable) String Uses

func (e *RequestErrUnavailable) String() string

type RequestErrUnprepared Uses

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

func (RequestErrUnprepared) Code Uses

func (e RequestErrUnprepared) Code() int

func (RequestErrUnprepared) Error Uses

func (e RequestErrUnprepared) Error() string

func (RequestErrUnprepared) Message Uses

func (e RequestErrUnprepared) Message() string

func (RequestErrUnprepared) String Uses

func (e RequestErrUnprepared) String() string

type RequestErrWriteFailure Uses

type RequestErrWriteFailure struct {
    Consistency Consistency
    Received    int
    BlockFor    int
    NumFailures int
    WriteType   string
    // contains filtered or unexported fields
}

func (RequestErrWriteFailure) Code Uses

func (e RequestErrWriteFailure) Code() int

func (RequestErrWriteFailure) Error Uses

func (e RequestErrWriteFailure) Error() string

func (RequestErrWriteFailure) Message Uses

func (e RequestErrWriteFailure) Message() string

func (RequestErrWriteFailure) String Uses

func (e RequestErrWriteFailure) String() string

type RequestErrWriteTimeout Uses

type RequestErrWriteTimeout struct {
    Consistency Consistency
    Received    int
    BlockFor    int
    WriteType   string
    // contains filtered or unexported fields
}

func (RequestErrWriteTimeout) Code Uses

func (e RequestErrWriteTimeout) Code() int

func (RequestErrWriteTimeout) Error Uses

func (e RequestErrWriteTimeout) Error() string

func (RequestErrWriteTimeout) Message Uses

func (e RequestErrWriteTimeout) Message() string

func (RequestErrWriteTimeout) String Uses

func (e RequestErrWriteTimeout) String() string

type RequestError Uses

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

type RetryPolicy Uses

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 Uses

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 Uses

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

func NewRoundRobin Uses

func NewRoundRobin() *RoundRobin

func (*RoundRobin) AddNode Uses

func (r *RoundRobin) AddNode(node Node)

func (*RoundRobin) Close Uses

func (r *RoundRobin) Close()

func (*RoundRobin) Pick Uses

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

func (*RoundRobin) RemoveNode Uses

func (r *RoundRobin) RemoveNode(node Node)

func (*RoundRobin) Size Uses

func (r *RoundRobin) Size() int

type RowData Uses

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

type Scanner Uses

type Scanner interface {
    Next() bool
    Scan(...interface{}) error
    Err() error
}

type SelectedHost Uses

type SelectedHost interface {
    Info() *HostInfo
    Mark(error)
}

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

type SerialConsistency Uses

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

func (SerialConsistency) String Uses

func (s SerialConsistency) String() string

type Session Uses

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 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 consistency level on all operations that do not have a consistency level set.

func NewSession Uses

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

NewSession wraps an existing Node.

func (*Session) Bind Uses

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 Uses

func (s *Session) Close()

Close closes all connections. The session is unusable after this operation.

func (*Session) Closed Uses

func (s *Session) Closed() bool

func (*Session) ExecuteBatch Uses

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) ExecuteBatchCAS Uses

func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...interface{}) (applied bool, iter *Iter, err error)

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

func (*Session) KeyspaceMetadata Uses

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

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

func (*Session) MapExecuteBatchCAS Uses

func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]interface{}) (applied bool, iter *Iter, err error)

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

func (*Session) NewBatch Uses

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

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

func (*Session) Query Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

interface to implement to receive the host information

type SetPartitioner Uses

type SetPartitioner interface {
    SetPartitioner(partitioner string)
}

interface to implement to receive the partitioner value

type SimpleRetryPolicy Uses

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 Uses

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 Uses

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 Uses

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

func (SnappyCompressor) Encode Uses

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

func (SnappyCompressor) Name Uses

func (s SnappyCompressor) Name() string

type SslOptions Uses

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 StdLogger Uses

type StdLogger interface {
    Print(v ...interface{})
    Printf(format string, v ...interface{})
    Println(v ...interface{})
}
var Logger StdLogger = &defaultLogger{}

type TableMetadata Uses

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 Uses

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 Uses

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 Uses

type TupleTypeInfo struct {
    NativeType
    Elems []TypeInfo
}

func (TupleTypeInfo) New Uses

func (t TupleTypeInfo) New() interface{}

type Type Uses

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
    TypeText      Type = 0x000A
    TypeTimestamp Type = 0x000B
    TypeUUID      Type = 0x000C
    TypeVarchar   Type = 0x000D
    TypeVarint    Type = 0x000E
    TypeTimeUUID  Type = 0x000F
    TypeInet      Type = 0x0010
    TypeDate      Type = 0x0011
    TypeTime      Type = 0x0012
    TypeSmallInt  Type = 0x0013
    TypeTinyInt   Type = 0x0014
    TypeList      Type = 0x0020
    TypeMap       Type = 0x0021
    TypeSet       Type = 0x0022
    TypeUDT       Type = 0x0030
    TypeTuple     Type = 0x0031
)

func (Type) String Uses

func (t Type) String() string

String returns the name of the identifier.

type TypeInfo Uses

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 Uses

type UDTField struct {
    Name string
    Type TypeInfo
}

type UDTMarshaler Uses

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 Uses

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

func (UDTTypeInfo) New Uses

func (u UDTTypeInfo) New() interface{}

func (UDTTypeInfo) String Uses

func (u UDTTypeInfo) String() string

type UDTUnmarshaler Uses

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 Uses

type UUID [16]byte

func ParseUUID Uses

func ParseUUID(input string) (UUID, error)

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

func RandomUUID Uses

func RandomUUID() (UUID, error)

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

func TimeUUID Uses

func TimeUUID() UUID

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

func UUIDFromBytes Uses

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

UUIDFromBytes converts a raw byte slice to an UUID.

func UUIDFromTime Uses

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 Uses

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 Uses

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

Marshaling for JSON

func (UUID) MarshalText Uses

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

func (UUID) Node Uses

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 Uses

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 Uses

func (u UUID) Time() time.Time

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

func (UUID) Timestamp Uses

func (u UUID) Timestamp() int64

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

func (*UUID) UnmarshalJSON Uses

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

Unmarshaling for JSON

func (*UUID) UnmarshalText Uses

func (u *UUID) UnmarshalText(text []byte) (err error)

func (UUID) Variant Uses

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 Uses

func (u UUID) Version() int

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

type UnmarshalError Uses

type UnmarshalError string

func (UnmarshalError) Error Uses

func (m UnmarshalError) Error() string

type Unmarshaler Uses

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

PathSynopsis
internal/lruPackage lru implements an LRU cache.
internal/murmur
internal/streams

Package gocql imports 35 packages (graph) and is imported by 136 packages. Updated 2017-03-25. Refresh now. Tools for package owners.