Documentation
¶
Index ¶
- Constants
- Variables
- func AnyRecordWithError(records ...Record) error
- func BeforeSave(ctx context.Context, db DB, record Record) error
- func EqualKeys(k1 *Key, k2 *Key) bool
- func EscapeID(id string) string
- func ExecuteQueryAndReadAllToRecordset(ctx context.Context, query Query, qe QueryExecutor, options ...ReaderOption) (rs recordset.Recordset, err error)
- func GetNonTransactionalContext(ctx context.Context) context.Context
- func InsertWithIdGenerator(ctx context.Context, r Record, generateID IDGenerator, maxAttempts 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 Prefix(prefix string) func(options *randomStringOptions)
- func RandomLength(length int) func(options *randomStringOptions)
- func RequiresEscaping(s string) bool
- func SelectAll(ctx context.Context, reader RecordsReader, addItem func(r Record), ...) (err error)
- func SelectAllIDs[T comparable](ctx context.Context, reader RecordsReader, options ...ReaderOption) (ids []T, err error)
- func WithAfterLoad(hook RecordDataHook) func(rd *recordData)
- func WithBeforeSave(hook RecordDataHook) func(rd *recordData)
- type Adapter
- type Array
- type Changes
- type CollectionGroupRef
- type CollectionRef
- type Column
- type Comparison
- type ConcurrencyAvailable
- type ConcurrencyAware
- type Condition
- type Constant
- type Cursor
- type DB
- type DataToKeyFunc
- type DataWrapper
- type Deleter
- type EmptyReader
- type ErrDuplicateUser
- type ErrNotFoundByKey
- type Expression
- type ExtraField
- type FieldName
- type FieldRef
- type FieldVal
- type FromSource
- type Getter
- type GroupCondition
- type IDGenerator
- type IQueryBuilder
- type InsertOption
- type InsertOptions
- type Inserter
- type JoinedSource
- type Key
- func NewIncompleteKey(collection string, idKind reflect.Kind, parent *Key) *Key
- func NewKeyWithFields(collection string, fields ...FieldVal) *Key
- func NewKeyWithID[T comparable](collection string, id T) (key *Key)
- func NewKeyWithOptions(collection string, options ...KeyOption) (key *Key, err error)
- func NewKeyWithParentAndID[T comparable](parent *Key, collection string, id T) (key *Key)
- type KeyOption
- func WithFields(fields []FieldVal) KeyOption
- func WithID[T comparable](id T) KeyOption
- func WithIDGenerator(ctx context.Context, g IDGenerator) KeyOption
- func WithIntID(id int) KeyOption
- func WithKeyID[T comparable](id T) KeyOption
- func WithParentKey(parent *Key) KeyOption
- func WithRandomStringID(options ...randomStringOption) KeyOption
- func WithStringID(id string) KeyOption
- type KeyToFieldsFunc
- type MultiDeleter
- type MultiGetter
- type MultiInserter
- type MultiSetter
- type MultiUpdater
- type NoConcurrency
- type Operator
- type OrderExpression
- type Precondition
- type Preconditions
- type Query
- type QueryArg
- type QueryBuilder
- func (s *QueryBuilder) Clone() IQueryBuilder
- func (s *QueryBuilder) Limit(i int) IQueryBuilder
- func (s *QueryBuilder) Offset(i int) IQueryBuilder
- func (s *QueryBuilder) OrderBy(expressions ...OrderExpression) IQueryBuilder
- func (s *QueryBuilder) SelectIntoRecord(into func() Record) StructuredQuery
- func (s *QueryBuilder) SelectIntoRecordset(options ...recordset.Option) StructuredQuery
- func (s *QueryBuilder) SelectKeysOnly(idKind reflect.Kind) StructuredQuery
- func (s *QueryBuilder) StartFrom(cursor Cursor) IQueryBuilder
- func (s *QueryBuilder) Where(conditions ...Condition) IQueryBuilder
- func (s *QueryBuilder) WhereField(name string, operator Operator, v any) IQueryBuilder
- func (s *QueryBuilder) WhereInArrayField(name string, v any) IQueryBuilder
- type QueryExecutor
- type ROTxWorker
- type RWTxWorker
- type RandomStringOptions
- type ReadSession
- type ReadTransaction
- type ReadTransactionCoordinator
- type Reader
- type ReaderOption
- type ReaderOptions
- type ReadwriteSession
- type ReadwriteTransaction
- type ReadwriteTransactionCoordinator
- type Record
- func ExecuteQueryAndReadAllToRecords(ctx context.Context, query Query, qe QueryExecutor, options ...ReaderOption) (records []Record, err error)
- func NewRecord(key *Key) Record
- func NewRecordWithData(key *Key, data any) Record
- func NewRecordWithIncompleteKey(collection string, idKind reflect.Kind, data any) Record
- func NewRecordWithoutKey(data any) Record
- func ReadAllToRecords(ctx context.Context, reader RecordsReader, options ...ReaderOption) (records []Record, err error)
- type RecordAfterLoadHook
- type RecordBeforeSaveHook
- type RecordDataHook
- type RecordDataOption
- type RecordHook
- type RecordsReader
- type RecordsetReader
- type RecordsetSource
- type Schema
- type SchemaBase
- type Setter
- type SingleSource
- type StructuredQuery
- type TextQuery
- type TimeStampAccuracy
- type Transaction
- type TransactionCoordinator
- type TransactionOption
- type TransactionOptions
- type Transform
- type TxIsolationLevel
- type Updater
- type ValidatableRecord
- type WriteSession
Constants ¶
const ( SUM = "SUM" COUNT = "COUNT" MIN = "MIN" MAX = "MAX" AVERAGE = "AVG" )
Variables ¶
var DefaultRandomStringIDLength = 16
var ErrExceedsMaxNumberOfAttempts = fmt.Errorf("exceeds maximum number of attempts")
var ErrHookFailed = errors.New("failed in dalgo hook")
ErrHookFailed indicates that error occurred during hook execution
var ErrLimitReached = fmt.Errorf("%w: limit reached", ErrNoMoreRecords)
var ErrNoError = errors.New("no error")
var ErrNoMoreRecords = fmt.Errorf("%w: no more errors", io.EOF)
ErrNoMoreRecords indicates there is no more records
var ErrNotImplementedYet = errors.New("not implemented yet")
ErrNotImplementedYet - return this if db name does not support requested operation yet.
var ErrNotSupported = errors.New("not supported")
ErrNotSupported - return this if db name does not support requested operation. (for example no support for transactions)
var ErrReaderClosed = errors.New("reader closed")
var ErrReaderNotStarted = errors.New("reader not started")
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 ExecuteQueryAndReadAllToRecordset ¶ added in v0.38.0
func ExecuteQueryAndReadAllToRecordset(ctx context.Context, query Query, qe QueryExecutor, options ...ReaderOption) (rs recordset.Recordset, err error)
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 InsertWithIdGenerator ¶ added in v0.20.0
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 intoRecord 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 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 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
NewAdapter creates new client info. Former ClientInfo.
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 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())
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 ConcurrencyAvailable ¶ added in v0.42.0
type ConcurrencyAvailable struct{}
ConcurrencyAvailable is a zero-value embeddable struct that satisfies ConcurrencyAware by reporting that concurrent connections ARE supported. Drivers whose backend tolerates multiple concurrent connections (such as a server-side RDBMS like PostgreSQL) should embed ConcurrencyAvailable to inherit the permissive answer with no method body of their own:
type PostgresDB struct {
dal.ConcurrencyAvailable
// ...
}
See ConcurrencyAware for the full contract.
func (ConcurrencyAvailable) SupportsConcurrentConnections ¶ added in v0.42.0
func (ConcurrencyAvailable) SupportsConcurrentConnections() bool
SupportsConcurrentConnections always returns true.
type ConcurrencyAware ¶ added in v0.42.0
type ConcurrencyAware interface {
// SupportsConcurrentConnections reports whether the underlying
// backend tolerates more than one open connection from a single
// client process at the same time. See [ConcurrencyAware] for the
// stability and asymmetry contract.
SupportsConcurrentConnections() bool
}
ConcurrencyAware is implemented by DB values that can report whether the underlying backend supports multiple concurrent open connections from a single client process.
The returned value is constant from the moment a DB value is returned by its constructor until it is discarded. Drivers MUST NOT change the answer in response to reconnects, failovers, transient errors, or runtime configuration reloads against the same DB handle. Callers are entitled to memoize the value once per DB value.
The boolean intentionally does not distinguish read-vs-write concurrency. A driver like SQLite that supports concurrent readers but serializes writers collapses to false. Refining this surface (or adding a sibling) is a future change if a real consumer needs the distinction.
ConcurrencyAware is embedded into DB; every DB implementation therefore answers the question. Drivers SHOULD embed one of the reusable structs NoConcurrency or ConcurrencyAvailable rather than hand-writing the method.
type Constant ¶ added in v0.2.15
type Constant struct {
Value any `json:"value"`
}
func NewConstant ¶ added in v0.23.0
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
// ConcurrencyAware reports whether this backend supports concurrent
// open connections. Drivers should embed NoConcurrency or
// ConcurrencyAvailable in their concrete type to satisfy this.
ConcurrencyAware
}
DB is an interface that defines a database provider
type DataToKeyFunc ¶ added in v0.25.0
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 ¶
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 ExtraField ¶ added in v0.25.0
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)
type FieldRef ¶ added in v0.2.6
type FieldRef struct {
// contains filtered or unexported fields
}
func NewFieldRef ¶ added in v0.25.0
NewFieldRef creates an expression that represents a FieldRef 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 ¶
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 ¶
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 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
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 ¶
Collection returns reference to colection
func (*Key) CollectionPath ¶
CollectionPath return path to Parent
type KeyOption ¶
KeyOption defines contract for key option
func WithFields ¶
WithFields sets a list of field values as key ID
func WithIDGenerator ¶
func WithIDGenerator(ctx context.Context, g IDGenerator) KeyOption
WithIDGenerator sets ID generator for a random string (usually random)
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 WithRandomStringID ¶
func WithRandomStringID(options ...randomStringOption) KeyOption
WithRandomStringID sets ID generator to random string
func WithStringID ¶
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 NoConcurrency ¶ added in v0.42.0
type NoConcurrency struct{}
NoConcurrency is a zero-value embeddable struct that satisfies ConcurrencyAware by reporting that concurrent connections are NOT supported. Drivers whose backend serializes connections (such as a single-writer SQLite, an unproven file-backed store, or a test stub) should embed NoConcurrency to inherit the conservative answer with no method body of their own:
type SQLiteDB struct {
dal.NoConcurrency
// ...
}
See ConcurrencyAware for the full contract.
func (NoConcurrency) SupportsConcurrentConnections ¶ added in v0.42.0
func (NoConcurrency) SupportsConcurrentConnections() bool
SupportsConcurrentConnections always returns false.
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 {
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 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 ¶
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 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 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 ¶
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 RecordBeforeSaveHook ¶ added in v0.2.7
type RecordDataHook ¶ added in v0.2.9
type RecordDataOption ¶ added in v0.4.0
type RecordDataOption = func(rd *recordData)
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 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
TextQuery defines an interface to represent a query with text and associated arguments.
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.
// The message field is mutable during execution via TransactionOptions.SetMessage();
// implementations should return options by shared reference so the update is observed.
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 TxWithMessage ¶ added in v0.45.0
func TxWithMessage(message string) TransactionOption
TxWithMessage sets a human-readable message on the transaction. The message can be read back via TransactionOptions.Message() and replaced during transaction execution via TransactionOptions.SetMessage().
func TxWithReadonly ¶
func TxWithReadonly() TransactionOption
TxWithReadonly requests a readonly transaction
type TransactionOptions ¶
type TransactionOptions interface {
// Message returns an optional human-readable message describing the transaction.
// Backends may surface it (e.g. dalgo2ingitdb uses it as a git commit message)
// or include it in logs. It returns an empty string when no message was set.
Message() string
// SetMessage sets (replaces) the transaction message. It can be used at
// transaction start via TxWithMessage, or during transaction execution.
// It is available on both readonly and read-write transactions.
SetMessage(message 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 ¶
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 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 ¶
type WriteSession interface {
Setter
MultiSetter
Deleter
MultiDeleter
Updater
MultiUpdater
Inserter
MultiInserter
}
WriteSession defines methods that can modify database
Source Files
¶
- adapter.go
- batching.go
- changes.go
- concurrency.go
- connection.go
- data_wrapper.go
- db_database.go
- errors.go
- field.go
- field_val.go
- hooks.go
- id_generator.go
- key.go
- key_options.go
- precondition.go
- q_array.go
- q_builder.go
- q_collection_group_ref.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_recordset_source.go
- q_text.go
- query.go
- query_executor.go
- query_select_funcs.go
- query_struct.go
- reader.go
- reader_empty.go
- reader_read_all.go
- reader_slice_records.go
- record.go
- record_interface.go
- schema.go
- schema_extra_field.go
- session.go
- transaction.go
- transform.go
- tx_deleter.go
- tx_getter.go
- tx_inserter.go
- tx_setter.go
- tx_updater.go
- unions.go
- with_hooks.go
- with_hooks_error.go