dal

package
v0.41.1 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2025 License: MIT Imports: 15 Imported by: 128

Documentation

Index

Constants

View Source
const (
	SUM     = "SUM"
	COUNT   = "COUNT"
	MIN     = "MIN"
	MAX     = "MAX"
	AVERAGE = "AVG"
)

Variables

View Source
var DefaultRandomStringIDLength = 16
View Source
var ErrExceedsMaxNumberOfAttempts = fmt.Errorf("exceeds maximum number of attempts")
View Source
var ErrHookFailed = errors.New("failed in dalgo hook")

ErrHookFailed indicates that error occurred during hook execution

View Source
var ErrLimitReached = fmt.Errorf("%w: limit reached", ErrNoMoreRecords)
View Source
var ErrNoError = errors.New("no error")
View Source
var ErrNoMoreRecords = fmt.Errorf("%w: no more errors", io.EOF)

ErrNoMoreRecords indicates there is no more records

View Source
var ErrNotImplementedYet = errors.New("not implemented yet")

ErrNotImplementedYet - return this if db name does not support requested operation yet.

View Source
var ErrNotSupported = errors.New("not supported")

ErrNotSupported - return this if db name does not support requested operation. (for example no support for transactions)

View Source
var ErrReaderClosed = errors.New("reader closed")
View Source
var ErrReaderNotStarted = errors.New("reader not started")
View Source
var (
	// ErrRecordNotFound is returned when a DB record is not found
	ErrRecordNotFound = errors.New("record not found")
)

Functions

func AnyRecordWithError added in v0.19.0

func AnyRecordWithError(records ...Record) error

func BeforeSave added in v0.2.9

func BeforeSave(ctx context.Context, db DB, record Record) error

func EqualKeys added in v0.2.4

func EqualKeys(k1 *Key, k2 *Key) bool

func EscapeID added in v0.2.23

func EscapeID(id string) string

func ExecuteQueryAndReadAllToRecordset added in v0.38.0

func ExecuteQueryAndReadAllToRecordset(ctx context.Context, query Query, qe QueryExecutor, options ...ReaderOption) (rs recordset.Recordset, err error)

func GetNonTransactionalContext

func GetNonTransactionalContext(ctx context.Context) context.Context

GetNonTransactionalContext returns non transaction context (e.g. Parent of transactional context) TODO: This is can be dangerous if child context creates a new context with a deadline for example

func InsertWithIdGenerator added in v0.20.0

func InsertWithIdGenerator(
	ctx context.Context,
	r Record,
	generateID IDGenerator,
	maxAttempts int,
	exists func(*Key) error,
	insert func(Record) error,
) error

func IsGroupOperator added in v0.2.6

func IsGroupOperator(o Operator) bool

IsGroupOperator says if an operator is a group operator

func IsNotFound

func IsNotFound(err error) bool

IsNotFound check if underlying error is ErrRecordNotFound

func NewContextWithTransaction

func NewContextWithTransaction(nonTransactionalContext context.Context, tx Transaction) context.Context

NewContextWithTransaction stores transaction and original context intoRecord a transactional context

func NewErrNotFoundByKey

func NewErrNotFoundByKey(key *Key, cause error) error

NewErrNotFoundByKey creates an error that indicates that entity was not found by value

func NewRollbackError

func NewRollbackError(rollbackErr, originalErr error) error

NewRollbackError creates a rollback error

func Prefix added in v0.3.3

func Prefix(prefix string) func(options *randomStringOptions)

Prefix sets prefix for a random string

func RandomLength added in v0.3.3

func RandomLength(length int) func(options *randomStringOptions)

RandomLength sets length for a random string

func RequiresEscaping added in v0.2.17

func RequiresEscaping(s string) bool

func SelectAll added in v0.5.0

func SelectAll(ctx context.Context, reader RecordsReader, addItem func(r Record), options ...ReaderOption) (err error)

SelectAll reads records from the provided RecordsReader and converts each Record to T using getItem. Behavior and caveats: - Panics if reader is nil (existing behavior). - Respects WithOffset by discarding the first offset records. - If WithLimit <= 0, reads until RecordsReader.Next() returns ErrNoMoreRecords. - Ensures reader.Close() is called; if Close returns an error and no prior error occurred, that error is returned. - Any panic inside getItem will propagate to the caller.

func SelectAllIDs added in v0.2.14

func SelectAllIDs[T comparable](ctx context.Context, reader RecordsReader, options ...ReaderOption) (ids []T, err error)

SelectAllIDs is a helper method that for a given reader returns all IDs as a strongly typed slice. Note: This will panic at runtime if the underlying ID types are not assignable to T.

func WithAfterLoad added in v0.4.0

func WithAfterLoad(hook RecordDataHook) func(rd *recordData)

func WithBeforeSave added in v0.4.0

func WithBeforeSave(hook RecordDataHook) func(rd *recordData)

Types

type Adapter added in v0.7.0

type Adapter interface {

	// Name of the dalgo adapter
	Name() string

	// Version of the name if applicable
	Version() string
}

