cbcolumnar

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

Couchbase Go Columnar Client

Go client for Couchbase Columnar

Documentation

You can explore our API reference through godoc at https://pkg.go.dev/github.com/couchbase/gocbcolumnar.

You can also find documentation for the Go Columnar SDK on the official Couchbase docs.

Installing

To install the latest stable version, run:

go get github.com/couchbase/gocbcolumnar@latest

To install the latest developer version, run:

go get github.com/couchbase/gocbcolumnar@main

Getting Started

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/couchbaselabs/gocbcolumnar"
)

func main() {
	const (
		connStr  = "couchbases://..."
		username = "..."
		password = "..."
	)
	
	cluster, err := cbcolumnar.NewCluster(
		connStr,
		cbcolumnar.NewCredential(username, password),
		// The third parameter is optional.
		// This example sets the default server query timeout to 3 minutes,
		// that is the timeout value sent to the query server.
		cbcolumnar.NewClusterOptions().SetTimeoutOptions(
			cbcolumnar.NewTimeoutOptions().SetQueryTimeout(3*time.Minute),
		),
	)
	handleErr(err)

	// We create a new context with a timeout of 2 minutes.
	// This context will apply timeout/cancellation on the client side.
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	printRows := func(result *cbcolumnar.QueryResult) {
		for row := result.NextRow(); row != nil; row = result.NextRow() {
			var content map[string]interface{}

			err = row.ContentAs(&content)
			handleErr(err)

			fmt.Printf("Got row content: %v", content)
		}
	}

	// Execute a query and process rows as they arrive from server.
	// Results are always streamed from the server.
	result, err := cluster.ExecuteQuery(ctx, "select 1")
	handleErr(err)

	printRows(result)

	// Execute a query with positional arguments.
	result, err = cluster.ExecuteQuery(
		ctx,
		"select ?=1",
		cbcolumnar.NewQueryOptions().SetPositionalParameters([]interface{}{1}),
	)
	handleErr(err)

	printRows(result)

	// Execute a query with named arguments.
	result, err = cluster.ExecuteQuery(
		ctx,
		"select $foo=1",
		cbcolumnar.NewQueryOptions().SetNamedParameters(map[string]interface{}{"foo": 1}),
	)
	handleErr(err)

	printRows(result)

	err = cluster.Close()
	handleErr(err)
}

func handleErr(err error) {
	if err != nil {
		panic(err)
	}
}

Testing

You can run tests in the usual Go way:

go test -race ./... --connstr couchbases://... --username ... --password ... --database ... --scope ...

Which will execute tests against the specified Columnar instance. See the testmain_test.go file for more information on command line arguments.

Linting

Linting is performed used golangci-lint. To run:

golangci-lint run

License

Copyright 2025 Couchbase Inc.

Licensed under the Apache License, Version 2.0.

See LICENSE for further details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("closed")

ErrClosed occurs when an entity was used after it was closed.

View Source
var ErrColumnar = errors.New("columnar error")

ErrColumnar is the base error for any Columnar error that is not captured by a more specific error.

View Source
var ErrInvalidArgument = errors.New("invalid argument")

ErrInvalidArgument occurs when an invalid argument is provided to a function.

View Source
var ErrInvalidCredential = errors.New("invalid credential")

ErrInvalidCredential occurs when invalid credentials are provided leading to errors in things like authentication.

View Source
var ErrQuery = errors.New("query error")

ErrQuery occurs when a server error is encountered while executing a query, excluding errors that caught by ErrInvalidCredential or ErrTimeout.

View Source
var ErrTimeout = errors.New("timeout error")

ErrTimeout occurs when a timeout is reached while waiting for a response. This is returned when a server timeout occurs, or an operation fails to be sent within the dispatch timeout.

View Source
var ErrUnmarshal = errors.New("unmarshalling error")

ErrUnmarshal occurs when an entity could not be unmarshalled.

Functions

func Identifier

func Identifier() string

Identifier returns a string representation of the current SDK identifier.

