cqlx

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

cqlx

Build codecov GoDoc License

A productivity toolkit for Apache Cassandra on top of the upstream apache/cassandra-gocql-driver/v2 — named parameters, struct binding, a query builder, table CRUD and schema generation, all with no replace directives in your go.mod.

Status: alpha (v0.x). API tracks gocqlx 1:1 but the driver underneath is the upstream Apache one, not the Scylla fork. Expect occasional breakage as v2 of the Apache driver evolves.

Install

go get github.com/moguchev/cqlx@latest

Quickstart

Run Cassandra locally:

docker run --name cqlx-cassandra -p 9042:9042 --rm -d cassandra:5.0

Connect and use:

package main

import (
	"context"
	"log"

	"github.com/apache/cassandra-gocql-driver/v2"
	"github.com/moguchev/cqlx"
	"github.com/moguchev/cqlx/qb"
)

type Song struct {
	ID     gocql.UUID
	Title  string
	Album  string
	Artist string
}

func main() {
	cluster := gocql.NewCluster("127.0.0.1")
	cluster.Keyspace = "examples"
	cluster.Consistency = gocql.Quorum

	session, err := cqlx.WrapSession(cluster.CreateSession())
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	s := Song{ID: gocql.TimeUUID(), Title: "T", Album: "A", Artist: "X"}
	stmt, names := qb.Insert("songs").Columns("id", "title", "album", "artist").ToCql()
	if err := session.ContextQuery(context.Background(), stmt, names).BindStruct(s).ExecRelease(); err != nil {
		log.Fatal(err)
	}
}

Subpackages

  • cqlx — root: sessions, queries, iterators, batches, struct binding, UDT.
  • qb — fluent query builder for SELECT/INSERT/UPDATE/DELETE/BATCH.
  • table — table-scoped CRUD helpers built on qb.
  • dbutil — small helpers for keyspace/table introspection and rewrites.
  • cmd/schemagen — generates Go models from a live keyspace.
  • cqlxtest — test helpers used by the integration suite.

Compatibility

Every release is exercised by the Build workflow against the matrix below. A means both the unit suite (make test-unit) and the integration suite (make test, -tags all) pass on the listed configuration.

Overall CI status: Build

Cassandra image Driver Go OS CI job
cassandra:4.1 apache/cassandra-gocql-driver/v2 1.25 ubuntu-latest Integration (Cassandra 4.1)
cassandra:5.0 apache/cassandra-gocql-driver/v2 1.25 ubuntu-latest Integration (Cassandra 5.0)
ScyllaDB * apache/cassandra-gocql-driver/v2 not tested

* For Scylla, use the upstream scylladb/gocqlx — that's what cqlx is forked from. cqlx exists because gocqlx requires replace github.com/gocql/gocql => github.com/scylladb/gocql, which is incompatible with the upstream Apache driver.

To run the matrix locally:

CASSANDRA_IMAGE=cassandra:4.1 make test
CASSANDRA_IMAGE=cassandra:5.0 make test

Relationship to gocqlx

cqlx is a derivative work of scylladb/gocqlx. The public API matches 1:1 except for a handful of Scylla-only methods that are intentionally omitted (Query.{Get,Set}RequestTimeout, Batch.{Get,Set}RequestTimeout, Batch.SetHostID) and cmd/schemagen adjustments needed for upstream driver metadata. See docs/api-deltas.md and docs/relationship-to-gocqlx.md.

The migrate/ package from gocqlx is not ported.

License

Apache 2.0. See LICENSE and NOTICE.

Documentation

Overview

Package cqlx makes working with Cassandra and Scylla easy and error prone without sacrificing performance. It’s inspired by Sqlx, a tool for working with SQL databases, but it goes beyond what Sqlx provides.

cqlx is built on top of github.com/apache/cassandra-gocql-driver/v2 — the upstream Apache driver — and is a fork of github.com/scylladb/gocqlx with an identical public API.

For more details consult README.

Index

