n1qlizer

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2025 License: MIT Imports: 10 Imported by: 0

README

n1qlizer - Fluent Couchbase N1QL Query Generator for Go

Go Reference

Overview

n1qlizer is a fluent query builder for Couchbase's N1QL language, inspired by Squirrel. It helps you build N1QL queries from composable parts using a clean, readable syntax.

Instead of concatenating strings or using complex template engines, n1qlizer lets you build queries programmatically, making them more maintainable and less error-prone. It handles parameter placeholders, escaping, and query composition while providing Couchbase-specific features not found in standard SQL builders.

Key benefits:

  • Type-safe, fluent API for building N1QL queries
  • Generic types for improved type safety (Go 1.18+)
  • Automatic parameter binding and placeholder generation
  • Support for all major N1QL operations (SELECT, INSERT, UPDATE, DELETE, UPSERT)
  • Integration with Couchbase-specific features (USE KEYS, NEST/UNNEST, FTS, etc.)
  • Ability to execute queries directly with the Couchbase SDK

Installation & Setup

Prerequisites
  • Go 1.18 or higher
  • A Couchbase database (for executing queries)
Installing the Package
go get github.com/ceylanomer/n1qlizer
Import in Your Project
import "github.com/ceylanomer/n1qlizer"

Go 1.18+ Features

n1qlizer fully leverages Go 1.18 features:

Generics

The library uses generics extensively to provide type safety throughout all operations:

// Type-safe list creation
userList := n1qlizer.NewGenericList[User]()

// Type-safe map operations
userMap := n1qlizer.NewGenericMap[User]()

// Type-safe builder operations
userBuilder := n1qlizer.Set[MyBuilder, User](builder, "user", userObject)
Builder Methods with Type Parameters

All builder methods now use Go's generic type parameters for increased type safety:

// Previous approach (pre-Go 1.18, no longer supported)
// userBuilder := userBuilder.Set("name", "John").(UserBuilder)

// New generic approach (Go 1.18+)
userBuilder := userBuilder.Set[UserBuilder, string]("name", "John")

For example, when building queries:

// Type-safe builder with generics
selectBuilder := n1qlizer.SelectBuilder{}.
    From[n1qlizer.SelectBuilder]("users").
    Where[n1qlizer.SelectBuilder]("status = ?", "active")
'any' Type

The library uses the any type alias instead of interface{} for improved readability:

// Function signatures use 'any' instead of interface{}
func Execute(query string, args ...any) (QueryResult, error)

// Defining maps with the 'any' type
data := map[string]any{
    "name": "John",
    "age": 30,
    "roles": []string{"admin", "user"},
}

Usage Examples

Basic Query Building
SELECT Queries
// Build a simple SELECT query
users := n1qlizer.Select("*").From("users").Where(n1qlizer.Eq{"type": "user"})
sql, args, err := users.ToN1ql()
// sql == "SELECT * FROM users WHERE type = ?"
// args == []any{"user"}

// With multiple conditions
query := n1qlizer.Select("name", "email").
    From("users").
    Where(n1qlizer.And{
        n1qlizer.Eq{"status": "active"},
        n1qlizer.Gt{"age": 18},
    }).
    OrderBy("name ASC").
    Limit(10)
sql, args, err := query.ToN1ql()
INSERT Queries
sql, args, err := n1qlizer.
    Insert("users").
    Columns("id", "name", "age").
    Values("user123", "Joe", 30).
    Values("user456", "Larry", n1qlizer.Expr("? + 5", 12)).
    ToN1ql()
// sql == "INSERT INTO users (id,name,age) VALUES (?,?,?),(?,?,? + 5)"
// args == []any{"user123", "Joe", 30, "user456", "Larry", 12}
UPDATE Queries
sql, args, err := n1qlizer.
    Update("users").
    UseKeys("'user123'").
    Set("name", "Moe Howard").
    Set("updated_at", n1qlizer.Expr("NOW()")).
    ToN1ql()
// sql == "UPDATE users USE KEYS 'user123' SET name = ?, updated_at = NOW()"
// args == []any{"Moe Howard"}
DELETE Queries
sql, args, err := n1qlizer.
    Delete("users").
    Where(n1qlizer.Eq{"status": "inactive"}).
    Limit(10).
    ToN1ql()
// sql == "DELETE FROM users WHERE status = ? LIMIT 10"
// args == []any{"inactive"}
Couchbase-Specific Features
UPSERT Operation
// Couchbase-specific UPSERT operation - preferred over INSERT
sql, args, err := n1qlizer.
    Upsert("users").
    Document("user123", map[string]any{
        "name": "Joe Smith",
        "email": "joe@example.com",
        "roles": []string{"admin", "user"},
    }).
    ToN1ql()
// sql == "UPSERT INTO users (KEY, VALUE) VALUES (?, ?)"
USE KEYS Clause
users := n1qlizer.Select("*").From("users").UseKeys("'user123', 'user456'")
sql, args, err := users.ToN1ql()
// sql == "SELECT * FROM users USE KEYS 'user123', 'user456'"
USE INDEX Clause
users := n1qlizer.Select("*").
    From("users").
    Prefix(n1qlizer.UseIndexGSI("users_by_email")).
    Where(n1qlizer.Eq{"email": "user@example.com"})
sql, args, err := users.ToN1ql()
// sql == "USE INDEX (`users_by_email` USING GSI) SELECT * FROM users WHERE email = ?"
// args == []any{"user@example.com"}
NEST and UNNEST Operations
// NEST operation joins a document with another bucket
sql, args, err := n1qlizer.
    Select("u.name", "o.orderDate", "o.total").
    From("users AS u").
    NestClause(n1qlizer.Nest("orders").As("o").OnKeys("u.orderIds")).
    Where(n1qlizer.Gt{"o.total": 100}).
    ToN1ql()
// sql == "SELECT u.name, o.orderDate, o.total FROM users AS u NEST orders AS o ON KEYS u.orderIds WHERE o.total > ?"
// args == []any{100}

// UNNEST flattens an array within a document
sql, args, err := n1qlizer.
    Select("u.name", "t").
    From("users AS u").
    UnnestClause(n1qlizer.Unnest("u.tags").As("t")).
    Where(n1qlizer.Eq{"t": "admin"}).
    ToN1ql()
// sql == "SELECT u.name, t FROM users AS u UNNEST u.tags AS t WHERE t = ?"
// args == []any{"admin"}
Analytics Queries
// Analytics queries with the LET clause
sql, args, err := n1qlizer.
    AnalyticsSelect("u.name", "AVG(u.age) as avgAge").
    From("users u").
    Let("minAge", 18).
    Where("u.age >= ?", 18).
    GroupBy("u.country").
    Having("COUNT(*) > ?", 5).
    OrderBy("avgAge DESC").
    ToN1ql()
// sql == "SELECT u.name, AVG(u.age) as avgAge LET minAge = ? FROM users u WHERE u.age >= ? GROUP BY u.country HAVING COUNT(*) > ? ORDER BY avgAge DESC"
// args == []any{18, 18, 5}
Full Text Search (FTS)
// FTS search with options
opts := n1qlizer.FTSSearchOptions{
    IndexName: "users_fts",
    Fields:    []string{"name", "email"},
    Fuzziness: 1,
}

sql, args, err := n1qlizer.
    Select("*").
    From("users").
    WithSearch(n1qlizer.FTSMatch("John Smith", opts)).
    ToN1ql()
