ecql

package module
v0.0.0-...-8ae2b35 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2018 License: MIT Imports: 9 Imported by: 0

README

ecql

GoDoc

Package ecql (EasyCQL) implements an easy to use Cassandra client for the Go programing language.

EasyCQL is based on gocql.

The current interface is still experimental and it will change without notice.

Features

Easy API:

  • Map struct types with Cassandra tables.
  • SELECT statements.
  • INSERT statements.
  • DELETE statements.
  • UPDATE statements.
  • Compound primary keys.

Statement API:

  • Map struct types with Cassandra tables.
  • SELECT statements.
  • SELECT COUNT(1) statements.
  • INSERT statements.
  • DELETE statements.
  • UPDATE statements.
  • BATCH statements.
  • Iterators to go through multiple results.
  • WHERE filtering (=, >, >=, <, or <=).
  • WHERE filtering (AND).
  • WHERE filtering (IN).
  • WHERE filtering (Interface mapping of keys).
  • WHERE filtering (CONTAINS, CONTAINS KEY)
  • LIMIT on SELECT statements.
  • ORDER BY on SELECT statements.
  • ALLOW FILTERING ON SELECT statements.
  • IF NOT EXISTS on INSERT statements.
  • IF and IF EXISTS on DELETE statements.
  • IF and IF EXISTS on UPDATE statements.
  • USING TTL on INSERT statements.
  • USING TIMESTAMP on INSERT statements.
  • USING TIMESTAMP on DELETE statements.
  • USING TIMESTAMP on BATCH statements.
  • USING TTL on UPDATE statements.
  • USING TIMESTAMP on UPDATE statements.
  • Counters.
  • Functions.

Documentation.

Defining a table.

To be able to bind a table in Cassandra to a Go struct we will need tag the struct fields using the tag cql, cqltable and cqlkey. The tag cql defines the column name, the tag cqltable defines the name of the table, and cqlkey is a comma separated list of the primary keys in the right order.

For example, for the CREATE TABLE statement:

CREATE TABLE tweet (
  id uuid,
  timeline text,
  text text,
  time timestamp,
  PRIMARY KEY (id)
);

We can use the following struct in Go:

type Tweet struct {
	ID       gocql.UUID `cql:"id" cqltable:"tweet" cqlkey:"id"`
	Timeline string     `cql:"timeline"`
	Text     string     `cql:"text"`
	Time     time.Time  `cql:"time"`
}

func init() {
	ecql.Register(Tweet{})
}

It is recommended to register the struct on init functions, but ecql will register new types if they are not registered.

Queries.
Easy API
sess.Get(i interface{}, keys ...interface{}) error

Creates and execute a SELECT statement in the table defined by the argument i using the keys as the values of the primary keys. It stores the result in the first argument, so it must be passed as a reference.

var tw Tweet
err := sess.Get(&tw, "a5450908-17d7-11e6-b9ec-542696d5770f")
sess.Set(i interface{}) error

Creates and execute a INSERT statement in the table defined by the argument i and sets the values in the mapped columns.

tw  := Tweet{
	ID:       gocql.TimeUUID(),
	Timeline: "ecql",
	Text:     "Hello World",
	Time:     time.Now(),
}
err := sess.Set(tw)
sess.Del(i interface{}) error

Creates a DELETE statement in the table defined by the argument i using the filtering by the primary keys defined on i.

uuid, _ := gocql.ParseUUID("a5450908-17d7-11e6-b9ec-542696d5770f")
tw := Tweet{
	ID: uuid,
}
err := sess.Del(tw)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidQueryType = errors.New("invalid query type")
	ErrInvalidCommand   = errors.New("invalid cql command")
)
View Source
var (
	// TAG_COLUMNS is the tag used in the structs to set the column name for a field.
	// If a name is not set, the name would be the lowercase version of the field.
	// If you want to skip a field you can use `cql:"-"`
	TAG_COLUMN = "cql"

	// TAG_TABLE is the tag used in the structs to define the table for a type.
	// If the table is not set it defaults to the type name in lowercase.
	TAG_TABLE = "cqltable"

	// TAG_KEY defines the primary key for the table.
	// If the table uses a composite key you just need to define multiple columns
	// separated by a comma: `cqlkey:"id"` or `cqlkey:"partkey,id"`
	TAG_KEY = "cqlkey"
)
View Source
var EcqlDebug = (os.Getenv("ECQL_DEBUG") == "true")
View Source
var ErrNotFound = gocql.ErrNotFound