Adapter describes adapter that provides access to data either through DB native client or direct implementation.

func NewAdapter added in v0.7.0

func NewAdapter(name, version string) Adapter

NewAdapter creates new client info. Former ClientInfo.

type Array added in v0.23.0

type Array struct {
	Value any `json:"value"`
}

func NewArray added in v0.23.0

func NewArray(v any) Array

func (Array) Equal added in v0.23.0

func (v Array) Equal(b Array) bool

func (Array) String added in v0.23.0

func (v Array) String() string

String returns string representation of a Constant

type Changes

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

Changes accumulates DB changes

func (*Changes) FlagAsChanged

func (changes *Changes) FlagAsChanged(record Record)

FlagAsChanged flags a record as changed

func (*Changes) HasChanges

func (changes *Changes) HasChanges() bool

HasChanges returns true if there are changes

func (*Changes) IsChanged

func (changes *Changes) IsChanged(record Record) bool

IsChanged returns true if entity changed

func (*Changes) Records added in v0.2.4

func (changes *Changes) Records() (records []Record)

Records returns list of entity holders

type CollectionGroupRef added in v0.22.0

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

func NewCollectionGroupRef added in v0.22.0

func NewCollectionGroupRef(name, alias string) CollectionGroupRef

func (CollectionGroupRef) Alias added in v0.22.0

func (v CollectionGroupRef) Alias() string

func (CollectionGroupRef) Name added in v0.22.0

func (v CollectionGroupRef) Name() string

func (CollectionGroupRef) String added in v0.22.0

func (v CollectionGroupRef) String() string

type CollectionRef

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

CollectionRef points to a recordsetSource (e.g. table) in a database

func NewCollectionRef added in v0.2.17

func NewCollectionRef(name, alias string, parent *Key) (collectionRef CollectionRef)

func NewRootCollectionRef added in v0.15.0

func NewRootCollectionRef(name, alias string) CollectionRef

func (CollectionRef) Alias added in v0.2.16

func (v CollectionRef) Alias() string

func (CollectionRef) Equal added in v0.27.0

func (v CollectionRef) Equal(other CollectionRef, ignoreAlias bool) bool

func (CollectionRef) Name

func (v CollectionRef) Name() string

func (CollectionRef) Parent

func (v CollectionRef) Parent() *Key

func (CollectionRef) Path

func (v CollectionRef) Path() string

func (CollectionRef) String added in v0.2.16

func (v CollectionRef) String() string

type Column added in v0.2.6

type Column struct {
	Alias      string     `json:"Alias"`
	Expression Expression `json:"expression"`
}

Column reference a column in a SELECT statement

func AverageAs added in v0.2.6

func AverageAs(expression Expression, alias string) Column

AverageAs returns average value for a given expression

func CountAs added in v0.2.6

func CountAs(expression Expression, alias string) Column

CountAs aggregate function (see SQL COUNT())

func MaxAs added in v0.2.6

func MaxAs(expression Expression, alias string) Column

MaxAs returns maximum value for a given expression

func MinAs added in v0.2.6

func MinAs(expression Expression, alias string) Column

MinAs returns minimum value for a given expression

func SumAs added in v0.2.6

func SumAs(expression Expression, alias string) Column

SumAs aggregate function (see SQL SUM())

func (Column) String added in v0.2.6

func (v Column) String() string

String stringifies column value

type Comparison added in v0.2.6

type Comparison struct {
	Operator Operator
	Left     Expression
	Right    Expression
}

Comparison defines a contact for a comparison

func NewComparison added in v0.2.6

func NewComparison(left Expression, o Operator, right Expression) Comparison

NewComparison creates new Comparison

func (Comparison) Equal added in v0.2.6

func (v Comparison) Equal(b Comparison) bool

func (Comparison) String added in v0.2.6

func (v Comparison) String() string

String returns string representation of a comparison

type Condition added in v0.2.6

type Condition interface {
	fmt.Stringer
}

func WhereField added in v0.2.6

func WhereField(name string, operator Operator, v any) Condition

type Constant added in v0.2.15

type Constant struct {
	Value any `json:"value"`
}

func NewConstant added in v0.23.0

func NewConstant(v any) Constant

func (Constant) Equal added in v0.2.15

func (v Constant) Equal(b Constant) bool

func (Constant) String added in v0.2.15

func (v Constant) String() string

String returns string representation of a Constant

type Cursor added in v0.2.19

type Cursor string

type DB added in v0.8.0

type DB interface {

	// ID is an identifier provided at time of DB creation
	ID() string

	// Adapter provides information about underlying name to access data
	Adapter() Adapter

	// Schema provides schema for the DB - for example, how keys are mapped to columns
	Schema() Schema

	// TransactionCoordinator provides shortcut methods to work with transactions
	// without opening a connection explicitly.
	TransactionCoordinator

	// ReadSession implements a virtual read session that opens connection/session for each read call on DB level
	// TODO: consider to sacrifice some simplicity for the sake of interoperability?
	ReadSession
}

DB is an interface that defines a database provider

type DataToKeyFunc added in v0.25.0