// sql == "SELECT * FROM users WHERE SEARCH(users_fts, { 'query': { 'match': 'John Smith' }, 'fields': ['name', 'email'], 'fuzziness': 1 })"

Working with JSON

n1qlizer provides numerous helpers for working with JSON documents:

// Create JSON documents
doc := n1qlizer.AsDocument(map[string]any{
    "name": "John Smith",
    "age": 30,
})

// Access nested fields
field := n1qlizer.JSONField("user.address.city") // "user.`address`.`city`"

// Check if an array contains a value
expr := n1qlizer.JSONArrayContains("user.roles", "admin")
// "user.roles ARRAY_CONTAINS ?"

// Create JSON arrays and objects
arr := n1qlizer.JSONArray("value1", "value2", 3)
obj := n1qlizer.JSONObject("name", "John", "age", 30)
Executing Queries

To execute queries directly with Couchbase SDK, you need to implement the QueryRunner interface:

import (
	"reflect"

	"github.com/ceylanomer/n1qlizer"
	"github.com/couchbase/gocb/v2"
)

type CouchbaseRunner struct {
	cluster *gocb.Cluster
}

func (r *CouchbaseRunner) Execute(query string, args ...interface{}) (n1qlizer.QueryResult, error) {
	// Execute the query using the Couchbase SDK
	result, err := r.cluster.Query(query, &gocb.QueryOptions{
		PositionalParameters: args,
	})
	if err != nil {
		return nil, err
	}

	return &CouchbaseQueryResult{result}, nil
}

// Implement the QueryResult interface
type CouchbaseQueryResult struct {
	result *gocb.QueryResult
}

func (r *CouchbaseQueryResult) One(valuePtr any) error {
	return r.result.One(valuePtr)
}

func (r *CouchbaseQueryResult) All(slicePtr any) error {
	// Get the value that slicePtr points to
	sliceVal := reflect.ValueOf(slicePtr).Elem()

	// Get the element type of the slice
	elemType := sliceVal.Type().Elem()

	// Create a new slice to hold the results
	results := reflect.MakeSlice(sliceVal.Type(), 0, 0)

	// Iterate through the query results
	for r.result.Next() {
		// Create a new element of the appropriate type
		elemPtr := reflect.New(elemType).Interface()

		// Scan the current row into the element
		if err := r.result.Row(elemPtr); err != nil {
			return err
		}

		// Append the element to our results slice
		results = reflect.Append(results, reflect.ValueOf(elemPtr).Elem())
	}

	// Check if there was an error during iteration
	if err := r.result.Err(); err != nil {
		return err
	}

	// Set the slice value to our results
	sliceVal.Set(results)
	return nil
}

func (r *CouchbaseQueryResult) Close() error {
	return r.result.Close()
}


// Usage with runner
func main() {
    // Set up your Couchbase cluster and create a runner
    cluster, err := gocb.Connect("couchbase://localhost", gocb.ClusterOptions{
        Username: "Administrator",
        Password: "password",
    })
    if err != nil {
        panic(err)
    }
    
    runner := &CouchbaseRunner{cluster: cluster}
    
    // Build and execute a query
    result, err := n1qlizer.
        Select("*").
        From("users").
        Where(n1qlizer.Eq{"type": "admin"}).
        RunWith(runner).
        Execute()
    
    if err != nil {
        panic(err)
    }
    
    // Process results
    var adminUsers []interface{}
    err = result.All(&adminUsers)
    if err != nil {
        panic(err)
    }
    
    // Do something with adminUsers
    fmt.Printf("Found %d admin users\n", len(adminUsers))
}

Migration from Pre-1.18 Code

If you're upgrading from a pre-1.18 version, here are the key changes:

  1. Replace interface{} with any in your code
  2. Update builder method calls to use the generic syntax:
    // Old
    builder.Set("field", value).(MyBuilder)
    
    // New
    builder.Set[MyBuilder, ValueType]("field", value)
    
  3. If you've created custom builders, update them to use generics

License

MIT License - See LICENSE file for details.

Documentation

Overview

Fully persistent data structures. A persistent data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not update the structure in-place, but instead always yield a new structure.

Persistent data structures typically share structure among themselves. This allows operations to avoid copying the entire data structure.

Package n1qlizer provides a fluent Couchbase N1QL query generator.

It is inspired by github.com/Masterminds/squirrel

Index

Constants

This section is empty.

Variables

View Source
var (
	// BuilderTypes stores the global registry of Builder types mapped to their corresponding struct types
	BuilderTypes = make(map[reflect.Type]reflect.Type)
	// BuilderMux provides thread-safe access to the BuilderTypes map
	BuilderMux sync.RWMutex
)
View Source
var Dollar = dollarFormat{}

Dollar is a PlaceholderFormat instance that replaces placeholders with dollar-prefixed positional placeholders (e.g. $1, $2, $3). This is the format used by Couchbase N1QL.

View Source
var (
	EmptyBuilder = Builder{NewMap()}
)
View Source
var Question = questionFormat{}

StatementBuilder is a parent builder for other statement builders.

View Source
var RunnerNotQueryRunnerContext = fmt.Errorf("cannot QueryRowContext; Runner is not a QueryRunnerContext")

RunnerNotQueryRunnerContext is returned by QueryRowContext if the RunWith value doesn't implement QueryRunnerContext.

View Source
var RunnerNotSet = fmt.Errorf("cannot run; no Runner set (RunWith)")

RunnerNotSet is returned by methods that need a Runner if it isn't set.

View Source
var StatementBuilder = StatementBuilderType(EmptyBuilder).PlaceholderFormat(Question)

Functions

func Append

func Append[T any, V any](builder T, name string, vs ...V) T

Append returns a copy of the given builder with new value(s) appended to the named list. If the value was previously unset or set with Set (even to a e.g. slice values), the new value(s) will be appended to an empty list.

func DebugN1qlizer

func DebugN1qlizer(s N1qlizer) string

DebugN1qlizer calls ToN1ql on s and shows the approximate N1QL to be executed

If ToN1ql returns an error, the result of this method will look like: "[ToN1ql error: %s]" or "[DebugN1qlizer error: %s]"

IMPORTANT: As its name suggests, this function should only be used for debugging. While the string result *might* be valid N1QL, this function does not try very hard to ensure it. Additionally, executing the output of this function with any untrusted user input is certainly insecure.

func Extend

func Extend[T any, V any](builder T, name string, vs []V) T

Extend behaves like Append, except it takes a single slice or array value which will be concatenated to the named list.

Unlike a variadic call to Append - which requires a []interface{} value - Extend accepts slices or arrays of any type.

Extend will panic if the given value is not a slice, array, or nil.

func ExtendValues

func ExtendValues[T any](builder T, name string, vs any) T

ExtendValues is like Extend but allows passing any value that can be iterated using reflection. Used for backward compatibility.

func Get

func Get[T any](builder T, name string) (any, bool)

Get retrieves a single named value from the given builder.

If the value was set with Append or Extend, the result will be a slice of the same concrete type as was appended to the list.

Get will panic when getting a key that was set with Append or Extend and the types of values in the list don't match. Get will also panic if a value was set with Set using a type derived from a registered struct's exported field and the value set on the Builder is not assignable to the field.

func GetBuilderStructType

func GetBuilderStructType(builderType reflect.Type) reflect.Type

GetBuilderStructType returns the registered struct type for a given builder type

func GetMap

func GetMap[T any](builder T) map[string]any

