core
import core "ganigeorgiev.com/pocketbase/pocketbase/core"
Package core is the backbone of PocketBase.
It defines the main PocketBase App interface and its base implementation.
Source: core.
Its types are on five pages: this one (the app, App and BaseApp, and what doesn't fit elsewhere), Records and collections, Fields, Events, Settings.
Constants
const (
DefaultDataMaxOpenConns int = 120
DefaultDataMaxIdleConns int = 15
DefaultAuxMaxOpenConns int = 20
DefaultAuxMaxIdleConns int = 3
DefaultQueryTimeout time.Duration = 30 * time.Second
LocalStorageDirName string = "storage"
LocalBackupsDirName string = "backups"
LocalAutocertCacheDirName string = ".autocert_cache"
LocalNotifyDirName string = ".notify" // optional watched directory that is used as a cross-platform workaround for synchronizing various runtime states between multiple PocketBase instances pointing to the same pb_data
LocalTempDirName string = ".pb_temp_to_delete" // temp pb_data sub directory that will be deleted on each app.Bootstrap()
)
const (
CollectionTypeBase = "base"
CollectionTypeAuth = "auth"
CollectionTypeView = "view"
)
const (
EmailPlaceholderAppName string = "{APP_NAME}"
EmailPlaceholderAppURL string = "{APP_URL}"
EmailPlaceholderToken string = "{TOKEN}"
EmailPlaceholderOTP string = "{OTP}"
EmailPlaceholderOTPId string = "{OTP_ID}"
EmailPlaceholderAlertInfo string = "{ALERT_INFO}"
)
Common settings placeholder tokens
const (
// DefaultIdLength is the default length of the generated model id.
DefaultIdLength int = 15
// DefaultIdAlphabet is the default characters set used for generating the model id.
DefaultIdAlphabet string = "abcdefghijklmnopqrstuvwxyz0123456789"
)
const (
RequestInfoContextDefault = "default"
RequestInfoContextExpand = "expand"
RequestInfoContextRealtime = "realtime"
RequestInfoContextProtectedFile = "protectedFile"
RequestInfoContextBatch = "batch"
RequestInfoContextOAuth2 = "oauth2"
RequestInfoContextOTP = "otp"
RequestInfoContextPasswordAuth = "password"
)
const (
FilesystemKindStorage = "storage" // app.NewFilesystem(): record uploads
FilesystemKindBackups = "backups" // app.NewBackupsFilesystem(): backup zips
)
Filesystem kinds, see FilesystemCreateEvent.
const (
ModelEventTypeCreate = "create"
ModelEventTypeUpdate = "update"
ModelEventTypeDelete = "delete"
ModelEventTypeValidate = "validate"
)
const (
FieldNameId = "id"
FieldNameCollectionId = "collectionId"
FieldNameCollectionName = "collectionName"
FieldNameExpand = "expand"
FieldNameEmail = "email"
FieldNameEmailVisibility = "emailVisibility"
FieldNameVerified = "verified"
FieldNameTokenKey = "tokenKey"
FieldNamePassword = "password"
)
Commonly used field names.
const (
InterceptorActionValidate = "validate"
InterceptorActionDelete = "delete"
InterceptorActionDeleteExecute = "deleteExecute"
InterceptorActionAfterDelete = "afterDelete"
InterceptorActionAfterDeleteError = "afterDeleteError"
InterceptorActionCreate = "create"
InterceptorActionCreateExecute = "createExecute"
InterceptorActionAfterCreate = "afterCreate"
InterceptorActionAfterCreateError = "afterCreateFailure"
InterceptorActionUpdate = "update"
InterceptorActionUpdateExecute = "updateExecute"
InterceptorActionAfterUpdate = "afterUpdate"
InterceptorActionAfterUpdateError = "afterUpdateError"
)
Common RecordInterceptor action names.
const (
MFAMethodPassword = "password"
MFAMethodOAuth2 = "oauth2"
MFAMethodOTP = "otp"
)
const (
TokenTypeAuth = "auth"
TokenTypeFile = "file"
TokenTypeVerification = "verification"
TokenTypePasswordReset = "passwordReset"
TokenTypeEmailChange = "emailChange"
)
Supported record token types
const (
TokenClaimId = "id"
TokenClaimType = "type"
TokenClaimCollectionId = "collectionId"
TokenClaimEmail = "email"
TokenClaimNewEmail = "newEmail"
TokenClaimRefreshable = "refreshable"
)
List with commonly used record token claims
const (
RateLimitRuleAudienceAll = ""
RateLimitRuleAudienceGuest = "@guest"
RateLimitRuleAudienceAuth = "@auth"
)
The allowed RateLimitRule.Audience values
const CollectionNameAuthOrigins = "_authOrigins"
const CollectionNameExternalAuths = "_externalAuths"
const CollectionNameMFAs = "_mfas"
const CollectionNameOTPs = "_otps"
const CollectionNameSuperusers = "_superusers"
const DefaultEditorFieldMaxSize int64 = 5 << 20
const DefaultFileFieldMaxSize int64 = 5 << 20
const DefaultInstallerEmail = "[email protected]"
DefaultInstallerEmail is the default superuser email address for the initial autogenerated superuser account.
const DefaultJSONFieldMaxSize int64 = 1 << 20
const DefaultMigrationsTable = "_migrations"
const FieldTypeAutodate = "autodate"
const FieldTypeBool = "bool"
const FieldTypeDate = "date"
const FieldTypeEditor = "editor"
const FieldTypeEmail = "email"
const FieldTypeFile = "file"
const FieldTypeGeoPoint = "geoPoint"
const FieldTypeJSON = "json"
const FieldTypeNumber = "number"
const FieldTypePassword = "password"
const FieldTypeRelation = "relation"
const FieldTypeSelect = "select"
const FieldTypeText = "text"
const FieldTypeURL = "url"
const LogsTableName = "_logs"
const (
RequestEventKeyInfoContext = "infoContext"
)
Common request store keys used by the middlewares and api handlers.
const (
StoreKeyActiveBackup = "@activeBackup"
)
const StoreKeyCachedCollections = "pbAppCachedCollections"
Variables
var (
ErrUnknownField = validation.NewError("validation_unknown_field", "Unknown or invalid field.")
ErrInvalidFieldValue = validation.NewError("validation_invalid_field_value", "Invalid field value.")
ErrMustBeSystemAndHidden = validation.NewError("validation_must_be_system_and_hidden", `The field must be marked as "System" and "Hidden".`)
ErrMustBeSystem = validation.NewError("validation_must_be_system", `The field must be marked as "System".`)
)
Common field errors.
var (
ErrNotAuthRecord = errors.New("not an auth collection record")
ErrMissingSigningKey = errors.New("missing or invalid signing key")
)
Common token related errors
var DefaultIdRegex = regexp.MustCompile(`^\w+$`)
DefaultIdRegex specifies the default regex pattern for an id value.
var Fields = map[string]FieldFactoryFunc{}
Fields holds all available collection fields.
var SystemDynamicFieldNames = []string{
FieldNameCollectionId,
FieldNameCollectionName,
FieldNameExpand,
}
SystemFields returns special internal field names that are usually readonly.
Functions
DefaultDBConnect
func DefaultDBConnect(dbPath string) (*dbx.DB, error)
DefaultFieldHelpValidationRule
func DefaultFieldHelpValidationRule(value any) error
DefaultFieldHelpValidationRule performs base validation on a field's "help" value.
DefaultFieldIdValidationRule
func DefaultFieldIdValidationRule(value any) error
DefaultFieldIdValidationRule performs base validation on a field id value.
DefaultFieldNameValidationRule
func DefaultFieldNameValidationRule(value any) error
DefaultFieldIdValidationRule performs base validation on a field name value.
GenerateDefaultRandomId
func GenerateDefaultRandomId() string
GenerateDefaultRandomId generates a default random id string (note: the generated random string is not intended for security purposes).
Types
App
type App interface {
// UnsafeWithoutHooks returns a shallow copy of the current app WITHOUT any registered hooks.
//
// NB! Note that using the returned app instance may cause data integrity errors
// since the Record validations and data normalization (including files uploads)
// rely on the app hooks to work.
UnsafeWithoutHooks() App
// WithContext creates a new shallow copy of the current app with its context set to the given one.
//
// WithContext is often used to customize the default timeouts and/or group the
// execution duration of DB queries, transactions and any other app related operation.
//
// Keep in mind that this context will be used by all queries executed by the new app
// instance meaning that technically you can provide a context.Background() for no limits.
// Be careful with that!
//
// For example:
//
// ctx, cancel := context.WithTimeout(app.Context(), 5*time.Second)
// defer cancel()
//
// ctxApp := app.WithContext(ctx)
//
// // run your queries using the newly created ctxApp
// // (in the below example both the Find and Save operations share the same context)
// record, err := ctxApp.FindRecordById("example", "123")
// record.Set("name", "abc")
// err = ctxApp.Save(record)
WithContext(ctx context.Context) App
// Context returns the context associated with the current app instance.
Context() context.Context
// Logger returns the default app logger.
//
// If the application is not bootstrapped yet, fallbacks to slog.Default().
Logger() *slog.Logger
// IsBootstrapped checks if the application was initialized
// (aka. whether Bootstrap() was called).
IsBootstrapped() bool
// IsTransactional checks if the current app instance is part of a transaction.
IsTransactional() bool
// TxInfo returns the transaction associated with the current app instance (if any).
//
// Could be used if you want to execute indirectly a function after
// the related app transaction completes using `app.TxInfo().OnAfterFunc(callback)`.
TxInfo() *TxAppInfo
// Bootstrap initializes the application
// (aka. create data dir, open db connections, load settings, etc.).
//
// It calls ClearBootstrap() if the application was already bootstrapped.
Bootstrap() error
// ClearBootstrap releases the initialized core app resources
// (closing db connections, stopping cron ticker, etc.).
//
// This method is no-op if the application is not bootstrapped yet.
ClearBootstrap() error
// Deprecated: use ClearBootstrap().
ResetBootstrapState() error
// DataDir returns the app data directory path.
DataDir() string
// EncryptionEnv returns the name of the app secret env key
// (currently used primarily for optional settings encryption but this may change in the future).
EncryptionEnv() string
// IsDev returns whether the app is in dev mode.
//
// When enabled logs, executed sql statements, etc. are printed to the stderr.
IsDev() bool
// Settings returns the loaded app settings.
Settings() *Settings
// Store returns the app runtime store.
Store() *store.Store[string, any]
// Cron returns the app cron instance.
Cron() *cron.Cron
// SubscriptionsBroker returns the app realtime subscriptions broker instance.
SubscriptionsBroker() *subscriptions.Broker
// NewMailClient creates and returns a new SMTP or Sendmail client
// based on the current app settings.
NewMailClient() mailer.Mailer
// NewFilesystem creates a new local or S3 filesystem instance
// for managing regular app files (ex. record uploads)
// based on the current app settings.
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
NewFilesystem() (*filesystem.System, error)
// NewBackupsFilesystem creates a new local or S3 filesystem instance
// for managing app backups based on the current app settings.
//
// NB! Make sure to call Close() on the returned result
// after you are done working with it.
NewBackupsFilesystem() (*filesystem.System, error)
// ReloadSettings reinitializes and reloads the stored application settings.
ReloadSettings() error
// CreateBackup creates a new backup of the current app pb_data directory.
//
// Backups can be stored on S3 if it is configured in app.Settings().Backups.
//
// Please refer to the godoc of the specific core.App implementation
// for details on the backup procedures.
CreateBackup(name string) error
// RestoreBackup restores the backup with the specified name and restarts
// the current running application process.
//
// The safely perform the restore it is recommended to have free disk space
// for at least 2x the size of the restored pb_data backup.
//
// Please refer to the godoc of the specific core.App implementation
// for details on the restore procedures.
//
// NB! This feature is experimental and currently is expected to work only on UNIX based systems.
RestoreBackup(name string) error
// Restart restarts (aka. replaces) the current running application process.
//
// NB! It relies on execve which is supported only on UNIX based systems.
Restart() error
// RunSystemMigrations applies all new migrations registered in the [core.SystemMigrations] list.
RunSystemMigrations() error
// RunAppMigrations applies all new migrations registered in the [core.AppMigrations] list.
RunAppMigrations() error
// RunAllMigrations applies all system and app migrations
// (aka. from both [core.SystemMigrations] and [core.AppMigrations]).
RunAllMigrations() error
// DB returns the default app data.db builder instance.
//
// To minimize SQLITE_BUSY errors, it automatically routes the
// SELECT queries to the underlying concurrent db pool and everything else
// to the nonconcurrent one.
//
// For more finer control over the used connections pools you can
// call directly ConcurrentDB() or NonconcurrentDB().
DB() dbx.Builder
// ConcurrentDB returns the concurrent app data.db builder instance.
//
// This method is used mainly internally for executing db read
// operations in a concurrent/non-blocking manner.
//
// Most users should use simply DB() as it will automatically
// route the query execution to ConcurrentDB() or NonconcurrentDB().
//
// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
ConcurrentDB() dbx.Builder
// NonconcurrentDB returns the nonconcurrent app data.db builder instance.
//
// The returned db instance is limited only to a single open connection,
// meaning that it can process only 1 db operation at a time (other queries queue up).
//
// This method is used mainly internally and in the tests to execute write
// (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
//
// Most users should use simply DB() as it will automatically
// route the query execution to ConcurrentDB() or NonconcurrentDB().
//
// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
NonconcurrentDB() dbx.Builder
// AuxDB returns the app auxiliary.db builder instance.
//
// To minimize SQLITE_BUSY errors, it automatically routes the
// SELECT queries to the underlying concurrent db pool and everything else
// to the nonconcurrent one.
//
// For more finer control over the used connections pools you can
// call directly AuxConcurrentDB() or AuxNonconcurrentDB().
AuxDB() dbx.Builder
// AuxConcurrentDB returns the concurrent app auxiliary.db builder instance.
//
// This method is used mainly internally for executing db read
// operations in a concurrent/non-blocking manner.
//
// Most users should use simply AuxDB() as it will automatically
// route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
//
// In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
AuxConcurrentDB() dbx.Builder
// AuxNonconcurrentDB returns the nonconcurrent app auxiliary.db builder instance.
//
// The returned db instance is limited only to a single open connection,
// meaning that it can process only 1 db operation at a time (other queries queue up).
//
// This method is used mainly internally and in the tests to execute write
// (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
//
// Most users should use simply AuxDB() as it will automatically
// route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
//
// In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
AuxNonconcurrentDB() dbx.Builder
// HasTable checks if a table (or view) with the provided name exists (case insensitive).
// in the data.db.
HasTable(tableName string) bool
// AuxHasTable checks if a table (or view) with the provided name exists (case insensitive)
// in the auxiliary.db.
AuxHasTable(tableName string) bool
// TableColumns returns all column names of a single table by its name.
TableColumns(tableName string) ([]string, error)
// TableInfo returns the "table_info" pragma result for the specified table.
TableInfo(tableName string) ([]*TableInfoRow, error)
// TableIndexes returns a name grouped map with all non empty index of the specified table.
//
// Note: This method doesn't return an error on nonexisting table.
TableIndexes(tableName string) (map[string]string, error)
// DeleteTable drops the specified table.
//
// This method is a no-op if a table with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousTableName" argument must come only from trusted input!
DeleteTable(dangerousTableName string) error
// DeleteView drops the specified view name.
//
// This method is a no-op if a view with the provided name doesn't exist.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousViewName" argument must come only from trusted input!
DeleteView(dangerousViewName string) error
// SaveView creates (or updates already existing) persistent SQL view.
//
// NB! Be aware that this method is vulnerable to SQL injection and
// its arguments must come only from trusted input!
SaveView(dangerousViewName string, dangerousSelectQuery string) error
// CreateViewFields creates a new FieldsList from the provided select query.
//
// There are some caveats:
// - The select query must have an "id" column.
// - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousSelectQuery" argument must come only from trusted input!
CreateViewFields(dangerousSelectQuery string) (FieldsList, error)
// DryRunView executes the provided query by creating a temporary view
// collection and returning a sample of the resulting query records (if valid).
//
// The same caveats from CreateViewFields apply here too.
//
// NB! Be aware that this method is vulnerable to SQL injection and the
// "dangerousSelectQuery" argument must come only from trusted input!
DryRunView(dangerousSelectQuery string, sampleSize int) (*DryRunViewResult, error)
// FindRecordByViewFile returns the original Record of the provided view collection file.
FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)
// Vacuum executes VACUUM on the data.db in order to reclaim unused data db disk space.
Vacuum() error
// AuxVacuum executes VACUUM on the auxiliary.db in order to reclaim unused auxiliary db disk space.
AuxVacuum() error
// ModelQuery creates a new preconfigured select data.db query with preset
// SELECT, FROM and other common fields based on the provided model.
ModelQuery(model Model) *dbx.SelectQuery
// AuxModelQuery creates a new preconfigured select auxiliary.db query with preset
// SELECT, FROM and other common fields based on the provided model.
AuxModelQuery(model Model) *dbx.SelectQuery
// Delete deletes the specified model from the regular app database.
Delete(model Model) error
// AuxDelete deletes the specified model from the auxiliary database.
AuxDelete(model Model) error
// Save validates and saves the specified model into the regular app database.
//
// If you don't want to run validations, use [App.SaveNoValidate()].
Save(model Model) error
// SaveNoValidate saves the specified model into the regular app database without performing validations.
//
// If you want to also run validations before persisting, use [App.Save()].
SaveNoValidate(model Model) error
// AuxSave validates and saves the specified model into the auxiliary app database.
//
// If you don't want to run validations, use [App.AuxSaveNoValidate()].
AuxSave(model Model) error
// AuxSaveNoValidate saves the specified model into the auxiliary app database without performing validations.
//
// If you want to also run validations before persisting, use [App.AuxSave()].
AuxSaveNoValidate(model Model) error
// Validate triggers the OnModelValidate hook for the specified model.
Validate(model Model) error
// RunInTransaction wraps fn into a transaction for the regular app database.
//
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
RunInTransaction(fn func(txApp App) error) error
// AuxRunInTransaction wraps fn into a transaction for the auxiliary app database.
//
// It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
AuxRunInTransaction(fn func(txApp App) error) error
// LogQuery returns a new Log select query.
LogQuery() *dbx.SelectQuery
// FindLogById finds a single Log entry by its id.
FindLogById(id string) (*Log, error)
// LogsStatsItem returns hourly grouped logs statistics.
LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error)
// CountLogs returns the total number of log entries.
CountLogs(exprs ...dbx.Expression) (int64, error)
// DeleteOldLogs delete all logs that are created before createdBefore.
DeleteOldLogs(createdBefore time.Time) error
// CollectionQuery returns a new Collection select query.
CollectionQuery() *dbx.SelectQuery
// FindCollections finds all collections by the given type(s).
//
// If collectionTypes is not set, it returns all collections.
//
// Example:
//
// app.FindAllCollections() // all collections
// app.FindAllCollections("auth", "view") // only auth and view collections
FindAllCollections(collectionTypes ...string) ([]*Collection, error)
// ReloadCachedCollections fetches all collections and caches them into the app store.
ReloadCachedCollections() error
// FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.s
FindCollectionByNameOrId(nameOrId string) (*Collection, error)
// FindCachedCollectionByNameOrId is similar to [App.FindCollectionByNameOrId]
// but retrieves the Collection from the app cache instead of making a db call.
//
// NB! This method is suitable for read-only Collection operations.
//
// Returns [sql.ErrNoRows] if no Collection is found for consistency
// with the [App.FindCollectionByNameOrId] method.
//
// If you plan making changes to the returned Collection model,
// use [App.FindCollectionByNameOrId] instead.
//
// Caveats:
//
// - The returned Collection should be used only for read-only operations.
// Avoid directly modifying the returned cached Collection as it will affect
// the global cached value even if you don't persist the changes in the database!
// - If you are updating a Collection in a transaction and then call this method before commit,
// it'll return the cached Collection state and not the one from the uncommitted transaction.
// - The cache is automatically updated on collections db change (create/update/delete).
// To manually reload the cache you can call [App.ReloadCachedCollections]
FindCachedCollectionByNameOrId(nameOrId string) (*Collection, error)
// FindCollectionReferences returns information for all relation
// 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 excludeIds argument.
FindCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
// FindCachedCollectionReferences is similar to [App.FindCollectionReferences]
// but retrieves the Collection from the app cache instead of making a db call.
//
// NB! This method is suitable for read-only Collection operations.
//
// If you plan making changes to the returned Collection model,
// use [App.FindCollectionReferences] instead.
//
// Caveats:
//
// - The returned Collection should be used only for read-only operations.
// Avoid directly modifying the returned cached Collection as it will affect
// the global cached value even if you don't persist the changes in the database!
// - If you are updating a Collection in a transaction and then call this method before commit,
// it'll return the cached Collection state and not the one from the uncommitted transaction.
// - The cache is automatically updated on collections db change (create/update/delete).
// To manually reload the cache you can call [App.ReloadCachedCollections].
FindCachedCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
// 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
// table name for the records.
IsCollectionNameUnique(name string, excludeIds ...string) bool
// TruncateCollection deletes all records associated with the provided collection.
//
// The truncate operation is executed in a single transaction,
// aka. either everything is deleted or none.
//
// Note that this method will also trigger the records related
// cascade and file delete actions.
TruncateCollection(collection *Collection) error
// ImportCollections imports the provided collections data in a single transaction.
//
// For existing matching collections, the imported data is unmarshaled on top of the existing model.
//
// NB! If deleteMissing is true, ALL NON-SYSTEM COLLECTIONS AND SCHEMA FIELDS,
// that are not present in the imported configuration, WILL BE DELETED
// (this includes their related records data).
ImportCollections(toImport []map[string]any, deleteMissing bool) error
// ImportCollectionsByMarshaledJSON is the same as [ImportCollections]
// but accept marshaled json array as import data (usually used for the autogenerated snapshots).
ImportCollectionsByMarshaledJSON(rawSliceOfMaps []byte, deleteMissing bool) 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.
//
// This method is automatically invoked as part of a collection create/update/delete operation.
SyncRecordTableSchema(newCollection *Collection, oldCollection *Collection) error
// FindAllExternalAuthsByRecord returns all ExternalAuth models
// linked to the provided auth record.
FindAllExternalAuthsByRecord(authRecord *Record) ([]*ExternalAuth, error)
// FindAllExternalAuthsByCollection returns all ExternalAuth models
// linked to the provided auth collection.
FindAllExternalAuthsByCollection(collection *Collection) ([]*ExternalAuth, error)
// FindFirstExternalAuthByExpr returns the first available (the most recent created)
// ExternalAuth model that satisfies the non-nil expression.
FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalAuth, error)
// DeleteAllExternalAuthsByRecord deletes all ExternalAuth models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllExternalAuthsByRecord(authRecord *Record) error
// FindAllMFAsByRecord returns all MFA models linked to the provided auth record.
FindAllMFAsByRecord(authRecord *Record) ([]*MFA, error)
// FindAllMFAsByCollection returns all MFA models linked to the provided collection.
FindAllMFAsByCollection(collection *Collection) ([]*MFA, error)
// FindMFAById returns a single MFA model by its id.
FindMFAById(id string) (*MFA, error)
// DeleteAllMFAsByRecord deletes all MFA models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllMFAsByRecord(authRecord *Record) error
// DeleteExpiredMFAs deletes the expired MFAs for all auth collections.
DeleteExpiredMFAs() error
// FindAllOTPsByRecord returns all OTP models linked to the provided auth record.
FindAllOTPsByRecord(authRecord *Record) ([]*OTP, error)
// FindAllOTPsByCollection returns all OTP models linked to the provided collection.
FindAllOTPsByCollection(collection *Collection) ([]*OTP, error)
// FindOTPById returns a single OTP model by its id.
FindOTPById(id string) (*OTP, error)
// DeleteAllOTPsByRecord deletes all OTP models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllOTPsByRecord(authRecord *Record) error
// DeleteExpiredOTPs deletes the expired OTPs for all auth collections.
DeleteExpiredOTPs() error
// FindAllAuthOriginsByRecord returns all AuthOrigin models linked to the provided auth record (in DESC order).
FindAllAuthOriginsByRecord(authRecord *Record) ([]*AuthOrigin, error)
// FindAllAuthOriginsByCollection returns all AuthOrigin models linked to the provided collection (in DESC order).
FindAllAuthOriginsByCollection(collection *Collection) ([]*AuthOrigin, error)
// FindAuthOriginById returns a single AuthOrigin model by its id.
FindAuthOriginById(id string) (*AuthOrigin, error)
// FindAuthOriginByRecordAndFingerprint returns a single AuthOrigin model
// by its authRecord relation and fingerprint.
FindAuthOriginByRecordAndFingerprint(authRecord *Record, fingerprint string) (*AuthOrigin, error)
// DeleteAllAuthOriginsByRecord deletes all AuthOrigin models associated with the provided record.
//
// Returns a combined error with the failed deletes.
DeleteAllAuthOriginsByRecord(authRecord *Record) error
// RecordQuery returns a new Record select query from a collection model, id or name.
//
// In case a collection id or name is provided and that collection doesn't
// actually exists, the generated query will be created with a cancelled context
// and will fail once an executor (Row(), One(), All(), etc.) is called.
RecordQuery(collectionModelOrIdentifier any) *dbx.SelectQuery
// FindRecordById finds the Record model by its id.
FindRecordById(collectionModelOrIdentifier any, recordId string, optFilters ...func(q *dbx.SelectQuery) error) (*Record, error)
// FindRecordsByIds finds all records by the specified ids.
// If no records are found, returns an empty slice.
FindRecordsByIds(collectionModelOrIdentifier any, recordIds []string, optFilters ...func(q *dbx.SelectQuery) error) ([]*Record, error)
// FindAllRecords finds all records matching specified db expressions.
//
// Returns all collection records if no expression is provided.
//
// Returns an empty slice if no records are found.
//
// Example:
//
// // no extra expressions
// app.FindAllRecords("example")
//
// // with extra expressions
// expr1 := dbx.HashExp{"email": "[email protected]"}
// expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"})
// app.FindAllRecords("example", expr1, expr2)
FindAllRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) ([]*Record, error)
// FindFirstRecordByData returns the first found record matching
// the provided key-value pair.
FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error)
// FindRecordsByFilter returns limit number of records matching the
// provided string filter.
//
// NB! Use the last "params" argument to bind untrusted user variables!
//
// The filter argument is optional and can be empty string to target
// all available records.
//
// The sort argument is optional and can be empty string OR the same format
// used in the web APIs, ex. "-created,title".
//
// If the limit argument is <= 0, no limit is applied to the query and
// all matching records are returned.
//
// Returns an empty slice if no records are found.
//
// Example:
//
// app.FindRecordsByFilter(
// "posts",
// "title ~ {:title} && visible = {:visible}",
// "-created",
// 10,
// 0,
// dbx.Params{"title": "lorem ipsum", "visible": true}
// )
FindRecordsByFilter(
collectionModelOrIdentifier any,
filter string,
sort string,
limit int,
offset int,
params ...dbx.Params,
) ([]*Record, error)
// FindFirstRecordByFilter returns the first available record matching the provided filter (if any).
//
// NB! Use the last params argument to bind untrusted user variables!
//
// Returns sql.ErrNoRows if no record is found.
//
// Example:
//
// app.FindFirstRecordByFilter("posts", "")
// app.FindFirstRecordByFilter("posts", "slug={:slug} && status='public'", dbx.Params{"slug": "test"})
FindFirstRecordByFilter(
collectionModelOrIdentifier any,
filter string,
params ...dbx.Params,
) (*Record, error)
// CountRecords returns the total number of records in a collection.
CountRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) (int64, error)
// FindAuthRecordByToken finds the auth record associated with the provided JWT
// (auth, file, verifyEmail, changeEmail, passwordReset types).
//
// Optionally specify a list of validTypes to check tokens only from those types.
//
// Returns an error if the JWT is invalid, expired or not associated to an auth collection record.
FindAuthRecordByToken(token string, validTypes ...string) (*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.
FindAuthRecordByEmail(collectionModelOrIdentifier any, email string) (*Record, error)
// CanAccessRecord checks if a record is allowed to be accessed by the
// specified requestInfo and accessRule.
//
// Rule and db checks are ignored in case requestInfo.Auth is a superuser.
//
// The returned error indicate that something unexpected happened during
// the check (eg. invalid rule or db query error).
//
// The method always return false on invalid rule or db query error.
//
// Example:
//
// requestInfo, _ := e.RequestInfo()
// record, _ := app.FindRecordById("example", "RECORD_ID")
// rule := types.Pointer("@request.auth.id != '' || status = 'public'")
// // ... or use one of the record collection's rule, eg. record.Collection().ViewRule
//
// if ok, _ := app.CanAccessRecord(record, requestInfo, rule); ok { ... }
CanAccessRecord(record *Record, requestInfo *RequestInfo, accessRule *string) (bool, error)
// ExpandRecord expands the relations of a single Record model.
//
// If optFetchFunc is not set, then a default function will be used
// that returns all relation records.
//
// Returns a map with the failed expand parameters and their errors.
ExpandRecord(record *Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
// ExpandRecords expands the relations of the provided Record models list.
//
// If optFetchFunc is not set, then a default function will be used
// that returns all relation records.
//
// Returns a map with the failed expand parameters and their errors.
ExpandRecords(records []*Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
// OnBootstrap hook is triggered when initializing the main application
// resources (db, app settings, etc).
OnBootstrap() *hook.Hook[*BootstrapEvent]
// OnBootstrapClear hook is triggered when clearing the main application
// resources (db connections, cron, logger, etc.)
//
// It is usually invoked automatically right before app termination
// or when manually calling app.ClearBootstrap().
OnBootstrapClear() *hook.Hook[*BootstrapEvent]
// OnServe hook is triggered when the app web server is started
// (after starting the TCP listener but before initializing the blocking serve task),
// allowing you to adjust its options and attach new routes or middlewares.
OnServe() *hook.Hook[*ServeEvent]
// OnTerminate hook is triggered when the app is in the process
// of being terminated (ex. on SIGTERM signal).
//
// Note that the app could be terminated abruptly without awaiting the hook completion.
OnTerminate() *hook.Hook[*TerminateEvent]
// OnBackupCreate hook is triggered on each [App.CreateBackup] call.
OnBackupCreate() *hook.Hook[*BackupEvent]
// OnBackupRestore hook is triggered before app backup restore (aka. [App.RestoreBackup] call).
//
// Note that by default on success the application is restarted and the after state of the hook is ignored.
OnBackupRestore() *hook.Hook[*BackupEvent]
// OnModelValidate is triggered every time when a model is being validated
// (e.g. triggered by App.Validate() or App.Save()).
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelValidate(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelCreate is triggered every time when a new model is being created
// (e.g. triggered by App.Save()).
//
// Operations BEFORE the e.Next() execute before the model validation
// and the INSERT DB statement.
//
// Operations AFTER the e.Next() execute after the model validation
// and the INSERT DB statement.
//
// Note that successful execution doesn't guarantee that the model
// is persisted in the database since its wrapping transaction may
// not have been committed yet.
// If you want to listen to only the actual persisted events, you can
// bind to [OnModelAfterCreateSuccess] or [OnModelAfterCreateError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelCreate(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelCreateExecute is triggered after successful Model validation
// and right before the model INSERT DB statement execution.
//
// Usually it is triggered as part of the App.Save() in the following firing order:
// OnModelCreate {
// -> OnModelValidate (skipped with App.SaveNoValidate())
// -> OnModelCreateExecute
// }
//
// Note that successful execution doesn't guarantee that the model
// is persisted in the database since its wrapping transaction may have been
// committed yet.
// If you want to listen to only the actual persisted events,
// you can bind to [OnModelAfterCreateSuccess] or [OnModelAfterCreateError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelCreateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelAfterCreateSuccess is triggered after each successful
// Model DB create persistence.
//
// Note that when a Model is persisted as part of a transaction,
// this hook is delayed and executed only AFTER the transaction has been committed.
// This hook is NOT triggered in case the transaction rollbacks
// (aka. when the model wasn't persisted).
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelAfterCreateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelAfterCreateError is triggered after each failed
// Model DB create persistence.
//
// Note that the execution of this hook is either immediate or delayed
// depending on the error:
// - "immediate" on App.Save() failure
// - "delayed" on transaction rollback
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelAfterCreateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
// OnModelUpdate is triggered every time when a new model is being updated
// (e.g. triggered by App.Save()).
//
// Operations BEFORE the e.Next() execute before the model validation
// and the UPDATE DB statement.
//
// Operations AFTER the e.Next() execute after the model validation
// and the UPDATE DB statement.
//
// Note that successful execution doesn't guarantee that the model
// is persisted in the database since its wrapping transaction may
// not have been committed yet.
// If you want to listen to only the actual persisted events, you can
// bind to [OnModelAfterUpdateSuccess] or [OnModelAfterUpdateError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelUpdate(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelUpdateExecute is triggered after successful Model validation
// and right before the model UPDATE DB statement execution.
//
// Usually it is triggered as part of the App.Save() in the following firing order:
// OnModelUpdate {
// -> OnModelValidate (skipped with App.SaveNoValidate())
// -> OnModelUpdateExecute
// }
//
// Note that successful execution doesn't guarantee that the model
// is persisted in the database since its wrapping transaction may have been
// committed yet.
// If you want to listen to only the actual persisted events,
// you can bind to [OnModelAfterUpdateSuccess] or [OnModelAfterUpdateError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelUpdateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelAfterUpdateSuccess is triggered after each successful
// Model DB update persistence.
//
// Note that when a Model is persisted as part of a transaction,
// this hook is delayed and executed only AFTER the transaction has been committed.
// This hook is NOT triggered in case the transaction rollbacks
// (aka. when the model changes weren't persisted).
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelAfterUpdateError is triggered after each failed
// Model DB update persistence.
//
// Note that the execution of this hook is either immediate or delayed
// depending on the error:
// - "immediate" on App.Save() failure
// - "delayed" on transaction rollback
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelAfterUpdateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
// OnModelDelete is triggered every time when a new model is being deleted
// (e.g. triggered by App.Delete()).
//
// Note that successful execution doesn't guarantee that the model
// is deleted from the database since its wrapping transaction may
// not have been committed yet.
// If you want to listen to only the actual persisted deleted events, you can
// bind to [OnModelAfterDeleteSuccess] or [OnModelAfterDeleteError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelDelete(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelUpdateExecute is triggered right before the model
// DELETE DB statement execution.
//
// Usually it is triggered as part of the App.Delete() in the following firing order:
// OnModelDelete {
// -> (internal delete checks)
// -> OnModelDeleteExecute
// }
//
// Note that successful execution doesn't guarantee that the model
// is deleted from the database since its wrapping transaction may
// not have been committed yet.
// If you want to listen to only the actual persisted deleted events, you can
// bind to [OnModelAfterDeleteSuccess] or [OnModelAfterDeleteError] hooks.
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelDeleteExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelAfterDeleteSuccess is triggered after each successful
// Model DB delete persistence.
//
// Note that when a Model is deleted as part of a transaction,
// this hook is delayed and executed only AFTER the transaction has been committed.
// This hook is NOT triggered in case the transaction rollbacks
// (aka. when the model delete wasn't persisted).
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
// OnModelAfterDeleteError is triggered after each failed
// Model DB delete persistence.
//
// Note that the execution of this hook is either immediate or delayed
// depending on the error:
// - "immediate" on App.Delete() failure
// - "delayed" on transaction rollback
//
// For convenience, if you want to listen to only the Record models
// events without doing manual type assertion, you can attach to the OnRecord* proxy hooks.
//
// If the optional "tags" list (Collection id/name, Model table name, etc.) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnModelAfterDeleteError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
// OnRecordEnrich is triggered every time when a record is enriched
// (as part of the builtin Record responses, during realtime message seriazation, or when [apis.EnrichRecord] is invoked).
//
// It could be used for example to redact/hide or add computed temporary
// Record model props only for the specific request info. For example:
//
// app.OnRecordEnrich("posts").BindFunc(func(e core.*RecordEnrichEvent) {
// // hide one or more fields
// e.Record.Hide("role")
//
// // add new custom field for registered users
// if e.RequestInfo.Auth != nil && e.RequestInfo.Auth.Collection().Name == "users" {
// e.Record.WithCustomData(true) // for security requires explicitly allowing it
// e.Record.Set("computedScore", e.Record.GetInt("score") * e.RequestInfo.Auth.GetInt("baseScore"))
// }
//
// return e.Next()
// })
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordEnrich(tags ...string) *hook.TaggedHook[*RecordEnrichEvent]
// OnRecordValidate is a Record proxy model hook of [OnModelValidate].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordValidate(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordCreate is a Record proxy model hook of [OnModelCreate].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordCreate(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordCreateExecute is a Record proxy model hook of [OnModelCreateExecute].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordCreateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordAfterCreateSuccess is a Record proxy model hook of [OnModelAfterCreateSuccess].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAfterCreateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordAfterCreateError is a Record proxy model hook of [OnModelAfterCreateError].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAfterCreateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
// OnRecordUpdate is a Record proxy model hook of [OnModelUpdate].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordUpdate(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordUpdateExecute is a Record proxy model hook of [OnModelUpdateExecute].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordUpdateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordAfterUpdateSuccess is a Record proxy model hook of [OnModelAfterUpdateSuccess].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordAfterUpdateError is a Record proxy model hook of [OnModelAfterUpdateError].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAfterUpdateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
// OnRecordDelete is a Record proxy model hook of [OnModelDelete].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordDelete(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordDeleteExecute is a Record proxy model hook of [OnModelDeleteExecute].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordDeleteExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordAfterDeleteSuccess is a Record proxy model hook of [OnModelAfterDeleteSuccess].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
// OnRecordAfterDeleteError is a Record proxy model hook of [OnModelAfterDeleteError].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAfterDeleteError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
// OnCollectionValidate is a Collection proxy model hook of [OnModelValidate].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionValidate(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionCreate is a Collection proxy model hook of [OnModelCreate].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionCreate(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionCreateExecute is a Collection proxy model hook of [OnModelCreateExecute].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionCreateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionAfterCreateSuccess is a Collection proxy model hook of [OnModelAfterCreateSuccess].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionAfterCreateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionAfterCreateError is a Collection proxy model hook of [OnModelAfterCreateError].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionAfterCreateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
// OnCollectionUpdate is a Collection proxy model hook of [OnModelUpdate].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionUpdate(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionUpdateExecute is a Collection proxy model hook of [OnModelUpdateExecute].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionUpdateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionAfterUpdateSuccess is a Collection proxy model hook of [OnModelAfterUpdateSuccess].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionAfterUpdateError is a Collection proxy model hook of [OnModelAfterUpdateError].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionAfterUpdateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
// OnCollectionDelete is a Collection proxy model hook of [OnModelDelete].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionDelete(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionDeleteExecute is a Collection proxy model hook of [OnModelDeleteExecute].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionDeleteExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionAfterDeleteSuccess is a Collection proxy model hook of [OnModelAfterDeleteSuccess].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
// OnCollectionAfterDeleteError is a Collection proxy model hook of [OnModelAfterDeleteError].
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnCollectionAfterDeleteError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
// OnMailerSend hook is triggered every time when a new email is
// being sent using the [App.NewMailClient()] instance.
//
// It allows intercepting the email message or to use a custom mailer client.
OnMailerSend() *hook.Hook[*MailerEvent]
// OnMailerRecordAuthAlertSend hook is triggered when
// sending a new device login auth alert email, allowing you to
// intercept and customize the email message that is being sent.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnMailerRecordAuthAlertSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
// OnMailerBeforeRecordResetPasswordSend hook is triggered when
// sending a password reset email to an auth record, allowing
// you to intercept and customize the email message that is being sent.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnMailerRecordPasswordResetSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
// OnMailerBeforeRecordVerificationSend hook is triggered when
// sending a verification email to an auth record, allowing
// you to intercept and customize the email message that is being sent.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnMailerRecordVerificationSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
// OnMailerRecordEmailChangeSend hook is triggered when sending a
// confirmation new address email to an auth record, allowing
// you to intercept and customize the email message that is being sent.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnMailerRecordEmailChangeSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
// OnMailerRecordOTPSend hook is triggered when sending an OTP email
// to an auth record, allowing you to intercept and customize the
// email message that is being sent.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnMailerRecordOTPSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
// PocketOne: OnFilesystemCreate hook is triggered every time app.NewFilesystem() or app.NewBackupsFilesystem()
// creates a filesystem, before the default one. A handler may supply its own (see [FilesystemCreateEvent]).
// Plugins may trigger it for their own kinds too. NewFilesystem and NewBackupsFilesystem call
// SetContext(app.Context()) on the filesystem they return, including one a handler supplies.
OnFilesystemCreate() *hook.Hook[*FilesystemCreateEvent]
// OnRealtimeConnectRequest hook is triggered when establishing the SSE client connection.
//
// Any execution after e.Next() of a hook handler happens after the client disconnects.
OnRealtimeConnectRequest() *hook.Hook[*RealtimeConnectRequestEvent]
// OnRealtimeMessageSend hook is triggered when sending an SSE message to a client.
OnRealtimeMessageSend() *hook.Hook[*RealtimeMessageEvent]
// OnRealtimeSubscribeRequest hook is triggered when updating the
// client subscriptions, allowing you to further validate and
// modify the submitted change.
OnRealtimeSubscribeRequest() *hook.Hook[*RealtimeSubscribeRequestEvent]
// OnSettingsListRequest hook is triggered on each API Settings list request.
//
// Could be used to validate or modify the response before returning it to the client.
OnSettingsListRequest() *hook.Hook[*SettingsListRequestEvent]
// OnSettingsUpdateRequest hook is triggered on each API Settings update request.
//
// Could be used to additionally validate the request data or
// implement completely different persistence behavior.
OnSettingsUpdateRequest() *hook.Hook[*SettingsUpdateRequestEvent]
// OnSettingsReload hook is triggered every time when the App.Settings()
// is being replaced with a new state.
//
// Calling App.Settings() after e.Next() returns the new state.
OnSettingsReload() *hook.Hook[*SettingsReloadEvent]
// OnFileDownloadRequest hook is triggered before each API File download request.
//
// Could be used to validate or modify the file response before
// returning it to the client.
OnFileDownloadRequest(tags ...string) *hook.TaggedHook[*FileDownloadRequestEvent]
// OnFileBeforeTokenRequest hook is triggered on each auth file token API request.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnFileTokenRequest(tags ...string) *hook.TaggedHook[*FileTokenRequestEvent]
// OnRecordAuthRequest hook is triggered on each successful API
// record authentication request (sign-in, token refresh, etc.).
//
// Could be used to additionally validate or modify the authenticated
// record data and token.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAuthRequest(tags ...string) *hook.TaggedHook[*RecordAuthRequestEvent]
// OnRecordAuthWithPasswordRequest hook is triggered on each
// Record auth with password API request.
//
// [RecordAuthWithPasswordRequestEvent.Record] could be nil if no matching identity is found, allowing
// you to manually locate a different Record model (by reassigning [RecordAuthWithPasswordRequestEvent.Record]).
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAuthWithPasswordRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithPasswordRequestEvent]
// OnRecordAuthWithOAuth2Request hook is triggered on each Record
// OAuth2 sign-in/sign-up API request (after token exchange and before external provider linking).
//
// If [RecordAuthWithOAuth2RequestEvent.Record] is not set, then the OAuth2
// request will try to create a new auth Record.
//
// To assign or link a different existing record model you can
// change the [RecordAuthWithOAuth2RequestEvent.Record] field.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAuthWithOAuth2Request(tags ...string) *hook.TaggedHook[*RecordAuthWithOAuth2RequestEvent]
// OnRecordAuthRefreshRequest hook is triggered on each Record
// auth refresh API request (right before generating a new auth token).
//
// Could be used to additionally validate the request data or implement
// completely different auth refresh behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAuthRefreshRequest(tags ...string) *hook.TaggedHook[*RecordAuthRefreshRequestEvent]
// OnRecordRequestPasswordResetRequest hook is triggered on
// each Record request password reset API request.
//
// Could be used to additionally validate the request data or implement
// completely different password reset behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordRequestPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordRequestPasswordResetRequestEvent]
// OnRecordConfirmPasswordResetRequest hook is triggered on
// each Record confirm password reset API request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordConfirmPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordConfirmPasswordResetRequestEvent]
// OnRecordRequestVerificationRequest hook is triggered on
// each Record request verification API request.
//
// Could be used to additionally validate the loaded request data or implement
// completely different verification behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordRequestVerificationRequest(tags ...string) *hook.TaggedHook[*RecordRequestVerificationRequestEvent]
// OnRecordConfirmVerificationRequest hook is triggered on each
// Record confirm verification API request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordConfirmVerificationRequest(tags ...string) *hook.TaggedHook[*RecordConfirmVerificationRequestEvent]
// OnRecordRequestEmailChangeRequest hook is triggered on each
// Record request email change API request.
//
// Could be used to additionally validate the request data or implement
// completely different request email change behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordRequestEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordRequestEmailChangeRequestEvent]
// OnRecordConfirmEmailChangeRequest hook is triggered on each
// Record confirm email change API request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordConfirmEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordConfirmEmailChangeRequestEvent]
// OnRecordRequestOTPRequest hook is triggered on each Record
// request OTP API request.
//
// [RecordCreateOTPRequestEvent.Record] could be nil if no matching identity is found, allowing
// you to manually create or locate a different Record model (by reassigning [RecordCreateOTPRequestEvent.Record]).
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordRequestOTPRequest(tags ...string) *hook.TaggedHook[*RecordCreateOTPRequestEvent]
// OnRecordAuthWithOTPRequest hook is triggered on each Record
// auth with OTP API request.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordAuthWithOTPRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithOTPRequestEvent]
// OnRecordsListRequest hook is triggered on each API Records list request.
//
// Could be used to validate or modify the response before returning it to the client.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordsListRequest(tags ...string) *hook.TaggedHook[*RecordsListRequestEvent]
// OnRecordViewRequest hook is triggered on each API Record view request.
//
// Could be used to validate or modify the response before returning it to the client.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordViewRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
// OnRecordCreateRequest hook is triggered on each API Record create request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordCreateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
// OnRecordUpdateRequest hook is triggered on each API Record update request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordUpdateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
// OnRecordDeleteRequest hook is triggered on each API Record delete request.
//
// Could be used to additionally validate the request data or implement
// completely different delete behavior.
//
// If the optional "tags" list (Collection ids or names) is specified,
// then all event handlers registered via the created hook will be
// triggered and called only if their event data origin matches the tags.
OnRecordDeleteRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
// OnCollectionsListRequest hook is triggered on each API Collections list request.
//
// Could be used to validate or modify the response before returning it to the client.
OnCollectionsListRequest() *hook.Hook[*CollectionsListRequestEvent]
// OnCollectionViewRequest hook is triggered on each API Collection view request.
//
// Could be used to validate or modify the response before returning it to the client.
OnCollectionViewRequest() *hook.Hook[*CollectionRequestEvent]
// OnCollectionCreateRequest hook is triggered on each API Collection create request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
OnCollectionCreateRequest() *hook.Hook[*CollectionRequestEvent]
// OnCollectionUpdateRequest hook is triggered on each API Collection update request.
//
// Could be used to additionally validate the request data or implement
// completely different persistence behavior.
OnCollectionUpdateRequest() *hook.Hook[*CollectionRequestEvent]
// OnCollectionDeleteRequest hook is triggered on each API Collection delete request.
//
// Could be used to additionally validate the request data or implement
// completely different delete behavior.
OnCollectionDeleteRequest() *hook.Hook[*CollectionRequestEvent]
// OnCollectionsBeforeImportRequest hook is triggered on each API
// collections import request.
//
// Could be used to additionally validate the imported collections or
// to implement completely different import behavior.
OnCollectionsImportRequest() *hook.Hook[*CollectionsImportRequestEvent]
// OnBatchRequest hook is triggered on each API batch request.
//
// Could be used to additionally validate or modify the submitted batch requests.
OnBatchRequest() *hook.Hook[*BatchRequestEvent]
// contains filtered or unexported methods
}
App defines the main PocketBase app interface.
Note that the interface is not intended to be implemented manually by users and instead they should use core.BaseApp (either directly or as embedded field in a custom struct).
This interface exists to make testing easier and to allow users to create common and pluggable helpers and methods that doesn't rely on a specific wrapped app struct (hence the large interface size).
BaseApp
type BaseApp struct {
// contains filtered or unexported fields
}
BaseApp implements core.App and defines the base PocketBase app structure.
NewBaseApp
func NewBaseApp(config BaseAppConfig) *BaseApp
NewBaseApp creates and returns a new BaseApp instance configured with the provided arguments.
To initialize the app, you need to call `app.Bootstrap()`.
BaseApp.AuxConcurrentDB
func (app *BaseApp) AuxConcurrentDB() dbx.Builder
AuxConcurrentDB returns the concurrent app auxiliary.db builder instance.
This method is used mainly internally for executing db read operations in a concurrent/non-blocking manner.
Most users should use simply AuxDB() as it will automatically route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
BaseApp.AuxDB
func (app *BaseApp) AuxDB() dbx.Builder
AuxDB returns the app auxiliary.db builder instance.
To minimize SQLITE_BUSY errors, it automatically routes the SELECT queries to the underlying concurrent db pool and everything else to the nonconcurrent one.
For more finer control over the used connections pools you can call directly AuxConcurrentDB() or AuxNonconcurrentDB().
BaseApp.AuxDelete
func (app *BaseApp) AuxDelete(model Model) error
AuxDelete deletes the specified model from the auxiliary database.
BaseApp.AuxHasTable
func (app *BaseApp) AuxHasTable(tableName string) bool
AuxHasTable checks if a table (or view) with the provided name exists (case insensitive) in the auixiliary.db.
BaseApp.AuxModelQuery
func (app *BaseApp) AuxModelQuery(m Model) *dbx.SelectQuery
AuxModelQuery creates a new preconfigured select auxiliary.db query with preset SELECT, FROM and other common fields based on the provided model.
BaseApp.AuxNonconcurrentDB
func (app *BaseApp) AuxNonconcurrentDB() dbx.Builder
AuxNonconcurrentDB returns the nonconcurrent app auxiliary.db builder instance.
The returned db instance is limited only to a single open connection, meaning that it can process only 1 db operation at a time (other queries queue up).
This method is used mainly internally and in the tests to execute write (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
Most users should use simply AuxDB() as it will automatically route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
BaseApp.AuxRunInTransaction
func (app *BaseApp) AuxRunInTransaction(fn func(txApp App) error) error
AuxRunInTransaction wraps fn into a transaction for the auxiliary app database.
It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
BaseApp.AuxSave
func (app *BaseApp) AuxSave(model Model) error
AuxSave validates and saves the specified model into the auxiliary app database.
If you don't want to run validations, use [App.AuxSaveNoValidate()].
BaseApp.AuxSaveNoValidate
func (app *BaseApp) AuxSaveNoValidate(model Model) error
AuxSaveNoValidate saves the specified model into the auxiliary app database without performing validations.
If you want to also run validations before persisting, use [App.AuxSave()].
BaseApp.AuxVacuum
func (app *BaseApp) AuxVacuum() error
AuxVacuum executes VACUUM on the auxiliary.db in order to reclaim unused auxiliary db disk space.
BaseApp.Bootstrap
func (app *BaseApp) Bootstrap() error
Bootstrap initializes the application (aka. create data dir, open db connections, load settings, etc.).
It calls ClearBootstrap() if the application was already bootstrapped.
BaseApp.CanAccessRecord
func (app *BaseApp) CanAccessRecord(record *Record, requestInfo *RequestInfo, accessRule *string) (bool, error)
CanAccessRecord checks if a record is allowed to be accessed by the specified requestInfo and accessRule.
Rule and db checks are ignored in case requestInfo.Auth is a superuser.
The returned error indicate that something unexpected happened during the check (eg. invalid rule or db query error).
The method always return false on invalid rule or db query error.
Example:
requestInfo, _ := e.RequestInfo()
record, _ := app.FindRecordById("example", "RECORD_ID")
rule := types.Pointer("@request.auth.id != '' || status = 'public'")
// ... or use one of the record collection's rule, eg. record.Collection().ViewRule
if ok, _ := app.CanAccessRecord(record, requestInfo, rule); ok { ... }
BaseApp.ClearBootstrap
func (app *BaseApp) ClearBootstrap() error
ClearBootstrap releases the initialized core app resources (closing db connections, stopping cron ticker, etc.).
This method is no-op if the application is not bootstrapped yet.
BaseApp.CollectionQuery
func (app *BaseApp) CollectionQuery() *dbx.SelectQuery
CollectionQuery returns a new Collection select query.
BaseApp.ConcurrentDB
func (app *BaseApp) ConcurrentDB() dbx.Builder
ConcurrentDB returns the concurrent app data.db builder instance.
This method is used mainly internally for executing db read operations in a concurrent/non-blocking manner.
Most users should use simply DB() as it will automatically route the query execution to ConcurrentDB() or NonconcurrentDB().
In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
BaseApp.Context
func (app *BaseApp) Context() context.Context
Context returns the context associated with the current app instance.
BaseApp.CountLogs
func (app *BaseApp) CountLogs(optExprs ...dbx.Expression) (int64, error)
CountLogs returns the total number of log entries.
BaseApp.CountRecords
func (app *BaseApp) CountRecords(collectionModelOrIdentifier any, optExprs ...dbx.Expression) (int64, error)
CountRecords returns the total number of records in a collection.
BaseApp.CreateBackup
func (app *BaseApp) CreateBackup(name string) error
CreateBackup creates a new backup of the current app pb_data directory.
If name is empty, it will be autogenerated. If backup with the same name exists, the new backup file will replace it.
To safely perform the backup, it is recommended to have free disk space for at least 2x the size of the pb_data directory.
By default backups are stored in pb_data/backups (the backups directory itself is excluded from the generated backup).
Backups can be stored on S3 if it is configured in app.Settings().Backups. When using S3 storage for the uploaded collection files, you have to take care manually to backup those since they are not part of the pb_data.
DB write locks are minimal and isolated only for the duration of the VACUUM INTO statement that creates a live copy of the app database.
The backup works as follow:
-
Start listening for DELETED storage files. In case a file is being deleted while the backup is still ongoing, we directly copy it in the zip before the deletion and mark it as "excluded".
-
Copy the main database with VACUUM INTO, write it in the zip and mark it as "excluded".
-
Stop listening for DELETED files.
-
Start listening for NEW storage files and mark all new files from this point as "excluded".
-
Copy the logs database with VACUUM INTO, write it in the zip and mark it as "excluded".
-
Copy the rest of the pb_data files in the zip while ignoring the "excluded" list (it should be concurrent safe).
-
Stop listening for NEW storage files.
While there is a risk for a race condition between steps 1, 2 and 3, it is an acceptable trade-off between performance and correctness because in the worst case there will be some unused storage files in the backup that don't do any harm.
BaseApp.CreateViewFields
func (app *BaseApp) CreateViewFields(dangerousSelectQuery string) (FieldsList, error)
CreateViewFields creates a new FieldsList from the provided select query.
There are some caveats: - The select query must have an "id" column. - Wildcard ("*") columns are not supported to avoid accidentally leaking sensitive data.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousSelectQuery" argument must come only from trusted input!
BaseApp.Cron
func (app *BaseApp) Cron() *cron.Cron
Cron returns the app cron instance.
BaseApp.DB
func (app *BaseApp) DB() dbx.Builder
DB returns the default app data.db builder instance.
To minimize SQLITE_BUSY errors, it automatically routes the SELECT queries to the underlying concurrent db pool and everything else to the nonconcurrent one.
For more finer control over the used connections pools you can call directly ConcurrentDB() or NonconcurrentDB().
BaseApp.DataDir
func (app *BaseApp) DataDir() string
DataDir returns the app data directory path.
BaseApp.Delete
func (app *BaseApp) Delete(model Model) error
Delete deletes the specified model from the regular app database.
BaseApp.DeleteAllAuthOriginsByRecord
func (app *BaseApp) DeleteAllAuthOriginsByRecord(authRecord *Record) error
DeleteAllAuthOriginsByRecord deletes all AuthOrigin models associated with the provided record.
Returns a combined error with the failed deletes.
BaseApp.DeleteAllExternalAuthsByRecord
func (app *BaseApp) DeleteAllExternalAuthsByRecord(authRecord *Record) error
DeleteAllExternalAuthsByRecord deletes all ExternalAuth models associated with the provided record.
Returns a combined error with the failed deletes.
BaseApp.DeleteAllMFAsByRecord
func (app *BaseApp) DeleteAllMFAsByRecord(authRecord *Record) error
DeleteAllMFAsByRecord deletes all MFA models associated with the provided record.
Returns a combined error with the failed deletes.
BaseApp.DeleteAllOTPsByRecord
func (app *BaseApp) DeleteAllOTPsByRecord(authRecord *Record) error
DeleteAllOTPsByRecord deletes all OTP models associated with the provided record.
Returns a combined error with the failed deletes.
BaseApp.DeleteExpiredMFAs
func (app *BaseApp) DeleteExpiredMFAs() error
DeleteExpiredMFAs deletes the expired MFAs for all auth collections.
BaseApp.DeleteExpiredOTPs
func (app *BaseApp) DeleteExpiredOTPs() error
DeleteExpiredOTPs deletes the expired OTPs for all auth collections.
BaseApp.DeleteOldLogs
func (app *BaseApp) DeleteOldLogs(createdBefore time.Time) error
DeleteOldLogs delete all logs that are created before createdBefore.
For better performance the logs delete is executed as plain SQL statement, aka. no delete model hook events will be fired.
BaseApp.DeleteTable
func (app *BaseApp) DeleteTable(dangerousTableName string) error
DeleteTable drops the specified table.
This method is a no-op if a table with the provided name doesn't exist.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousTableName" argument must come only from trusted input!
BaseApp.DeleteView
func (app *BaseApp) DeleteView(dangerousViewName string) error
DeleteView drops the specified view name.
This method is a no-op if a view with the provided name doesn't exist.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousViewName" argument must come only from trusted input!
BaseApp.DryRunView
func (app *BaseApp) DryRunView(dangerousSelectQuery string, sampleSize int) (*DryRunViewResult, error)
DryRunView executes the provided query by creating a temporary view collection and returning a sample of the resulting query records (if valid).
The same caveats from CreateViewFields apply here too.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousSelectQuery" argument must come only from trusted input!
BaseApp.EncryptionEnv
func (app *BaseApp) EncryptionEnv() string
EncryptionEnv returns the name of the app secret env key (currently used primarily for optional settings encryption but this may change in the future).
BaseApp.ExpandRecord
func (app *BaseApp) ExpandRecord(record *Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
ExpandRecord expands the relations of a single Record model.
If optFetchFunc is not set, then a default function will be used that returns all relation records.
Returns a map with the failed expand parameters and their errors.
BaseApp.ExpandRecords
func (app *BaseApp) ExpandRecords(records []*Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
ExpandRecords expands the relations of the provided Record models list.
If optFetchFunc is not set, then a default function will be used that returns all relation records.
Returns a map with the failed expand parameters and their errors.
BaseApp.FindAllAuthOriginsByCollection
func (app *BaseApp) FindAllAuthOriginsByCollection(collection *Collection) ([]*AuthOrigin, error)
FindAllAuthOriginsByCollection returns all AuthOrigin models linked to the provided collection (in DESC order).
BaseApp.FindAllAuthOriginsByRecord
func (app *BaseApp) FindAllAuthOriginsByRecord(authRecord *Record) ([]*AuthOrigin, error)
FindAllAuthOriginsByRecord returns all AuthOrigin models linked to the provided auth record (in DESC order).
BaseApp.FindAllCollections
func (app *BaseApp) FindAllCollections(collectionTypes ...string) ([]*Collection, error)
FindCollections finds all collections by the given type(s).
If collectionTypes is not set, it returns all collections.
Example:
app.FindAllCollections() // all collections
app.FindAllCollections("auth", "view") // only auth and view collections
BaseApp.FindAllExternalAuthsByCollection
func (app *BaseApp) FindAllExternalAuthsByCollection(collection *Collection) ([]*ExternalAuth, error)
FindAllExternalAuthsByCollection returns all ExternalAuth models linked to the provided auth collection.
BaseApp.FindAllExternalAuthsByRecord
func (app *BaseApp) FindAllExternalAuthsByRecord(authRecord *Record) ([]*ExternalAuth, error)
FindAllExternalAuthsByRecord returns all ExternalAuth models linked to the provided auth record.
BaseApp.FindAllMFAsByCollection
func (app *BaseApp) FindAllMFAsByCollection(collection *Collection) ([]*MFA, error)
FindAllMFAsByCollection returns all MFA models linked to the provided collection.
BaseApp.FindAllMFAsByRecord
func (app *BaseApp) FindAllMFAsByRecord(authRecord *Record) ([]*MFA, error)
FindAllMFAsByRecord returns all MFA models linked to the provided auth record.
BaseApp.FindAllOTPsByCollection
func (app *BaseApp) FindAllOTPsByCollection(collection *Collection) ([]*OTP, error)
FindAllOTPsByCollection returns all OTP models linked to the provided collection.
BaseApp.FindAllOTPsByRecord
func (app *BaseApp) FindAllOTPsByRecord(authRecord *Record) ([]*OTP, error)
FindAllOTPsByRecord returns all OTP models linked to the provided auth record.
BaseApp.FindAllRecords
func (app *BaseApp) FindAllRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) ([]*Record, error)
FindAllRecords finds all records matching specified db expressions.
Returns all collection records if no expression is provided.
Returns an empty slice if no records are found.
Example:
// no extra expressions
app.FindAllRecords("example")
// with extra expressions
expr1 := dbx.HashExp{"email": "[email protected]"}
expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"})
app.FindAllRecords("example", expr1, expr2)
BaseApp.FindAuthOriginById
func (app *BaseApp) FindAuthOriginById(id string) (*AuthOrigin, error)
FindAuthOriginById returns a single AuthOrigin model by its id.
BaseApp.FindAuthOriginByRecordAndFingerprint
func (app *BaseApp) FindAuthOriginByRecordAndFingerprint(authRecord *Record, fingerprint string) (*AuthOrigin, error)
FindAuthOriginByRecordAndFingerprint returns a single AuthOrigin model by its authRecord relation and fingerprint.
BaseApp.FindAuthRecordByEmail
func (app *BaseApp) FindAuthRecordByEmail(collectionModelOrIdentifier any, email string) (*Record, error)
FindAuthRecordByEmail finds the auth record associated with the provided email.
The email check would be case-insensitive if the related collection email unique index has COLLATE NOCASE specified for the email column.
Returns an error if it is not an auth collection or the record is not found.
BaseApp.FindAuthRecordByToken
func (app *BaseApp) FindAuthRecordByToken(token string, validTypes ...string) (*Record, error)
FindAuthRecordByToken finds the auth record associated with the provided JWT (auth, file, verifyEmail, changeEmail, passwordReset types).
Optionally specify a list of validTypes to check tokens only from those types.
Returns an error if the JWT is invalid, expired or not associated to an auth collection record.
BaseApp.FindCachedCollectionByNameOrId
func (app *BaseApp) FindCachedCollectionByNameOrId(nameOrId string) (*Collection, error)
FindCachedCollectionByNameOrId is similar to BaseApp.FindCollectionByNameOrId but retrieves the Collection from the app cache instead of making a db call.
NB! This method is suitable for read-only Collection operations.
Returns sql.ErrNoRows if no Collection is found for consistency with the BaseApp.FindCollectionByNameOrId method.
If you plan making changes to the returned Collection model, use BaseApp.FindCollectionByNameOrId instead.
Caveats:
- The returned Collection should be used only for read-only operations. Avoid directly modifying the returned cached Collection as it will affect the global cached value even if you don't persist the changes in the database!
- If you are updating a Collection in a transaction and then call this method before commit, it'll return the cached Collection state and not the one from the uncommitted transaction.
- The cache is automatically updated on collections db change (create/update/delete). To manually reload the cache you can call BaseApp.ReloadCachedCollections.
BaseApp.FindCachedCollectionReferences
func (app *BaseApp) FindCachedCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
FindCachedCollectionReferences is similar to BaseApp.FindCollectionReferences but retrieves the Collection from the app cache instead of making a db call.
NB! This method is suitable for read-only Collection operations.
If you plan making changes to the returned Collection model, use BaseApp.FindCollectionReferences instead.
Caveats:
- The returned Collection should be used only for read-only operations. Avoid directly modifying the returned cached Collection as it will affect the global cached value even if you don't persist the changes in the database!
- If you are updating a Collection in a transaction and then call this method before commit, it'll return the cached Collection state and not the one from the uncommitted transaction.
- The cache is automatically updated on collections db change (create/update/delete). To manually reload the cache you can call BaseApp.ReloadCachedCollections.
BaseApp.FindCollectionByNameOrId
func (app *BaseApp) FindCollectionByNameOrId(nameOrId string) (*Collection, error)
FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.
BaseApp.FindCollectionReferences
func (app *BaseApp) FindCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
FindCollectionReferences returns information for all relation 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 excludeIds argument.
BaseApp.FindFirstExternalAuthByExpr
func (app *BaseApp) FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalAuth, error)
FindFirstExternalAuthByExpr returns the first available (the most recent created) ExternalAuth model that satisfies the non-nil expression.
BaseApp.FindFirstRecordByData
func (app *BaseApp) FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error)
FindFirstRecordByData returns the first found record matching the provided key-value pair.
BaseApp.FindFirstRecordByFilter
func (app *BaseApp) FindFirstRecordByFilter(
collectionModelOrIdentifier any,
filter string,
params ...dbx.Params,
) (*Record, error)
FindFirstRecordByFilter returns the first available record matching the provided filter (if any).
NB! Use the last params argument to bind untrusted user variables!
Returns sql.ErrNoRows if no record is found.
Example:
app.FindFirstRecordByFilter("posts", "")
app.FindFirstRecordByFilter("posts", "slug={:slug} && status='public'", dbx.Params{"slug": "test"})
BaseApp.FindLogById
func (app *BaseApp) FindLogById(id string) (*Log, error)
FindLogById finds a single Log entry by its id.
BaseApp.FindMFAById
func (app *BaseApp) FindMFAById(id string) (*MFA, error)
FindMFAById returns a single MFA model by its id.
BaseApp.FindOTPById
func (app *BaseApp) FindOTPById(id string) (*OTP, error)
FindOTPById returns a single OTP model by its id.
BaseApp.FindRecordById
func (app *BaseApp) FindRecordById(
collectionModelOrIdentifier any,
recordId string,
optFilters ...func(q *dbx.SelectQuery) error,
) (*Record, error)
FindRecordById finds the Record model by its id.
BaseApp.FindRecordByViewFile
func (app *BaseApp) FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)
FindRecordByViewFile returns the original Record of the provided view collection file.
BaseApp.FindRecordsByFilter
func (app *BaseApp) FindRecordsByFilter(
collectionModelOrIdentifier any,
filter string,
sort string,
limit int,
offset int,
params ...dbx.Params,
) ([]*Record, error)
FindRecordsByFilter returns limit number of records matching the provided string filter.
NB! Use the last "params" argument to bind untrusted user variables!
The filter argument is optional and can be empty string to target all available records.
The sort argument is optional and can be empty string OR the same format used in the web APIs, ex. "-created,title".
If the limit argument is <= 0, no limit is applied to the query and all matching records are returned.
Returns an empty slice if no records are found.
Example:
app.FindRecordsByFilter(
"posts",
"title ~ {:title} && visible = {:visible}",
"-created",
10,
0,
dbx.Params{"title": "lorem ipsum", "visible": true}
)
BaseApp.FindRecordsByIds
func (app *BaseApp) FindRecordsByIds(
collectionModelOrIdentifier any,
recordIds []string,
optFilters ...func(q *dbx.SelectQuery) error,
) ([]*Record, error)
FindRecordsByIds finds all records by the specified ids. If no records are found, returns an empty slice.
BaseApp.HasTable
func (app *BaseApp) HasTable(tableName string) bool
HasTable checks if a table (or view) with the provided name exists (case insensitive). in the data.db.
BaseApp.ImportCollections
func (app *BaseApp) ImportCollections(toImport []map[string]any, deleteMissing bool) error
ImportCollections imports the provided collections data in a single transaction.
For existing matching collections, the imported data is unmarshaled on top of the existing model.
NB! If deleteMissing is true, ALL NON-SYSTEM COLLECTIONS AND SCHEMA FIELDS, that are not present in the imported configuration, WILL BE DELETED (this includes their related records data).
BaseApp.ImportCollectionsByMarshaledJSON
func (app *BaseApp) ImportCollectionsByMarshaledJSON(rawSliceOfMaps []byte, deleteMissing bool) error
ImportCollectionsByMarshaledJSON is the same as [ImportCollections] but accept marshaled json array as import data (usually used for the autogenerated snapshots).
BaseApp.IsBootstrapped
func (app *BaseApp) IsBootstrapped() bool
IsBootstrapped checks if the application was initialized (aka. whether Bootstrap() was called).
BaseApp.IsCollectionNameUnique
func (app *BaseApp) IsCollectionNameUnique(name string, excludeIds ...string) bool
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 table name for the records.
BaseApp.IsDev
func (app *BaseApp) IsDev() bool
IsDev returns whether the app is in dev mode.
When enabled logs, executed sql statements, etc. are printed to the stderr.
BaseApp.IsTransactional
func (app *BaseApp) IsTransactional() bool
IsTransactional checks if the current app instance is part of a transaction.
BaseApp.LogQuery
func (app *BaseApp) LogQuery() *dbx.SelectQuery
LogQuery returns a new Log select query.
BaseApp.Logger
func (app *BaseApp) Logger() *slog.Logger
Logger returns the default app logger.
If the application is not bootstrapped yet, fallbacks to slog.Default().
BaseApp.LogsStats
func (app *BaseApp) LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error)
LogsStats returns hourly grouped logs statistics.
BaseApp.ModelQuery
func (app *BaseApp) ModelQuery(m Model) *dbx.SelectQuery
ModelQuery creates a new preconfigured select data.db query with preset SELECT, FROM and other common fields based on the provided model.
BaseApp.NewBackupsFilesystem
func (app *BaseApp) NewBackupsFilesystem() (*filesystem.System, error)
NewBackupsFilesystem creates a new local or S3 filesystem instance for managing app backups based on the current app settings.
NB! Make sure to call Close() on the returned result after you are done working with it.
BaseApp.NewFilesystem
func (app *BaseApp) NewFilesystem() (fsys *filesystem.System, err error)
NewFilesystem creates a new local or S3 filesystem instance for managing regular app files (ex. record uploads) based on the current app settings.
NB! Make sure to call Close() on the returned result after you are done working with it.
BaseApp.NewMailClient
func (app *BaseApp) NewMailClient() mailer.Mailer
NewMailClient creates and returns a new SMTP or Sendmail client based on the current app settings.
BaseApp.NonconcurrentDB
func (app *BaseApp) NonconcurrentDB() dbx.Builder
NonconcurrentDB returns the nonconcurrent app data.db builder instance.
The returned db instance is limited only to a single open connection, meaning that it can process only 1 db operation at a time (other queries queue up).
This method is used mainly internally and in the tests to execute write (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
Most users should use simply DB() as it will automatically route the query execution to ConcurrentDB() or NonconcurrentDB().
In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
BaseApp.OnBackupCreate
func (app *BaseApp) OnBackupCreate() *hook.Hook[*BackupEvent]
BaseApp.OnBackupRestore
func (app *BaseApp) OnBackupRestore() *hook.Hook[*BackupEvent]
BaseApp.OnBatchRequest
func (app *BaseApp) OnBatchRequest() *hook.Hook[*BatchRequestEvent]
BaseApp.OnBootstrap
func (app *BaseApp) OnBootstrap() *hook.Hook[*BootstrapEvent]
BaseApp.OnBootstrapClear
func (app *BaseApp) OnBootstrapClear() *hook.Hook[*BootstrapEvent]
BaseApp.OnCollectionAfterCreateError
func (app *BaseApp) OnCollectionAfterCreateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
BaseApp.OnCollectionAfterCreateSuccess
func (app *BaseApp) OnCollectionAfterCreateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionAfterDeleteError
func (app *BaseApp) OnCollectionAfterDeleteError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
BaseApp.OnCollectionAfterDeleteSuccess
func (app *BaseApp) OnCollectionAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionAfterUpdateError
func (app *BaseApp) OnCollectionAfterUpdateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
BaseApp.OnCollectionAfterUpdateSuccess
func (app *BaseApp) OnCollectionAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionCreate
func (app *BaseApp) OnCollectionCreate(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionCreateExecute
func (app *BaseApp) OnCollectionCreateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionCreateRequest
func (app *BaseApp) OnCollectionCreateRequest() *hook.Hook[*CollectionRequestEvent]
BaseApp.OnCollectionDelete
func (app *BaseApp) OnCollectionDelete(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionDeleteExecute
func (app *BaseApp) OnCollectionDeleteExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionDeleteRequest
func (app *BaseApp) OnCollectionDeleteRequest() *hook.Hook[*CollectionRequestEvent]
BaseApp.OnCollectionUpdate
func (app *BaseApp) OnCollectionUpdate(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionUpdateExecute
func (app *BaseApp) OnCollectionUpdateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionUpdateRequest
func (app *BaseApp) OnCollectionUpdateRequest() *hook.Hook[*CollectionRequestEvent]
BaseApp.OnCollectionValidate
func (app *BaseApp) OnCollectionValidate(tags ...string) *hook.TaggedHook[*CollectionEvent]
BaseApp.OnCollectionViewRequest
func (app *BaseApp) OnCollectionViewRequest() *hook.Hook[*CollectionRequestEvent]
BaseApp.OnCollectionsImportRequest
func (app *BaseApp) OnCollectionsImportRequest() *hook.Hook[*CollectionsImportRequestEvent]
BaseApp.OnCollectionsListRequest
func (app *BaseApp) OnCollectionsListRequest() *hook.Hook[*CollectionsListRequestEvent]
BaseApp.OnFileDownloadRequest
func (app *BaseApp) OnFileDownloadRequest(tags ...string) *hook.TaggedHook[*FileDownloadRequestEvent]
BaseApp.OnFileTokenRequest
func (app *BaseApp) OnFileTokenRequest(tags ...string) *hook.TaggedHook[*FileTokenRequestEvent]
BaseApp.OnFilesystemCreate
func (app *BaseApp) OnFilesystemCreate() *hook.Hook[*FilesystemCreateEvent]
PocketOne: see App.OnFilesystemCreate.
BaseApp.OnMailerRecordAuthAlertSend
func (app *BaseApp) OnMailerRecordAuthAlertSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
BaseApp.OnMailerRecordEmailChangeSend
func (app *BaseApp) OnMailerRecordEmailChangeSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
BaseApp.OnMailerRecordOTPSend
func (app *BaseApp) OnMailerRecordOTPSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
BaseApp.OnMailerRecordPasswordResetSend
func (app *BaseApp) OnMailerRecordPasswordResetSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
BaseApp.OnMailerRecordVerificationSend
func (app *BaseApp) OnMailerRecordVerificationSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
BaseApp.OnMailerSend
func (app *BaseApp) OnMailerSend() *hook.Hook[*MailerEvent]
BaseApp.OnModelAfterCreateError
func (app *BaseApp) OnModelAfterCreateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
BaseApp.OnModelAfterCreateSuccess
func (app *BaseApp) OnModelAfterCreateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelAfterDeleteError
func (app *BaseApp) OnModelAfterDeleteError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
BaseApp.OnModelAfterDeleteSuccess
func (app *BaseApp) OnModelAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelAfterUpdateError
func (app *BaseApp) OnModelAfterUpdateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
BaseApp.OnModelAfterUpdateSuccess
func (app *BaseApp) OnModelAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelCreate
func (app *BaseApp) OnModelCreate(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelCreateExecute
func (app *BaseApp) OnModelCreateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelDelete
func (app *BaseApp) OnModelDelete(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelDeleteExecute
func (app *BaseApp) OnModelDeleteExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelUpdate
func (app *BaseApp) OnModelUpdate(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelUpdateExecute
func (app *BaseApp) OnModelUpdateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnModelValidate
func (app *BaseApp) OnModelValidate(tags ...string) *hook.TaggedHook[*ModelEvent]
BaseApp.OnRealtimeConnectRequest
func (app *BaseApp) OnRealtimeConnectRequest() *hook.Hook[*RealtimeConnectRequestEvent]
BaseApp.OnRealtimeMessageSend
func (app *BaseApp) OnRealtimeMessageSend() *hook.Hook[*RealtimeMessageEvent]
BaseApp.OnRealtimeSubscribeRequest
func (app *BaseApp) OnRealtimeSubscribeRequest() *hook.Hook[*RealtimeSubscribeRequestEvent]
BaseApp.OnRecordAfterCreateError
func (app *BaseApp) OnRecordAfterCreateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
BaseApp.OnRecordAfterCreateSuccess
func (app *BaseApp) OnRecordAfterCreateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordAfterDeleteError
func (app *BaseApp) OnRecordAfterDeleteError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
BaseApp.OnRecordAfterDeleteSuccess
func (app *BaseApp) OnRecordAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordAfterUpdateError
func (app *BaseApp) OnRecordAfterUpdateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
BaseApp.OnRecordAfterUpdateSuccess
func (app *BaseApp) OnRecordAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordAuthRefreshRequest
func (app *BaseApp) OnRecordAuthRefreshRequest(tags ...string) *hook.TaggedHook[*RecordAuthRefreshRequestEvent]
BaseApp.OnRecordAuthRequest
func (app *BaseApp) OnRecordAuthRequest(tags ...string) *hook.TaggedHook[*RecordAuthRequestEvent]
BaseApp.OnRecordAuthWithOAuth2Request
func (app *BaseApp) OnRecordAuthWithOAuth2Request(tags ...string) *hook.TaggedHook[*RecordAuthWithOAuth2RequestEvent]
BaseApp.OnRecordAuthWithOTPRequest
func (app *BaseApp) OnRecordAuthWithOTPRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithOTPRequestEvent]
BaseApp.OnRecordAuthWithPasswordRequest
func (app *BaseApp) OnRecordAuthWithPasswordRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithPasswordRequestEvent]
BaseApp.OnRecordConfirmEmailChangeRequest
func (app *BaseApp) OnRecordConfirmEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordConfirmEmailChangeRequestEvent]
BaseApp.OnRecordConfirmPasswordResetRequest
func (app *BaseApp) OnRecordConfirmPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordConfirmPasswordResetRequestEvent]
BaseApp.OnRecordConfirmVerificationRequest
func (app *BaseApp) OnRecordConfirmVerificationRequest(tags ...string) *hook.TaggedHook[*RecordConfirmVerificationRequestEvent]
BaseApp.OnRecordCreate
func (app *BaseApp) OnRecordCreate(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordCreateExecute
func (app *BaseApp) OnRecordCreateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordCreateRequest
func (app *BaseApp) OnRecordCreateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
BaseApp.OnRecordDelete
func (app *BaseApp) OnRecordDelete(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordDeleteExecute
func (app *BaseApp) OnRecordDeleteExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordDeleteRequest
func (app *BaseApp) OnRecordDeleteRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
BaseApp.OnRecordEnrich
func (app *BaseApp) OnRecordEnrich(tags ...string) *hook.TaggedHook[*RecordEnrichEvent]
BaseApp.OnRecordRequestEmailChangeRequest
func (app *BaseApp) OnRecordRequestEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordRequestEmailChangeRequestEvent]
BaseApp.OnRecordRequestOTPRequest
func (app *BaseApp) OnRecordRequestOTPRequest(tags ...string) *hook.TaggedHook[*RecordCreateOTPRequestEvent]
BaseApp.OnRecordRequestPasswordResetRequest
func (app *BaseApp) OnRecordRequestPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordRequestPasswordResetRequestEvent]
BaseApp.OnRecordRequestVerificationRequest
func (app *BaseApp) OnRecordRequestVerificationRequest(tags ...string) *hook.TaggedHook[*RecordRequestVerificationRequestEvent]
BaseApp.OnRecordUpdate
func (app *BaseApp) OnRecordUpdate(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordUpdateExecute
func (app *BaseApp) OnRecordUpdateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordUpdateRequest
func (app *BaseApp) OnRecordUpdateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
BaseApp.OnRecordValidate
func (app *BaseApp) OnRecordValidate(tags ...string) *hook.TaggedHook[*RecordEvent]
BaseApp.OnRecordViewRequest
func (app *BaseApp) OnRecordViewRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
BaseApp.OnRecordsListRequest
func (app *BaseApp) OnRecordsListRequest(tags ...string) *hook.TaggedHook[*RecordsListRequestEvent]
BaseApp.OnServe
func (app *BaseApp) OnServe() *hook.Hook[*ServeEvent]
BaseApp.OnSettingsListRequest
func (app *BaseApp) OnSettingsListRequest() *hook.Hook[*SettingsListRequestEvent]
BaseApp.OnSettingsReload
func (app *BaseApp) OnSettingsReload() *hook.Hook[*SettingsReloadEvent]
BaseApp.OnSettingsUpdateRequest
func (app *BaseApp) OnSettingsUpdateRequest() *hook.Hook[*SettingsUpdateRequestEvent]
BaseApp.OnTerminate
func (app *BaseApp) OnTerminate() *hook.Hook[*TerminateEvent]
BaseApp.RecordQuery
func (app *BaseApp) RecordQuery(collectionModelOrIdentifier any) *dbx.SelectQuery
RecordQuery returns a new Record select query from a collection model, id or name.
In case a collection id or name is provided and that collection doesn't actually exists, the generated query will be created with a cancelled context and will fail once an executor (Row(), One(), All(), etc.) is called.
BaseApp.ReloadCachedCollections
func (app *BaseApp) ReloadCachedCollections() error
ReloadCachedCollections fetches all collections and caches them into the app store.
BaseApp.ReloadSettings
func (app *BaseApp) ReloadSettings() error
ReloadSettings initializes and reloads the stored application settings.
If no settings were stored it will persist the current app ones.
BaseApp.ResetBootstrapState
func (app *BaseApp) ResetBootstrapState() error
Deprecated: use [ClearBootstrap].
BaseApp.Restart
func (app *BaseApp) Restart() error
Restart restarts (aka. replaces) the current running application process.
NB! It relies on execve which is supported only on UNIX based systems.
BaseApp.RestoreBackup
func (app *BaseApp) RestoreBackup(name string) error
RestoreBackup restores the backup with the specified name and restarts the current running application process.
NB! This feature is experimental and currently is expected to work only on UNIX based systems.
To safely perform the restore it is recommended to have free disk space for at least 2x the size of the restored pb_data backup.
The performed steps are:
-
Download the backup with the specified name in a temp location (this is in case of S3; otherwise it creates a temp copy of the zip)
-
Extract the backup in a temp directory inside the app "pb_data" (eg. "pb_data/.pb_temp_to_delete/pb_restore").
-
Move the current app "pb_data" content (excluding the local backups and the special temp dir) under another temp sub dir that will be deleted on the next app start up (eg. "pb_data/.pb_temp_to_delete/old_pb_data"). This is because on some environments it may not be allowed to delete the currently open "pb_data" files.
-
Move the extracted dir content to the app "pb_data".
-
Restart the app (on successful app bootstrap it will also remove the old pb_data).
If a failure occur during the restore process the dir changes are reverted. If for whatever reason the revert is not possible, it panics.
Note that if your pb_data has custom network mounts as subdirectories, then it is possible the restore to fail during the `os.Rename` operations (see https://ganigeorgiev.com/pocketbase/discussions/4647).
BaseApp.RunAllMigrations
func (app *BaseApp) RunAllMigrations() error
RunAllMigrations applies all system and app migrations (aka. from both core.SystemMigrations and core.AppMigrations; PocketOne: or the app's own list, see AppMigrationsOf).
BaseApp.RunAppMigrations
func (app *BaseApp) RunAppMigrations() error
RunAppMigrations applies all new migrations registered in the core.AppMigrations list (PocketOne: or the app's own list, see AppMigrationsOf).
BaseApp.RunInTransaction
func (app *BaseApp) RunInTransaction(fn func(txApp App) error) error
RunInTransaction wraps fn into a transaction for the regular app database.
It is safe to nest RunInTransaction calls as long as you use the callback's txApp.
BaseApp.RunSystemMigrations
func (app *BaseApp) RunSystemMigrations() error
RunSystemMigrations applies all new migrations registered in the core.SystemMigrations list.
BaseApp.Save
func (app *BaseApp) Save(model Model) error
Save validates and saves the specified model into the regular app database.
If you don't want to run validations, use [App.SaveNoValidate()].
BaseApp.SaveNoValidate
func (app *BaseApp) SaveNoValidate(model Model) error
SaveNoValidate saves the specified model into the regular app database without performing validations.
If you want to also run validations before persisting, use [App.Save()].
BaseApp.SaveView
func (app *BaseApp) SaveView(dangerousViewName string, dangerousSelectQuery string) error
SaveView creates (or updates already existing) persistent SQL view.
NB! Be aware that this method is vulnerable to SQL injection and its arguments must come only from trusted input!
BaseApp.Settings
func (app *BaseApp) Settings() *Settings
Settings returns the loaded app settings.
BaseApp.Store
func (app *BaseApp) Store() *store.Store[string, any]
Store returns the app runtime store.
BaseApp.SubscriptionsBroker
func (app *BaseApp) SubscriptionsBroker() *subscriptions.Broker
SubscriptionsBroker returns the app realtime subscriptions broker instance.
BaseApp.SyncRecordTableSchema
func (app *BaseApp) SyncRecordTableSchema(newCollection *Collection, oldCollection *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.
This method is automatically invoked as part of a collection create/update/delete operation.
BaseApp.TableColumns
func (app *BaseApp) TableColumns(tableName string) ([]string, error)
TableColumns returns all column names of a single table by its name.
BaseApp.TableIndexes
func (app *BaseApp) TableIndexes(tableName string) (map[string]string, error)
TableIndexes returns a name grouped map with all non empty index of the specified table.
Note: This method doesn't return an error on nonexisting table.
BaseApp.TableInfo
func (app *BaseApp) TableInfo(tableName string) ([]*TableInfoRow, error)
TableInfo returns the "table_info" pragma result for the specified table.
BaseApp.TruncateCollection
func (app *BaseApp) TruncateCollection(collection *Collection) error
TruncateCollection deletes all records associated with the provided collection.
The truncate operation is executed in a single transaction, aka. either everything is deleted or none.
Note that this method will also trigger the records related cascade and file delete actions.
BaseApp.TxInfo
func (app *BaseApp) TxInfo() *TxAppInfo
TxInfo returns the transaction associated with the current app instance (if any).
Could be used if you want to execute indirectly a function after the related app transaction completes using `app.TxInfo().OnAfterFunc(callback)`.
BaseApp.UnsafeWithoutHooks
func (app *BaseApp) UnsafeWithoutHooks() App
UnsafeWithoutHooks returns a shallow copy of the current app WITHOUT any registered hooks.
NB! Note that using the returned app instance may cause data integrity errors since the Record validations and data normalization (including files uploads) rely on the app hooks to work.
BaseApp.Vacuum
func (app *BaseApp) Vacuum() error
Vacuum executes VACUUM on the data.db in order to reclaim unused data db disk space.
BaseApp.Validate
func (app *BaseApp) Validate(model Model) error
Validate triggers the OnModelValidate hook for the specified model.
BaseApp.WithContext
func (app *BaseApp) WithContext(ctx context.Context) App
WithContext creates a new shallow copy of the current app with its context set to the given one.
WithContext is often used to customize the default timeouts and/or group the execution duration of DB queries, transactions and any other app related operation.
Keep in mind that this context will be used by all queries executed by the new app instance meaning that technically you can provide a context.Background() for no limits. Be careful with that!
For example:
ctx, cancel := context.WithTimeout(app.Context(), 5*time.Second)
defer cancel()
ctxApp := app.WithContext(ctx)
// run your queries using the newly created ctxApp
// (in the below example both the Find and Save operations share the same context)
record, err := ctxApp.FindRecordById("example", "123")
record.Set("name", "abc")
err = ctxApp.Save(record)
DBConnectFunc
type DBConnectFunc func(dbPath string) (*dbx.DB, error)
DBConnectFunc defines a database connection initialization function.
DBExporter
type DBExporter interface {
// DBExport returns a key-value map with the data to be used when saving the struct in the database.
DBExport(app App) (map[string]any, error)
}
DBExporter defines an interface for custom DB data export. Usually used as part of App.Save.
DriverValuer
type DriverValuer interface {
// DriverValue exports a single field value for persistence in the database.
DriverValue(record *Record) (driver.Value, error)
}
DriverValuer defines a Field interface for exporting and formatting a field value for the database.
DryRunViewResult
type DryRunViewResult struct {
Fields FieldsList `json:"fields"`
Sample []*Record `json:"sample"`
}
EmailTemplate
type EmailTemplate struct {
Subject string `form:"subject" json:"subject"`
Body string `form:"body" json:"body"`
}
EmailTemplate.Resolve
func (t EmailTemplate) Resolve(placeholders map[string]any) (subject, body string)
Resolve replaces the placeholder parameters in the current email template and returns its components as ready-to-use strings.
EmailTemplate.Validate
func (t EmailTemplate) Validate() error
Validate makes EmailTemplate validatable by implementing validation.Validatable interface.
ExpandFetchFunc
type ExpandFetchFunc func(relCollection *Collection, relIds []string) ([]*Record, error)
ExpandFetchFunc defines the function that is used to fetch the expanded relation records.
FilesManager
type FilesManager interface {
// BaseFilesPath returns the storage dir path used by the interface instance.
BaseFilesPath() string
}
FilesManager defines an interface with common methods that files manager models should implement.
GetterFinder
type GetterFinder interface {
// FindGetter returns a single field value getter function
// by performing pattern-like field matching using the specified key.
//
// The key is usually just the field name but it could also
// contains "modifier" characters based on which you can perform custom get operations
// (ex. "description:excerpt" could be mapped to a function that will return an excerpt of the current field value).
//
// Return nil if you want to fallback to the default field value setter.
FindGetter(key string) GetterFunc
}
GetterFinder defines a field interface for registering custom field value getters.
GetterFunc
type GetterFunc func(record *Record) any
HookTagger
type HookTagger interface {
HookTags() []string
}
InternalRequest
type InternalRequest struct {
// note: for uploading files the value must be either *filesystem.File or []*filesystem.File
Body map[string]any `form:"body" json:"body"`
Headers map[string]string `form:"headers" json:"headers"`
Method string `form:"method" json:"method"`
URL string `form:"url" json:"url"`
}
InternalRequest.Validate
func (br InternalRequest) Validate() error
MaxBodySizeCalculator
type MaxBodySizeCalculator interface {
// CalculateMaxBodySize returns the approximate max body size of a field value.
CalculateMaxBodySize() int64
}
MaxBodySizeCalculator defines an optional field interface for specifying the max size of a field value.
Migration
type Migration struct {
Up func(txApp App) error
Down func(txApp App) error
File string
ReapplyCondition func(txApp App, runner *MigrationsRunner, fileName string) (bool, error)
}
MigrationsList
type MigrationsList struct {
// contains filtered or unexported fields
}
MigrationsList defines a list with migration definitions
var AppMigrations MigrationsList
var SystemMigrations MigrationsList
AppMigrationsOf
func AppMigrationsOf(app App) *MigrationsList
PocketOne: AppMigrationsOf returns the app's own migrations list (BaseAppConfig.AppMigrations) when it has one, otherwise the global AppMigrations. Register and run app migrations through it so each app in a shared process keeps its own.
MigrationsList.Add
func (l *MigrationsList) Add(m *Migration)
Add adds adds an existing migration definition to the list.
If m.File is not provided, it will try to get the name from its .go file.
The list will be sorted automatically based on the migrations file name.
MigrationsList.Copy
func (l *MigrationsList) Copy(list MigrationsList)
Copy copies all provided list migrations into the current one.
MigrationsList.Item
func (l *MigrationsList) Item(index int) *Migration
Item returns a single migration from the list by its index.
MigrationsList.Items
func (l *MigrationsList) Items() []*Migration
Items returns the internal migrations list slice.
MigrationsList.Register
func (l *MigrationsList) Register(
up func(txApp App) error,
down func(txApp App) error,
optFilename ...string,
)
Register adds new migration definition to the list.
If optFilename is not provided, it will try to get the name from its .go file.
The list will be sorted automatically based on the migrations file name.
MigrationsRunner
type MigrationsRunner struct {
// contains filtered or unexported fields
}
MigrationsRunner defines a simple struct for managing the execution of db migrations.
NewMigrationsRunner
func NewMigrationsRunner(app App, migrationsList MigrationsList) *MigrationsRunner
NewMigrationsRunner creates and initializes a new db migrations MigrationsRunner instance.
MigrationsRunner.Down
func (r *MigrationsRunner) Down(toRevertCount int) ([]string, error)
Down reverts the last `toRevertCount` applied migrations (in the order they were applied).
On success returns list with the reverted migrations file names.
MigrationsRunner.RemoveMissingAppliedMigrations
func (r *MigrationsRunner) RemoveMissingAppliedMigrations() error
RemoveMissingAppliedMigrations removes the db entries of all applied migrations that are not listed in the runner's migrations list.
MigrationsRunner.Run
func (r *MigrationsRunner) Run(args ...string) error
Run interactively executes the current runner with the provided args.
The following commands are supported: - up - applies all migrations - down [n] - reverts the last n (default 1) applied migrations - history-sync - syncs the migrations table with the runner's migrations list
MigrationsRunner.Up
func (r *MigrationsRunner) Up() ([]string, error)
Up executes all unapplied migrations for the provided runner.
On success returns list with the applied migrations file names.
MultiValuer
type MultiValuer interface {
// IsMultiple checks whether the field is configured to support multiple or single values.
IsMultiple() bool
}
MultiValuer defines a field interface that every multi-valued (eg. with MaxSelect) field has.
OAuth2KnownFields
type OAuth2KnownFields struct {
Id string `form:"id" json:"id"`
Name string `form:"name" json:"name"`
Username string `form:"username" json:"username"`
AvatarURL string `form:"avatarURL" json:"avatarURL"`
}
PasswordFieldValue
type PasswordFieldValue struct {
LastError error
Hash string
Plain string
}
PasswordFieldValue.Validate
func (pv PasswordFieldValue) Validate(pass string) bool
PostValidator
type PostValidator interface {
// PostValidate defines a function that runs AFTER the successful
// execution of the validation hooks.
PostValidate(app App) error
}
PostValidator defines an optional model interface for registering a function that will run AFTER executing the validation hooks (see App.Validate).
PreValidator
type PreValidator interface {
// PreValidate defines a function that runs BEFORE the validation hooks.
PreValidate(app App) error
}
PreValidator defines an optional model interface for registering a function that will run BEFORE firing the validation hooks (see App.Validate).
RateLimitRule
type RateLimitRule struct {
// Label is the identifier of the current rule.
//
// It could be a tag, complete path or path prerefix (when ends with `/`).
//
// Example supported labels:
// - test_a (plain text "tag")
// - users:create
// - *:create
// - /
// - /api
// - POST /api/collections/
Label string `form:"label" json:"label"`
// Audience specifies the auth group the rule should apply for:
// - "" - both guests and authenticated users (default)
// - "@guest" - only for guests
// - "@auth" - only for authenticated users
Audience string `form:"audience" json:"audience"`
// Duration specifies the interval (in seconds) per which to reset
// the counted/accumulated rate limiter tokens.
Duration int64 `form:"duration" json:"duration"`
// MaxRequests is the max allowed number of requests per Duration.
MaxRequests int `form:"maxRequests" json:"maxRequests"`
}
RateLimitRule.DurationTime
func (c RateLimitRule) DurationTime() time.Duration
DurationTime returns the tag's Duration as time.Duration.
RateLimitRule.String
func (c RateLimitRule) String() string
String returns a string representation of the rule.
RateLimitRule.Validate
func (c RateLimitRule) Validate() error
Validate makes RateLimitRule validatable by implementing validation.Validatable interface.
RequestInfo
type RequestInfo struct {
Query map[string]string `json:"query"`
Headers map[string]string `json:"headers"`
Body map[string]any `json:"body"`
Auth *Record `json:"auth"`
Method string `json:"method"`
Context string `json:"context"`
}
RequestInfo defines a HTTP request data struct, usually used as part of the `@request.*` filter resolver.
The Query and Headers fields contains only the first value for each found entry.
RequestInfo.Clone
func (info *RequestInfo) Clone() *RequestInfo
Clone creates a new shallow copy of the current RequestInfo and its Auth record (if any).
RequestInfo.HasSuperuserAuth
func (info *RequestInfo) HasSuperuserAuth() bool
HasSuperuserAuth checks whether the current RequestInfo instance has superuser authentication loaded.
SetterFinder
type SetterFinder interface {
// FindSetter returns a single field value setter function
// by performing pattern-like field matching using the specified key.
//
// The key is usually just the field name but it could also
// contains "modifier" characters based on which you can perform custom set operations
// (ex. "users+" could be mapped to a function that will append new user to the existing field value).
//
// Return nil if you want to fallback to the default field value setter.
FindSetter(key string) SetterFunc
}
SetterFinder defines a field interface for registering custom field value setters.
SetterFunc
type SetterFunc func(record *Record, raw any)
TableInfoRow
type TableInfoRow struct {
// the `db:"pk"` tag has special semantic so we cannot rename
// the original field without specifying a custom mapper
PK int
Index int `db:"cid"`
Name string `db:"name"`
Type string `db:"type"`
NotNull bool `db:"notnull"`
DefaultValue sql.NullString `db:"dflt_value"`
}
TxAppInfo
type TxAppInfo struct {
// contains filtered or unexported fields
}
TxAppInfo represents an active transaction context associated to an existing app instance.
TxAppInfo.OnComplete
func (a *TxAppInfo) OnComplete(fn func(txErr error) error)
OnComplete registers the provided callback that will be invoked once the related transaction ends (either completes successfully or rollbacked with an error).
The callback receives the transaction error (if any) as its argument. Any additional errors returned by the OnComplete callbacks will be joined together with txErr when returning the final transaction result.
UIExtension
type UIExtension struct {
// Name is the name of the extension.
// It is also used as path segment for the registered public extension endpoint
// (e.g. /_/extensions/{name}/*)
Name string
// FS is the extension file system.
FS fs.FS
}
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.