type DataToKeyFunc func(incompleteKey *Key, data any) (key *Key, err error)

DataToKeyFunc takes data retrieved from DB table/view/query and maps primary key columns to the record key.

type DataWrapper added in v0.4.0

type DataWrapper interface {
	Data() any
}

DataWrapper is a wrapper for data transfer objects (DTOs). TODO: document intended usage or consider removing as it makes implementation of RecordsReader more complex.

func MakeRecordData added in v0.2.7

func MakeRecordData(data any, options ...RecordDataOption) DataWrapper

MakeRecordData creates a DataWrapper with the given data and options.

type Deleter added in v0.2.27

type Deleter interface {

	// Delete deletes a single record from database by key
	Delete(ctx context.Context, key *Key) error
}

Deleter defines a function to delete a single record from database by key

type EmptyReader added in v0.3.1

type EmptyReader struct{}

func (EmptyReader) Close added in v0.3.1

func (e EmptyReader) Close() error

func (EmptyReader) Cursor added in v0.3.1

func (e EmptyReader) Cursor() (string, error)

func (EmptyReader) Next added in v0.3.1

func (e EmptyReader) Next() (Record, error)

type ErrDuplicateUser

type ErrDuplicateUser struct {
	// TODO: Should it be moved out of this package to strongo/app/user?
	SearchCriteria   string
	DuplicateUserIDs []string
}

ErrDuplicateUser indicates there is a duplicate user // TODO: move to strongo/app?

func (ErrDuplicateUser) Error

func (err ErrDuplicateUser) Error() string

Error implements error interface

type ErrNotFoundByKey

type ErrNotFoundByKey interface {
	Key() *Key
	Cause() error
	error
}

ErrNotFoundByKey indicates error was not found by value

type Expression added in v0.2.6

type Expression interface {
	fmt.Stringer
}

Expression represent either a FieldRef, Constant or a formula

func ID added in v0.2.6

func ID(name string, value any) Expression

ID creates an expression that compares an ID with a constant

func String added in v0.2.6

func String(v string) Expression

String creates a new Constant expression

type ExtraField added in v0.25.0

type ExtraField interface {
	Name() string
	Value() any
}

func NewExtraField added in v0.25.0

func NewExtraField(name string, value any) ExtraField

type FieldName added in v0.25.0

type FieldName string

FieldName represents a field name as string (for backward compatibility)

func (FieldName) String added in v0.25.0

func (f FieldName) String() string

String implements Expression interface

type FieldRef added in v0.2.6

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

func Field added in v0.2.6

func Field(name string) FieldRef

Field creates a FieldRef with the given name

func NewFieldRef added in v0.25.0

func NewFieldRef(name string) FieldRef

NewFieldRef creates an expression that represents a FieldRef value

func (FieldRef) Equal added in v0.2.6

func (f FieldRef) Equal(b FieldRef) bool

func (FieldRef) EqualTo added in v0.2.6

func (f FieldRef) EqualTo(v any) Condition

EqualTo creates equality condition for a field

func (FieldRef) IsID added in v0.2.6

func (f FieldRef) IsID() bool

func (FieldRef) Name added in v0.2.6

func (f FieldRef) Name() string

func (FieldRef) String added in v0.2.6

func (f FieldRef) String() string

String returns string representation of a field

type FieldVal

type FieldVal struct {
	Name  string `json:"NewFieldRef"`
	Value any    `json:"value"`
}

FieldVal hold a reference to a single record within a root or nested recordset.

func (FieldVal) Validate

func (v FieldVal) Validate() error

Validate validates field value

type FromSource added in v0.28.0

type FromSource interface {
	Base() RecordsetSource
	Join(joint JoinedSource) FromSource
	Joins() []JoinedSource
	NewQuery() *QueryBuilder
}

func From added in v0.2.6

func From(source RecordsetSource) FromSource

From creates a new IQueryBuilder with optional conditions. We can use NewQueryBuilder() directly but this is shorter.

type Getter added in v0.2.27

type Getter interface {

	// Get gets a single record from a database by key
	Get(ctx context.Context, record Record) error

	// Exists returns true if a record with the given key exists
	Exists(ctx context.Context, key *Key) (bool, error)
}

Getter defines a method to get a single record by key or check its existence

type GroupCondition added in v0.2.15

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

func (GroupCondition) Conditions added in v0.2.15

func (v GroupCondition) Conditions() []Condition

func (GroupCondition) Operator added in v0.2.15

func (v GroupCondition) Operator() Operator

func (GroupCondition) String added in v0.2.15

func (v GroupCondition) String() string

type IDGenerator

type IDGenerator = func(ctx context.Context, record Record) error

IDGenerator defines a contract for ID generator function

func NewIDGenerator added in v0.20.0

func NewIDGenerator(f IDGenerator, maxAttempts int) IDGenerator

type IQueryBuilder added in v0.28.0