Examples

Constants

This section is empty.

Variables

DefaultMapper uses `db` tag and automatically converts struct field names to snake case. It can be set to whatever you want, but it is encouraged to be set before cqlx is used as name-to-field mappings are cached after first use on a type.

A custom mapper can always be set per Sessionm, Query and Iter.

View Source
var DefaultStrict bool

DefaultStrict disables the behavior of forcing queries and iterators to ignore missing fields for all queries. See Strict below for more information.

View Source
var UnsetEmptyTransformer = func(name string, val any) any {
	v := reflect.ValueOf(val)
	if v.IsZero() {
		return gocqlv2.UnsetValue
	}
	return val
}

UnsetEmptyTransformer unsets all empty parameters. It helps to avoid tombstones when using the same insert/update statement for filled and partially filled named parameters.

Functions

func CompileNamedQuery

func CompileNamedQuery(qs []byte) (stmt string, names []string, err error)

CompileNamedQuery translates query with named parameters in a form ':<identifier>' to query with '?' placeholders and a list of parameter names. If you need to use ':' in a query, i.e. with maps or UDTs use '::' instead.

func CompileNamedQueryString

func CompileNamedQueryString(qs string) (stmt string, names []string, err error)

CompileNamedQueryString translates query with named parameters in a form ':<identifier>' to query with '?' placeholders and a list of parameter names. If you need to use ':' in a query, i.e. with maps or UDTs use '::' instead.

Types

type Batch

type Batch struct {
	*gocqlv2.Batch
	// contains filtered or unexported fields
}

Batch is a wrapper around gocqlv2.Batch

func (*Batch) Bind

func (b *Batch) Bind(qry *Queryx, args ...any) error

Bind binds query parameters to values from args. If value cannot be found an error is reported.

func (*Batch) BindMap

func (b *Batch) BindMap(qry *Queryx, arg map[string]any) error

BindMap binds query named parameters to values from arg using a mapper. If value cannot be found an error is reported.

func (*Batch) BindStruct

func (b *Batch) BindStruct(qry *Queryx, arg any) error

BindStruct binds query named parameters to values from arg using a mapper. If value cannot be found an error is reported.

func (*Batch) BindStructMap

func (b *Batch) BindStructMap(qry *Queryx, arg0 any, arg1 map[string]any) error

BindStructMap binds query named parameters to values from arg0 and arg1 using a mapper. If value cannot be found an error is reported.

func (*Batch) Consistency

func (b *Batch) Consistency(c gocqlv2.Consistency) *Batch

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

func (*Batch) DefaultTimestamp

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

DefaultTimestamp will enable the with default timestamp flag on the query. If enabled, 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) Observer

func (b *Batch) Observer(observer gocqlv2.BatchObserver) *Batch

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

func (*Batch) Query

func (b *Batch) Query(stmt string, args ...any) *Batch

Query adds the query to the batch operation

func (*Batch) RetryPolicy

func (b *Batch) RetryPolicy(policy gocqlv2.RetryPolicy) *Batch

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

func (*Batch) SerialConsistency

func (b *Batch) SerialConsistency(cons gocqlv2.Consistency) *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) SetKeyspace

func (b *Batch) SetKeyspace(keyspace string) *Batch

SetKeyspace will enable per-batch keyspace override (Cassandra 5.0+).

func (*Batch) SpeculativeExecutionPolicy

func (b *Batch) SpeculativeExecutionPolicy(policy gocqlv2.SpeculativeExecutionPolicy) *Batch

SpeculativeExecutionPolicy sets the speculative execution policy to use when executing the batch operation

func (*Batch) Trace

func (b *Batch) Trace(trace gocqlv2.Tracer) *Batch

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

func (*Batch) WithContext

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

WithContext returns a copy of b with its context set to ctx. The context controls the entire lifetime of executing the batch: it will be canceled and return once the context is canceled.