func SetLogRedactionLevel

func SetLogRedactionLevel(level LogRedactLevel)

SetLogRedactionLevel specifies the level with which logs should be redacted.

func SetLogger

func SetLogger(logger Logger)

SetLogger sets a logger to be used by the library. A logger can be obtained via the DefaultStdioLogger() or VerboseStdioLogger() functions. You can also implement your own logger using the Logger interface.

func Version

func Version() string

Version returns a string representation of the current SDK version.

Types

type Cluster

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

Cluster is the main entry point for the SDK. It is used to perform operations on the data against a Couchbase Columnar cluster.

func NewCluster

func NewCluster(connStr string, credential Credential, opts ...*ClusterOptions) (*Cluster, error)

NewCluster creates a new Cluster instance.

func (*Cluster) Close

func (c *Cluster) Close() error

Close shuts down the cluster and releases all resources.

func (*Cluster) Database

func (c *Cluster) Database(name string) *Database

Database creates a new Database instance.

func (*Cluster) ExecuteQuery

func (c *Cluster) ExecuteQuery(ctx context.Context, statement string, opts ...*QueryOptions) (*QueryResult, error)

ExecuteQuery executes the query statement on the server. When ExecuteQuery is called with no context.Context, or a context.Context with no Deadline, then the Cluster level QueryTimeout will be applied.

type ClusterOptions

type ClusterOptions struct {
	// TimeoutOptions specifies various operation timeouts.
	TimeoutOptions *TimeoutOptions

	// SecurityOptions specifies security related configuration options.
	SecurityOptions *SecurityOptions

	// Unmarshaler specifies the default unmarshaler to use for decoding query response rows.
	Unmarshaler Unmarshaler
}

ClusterOptions specifies options for configuring the cluster.

func NewClusterOptions

func NewClusterOptions() *ClusterOptions

NewClusterOptions creates a new instance of ClusterOptions.

func (*ClusterOptions) SetSecurityOptions

func (co *ClusterOptions) SetSecurityOptions(securityOptions *SecurityOptions) *ClusterOptions

SetSecurityOptions sets the SecurityOptions field in ClusterOptions.

func (*ClusterOptions) SetTimeoutOptions

func (co *ClusterOptions) SetTimeoutOptions(timeoutOptions *TimeoutOptions) *ClusterOptions

SetTimeoutOptions sets the TimeoutOptions field in ClusterOptions.

func (*ClusterOptions) SetUnmarshaler

func (co *ClusterOptions) SetUnmarshaler(unmarshaler Unmarshaler) *ClusterOptions

SetUnmarshaler sets the Unmarshaler field in ClusterOptions.

type ColumnarError

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

ColumnarError occurs when an error is encountered while interacting with the Columnar service.

func (ColumnarError) Error

func (e ColumnarError) Error() string

Error returns the string representation of a Columnar error.

func (ColumnarError) Unwrap

func (e ColumnarError) Unwrap() error

Unwrap returns the underlying reason for the error.

type Credential

type Credential struct {
	UsernamePassword *UserPassPair
}

Credential provides a way to specify credentials to the SDK.

func NewCredential

func NewCredential(username, password string) Credential

NewCredential creates a new Credential with the specified username and password.

type Database

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

Database represents a Columnar database and provides access to Scope.

func (*Database) Name

func (d *Database) Name() string

Name returns the name of the Database.

func (*Database) Scope

func (d *Database) Scope(name string) *Scope

Scope creates a new Scope instance.

type JSONUnmarshaler

type JSONUnmarshaler struct{}

JSONUnmarshaler is an Unmarshaler that performs JSON unmarshalling.

func NewJSONUnmarshaler

func NewJSONUnmarshaler() *JSONUnmarshaler

NewJSONUnmarshaler creates a new JSONUnmarshaler.

func (*JSONUnmarshaler) Unmarshal

func (ju *JSONUnmarshaler) Unmarshal(data []byte, v interface{}) error

Unmarshal unmarshals the data into the provided value.