type IQueryBuilder interface {
	Clone() IQueryBuilder
	Offset(int) IQueryBuilder
	Limit(int) IQueryBuilder
	Where(conditions ...Condition) IQueryBuilder
	WhereField(name string, operator Operator, v any) IQueryBuilder
	WhereInArrayField(name string, v any) IQueryBuilder
	OrderBy(expressions ...OrderExpression) IQueryBuilder
	SelectIntoRecord(func() Record) StructuredQuery
	SelectIntoRecordset(options ...recordset.Option) StructuredQuery
	SelectKeysOnly(idKind reflect.Kind) StructuredQuery
	StartFrom(cursor Cursor) IQueryBuilder
}

type InsertOption

type InsertOption func(options *insertOptions)

InsertOption defines a contract for an insert option

func WithRandomStringKey added in v0.20.0

func WithRandomStringKey(length, maxAttempts int) InsertOption

func WithRandomStringKeyPrefixedByUnixTime added in v0.21.1

func WithRandomStringKeyPrefixedByUnixTime(randomLength, maxAttempts int) InsertOption

func WithTimeStampStringID added in v0.24.0

func WithTimeStampStringID(accuracy TimeStampAccuracy, base, maxAttempts int) InsertOption

type InsertOptions

type InsertOptions interface {
	IDGenerator() IDGenerator
}

InsertOptions defines interface for insert options

func NewInsertOptions

func NewInsertOptions(opts ...InsertOption) InsertOptions

NewInsertOptions creates insert options

type Inserter added in v0.2.27

type Inserter interface {

	// Insert inserts a single record intoRecord a database
	Insert(ctx context.Context, record Record, opts ...InsertOption) error
}

Inserter defines a function to insert a single record intoRecord a database

type JoinedSource added in v0.28.0

type JoinedSource struct {
	RecordsetSource
	// contains filtered or unexported fields
}

func (*JoinedSource) On added in v0.28.0

func (j *JoinedSource) On() []Condition

type Key

type Key struct {
	ID     any
	IDKind reflect.Kind
	// contains filtered or unexported fields
}

Key represents a full path to a given record (no Parent in case of root recordset)

func NewIncompleteKey added in v0.2.6

func NewIncompleteKey(collection string, idKind reflect.Kind, parent *Key) *Key

func NewKeyWithFields

func NewKeyWithFields(collection string, fields ...FieldVal) *Key

NewKeyWithFields creates a new record key from a sequence of record's references

func NewKeyWithID

func NewKeyWithID[T comparable](collection string, id T) (key *Key)

NewKeyWithID creates a new key with an ID We need to make it generic to enforce `comparable` restriction on Key.ID

func NewKeyWithOptions added in v0.3.0

func NewKeyWithOptions(collection string, options ...KeyOption) (key *Key, err error)

NewKeyWithOptions creates a new key with an ID

func NewKeyWithParentAndID added in v0.3.0

func NewKeyWithParentAndID[T comparable](parent *Key, collection string, id T) (key *Key)

func (*Key) Collection

func (k *Key) Collection() string

Collection returns reference to colection

func (*Key) CollectionPath

func (k *Key) CollectionPath() string

CollectionPath return path to Parent

func (*Key) Equal added in v0.2.4

func (k *Key) Equal(key *Key) bool

func (*Key) Level

func (k *Key) Level() int

Level returns level of key (e.g. how many parents it have)

func (*Key) Parent

func (k *Key) Parent() *Key

Parent return a reference to the Parent key

func (*Key) String

func (k *Key) String() string

String returns string representation of a key instance

func (*Key) Validate

func (k *Key) Validate() error

Validate validate key

type KeyOption

type KeyOption = func(*Key) error

KeyOption defines contract for key option

func WithFields

func WithFields(fields []FieldVal) KeyOption

WithFields sets a list of field values as key ID

func WithID

func WithID[T comparable](id T) KeyOption

WithID sets ID of a key

func WithIDGenerator

func WithIDGenerator(ctx context.Context, g IDGenerator) KeyOption

WithIDGenerator sets ID generator for a random string (usually random)

func WithIntID added in v0.10.1

func WithIntID(id int) KeyOption

WithIntID sets ID as a predefined int

func WithKeyID added in v0.10.1

func WithKeyID[T comparable](id T) KeyOption

WithKeyID sets ID as a predefined value. It's advised to use WithIntID and WithStringID when possible.

func WithParentKey

func WithParentKey(parent *Key) KeyOption

WithParentKey sets Parent key

func WithRandomStringID

func WithRandomStringID(options ...randomStringOption) KeyOption

WithRandomStringID sets ID generator to random string

func WithStringID

func WithStringID(id string) KeyOption

WithStringID sets ID as a predefined string

type KeyToFieldsFunc added in v0.25.0

type KeyToFieldsFunc func(key *Key, data any) (fields []ExtraField, err error)

KeyToFieldsFunc takes key and should either populate fields on a `data` struct or return extra fields to be stored to the target table.

type MultiDeleter added in v0.2.27

type MultiDeleter interface {

	// DeleteMulti deletes multiple records from database by keys
	DeleteMulti(ctx context.Context, keys []*Key) error
}

MultiDeleter defines a function to delete multiple records from database by keys