Note: unlike gocqlx, the returned *Batch shares the underlying *gocql.Batch with the original — Apache v2 deprecated Batch.WithContext, and cqlx stores the context on the wrapper to keep the public API gocqlx-compatible. As a result, subsequent mutations (e.g. Query, RetryPolicy) on either copy are observed by both. See docs/api-deltas.md.

func (*Batch) WithNowInSeconds

func (b *Batch) WithNowInSeconds(now int) *Batch

WithNowInSeconds sets the "now" value (in seconds) used by the server to evaluate TTLs and write times for this batch. Available on protocol >= 5.

func (*Batch) WithTimestamp

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 Iterx

type Iterx struct {
	*gocqlv2.Iter
	Mapper *reflectx.Mapper
	// contains filtered or unexported fields
}

Iterx is a wrapper around gocqlv2.Iter which adds struct scanning capabilities.

func (*Iterx) Close

func (iter *Iterx) Close() error

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

func (*Iterx) Get

func (iter *Iterx) Get(dest any) error

Get scans first row into a destination and closes the iterator.

If the destination type is a struct pointer, then StructScan will be used. If the destination is some other type, then the row must only have one column which can scan into that type. This includes types that implement gocqlv2.Unmarshaler and gocqlv2.UDTUnmarshaler.

If you'd like to treat a type that implements gocqlv2.Unmarshaler or gocqlv2.UDTUnmarshaler as an ordinary struct you should call StructOnly().Get(dest) instead.

If no rows were selected, ErrNotFound is returned.

func (*Iterx) Scan

func (iter *Iterx) Scan(dest ...any) 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 (*Iterx) Select

func (iter *Iterx) Select(dest any) error

Select scans all rows into a destination, which must be a pointer to slice of any type, and closes the iterator.

If the destination slice type is a struct, then StructScan will be used on each row. If the destination is some other type, then each row must only have one column which can scan into that type. This includes types that implement gocqlv2.Unmarshaler and gocqlv2.UDTUnmarshaler.

If you'd like to treat a type that implements gocqlv2.Unmarshaler or gocqlv2.UDTUnmarshaler as an ordinary struct you should call StructOnly().Select(dest) instead.

If no rows were selected, ErrNotFound is NOT returned.

func (*Iterx) Strict

func (iter *Iterx) Strict() *Iterx

Strict forces the iterator to disable ignoring missing fields. In Strict mode when scanning a struct if result row has a column that cannot be mapped to any destination field an error is reported. By default such columns are ignored.

func (*Iterx) StructOnly

func (iter *Iterx) StructOnly() *Iterx

StructOnly forces the iterator to treat a single-argument struct as non-scannable. This is is useful if you need to scan a row into a struct that also implements gocqlv2.UDTUnmarshaler or in rare cases gocqlv2.Unmarshaler.

func (*Iterx) StructScan

func (iter *Iterx) StructScan(dest any) bool

StructScan is like gocqlv2.Iter.Scan, but scans a single row into a single struct. Use this and iterate manually when the memory load of Select() might be prohibitive. StructScan caches the reflect work of matching up column positions to fields to avoid that overhead per scan, which means it is not safe to run StructScan on the same Iterx instance with different struct types.

type Queryx

type Queryx struct {
	Mapper *reflectx.Mapper

	*gocqlv2.Query
	Names []string
	// contains filtered or unexported fields
}

Queryx is a wrapper around gocqlv2.Query which adds struct binding capabilities.

func Query deprecated

func Query(q *gocqlv2.Query, names []string) *Queryx

Query creates a new Queryx from gocqlv2.Query using a default mapper.

Deprecated: Use cqlx.Session.Query API instead.

func (*Queryx) Bind

func (q *Queryx) Bind(v ...any) *Queryx

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

func (*Queryx) BindMap

func (q *Queryx) BindMap(arg map[string]any) *Queryx

BindMap binds query named parameters using map.

func (*Queryx) BindStruct

func (q *Queryx) BindStruct(arg any) *Queryx