type LogLevel

type LogLevel gocbcore.LogLevel

LogLevel specifies the severity of a log message.

const (
	LogError        LogLevel = LogLevel(gocbcore.LogError)
	LogWarn         LogLevel = LogLevel(gocbcore.LogWarn)
	LogInfo         LogLevel = LogLevel(gocbcore.LogInfo)
	LogDebug        LogLevel = LogLevel(gocbcore.LogDebug)
	LogTrace        LogLevel = LogLevel(gocbcore.LogTrace)
	LogSched        LogLevel = LogLevel(gocbcore.LogSched)
	LogMaxVerbosity LogLevel = LogLevel(gocbcore.LogMaxVerbosity)
)

Various logging levels (or subsystems) which can categorize the message. Currently these are ordered in decreasing severity.

type LogRedactLevel

type LogRedactLevel uint

LogRedactLevel specifies the degree with which to redact the logs.

const (
	// RedactNone indicates to perform no redactions
	RedactNone LogRedactLevel = iota

	// RedactPartial indicates to redact all possible user-identifying information from logs.
	RedactPartial

	// RedactFull indicates to fully redact all possible identifying information from logs.
	RedactFull
)

type Logger

type Logger interface {
	// Log Outputs logging information:
	// level is the verbosity level
	// offset is the position within the calling stack from which the message
	// originated. This is useful for contextual loggers which retrieve file/line
	// information.
	Log(level LogLevel, offset int, format string, v ...interface{}) error
}

Logger defines a logging interface. You can either use one of the default loggers (DefaultStdioLogger(), VerboseStdioLogger()) or implement your own.

func DefaultStdioLogger

func DefaultStdioLogger() Logger

DefaultStdioLogger gets the default standard I/O logger.

gocb.SetLogger(gocb.DefaultStdioLogger())

func VerboseStdioLogger

func VerboseStdioLogger() Logger

VerboseStdioLogger is a more verbose level of DefaultStdioLogger(). Messages pertaining to the scheduling of ordinary commands (and their responses) will also be emitted.

gocb.SetLogger(gocb.VerboseStdioLogger())

type QueryError

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

QueryError occurs when an error is returned in the errors field of the response body of a response from the query server.

func (QueryError) Code

func (e QueryError) Code() int

Code returns the error code from the server for this error.

func (QueryError) Error

func (e QueryError) Error() string

Error returns the string representation of a query error.

func (QueryError) Message

func (e QueryError) Message() string

Message returns the error message from the server for this error.

func (QueryError) Unwrap

func (e QueryError) Unwrap() error

Unwrap returns the underlying reason for the error.

type QueryMetadata

type QueryMetadata struct {
	RequestID string
	Metrics   QueryMetrics
	Warnings  []QueryWarning
}

QueryMetadata provides access to the meta-data properties of a query result.

func BufferQueryResult

func BufferQueryResult[T any](result *QueryResult) ([]T, *QueryMetadata, error)

BufferQueryResult will buffer all rows in the result set into memory and return them as a slice, with any metadata.

type QueryMetrics

type QueryMetrics struct {
	ElapsedTime      time.Duration
	ExecutionTime    time.Duration
	ResultCount      uint64
	ResultSize       uint64
	ProcessedObjects uint64
}

QueryMetrics encapsulates various metrics gathered during a queries execution.

type QueryOptions

type QueryOptions struct {
	// Priority sets whether this query should be assigned as high priority by the analytics engine.
	Priority *bool

	// PositionalParameters sets any positional placeholder parameters for the query.
	PositionalParameters []interface{}

	// NamedParameters sets any positional placeholder parameters for the query.
	NamedParameters map[string]interface{}

	// ReadOnly sets whether this query should be read-only.
	ReadOnly *bool

	// ScanConsistency specifies the level of data consistency required for this query.
	ScanConsistency *QueryScanConsistency

	// Raw provides a way to provide extra parameters in the request body for the query.
	Raw map[string]interface{}

	// Unmarshaler specifies the default unmarshaler to use for decoding rows from this query.
	Unmarshaler Unmarshaler
}

