dal

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2024 License: MIT Imports: 13 Imported by: 138

Documentation

Index

Constants

View Source
const (
	SUM     = "SUM"
	COUNT   = "COUNT"
	MIN     = "MIN"
	MAX     = "MAX"
	AVERAGE = "AVG"
)
View Source
const (
	// DeleteField is used as a value in a call to Update or Set with merge to indicate
	// that the corresponding child should be deleted.
	DeleteField sentinel = iota

	// ServerTimestamp is used as a value in a call to Update to indicate that the
	// child's value should be set to the time at which the server processed
	// the request.
	//
	// ServerTimestamp 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.
	ServerTimestamp
)

Variables

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

ErrHookFailed indicates that error occurred during hook execution

View Source
var ErrNoMoreRecords = errors.New("no more errors")

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")
)
View Source
var NoError = errors.New("no error")

Functions

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

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

InsertWithRandomID inserts a record with a random ID

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 into 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 prefix 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[T any](reader Reader, getItem func(r Record) T, options ...ReaderOption) (items []T, err error)

SelectAll is a helper method that for a given reader returns all items as a slice.

func SelectAllIDs added in v0.2.14

func SelectAllIDs[T comparable](reader Reader, options ...ReaderOption) (ids []T, err error)

SelectAllIDs is a helper method that for a given reader returns all IDs as a strongly typed slice.

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)

func WithLimit added in v0.5.0

func WithLimit(limit int) func(ro *readerOptions)

func WithOffset added in v0.5.0

func WithOffset(offset int) func(ro *readerOptions)

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

type CollectionRef struct {
	Name   string
	Alias  string
	Parent *Key
}

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

func NewCollectionRef added in v0.2.17

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

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

	// TransactionCoordinator provides shortcut methods to work with transactions
	// without opening 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 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 Reader 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 FieldPath

type FieldPath []string

A FieldPath is a non-empty sequence of non-empty fields that reference a value.

A FieldPath value should only be necessary if one of the field names contains one of the runes ".˜*/[]". Most methods accept a simpler form of field path as a string in which the individual fields are separated by dots. For example,

[]string{"a", "b"}

is equivalent to the string form

"a.b"

but

[]string{"*"}

has no equivalent string form.

type FieldRef added in v0.2.6

type FieldRef struct {
	Name string
	IsID bool
}

func Field added in v0.2.6

func Field(name string) FieldRef

Field 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) 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:"Name"`
	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 Getter added in v0.2.27

type Getter interface {

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

Getter defines method to get a single record by key

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

type InsertOption

type InsertOption func(options *insertOptions)

InsertOption defines a contract for an insert option

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 in database
	Insert(ctx context.Context, record Record, opts ...InsertOption) error
}

Inserter defines a function to insert a single record into database

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 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 multiples records from database by keys
	GetMulti(ctx context.Context, records []Record) error
}

MultiGetter defines method to get multiples records from database by keys

type MultiSetter added in v0.2.27

type MultiSetter interface {

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

MultiSetter defines a function to store multiple records into 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, 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 {
	fmt.Stringer

	// From defines target table/collection
	From() *CollectionRef

	// Where defines filter condition
	Where() Condition

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

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

	// Columns defines what columns to return
	Columns() []Column

	// Into defines the type of the result
	Into() func() Record

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

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

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

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

Query represents a query to a collection

type QueryBuilder added in v0.2.11

type QueryBuilder interface {
	Offset(int) QueryBuilder
	Limit(int) QueryBuilder
	Where(conditions ...Condition) QueryBuilder
	WhereField(name string, operator Operator, v any) QueryBuilder
	OrderBy(expressions ...OrderExpression) QueryBuilder
	SelectInto(func() Record) Query
	SelectKeysOnly(idKind reflect.Kind) Query
	StartFrom(cursor Cursor) QueryBuilder
}

func From added in v0.2.6

func From(collection string, conditions ...Condition) QueryBuilder

type QueryExecutor added in v0.2.14

type QueryExecutor interface {

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

	// QueryAllRecords is a helper method that returns all records for the given query.
	// It reads reader created by QueryReader until it returns ErrNoMoreRecords.
	// If you are interested only in IDs, use like:
	//
	//		reader, err := queryExecutor.SelectReader(ctx)
	//      // handle err
	//		var ids []int
	//		ids, err = dal.SelectAllIDs[int](reader)
	QueryAllRecords(ctx context.Context, query Query) (records []Record, err error)
}

QueryExecutor is a query executor that returns a reader + related helper methods.

func NewQueryExecutor added in v0.2.14

func NewQueryExecutor(getReader ReaderProvider) QueryExecutor

NewQueryExecutor creates a new query executor. This is supposed to be used by dalgo DB drivers.

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 {

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

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

	// Close closes the reader
	Close() error
}

Reader reads records one by one

func NewRecordsReader added in v0.3.2

func NewRecordsReader(records []Record) Reader

type ReaderOption added in v0.5.0

type ReaderOption = func(ro *readerOptions)

type ReaderOptions added in v0.5.0

type ReaderOptions interface {
	Limit() int
	Offset() int
}

type ReaderProvider added in v0.2.14

type ReaderProvider = func(ctx context.Context, query Query) (reader Reader, err error)

ReaderProvider is a function that returns a Reader for the given query.

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 a `table` Name 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 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 ReadAll

func ReadAll(_ context.Context, reader Reader, limit int) (records []Record, err error)

ReadAll reads all records from a reader

func SelectAllRecords added in v0.2.14

func SelectAllRecords(reader Reader, options ...ReaderOption) (records []Record, err error)

SelectAllRecords 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 Setter added in v0.2.27

type Setter interface {

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

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

type SingleSource added in v0.2.6

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

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 TxWithReadonly

func TxWithReadonly() TransactionOption

TxWithReadonly requests a readonly transaction

type TransactionOptions

type TransactionOptions interface {

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

type Update struct {
	Field     string
	FieldPath FieldPath
	Value     any
}

Update defines an update of a single field

func (Update) Validate

func (v Update) Validate() error

Validate validates the update

type Updater added in v0.2.27

type Updater interface {

	// Update updates a single record in database by key
	Update(ctx context.Context, key *Key, updates []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

type WriteSession interface {
	//Connection // TODO
	Setter
	MultiSetter
	Deleter
	MultiDeleter
	Updater
	MultiUpdater
	Inserter
}

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