type MultiGetter added in v0.2.27

type MultiGetter interface {

	// GetMulti gets multiple records from a database by keys
	GetMulti(ctx context.Context, records []Record) error
}

MultiGetter defines method to get multiple records from a database by keys

type MultiInserter added in v0.13.0

type MultiInserter interface {
	// InsertMulti inserts multiple record intoRecord a database at once if possible, or fallback to batch of single inserts
	InsertMulti(ctx context.Context, records []Record, opts ...InsertOption) error
}

MultiInserter defines a function to insert multiple records intoRecord a database

type MultiSetter added in v0.2.27

type MultiSetter interface {

	// SetMulti stores multiples records intoRecord database by keys
	SetMulti(ctx context.Context, records []Record) error
}

MultiSetter defines a function to store multiple records intoRecord database by keys

type MultiUpdater added in v0.2.27

type MultiUpdater interface {

	// UpdateMulti updates multiples records in database by keys
	UpdateMulti(ctx context.Context, keys []*Key, updates []update.Update, preconditions ...Precondition) error
}

MultiUpdater defines a function to update multiples records in database by keys

type Operator added in v0.2.6

type Operator string

Operator defines a Comparison operator

const (
	// Equal is a Comparison operator
	Equal Operator = "=="

	// In is a Comparison operator
	In Operator = "In"

	// GreaterThen is a Comparison operator
	GreaterThen Operator = ">"

	// GreaterOrEqual is a Comparison operator
	GreaterOrEqual Operator = ">="

	// LessThen is a Comparison operator
	LessThen Operator = "<"

	// LessOrEqual is a Comparison operator
	LessOrEqual Operator = "<="

	// And is a Comparison operator // TODO: Is it an operator?
	And = "AND"

	// Or is a Comparison operator // TODO: Is it an operator?
	Or = "OR"
)

type OrderExpression added in v0.2.6

type OrderExpression interface {
	fmt.Stringer
	Expression() Expression
	Descending() bool
}

func Ascending added in v0.2.6

func Ascending(expression Expression) OrderExpression

func AscendingField added in v0.2.6

func AscendingField(name string) OrderExpression

func Descending added in v0.2.6

func Descending(expression Expression) OrderExpression

func DescendingField added in v0.2.6

func DescendingField(name string) OrderExpression

type Precondition

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

Precondition defines precondition

func WithExistsPrecondition

func WithExistsPrecondition() Precondition

WithExistsPrecondition sets exists precondition

func WithLastUpdateTimePrecondition

func WithLastUpdateTimePrecondition(t time.Time) Precondition

WithLastUpdateTimePrecondition sets last update time

type Preconditions

type Preconditions interface {
	Exists() bool
	LastUpdateTime() time.Time
}

Preconditions defines preconditions

func GetPreconditions

func GetPreconditions(items ...Precondition) Preconditions

GetPreconditions create Preconditions

type Query added in v0.2.6

type Query interface {
	String() string

	// Offset specifies the number of records to skip
	Offset() int

	// Limit specifies the maximum number of records to be returned
	Limit() int

	GetRecordsReader(ctx context.Context, qe QueryExecutor) (reader RecordsReader, err error)
	GetRecordsetReader(ctx context.Context, qe QueryExecutor) (reader RecordsetReader, err error)
}

type QueryArg added in v0.27.0

type QueryArg struct {
	Name  string
	Value any
}

type QueryBuilder added in v0.2.11

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

func NewQueryBuilder added in v0.15.0

func NewQueryBuilder(from FromSource) *QueryBuilder

NewQueryBuilder creates a new IQueryBuilder - it's an entry point to build a query. We can use From() directly but this is easier to remember.

func (*QueryBuilder) Clone added in v0.28.0

func (s *QueryBuilder) Clone() IQueryBuilder

func (*QueryBuilder) Limit added in v0.2.16

func (s *QueryBuilder) Limit(i int) IQueryBuilder

func (*QueryBuilder) Offset added in v0.2.16

func (s *QueryBuilder) Offset(i int) IQueryBuilder

func (*QueryBuilder) OrderBy added in v0.2.11

func (s *QueryBuilder) OrderBy(expressions ...OrderExpression) IQueryBuilder

func (*QueryBuilder) SelectIntoRecord added in v0.34.0

func (s *QueryBuilder) SelectIntoRecord(into func() Record) StructuredQuery

func (*QueryBuilder) SelectIntoRecordset added in v0.34.0

func (s *QueryBuilder) SelectIntoRecordset(options ...recordset.Option) StructuredQuery

func (*QueryBuilder) SelectKeysOnly added in v0.2.11

func (s *QueryBuilder) SelectKeysOnly(idKind reflect.Kind) StructuredQuery

func (*QueryBuilder) StartFrom added in v0.2.19

func (s *QueryBuilder) StartFrom(cursor Cursor) IQueryBuilder

func (*QueryBuilder) Where added in v0.2.11

func (s *QueryBuilder) Where(conditions ...Condition) IQueryBuilder

func (*QueryBuilder) WhereField added in v0.2.11