BindStruct binds query named parameters to values from arg using mapper. If value cannot be found error is reported.

func (*Queryx) BindStructMap

func (q *Queryx) BindStructMap(arg0 any, arg1 map[string]any) *Queryx

BindStructMap binds query named parameters to values from arg0 and arg1 using a mapper. If value cannot be found in arg0 it's looked up in arg1 before reporting an error.

func (*Queryx) Consistency

func (q *Queryx) Consistency(c gocqlv2.Consistency) *Queryx

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 (*Queryx) CustomPayload

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

CustomPayload sets the custom payload level for this query.

func (*Queryx) DefaultTimestamp

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

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 (*Queryx) Err

func (q *Queryx) Err() error

Err returns any binding errors.

func (*Queryx) Exec

func (q *Queryx) Exec() error

Exec executes the query without returning any rows.

func (*Queryx) ExecCAS

func (q *Queryx) ExecCAS() (applied bool, err error)

ExecCAS executes the Lightweight Transaction query, returns whether query was applied.

When using Cassandra it may be necessary to use NoSkipMetadata in order to obtain an accurate "applied" value. See the documentation of NoSkipMetaData method on this page for more details.

func (*Queryx) ExecCASRelease

func (q *Queryx) ExecCASRelease() (bool, error)

ExecCASRelease calls ExecCAS.

On Apache v2 the underlying driver releases query resources automatically, so this is equivalent to ExecCAS. The method is kept for API symmetry with gocqlx.

func (*Queryx) ExecRelease

func (q *Queryx) ExecRelease() error

ExecRelease calls Exec.

On Apache v2 the underlying driver releases query resources automatically, so this is equivalent to Exec. The method is kept for API symmetry with gocqlx.

func (*Queryx) Get

func (q *Queryx) Get(dest any) error

Get scans first row into a destination and closes the iterator.

If the destination type is a struct pointer, then Iter.StructScan will be used. If the destination is some other type, then the row must only have one column which can scan into that type. This includes types that implement gocqlv2.Unmarshaler and gocqlv2.UDTUnmarshaler.

If you'd like to treat a type that implements gocqlv2.Unmarshaler or gocqlv2.UDTUnmarshaler as an ordinary struct you should call Iter().StructOnly().Get(dest) instead.

If no rows were selected, ErrNotFound is returned.

func (*Queryx) GetCAS

func (q *Queryx) GetCAS(dest any) (applied bool, err error)

GetCAS executes a lightweight transaction. If the transaction fails because the existing values did not match, the previous values will be stored in dest object.

func (*Queryx) GetCASRelease

func (q *Queryx) GetCASRelease(dest any) (bool, error)

GetCASRelease calls GetCAS.

On Apache v2 the underlying driver releases query resources automatically, so this is equivalent to GetCAS. The method is kept for API symmetry with gocqlx.

func (*Queryx) GetRelease

func (q *Queryx) GetRelease(dest any) error

GetRelease calls Get.

On Apache v2 the underlying driver releases query resources automatically, so this is equivalent to Get. The method is kept for API symmetry with gocqlx.

func (*Queryx) Idempotent

func (q *Queryx) Idempotent(value bool) *Queryx

Idempotent marks the query as being idempotent or not depending on the value.

func (*Queryx) Iter

func (q *Queryx) Iter() *Iterx

Iter returns Iterx instance for the query. It should be used when data is too big to be loaded with Select in order to do row by row iteration. See Iterx StructScan function.

func (*Queryx) NoSkipMetadata

func (q *Queryx) NoSkipMetadata() *Queryx

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

func (*Queryx) Observer

func (q *Queryx) Observer(observer gocqlv2.QueryObserver) *Queryx

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

func (*Queryx) PageSize

func (q *Queryx) PageSize(n int) *Queryx

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 (*Queryx) PageState

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

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 (*Queryx) Prefetch

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

Prefetch 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 (*Queryx) RetryPolicy

func (q *Queryx) RetryPolicy(r gocqlv2.RetryPolicy) *Queryx