Functions

func Bind

func Bind(i interface{}) []interface{}

Bind returns the values of i to bind in insert queries.

func Dec

func Dec(v int64) decreaseType

Dec decreases (or increases) a counter.

func DeleteRegistry

func DeleteRegistry()

Delete registry cleans the registry. This would be mainly used in unit testing.

func Inc

func Inc(v int64) increaseType

Inc increases (or decreases) a counter.

func Map

func Map(i interface{}) map[string]interface{}

Map creates a new map[string]interface{} where each member in the map is a reference to a field in the struct. This allows to assign values to a struct using gocql MapScan.

Given a gocql session, the following code will populate the struct 't' with the values in the datastore.

var t MyStruct
query := session.Query("select * from mytable where id = ?", "my-id")
m := cql.Map(&t)
err := query.MapScan(m)

func MustUUID

func MustUUID(input string) gocql.UUID

MustUUID parses a 32 digit hexadecimal number (that might contain hypens) representing an UUID. If panics if the UUID is invalid.

func Now

func Now() time.Time

Now returns the current local time rounded to milliseconds.

func Register

func Register(i interface{})

Register adds the passed struct to the registry to be able to use gocql MapScan methods with struct types.

It maps the columns using the struct tag 'cql' or the lowercase of the field name. You can skip the mapping of one field using the tag `cql:"-"`

Types

type Batch

type Batch interface {
	Add(s ...Statement) Batch
	Apply() error
	ApplyCAS() (bool, error)
}

func NewBatch

func NewBatch(sess *SessionImpl, typ gocql.BatchType) Batch

type BatchImpl

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

func (*BatchImpl) Add

func (b *BatchImpl) Add(s ...Statement) Batch

func (*BatchImpl) Apply

func (b *BatchImpl) Apply() error

func (*BatchImpl) ApplyCAS

func (b *BatchImpl) ApplyCAS() (bool, error)

type Column

type Column struct {
	Name     string
	Position int
}

Column contains the information of a column in a table required to create a map for it.

type Command

type Command int
const (
	SelectCmd Command = iota
	InsertCmd
	DeleteCmd
	UpdateCmd
	CountCmd
)

type Condition

type Condition struct {
	CQLFragment string
	Values      []interface{}
}

func And

func And(lhs Condition, list ...Condition) Condition

func Contains

func Contains(col string, v interface{}) Condition

Contains creates the condition 'col CONTAINS value' used to filter elements in a collection set, list, or map. Supported on CQL versions >= 3.2.0.

func ContainsKey

func ContainsKey(col string, v interface{}) Condition

Contains creates the condition 'col CONTAINS KEY value' used to filter elements by key in a map. Supported on CQL versions >= 3.2.0.

func Eq

func Eq(col string, v interface{}) Condition

func EqInt

func EqInt(i interface{}) Condition

EqInt takes is interested in the CQL indexes of the provided struct as a condition For convenience, that struct is assumed to follow the same rules as other mappings

func Ge

func Ge(col string, v interface{}) Condition

func Gt

func Gt(col string, v interface{}) Condition

func In

func In(col string, v ...interface{}) Condition

func Le

func Le(col string, v interface{}) Condition

func Lt

func Lt(col string, v interface{}) Condition

func Raw

func Raw(fragment string, v ...interface{}) Condition

Raw allows to set the CQLFrament and Values of a condition. It allows to add any not yet supported condition in a easy way.