func (s *QueryBuilder) WhereField(name string, operator Operator, v any) IQueryBuilder

func (*QueryBuilder) WhereInArrayField added in v0.16.1

func (s *QueryBuilder) WhereInArrayField(name string, v any) IQueryBuilder

type QueryExecutor added in v0.2.14

type QueryExecutor interface {

	// ExecuteQueryToRecordsReader returns a reader for the given query to read records 1 by 1 sequentially.
	// The RecordsReader.Next() method returns ErrNoMoreRecords when there are no more records.
	ExecuteQueryToRecordsReader(ctx context.Context, query Query) (RecordsReader, error)

	// ExecuteQueryToRecordsetReader returns a RecordsetReader for the given query, allowing sequential read of records into the provided recordset.
	ExecuteQueryToRecordsetReader(ctx context.Context, query Query, options ...recordset.Option) (RecordsetReader, error)
}

QueryExecutor is a query executor that returns a reader and have few helper methods.

type ROTxWorker

type ROTxWorker = func(ctx context.Context, tx ReadTransaction) error

ROTxWorker defines a callback to be called to do work within a readonly transaction

type RWTxWorker

type RWTxWorker = func(ctx context.Context, tx ReadwriteTransaction) error

RWTxWorker defines a callback to be called to do work within a readwrite transaction

type RandomStringOptions

type RandomStringOptions interface {
	Prefix() string
	Length() int
}

RandomStringOptions defines settings for random string

type ReadSession

type ReadSession interface {
	Getter
	MultiGetter
	QueryExecutor
}

ReadSession defines methods that query data from DB and does not modify it

type ReadTransaction

type ReadTransaction interface {
	Transaction
	ReadSession
}

ReadTransaction defines an interface for a readonly transaction

type ReadTransactionCoordinator

type ReadTransactionCoordinator interface {

	// RunReadonlyTransaction starts readonly transaction
	RunReadonlyTransaction(ctx context.Context, f ROTxWorker, options ...TransactionOption) error
}

ReadTransactionCoordinator creates a readonly transaction

type Reader

type Reader interface {
	// Cursor points to a position in the result set. This can be used for pagination.
	Cursor() (string, error)

	// Close closes the reader
	Close() error
}

type ReaderOption added in v0.5.0

type ReaderOption = func(ro *ReaderOptions)

ReaderOption configures how SelectAll reads from the RecordsReader (e.g., limit, offset).

func WithLimit added in v0.5.0

func WithLimit(limit int) ReaderOption

WithLimit sets the maximum number of items to read. If limit <= 0, SelectAll reads until ErrNoMoreRecords.

func WithOffset added in v0.5.0

func WithOffset(offset int) ReaderOption

WithOffset skips the first N records before collecting results in SelectAll. If offset <= 0, no records are skipped.

type ReaderOptions added in v0.5.0

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

func (*ReaderOptions) Limit added in v0.5.0

func (ro *ReaderOptions) Limit() int

Limit specifies the maximum number of records to read, if 0 - unlimited

func (*ReaderOptions) Offset added in v0.5.0

func (ro *ReaderOptions) Offset() int

Offset specifies how many records to skip, if 0 - no records are skipped

type ReadwriteSession

type ReadwriteSession interface {
	ReadSession
	WriteSession
}

ReadwriteSession defines methods that can read & modify database. Some databases allow to modify data without transaction.

type ReadwriteTransaction

type ReadwriteTransaction interface {

	// ID returns a unique ID of a transaction if it is supported by the underlying DB client
	ID() string

	Transaction
	ReadwriteSession
}

ReadwriteTransaction defines an interface for a readwrite transaction

type ReadwriteTransactionCoordinator

type ReadwriteTransactionCoordinator interface {

	// RunReadwriteTransaction starts read-write transaction
	RunReadwriteTransaction(ctx context.Context, f RWTxWorker, options ...TransactionOption) error
}

ReadwriteTransactionCoordinator creates a read-write transaction

type Record

type Record interface {
	// Key keeps fields  of an entity and an ID within that table or a chain of nested keys
	Key() *Key

	// Error keeps an error for the last operation on the record. Not found is not treated as an error
	Error() error

	// Exists indicates if record was found in database. Throws panic if called before a `Get` or `Set`.
	Exists() bool

	// SetError sets error relevant to specific record. Intended to be used only by DALgo DB drivers.
	// Returns the record itself for convenience.
	SetError(err error) Record

	// Data returns record data (without ID/key).
	// Requires either record to be created by NewRecordWithData()
	// or DataTo() to be called first, otherwise panics.
	Data() any

	// HasChanged & MarkAsChanged are methods of convenience
	HasChanged() bool

	// MarkAsChanged & HasChanged are methods of convenience
	MarkAsChanged()
}

Record is a gateway to a database record.

func ExecuteQueryAndReadAllToRecords added in v0.35.1

func ExecuteQueryAndReadAllToRecords(ctx context.Context, query Query, qe QueryExecutor, options ...ReaderOption) (records []Record, err error)

func NewRecord