GetMap returns a copy of the builder's underlying map of values.

If any values were appended with Append or Extend, the value in the map will be the equivalent slice or array.

See notes on Get regarding returned slices.

func GetStruct

func GetStruct[T any](builder T) any

GetStruct returns a new value with the same type as a struct registered for the given Builder type with field values taken from the builder.

GetStruct will panic if any of these "exported" values are not assignable to their corresponding struct fields.

func GetStructLike

func GetStructLike[T any, S any](builder T, strct S) S

GetStructLike will panic if any of these "exported" values are not assignable to their corresponding struct fields.

func JSONField

func JSONField(fieldPath string) string

JSONField is a helper to access a field in a JSON document

func NewBuilderStruct

func NewBuilderStruct(builderType reflect.Type) *reflect.Value

NewBuilderStruct returns a new value with the same type as a struct associated with the given Builder type.

func Register

func Register(builderProto any, structProto any) any

Register wraps RegisterType, taking instances instead of Types.

Returns an empty instance of the registered builder type which can be used as the initial value for builder expressions. See example.

func RegisterBuilder

func RegisterBuilder(builderProto any, structProto any) any

RegisterBuilder wraps RegisterBuilderType, taking instances instead of types.

Returns an empty instance of the registered builder type, which can be used as the initial value for builder expressions. See example.

func RegisterBuilderType

func RegisterBuilderType(builderType reflect.Type, structType reflect.Type) *reflect.Value

RegisterBuilderType registers a Builder type and its corresponding struct type. This mapping affects the type of slices returned by Get and is required for GetStruct to work.

Returns a Value containing an instance of the registered builderType.

RegisterBuilderType will panic if builderType's underlying type is not Builder or if structType's Kind is not Struct.

func RegisterType

func RegisterType(builderType reflect.Type, structType reflect.Type) *reflect.Value

RegisterType maps the given builderType to a structType. This mapping affects the type of slices returned by Get and is required for GetStruct to work.

Returns a Value containing an empty instance of the registered builderType.

RegisterType will panic if builderType's underlying type is not Builder or if structType's Kind is not Struct.

func Remove

func Remove[T any](builder T, name string) T

Remove returns a copy of the given builder with the given named value unset.

func Set

func Set[T any, V any](builder T, name string, v V) T

Set returns a copy of the given builder with a new value set for the given name.

Set (and all other functions taking a builder in this package) will panic if the given builder's underlying type is not Builder.

Types

type AnalyticsSelectBuilder

type AnalyticsSelectBuilder Builder

AnalyticsSelectBuilder builds Couchbase Analytics SELECT statements.

func AnalyticsSelect

func AnalyticsSelect(columns ...string) AnalyticsSelectBuilder

AnalyticsSelect creates a new AnalyticsSelectBuilder for Couchbase Analytics queries.

func (AnalyticsSelectBuilder) Column

func (b AnalyticsSelectBuilder) Column(column any, args ...any) AnalyticsSelectBuilder

Column adds a result column to the query. Unlike Columns, Column accepts args which will be bound to placeholders in the column string, for example:

.Column("IF(n_subscribers > ?, ?, ?)", 100, "HIGH", "LOW")

func (AnalyticsSelectBuilder) Columns

Columns adds result columns to the query.

func (AnalyticsSelectBuilder) Execute

func (b AnalyticsSelectBuilder) Execute() (QueryResult, error)

Execute builds and executes the query.

func (AnalyticsSelectBuilder) ExecuteContext

func (b AnalyticsSelectBuilder) ExecuteContext(ctx context.Context) (QueryResult, error)

ExecuteContext builds and executes the query using the provided context.

func (AnalyticsSelectBuilder) From

From sets the FROM clause of the query.

func (AnalyticsSelectBuilder) GroupBy

func (b AnalyticsSelectBuilder) GroupBy(groupBys ...string) AnalyticsSelectBuilder

GroupBy adds GROUP BY expressions to the query.

func (AnalyticsSelectBuilder) Having

func (b AnalyticsSelectBuilder) Having(pred any, rest ...any) AnalyticsSelectBuilder

Having adds an expression to the HAVING clause of the query.

func (AnalyticsSelectBuilder) Let

Let adds a LET binding variable to the query.

func (AnalyticsSelectBuilder) Limit

Limit sets a LIMIT clause on the query.

func (AnalyticsSelectBuilder) MustN1ql

func (b AnalyticsSelectBuilder) MustN1ql() (string, []any)

MustN1ql builds the query into a N1QL string and bound args.

MustN1ql panics if there are any errors.

func (AnalyticsSelectBuilder) Offset

Offset sets an OFFSET clause on the query.

func (AnalyticsSelectBuilder) OrderBy

func (b AnalyticsSelectBuilder) OrderBy(orderBys ...string) AnalyticsSelectBuilder

OrderBy adds ORDER BY expressions to the query.

func (AnalyticsSelectBuilder) PlaceholderFormat

PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the query.

func (AnalyticsSelectBuilder) RunWith

RunWith sets a Runner (like a Couchbase DB connection) to be used with e.g. Execute.

func (AnalyticsSelectBuilder) RunWithContext

RunWithContext sets a QueryRunnerContext (like a Couchbase DB connection with context methods) to be used with e.g. ExecuteContext.

func (AnalyticsSelectBuilder) ToN1ql

func (b AnalyticsSelectBuilder) ToN1ql() (string, []any, error)

ToN1ql builds the query into a N1QL string and bound args.

func (AnalyticsSelectBuilder) Where

func (b AnalyticsSelectBuilder) Where(pred any, args ...any) AnalyticsSelectBuilder

Where adds an expression to the WHERE clause of the query.

func (AnalyticsSelectBuilder) Window

func (b AnalyticsSelectBuilder) Window(windowClause string) AnalyticsSelectBuilder

Window sets the WINDOW clause for window functions.

type And

type And []N1qlizer

And combines multiple expressions with the "AND" operator.

func (And) ToN1ql

func (and And) ToN1ql() (string, []any, error)

type Any

type Any = any

Any is an alias for 'any', provided for backward compatibility. New code should use 'any' directly.

type Builder

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

Builder stores a set of named values.

New types can be declared with underlying type Builder and used with the functions in this package. See example.

Instances of Builder should be treated as immutable. It is up to the implementor to ensure mutable values set on a Builder are not mutated while the Builder is in use.

type CaseBuilder

type CaseBuilder interface {
	N1qlizer
	When(condition interface{}, value interface{}) CaseBuilder
	Else(value interface{}) CaseBuilder
}

CaseBuilder builds SQL CASE expressions.

func NewCaseBuilder

func NewCaseBuilder() CaseBuilder

NewCaseBuilder creates a new CaseBuilder for building CASE expressions

func NewCaseBuilderWithValue

func NewCaseBuilderWithValue(value interface{}) CaseBuilder

NewCaseBuilderWithValue creates a new CaseBuilder for building CASE expressions with an initial value. e.g. "CASE a WHEN 'foo' THEN 1 WHEN 'bar' THEN 2 ELSE 3 END"

type DeleteBuilder

type DeleteBuilder Builder

DeleteBuilder builds DELETE statements.

func Delete

func Delete(from string) DeleteBuilder

Delete returns a new DeleteBuilder with the given table name.

See DeleteBuilder.Table.

func (DeleteBuilder) Execute

func (b DeleteBuilder) Execute() (QueryResult, error)

Execute builds and executes the query.