Raw("token(partition_key) > token(?)", v.ID)
Raw("token(partition_key) > token('value')")
Raw("time > maxTimeuuid('2013-01-01 00:05+0000')")
Raw("time > maxTimeuuid(?) AND time < minTimeuuid(?)", maxTime, minTime)

func True

func True() Condition

type Iter

type Iter interface {
	TypeScan(i interface{}) bool
	Close() error
}

type IterImpl

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

func (*IterImpl) Close

func (it *IterImpl) Close() error

func (*IterImpl) TypeScan

func (it *IterImpl) TypeScan(i interface{}) bool

type OrderBy

type OrderBy struct {
	Column string
	OrderType
}

func Asc

func Asc(col string) OrderBy

func Desc

func Desc(col string) OrderBy

type OrderType

type OrderType string
const (
	AscOrder  OrderType = "ASC"
	DescOrder           = "DESC"
)

type PredicateType

type PredicateType int

type Session

type Session interface {
	Get(i interface{}, keys ...interface{}) error
	Set(i interface{}) error
	Del(i interface{}) error
	Exists(i interface{}) (bool, error)
	Select(i interface{}) Statement
	Insert(i interface{}) Statement
	Delete(i interface{}) Statement
	Update(i interface{}) Statement
	Count(i interface{}) Statement
	Batch() Batch
	Query(stmt string, args ...interface{}) *gocql.Query
}

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

func New

func New(s *gocql.Session) Session

New creates a ecql.Session from an already existent gocql.Session.

func NewSession

func NewSession(cfg gocql.ClusterConfig) (Session, error)

NewSession initializes a new ecql.Session with gocql.ConsterConfig.

type SessionImpl

type SessionImpl struct {
	*gocql.Session
}

func (*SessionImpl) Batch

func (s *SessionImpl) Batch() Batch

Batch initializes a new LOGGED BATCH to combine multiple data modification statements (INSERT, UPDATE, DELETE)

func (*SessionImpl) Count

func (s *SessionImpl) Count(i interface{}) Statement

Count initializes a SELECT COUNT(1) statement from the table defined by i.

func (*SessionImpl) Del

func (s *SessionImpl) Del(i interface{}) error

Del extecutes a delete statement on the table defined in i to remove the object i from the database.

func (*SessionImpl) Delete

func (s *SessionImpl) Delete(i interface{}) Statement

Select initializes an DELETE statement.

func (*SessionImpl) Exists

func (s *SessionImpl) Exists(i interface{}) (bool, error)

Exists executes a count statement on the table defined in i and returns if the object i exists in the database.

func (*SessionImpl) Get

func (s *SessionImpl) Get(i interface{}, keys ...interface{}) error

Get executes a SELECT statements on the table defined in i and sets the fields on i with the information present in the database.

func (*SessionImpl) Insert

func (s *SessionImpl) Insert(i interface{}) Statement

Select initializes an INSERT statement.

func (*SessionImpl) Select

func (s *SessionImpl) Select(i interface{}) Statement

Select initializes a SELECT statement.

func (*SessionImpl) Set

func (s *SessionImpl) Set(i interface{}) error

Set executes an INSERT statement on the the table defined in i and saves the information of i in the dtabase.

func (*SessionImpl) Update

func (s *SessionImpl) Update(i interface{}) Statement

Update initializes an UPDATE statement.

type Statement

type Statement interface {
	TypeScan() error
	Scan(i ...interface{}) error
	Exec() error
	Iter() Iter
	BuildQuery() (string, []interface{})
	Do(cmd Command) Statement
	From(table string) Statement
	FromType(i interface{}) Statement
	Columns(columns ...string) Statement
	Set(column string, value interface{}) Statement
	Where(cond ...Condition) Statement
	OrderBy(order ...OrderBy) Statement
	AllowFiltering() Statement
	IfExists() Statement
	IfNotExists() Statement
	Bind(i interface{}) Statement
	Map(i interface{}) Statement
	Limit(n int) Statement
	TTL(seconds int) Statement
	Timestamp(microseconds int64) Statement
}