QueryOptions is the set of options available to an Analytics query.

func NewQueryOptions

func NewQueryOptions() *QueryOptions

NewQueryOptions creates a new instance of QueryOptions.

func (*QueryOptions) SetNamedParameters

func (opts *QueryOptions) SetNamedParameters(params map[string]interface{}) *QueryOptions

SetNamedParameters sets the NamedParameters field in QueryOptions.

func (*QueryOptions) SetPositionalParameters

func (opts *QueryOptions) SetPositionalParameters(params []interface{}) *QueryOptions

SetPositionalParameters sets the PositionalParameters field in QueryOptions.

func (*QueryOptions) SetPriority

func (opts *QueryOptions) SetPriority(priority bool) *QueryOptions

SetPriority sets the Priority field in QueryOptions.

func (*QueryOptions) SetRaw

func (opts *QueryOptions) SetRaw(raw map[string]interface{}) *QueryOptions

SetRaw sets the Raw field in QueryOptions.

func (*QueryOptions) SetReadOnly

func (opts *QueryOptions) SetReadOnly(readOnly bool) *QueryOptions

SetReadOnly sets the ReadOnly field in QueryOptions.

func (*QueryOptions) SetScanConsistency

func (opts *QueryOptions) SetScanConsistency(scanConsistency QueryScanConsistency) *QueryOptions

SetScanConsistency sets the ScanConsistency field in QueryOptions.

func (*QueryOptions) SetUnmarshaler

func (opts *QueryOptions) SetUnmarshaler(unmarshaler Unmarshaler) *QueryOptions

SetUnmarshaler sets the Unmarshaler field in QueryOptions.

type QueryResult

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

QueryResult allows access to the results of a query.

func (*QueryResult) Err

func (r *QueryResult) Err() error

Err returns any errors that have occurred on the stream.

func (*QueryResult) MetaData

func (r *QueryResult) MetaData() (*QueryMetadata, error)

MetaData returns any meta-data that was available from this query. Note that the meta-data will only be available once the object has been closed (either implicitly or explicitly).

func (*QueryResult) NextRow

func (r *QueryResult) NextRow() *QueryResultRow

NextRow returns the next row in the result set, or nil if there are no more rows.

type QueryResultRow

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

QueryResultRow encapsulates a single row of a query result.

func (*QueryResultRow) ContentAs

func (qrr *QueryResultRow) ContentAs(valuePtr any) error

ContentAs will attempt to unmarshal the content of the row into the provided value pointer.

type QueryScanConsistency

type QueryScanConsistency uint

QueryScanConsistency indicates the level of data consistency desired for an analytics query.

const (
	// QueryScanConsistencyNotBounded indicates no data consistency is required.
	QueryScanConsistencyNotBounded QueryScanConsistency = iota + 1
	// QueryScanConsistencyRequestPlus indicates that request-level data consistency is required.
	QueryScanConsistencyRequestPlus
)

type QueryWarning

type QueryWarning struct {
	Code    uint32
	Message string
}

QueryWarning encapsulates any warnings returned by a query.

type Scope

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

Scope represents a Columnar scope.

func (*Scope) ExecuteQuery

func (s *Scope) ExecuteQuery(ctx context.Context, statement string, opts ...*QueryOptions) (*QueryResult, error)

ExecuteQuery executes the query statement on the server, tying the query context to this Scope. When ExecuteQuery is called with no context.Context, or a context.Context with no Deadline, then the Cluster level QueryTimeout will be applied.

func (*Scope) Name

func (s *Scope) Name() string

Name returns the name of the Scope.

type SecurityOptions

type SecurityOptions struct {
	// TrustOnly specifies the trust mode to use within the SDK.
	TrustOnly TrustOnly

	// DisableServerCertificateVerification when specified causes the SDK to trust ANY certificate
	// regardless of validity.
	DisableServerCertificateVerification *bool

	// CipherSuites specifies the TLS cipher suites the SDK is allowed to use when negotiating TLS
	// settings, or an empty list to use any cipher suite supported by the runtime environment.
	// See: https://go.dev/src/crypto/tls/cipher_suites.go
	CipherSuites []string
}