func NewRecord(key *Key) Record

NewRecord creates a new record

func NewRecordWithData

func NewRecordWithData(key *Key, data any) Record

NewRecordWithData creates a new record with a data target struct

func NewRecordWithIncompleteKey added in v0.2.6

func NewRecordWithIncompleteKey(collection string, idKind reflect.Kind, data any) Record

NewRecordWithIncompleteKey creates a new record with an incomplete key This is mostly intended for use in Select queries

func NewRecordWithoutKey

func NewRecordWithoutKey(data any) Record

func ReadAllToRecords added in v0.33.0

func ReadAllToRecords(ctx context.Context, reader RecordsReader, options ...ReaderOption) (records []Record, err error)

ReadAllToRecords is a helper method that for a given reader returns all records as a slice.

type RecordAfterLoadHook added in v0.2.7

type RecordAfterLoadHook interface {
	AfterLoad(ctx context.Context, key *Key) (err error)
}

type RecordBeforeSaveHook added in v0.2.7

type RecordBeforeSaveHook interface {
	BeforeSave(ctx context.Context, key *Key) (err error)
}

type RecordDataHook added in v0.2.9

type RecordDataHook = func(ctx context.Context, db DB, key *Key, data any) (err error)

type RecordDataOption added in v0.4.0

type RecordDataOption = func(rd *recordData)

type RecordHook added in v0.2.9

type RecordHook = func(ctx context.Context, record Record) error

type RecordsReader added in v0.3.1

type RecordsReader interface {
	Reader
	// Next returns the next record for a query.
	// If no more records, a nil record and ErrNoMoreRecords are returned.
	Next() (Record, error)
}

RecordsReader reads records one by one into Record

func NewRecordsReader added in v0.3.2

func NewRecordsReader(records []Record) RecordsReader

type RecordsetReader added in v0.34.0

type RecordsetReader interface {
	Reader
	Recordset() recordset.Recordset
	Next() (row recordset.Row, rs recordset.Recordset, err error)
}

RecordsetReader reads records one by one into recordset.Recordset

type RecordsetSource added in v0.22.0

type RecordsetSource interface {
	Name() string
	Alias() string
	// contains filtered or unexported methods
}

type Schema added in v0.25.0

type Schema interface {
	DataToKey(incompleteKey *Key, data any) (key *Key, err error)
	KeyToFields(key *Key, data any) (fields []ExtraField, err error)
}

func NewSchema added in v0.25.0

func NewSchema(keyToField KeyToFieldsFunc, dataToKey DataToKeyFunc) Schema

type SchemaBase added in v0.26.0

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

SchemaBase provides rules for mapping of fields, keys and collections

func (*SchemaBase) DataToKey added in v0.26.0

func (s *SchemaBase) DataToKey(incompleteKey *Key, data any) (key *Key, err error)

DataToKey creates a *Key from data read from DB

func (*SchemaBase) KeyToFields added in v0.26.0

func (s *SchemaBase) KeyToFields(key *Key, data any) (fields []ExtraField, err error)

KeyToFields maps key intoRecord DB fields. This is needed as relational DBs usually have key column(s) that are part of the record set, while key-value DBs can have key and data separated and data would not include the key.

type Setter added in v0.2.27

type Setter interface {

	// Set stores a single record intoRecord database by key
	Set(ctx context.Context, record Record) error
}

Setter defines a function to store a single record intoRecord database by key

type SingleSource added in v0.2.6

type SingleSource interface {
	Where(conditions ...Condition) IQueryBuilder
}

type StructuredQuery added in v0.27.0

type StructuredQuery interface {
	Query

	// From - defines target table/recordsetSource
	From() FromSource

	// Where defines filter condition
	Where() Condition

	// GroupBy defines expressions to group by
	GroupBy() []Expression

	// OrderBy defines expressions to order by
	OrderBy() []OrderExpression

	// Columns specifies columns to return
	Columns() []Column

	// IntoRecord provides a function that creates a record for a new row
	IntoRecord() Record // TODO: Should this be moved into Query.GetRecordsReader ?

	// IDKind defines the type of the ID
	IDKind() reflect.Kind // TODO: what about composite keys?

	// StartFrom specifies the startCursor/point to start from
	StartFrom() Cursor
}

StructuredQuery represents a query to a recordsetSource

type TextQuery added in v0.27.0

type TextQuery interface {
	Query
	Text() string
	Args() []QueryArg
}

TextQuery defines an interface to represent a query with text and associated arguments.

func NewTextQuery added in v0.27.0

func NewTextQuery(text string, getKey func(data any, args []QueryArg) *Key, args ...QueryArg) TextQuery

type TimeStampAccuracy added in v0.24.0

type TimeStampAccuracy int
const (
	TimeStampAccuracyNano TimeStampAccuracy = iota
	TimeStampAccuracyMicrosecond
	TimeStampAccuracyMillisecond
	TimeStampAccuracySecond
	TimeStampAccuracyMinute
	TimeStampAccuracyHour
	TimeStampAccuracyDay
)

type Transaction

