Documentation ¶
Overview ¶
Package daos handles common PocketBase DB model manipulations.
Think of daos as DB repository and service layer in one.
Index ¶
- Constants
- type Dao
- func (dao *Dao) AdminQuery() *dbx.SelectQuery
- func (dao *Dao) Block(ctx context.Context) errordeprecated
- func (dao *Dao) CollectionQuery() *dbx.SelectQuery
- func (dao *Dao) ConcurrentDB() dbx.Builder
- func (dao *Dao) Continue()deprecated
- func (dao *Dao) DB() dbx.Builder
- func (dao *Dao) Delete(m models.Model) error
- func (dao *Dao) DeleteAdmin(admin *models.Admin) error
- func (dao *Dao) DeleteCollection(collection *models.Collection) error
- func (dao *Dao) DeleteExternalAuth(model *models.ExternalAuth) error
- func (dao *Dao) DeleteOldRequests(createdBefore time.Time) error
- func (dao *Dao) DeleteParam(param *models.Param) error
- func (dao *Dao) DeleteRecord(record *models.Record) error
- func (dao *Dao) DeleteTable(tableName string) error
- func (dao *Dao) ExpandRecord(record *models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error
- func (dao *Dao) ExpandRecords(records []*models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error
- func (dao *Dao) ExternalAuthQuery() *dbx.SelectQuery
- func (dao *Dao) FindAdminByEmail(email string) (*models.Admin, error)
- func (dao *Dao) FindAdminById(id string) (*models.Admin, error)
- func (dao *Dao) FindAdminByToken(token string, baseTokenKey string) (*models.Admin, error)
- func (dao *Dao) FindAllExternalAuthsByRecord(authRecord *models.Record) ([]*models.ExternalAuth, error)
- func (dao *Dao) FindAuthRecordByEmail(collectionNameOrId string, email string) (*models.Record, error)
- func (dao *Dao) FindAuthRecordByToken(token string, baseTokenKey string) (*models.Record, error)
- func (dao *Dao) FindAuthRecordByUsername(collectionNameOrId string, username string) (*models.Record, error)
- func (dao *Dao) FindById(m models.Model, id string) error
- func (dao *Dao) FindCollectionByNameOrId(nameOrId string) (*models.Collection, error)
- func (dao *Dao) FindCollectionReferences(collection *models.Collection, excludeIds ...string) (map[*models.Collection][]*schema.SchemaField, error)
- func (dao *Dao) FindCollectionsByType(collectionType string) ([]*models.Collection, error)
- func (dao *Dao) FindExternalAuthByProvider(provider, providerId string) (*models.ExternalAuth, error)
- func (dao *Dao) FindExternalAuthByRecordAndProvider(authRecord *models.Record, provider string) (*models.ExternalAuth, error)
- func (dao *Dao) FindFirstRecordByData(collectionNameOrId string, key string, value any) (*models.Record, error)
- func (dao *Dao) FindParamByKey(key string) (*models.Param, error)
- func (dao *Dao) FindRecordById(collectionNameOrId string, recordId string, ...) (*models.Record, error)
- func (dao *Dao) FindRecordsByExpr(collectionNameOrId string, exprs ...dbx.Expression) ([]*models.Record, error)
- func (dao *Dao) FindRecordsByIds(collectionNameOrId string, recordIds []string, ...) ([]*models.Record, error)
- func (dao *Dao) FindRequestById(id string) (*models.Request, error)
- func (dao *Dao) FindSettings(optEncryptionKey ...string) (*settings.Settings, error)
- func (dao *Dao) GetTableColumns(tableName string) ([]string, error)
- func (dao *Dao) HasTable(tableName string) bool
- func (dao *Dao) ImportCollections(importedCollections []*models.Collection, deleteMissing bool, ...) error
- func (dao *Dao) IsAdminEmailUnique(email string, excludeIds ...string) bool
- func (dao *Dao) IsCollectionNameUnique(name string, excludeIds ...string) bool
- func (dao *Dao) IsRecordValueUnique(collectionNameOrId string, key string, value any, excludeIds ...string) bool
- func (dao *Dao) ModelQuery(m models.Model) *dbx.SelectQuery
- func (dao *Dao) NonconcurrentDB() dbx.Builder
- func (dao *Dao) ParamQuery() *dbx.SelectQuery
- func (dao *Dao) RecordQuery(collection *models.Collection) *dbx.SelectQuery
- func (dao *Dao) RequestQuery() *dbx.SelectQuery
- func (dao *Dao) RequestsStats(expr dbx.Expression) ([]*RequestsStatsItem, error)
- func (dao *Dao) RunInTransaction(fn func(txDao *Dao) error) error
- func (dao *Dao) Save(m models.Model) error
- func (dao *Dao) SaveAdmin(admin *models.Admin) error
- func (dao *Dao) SaveCollection(collection *models.Collection) error
- func (dao *Dao) SaveExternalAuth(model *models.ExternalAuth) error
- func (dao *Dao) SaveParam(key string, value any, optEncryptionKey ...string) error
- func (dao *Dao) SaveRecord(record *models.Record) error
- func (dao *Dao) SaveRequest(request *models.Request) error
- func (dao *Dao) SaveSettings(newSettings *settings.Settings, optEncryptionKey ...string) error
- func (dao *Dao) SuggestUniqueAuthRecordUsername(collectionNameOrId string, baseUsername string, excludeIds ...string) string
- func (dao *Dao) SyncRecordTableSchema(newCollection *models.Collection, oldCollection *models.Collection) error
- func (dao *Dao) TotalAdmins() (int, error)
- func (dao *Dao) Vacuum() error
- type ExpandFetchFunc
- type RequestsStatsItem
Constants ¶
const DefaultMaxFailRetries = 5
const MaxExpandDepth = 6
MaxExpandDepth specifies the max allowed nested expand depth path.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dao ¶
type Dao struct { BeforeCreateFunc func(eventDao *Dao, m models.Model) error AfterCreateFunc func(eventDao *Dao, m models.Model) BeforeUpdateFunc func(eventDao *Dao, m models.Model) error AfterUpdateFunc func(eventDao *Dao, m models.Model) BeforeDeleteFunc func(eventDao *Dao, m models.Model) error AfterDeleteFunc func(eventDao *Dao, m models.Model) // contains filtered or unexported fields }
Dao handles various db operations. Think of Dao as a repository and service layer in one.
func New ¶
New creates a new Dao instance with the provided db builder (for both async and sync db operations).
func NewMultiDB ¶ added in v0.10.0
New creates a new Dao instance with the provided dedicated async and sync db builders.
func (*Dao) AdminQuery ¶
func (dao *Dao) AdminQuery() *dbx.SelectQuery
AdminQuery returns a new Admin select query.
func (*Dao) Block
deprecated
added in
v0.9.1
Deprecated: Will be removed in the next releases. Use [Dao.NonconcurrentDB()] instead.
Block acquires a lock and blocks all other go routines that uses the Dao instance until dao.Continue() is called, effectively making the concurrent requests to perform synchronous db operations.
This method should be used only as a last resort and as a workaround for the SQLITE_BUSY error when mixing read&write in a transaction.
Example:
func someLongRunningTransaction() error { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := app.Dao().Block(ctx); err != nil { return err } defer app.Dao().Continue() return app.Dao().RunInTransaction(func (txDao *daos.Dao) error { // some long running read&write transaction... }) }
func (*Dao) CollectionQuery ¶
func (dao *Dao) CollectionQuery() *dbx.SelectQuery
CollectionQuery returns a new Collection select query.
func (*Dao) ConcurrentDB ¶ added in v0.10.0
ConcurrentDB returns the dao concurrent (aka. multiple open connections) db builder (*dbx.DB or *dbx.TX).
In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance.
func (*Dao) DB ¶
DB returns the default dao db builder (*dbx.DB or *dbx.TX).
Currently the default db builder is dao.concurrentDB but that may change in the future.
func (*Dao) DeleteAdmin ¶
DeleteAdmin deletes the provided Admin model.
Returns an error if there is only 1 admin.
func (*Dao) DeleteCollection ¶
func (dao *Dao) DeleteCollection(collection *models.Collection) error
DeleteCollection deletes the provided Collection model. This method automatically deletes the related collection records table.
NB! The collection cannot be deleted, if: - is system collection (aka. collection.System is true) - is referenced as part of a relation field in another collection
func (*Dao) DeleteExternalAuth ¶ added in v0.6.0
func (dao *Dao) DeleteExternalAuth(model *models.ExternalAuth) error
DeleteExternalAuth deletes the provided ExternalAuth model.
func (*Dao) DeleteOldRequests ¶
DeleteOldRequests delete all requests that are created before createdBefore.
func (*Dao) DeleteParam ¶
DeleteParam deletes the provided Param model.
func (*Dao) DeleteRecord ¶
DeleteRecord deletes the provided Record model.
This method will also cascade the delete operation to all linked relational records (delete or unset, depending on the rel settings).
The delete operation may fail if the record is part of a required reference in another record (aka. cannot be deleted or unset).
func (*Dao) DeleteTable ¶
DeleteTable drops the specified table.
func (*Dao) ExpandRecord ¶
func (dao *Dao) ExpandRecord(record *models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error
ExpandRecord expands the relations of a single Record model.
Returns a map with the failed expand parameters and their errors.
func (*Dao) ExpandRecords ¶
func (dao *Dao) ExpandRecords(records []*models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error
ExpandRecords expands the relations of the provided Record models list.
Returns a map with the failed expand parameters and their errors.
func (*Dao) ExternalAuthQuery ¶ added in v0.6.0
func (dao *Dao) ExternalAuthQuery() *dbx.SelectQuery
ExternalAuthQuery returns a new ExternalAuth select query.
func (*Dao) FindAdminByEmail ¶
FindAdminByEmail finds the admin with the provided email address.
func (*Dao) FindAdminById ¶
FindAdminById finds the admin with the provided id.
func (*Dao) FindAdminByToken ¶
FindAdminByToken finds the admin associated with the provided JWT token.
Returns an error if the JWT token is invalid or expired.
func (*Dao) FindAllExternalAuthsByRecord ¶ added in v0.8.0
func (dao *Dao) FindAllExternalAuthsByRecord(authRecord *models.Record) ([]*models.ExternalAuth, error)
/ FindAllExternalAuthsByRecord returns all ExternalAuth models / linked to the provided auth record.
func (*Dao) FindAuthRecordByEmail ¶ added in v0.8.0
func (dao *Dao) FindAuthRecordByEmail(collectionNameOrId string, email string) (*models.Record, error)
FindAuthRecordByEmail finds the auth record associated with the provided email.
Returns an error if it is not an auth collection or the record is not found.
func (*Dao) FindAuthRecordByToken ¶ added in v0.8.0
FindAuthRecordByToken finds the auth record associated with the provided JWT token.
Returns an error if the JWT token is invalid, expired or not associated to an auth collection record.
func (*Dao) FindAuthRecordByUsername ¶ added in v0.8.0
func (dao *Dao) FindAuthRecordByUsername(collectionNameOrId string, username string) (*models.Record, error)
FindAuthRecordByUsername finds the auth record associated with the provided username (case insensitive).
Returns an error if it is not an auth collection or the record is not found.
func (*Dao) FindById ¶
FindById finds a single db record with the specified id and scans the result into m.
func (*Dao) FindCollectionByNameOrId ¶
func (dao *Dao) FindCollectionByNameOrId(nameOrId string) (*models.Collection, error)
FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.
func (*Dao) FindCollectionReferences ¶
func (dao *Dao) FindCollectionReferences(collection *models.Collection, excludeIds ...string) (map[*models.Collection][]*schema.SchemaField, error)
FindCollectionReferences returns information for all relation schema fields referencing the provided collection.
If the provided collection has reference to itself then it will be also included in the result. To exclude it, pass the collection id as the excludeId argument.
func (*Dao) FindCollectionsByType ¶ added in v0.8.0
func (dao *Dao) FindCollectionsByType(collectionType string) ([]*models.Collection, error)
FindCollectionsByType finds all collections by the given type.
func (*Dao) FindExternalAuthByProvider ¶ added in v0.6.0
func (dao *Dao) FindExternalAuthByProvider(provider, providerId string) (*models.ExternalAuth, error)
FindExternalAuthByProvider returns the first available ExternalAuth model for the specified provider and providerId.
func (*Dao) FindExternalAuthByRecordAndProvider ¶ added in v0.8.0
func (dao *Dao) FindExternalAuthByRecordAndProvider(authRecord *models.Record, provider string) (*models.ExternalAuth, error)
FindExternalAuthByRecordAndProvider returns the first available ExternalAuth model for the specified record data and provider.
func (*Dao) FindFirstRecordByData ¶
func (dao *Dao) FindFirstRecordByData(collectionNameOrId string, key string, value any) (*models.Record, error)
FindFirstRecordByData returns the first found record matching the provided key-value pair.
func (*Dao) FindParamByKey ¶
FindParamByKey finds the first Param model with the provided key.
func (*Dao) FindRecordById ¶
func (dao *Dao) FindRecordById( collectionNameOrId string, recordId string, optFilters ...func(q *dbx.SelectQuery) error, ) (*models.Record, error)
FindRecordById finds the Record model by its id.
func (*Dao) FindRecordsByExpr ¶
func (dao *Dao) FindRecordsByExpr(collectionNameOrId string, exprs ...dbx.Expression) ([]*models.Record, error)
FindRecordsByExpr finds all records by the specified db expression.
Returns all collection records if no expressions are provided.
Returns an empty slice if no records are found.
Example:
expr1 := dbx.HashExp{"email": "test@example.com"} expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"}) dao.FindRecordsByExpr("example", expr1, expr2)
func (*Dao) FindRecordsByIds ¶
func (dao *Dao) FindRecordsByIds( collectionNameOrId string, recordIds []string, optFilters ...func(q *dbx.SelectQuery) error, ) ([]*models.Record, error)
FindRecordsByIds finds all Record models by the provided ids. If no records are found, returns an empty slice.
func (*Dao) FindRequestById ¶
FindRequestById finds a single Request log by its id.
func (*Dao) FindSettings ¶ added in v0.9.0
FindSettings returns and decode the serialized app settings param value.
The method will first try to decode the param value without decryption. If it fails and optEncryptionKey is set, it will try again by first decrypting the value and then decode it again.
Returns an error if it fails to decode the stored serialized param value.
func (*Dao) GetTableColumns ¶
GetTableColumns returns all column names of a single table by its name.
func (*Dao) ImportCollections ¶ added in v0.4.0
func (dao *Dao) ImportCollections( importedCollections []*models.Collection, deleteMissing bool, beforeRecordsSync func(txDao *Dao, mappedImported, mappedExisting map[string]*models.Collection) error, ) error
ImportCollections imports the provided collections list within a single transaction.
NB1! If deleteMissing is set, all local collections and schema fields, that are not present in the imported configuration, WILL BE DELETED (including their related records data).
NB2! This method doesn't perform validations on the imported collections data! If you need validations, use [forms.CollectionsImport].
func (*Dao) IsAdminEmailUnique ¶
IsAdminEmailUnique checks if the provided email address is not already in use by other admins.
func (*Dao) IsCollectionNameUnique ¶
IsCollectionNameUnique checks that there is no existing collection with the provided name (case insensitive!).
Note: case insensitive check because the name is used also as a table name for the records.
func (*Dao) IsRecordValueUnique ¶
func (dao *Dao) IsRecordValueUnique( collectionNameOrId string, key string, value any, excludeIds ...string, ) bool
IsRecordValueUnique checks if the provided key-value pair is a unique Record value.
For correctness, if the collection is "auth" and the key is "username", the unique check will be case insensitive.
NB! Array values (eg. from multiple select fields) are matched as a serialized json strings (eg. `["a","b"]`), so the value uniqueness depends on the elements order. Or in other words the following values are considered different: `[]string{"a","b"}` and `[]string{"b","a"}`
func (*Dao) ModelQuery ¶
func (dao *Dao) ModelQuery(m models.Model) *dbx.SelectQuery
ModelQuery creates a new query with preset Select and From fields based on the provided model argument.
func (*Dao) NonconcurrentDB ¶ added in v0.10.0
NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) db builder (*dbx.DB or *dbx.TX).
In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance.
func (*Dao) ParamQuery ¶
func (dao *Dao) ParamQuery() *dbx.SelectQuery
ParamQuery returns a new Param select query.
func (*Dao) RecordQuery ¶
func (dao *Dao) RecordQuery(collection *models.Collection) *dbx.SelectQuery
RecordQuery returns a new Record select query.
func (*Dao) RequestQuery ¶
func (dao *Dao) RequestQuery() *dbx.SelectQuery
RequestQuery returns a new Request logs select query.
func (*Dao) RequestsStats ¶
func (dao *Dao) RequestsStats(expr dbx.Expression) ([]*RequestsStatsItem, error)
RequestsStats returns hourly grouped requests logs statistics.
func (*Dao) RunInTransaction ¶
RunInTransaction wraps fn into a transaction.
It is safe to nest RunInTransaction calls as long as you use the txDao.
func (*Dao) SaveCollection ¶
func (dao *Dao) SaveCollection(collection *models.Collection) error
SaveCollection upserts the provided Collection model and updates its related records table schema.
func (*Dao) SaveExternalAuth ¶ added in v0.6.0
func (dao *Dao) SaveExternalAuth(model *models.ExternalAuth) error
SaveExternalAuth upserts the provided ExternalAuth model.
func (*Dao) SaveParam ¶
SaveParam creates or updates a Param model by the provided key-value pair. The value argument will be encoded as json string.
If `optEncryptionKey` is provided it will encrypt the value before storing it.
func (*Dao) SaveRecord ¶
SaveRecord upserts the provided Record model.
func (*Dao) SaveRequest ¶
SaveRequest upserts the provided Request model.
func (*Dao) SaveSettings ¶ added in v0.9.0
SaveSettings persists the specified settings configuration.
If optEncryptionKey is set, then the stored serialized value will be encrypted with it.
func (*Dao) SuggestUniqueAuthRecordUsername ¶ added in v0.8.0
func (dao *Dao) SuggestUniqueAuthRecordUsername( collectionNameOrId string, baseUsername string, excludeIds ...string, ) string
SuggestUniqueAuthRecordUsername checks if the provided username is unique and return a new "unique" username with appended random numeric part (eg. "existingName" -> "existingName583").
The same username will be returned if the provided string is already unique.
func (*Dao) SyncRecordTableSchema ¶
func (dao *Dao) SyncRecordTableSchema(newCollection *models.Collection, oldCollection *models.Collection) error
SyncRecordTableSchema compares the two provided collections and applies the necessary related record table changes.
If `oldCollection` is null, then only `newCollection` is used to create the record table.
func (*Dao) TotalAdmins ¶
TotalAdmins returns the number of existing admin records.
type ExpandFetchFunc ¶
type ExpandFetchFunc func(relCollection *models.Collection, relIds []string) ([]*models.Record, error)
ExpandFetchFunc defines the function that is used to fetch the expanded relation records.