RetryPolicy sets the policy to use when retrying the query.

func (*Queryx) RoutingKey

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

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

func (*Queryx) Scan

func (q *Queryx) Scan(v ...any) 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 (*Queryx) Select

func (q *Queryx) Select(dest any) error

Select scans all rows into a destination, which must be a pointer to slice of any type, and closes the iterator.

If the destination slice type is a struct, then Iter.StructScan will be used on each row. If the destination is some other type, then each row must only have one column which can scan into that type. This includes types that implement gocqlv2.Unmarshaler and gocqlv2.UDTUnmarshaler.

If you'd like to treat a type that implements gocqlv2.Unmarshaler or gocqlv2.UDTUnmarshaler as an ordinary struct you should call Iter().StructOnly().Select(dest) instead.

If no rows were selected, ErrNotFound is NOT returned.

func (*Queryx) SelectRelease

func (q *Queryx) SelectRelease(dest any) error

SelectRelease calls Select.

On Apache v2 the underlying driver releases query resources automatically, so this is equivalent to Select. The method is kept for API symmetry with gocqlx.

func (*Queryx) SerialConsistency

func (q *Queryx) SerialConsistency(cons gocqlv2.SerialConsistency) *Queryx

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 (*Queryx) SetHostID

func (q *Queryx) SetHostID(hostID string) *Queryx

SetHostID allows to define the host the query should be executed against. If the host was filtered or otherwise unavailable, then the query will error. If an empty string is sent, the default behavior, using the configured HostSelectionPolicy will be used. A hostID can be obtained from HostInfo.HostID() after calling GetHosts().

func (*Queryx) SetKeyspace

func (q *Queryx) SetKeyspace(keyspace string) *Queryx

SetKeyspace will enable per-query keyspace override (Cassandra 5.0+).

func (*Queryx) SetSpeculativeExecutionPolicy

func (q *Queryx) SetSpeculativeExecutionPolicy(sp gocqlv2.SpeculativeExecutionPolicy) *Queryx

SetSpeculativeExecutionPolicy sets the execution policy.

func (*Queryx) Strict

func (q *Queryx) Strict() *Queryx

Strict forces the query and iterators to report an error if there are missing fields. By default when scanning a struct if result row has a column that cannot be mapped to any destination it is ignored. With strict error is reported.

func (*Queryx) Trace

func (q *Queryx) Trace(trace gocqlv2.Tracer) *Queryx

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

func (*Queryx) WithBindTransformer

func (q *Queryx) WithBindTransformer(tr Transformer) *Queryx

WithBindTransformer sets the query bind transformer. The transformer is called right before binding a value to a named parameter.

func (*Queryx) WithContext

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

WithContext stores ctx on q. The context controls the entire lifetime of executing a query: queries will be canceled and return once the context is canceled. Subsequent Exec/Iter/Scan call the underlying ExecContext/ IterContext/ScanContext driver methods with the stored context.

Note: unlike gocqlx, this does not create a shallow copy of the embedded *gocql.Query. Apache v2 deprecated Query.WithContext in favor of passing context at execution time; cqlx stores the context on the wrapper to keep the public API gocqlx-compatible. See docs/api-deltas.md.

func (*Queryx) WithNowInSeconds

func (q *Queryx) WithNowInSeconds(now int) *Queryx

WithNowInSeconds sets the "now" value (in seconds) used by the server to evaluate TTLs and write times for this query. Available on protocol >= 5.

func (*Queryx) WithTimestamp

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

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 Session

type Session struct {
	*gocqlv2.Session
	Mapper *reflectx.Mapper
}

Session wraps gocqlv2.Session and provides a modified Query function that returns Queryx instance. The original Session instance can be accessed as Session. The default mapper uses `db` tag and automatically converts struct field names to snake case. If needed package reflectx provides constructors for other types of mappers.

Example
package main