func (DeleteBuilder) ExecuteContext

func (b DeleteBuilder) ExecuteContext(ctx context.Context) (QueryResult, error)

ExecuteContext builds and executes the query with the context and runner set by RunWith.

func (DeleteBuilder) From

func (b DeleteBuilder) From(from string) DeleteBuilder

From sets the table to be deleted from.

func (DeleteBuilder) Limit

func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder

Limit sets a LIMIT clause on the query.

func (DeleteBuilder) MustN1ql

func (b DeleteBuilder) MustN1ql() (string, []any)

MustN1ql builds the query into a N1QL string and bound args.

MustN1ql panics if there are any errors.

func (DeleteBuilder) Offset

func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder

Offset sets an OFFSET clause on the query.

func (DeleteBuilder) PlaceholderFormat

func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder

PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the query.

func (DeleteBuilder) Prefix

func (b DeleteBuilder) Prefix(sql string, args ...any) DeleteBuilder

Prefix adds an expression to the beginning of the query

func (DeleteBuilder) PrefixExpr

func (b DeleteBuilder) PrefixExpr(expr N1qlizer) DeleteBuilder

PrefixExpr adds an expression to the very beginning of the query

func (DeleteBuilder) RunWith

func (b DeleteBuilder) RunWith(runner QueryRunner) DeleteBuilder

RunWith sets a Runner (like a Couchbase DB connection) to be used with e.g. Execute.

func (DeleteBuilder) RunWithContext

func (b DeleteBuilder) RunWithContext(runner QueryRunnerContext) DeleteBuilder

RunWithContext sets a Runner (like a Couchbase DB connection with Context support) to be used with e.g. ExecuteContext.

func (DeleteBuilder) Suffix

func (b DeleteBuilder) Suffix(sql string, args ...any) DeleteBuilder

Suffix adds an expression to the end of the query.

func (DeleteBuilder) SuffixExpr

func (b DeleteBuilder) SuffixExpr(expr N1qlizer) DeleteBuilder

SuffixExpr adds an expression to the end of the query.

func (DeleteBuilder) ToN1ql

func (b DeleteBuilder) ToN1ql() (string, []any, error)

ToN1ql builds the query into a N1QL string and bound args.

func (DeleteBuilder) UseKeys

func (b DeleteBuilder) UseKeys(keys string) DeleteBuilder

UseKeys sets the USE KEYS clause of the query.

func (DeleteBuilder) Where

func (b DeleteBuilder) Where(pred any, args ...any) DeleteBuilder

Where adds an expression to the WHERE clause of the query.

type Eq

type Eq map[string]any

Eq is an equality expression ("=").

func (Eq) ToN1ql

func (eq Eq) ToN1ql() (sql string, args []any, err error)

type FTSSearchOptions

type FTSSearchOptions struct {
	IndexName string
	Analyzer  string
	Fuzziness int
	Boost     float64
	Limit     int
	Score     string   // Name of the field to store the score in
	Highlight bool     // Whether to enable highlighting
	Fields    []string // Fields to search in
}

FTSSearchOptions represents options for a Full-Text Search query

type GenericList

type GenericList[T any] interface {
	// IsNil returns true if the list is empty
	IsNil() bool

	// Cons returns a new list with val as the head
	Cons(val T) GenericList[T]

	// Head returns the first element of the list;
	// panics if the list is empty
	Head() T

	// Tail returns a list with all elements except the head;
	// panics if the list is empty
	Tail() GenericList[T]

	// Size returns the list's length.  This takes O(1) time.
	Size() int

	// ForEach executes a callback for each value in the list.
	ForEach(f func(T))

	// Reverse returns a list whose elements are in the opposite order as
	// the original list.
	Reverse() GenericList[T]
}

GenericList is a type-safe persistent list using generics.

func NewGenericList

func NewGenericList[T any]() GenericList[T]

NewGenericList returns a new, empty generic list with type parameter T.

type GenericMap

type GenericMap[V any] interface {
	// IsNil returns true if the Map is empty
	IsNil() bool

	// Set returns a new map in which key and value are associated.
	// If the key didn't exist before, it's created; otherwise, the
	// associated value is changed.
	// This operation is O(log N) in the number of keys.
	Set(key string, value V) GenericMap[V]

	// Delete returns a new map with the association for key, if any, removed.
	// This operation is O(log N) in the number of keys.
	Delete(key string) GenericMap[V]

	// Lookup returns the value associated with a key, if any.  If the key
	// exists, the second return value is true; otherwise, false.
	// This operation is O(log N) in the number of keys.
	Lookup(key string) (V, bool)

	// Size returns the number of key value pairs in the map.
	// This takes O(1) time.
	Size() int

	// ForEach executes a callback on each key value pair in the map.
	ForEach(f func(key string, val V))

	// Keys returns a slice with all keys in this map.
	// This operation is O(N) in the number of keys.
	Keys() []string

	String() string
}

GenericMap is a generic version of Map that uses type parameters to provide type safety for the values.

type Gt

type Gt map[string]any

Gt is a greater-than expression (">").

func (Gt) ToN1ql

func (gt Gt) ToN1ql() (sql string, args []any, err error)

type Gte

type Gte map[string]any

Gte is a greater-than-or-equal expression (">=").

func (Gte) ToN1ql

func (gte Gte) ToN1ql() (sql string, args []any, err error)

type InsertBuilder

type InsertBuilder Builder

InsertBuilder builds SQL INSERT statements.

func Insert

func Insert(into string) InsertBuilder

Insert returns a new InsertBuilder with the given table name.

See InsertBuilder.Into.

func (InsertBuilder) Columns

func (b InsertBuilder) Columns(columns ...string) InsertBuilder

Columns adds column names to the query.

func (InsertBuilder) Execute

func (b InsertBuilder) Execute() (QueryResult, error)

Execute builds and executes the query.

func (InsertBuilder) ExecuteContext

func (b InsertBuilder) ExecuteContext(ctx context.Context) (QueryResult, error)

ExecuteContext builds and executes the query with the context and runner set by RunWith.

func (InsertBuilder) Into

func (b InsertBuilder) Into(into string) InsertBuilder

Into sets the INTO clause of the query.

func (InsertBuilder) MustN1ql

func (b InsertBuilder) MustN1ql() (string, []any)

MustN1ql builds the query into a N1QL string and bound args.

MustN1ql panics if there are any errors.

func (InsertBuilder) Options

func (b InsertBuilder) Options(options ...string) InsertBuilder

Options adds options to the query.

func (InsertBuilder) PlaceholderFormat

func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder

PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the query.

func (InsertBuilder) Prefix

func (b InsertBuilder) Prefix(sql string, args ...any) InsertBuilder

Prefix adds an expression to the beginning of the query

func (InsertBuilder) PrefixExpr

func (b InsertBuilder) PrefixExpr(expr N1qlizer) InsertBuilder

PrefixExpr adds an expression to the beginning of the query

func (InsertBuilder) RunWith

func (b InsertBuilder) RunWith(runner QueryRunner) InsertBuilder

RunWith sets a Runner (like a Couchbase DB connection) to be used with e.g. Execute.

func (InsertBuilder) RunWithContext

func (b InsertBuilder) RunWithContext(runner QueryRunnerContext) InsertBuilder

RunWithContext sets a Runner (like a Couchbase DB connection with Context support) to be used with e.g. ExecuteContext.

func (InsertBuilder) SetMap