type Transaction interface {
	// Options indicates parameters that were requested at time of transaction creation.
	Options() TransactionOptions
}

Transaction defines an instance of DALgo transaction

func GetTransaction

func GetTransaction(ctx context.Context) Transaction

GetTransaction returns original transaction object

type TransactionCoordinator

type TransactionCoordinator interface {

	// ReadTransactionCoordinator can start a readonly transaction
	ReadTransactionCoordinator

	// ReadwriteTransactionCoordinator can start a readwrite transaction
	ReadwriteTransactionCoordinator
}

TransactionCoordinator provides methods to work with transactions

type TransactionOption

type TransactionOption func(options *txOptions)

TransactionOption defines contact for transaction option

func TxWithAttempts

func TxWithAttempts(attempts int) TransactionOption

TxWithAttempts specifies number of attempts to execute a transaction

func TxWithCrossGroup

func TxWithCrossGroup() TransactionOption

TxWithCrossGroup requires transaction that spans multiple entity groups

func TxWithIsolationLevel

func TxWithIsolationLevel(isolationLevel TxIsolationLevel) TransactionOption

TxWithIsolationLevel requests transaction with required isolation level

func TxWithName added in v0.26.1

func TxWithName(name string) TransactionOption

TxWithName specifies number of attempts to execute a transaction

func TxWithReadonly

func TxWithReadonly() TransactionOption

TxWithReadonly requests a readonly transaction

type TransactionOptions

type TransactionOptions interface {

	// Name describes what will be done in transaction.
	// This is useful for mocking transaction in tests
	Name() string

	// IsolationLevel indicates requested isolation level
	IsolationLevel() TxIsolationLevel

	// IsReadonly indicates a readonly transaction
	IsReadonly() bool

	// IsCrossGroup indicates a cross-group transaction. Makes sense for Google App Engine.
	IsCrossGroup() bool

	// Attempts returns number of attempts to execute a transaction. This is used in Google Datastore for example.
	Attempts() int
}

TransactionOptions holds transaction settings

func NewTransactionOptions

func NewTransactionOptions(opts ...TransactionOption) TransactionOptions

NewTransactionOptions creates instance of TransactionOptions

type Transform

type Transform interface {

	// Name returns Name of a transform
	Name() string

	// Value returns arguments of transform
	Value() any
}

Transform defines a transform operation

func ArrayUnion

func ArrayUnion(elems ...any) Transform

ArrayUnion specifies elements to be added to whatever array already exists in the server, or to create an array if no value exists.

If a value exists and it's an array, values are appended to it. Any duplicate value is ignored. If a value exists and it's not an array, the value is replaced by an array of the values in the ArrayUnion. If a value does not exist, an array of the values in the ArrayUnion is created.

ArrayUnion must be the value of a field directly; it cannot appear in array or struct values, or in any value that is itself inside an array or struct.

func Increment

func Increment(v int) Transform

Increment defines an increment transform operation

func IsTransform

func IsTransform(v any) (t Transform, ok bool)

type TxIsolationLevel

type TxIsolationLevel int

TxIsolationLevel defines an isolation level for a transaction

const (
	// TxUnspecified indicates transaction level is not specified
	TxUnspecified TxIsolationLevel = iota

	// TxChaos - The pending changes from more highly isolated transactions cannot be overwritten.
	TxChaos

	// TxReadCommitted - Shared locks are held while the data is being read to avoid dirty reads,
	// but the data can be changed before the end of the transaction,
	// resulting in non-repeatable reads or phantom data.
	TxReadCommitted

	// TxReadUncommitted - A dirty read is possible, meaning that no shared locks are issued
	// and no exclusive locks are honored.
	TxReadUncommitted

	// TxRepeatableRead - Locks are placed on all data that is used in a query,
	// preventing other users from updating the data.
	// Prevents non-repeatable reads but phantom rows are still possible.
	TxRepeatableRead

	// TxSerializable - A range lock is placed on the DataSet, preventing other users
	// from updating or inserting rows intoRecord the dataset until the transaction is complete.
	TxSerializable

	// TxSnapshot - Reduces blocking by storing a version of data that one application can read
	// while another is modifying the same data.
	// Indicates that from one transaction you cannot see changes made in other transactions,
	// even if you requery.
	TxSnapshot
)

type Updater added in v0.2.27

type Updater interface {

	// Update updates a single record in a database by key
	Update(ctx context.Context, key *Key, updates []update.Update, preconditions ...Precondition) error

	// UpdateRecord updates a single record in a database.
	// For example, this is useful in case if we want to put the record.Data to memcache.
	// See https://github.com/dal-go/dalgo-memcache-appengine
	// A regular DB adapter should call update(record.Key()) inside this method.
	UpdateRecord(ctx context.Context, record Record, updates []update.Update, preconditions ...Precondition) error
}

Updater defines a function to update a single record in database by key

type ValidatableRecord added in v0.2.9

type ValidatableRecord interface {
	Validate() error
}

type WriteSession

WriteSession defines methods that can modify database

Jump to

Keyboard shortcuts

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