import (
	gocqlv2 "github.com/apache/cassandra-gocql-driver/v2"

	"github.com/moguchev/cqlx"
	"github.com/moguchev/cqlx/qb"
)

func main() {
	cluster := gocqlv2.NewCluster("host")
	session, err := cqlx.WrapSession(cluster.CreateSession())
	if err != nil {
		// handle error
	}

	builder := qb.Select("foo")
	session.Query(builder.ToCql())
}

func NewSession

func NewSession(session *gocqlv2.Session) Session

NewSession wraps existing gocqlv2.session.

func WrapSession

func WrapSession(session *gocqlv2.Session, err error) (Session, error)

WrapSession should be called on CreateSession() gocql function to convert the created session to cqlx.Session.

Example:

session, err := cqlx.WrapSession(cluster.CreateSession())

func (*Session) Batch

func (s *Session) Batch(bt gocqlv2.BatchType) *Batch

Batch creates a new batch operation using defaults defined in the cluster.

func (*Session) ContextBatch

func (s *Session) ContextBatch(ctx context.Context, bt gocqlv2.BatchType) *Batch

ContextBatch creates a new batch operation using defaults defined in the cluster with attached context.

func (Session) ContextQuery

func (s Session) ContextQuery(ctx context.Context, stmt string, names []string) *Queryx

ContextQuery is a helper function that allows to pass context when creating a query, see the "Query" function .

func (Session) ExecStmt

func (s Session) ExecStmt(stmt string) error

ExecStmt creates query and executes the given statement.

func (*Session) ExecuteBatch

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

ExecuteBatch executes a batch operation and returns nil if successful otherwise an error describing the failure.

func (*Session) ExecuteBatchCAS

func (s *Session) ExecuteBatchCAS(batch *Batch, dest ...any) (applied bool, iter *gocqlv2.Iter, err error)

ExecuteBatchCAS executes a batch operation and returns true if successful and an iterator (to scan additional 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) MapExecuteBatchCAS

func (s *Session) MapExecuteBatchCAS(batch *Batch, dest map[string]any) (applied bool, iter *gocqlv2.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 deprecated

func (s *Session) NewBatch(bt gocqlv2.BatchType) *Batch

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

Deprecated: use session.Batch instead

func (Session) Query

func (s Session) Query(stmt string, names []string) *Queryx

Query creates a new Queryx using the session mapper. The stmt and names parameters are typically result of a query builder (package qb) ToCql() function or come from table model (package table). The names parameter is a list of query parameters' names and it's used for binding.

type Transformer

type Transformer func(name string, val any) any

Transformer transforms the value of the named parameter to another value.

var DefaultBindTransformer Transformer

DefaultBindTransformer just do nothing.

A custom transformer can always be set per Query.

type UDT

type UDT interface {
	// contains filtered or unexported methods
}

UDT is a marker interface that needs to be embedded in a struct if you want to marshal or unmarshal it as a User Defined Type.

Example
package main

import (
	"github.com/moguchev/cqlx"
)

func main() {
	// Just add cqlx.UDT to a type, no need to implement marshalling functions
	type FullName struct {
		cqlx.UDT
		FirstName string
		LastName  string
	}

	_ = FullName{}
}
Example (Wraper)
package main

import (
	"github.com/moguchev/cqlx"
)

func main() {
	type FullName struct {
		FirstName string
		LastName  string
	}

	// Create new UDT wrapper type
	type FullNameUDT struct {
		cqlx.UDT
		*FullName
	}

	_ = FullNameUDT{}
}

Directories

Path Synopsis
cmd
schemagen command
Package cqlxtest provides test helpers for integration tests.
Package cqlxtest provides test helpers for integration tests.
Package dbutil provides various utilities built on top of core cqlx modules.
Package dbutil provides various utilities built on top of core cqlx modules.
Package qb provides CQL query builders.
Package qb provides CQL query builders.
Package table adds support for super simple CRUD operations based on table model.
Package table adds support for super simple CRUD operations based on table model.

Jump to

Keyboard shortcuts

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