func (b InsertBuilder) SetMap(clauses map[string]any) InsertBuilder

SetMap adds key-value pairs to set rather than a list of values.

func (InsertBuilder) Suffix

func (b InsertBuilder) Suffix(sql string, args ...any) InsertBuilder

Suffix adds an expression to the end of the query

func (InsertBuilder) SuffixExpr

func (b InsertBuilder) SuffixExpr(expr N1qlizer) InsertBuilder

SuffixExpr adds an expression to the end of the query

func (InsertBuilder) ToN1ql

func (b InsertBuilder) ToN1ql() (string, []any, error)

ToN1ql builds the query into a N1QL string and bound args.

func (InsertBuilder) Values

func (b InsertBuilder) Values(values ...any) InsertBuilder

Values adds a single row's values to the query.

type JSONDocument

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

JSONDocument wraps a Go struct or map to be marshaled as a JSON document for Couchbase

func AsDocument

func AsDocument(value any) JSONDocument

AsDocument wraps a value as a JSONDocument

func (JSONDocument) MarshalJSON

func (d JSONDocument) MarshalJSON() ([]byte, error)

MarshalJSON implementation

func (JSONDocument) ToN1ql

func (d JSONDocument) ToN1ql() (string, []any, error)

ToN1ql implements N1qlizer for JSONDocument

type LeftNestClause

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

LeftNestClause represents a LEFT NEST clause in a N1QL query

func LeftNest

func LeftNest(bucket string) LeftNestClause

LeftNest creates a new LEFT NEST clause for outer joining with nested sub-documents

func (LeftNestClause) As

func (ln LeftNestClause) As(alias string) LeftNestClause

As sets the alias for the nested bucket

func (LeftNestClause) On

func (ln LeftNestClause) On(condition interface{}, args ...interface{}) LeftNestClause

On sets the ON condition for the LEFT NEST clause

func (LeftNestClause) OnKeys

func (ln LeftNestClause) OnKeys(keys string) LeftNestClause

OnKeys sets the ON KEYS expression for the LEFT NEST clause

func (LeftNestClause) ToN1ql

func (ln LeftNestClause) ToN1ql() (string, []interface{}, error)

ToN1ql implements the N1qlizer interface

type LeftUnnestClause

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

LeftUnnestClause represents a LEFT UNNEST clause in a N1QL query

func LeftUnnest

func LeftUnnest(path string) LeftUnnestClause

LeftUnnest creates a new LEFT UNNEST clause for outer flattening of array fields

func (LeftUnnestClause) As

As sets the alias for the unnested array

func (LeftUnnestClause) On

func (lu LeftUnnestClause) On(condition interface{}, args ...interface{}) LeftUnnestClause

On sets the ON condition for the LEFT UNNEST clause

func (LeftUnnestClause) ToN1ql

func (lu LeftUnnestClause) ToN1ql() (string, []interface{}, error)

ToN1ql implements the N1qlizer interface

type List

type List interface {
	// IsNil returns true if the list is empty
	IsNil() bool

	// Cons returns a new list with val as the head
	Cons(val any) List

	// Head returns the first element of the list;
	// panics if the list is empty
	Head() any

	// Tail returns a list with all elements except the head;
	// panics if the list is empty
	Tail() List

	// Size returns the list's length.  This takes O(1) time.
	Size() int

	// ForEach executes a callback for each value in the list.
	ForEach(f func(any))

	// Reverse returns a list whose elements are in the opposite order as
	// the original list.
	Reverse() List
}

List is a persistent list of possibly heterogeneous values.

func NewList

func NewList() List

NewList returns a new, empty list. The result is a singly linked list implementation. All lists share an empty tail, so allocating empty lists is efficient in time and memory.

type Lt

type Lt map[string]any

Lt is a less-than expression ("<").

func (Lt) ToN1ql

func (lt Lt) ToN1ql() (sql string, args []any, err error)

type Lte

type Lte map[string]any

Lte is a less-than-or-equal expression ("<=").

func (Lte) ToN1ql

func (lte Lte) ToN1ql() (sql string, args []any, err error)

type Map

type Map interface {
	// IsNil returns true if the Map is empty
	IsNil() bool

	// Set returns a new map in which key and value are associated.
	// If the key didn't exist before, it's created; otherwise, the
	// associated value is changed.
	// This operation is O(log N) in the number of keys.
	Set(key string, value any) Map

	// Delete returns a new map with the association for key, if any, removed.
	// This operation is O(log N) in the number of keys.
	Delete(key string) Map

	// Lookup returns the value associated with a key, if any.  If the key
	// exists, the second return value is true; otherwise, false.
	// This operation is O(log N) in the number of keys.
	Lookup(key string) (any, bool)

	// Size returns the number of key value pairs in the map.
	// This takes O(1) time.
	Size() int

	// ForEach executes a callback on each key value pair in the map.
	ForEach(f func(key string, val any))

	// Keys returns a slice with all keys in this map.
	// This operation is O(N) in the number of keys.
	Keys() []string

	String() string
}

A Map associates unique keys (type string) with values (type any).

func NewMap

func NewMap() Map

NewMap allocates a new, persistent map from strings to values of any type. This is currently implemented as a path-copying binary tree.

type N1qlizer

type N1qlizer interface {
	ToN1ql() (string, []any, error)
}

N1qlizer is the interface that wraps the ToN1ql method.

ToN1ql returns a N1QL representation of the N1qlizer, along with a slice of args as passed to Couchbase SDK. It can also return an error.

func Alias

func Alias(expr N1qlizer, alias string) N1qlizer

Alias allows a N1qlizer to alias itself with the "AS" keyword.

func ArrayAvg

func ArrayAvg(arr string) N1qlizer

ArrayAvg returns an Analytics array_avg function call

func ArrayCount

func ArrayCount(arr string) N1qlizer

ArrayCount returns an Analytics array_count function call

func ArrayFilter

func ArrayFilter(arr, variable, condition string) N1qlizer

ArrayFilter returns an Analytics array_filter function call

func ArrayFlatten

func ArrayFlatten(arr string) N1qlizer

ArrayFlatten returns an Analytics array_flatten function call

func ArrayMax

func ArrayMax(arr string) N1qlizer

ArrayMax returns an Analytics array_max function call

func ArrayMin

func ArrayMin(arr string) N1qlizer

ArrayMin returns an Analytics array_min function call

func ArraySum

func ArraySum(arr string) N1qlizer

ArraySum returns an Analytics array_sum function call

func Expr

func Expr(sql any, args ...any) N1qlizer

Expr builds an expression from a SQL fragment and arguments. The first argument should be a string, which may contain ? placeholders.

func FTSConjunction

func FTSConjunction(expressions ...N1qlizer) N1qlizer

FTSConjunction creates a conjunction (AND) of multiple FTS expressions

func FTSDisjunction

func FTSDisjunction(expressions ...N1qlizer) N1qlizer

FTSDisjunction creates a disjunction (OR) of multiple FTS expressions

func FTSMatch

func FTSMatch(query string, options ...FTSSearchOptions) N1qlizer

FTSMatch creates a Full-Text Search match expression

func FTSPhraseMatch

func FTSPhraseMatch(query string, options ...FTSSearchOptions) N1qlizer

FTSPhraseMatch creates a Full-Text Search phrase match expression

func FTSPrefixMatch

func FTSPrefixMatch(prefix string, options ...FTSSearchOptions) N1qlizer

FTSPrefixMatch creates a Full-Text Search prefix match expression