SecurityOptions specifies options for controlling security related items such as TLS root certificates and verification skipping.

func NewSecurityOptions

func NewSecurityOptions() *SecurityOptions

NewSecurityOptions creates a new instance of SecurityOptions.

func (*SecurityOptions) SetCipherSuites

func (opts *SecurityOptions) SetCipherSuites(cipherSuites []string) *SecurityOptions

SetCipherSuites sets the CipherSuites field in SecurityOptions.

func (*SecurityOptions) SetDisableServerCertificateVerification

func (opts *SecurityOptions) SetDisableServerCertificateVerification(disabled bool) *SecurityOptions

SetDisableServerCertificateVerification sets the DisableServerCertificateVerification field in SecurityOptions.

func (*SecurityOptions) SetTrustOnly

func (opts *SecurityOptions) SetTrustOnly(trustOnly TrustOnly) *SecurityOptions

SetTrustOnly sets the TrustOnly field in SecurityOptions.

type TimeoutOptions

type TimeoutOptions struct {
	// ConnectTimeout specifies the socket connection timeout, or more broadly the timeout
	// for establishing an individual authenticated connection.
	// Default = 10 seconds
	ConnectTimeout *time.Duration

	// QueryTimeout specifies the default amount of time to spend executing a query before timing it out.
	// This value is only used if the context.Context at the operation level does not specify a deadline.
	// Default = 10 minutes
	QueryTimeout *time.Duration
}

TimeoutOptions specifies options for various operation timeouts.

func NewTimeoutOptions

func NewTimeoutOptions() *TimeoutOptions

NewTimeoutOptions creates a new instance of TimeoutOptions.

func (*TimeoutOptions) SetConnectTimeout

func (opts *TimeoutOptions) SetConnectTimeout(timeout time.Duration) *TimeoutOptions

SetConnectTimeout sets the ConnectTimeout field in TimeoutOptions.

func (*TimeoutOptions) SetQueryTimeout

func (opts *TimeoutOptions) SetQueryTimeout(timeout time.Duration) *TimeoutOptions

SetQueryTimeout sets the QueryTimeout field in TimeoutOptions.

type TrustOnly

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

TrustOnly specifies the trust mode to use within the SDK.

type TrustOnlyCapella

type TrustOnlyCapella struct{}

TrustOnlyCapella tells the SDK to trust only the Capella CA certificate(s) bundled with the SDK. This is the default behavior.

type TrustOnlyCertificates

type TrustOnlyCertificates struct {
	Certificates *x509.CertPool
}

TrustOnlyCertificates tells the SDK to trust only the specified certificates.

type TrustOnlyPemFile

type TrustOnlyPemFile struct {
	Path string
}

TrustOnlyPemFile tells the SDK to trust only the PEM-encoded certificate(s) in the file at the given FS path.

type TrustOnlyPemString

type TrustOnlyPemString struct {
	Pem string
}

TrustOnlyPemString tells the SDK to trust only the PEM-encoded certificate(s) in the given string.

type TrustOnlySystem

type TrustOnlySystem struct{}

TrustOnlySystem tells the SDK to trust only the certificates trusted by the system cert pool.

type Unmarshaler

type Unmarshaler interface {
	// Unmarshal unmarshals the data into the provided value.
	Unmarshal([]byte, interface{}) error
}

Unmarshaler provides a way to unmarshal data into a Go value.

type UserPassPair

type UserPassPair struct {
	Username string
	Password string
}

UserPassPair represents a username and password pair.

Directories

Path Synopsis
internal
leakcheck
Package leakcheck provides utilities for detecting and reporting goroutine leaks in Go applications.
Package leakcheck provides utilities for detecting and reporting goroutine leaks in Go applications.

Jump to

Keyboard shortcuts

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