Documentation ¶
Index ¶
- Constants
- Variables
- func BeforeSave(c context.Context, db Database, record Record) error
- func EqualKeys(k1 *Key, k2 *Key) bool
- func EscapeID(id string) string
- func GetNonTransactionalContext(ctx context.Context) context.Context
- func InsertWithRandomID(c context.Context, r Record, generateID IDGenerator, attempts int, ...) error
- func IsGroupOperator(o Operator) bool
- func IsNotFound(err error) bool
- func NewContextWithTransaction(nonTransactionalContext context.Context, tx Transaction) context.Context
- func NewErrNotFoundByKey(key *Key, cause error) error
- func NewRollbackError(rollbackErr, originalErr error) error
- func RequiresEscaping(s string) bool
- func SelectAllIDs[T comparable](reader Reader, limit int) (ids []T, err error)
- func WithPrefix(prefix string) func(options *randomStringOptions)
- type Changes
- type ClientInfo
- type CollectionRef
- type Column
- type Comparison
- type Condition
- type Constant
- type Cursor
- type Data
- type Database
- type ErrDuplicateUser
- type ErrNotFoundByKey
- type Expression
- type FieldPath
- type FieldRef
- type FieldVal
- type GroupCondition
- type IDGenerator
- type InsertOption
- type InsertOptions
- type Key
- type KeyOption
- func WithFields(fields []FieldVal) KeyOption
- func WithID[T comparable](id T) KeyOption
- func WithIDGenerator(g IDGenerator) KeyOption
- func WithParent(collection string, id any, options ...KeyOption) KeyOption
- func WithParentKey(parent *Key) KeyOption
- func WithRandomStringID(length int, options ...randomStringOption) KeyOption
- func WithStringID(id string) KeyOption
- type Operator
- type OrderExpression
- type Precondition
- type Preconditions
- type Query
- type QueryBuilder
- type QueryExecutor
- type ROTxWorker
- type RWTxWorker
- type RandomStringOptions
- type ReadSession
- type ReadTransaction
- type ReadTransactionCoordinator
- type Reader
- type ReaderProvider
- type ReadwriteSession
- type ReadwriteTransaction
- type ReadwriteTransactionCoordinator
- type Record
- func NewRecord(key *Key) Record
- func NewRecordWithData(key *Key, data any) Record
- func NewRecordWithIncompleteKey(collection string, idKind reflect.Kind, data any) Record
- func NewRecordWithoutKey(collection string, idKind reflect.Kind, data any) Record
- func ReadAll(_ context.Context, reader Reader, limit int) (records []Record, err error)
- func SelectAllRecords(reader Reader, limit int) (records []Record, err error)
- type RecordAfterLoadHook
- type RecordBeforeSaveHook
- type RecordData
- type RecordDataHook
- type RecordHook
- type SingleSource
- type Transaction
- type TransactionCoordinator
- type TransactionOption
- type TransactionOptions
- type Transform
- type TxIsolationLevel
- type Update
- type ValidatableRecord
- type WriteSession
Constants ¶
const ( SUM = "SUM" COUNT = "COUNT" MIN = "MIN" MAX = "MAX" AVERAGE = "AVG" )
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 ¶
var ErrDoesNotExist = errors.New("does not exist")
ErrDoesNotExist indicates a record does not exist
var ErrHookFailed = errors.New("failed in dalgo hook")
ErrHookFailed indicates that error occurred during hook execution
var ErrNoMoreRecords = errors.New("no more errors")
ErrNoMoreRecords indicates there is no more records
var ErrNotImplementedYet = errors.New("not implemented yet")
ErrNotImplementedYet - return this if db driver does not support requested operation yet.
var ErrNotSupported = errors.New("not supported")
ErrNotSupported - return this if db driver does not support requested operation. (for example no support for transactions)
var ( // ErrRecordNotFound is returned when a DB record is not found ErrRecordNotFound = errors.New("record not found") )
var NoError = errors.New("no error")
Functions ¶
func BeforeSave ¶ added in v0.2.9
func GetNonTransactionalContext ¶
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( c 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
IsGroupOperator says if an operator is a group operator
func IsNotFound ¶
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 ¶
NewErrNotFoundByKey creates an error that indicates that entity was not found by Value
func NewRollbackError ¶
NewRollbackError creates a rollback error
func RequiresEscaping ¶ added in v0.2.17
func SelectAllIDs ¶ added in v0.2.14
func SelectAllIDs[T comparable](reader Reader, limit int) (ids []T, err error)
SelectAllIDs is a helper method that for a given reader returns all IDs as a strongly typed slice.
func WithPrefix ¶
func WithPrefix(prefix string) func(options *randomStringOptions)
WithPrefix sets prefix for a random string
Types ¶
type Changes ¶
type Changes struct {
// contains filtered or unexported fields
}
Changes accumulates DB changes
func (*Changes) FlagAsChanged ¶
FlagAsChanged flags a record as changed
func (*Changes) HasChanges ¶
HasChanges returns true if there are changes
type ClientInfo ¶ added in v0.2.9
func NewClientInfo ¶ added in v0.2.9
func NewClientInfo(driver, version string) ClientInfo
type CollectionRef ¶
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())
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 Database ¶
type Database interface { ID() string Client() ClientInfo TransactionCoordinator ReadSession }
Database is an interface that defines a DB provider
type ErrDuplicateUser ¶
type ErrDuplicateUser struct { // TODO: Should it be moved out of this package to strongo/app/user? SearchCriteria string DuplicateUserIDs []int64 }
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 ¶
ErrNotFoundByKey indicates error was not found by Value
type Expression ¶ added in v0.2.6
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 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 ¶
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 Key ¶
Key represents a full path to a given record (no Parent in case of root recordset)
func NewIncompleteKey ¶ added in v0.2.6
func NewKeyWithFields ¶
NewKeyWithFields creates a new record child from a sequence of record's references
func NewKeyWithID ¶
func NewKeyWithID[T comparable](collection string, id T, options ...KeyOption) (key *Key)
NewKeyWithID creates a new key with an ID
func (*Key) Collection ¶
Collection returns reference to colection
func (*Key) CollectionPath ¶
CollectionPath return path to Parent
type KeyOption ¶
type KeyOption = func(*Key)
KeyOption defines contract for key option
func WithFields ¶
WithFields sets a list of field values as key ID
func WithIDGenerator ¶
func WithIDGenerator(g IDGenerator) KeyOption
WithIDGenerator sets ID generator for a random string (usually random)
func WithParent ¶
WithParent sets Parent
func WithRandomStringID ¶
WithRandomStringID sets ID generator to random string
func WithStringID ¶
WithStringID sets ID as a predefined string
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 ¶
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(c 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
}
RandomStringOptions defines settings for random string
type ReadSession ¶
type ReadSession interface { // Get gets a single record from database by key Get(ctx context.Context, record Record) error // GetMulti gets multiples records from database by keys GetMulti(ctx context.Context, records []Record) error 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) }
Reader reads records one by one
type ReaderProvider ¶ added in v0.2.14
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. SetError(err error) // 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 NewRecordWithData ¶
NewRecordWithData creates a new record with a data target struct
func NewRecordWithIncompleteKey ¶ added in v0.2.6
NewRecordWithIncompleteKey creates a new record with an incomplete key This is mostly intended for use in Select queries
func NewRecordWithoutKey ¶
NewRecordWithoutKey creates a new record without a key Obsolete, use NewRecordWithIncompleteKey instead
type RecordAfterLoadHook ¶ added in v0.2.7
type RecordBeforeSaveHook ¶ added in v0.2.7
type RecordData ¶ added in v0.2.7
type RecordData interface {
DTO() any
}
RecordData 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[T any](data T) RecordData
func MakeRecordDataWithCallbacks ¶ added in v0.2.7
func MakeRecordDataWithCallbacks[T any]( data T, beforeSave RecordDataHook, afterLoad RecordDataHook, ) RecordData
type RecordDataHook ¶ added in v0.2.9
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 ¶
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 IsTransform ¶
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 ValidatableRecord ¶ added in v0.2.9
type ValidatableRecord interface {
Validate() error
}
type WriteSession ¶
type WriteSession interface { // Insert inserts a single record in database Insert(c context.Context, record Record, opts ...InsertOption) error // Set sets a single record in database by key Set(ctx context.Context, record Record) error // SetMulti sets multiples records in database by keys SetMulti(ctx context.Context, records []Record) error // Update updates a single record in database by key Update(ctx context.Context, key *Key, updates []Update, preconditions ...Precondition) error // UpdateMulti updates multiples records in database by keys UpdateMulti(c context.Context, keys []*Key, updates []Update, preconditions ...Precondition) error // Delete deletes a single record from database by key Delete(ctx context.Context, key *Key) error // DeleteMulti deletes multiple records from database by keys DeleteMulti(ctx context.Context, keys []*Key) error }
WriteSession defines methods that can modify database
Source Files ¶
- batching.go
- changes.go
- client_info.go
- database.go
- errors.go
- hooks.go
- inserter.go
- key.go
- precondition.go
- q_collection_ref.go
- q_column.go
- q_conditions.go
- q_constant.go
- q_expression.go
- q_field.go
- q_field_ref.go
- q_functions.go
- q_group_condition.go
- q_id.go
- q_operator.go
- q_simple.go
- query.go
- query_executor.go
- query_select_funcs.go
- query_struct.go
- reader.go
- record.go
- record_data.go
- transaction.go
- transform.go
- unions.go
- update.go