func FTSRangeMatch

func FTSRangeMatch(field string, min, max interface{}, options ...FTSSearchOptions) N1qlizer

FTSRangeMatch creates a Full-Text Search range match expression

func FTSSearchService

func FTSSearchService(indexName, query string, options ...interface{}) N1qlizer

FTSSearchService creates an expression to use Couchbase's dedicated search service

func FTSWildcardMatch

func FTSWildcardMatch(pattern string, options ...FTSSearchOptions) N1qlizer

FTSWildcardMatch creates a Full-Text Search wildcard match expression

func JSONArray

func JSONArray(values ...any) N1qlizer

JSONArray creates an array constructor expression for N1QL

func JSONArrayContains

func JSONArrayContains(field string, value any) N1qlizer

JSONArrayContains creates an expression for checking if a JSON array contains a value field ARRAY_CONTAINS value

func JSONObject

func JSONObject(keyValuePairs ...any) N1qlizer

JSONObject creates an object constructor expression for N1QL

func ObjectNames

func ObjectNames(obj string) N1qlizer

ObjectNames returns an Analytics object_names function call

func ObjectPairs

func ObjectPairs(obj string) N1qlizer

ObjectPairs returns an Analytics object_pairs function call

func ObjectPut

func ObjectPut(obj, fieldName, value string) N1qlizer

ObjectPut returns an Analytics object_put function call

func ObjectRemove

func ObjectRemove(obj string, fields ...string) N1qlizer

ObjectRemove returns an Analytics object_remove function call

func ObjectValues

func ObjectValues(obj string) N1qlizer

ObjectValues returns an Analytics object_values function call

func SubDocument

func SubDocument(document any, path ...string) N1qlizer

SubDocument returns a subdocument expression

type NestClause

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

NestClause represents a NEST clause in a N1QL query

func Nest

func Nest(bucket string) NestClause

Nest creates a new NEST clause for joining with nested sub-documents

func (NestClause) As

func (n NestClause) As(alias string) NestClause

As sets the alias for the nested bucket

func (NestClause) On

func (n NestClause) On(condition interface{}, args ...interface{}) NestClause

On sets the ON condition for the NEST clause

func (NestClause) OnKeys

func (n NestClause) OnKeys(keys string) NestClause

OnKeys sets the ON KEYS expression for the NEST clause

func (NestClause) ToN1ql

func (n NestClause) ToN1ql() (string, []interface{}, error)

ToN1ql implements the N1qlizer interface

type NestedField

type NestedField struct {
	Field string
	Path  []string
}

NestedField is a helper for accessing nested JSON fields

func Field

func Field(field string, path ...string) NestedField

Field creates a new NestedField

func (NestedField) String

func (n NestedField) String() string

String returns the full path as a string

type NotEq

type NotEq map[string]any

NotEq is an inequality expression ("<>").

func (NotEq) ToN1ql

func (neq NotEq) ToN1ql() (sql string, args []any, err error)

type Or

type Or []N1qlizer

Or combines multiple expressions with the "OR" operator.

func (Or) ToN1ql

func (or Or) ToN1ql() (string, []any, error)

type PlaceholderFormat

type PlaceholderFormat interface {
	ReplacePlaceholders(sql string) (string, error)
}

PlaceholderFormat is the interface that wraps the ReplacePlaceholders method.

type QueryExecutor

type QueryExecutor interface {
	Execute(query string, args ...any) (QueryResult, error)
}

QueryExecutor is the interface that wraps the Execute method.

Execute executes the given N1QL query as implemented by Couchbase SDK.

type QueryExecutorContext

type QueryExecutorContext interface {
	ExecuteContext(ctx context.Context, query string, args ...any) (QueryResult, error)
}

QueryExecutorContext is the interface that wraps the ExecuteContext method.

ExecuteContext executes the given N1QL query with context as implemented by Couchbase SDK.

type QueryResult

type QueryResult interface {
	One(valuePtr any) error
	All(slicePtr any) error
	Close() error
}

QueryResult represents the result of a N1QL query

func ExecuteContextWith

func ExecuteContextWith(ctx context.Context, db QueryExecutorContext, n N1qlizer) (res QueryResult, err error)

ExecuteContextWith executes the given N1QLizer with context using the provided QueryExecutorContext.

func ExecuteWith

func ExecuteWith(db QueryExecutor, n N1qlizer) (res QueryResult, err error)

ExecuteWith executes the given N1QLizer using the provided QueryExecutor. This function is similar to ExecuteContextWith but does not use a context.

type QueryRunner

type QueryRunner interface {
	QueryExecutor
}

QueryRunner is the interface that combines query execution and result handling

func WrapStdCb

func WrapStdCb(stdCb StdCb) QueryRunner

WrapStdCb wraps a type implementing the standard Couchbase SDK interface with methods that n1qlizer expects.

type QueryRunnerContext

type QueryRunnerContext interface {
	QueryExecutor
	QueryExecutorContext
}

QueryRunnerContext is the interface that combines QueryExecutor and QueryExecutorContext.

func WrapStdCbCtx

func WrapStdCbCtx(stdCb StdCbCtx) QueryRunnerContext

WrapStdCbCtx wraps a type implementing the standard Couchbase SDK interface with context support with methods that n1qlizer expects.

type SelectBuilder

type SelectBuilder Builder

SelectBuilder builds SELECT statements.

func Select

func Select(columns ...string) SelectBuilder

Select returns a new SelectBuilder, optionally setting some result columns.

See SelectBuilder.Columns.

func (SelectBuilder) Column

func (b SelectBuilder) Column(column any, args ...any) SelectBuilder

Column adds a result column to the query. Unlike Columns, Column accepts args which will be bound to placeholders in the column string, for example:

.Column("IF(n_subscribers > ?, ?, ?)", 100, "HIGH", "LOW")

func (SelectBuilder) Columns

func (b SelectBuilder) Columns(columns ...string) SelectBuilder

Columns adds result columns to the query.

func (SelectBuilder) Distinct

func (b SelectBuilder) Distinct() SelectBuilder

Distinct adds a DISTINCT clause to the query.

func (SelectBuilder) Execute

func (b SelectBuilder) Execute() (QueryResult, error)

Execute builds and executes the query.

func (SelectBuilder) ExecuteContext

func (b SelectBuilder) ExecuteContext(ctx context.Context) (QueryResult, error)

ExecuteContext builds and executes the query with the context and runner set by RunWith.

func (SelectBuilder) From

func (b SelectBuilder) From(from string) SelectBuilder

From sets the FROM clause of the query.

func (SelectBuilder) FromSelect

func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder

FromSelect sets a subquery into the FROM clause of the query.

func (SelectBuilder) GroupBy

func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder

GroupBy adds GROUP BY expressions to the query.

func (SelectBuilder) Having

func (b SelectBuilder) Having(pred any, rest ...any) SelectBuilder

Having adds an expression to the HAVING clause of the query.

func (SelectBuilder) InnerJoin

func (b SelectBuilder) InnerJoin(join string, rest ...any) SelectBuilder

InnerJoin adds an INNER JOIN clause to the query.

func (SelectBuilder) Join

func (b SelectBuilder) Join(join string, rest ...any) SelectBuilder

Join adds a JOIN clause to the query.

func (SelectBuilder) JoinClause

func (b SelectBuilder) JoinClause(join string, args ...any) SelectBuilder

JoinClause adds a join clause to the query.