func NewStatement

func NewStatement(sess *SessionImpl) Statement

type StatementImpl

type StatementImpl struct {
	Command             Command
	Table               Table
	ColumnNames         []string
	Conditions          *Condition
	Orders              []OrderBy
	Assignments         map[string]interface{}
	LimitValue          int
	TTLValue            int
	TimestampValue      int64
	AllowFilteringValue bool
	IfExistsValue       bool
	IfNotExistsValue    bool
	// contains filtered or unexported fields
}

func (*StatementImpl) AllowFiltering

func (s *StatementImpl) AllowFiltering() Statement

func (*StatementImpl) Bind

func (s *StatementImpl) Bind(i interface{}) Statement

func (*StatementImpl) BuildQuery

func (s *StatementImpl) BuildQuery() (string, []interface{})

BuildQuery returns the statement query and arguments that will be executed.

func (*StatementImpl) Columns

func (s *StatementImpl) Columns(columns ...string) Statement

Columns define a list of columns to get on SELECT statements, to set on UPDATE or INSERT statemets or to remove on DELETE statements.

func (*StatementImpl) Do

func (s *StatementImpl) Do(cmd Command) Statement

func (*StatementImpl) Exec

func (s *StatementImpl) Exec() error

Exec builds the query statement and executes it returning nil or the gocql error. On DELETE and UPDATE statements, the behavior of Exec differs from gocql if IfExists() is used, in this case, ecql will perform a ScanCAS and return ErrNotFound if the query was not applied.

func (*StatementImpl) From

func (s *StatementImpl) From(table string) Statement

func (*StatementImpl) FromType

func (s *StatementImpl) FromType(i interface{}) Statement

func (*StatementImpl) IfExists

func (s *StatementImpl) IfExists() Statement

func (*StatementImpl) IfNotExists

func (s *StatementImpl) IfNotExists() Statement

func (*StatementImpl) Iter

func (s *StatementImpl) Iter() Iter

func (*StatementImpl) Limit

func (s *StatementImpl) Limit(n int) Statement

func (*StatementImpl) Map

func (s *StatementImpl) Map(i interface{}) Statement

func (*StatementImpl) OrderBy

func (s *StatementImpl) OrderBy(order ...OrderBy) Statement

func (*StatementImpl) Scan

func (s *StatementImpl) Scan(i ...interface{}) error

func (*StatementImpl) Set

func (s *StatementImpl) Set(column string, value interface{}) Statement

Set allows to add a new Set to an UPDATE statement.

func (*StatementImpl) TTL

func (s *StatementImpl) TTL(seconds int) Statement

func (*StatementImpl) Timestamp

func (s *StatementImpl) Timestamp(microseconds int64) Statement

func (*StatementImpl) TypeScan

func (s *StatementImpl) TypeScan() error

func (*StatementImpl) Where

func (s *StatementImpl) Where(cond ...Condition) Statement

Where Conditionss are implicitly And with each other

type Table

type Table struct {
	Name       string
	KeyColumns []string
	Columns    []Column
}

Table contains the information of a table in cassandra.

func BindTable

func BindTable(i interface{}) ([]interface{}, map[string]interface{}, Table)

BindTables returns the values of i to bind in insert queries and the Table with the information about the type.

func GetTable

func GetTable(i interface{}) Table

GetTable returns the Table with the information about the type of i.

func MapTable

func MapTable(i interface{}) (map[string]interface{}, Table)

MapTable creates a new map[string]interface{} where each member in the map is a reference to a field in the struct. This allows to assign values to a struct using gocql MapScan. MapTable also returns the Table with the information about the type.

Given a gocql session, the following code will populate the struct 't' with the values in the datastore.

var t MyStruct
query := session.Query("select * from mytable where id = ?", "my-id")
m, _ := cql.MapTable(&t)
err := query.MapScan(m)

func (*Table) BuildQuery

func (t *Table) BuildQuery(qt queryType) (string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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