Thanks to visit codestin.com
Credit goes to pkg.go.dev

cbanalytics

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2025 License: Apache-2.0 Imports: 14 Imported by: 0

README

Couchbase Go Analytics Client

Go client for Couchbase Analytics.

Documentation

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

Installing

To install the latest stable version, run:

go get github.com/couchbase/gocbanalytics@latest

To install the latest developer version, run:

go get github.com/couchbase/gocbanalytics@main

Getting Started

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/couchbase/gocbanalytics"
)

func main() {
	const (
		connStr  = "couchbases://..."
		username = "..."
		password = "..."
	)
	
	cluster, err := cbanalytics.NewCluster(
		connStr,
		cbanalytics.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.
		cbanalytics.NewClusterOptions().SetTimeoutOptions(
			cbanalytics.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 *cbanalytics.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",
		cbanalytics.NewQueryOptions().SetPositionalParameters([]interface{}{1}),
	)
	handleErr(err)

	printRows(result)

	// Execute a query with named arguments.
	result, err = cluster.ExecuteQuery(
		ctx,
		"select $foo=1",
		cbanalytics.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 Analytics 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

View Source
const (
	LogError = LogLevel(logging.LogError)
	LogWarn  = LogLevel(logging.LogWarn)
	LogInfo  = LogLevel(logging.LogInfo)
	LogDebug = LogLevel(logging.LogDebug)
	LogTrace = LogLevel(logging.LogTrace)
)

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

Variables

View Source
var ErrAnalytics = errors.New("analytics error")

ErrAnalytics is the base error for any Analytics error that is not captured by a more specific error.

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

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

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 ErrServiceUnavailable = errors.New("service unavailable")

ErrServiceUnavailable occurs when the Analytics service, or a part of the system in the path to it, is unavailable.

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 Version

func Version() string

Version returns a string representation of the current SDK version.

Types

type AnalyticsError

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

AnalyticsError occurs when an error is encountered while interacting with the Analytics service.

func (AnalyticsError) Error

func (e AnalyticsError) Error() string

Error returns the string representation of an Analytics error.

func (AnalyticsError) Unwrap

func (e AnalyticsError) Unwrap() error

Unwrap returns the underlying reason for the error.

type BasicAuthCredential

type BasicAuthCredential struct {
	UserPassPair UserPassPair
}

BasicAuthCredential provides a way to authenticate using username and password.

func NewBasicAuthCredential

func NewBasicAuthCredential(username, password string) *BasicAuthCredential

NewBasicAuthCredential creates a new BasicAuthCredential with the specified username and password.

func (*BasicAuthCredential) Credentials

func (u *BasicAuthCredential) Credentials() UserPassPair

Credentials returns the UserPassPair for BasicAuthCredential.

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 Analytics cluster.

func NewCluster

func NewCluster(httpEndpoint 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

	// Logger specifies the logger to use for logging.
	Logger Logger

	// MaxRetries specifies the maximum number of retries that a query will be attempted.
	// This includes connection attempts.
	// VOLATILE: This API is subject to change at any time.
	MaxRetries *uint32
}

ClusterOptions specifies options for configuring the cluster.

func NewClusterOptions

func NewClusterOptions() *ClusterOptions

NewClusterOptions creates a new instance of ClusterOptions.

func (*ClusterOptions) SetLogger

func (co *ClusterOptions) SetLogger(logger Logger) *ClusterOptions

SetLogger sets the Logger field in ClusterOptions.

func (*ClusterOptions) SetMaxRetries

func (co *ClusterOptions) SetMaxRetries(maxRetries uint32) *ClusterOptions

SetMaxRetries sets the MaxRetries field in ClusterOptions. VOLATILE: This API is subject to change at any time.

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 Credential

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

Credential provides a way to authenticate with the server.

type Database

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

Database represents an Analytics 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 DynamicBasicAuthCredential

type DynamicBasicAuthCredential struct {
	Provider func() UserPassPair
}

DynamicBasicAuthCredential provides a way to authenticate using a dynamic username and password.

func NewDynamicBasicAuthCredential

func NewDynamicBasicAuthCredential(provider func() UserPassPair) *DynamicBasicAuthCredential

NewDynamicBasicAuthCredential creates a new DynamicBasicAuthCredential with the specified provider function.

func (*DynamicBasicAuthCredential) Credentials

func (u *DynamicBasicAuthCredential) Credentials() UserPassPair

type InfoLogger

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

InfoLogger logs to stderr with a level of LogInfo.

func NewInfoLogger

func NewInfoLogger() *InfoLogger

NewInfoLogger creates a new InfoLogger instance.

func (InfoLogger) Debug

func (b InfoLogger) Debug(format string, v ...interface{})

func (InfoLogger) Error

func (b InfoLogger) Error(format string, v ...interface{})

func (InfoLogger) Info

func (b InfoLogger) Info(format string, v ...interface{})

func (InfoLogger) Trace

func (b InfoLogger) Trace(format string, v ...interface{})

func (InfoLogger) Warn

func (b InfoLogger) Warn(format string, v ...interface{})

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 int

LogLevel specifies the severity of a log message.

type Logger

type Logger interface {
	// Error outputs an error level log message.
	Error(format string, v ...interface{})

	// Warn outputs an warn level log message.
	Warn(format string, v ...interface{})

	// Info outputs an info level log message.
	Info(format string, v ...interface{})

	// Debug outputs a debug level error log message.
	Debug(format string, v ...interface{})

	// Trace outputs a trace level error log message.
	Trace(format string, v ...interface{})
}

Logger defines a logging interface.

type NoopLogger

type NoopLogger struct {
}

NoopLogger is a no-operation logger that ignores all log messages. This is equivalent to specifying Logger on ClusterOptions as nil.

func NewNoopLogger

func NewNoopLogger() *NoopLogger

NewNoopLogger creates a new NoopLogger instance.

func (NoopLogger) Debug

func (n NoopLogger) Debug(_ string, _ ...interface{})

func (NoopLogger) Error

func (n NoopLogger) Error(_ string, _ ...interface{})

func (NoopLogger) Info

func (n NoopLogger) Info(_ string, _ ...interface{})

func (NoopLogger) Trace

func (n NoopLogger) Trace(_ string, _ ...interface{})

func (NoopLogger) Warn

func (n NoopLogger) Warn(_ string, _ ...interface{})

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 {
	// ClientContextID is an optional identifier for the query.
	ClientContextID *string

	// 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

	// MaxRetries specifies the maximum number of retries that a query will be attempted.
	// This includes connection attempts.
	// VOLATILE: This API is subject to change at any time.
	MaxRetries *uint32
}

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

func (opts *QueryOptions) SetClientContextID(clientContextID string) *QueryOptions

func (*QueryOptions) SetMaxRetries

func (opts *QueryOptions) SetMaxRetries(maxRetries uint32) *QueryOptions

SetMaxRetries sets the MaxRetries field in QueryOptions. VOLATILE: This API is subject to change at any time.

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) 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 an Analytics 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
}

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

type VerboseLogger

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

VerboseLogger logs to stderr with a level of LogTrace.

func NewVerboseLogger

func NewVerboseLogger() *VerboseLogger

NewVerboseLogger creates a new VerboseLogger instance.

func (VerboseLogger) Debug

func (b VerboseLogger) Debug(format string, v ...interface{})

func (VerboseLogger) Error

func (b VerboseLogger) Error(format string, v ...interface{})

func (VerboseLogger) Info

func (b VerboseLogger) Info(format string, v ...interface{})

func (VerboseLogger) Trace

func (b VerboseLogger) Trace(format string, v ...interface{})

func (VerboseLogger) Warn

func (b VerboseLogger) Warn(format string, v ...interface{})

Directories

Path Synopsis
internal
httpqueryclient
Package httpqueryclient implements an HTTP client for making requests against a server.
Package httpqueryclient implements an HTTP client for making requests against a server.
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