func (SelectBuilder) LeftJoin

func (b SelectBuilder) LeftJoin(join string, rest ...any) SelectBuilder

LeftJoin adds a LEFT JOIN clause to the query.

func (SelectBuilder) LeftNest

func (b SelectBuilder) LeftNest(bucket string) SelectBuilder

LeftNest adds a LEFT NEST clause to the query

func (SelectBuilder) LeftNestClause

func (b SelectBuilder) LeftNestClause(nest LeftNestClause) SelectBuilder

LeftNestClause adds a LEFT NEST clause to the query

func (SelectBuilder) LeftUnnest

func (b SelectBuilder) LeftUnnest(path string) SelectBuilder

LeftUnnest adds a LEFT UNNEST clause to the query

func (SelectBuilder) LeftUnnestClause

func (b SelectBuilder) LeftUnnestClause(unnest LeftUnnestClause) SelectBuilder

LeftUnnestClause adds a LEFT UNNEST clause to the query

func (SelectBuilder) Limit

func (b SelectBuilder) Limit(limit uint64) SelectBuilder

Limit sets a LIMIT clause on the query.

func (SelectBuilder) MustN1ql

func (b SelectBuilder) MustN1ql() (string, []any)

MustN1ql builds the query into a N1QL string and bound args.

MustN1ql panics if there are any errors.

func (SelectBuilder) Nest

func (b SelectBuilder) Nest(bucket string) SelectBuilder

Nest adds a NEST clause to the query

func (SelectBuilder) NestClause

func (b SelectBuilder) NestClause(nest NestClause) SelectBuilder

NestClause adds a NEST clause to the query

func (SelectBuilder) Offset

func (b SelectBuilder) Offset(offset uint64) SelectBuilder

Offset sets an OFFSET clause on the query.

func (SelectBuilder) Options

func (b SelectBuilder) Options(options ...string) SelectBuilder

Options adds options to the query.

func (SelectBuilder) OrderBy

func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder

OrderBy adds ORDER BY expressions to the query.

func (SelectBuilder) OrderByClause

func (b SelectBuilder) OrderByClause(pred any, args ...any) SelectBuilder

OrderByClause adds ORDER BY expressions to the query with a custom clause.

This is a more flexible version of OrderBy, and can be used for complex expressions like "ORDER BY field ASC NULLS FIRST".

func (SelectBuilder) PlaceholderFormat

func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder

PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the query.

func (SelectBuilder) Prefix

func (b SelectBuilder) Prefix(sql string, args ...any) SelectBuilder

Prefix adds an expression to the beginning of the query

func (SelectBuilder) PrefixExpr

func (b SelectBuilder) PrefixExpr(expr N1qlizer) SelectBuilder

PrefixExpr adds an expression to the very beginning of the query

func (SelectBuilder) RightJoin

func (b SelectBuilder) RightJoin(join string, rest ...any) SelectBuilder

RightJoin adds a RIGHT JOIN clause to the query.

func (SelectBuilder) RunWith

func (b SelectBuilder) RunWith(runner QueryRunner) SelectBuilder

RunWith sets a Runner (like a Couchbase DB connection) to be used with e.g. Execute.

func (SelectBuilder) RunWithContext

func (b SelectBuilder) RunWithContext(runner QueryRunnerContext) SelectBuilder

RunWithContext sets a Runner (like a Couchbase DB connection with Context support) to be used with e.g. ExecuteContext.

func (SelectBuilder) Suffix

func (b SelectBuilder) Suffix(sql string, args ...any) SelectBuilder

Suffix adds an expression to the end of the query

func (SelectBuilder) SuffixExpr

func (b SelectBuilder) SuffixExpr(expr N1qlizer) SelectBuilder

SuffixExpr adds an expression to the end of the query

func (SelectBuilder) ToN1ql

func (b SelectBuilder) ToN1ql() (string, []any, error)

ToN1ql builds the query into a N1QL string and bound args.

func (SelectBuilder) Unnest

func (b SelectBuilder) Unnest(path string) SelectBuilder

Unnest adds an UNNEST clause to the query

func (SelectBuilder) UnnestClause

func (b SelectBuilder) UnnestClause(unnest UnnestClause) SelectBuilder

UnnestClause adds an UNNEST clause to the query

func (SelectBuilder) UseKeys

func (b SelectBuilder) UseKeys(keys string) SelectBuilder

UseKeys sets the USE KEYS clause of the query.

func (SelectBuilder) Where

func (b SelectBuilder) Where(pred any, args ...any) SelectBuilder

Where adds an expression to the WHERE clause of the query.

func (SelectBuilder) WithSearch

func (b SelectBuilder) WithSearch(search N1qlizer) SelectBuilder

WithSearch adds a SEARCH clause to the WHERE part of a query

type StatementBuilderType

type StatementBuilderType Builder

StatementBuilderType is the type of StatementBuilder.

func (StatementBuilderType) AnalyticsSelect

func (b StatementBuilderType) AnalyticsSelect(columns ...string) AnalyticsSelectBuilder

AnalyticsSelect returns an AnalyticsSelectBuilder for this StatementBuilderType. This is specific to the Couchbase Analytics Service.

func (StatementBuilderType) Delete

func (b StatementBuilderType) Delete(from string) DeleteBuilder

Delete returns a DeleteBuilder for this StatementBuilderType.

func (StatementBuilderType) Insert

func (b StatementBuilderType) Insert(into string) InsertBuilder

Insert returns a InsertBuilder for this StatementBuilderType.

func (StatementBuilderType) PlaceholderFormat

PlaceholderFormat sets the PlaceholderFormat for this StatementBuilderType.

func (StatementBuilderType) RunWith

RunWith sets the QueryRunner that this StatementBuilderType should execute queries with.

func (StatementBuilderType) RunWithContext

RunWithContext sets the QueryRunnerContext that this StatementBuilderType should execute queries with context support.

func (StatementBuilderType) Select

func (b StatementBuilderType) Select(columns ...string) SelectBuilder

Select returns a SelectBuilder for this StatementBuilderType.

func (StatementBuilderType) Update

func (b StatementBuilderType) Update(table string) UpdateBuilder

Update returns a UpdateBuilder for this StatementBuilderType.

func (StatementBuilderType) Upsert

func (b StatementBuilderType) Upsert(into string) UpsertBuilder

Upsert returns a UpsertBuilder for this StatementBuilderType. This is specific to Couchbase and is the preferred way to insert documents.

type StdCb

type StdCb interface {
	Execute(query string, args ...any) (QueryResult, error)
}

StdCb encompasses the standard methods of Couchbase SDK that execute queries.

type StdCbCtx

type StdCbCtx interface {
	ExecuteContext(ctx context.Context, query string, args ...any) (QueryResult, error)
}

StdCbCtx encompasses the standard methods of Couchbase SDK that execute queries with context.

type UnnestClause

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

UnnestClause represents an UNNEST clause in a N1QL query

func Unnest

func Unnest(path string) UnnestClause

Unnest creates a new UNNEST clause for flattening array fields

func (UnnestClause) As

func (u UnnestClause) As(alias string) UnnestClause

As sets the alias for the unnested array

func (UnnestClause) On

func (u UnnestClause) On(condition interface{}, args ...interface{}) UnnestClause

On sets the ON condition for the UNNEST clause

func (UnnestClause) ToN1ql

func (u UnnestClause) ToN1ql() (string, []interface{}, error)

ToN1ql implements the N1qlizer interface

type UpdateBuilder

type UpdateBuilder Builder

UpdateBuilder builds UPDATE statements.

func Update

func Update(table string) UpdateBuilder

Update returns a new UpdateBuilder with the given table name.

See UpdateBuilder.Table.

func (UpdateBuilder) Execute

func (b UpdateBuilder) Execute() (QueryResult, error)

Execute builds and executes the query.

func (UpdateBuilder) ExecuteContext

func (b UpdateBuilder) ExecuteContext(ctx context.Context) (QueryResult, error)

ExecuteContext builds and executes the query with the context and runner set by RunWith.

func (UpdateBuilder) Limit

func (b UpdateBuilder) Limit(limit uint64) UpdateBuilder

Limit sets a LIMIT clause on the query.

func (UpdateBuilder) MustN1ql

func (b UpdateBuilder) MustN1ql() (string, []any)

MustN1ql builds the query into a N1QL string and bound args.

MustN1ql panics if there are any errors.

func (UpdateBuilder) Offset

func (b UpdateBuilder) Offset(offset uint64) UpdateBuilder

Offset sets a OFFSET clause on the query.

func (UpdateBuilder) PlaceholderFormat

func (b UpdateBuilder) PlaceholderFormat(f PlaceholderFormat) UpdateBuilder

PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the query.

func (UpdateBuilder) Prefix

func (b UpdateBuilder) Prefix(sql string, args ...any) UpdateBuilder

Prefix adds an expression to the beginning of the query

func (UpdateBuilder) PrefixExpr

func (b UpdateBuilder) PrefixExpr(expr N1qlizer) UpdateBuilder

PrefixExpr adds an expression to the beginning of the query

func (UpdateBuilder) RunWith

func (b UpdateBuilder) RunWith(runner QueryRunner) UpdateBuilder

RunWith sets a Runner (like a Couchbase DB connection) to be used with e.g. Execute.

func (UpdateBuilder) RunWithContext

func (b UpdateBuilder) RunWithContext(runner QueryRunnerContext) UpdateBuilder

RunWithContext sets a Runner (like a Couchbase DB connection with Context support) to be used with e.g. ExecuteContext.

func (UpdateBuilder) Set

func (b UpdateBuilder) Set(column string, value any) UpdateBuilder

Set adds SET clauses to the query.

func (UpdateBuilder) SetMap

func (b UpdateBuilder) SetMap(clauses map[string]any) UpdateBuilder

SetMap is a convenience method which calls .Set for each key/value pair in clauses.

func (UpdateBuilder) Suffix

func (b UpdateBuilder) Suffix(sql string, args ...any) UpdateBuilder

Suffix adds an expression to the end of the query

func (UpdateBuilder) SuffixExpr

func (b UpdateBuilder) SuffixExpr(expr N1qlizer) UpdateBuilder

SuffixExpr adds an expression to the end of the query

func (UpdateBuilder) Table

func (b UpdateBuilder) Table(table string) UpdateBuilder

Table sets the table to be updated.

func (UpdateBuilder) ToN1ql

func (b UpdateBuilder) ToN1ql() (string, []any, error)

ToN1ql builds the query into a N1QL string and bound args.

func (UpdateBuilder) UseKeys

func (b UpdateBuilder) UseKeys(keys string) UpdateBuilder

UseKeys sets the USE KEYS clause of the query.

func (UpdateBuilder) Where

func (b UpdateBuilder) Where(pred any, args ...any) UpdateBuilder

Where adds WHERE expressions to the query.

type UpsertBuilder

type UpsertBuilder Builder

UpsertBuilder builds Couchbase N1QL UPSERT statements.

func Upsert

func Upsert(into string) UpsertBuilder

Upsert returns a new UpsertBuilder with the given table name.

See UpsertBuilder.Into.

func (UpsertBuilder) Columns

func (b UpsertBuilder) Columns(columns ...string) UpsertBuilder

Columns adds column names to the query.

func (UpsertBuilder) Document

func (b UpsertBuilder) Document(key string, value any) UpsertBuilder

Document sets the document key and value for the UPSERT operation. Specific to Couchbase, uses (KEY, VALUE) syntax.

func (UpsertBuilder) Execute

func (b UpsertBuilder) Execute() (QueryResult, error)

Execute builds and executes the query.

func (UpsertBuilder) ExecuteContext

func (b UpsertBuilder) ExecuteContext(ctx context.Context) (QueryResult, error)

ExecuteContext builds and executes the query with the context and runner set by RunWith.

func (UpsertBuilder) Into

func (b UpsertBuilder) Into(into string) UpsertBuilder

Into sets the INTO clause of the query.

func (UpsertBuilder) MustN1ql

func (b UpsertBuilder) MustN1ql() (string, []any)

MustN1ql builds the query into a N1QL string and bound args.

MustN1ql panics if there are any errors.

func (UpsertBuilder) Options

func (b UpsertBuilder) Options(options ...string) UpsertBuilder

Options adds options to the query.

func (UpsertBuilder) PlaceholderFormat

func (b UpsertBuilder) PlaceholderFormat(f PlaceholderFormat) UpsertBuilder

PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the query.

func (UpsertBuilder) Prefix

func (b UpsertBuilder) Prefix(sql string, args ...any) UpsertBuilder

Prefix adds an expression to the beginning of the query

func (UpsertBuilder) PrefixExpr

func (b UpsertBuilder) PrefixExpr(expr N1qlizer) UpsertBuilder

PrefixExpr adds an expression to the beginning of the query

func (UpsertBuilder) RunWith

func (b UpsertBuilder) RunWith(runner QueryRunner) UpsertBuilder

RunWith sets a Runner (like a Couchbase DB connection) to be used with e.g. Execute.

func (UpsertBuilder) RunWithContext

func (b UpsertBuilder) RunWithContext(runner QueryRunnerContext) UpsertBuilder

RunWithContext sets a Runner (like a Couchbase DB connection with Context support) to be used with e.g. ExecuteContext.

func (UpsertBuilder) SetMap

func (b UpsertBuilder) SetMap(clauses map[string]any) UpsertBuilder

SetMap adds key-value pairs to set rather than a list of values.

func (UpsertBuilder) Suffix

func (b UpsertBuilder) Suffix(sql string, args ...any) UpsertBuilder

Suffix adds an expression to the end of the query

func (UpsertBuilder) SuffixExpr

func (b UpsertBuilder) SuffixExpr(expr N1qlizer) UpsertBuilder

SuffixExpr adds an expression to the end of the query

func (UpsertBuilder) ToN1ql

func (b UpsertBuilder) ToN1ql() (string, []any, error)

ToN1ql builds the query into a N1QL string and bound args.

func (UpsertBuilder) Values

func (b UpsertBuilder) Values(values ...any) UpsertBuilder

Values adds a single row's values to the query.

type UseIndex

type UseIndex struct {
	IndexName string
	IndexType string // "GSI" or "VIEW", etc.
}

UseIndex adds support for Couchbase's USE INDEX clause

func UseIndexGSI

func UseIndexGSI(indexName string) UseIndex

UseIndexGSI creates a USE INDEX clause for a GSI index

func UseIndexView

func UseIndexView(indexName string) UseIndex

UseIndexView creates a USE INDEX clause for a VIEW index

func (UseIndex) ToN1ql

func (ui UseIndex) ToN1ql() (string, []any, error)

ToN1ql implements N1qlizer

Jump to

Keyboard shortcuts

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