core

package
v0.23.4 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2024 License: MIT Imports: 59 Imported by: 435

Documentation

Overview

Package core is the backbone of PocketBase.

It defines the main PocketBase App interface and its base implementation.

Index

Constants

View Source
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"
	LocalTempDirName          string = ".pb_temp_to_delete" // temp pb_data sub directory that will be deleted on each app.Bootstrap()
	LocalAutocertCacheDirName string = ".autocert_cache"
)
View Source
const (
	CollectionTypeBase = "base"
	CollectionTypeAuth = "auth"
	CollectionTypeView = "view"
)
View Source
const (
	EmailPlaceholderAppName string = "{APP_NAME}"
	EmailPlaceholderAppURL  string = "{APP_URL}"
	EmailPlaceholderToken   string = "{TOKEN}"
	EmailPlaceholderOTP     string = "{OTP}"
	EmailPlaceholderOTPId   string = "{OTP_ID}"
)

Common settings placeholder tokens

View Source
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"
)
View Source
const (
	RequestInfoContextDefault       = "default"
	RequestInfoContextExpand        = "expand"
	RequestInfoContextRealtime      = "realtime"
	RequestInfoContextProtectedFile = "protectedFile"
	RequestInfoContextOAuth2        = "oauth2"
	RequestInfoContextBatch         = "batch"
)
View Source
const (
	ModelEventTypeCreate   = "create"
	ModelEventTypeUpdate   = "update"
	ModelEventTypeDelete   = "delete"
	ModelEventTypeValidate = "validate"
)
View Source
const (
	FieldNameId              = "id"
	FieldNameCollectionId    = "collectionId"
	FieldNameCollectionName  = "collectionName"
	FieldNameExpand          = "expand"
	FieldNameEmail           = "email"
	FieldNameEmailVisibility = "emailVisibility"
	FieldNameVerified        = "verified"
	FieldNameTokenKey        = "tokenKey"
	FieldNamePassword        = "password"
)

Commonly used field names.

View Source
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.

View Source
const (
	MFAMethodPassword = "password"
	MFAMethodOAuth2   = "oauth2"
	MFAMethodOTP      = "otp"
)
View Source
const (
	TokenTypeAuth          = "auth"
	TokenTypeFile          = "file"
	TokenTypeVerification  = "verification"
	TokenTypePasswordReset = "passwordReset"
	TokenTypeEmailChange   = "emailChange"
)

Supported record token types

View Source
const (
	TokenClaimId           = "id"
	TokenClaimType         = "type"
	TokenClaimCollectionId = "collectionId"
	TokenClaimEmail        = "email"
	TokenClaimNewEmail     = "newEmail"
	TokenClaimRefreshable  = "refreshable"
)

List with commonly used record token claims

View Source
const (
	RateLimitRuleAudienceAll   = ""
	RateLimitRuleAudienceGuest = "@guest"
	RateLimitRuleAudienceAuth  = "@auth"
)

The allowed RateLimitRule.Audience values

View Source
const CollectionNameAuthOrigins = "_authOrigins"
View Source
const CollectionNameExternalAuths = "_externalAuths"
View Source
const CollectionNameMFAs = "_mfas"
View Source
const CollectionNameOTPs = "_otps"
View Source
const CollectionNameSuperusers = "_superusers"
View Source
const DefaultEditorFieldMaxSize int64 = 5 << 20
View Source
const DefaultFileFieldMaxSize int64 = 5 << 20
View Source
const DefaultInstallerEmail = "__pbinstaller@example.com"

DefaultInstallerEmail is the default superuser email address for the initial autogenerated superuser account.

View Source
const DefaultJSONFieldMaxSize int64 = 5 << 20
View Source
const DefaultMigrationsTable = "_migrations"
View Source
const FieldTypeAutodate = "autodate"
View Source
const FieldTypeBool = "bool"
View Source
const FieldTypeDate = "date"
View Source
const FieldTypeEditor = "editor"
View Source
const FieldTypeEmail = "email"
View Source
const FieldTypeFile = "file"
View Source
const FieldTypeJSON = "json"
View Source
const FieldTypeNumber = "number"
View Source
const FieldTypePassword = "password"
View Source
const FieldTypeRelation = "relation"
View Source
const FieldTypeSelect = "select"
View Source
const FieldTypeText = "text"
View Source
const FieldTypeURL = "url"
View Source
const LogsTableName = "_logs"
View Source
const (
	RequestEventKeyInfoContext = "infoContext"
)

Common request store keys used by the middlewares and api handlers.

View Source
const (
	StoreKeyActiveBackup = "@activeBackup"
)
View Source
const StoreKeyCachedCollections = "pbAppCachedCollections"

Variables

View Source
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.

View Source
var (
	ErrNotAuthRecord     = errors.New("not an auth collection record")
	ErrMissingSigningKey = errors.New("missing or invalid signing key")
)

Common token related errors

View Source
var DefaultIdRegex = regexp.MustCompile(`^\w+$`)

DefaultIdRegex specifies the default regex pattern for an id value.

View Source
var Fields = map[string]FieldFactoryFunc{}

Fields holds all available collection fields.

SystemFields returns special internal field names that are usually readonly.

Functions

func DefaultDBConnect added in v0.23.0

func DefaultDBConnect(dbPath string) (*dbx.DB, error)

func DefaultFieldIdValidationRule added in v0.23.0

func DefaultFieldIdValidationRule(value any) error

DefaultFieldIdValidationRule performs base validation on a field id value.

func DefaultFieldNameValidationRule added in v0.23.0

func DefaultFieldNameValidationRule(value any) error

DefaultFieldIdValidationRule performs base validation on a field name value.

func GenerateDefaultRandomId added in v0.23.0

func GenerateDefaultRandomId() string

GenerateDefaultRandomId generates a default random id string (note: the generated random string is not intended for security purposes).

Types

type 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 normalizations (including files uploads)
	// rely on the app hooks to work.
	UnsafeWithoutHooks() App

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

	// Bootstrap initializes the application
	// (aka. create data dir, open db connections, load settings, etc.).
	//
	// It will call ResetBootstrapState() if the application was already bootstrapped.
	Bootstrap() error

	// ResetBootstrapState releases the initialized core app resources
	// (closing db connections, stopping cron ticker, etc.).
	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[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)

	// NewFilesystem 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(ctx context.Context, 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(ctx context.Context, 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 instance (pb_data/data.db).
	DB() dbx.Builder

	// NonconcurrentDB returns the nonconcurrent app data db instance (pb_data/data.db).
	//
	// 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 operations will be queued 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.
	//
	// For the majority of cases you would want to use the regular DB() method
	// since it allows concurrent db read operations.
	//
	// In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
	NonconcurrentDB() dbx.Builder

	// AuxDB returns the default app auxiliary db instance (pb_data/auxiliary.db).
	AuxDB() dbx.Builder

	// AuxNonconcurrentDB returns the nonconcurrent app auxiliary db instance (pb_data/auxiliary.db)..
	//
	// 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 operations will be queued 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.
	//
	// For the majority of cases you would want to use the regular DB() method
	// since it allows concurrent db read operations.
	//
	// In a transaction the AuxNonconcurrentDB() 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 current app.DB() instance.
	HasTable(tableName string) bool

	// AuxHasTable checks if a table (or view) with the provided name exists (case insensitive)
	// in the current app.AuxDB() instance.
	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
	// "tableName" argument must come only from trusted input!
	DeleteTable(tableName 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
	// "name" argument must come only from trusted input!
	DeleteView(name string) error

	// SaveView creates (or updates already existing) persistent SQL view.
	//
	// NB! Be aware that this method is vulnerable to SQL injection and the
	// "selectQuery" argument must come only from trusted input!
	SaveView(name string, selectQuery 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.
	CreateViewFields(selectQuery string) (FieldsList, 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 current app.DB() instance
	// in order to reclaim unused data db disk space.
	Vacuum() error

	// AuxVacuum executes VACUUM on the current app.AuxDB() instance
	// in order to reclaim unused auxiliary db disk space.
	AuxVacuum() error

	// ModelQuery creates a new preconfigured select app.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 app.AuxDB() 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

	// Delete deletes the specified model from the regular app database
	// (the context could be used to limit the query execution).
	DeleteWithContext(ctx context.Context, model Model) error

	// AuxDelete deletes the specified model from the auxiliary database.
	AuxDelete(model Model) error

	// AuxDeleteWithContext deletes the specified model from the auxiliary database
	// (the context could be used to limit the query execution).
	AuxDeleteWithContext(ctx context.Context, 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

	// SaveWithContext is the same as [App.Save()] but allows specifying a context to limit the db execution.
	//
	// If you don't want to run validations, use [App.SaveNoValidateWithContext()].
	SaveWithContext(ctx context.Context, 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

	// SaveNoValidateWithContext is the same as [App.SaveNoValidate()]
	// but allows specifying a context to limit the db execution.
	//
	// If you want to also run validations before persisting, use [App.SaveWithContext()].
	SaveNoValidateWithContext(ctx context.Context, 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

	// AuxSaveWithContext is the same as [App.AuxSave()] but allows specifying a context to limit the db execution.
	//
	// If you don't want to run validations, use [App.AuxSaveNoValidateWithContext()].
	AuxSaveWithContext(ctx context.Context, 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

	// AuxSaveNoValidateWithContext is the same as [App.AuxSaveNoValidate()]
	// but allows specifying a context to limit the db execution.
	//
	// If you want to also run validations before persisting, use [App.AuxSaveWithContext()].
	AuxSaveNoValidateWithContext(ctx context.Context, model Model) error

	// Validate triggers the OnModelValidate hook for the specified model.
	Validate(model Model) error

	// ValidateWithContext is the same as Validate but allows specifying the ModelEvent context.
	ValidateWithContext(ctx context.Context, 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 defines the total number of logs for a specific time period.
	LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error)

	// DeleteOldLogs delete all requests 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)

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

	// 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)

	// 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)

	// 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": "test@example.com"}
	//	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]

	// 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 send 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]

	// 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]
}

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).

type AuthAlertConfig added in v0.23.0

type AuthAlertConfig struct {
	Enabled       bool          `form:"enabled" json:"enabled"`
	EmailTemplate EmailTemplate `form:"emailTemplate" json:"emailTemplate"`
}

func (AuthAlertConfig) Validate added in v0.23.0

func (c AuthAlertConfig) Validate() error

Validate makes AuthAlertConfig validatable by implementing validation.Validatable interface.

type AuthOrigin added in v0.23.0

type AuthOrigin struct {
	*Record
}

AuthOrigin defines a Record proxy for working with the authOrigins collection.

func NewAuthOrigin added in v0.23.0

func NewAuthOrigin(app App) *AuthOrigin

NewAuthOrigin instantiates and returns a new blank *AuthOrigin model.

Example usage:

origin := core.NewOrigin(app)
origin.SetRecordRef(user.Id)
origin.SetCollectionRef(user.Collection().Id)
origin.SetFingerprint("...")
app.Save(origin)

func (*AuthOrigin) CollectionRef added in v0.23.0

func (m *AuthOrigin) CollectionRef() string

CollectionRef returns the "collectionRef" field value.

func (*AuthOrigin) Created added in v0.23.0

func (m *AuthOrigin) Created() types.DateTime

Created returns the "created" record field value.

func (*AuthOrigin) Fingerprint added in v0.23.0

func (m *AuthOrigin) Fingerprint() string

Fingerprint returns the "fingerprint" record field value.

func (*AuthOrigin) PreValidate added in v0.23.0

func (m *AuthOrigin) PreValidate(ctx context.Context, app App) error

PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.

func (*AuthOrigin) ProxyRecord added in v0.23.0

func (m *AuthOrigin) ProxyRecord() *Record

ProxyRecord returns the proxied Record model.

func (*AuthOrigin) RecordRef added in v0.23.0

func (m *AuthOrigin) RecordRef() string

RecordRef returns the "recordRef" record field value.

func (*AuthOrigin) SetCollectionRef added in v0.23.0

func (m *AuthOrigin) SetCollectionRef(collectionId string)

SetCollectionRef updates the "collectionRef" record field value.

func (*AuthOrigin) SetFingerprint added in v0.23.0

func (m *AuthOrigin) SetFingerprint(fingerprint string)

SetFingerprint updates the "fingerprint" record field value.

func (*AuthOrigin) SetProxyRecord added in v0.23.0

func (m *AuthOrigin) SetProxyRecord(record *Record)

SetProxyRecord loads the specified record model into the current proxy.

func (*AuthOrigin) SetRecordRef added in v0.23.0

func (m *AuthOrigin) SetRecordRef(recordId string)

SetRecordRef updates the "recordRef" record field value.

func (*AuthOrigin) Updated added in v0.23.0

func (m *AuthOrigin) Updated() types.DateTime

Updated returns the "updated" record field value.

type AutodateField added in v0.23.0

type AutodateField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// OnCreate auto sets the current datetime as field value on record create.
	OnCreate bool `form:"onCreate" json:"onCreate"`

	// OnUpdate auto sets the current datetime as field value on record update.
	OnUpdate bool `form:"onUpdate" json:"onUpdate"`
}

AutodateField defines an "autodate" type field, aka. field which datetime value could be auto set on record create/update.

This field is usually used for defining timestamp fields like "created" and "updated".

Requires either both or at least one of the OnCreate or OnUpdate options to be set.

func (*AutodateField) ColumnType added in v0.23.0

func (f *AutodateField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*AutodateField) FindSetter added in v0.23.0

func (f *AutodateField) FindSetter(key string) SetterFunc

FindSetter implements the SetterFinder interface.

func (*AutodateField) GetHidden added in v0.23.0

func (f *AutodateField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*AutodateField) GetId added in v0.23.0

func (f *AutodateField) GetId() string

GetId implements [Field.GetId] interface method.

func (*AutodateField) GetName added in v0.23.0

func (f *AutodateField) GetName() string

GetName implements [Field.GetName] interface method.

func (*AutodateField) GetSystem added in v0.23.0

func (f *AutodateField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*AutodateField) Intercept added in v0.23.0

func (f *AutodateField) Intercept(
	ctx context.Context,
	app App,
	record *Record,
	actionName string,
	actionFunc func() error,
) error

Intercept implements the RecordInterceptor interface.

func (*AutodateField) PrepareValue added in v0.23.0

func (f *AutodateField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*AutodateField) SetHidden added in v0.23.0

func (f *AutodateField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*AutodateField) SetId added in v0.23.0

func (f *AutodateField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*AutodateField) SetName added in v0.23.0

func (f *AutodateField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*AutodateField) SetSystem added in v0.23.0

func (f *AutodateField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*AutodateField) Type added in v0.23.0

func (f *AutodateField) Type() string

Type implements [Field.Type] interface method.

func (*AutodateField) ValidateSettings added in v0.23.0

func (f *AutodateField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*AutodateField) ValidateValue added in v0.23.0

func (f *AutodateField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type BackupEvent added in v0.23.0

type BackupEvent struct {
	hook.Event
	App     App
	Context context.Context
	Name    string   // the name of the backup to create/restore.
	Exclude []string // list of dir entries to exclude from the backup create/restore.
}

type BackupsConfig added in v0.23.0

type BackupsConfig struct {
	// Cron is a cron expression to schedule auto backups, eg. "* * * * *".
	//
	// Leave it empty to disable the auto backups functionality.
	Cron string `form:"cron" json:"cron"`

	// CronMaxKeep is the the max number of cron generated backups to
	// keep before removing older entries.
	//
	// This field works only when the cron config has valid cron expression.
	CronMaxKeep int `form:"cronMaxKeep" json:"cronMaxKeep"`

	// S3 is an optional S3 storage config specifying where to store the app backups.
	S3 S3Config `form:"s3" json:"s3"`
}

func (BackupsConfig) Validate added in v0.23.0

func (c BackupsConfig) Validate() error

Validate makes BackupsConfig validatable by implementing validation.Validatable interface.

type BaseApp

type BaseApp struct {
	// contains filtered or unexported fields
}

BaseApp implements core.App and defines the base PocketBase app structure.

func 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()`.

func (*BaseApp) AuxDB added in v0.23.0

func (app *BaseApp) AuxDB() dbx.Builder

AuxDB returns the default app auxiliary db instance (pb_data/auxiliary.db).

func (*BaseApp) AuxDelete added in v0.23.0

func (app *BaseApp) AuxDelete(model Model) error

AuxDelete deletes the specified model from the auxiliary database.

func (*BaseApp) AuxDeleteWithContext added in v0.23.0

func (app *BaseApp) AuxDeleteWithContext(ctx context.Context, model Model) error

AuxDeleteWithContext deletes the specified model from the auxiliary database (the context could be used to limit the query execution).

func (*BaseApp) AuxHasTable added in v0.23.0

func (app *BaseApp) AuxHasTable(tableName string) bool

AuxHasTable checks if a table (or view) with the provided name exists (case insensitive) in the current app.AuxDB() instance.

func (*BaseApp) AuxModelQuery added in v0.23.0

func (app *BaseApp) AuxModelQuery(m Model) *dbx.SelectQuery

AuxModelQuery creates a new preconfigured select app.AuxDB() query with preset SELECT, FROM and other common fields based on the provided model.

func (*BaseApp) AuxNonconcurrentDB added in v0.23.0

func (app *BaseApp) AuxNonconcurrentDB() dbx.Builder

AuxNonconcurrentDB returns the nonconcurrent app auxiliary db instance (pb_data/auxiliary.db).

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 operations will be queued 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.

For the majority of cases you would want to use the regular DB() method since it allows concurrent db read operations.

In a transaction the AuxNonconcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.

func (*BaseApp) AuxRunInTransaction added in v0.23.0

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.

func (*BaseApp) AuxSave added in v0.23.0

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()].

func (*BaseApp) AuxSaveNoValidate added in v0.23.0

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()].

func (*BaseApp) AuxSaveNoValidateWithContext added in v0.23.0

func (app *BaseApp) AuxSaveNoValidateWithContext(ctx context.Context, model Model) error

AuxSaveNoValidateWithContext is the same as [App.AuxSaveNoValidate()] but allows specifying a context to limit the db execution.

If you want to also run validations before persisting, use [App.AuxSaveWithContext()].

func (*BaseApp) AuxSaveWithContext added in v0.23.0

func (app *BaseApp) AuxSaveWithContext(ctx context.Context, model Model) error

AuxSaveWithContext is the same as [App.AuxSave()] but allows specifying a context to limit the db execution.

If you don't want to run validations, use [App.AuxSaveNoValidateWithContext()].

func (*BaseApp) AuxVacuum added in v0.23.0

func (app *BaseApp) AuxVacuum() error

AuxVacuum executes VACUUM on the current app.AuxDB() instance in order to reclaim unused auxiliary db disk space.

func (*BaseApp) Bootstrap

func (app *BaseApp) Bootstrap() error

Bootstrap initializes the application (aka. create data dir, open db connections, load settings, etc.).

It will call ResetBootstrapState() if the application was already bootstrapped.

func (*BaseApp) CanAccessRecord added in v0.23.0

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 { ... }

func (*BaseApp) CollectionQuery added in v0.23.0

func (app *BaseApp) CollectionQuery() *dbx.SelectQuery

CollectionQuery returns a new Collection select query.

func (*BaseApp) CountRecords added in v0.23.0

func (app *BaseApp) CountRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) (int64, error)

CountRecords returns the total number of records in a collection.

func (*BaseApp) CreateBackup added in v0.16.0

func (app *BaseApp) CreateBackup(ctx context.Context, 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.

The backup is executed within a transaction, meaning that new writes will be temporary "blocked" until the backup file is generated.

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).

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.

Backups can be stored on S3 if it is configured in app.Settings().Backups.

func (*BaseApp) CreateViewFields added in v0.23.0

func (app *BaseApp) CreateViewFields(selectQuery 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.

func (*BaseApp) Cron added in v0.23.0

func (app *BaseApp) Cron() *cron.Cron

Cron returns the app cron instance.

func (*BaseApp) DB

func (app *BaseApp) DB() dbx.Builder

DB returns the default app data db instance (pb_data/data.db).

func (*BaseApp) DataDir

func (app *BaseApp) DataDir() string

DataDir returns the app data directory path.

func (*BaseApp) Delete added in v0.23.0

func (app *BaseApp) Delete(model Model) error

Delete deletes the specified model from the regular app database.

func (*BaseApp) DeleteAllAuthOriginsByRecord added in v0.23.0

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.

func (*BaseApp) DeleteAllMFAsByRecord added in v0.23.0

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.

func (*BaseApp) DeleteAllOTPsByRecord added in v0.23.0

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.

func (*BaseApp) DeleteExpiredMFAs added in v0.23.0

func (app *BaseApp) DeleteExpiredMFAs() error

DeleteExpiredMFAs deletes the expired MFAs for all auth collections.

func (*BaseApp) DeleteExpiredOTPs added in v0.23.0

func (app *BaseApp) DeleteExpiredOTPs() error

DeleteExpiredOTPs deletes the expired OTPs for all auth collections.

func (*BaseApp) DeleteOldLogs added in v0.23.0

func (app *BaseApp) DeleteOldLogs(createdBefore time.Time) error

DeleteOldLogs delete all requests 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.

func (*BaseApp) DeleteTable added in v0.23.0

func (app *BaseApp) DeleteTable(tableName 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 "tableName" argument must come only from trusted input!

func (*BaseApp) DeleteView added in v0.23.0

func (app *BaseApp) DeleteView(name 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 "name" argument must come only from trusted input!

func (*BaseApp) DeleteWithContext added in v0.23.0

func (app *BaseApp) DeleteWithContext(ctx context.Context, model Model) error

Delete deletes the specified model from the regular app database (the context could be used to limit the query execution).

func (*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).

func (*BaseApp) ExpandRecord added in v0.23.0

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.

func (*BaseApp) ExpandRecords added in v0.23.0

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.

func (*BaseApp) FindAllAuthOriginsByCollection added in v0.23.0

func (app *BaseApp) FindAllAuthOriginsByCollection(collection *Collection) ([]*AuthOrigin, error)

FindAllAuthOriginsByCollection returns all AuthOrigin models linked to the provided collection (in DESC order).

func (*BaseApp) FindAllAuthOriginsByRecord added in v0.23.0

func (app *BaseApp) FindAllAuthOriginsByRecord(authRecord *Record) ([]*AuthOrigin, error)

FindAllAuthOriginsByRecord returns all AuthOrigin models linked to the provided auth record (in DESC order).

func (*BaseApp) FindAllCollections added in v0.23.0

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

func (*BaseApp) FindAllExternalAuthsByCollection added in v0.23.0

func (app *BaseApp) FindAllExternalAuthsByCollection(collection *Collection) ([]*ExternalAuth, error)

FindAllExternalAuthsByCollection returns all ExternalAuth models linked to the provided auth collection.

func (*BaseApp) FindAllExternalAuthsByRecord added in v0.23.0

func (app *BaseApp) FindAllExternalAuthsByRecord(authRecord *Record) ([]*ExternalAuth, error)

FindAllExternalAuthsByRecord returns all ExternalAuth models linked to the provided auth record.

func (*BaseApp) FindAllMFAsByCollection added in v0.23.0

func (app *BaseApp) FindAllMFAsByCollection(collection *Collection) ([]*MFA, error)

FindAllMFAsByCollection returns all MFA models linked to the provided collection.

func (*BaseApp) FindAllMFAsByRecord added in v0.23.0

func (app *BaseApp) FindAllMFAsByRecord(authRecord *Record) ([]*MFA, error)

FindAllMFAsByRecord returns all MFA models linked to the provided auth record.

func (*BaseApp) FindAllOTPsByCollection added in v0.23.0

func (app *BaseApp) FindAllOTPsByCollection(collection *Collection) ([]*OTP, error)

FindAllOTPsByCollection returns all OTP models linked to the provided collection.

func (*BaseApp) FindAllOTPsByRecord added in v0.23.0

func (app *BaseApp) FindAllOTPsByRecord(authRecord *Record) ([]*OTP, error)

FindAllOTPsByRecord returns all OTP models linked to the provided auth record.

func (*BaseApp) FindAllRecords added in v0.23.0

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": "test@example.com"}
expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"})
app.FindAllRecords("example", expr1, expr2)

func (*BaseApp) FindAuthOriginById added in v0.23.0

func (app *BaseApp) FindAuthOriginById(id string) (*AuthOrigin, error)

FindAuthOriginById returns a single AuthOrigin model by its id.

func (*BaseApp) FindAuthOriginByRecordAndFingerprint added in v0.23.0

func (app *BaseApp) FindAuthOriginByRecordAndFingerprint(authRecord *Record, fingerprint string) (*AuthOrigin, error)

FindAuthOriginByRecordAndFingerprint returns a single AuthOrigin model by its authRecord relation and fingerprint.

func (*BaseApp) FindAuthRecordByEmail added in v0.23.0

func (app *BaseApp) FindAuthRecordByEmail(collectionModelOrIdentifier any, email 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.

func (*BaseApp) FindAuthRecordByToken added in v0.23.0

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.

func (*BaseApp) FindCachedCollectionByNameOrId added in v0.23.0

func (app *BaseApp) FindCachedCollectionByNameOrId(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()]

func (*BaseApp) FindCollectionByNameOrId added in v0.23.0

func (app *BaseApp) FindCollectionByNameOrId(nameOrId string) (*Collection, error)

FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.

func (*BaseApp) FindCollectionReferences added in v0.23.0

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.

func (*BaseApp) FindFirstExternalAuthByExpr added in v0.23.0

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.

func (*BaseApp) FindFirstRecordByData added in v0.23.0

func (app *BaseApp) FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error)

FindFirstRecordByData returns the first found record matching the provided key-value pair.

func (*BaseApp) FindFirstRecordByFilter added in v0.23.0

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"})

func (*BaseApp) FindLogById added in v0.23.0

func (app *BaseApp) FindLogById(id string) (*Log, error)

FindLogById finds a single Log entry by its id.

func (*BaseApp) FindMFAById added in v0.23.0

func (app *BaseApp) FindMFAById(id string) (*MFA, error)

FindMFAById returns a single MFA model by its id.

func (*BaseApp) FindOTPById added in v0.23.0

func (app *BaseApp) FindOTPById(id string) (*OTP, error)

FindOTPById returns a single OTP model by its id.

func (*BaseApp) FindRecordById added in v0.23.0

func (app *BaseApp) FindRecordById(
	collectionModelOrIdentifier any,
	recordId string,
	optFilters ...func(q *dbx.SelectQuery) error,
) (*Record, error)

FindRecordById finds the Record model by its id.

func (*BaseApp) FindRecordByViewFile added in v0.23.0

func (app *BaseApp) FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)

FindRecordByViewFile returns the original Record of the provided view collection file.

func (*BaseApp) FindRecordsByFilter added in v0.23.0

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}
)

func (*BaseApp) FindRecordsByIds added in v0.23.0

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.

func (*BaseApp) HasTable added in v0.23.0

func (app *BaseApp) HasTable(tableName string) bool

HasTable checks if a table (or view) with the provided name exists (case insensitive). in the current app.DB() instance.

func (*BaseApp) ImportCollections added in v0.23.0

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).

func (*BaseApp) ImportCollectionsByMarshaledJSON added in v0.23.0

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).

func (*BaseApp) IsBootstrapped added in v0.10.0

func (app *BaseApp) IsBootstrapped() bool

IsBootstrapped checks if the application was initialized (aka. whether Bootstrap() was called).

func (*BaseApp) IsCollectionNameUnique added in v0.23.0

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.

func (*BaseApp) IsDev added in v0.20.1

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.

func (*BaseApp) IsTransactional added in v0.23.0

func (app *BaseApp) IsTransactional() bool

IsTransactional checks if the current app instance is part of a transaction.

func (*BaseApp) LogQuery added in v0.23.0

func (app *BaseApp) LogQuery() *dbx.SelectQuery

LogQuery returns a new Log select query.

func (*BaseApp) Logger added in v0.20.0

func (app *BaseApp) Logger() *slog.Logger

Logger returns the default app logger.

If the application is not bootstrapped yet, fallbacks to slog.Default().

func (*BaseApp) LogsStats added in v0.23.0

func (app *BaseApp) LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error)

LogsStats returns hourly grouped requests logs statistics.

func (*BaseApp) ModelQuery added in v0.23.0

func (app *BaseApp) ModelQuery(m Model) *dbx.SelectQuery

ModelQuery creates a new preconfigured select app.DB() query with preset SELECT, FROM and other common fields based on the provided model.

func (*BaseApp) NewBackupsFilesystem added in v0.16.0

func (app *BaseApp) NewBackupsFilesystem() (*filesystem.System, error)

NewFilesystem 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.

func (*BaseApp) NewFilesystem

func (app *BaseApp) NewFilesystem() (*filesystem.System, 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.

func (*BaseApp) NewMailClient

func (app *BaseApp) NewMailClient() mailer.Mailer

NewMailClient creates and returns a new SMTP or Sendmail client based on the current app settings.

func (*BaseApp) NonconcurrentDB added in v0.23.0

func (app *BaseApp) NonconcurrentDB() dbx.Builder

NonconcurrentDB returns the nonconcurrent app data db instance (pb_data/data.db).

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 operations will be queued 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.

For the majority of cases you would want to use the regular DB() method since it allows concurrent db read operations.

In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.

func (*BaseApp) OnBackupCreate added in v0.23.0

func (app *BaseApp) OnBackupCreate() *hook.Hook[*BackupEvent]

func (*BaseApp) OnBackupRestore added in v0.23.0

func (app *BaseApp) OnBackupRestore() *hook.Hook[*BackupEvent]

func (*BaseApp) OnBatchRequest added in v0.23.0

func (app *BaseApp) OnBatchRequest() *hook.Hook[*BatchRequestEvent]

func (*BaseApp) OnBootstrap added in v0.23.0

func (app *BaseApp) OnBootstrap() *hook.Hook[*BootstrapEvent]

func (*BaseApp) OnCollectionAfterCreateError added in v0.23.0

func (app *BaseApp) OnCollectionAfterCreateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]

func (*BaseApp) OnCollectionAfterCreateSuccess added in v0.23.0

func (app *BaseApp) OnCollectionAfterCreateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionAfterDeleteError added in v0.23.0

func (app *BaseApp) OnCollectionAfterDeleteError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]

func (*BaseApp) OnCollectionAfterDeleteSuccess added in v0.23.0

func (app *BaseApp) OnCollectionAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionAfterUpdateError added in v0.23.0

func (app *BaseApp) OnCollectionAfterUpdateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]

func (*BaseApp) OnCollectionAfterUpdateSuccess added in v0.23.0

func (app *BaseApp) OnCollectionAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionCreate added in v0.23.0

func (app *BaseApp) OnCollectionCreate(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionCreateExecute added in v0.23.0

func (app *BaseApp) OnCollectionCreateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionCreateRequest added in v0.23.0

func (app *BaseApp) OnCollectionCreateRequest() *hook.Hook[*CollectionRequestEvent]

func (*BaseApp) OnCollectionDelete added in v0.23.0

func (app *BaseApp) OnCollectionDelete(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionDeleteExecute added in v0.23.0

func (app *BaseApp) OnCollectionDeleteExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionDeleteRequest added in v0.23.0

func (app *BaseApp) OnCollectionDeleteRequest() *hook.Hook[*CollectionRequestEvent]

func (*BaseApp) OnCollectionUpdate added in v0.23.0

func (app *BaseApp) OnCollectionUpdate(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionUpdateExecute added in v0.23.0

func (app *BaseApp) OnCollectionUpdateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionUpdateRequest added in v0.23.0

func (app *BaseApp) OnCollectionUpdateRequest() *hook.Hook[*CollectionRequestEvent]

func (*BaseApp) OnCollectionValidate added in v0.23.0

func (app *BaseApp) OnCollectionValidate(tags ...string) *hook.TaggedHook[*CollectionEvent]

func (*BaseApp) OnCollectionViewRequest

func (app *BaseApp) OnCollectionViewRequest() *hook.Hook[*CollectionRequestEvent]

func (*BaseApp) OnCollectionsImportRequest added in v0.23.0

func (app *BaseApp) OnCollectionsImportRequest() *hook.Hook[*CollectionsImportRequestEvent]

func (*BaseApp) OnCollectionsListRequest

func (app *BaseApp) OnCollectionsListRequest() *hook.Hook[*CollectionsListRequestEvent]

func (*BaseApp) OnFileDownloadRequest

func (app *BaseApp) OnFileDownloadRequest(tags ...string) *hook.TaggedHook[*FileDownloadRequestEvent]

func (*BaseApp) OnFileTokenRequest added in v0.23.0

func (app *BaseApp) OnFileTokenRequest(tags ...string) *hook.TaggedHook[*FileTokenRequestEvent]

func (*BaseApp) OnMailerRecordAuthAlertSend added in v0.23.0

func (app *BaseApp) OnMailerRecordAuthAlertSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]

func (*BaseApp) OnMailerRecordEmailChangeSend added in v0.23.0

func (app *BaseApp) OnMailerRecordEmailChangeSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]

func (*BaseApp) OnMailerRecordOTPSend added in v0.23.0

func (app *BaseApp) OnMailerRecordOTPSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]

func (*BaseApp) OnMailerRecordPasswordResetSend added in v0.23.0

func (app *BaseApp) OnMailerRecordPasswordResetSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]

func (*BaseApp) OnMailerRecordVerificationSend added in v0.23.0

func (app *BaseApp) OnMailerRecordVerificationSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]

func (*BaseApp) OnMailerSend added in v0.23.0

func (app *BaseApp) OnMailerSend() *hook.Hook[*MailerEvent]

func (*BaseApp) OnModelAfterCreateError added in v0.23.0

func (app *BaseApp) OnModelAfterCreateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]

func (*BaseApp) OnModelAfterCreateSuccess added in v0.23.0

func (app *BaseApp) OnModelAfterCreateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelAfterDeleteError added in v0.23.0

func (app *BaseApp) OnModelAfterDeleteError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]

func (*BaseApp) OnModelAfterDeleteSuccess added in v0.23.0

func (app *BaseApp) OnModelAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelAfterUpdateError added in v0.23.0

func (app *BaseApp) OnModelAfterUpdateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]

func (*BaseApp) OnModelAfterUpdateSuccess added in v0.23.0

func (app *BaseApp) OnModelAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelCreate added in v0.23.0

func (app *BaseApp) OnModelCreate(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelCreateExecute added in v0.23.0

func (app *BaseApp) OnModelCreateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelDelete added in v0.23.0

func (app *BaseApp) OnModelDelete(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelDeleteExecute added in v0.23.0

func (app *BaseApp) OnModelDeleteExecute(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelUpdate added in v0.23.0

func (app *BaseApp) OnModelUpdate(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelUpdateExecute added in v0.23.0

func (app *BaseApp) OnModelUpdateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnModelValidate added in v0.23.0

func (app *BaseApp) OnModelValidate(tags ...string) *hook.TaggedHook[*ModelEvent]

func (*BaseApp) OnRealtimeConnectRequest

func (app *BaseApp) OnRealtimeConnectRequest() *hook.Hook[*RealtimeConnectRequestEvent]

func (*BaseApp) OnRealtimeMessageSend added in v0.23.0

func (app *BaseApp) OnRealtimeMessageSend() *hook.Hook[*RealtimeMessageEvent]

func (*BaseApp) OnRealtimeSubscribeRequest added in v0.23.0

func (app *BaseApp) OnRealtimeSubscribeRequest() *hook.Hook[*RealtimeSubscribeRequestEvent]

func (*BaseApp) OnRecordAfterCreateError added in v0.23.0

func (app *BaseApp) OnRecordAfterCreateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]

func (*BaseApp) OnRecordAfterCreateSuccess added in v0.23.0

func (app *BaseApp) OnRecordAfterCreateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordAfterDeleteError added in v0.23.0

func (app *BaseApp) OnRecordAfterDeleteError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]

func (*BaseApp) OnRecordAfterDeleteSuccess added in v0.23.0

func (app *BaseApp) OnRecordAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordAfterUpdateError added in v0.23.0

func (app *BaseApp) OnRecordAfterUpdateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]

func (*BaseApp) OnRecordAfterUpdateSuccess added in v0.23.0

func (app *BaseApp) OnRecordAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordAuthRefreshRequest added in v0.23.0

func (app *BaseApp) OnRecordAuthRefreshRequest(tags ...string) *hook.TaggedHook[*RecordAuthRefreshRequestEvent]

func (*BaseApp) OnRecordAuthRequest added in v0.8.0

func (app *BaseApp) OnRecordAuthRequest(tags ...string) *hook.TaggedHook[*RecordAuthRequestEvent]

func (*BaseApp) OnRecordAuthWithOAuth2Request added in v0.23.0

func (app *BaseApp) OnRecordAuthWithOAuth2Request(tags ...string) *hook.TaggedHook[*RecordAuthWithOAuth2RequestEvent]

func (*BaseApp) OnRecordAuthWithOTPRequest added in v0.23.0

func (app *BaseApp) OnRecordAuthWithOTPRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithOTPRequestEvent]

func (*BaseApp) OnRecordAuthWithPasswordRequest added in v0.23.0

func (app *BaseApp) OnRecordAuthWithPasswordRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithPasswordRequestEvent]

func (*BaseApp) OnRecordConfirmEmailChangeRequest added in v0.23.0

func (app *BaseApp) OnRecordConfirmEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordConfirmEmailChangeRequestEvent]

func (*BaseApp) OnRecordConfirmPasswordResetRequest added in v0.23.0

func (app *BaseApp) OnRecordConfirmPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordConfirmPasswordResetRequestEvent]

func (*BaseApp) OnRecordConfirmVerificationRequest added in v0.23.0

func (app *BaseApp) OnRecordConfirmVerificationRequest(tags ...string) *hook.TaggedHook[*RecordConfirmVerificationRequestEvent]

func (*BaseApp) OnRecordCreate added in v0.23.0

func (app *BaseApp) OnRecordCreate(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordCreateExecute added in v0.23.0

func (app *BaseApp) OnRecordCreateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordCreateRequest added in v0.23.0

func (app *BaseApp) OnRecordCreateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]

func (*BaseApp) OnRecordDelete added in v0.23.0

func (app *BaseApp) OnRecordDelete(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordDeleteExecute added in v0.23.0

func (app *BaseApp) OnRecordDeleteExecute(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordDeleteRequest added in v0.23.0

func (app *BaseApp) OnRecordDeleteRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]

func (*BaseApp) OnRecordEnrich added in v0.23.0

func (app *BaseApp) OnRecordEnrich(tags ...string) *hook.TaggedHook[*RecordEnrichEvent]

func (*BaseApp) OnRecordRequestEmailChangeRequest added in v0.23.0

func (app *BaseApp) OnRecordRequestEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordRequestEmailChangeRequestEvent]

func (*BaseApp) OnRecordRequestOTPRequest added in v0.23.0

func (app *BaseApp) OnRecordRequestOTPRequest(tags ...string) *hook.TaggedHook[*RecordCreateOTPRequestEvent]

func (*BaseApp) OnRecordRequestPasswordResetRequest added in v0.23.0

func (app *BaseApp) OnRecordRequestPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordRequestPasswordResetRequestEvent]

func (*BaseApp) OnRecordRequestVerificationRequest added in v0.23.0

func (app *BaseApp) OnRecordRequestVerificationRequest(tags ...string) *hook.TaggedHook[*RecordRequestVerificationRequestEvent]

func (*BaseApp) OnRecordUpdate added in v0.23.0

func (app *BaseApp) OnRecordUpdate(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordUpdateExecute added in v0.23.0

func (app *BaseApp) OnRecordUpdateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordUpdateRequest added in v0.23.0

func (app *BaseApp) OnRecordUpdateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]

func (*BaseApp) OnRecordValidate added in v0.23.0

func (app *BaseApp) OnRecordValidate(tags ...string) *hook.TaggedHook[*RecordEvent]

func (*BaseApp) OnRecordViewRequest

func (app *BaseApp) OnRecordViewRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]

func (*BaseApp) OnRecordsListRequest

func (app *BaseApp) OnRecordsListRequest(tags ...string) *hook.TaggedHook[*RecordsListRequestEvent]

func (*BaseApp) OnServe added in v0.23.0

func (app *BaseApp) OnServe() *hook.Hook[*ServeEvent]

func (*BaseApp) OnSettingsListRequest

func (app *BaseApp) OnSettingsListRequest() *hook.Hook[*SettingsListRequestEvent]

func (*BaseApp) OnSettingsReload added in v0.23.0

func (app *BaseApp) OnSettingsReload() *hook.Hook[*SettingsReloadEvent]

func (*BaseApp) OnSettingsUpdateRequest added in v0.23.0

func (app *BaseApp) OnSettingsUpdateRequest() *hook.Hook[*SettingsUpdateRequestEvent]

func (*BaseApp) OnTerminate added in v0.16.0

func (app *BaseApp) OnTerminate() *hook.Hook[*TerminateEvent]

func (*BaseApp) RecordQuery added in v0.23.0

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.

func (*BaseApp) ReloadCachedCollections added in v0.23.0

func (app *BaseApp) ReloadCachedCollections() error

ReloadCachedCollections fetches all collections and caches them into the app store.

func (*BaseApp) ReloadSettings added in v0.23.0

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.

func (*BaseApp) ResetBootstrapState

func (app *BaseApp) ResetBootstrapState() error

ResetBootstrapState releases the initialized core app resources (closing db connections, stopping cron ticker, etc.).

func (*BaseApp) Restart added in v0.16.0

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.

func (*BaseApp) RestoreBackup added in v0.16.0

func (app *BaseApp) RestoreBackup(ctx context.Context, 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:

  1. 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)

  2. Extract the backup in a temp directory inside the app "pb_data" (eg. "pb_data/.pb_temp_to_delete/pb_restore").

  3. 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.

  4. Move the extracted dir content to the app "pb_data".

  5. Restart the app (on successful app bootstap it will also remove the old pb_data).

If a failure occure during the restore process the dir changes are reverted. If for whatever reason the revert is not possible, it panics.

func (*BaseApp) RunAllMigrations added in v0.23.0

func (app *BaseApp) RunAllMigrations() error

RunAllMigrations applies all system and app migrations (aka. from both core.SystemMigrations and core.AppMigrations).

func (*BaseApp) RunAppMigrations added in v0.23.0

func (app *BaseApp) RunAppMigrations() error

RunAppMigrations applies all new migrations registered in the core.AppMigrations list.

func (*BaseApp) RunInTransaction added in v0.23.0

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.

func (*BaseApp) RunSystemMigrations added in v0.23.0

func (app *BaseApp) RunSystemMigrations() error

RunSystemMigrations applies all new migrations registered in the core.SystemMigrations list.

func (*BaseApp) Save added in v0.23.0

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()].

func (*BaseApp) SaveNoValidate added in v0.23.0

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()].

func (*BaseApp) SaveNoValidateWithContext added in v0.23.0

func (app *BaseApp) SaveNoValidateWithContext(ctx context.Context, model Model) error

SaveNoValidateWithContext is the same as [App.SaveNoValidate()] but allows specifying a context to limit the db execution.

If you want to also run validations before persisting, use [App.SaveWithContext()].

func (*BaseApp) SaveView added in v0.23.0

func (app *BaseApp) SaveView(name string, selectQuery string) error

SaveView creates (or updates already existing) persistent SQL view.

NB! Be aware that this method is vulnerable to SQL injection and the "selectQuery" argument must come only from trusted input!

func (*BaseApp) SaveWithContext added in v0.23.0

func (app *BaseApp) SaveWithContext(ctx context.Context, model Model) error

SaveWithContext is the same as [App.Save()] but allows specifying a context to limit the db execution.

If you don't want to run validations, use [App.SaveNoValidateWithContext()].

func (*BaseApp) Settings

func (app *BaseApp) Settings() *Settings

Settings returns the loaded app settings.

func (*BaseApp) Store added in v0.20.0

func (app *BaseApp) Store() *store.Store[any]

Store returns the app runtime store.

func (*BaseApp) SubscriptionsBroker

func (app *BaseApp) SubscriptionsBroker() *subscriptions.Broker

SubscriptionsBroker returns the app realtime subscriptions broker instance.

func (*BaseApp) SyncRecordTableSchema added in v0.23.0

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.

func (*BaseApp) TableColumns added in v0.23.0

func (app *BaseApp) TableColumns(tableName string) ([]string, error)

TableColumns returns all column names of a single table by its name.

func (*BaseApp) TableIndexes added in v0.23.0

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.

func (*BaseApp) TableInfo added in v0.23.0

func (app *BaseApp) TableInfo(tableName string) ([]*TableInfoRow, error)

TableInfo returns the "table_info" pragma result for the specified table.

func (*BaseApp) TruncateCollection added in v0.23.0

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.

func (*BaseApp) UnsafeWithoutHooks added in v0.23.0

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 normalizations (including files uploads) rely on the app hooks to work.

func (*BaseApp) Vacuum added in v0.23.0

func (app *BaseApp) Vacuum() error

Vacuum executes VACUUM on the current app.DB() instance in order to reclaim unused data db disk space.

func (*BaseApp) Validate added in v0.23.0

func (app *BaseApp) Validate(model Model) error

Validate triggers the OnModelValidate hook for the specified model.

func (*BaseApp) ValidateWithContext added in v0.23.0

func (app *BaseApp) ValidateWithContext(ctx context.Context, model Model) error

ValidateWithContext is the same as Validate but allows specifying the ModelEvent context.

type BaseAppConfig added in v0.10.0

type BaseAppConfig struct {
	DBConnect        DBConnectFunc
	DataDir          string
	EncryptionEnv    string
	QueryTimeout     time.Duration
	DataMaxOpenConns int
	DataMaxIdleConns int
	AuxMaxOpenConns  int
	AuxMaxIdleConns  int
	IsDev            bool
}

BaseAppConfig defines a BaseApp configuration option

type BaseModel added in v0.23.0

type BaseModel struct {

	// Id is the primary key of the model.
	// It is usually autogenerated by the parent model implementation.
	Id string `db:"id" json:"id" form:"id" xml:"id"`
	// contains filtered or unexported fields
}

BaseModel defines a base struct that is intended to be embedded into other custom models.

func (*BaseModel) IsNew added in v0.23.0

func (m *BaseModel) IsNew() bool

IsNew indicates what type of db query (insert or update) should be used with the model instance.

func (*BaseModel) LastSavedPK added in v0.23.0

func (m *BaseModel) LastSavedPK() any

LastSavedPK returns the last saved primary key of the model.

Its value is updated to the latest PK value after MarkAsNotNew() or PostScan() calls.

func (*BaseModel) MarkAsNew added in v0.23.0

func (m *BaseModel) MarkAsNew()

MarkAsNew clears the pk field and marks the current model as "new" (aka. forces m.IsNew() to be true).

func (*BaseModel) MarkAsNotNew added in v0.23.0

func (m *BaseModel) MarkAsNotNew()

MarkAsNew set the pk field to the Id value and marks the current model as NOT "new" (aka. forces m.IsNew() to be false).

func (*BaseModel) PK added in v0.23.0

func (m *BaseModel) PK() any

func (*BaseModel) PostScan added in v0.23.0

func (m *BaseModel) PostScan() error

PostScan implements the dbx.PostScanner interface.

It is usually executed right after the model is populated with the db row values.

type BaseRecordProxy added in v0.23.0

type BaseRecordProxy struct {
	*Record
}

BaseRecordProxy implements the RecordProxy interface and it is intended to be used as embed to custom user provided Record proxy structs.

func (*BaseRecordProxy) ProxyRecord added in v0.23.0

func (m *BaseRecordProxy) ProxyRecord() *Record

ProxyRecord returns the proxied Record model.

func (*BaseRecordProxy) SetProxyRecord added in v0.23.0

func (m *BaseRecordProxy) SetProxyRecord(record *Record)

SetProxyRecord loads the specified record model into the current proxy.

type BatchConfig added in v0.23.0

type BatchConfig struct {
	Enabled bool `form:"enabled" json:"enabled"`

	// MaxRequests is the maximum allowed batch request to execute.
	MaxRequests int `form:"maxRequests" json:"maxRequests"`

	// Timeout is the the max duration in seconds to wait before cancelling the batch transaction.
	Timeout int64 `form:"timeout" json:"timeout"`

	// MaxBodySize is the maximum allowed batch request body size in bytes.
	//
	// If not set, fallbacks to max ~128MB.
	MaxBodySize int64 `form:"maxBodySize" json:"maxBodySize"`
}

func (BatchConfig) Validate added in v0.23.0

func (c BatchConfig) Validate() error

Validate makes BatchConfig validatable by implementing validation.Validatable interface.

type BatchRequestEvent added in v0.23.0

type BatchRequestEvent struct {
	hook.Event
	*RequestEvent

	Batch []*InternalRequest
}

type BoolField added in v0.23.0

type BoolField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// Required will require the field value to be always "true".
	Required bool `form:"required" json:"required"`
}

BoolField defines "bool" type field to store a single true/false value.

The respective zero record field value is false.

func (*BoolField) ColumnType added in v0.23.0

func (f *BoolField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*BoolField) GetHidden added in v0.23.0

func (f *BoolField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*BoolField) GetId added in v0.23.0

func (f *BoolField) GetId() string

GetId implements [Field.GetId] interface method.

func (*BoolField) GetName added in v0.23.0

func (f *BoolField) GetName() string

GetName implements [Field.GetName] interface method.

func (*BoolField) GetSystem added in v0.23.0

func (f *BoolField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*BoolField) PrepareValue added in v0.23.0

func (f *BoolField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*BoolField) SetHidden added in v0.23.0

func (f *BoolField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*BoolField) SetId added in v0.23.0

func (f *BoolField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*BoolField) SetName added in v0.23.0

func (f *BoolField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*BoolField) SetSystem added in v0.23.0

func (f *BoolField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*BoolField) Type added in v0.23.0

func (f *BoolField) Type() string

Type implements [Field.Type] interface method.

func (*BoolField) ValidateSettings added in v0.23.0

func (f *BoolField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*BoolField) ValidateValue added in v0.23.0

func (f *BoolField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type BootstrapEvent added in v0.9.0

type BootstrapEvent struct {
	hook.Event
	App App
}

type Collection added in v0.23.0

type Collection struct {
	// contains filtered or unexported fields
}

Collection defines the table, fields and various options related to a set of records.

func NewAuthCollection added in v0.23.0

func NewAuthCollection(name string, optId ...string) *Collection

NewAuthCollection initializes and returns a new "auth" Collection model.

It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).

func NewBaseCollection added in v0.23.0

func NewBaseCollection(name string, optId ...string) *Collection

NewBaseCollection initializes and returns a new "base" Collection model.

It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).

func NewCollection added in v0.23.0

func NewCollection(typ, name string, optId ...string) *Collection

NewCollection initializes and returns a new Collection model with the specified type and name.

It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).

func NewViewCollection added in v0.23.0

func NewViewCollection(name string, optId ...string) *Collection

NewViewCollection initializes and returns a new "view" Collection model.

It also loads the minimal default configuration for the collection (eg. system fields, indexes, type specific options, etc.).

func (*Collection) AddIndex added in v0.23.0

func (m *Collection) AddIndex(name string, unique bool, columnsExpr string, optWhereExpr string)

AddIndex adds a new index into the current collection.

If the collection has an existing index matching the new name it will be replaced with the new one.

func (*Collection) BaseFilesPath added in v0.23.0

func (m *Collection) BaseFilesPath() string

BaseFilesPath returns the storage dir path used by the collection.

func (*Collection) DBExport added in v0.23.0

func (m *Collection) DBExport(app App) (map[string]any, error)

DBExport prepares and exports the current collection data for db persistence.

func (*Collection) GetIndex added in v0.23.0

func (m *Collection) GetIndex(name string) string

GetIndex returns s single Collection index expression by its name.

func (*Collection) IntegrityChecks added in v0.23.0

func (m *Collection) IntegrityChecks(enable bool)

IntegrityChecks toggles the current collection integrity checks (ex. checking references on delete).

func (*Collection) IsAuth added in v0.23.0

func (m *Collection) IsAuth() bool

IsAuth checks if the current collection has "auth" type.

func (*Collection) IsBase added in v0.23.0

func (m *Collection) IsBase() bool

IsBase checks if the current collection has "base" type.

func (*Collection) IsView added in v0.23.0

func (m *Collection) IsView() bool

IsView checks if the current collection has "view" type.

func (Collection) MarshalJSON added in v0.23.0

func (m Collection) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

Note that non-type related fields are ignored from the serialization (ex. for "view" colections the "auth" fields are skipped).

func (*Collection) PostScan added in v0.23.0

func (m *Collection) PostScan() error

PostScan implements the dbx.PostScanner interface to auto unmarshal the raw serialized options into the concrete type specific fields.

func (*Collection) RemoveIndex added in v0.23.0

func (m *Collection) RemoveIndex(name string)

RemoveIndex removes a single index with the specified name from the current collection.

func (Collection) String added in v0.23.0

func (m Collection) String() string

String returns a string representation of the current collection.

func (*Collection) TableName added in v0.23.0

func (m *Collection) TableName() string

TableName returns the Collection model SQL table name.

func (*Collection) UnmarshalJSON added in v0.23.0

func (m *Collection) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

For new/"blank" Collection models it replaces the model with a factory instance and then unmarshal the provided data one on top of it.

type CollectionErrorEvent added in v0.23.0

type CollectionErrorEvent struct {
	CollectionEvent
	Error error
}

func (*CollectionErrorEvent) Tags added in v0.23.0

func (e *CollectionErrorEvent) Tags() []string

type CollectionEvent added in v0.23.0

type CollectionEvent struct {
	hook.Event
	App App

	Context context.Context

	// Could be any of the ModelEventType* constants, like:
	// - create
	// - update
	// - delete
	// - validate
	Type string
	// contains filtered or unexported fields
}

func (*CollectionEvent) Tags added in v0.23.0

func (e *CollectionEvent) Tags() []string

type CollectionRequestEvent added in v0.23.0

type CollectionRequestEvent struct {
	hook.Event
	*RequestEvent
	// contains filtered or unexported fields
}

func (*CollectionRequestEvent) Tags added in v0.23.0

func (e *CollectionRequestEvent) Tags() []string

type CollectionsImportRequestEvent added in v0.23.0

type CollectionsImportRequestEvent struct {
	hook.Event
	*RequestEvent

	CollectionsData []map[string]any
	DeleteMissing   bool
}

type CollectionsListRequestEvent added in v0.23.0

type CollectionsListRequestEvent struct {
	hook.Event
	*RequestEvent

	Collections []*Collection
	Result      *search.Result
}

type DBConnectFunc added in v0.23.0

type DBConnectFunc func(dbPath string) (*dbx.DB, error)

DBConnectFunc defines a database connection initialization function.

type DBExporter added in v0.23.0

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].

type DateField added in v0.23.0

type DateField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// Min specifies the min allowed field value.
	//
	// Leave it empty to skip the validator.
	Min types.DateTime `form:"min" json:"min"`

	// Max specifies the max allowed field value.
	//
	// Leave it empty to skip the validator.
	Max types.DateTime `form:"max" json:"max"`

	// Required will require the field value to be non-zero [types.DateTime].
	Required bool `form:"required" json:"required"`
}

DateField defines "date" type field to store a single types.DateTime value.

The respective zero record field value is the zero types.DateTime.

func (*DateField) ColumnType added in v0.23.0

func (f *DateField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*DateField) GetHidden added in v0.23.0

func (f *DateField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*DateField) GetId added in v0.23.0

func (f *DateField) GetId() string

GetId implements [Field.GetId] interface method.

func (*DateField) GetName added in v0.23.0

func (f *DateField) GetName() string

GetName implements [Field.GetName] interface method.

func (*DateField) GetSystem added in v0.23.0

func (f *DateField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*DateField) PrepareValue added in v0.23.0

func (f *DateField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*DateField) SetHidden added in v0.23.0

func (f *DateField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*DateField) SetId added in v0.23.0

func (f *DateField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*DateField) SetName added in v0.23.0

func (f *DateField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*DateField) SetSystem added in v0.23.0

func (f *DateField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*DateField) Type added in v0.23.0

func (f *DateField) Type() string

Type implements [Field.Type] interface method.

func (*DateField) ValidateSettings added in v0.23.0

func (f *DateField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*DateField) ValidateValue added in v0.23.0

func (f *DateField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type DriverValuer added in v0.23.0

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.

type EditorField added in v0.23.0

type EditorField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// MaxSize specifies the maximum size of the allowed field value (in bytes).
	//
	// If zero, a default limit of ~5MB is applied.
	MaxSize int64 `form:"maxSize" json:"maxSize"`

	// ConvertURLs is usually used to instruct the editor whether to
	// apply url conversion (eg. stripping the domain name in case the
	// urls are using the same domain as the one where the editor is loaded).
	//
	// (see also https://www.tiny.cloud/docs/tinymce/6/url-handling/#convert_urls)
	ConvertURLs bool `form:"convertURLs" json:"convertURLs"`

	// Required will require the field value to be non-empty string.
	Required bool `form:"required" json:"required"`
}

EditorField defines "editor" type field to store HTML formatted text.

The respective zero record field value is empty string.

func (*EditorField) CalculateMaxBodySize added in v0.23.0

func (f *EditorField) CalculateMaxBodySize() int64

CalculateMaxBodySize implements the MaxBodySizeCalculator interface.

func (*EditorField) ColumnType added in v0.23.0

func (f *EditorField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*EditorField) GetHidden added in v0.23.0

func (f *EditorField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*EditorField) GetId added in v0.23.0

func (f *EditorField) GetId() string

GetId implements [Field.GetId] interface method.

func (*EditorField) GetName added in v0.23.0

func (f *EditorField) GetName() string

GetName implements [Field.GetName] interface method.

func (*EditorField) GetSystem added in v0.23.0

func (f *EditorField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*EditorField) PrepareValue added in v0.23.0

func (f *EditorField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*EditorField) SetHidden added in v0.23.0

func (f *EditorField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*EditorField) SetId added in v0.23.0

func (f *EditorField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*EditorField) SetName added in v0.23.0

func (f *EditorField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*EditorField) SetSystem added in v0.23.0

func (f *EditorField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*EditorField) Type added in v0.23.0

func (f *EditorField) Type() string

Type implements [Field.Type] interface method.

func (*EditorField) ValidateSettings added in v0.23.0

func (f *EditorField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*EditorField) ValidateValue added in v0.23.0

func (f *EditorField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type EmailField added in v0.23.0

type EmailField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// ExceptDomains will require the email domain to NOT be included in the listed ones.
	//
	// This validator can be set only if OnlyDomains is empty.
	ExceptDomains []string `form:"exceptDomains" json:"exceptDomains"`

	// OnlyDomains will require the email domain to be included in the listed ones.
	//
	// This validator can be set only if ExceptDomains is empty.
	OnlyDomains []string `form:"onlyDomains" json:"onlyDomains"`

	// Required will require the field value to be non-empty email string.
	Required bool `form:"required" json:"required"`
}

EmailField defines "email" type field for storing a single email string address.

The respective zero record field value is empty string.

func (*EmailField) ColumnType added in v0.23.0

func (f *EmailField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*EmailField) GetHidden added in v0.23.0

func (f *EmailField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*EmailField) GetId added in v0.23.0

func (f *EmailField) GetId() string

GetId implements [Field.GetId] interface method.

func (*EmailField) GetName added in v0.23.0

func (f *EmailField) GetName() string

GetName implements [Field.GetName] interface method.

func (*EmailField) GetSystem added in v0.23.0

func (f *EmailField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*EmailField) PrepareValue added in v0.23.0

func (f *EmailField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*EmailField) SetHidden added in v0.23.0

func (f *EmailField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*EmailField) SetId added in v0.23.0

func (f *EmailField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*EmailField) SetName added in v0.23.0

func (f *EmailField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*EmailField) SetSystem added in v0.23.0

func (f *EmailField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*EmailField) Type added in v0.23.0

func (f *EmailField) Type() string

Type implements [Field.Type] interface method.

func (*EmailField) ValidateSettings added in v0.23.0

func (f *EmailField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*EmailField) ValidateValue added in v0.23.0

func (f *EmailField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type EmailTemplate added in v0.5.0

type EmailTemplate struct {
	Subject string `form:"subject" json:"subject"`
	Body    string `form:"body" json:"body"`
}

func (EmailTemplate) Resolve added in v0.5.0

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.

func (EmailTemplate) Validate added in v0.5.0

func (t EmailTemplate) Validate() error

Validate makes EmailTemplate validatable by implementing validation.Validatable interface.

type ExpandFetchFunc added in v0.23.0

type ExpandFetchFunc func(relCollection *Collection, relIds []string) ([]*Record, error)

ExpandFetchFunc defines the function that is used to fetch the expanded relation records.

type ExternalAuth added in v0.23.0

type ExternalAuth struct {
	*Record
}

ExternalAuth defines a Record proxy for working with the externalAuths collection.

func NewExternalAuth added in v0.23.0

func NewExternalAuth(app App) *ExternalAuth

NewExternalAuth instantiates and returns a new blank *ExternalAuth model.

Example usage:

ea := core.NewExternalAuth(app)
ea.SetRecordRef(user.Id)
ea.SetCollectionRef(user.Collection().Id)
ea.SetProvider("google")
ea.SetProviderId("...")
app.Save(ea)

func (*ExternalAuth) CollectionRef added in v0.23.0

func (m *ExternalAuth) CollectionRef() string

CollectionRef returns the "collectionRef" field value.

func (*ExternalAuth) Created added in v0.23.0

func (m *ExternalAuth) Created() types.DateTime

Created returns the "created" record field value.

func (*ExternalAuth) PreValidate added in v0.23.0

func (m *ExternalAuth) PreValidate(ctx context.Context, app App) error

PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.

func (*ExternalAuth) Provider added in v0.23.0

func (m *ExternalAuth) Provider() string

Provider returns the "provider" record field value.

func (*ExternalAuth) ProviderId added in v0.23.0

func (m *ExternalAuth) ProviderId() string

Provider returns the "providerId" record field value.

func (*ExternalAuth) ProxyRecord added in v0.23.0

func (m *ExternalAuth) ProxyRecord() *Record

ProxyRecord returns the proxied Record model.

func (*ExternalAuth) RecordRef added in v0.23.0

func (m *ExternalAuth) RecordRef() string

RecordRef returns the "recordRef" record field value.

func (*ExternalAuth) SetCollectionRef added in v0.23.0

func (m *ExternalAuth) SetCollectionRef(collectionId string)

SetCollectionRef updates the "collectionRef" record field value.

func (*ExternalAuth) SetProvider added in v0.23.0

func (m *ExternalAuth) SetProvider(provider string)

SetProvider updates the "provider" record field value.

func (*ExternalAuth) SetProviderId added in v0.23.0

func (m *ExternalAuth) SetProviderId(providerId string)

SetProvider updates the "providerId" record field value.

func (*ExternalAuth) SetProxyRecord added in v0.23.0

func (m *ExternalAuth) SetProxyRecord(record *Record)

SetProxyRecord loads the specified record model into the current proxy.

func (*ExternalAuth) SetRecordRef added in v0.23.0

func (m *ExternalAuth) SetRecordRef(recordId string)

SetRecordRef updates the "recordRef" record field value.

func (*ExternalAuth) Updated added in v0.23.0

func (m *ExternalAuth) Updated() types.DateTime

Updated returns the "updated" record field value.

type Field added in v0.23.0

type Field interface {

	// GetId returns the field id.
	GetId() string

	// SetId changes the field id.
	SetId(id string)

	// GetName returns the field name.
	GetName() string

	// SetName changes the field name.
	SetName(name string)

	// GetSystem returns the field system flag state.
	GetSystem() bool

	// SetSystem changes the field system flag state.
	SetSystem(system bool)

	// GetHidden returns the field hidden flag state.
	GetHidden() bool

	// SetHidden changes the field hidden flag state.
	SetHidden(hidden bool)

	// Type returns the unique type of the field.
	Type() string

	// ColumnType returns the DB column definition of the field.
	ColumnType(app App) string

	// PrepareValue returns a properly formatted field value based on the provided raw one.
	//
	// This method is also called on record construction to initialize its default field value.
	PrepareValue(record *Record, raw any) (any, error)

	// ValidateSettings validates the current field value associated with the provided record.
	ValidateValue(ctx context.Context, app App, record *Record) error

	// ValidateSettings validates the current field settings.
	ValidateSettings(ctx context.Context, app App, collection *Collection) error
}

Field defines a common interface that all Collection fields should implement.

type FieldFactoryFunc added in v0.23.0

type FieldFactoryFunc func() Field

FieldFactoryFunc defines a simple function to construct a specific Field instance.

type FieldsList added in v0.23.0

type FieldsList []Field

FieldsList defines a Collection slice of fields.

func NewFieldsList added in v0.23.0

func NewFieldsList(fields ...Field) FieldsList

NewFieldsList creates a new FieldsList instance with the provided fields.

func (*FieldsList) Add added in v0.23.0

func (l *FieldsList) Add(fields ...Field)

Add adds one or more fields to the current list.

By default this method will try to REPLACE existing fields with the new ones by their id or by their name if the new field doesn't have an explicit id.

If no matching existing field is found, it will APPEND the field to the end of the list.

In all cases, if any of the new fields don't have an explicit id it will auto generate a default one for them (the id value doesn't really matter and it is mostly used as a stable identifier in case of a field rename).

func (*FieldsList) AddAt added in v0.23.0

func (l *FieldsList) AddAt(pos int, fields ...Field)

AddAt is the same as Add but insert/move the fields at the specific position.

If pos < 0, then this method acts the same as calling Add.

If pos > FieldsList total items, then the specified fields are inserted/moved at the end of the list.

func (*FieldsList) AddMarshaledJSON added in v0.23.0

func (l *FieldsList) AddMarshaledJSON(rawJSON []byte) error

AddMarshaledJSON parses the provided raw json data and adds the found fields into the current list (following the same rule as the Add method).

The rawJSON argument could be one of:

  • serialized array of field objects
  • single field object.

Example:

l.AddMarshaledJSON([]byte{`{"type":"text", name: "test"}`})
l.AddMarshaledJSON([]byte{`[{"type":"text", name: "test1"}, {"type":"text", name: "test2"}]`})

func (*FieldsList) AddMarshaledJSONAt added in v0.23.0

func (l *FieldsList) AddMarshaledJSONAt(pos int, rawJSON []byte) error

AddMarshaledJSONAt is the same as AddMarshaledJSON but insert/move the fields at the specific position.

If pos < 0, then this method acts the same as calling AddMarshaledJSON.

If pos > FieldsList total items, then the specified fields are inserted/moved at the end of the list.

func (FieldsList) AsMap added in v0.23.0

func (l FieldsList) AsMap() map[string]Field

AsMap returns a map with all registered list field. The returned map is indexed with each field name.

func (FieldsList) Clone added in v0.23.0

func (l FieldsList) Clone() (FieldsList, error)

Clone creates a deep clone of the current list.

func (FieldsList) FieldNames added in v0.23.0

func (l FieldsList) FieldNames() []string

FieldNames returns a slice with the name of all list fields.

func (FieldsList) GetById added in v0.23.0

func (l FieldsList) GetById(fieldId string) Field

GetById returns a single field by its id.

func (FieldsList) GetByName added in v0.23.0

func (l FieldsList) GetByName(fieldName string) Field

GetByName returns a single field by its name.

func (FieldsList) MarshalJSON added in v0.23.0

func (l FieldsList) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*FieldsList) RemoveById added in v0.23.0

func (l *FieldsList) RemoveById(fieldId string)

RemoveById removes a single field by its id.

This method does nothing if field with the specified id doesn't exist.

func (*FieldsList) RemoveByName added in v0.23.0

func (l *FieldsList) RemoveByName(fieldName string)

RemoveByName removes a single field by its name.

This method does nothing if field with the specified name doesn't exist.

func (*FieldsList) Scan added in v0.23.0

func (l *FieldsList) Scan(value any) error

Scan implements sql.Scanner interface to scan the provided value into the current FieldsList instance.

func (FieldsList) String added in v0.23.0

func (l FieldsList) String() string

String returns the string representation of the current list.

func (*FieldsList) UnmarshalJSON added in v0.23.0

func (l *FieldsList) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler and loads the provided json data into the current FieldsList.

func (FieldsList) Value added in v0.23.0

func (l FieldsList) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type FileDownloadRequestEvent added in v0.23.0

type FileDownloadRequestEvent struct {
	hook.Event
	*RequestEvent

	Record     *Record
	FileField  *FileField
	ServedPath string
	ServedName string
	// contains filtered or unexported fields
}

func (*FileDownloadRequestEvent) Tags added in v0.23.0

func (e *FileDownloadRequestEvent) Tags() []string

type FileField added in v0.23.0

type FileField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// MaxSize specifies the maximum size of a single uploaded file (in bytes).
	//
	// If zero, a default limit of 5MB is applied.
	MaxSize int64 `form:"maxSize" json:"maxSize"`

	// MaxSelect specifies the max allowed files.
	//
	// For multiple files the value must be > 1, otherwise fallbacks to single (default).
	MaxSelect int `form:"maxSelect" json:"maxSelect"`

	// MimeTypes specifies an optional list of the allowed file mime types.
	//
	// Leave it empty to disable the validator.
	MimeTypes []string `form:"mimeTypes" json:"mimeTypes"`

	// Thumbs specifies an optional list of the supported thumbs for image based files.
	//
	// Each entry must be in one of the following formats:
	//
	//   - WxH  (eg. 100x300) - crop to WxH viewbox (from center)
	//   - WxHt (eg. 100x300t) - crop to WxH viewbox (from top)
	//   - WxHb (eg. 100x300b) - crop to WxH viewbox (from bottom)
	//   - WxHf (eg. 100x300f) - fit inside a WxH viewbox (without cropping)
	//   - 0xH  (eg. 0x300)    - resize to H height preserving the aspect ratio
	//   - Wx0  (eg. 100x0)    - resize to W width preserving the aspect ratio
	Thumbs []string `form:"thumbs" json:"thumbs"`

	// Protected will require the users to provide a special file token to access the file.
	//
	// Note that by default all files are publicly accessible.
	//
	// For the majority of the cases this is fine because by default
	// all file names have random part appended to their name which
	// need to be known by the user before accessing the file.
	Protected bool `form:"protected" json:"protected"`

	// Required will require the field value to have at least one file.
	Required bool `form:"required" json:"required"`
}

FileField defines "file" type field for managing record file(s).

Only the file name is stored as part of the record value. New files (aka. files to upload) are expected to be of *filesytem.File.

If MaxSelect is not set or <= 1, then the field value is expected to be a single record id.

If MaxSelect is > 1, then the field value is expected to be a slice of record ids.

The respective zero record field value is either empty string (single) or empty string slice (multiple).

---

The following additional setter keys are available:

  • "fieldName+" - append one or more files to the existing record one. For example:

    // []string{"old1.txt", "old2.txt", "new1_ajkvass.txt", "new2_klhfnwd.txt"} record.Set("documents+", []*filesystem.File{new1, new2})

  • "+fieldName" - prepend one or more files to the existing record one. For example:

    // []string{"new1_ajkvass.txt", "new2_klhfnwd.txt", "old1.txt", "old2.txt",} record.Set("+documents", []*filesystem.File{new1, new2})

  • "fieldName-" - subtract/delete one or more files from the existing record one. For example:

    // []string{"old2.txt",} record.Set("documents-", "old1.txt")

func (*FileField) CalculateMaxBodySize added in v0.23.0

func (f *FileField) CalculateMaxBodySize() int64

CalculateMaxBodySize implements the MaxBodySizeCalculator interface.

func (*FileField) ColumnType added in v0.23.0

func (f *FileField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*FileField) DriverValue added in v0.23.0

func (f *FileField) DriverValue(record *Record) (driver.Value, error)

DriverValue implements the DriverValuer interface.

func (*FileField) FindGetter added in v0.23.0

func (f *FileField) FindGetter(key string) GetterFunc

FindGetter implements the GetterFinder interface.

func (*FileField) FindSetter added in v0.23.0

func (f *FileField) FindSetter(key string) SetterFunc

FindSetter implements the SetterFinder interface.

func (*FileField) GetHidden added in v0.23.0

func (f *FileField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*FileField) GetId added in v0.23.0

func (f *FileField) GetId() string

GetId implements [Field.GetId] interface method.

func (*FileField) GetName added in v0.23.0

func (f *FileField) GetName() string

GetName implements [Field.GetName] interface method.

func (*FileField) GetSystem added in v0.23.0

func (f *FileField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*FileField) Intercept added in v0.23.0

func (f *FileField) Intercept(
	ctx context.Context,
	app App,
	record *Record,
	actionName string,
	actionFunc func() error,
) error

Intercept implements the RecordInterceptor interface.

note: files delete after records deletion is handled globally by the app FileManager hook

func (*FileField) IsMultiple added in v0.23.0

func (f *FileField) IsMultiple() bool

IsMultiple implements MultiValuer interface and checks whether the current field options support multiple values.

func (*FileField) PrepareValue added in v0.23.0

func (f *FileField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*FileField) SetHidden added in v0.23.0

func (f *FileField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*FileField) SetId added in v0.23.0

func (f *FileField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*FileField) SetName added in v0.23.0

func (f *FileField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*FileField) SetSystem added in v0.23.0

func (f *FileField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*FileField) Type added in v0.23.0

func (f *FileField) Type() string

Type implements [Field.Type] interface method.

func (*FileField) ValidateSettings added in v0.23.0

func (f *FileField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*FileField) ValidateValue added in v0.23.0

func (f *FileField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type FileTokenRequestEvent added in v0.23.0

type FileTokenRequestEvent struct {
	hook.Event
	*RequestEvent

	Token string
	// contains filtered or unexported fields
}

func (*FileTokenRequestEvent) Tags added in v0.23.0

func (e *FileTokenRequestEvent) Tags() []string

type FilesManager added in v0.23.0

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.

type GetterFinder added in v0.23.0

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.

type GetterFunc added in v0.23.0

type GetterFunc func(record *Record) any

type HookTagger added in v0.23.0

type HookTagger interface {
	HookTags() []string
}

type InternalRequest added in v0.23.0

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"`
}

func (InternalRequest) Validate added in v0.23.0

func (br InternalRequest) Validate() error

type JSONField added in v0.23.0

type JSONField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// MaxSize specifies the maximum size of the allowed field value (in bytes).
	//
	// If zero, a default limit of 5MB is applied.
	MaxSize int64 `form:"maxSize" json:"maxSize"`

	// Required will require the field value to be non-empty JSON value
	// (aka. not "null", `""`, "[]", "{}").
	Required bool `form:"required" json:"required"`
}

JSONField defines "json" type field for storing any serialized JSON value.

The respective zero record field value is the zero types.JSONRaw.

func (*JSONField) CalculateMaxBodySize added in v0.23.0

func (f *JSONField) CalculateMaxBodySize() int64

CalculateMaxBodySize implements the MaxBodySizeCalculator interface.

func (*JSONField) ColumnType added in v0.23.0

func (f *JSONField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*JSONField) GetHidden added in v0.23.0

func (f *JSONField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*JSONField) GetId added in v0.23.0

func (f *JSONField) GetId() string

GetId implements [Field.GetId] interface method.

func (*JSONField) GetName added in v0.23.0

func (f *JSONField) GetName() string

GetName implements [Field.GetName] interface method.

func (*JSONField) GetSystem added in v0.23.0

func (f *JSONField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*JSONField) PrepareValue added in v0.23.0

func (f *JSONField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*JSONField) SetHidden added in v0.23.0

func (f *JSONField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*JSONField) SetId added in v0.23.0

func (f *JSONField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*JSONField) SetName added in v0.23.0

func (f *JSONField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*JSONField) SetSystem added in v0.23.0

func (f *JSONField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*JSONField) Type added in v0.23.0

func (f *JSONField) Type() string

Type implements [Field.Type] interface method.

func (*JSONField) ValidateSettings added in v0.23.0

func (f *JSONField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*JSONField) ValidateValue added in v0.23.0

func (f *JSONField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type Log added in v0.23.0

type Log struct {
	BaseModel

	Created types.DateTime     `db:"created" json:"created"`
	Data    types.JSONMap[any] `db:"data" json:"data"`
	Message string             `db:"message" json:"message"`
	Level   int                `db:"level" json:"level"`
}

func (*Log) TableName added in v0.23.0

func (m *Log) TableName() string

type LogsConfig

type LogsConfig struct {
	MaxDays   int  `form:"maxDays" json:"maxDays"`
	MinLevel  int  `form:"minLevel" json:"minLevel"`
	LogIP     bool `form:"logIP" json:"logIP"`
	LogAuthId bool `form:"logAuthId" json:"logAuthId"`
}

func (LogsConfig) Validate

func (c LogsConfig) Validate() error

Validate makes LogsConfig validatable by implementing validation.Validatable interface.

type LogsStatsItem added in v0.23.0

type LogsStatsItem struct {
	Date  types.DateTime `db:"date" json:"date"`
	Total int            `db:"total" json:"total"`
}

LogsStatsItem defines the total number of logs for a specific time period.

type MFA added in v0.23.0

type MFA struct {
	*Record
}

MFA defines a Record proxy for working with the mfas collection.

func NewMFA added in v0.23.0

func NewMFA(app App) *MFA

NewMFA instantiates and returns a new blank *MFA model.

Example usage:

mfa := core.NewMFA(app)
mfa.SetRecordRef(user.Id)
mfa.SetCollectionRef(user.Collection().Id)
mfa.SetMethod(core.MFAMethodPassword)
app.Save(mfa)

func (*MFA) CollectionRef added in v0.23.0

func (m *MFA) CollectionRef() string

CollectionRef returns the "collectionRef" field value.

func (*MFA) Created added in v0.23.0

func (m *MFA) Created() types.DateTime

Created returns the "created" record field value.

func (*MFA) HasExpired added in v0.23.0

func (m *MFA) HasExpired(maxElapsed time.Duration) bool

HasExpired checks if the mfa is expired, aka. whether it has been more than maxElapsed time since its creation.

func (*MFA) Method added in v0.23.0

func (m *MFA) Method() string

Method returns the "method" record field value.

func (*MFA) PreValidate added in v0.23.0

func (m *MFA) PreValidate(ctx context.Context, app App) error

PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.

func (*MFA) ProxyRecord added in v0.23.0

func (m *MFA) ProxyRecord() *Record

ProxyRecord returns the proxied Record model.

func (*MFA) RecordRef added in v0.23.0

func (m *MFA) RecordRef() string

RecordRef returns the "recordRef" record field value.

func (*MFA) SetCollectionRef added in v0.23.0

func (m *MFA) SetCollectionRef(collectionId string)

SetCollectionRef updates the "collectionRef" record field value.

func (*MFA) SetMethod added in v0.23.0

func (m *MFA) SetMethod(method string)

SetMethod updates the "method" record field value.

func (*MFA) SetProxyRecord added in v0.23.0

func (m *MFA) SetProxyRecord(record *Record)

SetProxyRecord loads the specified record model into the current proxy.

func (*MFA) SetRecordRef added in v0.23.0

func (m *MFA) SetRecordRef(recordId string)

SetRecordRef updates the "recordRef" record field value.

func (*MFA) Updated added in v0.23.0

func (m *MFA) Updated() types.DateTime

Updated returns the "updated" record field value.

type MFAConfig added in v0.23.0

type MFAConfig struct {
	Enabled bool `form:"enabled" json:"enabled"`

	// Duration specifies how long an issued MFA to be valid (in seconds)
	Duration int64 `form:"duration" json:"duration"`

	// Rule is an optional field to restrict MFA only for the records that satisfy the rule.
	//
	// Leave it empty to enable MFA for everyone.
	Rule string `form:"rule" json:"rule"`
}

func (MFAConfig) DurationTime added in v0.23.0

func (c MFAConfig) DurationTime() time.Duration

DurationTime returns the current Duration as time.Duration.

func (MFAConfig) Validate added in v0.23.0

func (c MFAConfig) Validate() error

Validate makes MFAConfig validatable by implementing validation.Validatable interface.

type MailerEvent added in v0.23.0

type MailerEvent struct {
	hook.Event
	App App

	Mailer  mailer.Mailer
	Message *mailer.Message
}

type MailerRecordEvent added in v0.8.0

type MailerRecordEvent struct {
	MailerEvent

	Meta map[string]any
	// contains filtered or unexported fields
}

func (*MailerRecordEvent) Tags added in v0.23.0

func (e *MailerRecordEvent) Tags() []string

type MaxBodySizeCalculator added in v0.23.0

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.

type MetaConfig

type MetaConfig struct {
	AppName       string `form:"appName" json:"appName"`
	AppURL        string `form:"appURL" json:"appURL"`
	SenderName    string `form:"senderName" json:"senderName"`
	SenderAddress string `form:"senderAddress" json:"senderAddress"`
	HideControls  bool   `form:"hideControls" json:"hideControls"`
}

func (MetaConfig) Validate

func (c MetaConfig) Validate() error

Validate makes MetaConfig validatable by implementing validation.Validatable interface.

type Migration added in v0.23.0

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)
}

type MigrationsList added in v0.23.0

type MigrationsList struct {
	// contains filtered or unexported fields
}

MigrationsList defines a list with migration definitions

var AppMigrations MigrationsList
var SystemMigrations MigrationsList

func (*MigrationsList) Add added in v0.23.0

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.

func (*MigrationsList) Copy added in v0.23.0

func (l *MigrationsList) Copy(list MigrationsList)

Copy copies all provided list migrations into the current one.

func (*MigrationsList) Item added in v0.23.0

func (l *MigrationsList) Item(index int) *Migration

Item returns a single migration from the list by its index.

func (*MigrationsList) Items added in v0.23.0

func (l *MigrationsList) Items() []*Migration

Items returns the internal migrations list slice.

func (*MigrationsList) Register added in v0.23.0

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.

type MigrationsRunner added in v0.23.0

type MigrationsRunner struct {
	// contains filtered or unexported fields
}

MigrationsRunner defines a simple struct for managing the execution of db migrations.

func NewMigrationsRunner added in v0.23.0

func NewMigrationsRunner(app App, migrationsList MigrationsList) *MigrationsRunner

NewMigrationsRunner creates and initializes a new db migrations MigrationsRunner instance.

func (*MigrationsRunner) Down added in v0.23.0

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.

func (*MigrationsRunner) RemoveMissingAppliedMigrations added in v0.23.0

func (r *MigrationsRunner) RemoveMissingAppliedMigrations() error

RemoveMissingAppliedMigrations removes the db entries of all applied migrations that are not listed in the runner's migrations list.

func (*MigrationsRunner) Run added in v0.23.0

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

func (*MigrationsRunner) Up added in v0.23.0

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.

type Model added in v0.23.0

type Model interface {
	TableName() string
	PK() any
	LastSavedPK() any
	IsNew() bool
	MarkAsNew()
	MarkAsNotNew()
}

Model defines an interface with common methods that all db models should have.

Note: for simplicity composite pk are not supported.

type ModelErrorEvent added in v0.23.0

type ModelErrorEvent struct {
	ModelEvent
	Error error
}

func (*ModelErrorEvent) Tags added in v0.23.0

func (e *ModelErrorEvent) Tags() []string

type ModelEvent

type ModelEvent struct {
	hook.Event
	App App

	Context context.Context

	// Could be any of the ModelEventType* constants, like:
	// - create
	// - update
	// - delete
	// - validate
	Type string
	// contains filtered or unexported fields
}

func (*ModelEvent) Tags added in v0.12.0

func (e *ModelEvent) Tags() []string

type MultiValuer added in v0.23.0

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.

type NumberField added in v0.23.0

type NumberField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// Min specifies the min allowed field value.
	//
	// Leave it nil to skip the validator.
	Min *float64 `form:"min" json:"min"`

	// Max specifies the max allowed field value.
	//
	// Leave it nil to skip the validator.
	Max *float64 `form:"max" json:"max"`

	// OnlyInt will require the field value to be integer.
	OnlyInt bool `form:"onlyInt" json:"onlyInt"`

	// Required will require the field value to be non-zero.
	Required bool `form:"required" json:"required"`
}

NumberField defines "number" type field for storing numeric (float64) value.

The respective zero record field value is 0.

The following additional setter keys are available:

  • "fieldName+" - appends to the existing record value. For example: record.Set("total+", 5)
  • "fieldName-" - subtracts from the existing record value. For example: record.Set("total-", 5)

func (*NumberField) ColumnType added in v0.23.0

func (f *NumberField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*NumberField) FindSetter added in v0.23.0

func (f *NumberField) FindSetter(key string) SetterFunc

FindSetter implements the SetterFinder interface.

func (*NumberField) GetHidden added in v0.23.0

func (f *NumberField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*NumberField) GetId added in v0.23.0

func (f *NumberField) GetId() string

GetId implements [Field.GetId] interface method.

func (*NumberField) GetName added in v0.23.0

func (f *NumberField) GetName() string

GetName implements [Field.GetName] interface method.

func (*NumberField) GetSystem added in v0.23.0

func (f *NumberField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*NumberField) PrepareValue added in v0.23.0

func (f *NumberField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*NumberField) SetHidden added in v0.23.0

func (f *NumberField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*NumberField) SetId added in v0.23.0

func (f *NumberField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*NumberField) SetName added in v0.23.0

func (f *NumberField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*NumberField) SetSystem added in v0.23.0

func (f *NumberField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*NumberField) Type added in v0.23.0

func (f *NumberField) Type() string

Type implements [Field.Type] interface method.

func (*NumberField) ValidateSettings added in v0.23.0

func (f *NumberField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*NumberField) ValidateValue added in v0.23.0

func (f *NumberField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type OAuth2Config added in v0.23.0

type OAuth2Config struct {
	Providers []OAuth2ProviderConfig `form:"providers" json:"providers"`

	MappedFields OAuth2KnownFields `form:"mappedFields" json:"mappedFields"`

	Enabled bool `form:"enabled" json:"enabled"`
}

func (OAuth2Config) GetProviderConfig added in v0.23.0

func (c OAuth2Config) GetProviderConfig(name string) (config OAuth2ProviderConfig, exists bool)

GetProviderConfig returns the first OAuth2ProviderConfig that matches the specified name.

Returns false and zero config if no such provider is available in c.Providers.

func (OAuth2Config) Validate added in v0.23.0

func (c OAuth2Config) Validate() error

Validate makes OAuth2Config validatable by implementing validation.Validatable interface.

type OAuth2KnownFields added in v0.23.0

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"`
}

type OAuth2ProviderConfig added in v0.23.0

type OAuth2ProviderConfig struct {
	// PKCE overwrites the default provider PKCE config option.
	//
	// This usually shouldn't be needed but some OAuth2 vendors, like the LinkedIn OIDC,
	// may require manual adjustment due to returning error if extra parameters are added to the request
	// (https://github.com/pocketbase/pocketbase/discussions/3799#discussioncomment-7640312)
	PKCE *bool `form:"pkce" json:"pkce"`

	Name         string         `form:"name" json:"name"`
	ClientId     string         `form:"clientId" json:"clientId"`
	ClientSecret string         `form:"clientSecret" json:"clientSecret,omitempty"`
	AuthURL      string         `form:"authURL" json:"authURL"`
	TokenURL     string         `form:"tokenURL" json:"tokenURL"`
	UserInfoURL  string         `form:"userInfoURL" json:"userInfoURL"`
	DisplayName  string         `form:"displayName" json:"displayName"`
	Extra        map[string]any `form:"extra" json:"extra"`
}

func (OAuth2ProviderConfig) InitProvider added in v0.23.0

func (c OAuth2ProviderConfig) InitProvider() (auth.Provider, error)

InitProvider returns a new auth.Provider instance loaded with the current OAuth2ProviderConfig options.

func (OAuth2ProviderConfig) Validate added in v0.23.0

func (c OAuth2ProviderConfig) Validate() error

Validate makes OAuth2ProviderConfig validatable by implementing validation.Validatable interface.

type OTP added in v0.23.0

type OTP struct {
	*Record
}

OTP defines a Record proxy for working with the otps collection.

func NewOTP added in v0.23.0

func NewOTP(app App) *OTP

NewOTP instantiates and returns a new blank *OTP model.

Example usage:

otp := core.NewOTP(app)
otp.SetRecordRef(user.Id)
otp.SetCollectionRef(user.Collection().Id)
otp.SetPassword(security.RandomStringWithAlphabet(6, "1234567890"))
app.Save(otp)

func (*OTP) CollectionRef added in v0.23.0

func (m *OTP) CollectionRef() string

CollectionRef returns the "collectionRef" field value.

func (*OTP) Created added in v0.23.0

func (m *OTP) Created() types.DateTime

Created returns the "created" record field value.

func (*OTP) HasExpired added in v0.23.0

func (m *OTP) HasExpired(maxElapsed time.Duration) bool

HasExpired checks if the otp is expired, aka. whether it has been more than maxElapsed time since its creation.

func (*OTP) PreValidate added in v0.23.0

func (m *OTP) PreValidate(ctx context.Context, app App) error

PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.

func (*OTP) ProxyRecord added in v0.23.0

func (m *OTP) ProxyRecord() *Record

ProxyRecord returns the proxied Record model.

func (*OTP) RecordRef added in v0.23.0

func (m *OTP) RecordRef() string

RecordRef returns the "recordRef" record field value.

func (*OTP) SentTo added in v0.23.0

func (m *OTP) SentTo() string

SentTo returns the "sentTo" record field value.

It could be any string value (email, phone, message app id, etc.) and usually is used as part of the auth flow to update the verified user state in case for example the sentTo value matches with the user record email.

func (*OTP) SetCollectionRef added in v0.23.0

func (m *OTP) SetCollectionRef(collectionId string)

SetCollectionRef updates the "collectionRef" record field value.

func (*OTP) SetProxyRecord added in v0.23.0

func (m *OTP) SetProxyRecord(record *Record)

SetProxyRecord loads the specified record model into the current proxy.

func (*OTP) SetRecordRef added in v0.23.0

func (m *OTP) SetRecordRef(recordId string)

SetRecordRef updates the "recordRef" record field value.

func (*OTP) SetSentTo added in v0.23.0

func (m *OTP) SetSentTo(val string)

SetSentTo updates the "sentTo" record field value.

func (*OTP) Updated added in v0.23.0

func (m *OTP) Updated() types.DateTime

Updated returns the "updated" record field value.

type OTPConfig added in v0.23.0

type OTPConfig struct {
	Enabled bool `form:"enabled" json:"enabled"`

	// Duration specifies how long the OTP to be valid (in seconds)
	Duration int64 `form:"duration" json:"duration"`

	// Length specifies the auto generated password length.
	Length int `form:"length" json:"length"`

	// EmailTemplate is the default OTP email template that will be send to the auth record.
	//
	// In addition to the system placeholders you can also make use of
	// [core.EmailPlaceholderOTPId] and [core.EmailPlaceholderOTP].
	EmailTemplate EmailTemplate `form:"emailTemplate" json:"emailTemplate"`
}

func (OTPConfig) DurationTime added in v0.23.0

func (c OTPConfig) DurationTime() time.Duration

DurationTime returns the current Duration as time.Duration.

func (OTPConfig) Validate added in v0.23.0

func (c OTPConfig) Validate() error

Validate makes OTPConfig validatable by implementing validation.Validatable interface.

type Param added in v0.23.0

type Param struct {
	BaseModel

	Created types.DateTime `db:"created" json:"created"`
	Updated types.DateTime `db:"updated" json:"updated"`
	Value   types.JSONRaw  `db:"value" json:"value"`
}

func (*Param) TableName added in v0.23.0

func (m *Param) TableName() string

type PasswordAuthConfig added in v0.23.0

type PasswordAuthConfig struct {
	Enabled bool `form:"enabled" json:"enabled"`

	// IdentityFields is a list of field names that could be used as
	// identity during password authentication.
	//
	// Usually only fields that has single column UNIQUE index are accepted as values.
	IdentityFields []string `form:"identityFields" json:"identityFields"`
}

func (PasswordAuthConfig) Validate added in v0.23.0

func (c PasswordAuthConfig) Validate() error

Validate makes PasswordAuthConfig validatable by implementing validation.Validatable interface.

type PasswordField added in v0.23.0

type PasswordField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// Pattern specifies an optional regex pattern to match against the field value.
	//
	// Leave it empty to skip the pattern check.
	Pattern string `form:"pattern" json:"pattern"`

	// Min specifies an optional required field string length.
	Min int `form:"min" json:"min"`

	// Max specifies an optional required field string length.
	//
	// If zero, fallback to max 71 bytes.
	Max int `form:"max" json:"max"`

	// Cost specifies the cost/weight/iteration/etc. bcrypt factor.
	//
	// If zero, fallback to [bcrypt.DefaultCost].
	//
	// If explicitly set, must be between [bcrypt.MinCost] and [bcrypt.MaxCost].
	Cost int `form:"cost" json:"cost"`

	// Required will require the field value to be non-empty string.
	Required bool `form:"required" json:"required"`
}

PasswordField defines "password" type field for storing bcrypt hashed strings (usually used only internally for the "password" auth collection system field).

If you want to set a direct bcrypt hash as record field value you can use the SetRaw method, for example:

// generates a bcrypt hash of "123456" and set it as field value
// (record.GetString("password") returns the plain password until persisted, otherwise empty string)
record.Set("password", "123456")

// set directly a bcrypt hash of "123456" as field value
// (record.GetString("password") returns empty string)
record.SetRaw("password", "$2a$10$.5Elh8fgxypNUWhpUUr/xOa2sZm0VIaE0qWuGGl9otUfobb46T1Pq")

The following additional getter keys are available:

  • "fieldName:hash" - returns the bcrypt hash string of the record field value (if any). For example: record.GetString("password:hash")

func (*PasswordField) ColumnType added in v0.23.0

func (f *PasswordField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*PasswordField) DriverValue added in v0.23.0

func (f *PasswordField) DriverValue(record *Record) (driver.Value, error)

DriverValue implements the DriverValuer interface.

func (*PasswordField) FindGetter added in v0.23.0

func (f *PasswordField) FindGetter(key string) GetterFunc

FindGetter implements the GetterFinder interface.

func (*PasswordField) FindSetter added in v0.23.0

func (f *PasswordField) FindSetter(key string) SetterFunc

FindSetter implements the SetterFinder interface.

func (*PasswordField) GetHidden added in v0.23.0

func (f *PasswordField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*PasswordField) GetId added in v0.23.0

func (f *PasswordField) GetId() string

GetId implements [Field.GetId] interface method.

func (*PasswordField) GetName added in v0.23.0

func (f *PasswordField) GetName() string

GetName implements [Field.GetName] interface method.

func (*PasswordField) GetSystem added in v0.23.0

func (f *PasswordField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*PasswordField) Intercept added in v0.23.0

func (f *PasswordField) Intercept(
	ctx context.Context,
	app App,
	record *Record,
	actionName string,
	actionFunc func() error,
) error

Intercept implements the RecordInterceptor interface.

func (*PasswordField) PrepareValue added in v0.23.0

func (f *PasswordField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*PasswordField) SetHidden added in v0.23.0

func (f *PasswordField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*PasswordField) SetId added in v0.23.0

func (f *PasswordField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*PasswordField) SetName added in v0.23.0

func (f *PasswordField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*PasswordField) SetSystem added in v0.23.0

func (f *PasswordField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*PasswordField) Type added in v0.23.0

func (f *PasswordField) Type() string

Type implements [Field.Type] interface method.

func (*PasswordField) ValidateSettings added in v0.23.0

func (f *PasswordField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*PasswordField) ValidateValue added in v0.23.0

func (f *PasswordField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type PasswordFieldValue added in v0.23.0

type PasswordFieldValue struct {
	LastError error
	Hash      string
	Plain     string
}

func (PasswordFieldValue) Validate added in v0.23.0

func (pv PasswordFieldValue) Validate(pass string) bool

type PostValidator added in v0.23.0

type PostValidator interface {
	// PostValidate defines a function that runs AFTER the successful
	// execution of the validation hooks.
	PostValidate(ctx context.Context, app App) error
}

PostValidator defines an optional model interface for registering a function that will run AFTER executing the validation hooks (see [App.ValidateWithContext]).

type PreValidator added in v0.23.0

type PreValidator interface {
	// PreValidate defines a function that runs BEFORE the validation hooks.
	PreValidate(ctx context.Context, app App) error
}

PreValidator defines an optional model interface for registering a function that will run BEFORE firing the validation hooks (see [App.ValidateWithContext]).

type RateLimitRule added in v0.23.0

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"`
}

func (RateLimitRule) DurationTime added in v0.23.0

func (c RateLimitRule) DurationTime() time.Duration

DurationTime returns the tag's Duration as time.Duration.

func (RateLimitRule) Validate added in v0.23.0

func (c RateLimitRule) Validate() error

Validate makes RateLimitRule validatable by implementing validation.Validatable interface.

type RateLimitsConfig added in v0.23.0

type RateLimitsConfig struct {
	Rules   []RateLimitRule `form:"rules" json:"rules"`
	Enabled bool            `form:"enabled" json:"enabled"`
}

func (*RateLimitsConfig) FindRateLimitRule added in v0.23.0

func (c *RateLimitsConfig) FindRateLimitRule(searchLabels []string, optOnlyAudience ...string) (RateLimitRule, bool)

FindRateLimitRule returns the first matching rule based on the provided labels.

Optionally you can further specify a list of valid RateLimitRule.Audience values to further filter the matching rule (aka. the rule Audience will have to exist in one of the specified options).

func (RateLimitsConfig) MarshalJSON added in v0.23.0

func (c RateLimitsConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (RateLimitsConfig) Validate added in v0.23.0

func (c RateLimitsConfig) Validate() error

Validate makes RateLimitsConfig validatable by implementing validation.Validatable interface.

type RealtimeConnectRequestEvent added in v0.23.0

type RealtimeConnectRequestEvent struct {
	hook.Event
	*RequestEvent

	Client subscriptions.Client

	// note: modifying it after the connect has no effect
	IdleTimeout time.Duration
}

type RealtimeMessageEvent added in v0.9.0

type RealtimeMessageEvent struct {
	hook.Event
	*RequestEvent

	Client  subscriptions.Client
	Message *subscriptions.Message
}

type RealtimeSubscribeRequestEvent added in v0.23.0

type RealtimeSubscribeRequestEvent struct {
	hook.Event
	*RequestEvent

	Client        subscriptions.Client
	Subscriptions []string
}

type Record added in v0.23.0

type Record struct {
	BaseModel
	// contains filtered or unexported fields
}

func NewRecord added in v0.23.0

func NewRecord(collection *Collection) *Record

NewRecord initializes a new empty Record model.

func (*Record) BaseFilesPath added in v0.23.0

func (m *Record) BaseFilesPath() string

BaseFilesPath returns the storage dir path used by the record.

func (*Record) Clone added in v0.23.0

func (m *Record) Clone() *Record

Clone returns a shallow copy of the current record model with all of its collection and unknown fields data, expand and flags copied.

use [Record.Fresh()] instead if you want a copy with only the latest collection fields data and everything else reset to the defaults.

func (*Record) Collection added in v0.23.0

func (m *Record) Collection() *Collection

Collection returns the Collection model associated with the current Record model.

NB! The returned collection is only for read purposes and it shouldn't be modified because it could have unintended side-effects on other Record models from the same collection.

func (*Record) CustomData added in v0.23.0

func (m *Record) CustomData() map[string]any

CustomData returns a shallow copy ONLY of the custom record fields data, aka. fields that are neither defined by the collection, nor special system ones.

Note that custom fields prefixed with "@pbInternal" are always skipped.

func (*Record) DBExport added in v0.23.0

func (m *Record) DBExport(app App) (map[string]any, error)

DBExport implements the DBExporter interface and returns a key-value map with the data to be persisted when saving the Record in the database.

func (*Record) Email added in v0.23.0

func (m *Record) Email() string

Email returns the "email" record field value (usually available with Auth collections).

func (*Record) EmailVisibility added in v0.23.0

func (m *Record) EmailVisibility() bool

Verified returns the "emailVisibility" record field value (usually available with Auth collections).

func (*Record) Expand added in v0.23.0

func (m *Record) Expand() map[string]any

Expand returns a shallow copy of the current Record model expand data (if any).

func (*Record) ExpandedAll added in v0.23.0

func (m *Record) ExpandedAll(relField string) []*Record

ExpandedAll retrieves a slice of relation Records from the already loaded expand data of the current model.

If the requested expand relation is single, this method normalizes the return result and will wrap the single model as a slice.

Returns nil slice if there is no such expand relation loaded.

func (*Record) ExpandedOne added in v0.23.0

func (m *Record) ExpandedOne(relField string) *Record

ExpandedOne retrieves a single relation Record from the already loaded expand data of the current model.

If the requested expand relation is multiple, this method returns only first available Record from the expanded relation.

Returns nil if there is no such expand relation loaded.

func (*Record) FieldsData added in v0.23.0

func (m *Record) FieldsData() map[string]any

FieldsData returns a shallow copy ONLY of the collection's fields record's data.

func (*Record) FindFileFieldByFile added in v0.23.0

func (m *Record) FindFileFieldByFile(filename string) *FileField

FindFileFieldByFile returns the first file type field for which any of the record's data contains the provided filename.

func (*Record) Fresh added in v0.23.0

func (m *Record) Fresh() *Record

Fresh returns a shallow copy of the current record model populated with its LATEST data state and everything else reset to the defaults (aka. no expand, no unknown fields and with default visibility flags).

func (*Record) Get added in v0.23.0

func (m *Record) Get(key string) any

Get returns a normalized single record model data value for "key".

func (*Record) GetBool added in v0.23.0

func (m *Record) GetBool(key string) bool

GetBool returns the data value for "key" as a bool.

func (*Record) GetDateTime added in v0.23.0

func (m *Record) GetDateTime(key string) types.DateTime

GetDateTime returns the data value for "key" as a DateTime instance.

func (*Record) GetFloat added in v0.23.0

func (m *Record) GetFloat(key string) float64

GetFloat returns the data value for "key" as a float64.

func (*Record) GetInt added in v0.23.0

func (m *Record) GetInt(key string) int

GetInt returns the data value for "key" as an int.

func (*Record) GetRaw added in v0.23.0

func (m *Record) GetRaw(key string) any

func (*Record) GetString added in v0.23.0

func (m *Record) GetString(key string) string

GetString returns the data value for "key" as a string.

func (*Record) GetStringSlice added in v0.23.0

func (m *Record) GetStringSlice(key string) []string

GetStringSlice returns the data value for "key" as a slice of non-zero unique strings.

func (*Record) GetUploadedFiles added in v0.23.0

func (m *Record) GetUploadedFiles(key string) []*filesystem.File

GetUploadedFiles returns the uploaded files for the provided "file" field key, (aka. the current [*filesytem.File] values) so that you can apply further validations or modifications (including changing the file name or content before persisting).

Example:

files := record.GetUploadedFiles("documents")
for _, f := range files {
    f.Name = "doc_" + f.Name // add a prefix to each file name
}
app.Save(record) // the files are pointers so the applied changes will transparently reflect on the record value

func (*Record) Hide added in v0.23.0

func (record *Record) Hide(fieldNames ...string) *Record

Hide hides the specified fields from the public safe serialization of the record.

func (*Record) HookTags added in v0.23.0

func (m *Record) HookTags() []string

HookTags returns the hook tags associated with the current record.

func (*Record) IgnoreEmailVisibility added in v0.23.0

func (m *Record) IgnoreEmailVisibility(state bool) *Record

IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check.

func (*Record) IgnoreUnchangedFields added in v0.23.0

func (m *Record) IgnoreUnchangedFields(state bool) *Record

IgnoreUnchangedFields toggles the flag to ignore the unchanged fields from the DB export for the UPDATE SQL query.

This could be used if you want to save only the record fields that you've changed without overwrite other untouched fields in case of concurrent update.

func (*Record) IsSuperuser added in v0.23.0

func (m *Record) IsSuperuser() bool

IsSuperuser returns whether the current record is a superuser, aka. whether the record is from the _superusers collection.

func (*Record) Load added in v0.23.0

func (m *Record) Load(data map[string]any)

Load bulk loads the provided data into the current Record model.

func (Record) MarshalJSON added in v0.23.0

func (m Record) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

Only the data exported by `PublicExport()` will be serialized.

func (*Record) MergeExpand added in v0.23.0

func (m *Record) MergeExpand(expand map[string]any)

MergeExpand merges recursively the provided expand data into the current model's expand (if any).

Note that if an expanded prop with the same key is a slice (old or new expand) then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew).

func (*Record) NewAuthToken added in v0.23.0

func (m *Record) NewAuthToken() (string, error)

NewAuthToken generates and returns a new record authentication token.

func (*Record) NewEmailChangeToken added in v0.23.0

func (m *Record) NewEmailChangeToken(newEmail string) (string, error)

NewEmailChangeToken generates and returns a new auth record change email request token.

func (*Record) NewFileToken added in v0.23.0

func (m *Record) NewFileToken() (string, error)

NewFileToken generates and returns a new record private file access token.

func (*Record) NewPasswordResetToken added in v0.23.0

func (m *Record) NewPasswordResetToken() (string, error)

NewPasswordResetToken generates and returns a new auth record password reset request token.

func (*Record) NewStaticAuthToken added in v0.23.0

func (m *Record) NewStaticAuthToken(duration time.Duration) (string, error)

NewStaticAuthToken generates and returns a new static record authentication token.

Static auth tokens are similar to the regular auth tokens, but are non-refreshable and support custom duration.

Zero or negative duration will fallback to the duration from the auth collection settings.

func (*Record) NewVerificationToken added in v0.23.0

func (m *Record) NewVerificationToken() (string, error)

NewVerificationToken generates and returns a new record verification token.

func (*Record) Original added in v0.23.0

func (m *Record) Original() *Record

Original returns a shallow copy of the current record model populated with its ORIGINAL db data state (aka. right after PostScan()) and everything else reset to the defaults.

If record was created using NewRecord() the original will be always a blank record (until PostScan() is invoked).

func (*Record) PostScan added in v0.23.0

func (m *Record) PostScan() error

PostScan implements the dbx.PostScanner interface.

It essentially refreshes/updates the current Record original state as if the model was fetched from the databases for the first time.

Or in other words, it means that m.Original().FieldsData() will have the same values as m.Record().FieldsData().

func (*Record) PublicExport added in v0.23.0

func (record *Record) PublicExport() map[string]any

PublicExport exports only the record fields that are safe to be public.

To export unknown data fields you need to set record.WithCustomData(true).

For auth records, to force the export of the email field you need to set record.IgnoreEmailVisibility(true).

func (*Record) RefreshTokenKey added in v0.23.0

func (m *Record) RefreshTokenKey()

RefreshTokenKey generates and sets a new random auth record "tokenKey".

func (*Record) ReplaceModifiers added in v0.23.0

func (m *Record) ReplaceModifiers(data map[string]any) map[string]any

ReplaceModifiers returns a new map with applied modifier values based on the current record and the specified data.

The resolved modifier keys will be removed.

Multiple modifiers will be applied one after another, while reusing the previous base key value result (ex. 1; -5; +2 => -2).

Note that because Go doesn't guaranteed the iteration order of maps, we would explicitly apply shorter keys first for a more consistent and reproducible behavior.

Example usage:

 newData := record.ReplaceModifiers(data)
	// record: {"field": 10}
	// data:   {"field+": 5}
	// result: {"field": 15}

func (*Record) Set added in v0.23.0

func (m *Record) Set(key string, value any)

Set sets the provided key-value data pair into the current Record model.

If the record collection has field with name matching the provided "key", the value will be further normalized according to the field setter(s).

func (*Record) SetEmail added in v0.23.0

func (m *Record) SetEmail(email string)

SetEmail sets the "email" record field value (usually available with Auth collections).

func (*Record) SetEmailVisibility added in v0.23.0

func (m *Record) SetEmailVisibility(visible bool)

SetEmailVisibility sets the "emailVisibility" record field value (usually available with Auth collections).

func (*Record) SetExpand added in v0.23.0

func (m *Record) SetExpand(expand map[string]any)

SetExpand replaces the current Record's expand with the provided expand arg data (shallow copied).

func (*Record) SetIfFieldExists added in v0.23.0

func (m *Record) SetIfFieldExists(key string, value any) Field

SetIfFieldExists sets the provided key-value data pair into the current Record model ONLY if key is existing Collection field name/modifier.

This method does nothing if key is not a known Collection field name/modifier.

On success returns the matched Field, otherwise - nil.

To set any key-value, including custom/unknown fields, use the Record.Set method.

func (*Record) SetPassword added in v0.23.0

func (m *Record) SetPassword(password string)

SetPassword sets the "password" record field value (usually available with Auth collections).

func (*Record) SetRaw added in v0.23.0

func (m *Record) SetRaw(key string, value any)

Set sets the provided key-value data pair into the current Record model directly as it is WITHOUT NORMALIZATIONS.

See also Record.Set.

func (*Record) SetTokenKey added in v0.23.0

func (m *Record) SetTokenKey(key string)

SetTokenKey sets the "tokenKey" record field value (usually available with Auth collections).

func (*Record) SetVerified added in v0.23.0

func (m *Record) SetVerified(verified bool)

SetVerified sets the "verified" record field value (usually available with Auth collections).

func (*Record) TableName added in v0.23.0

func (m *Record) TableName() string

TableName returns the table name associated with the current Record model.

func (*Record) TokenKey added in v0.23.0

func (m *Record) TokenKey() string

TokenKey returns the "tokenKey" record field value (usually available with Auth collections).

func (*Record) Unhide added in v0.23.0

func (record *Record) Unhide(fieldNames ...string) *Record

Unhide forces to unhide the specified fields from the public safe serialization of the record (even when the collection field itself is marked as hidden).

func (*Record) UnmarshalJSON added in v0.23.0

func (m *Record) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Record) UnmarshalJSONField added in v0.23.0

func (m *Record) UnmarshalJSONField(key string, result any) error

Retrieves the "key" json field value and unmarshals it into "result".

Example

result := struct {
    FirstName string `json:"first_name"`
}{}
err := m.UnmarshalJSONField("my_field_name", &result)

func (*Record) ValidatePassword added in v0.23.0

func (m *Record) ValidatePassword(password string) bool

ValidatePassword validates a plain password against the "password" record field.

Returns false if the password is incorrect.

func (*Record) Verified added in v0.23.0

func (m *Record) Verified() bool

Verified returns the "verified" record field value (usually available with Auth collections).

func (*Record) WithCustomData added in v0.23.0

func (m *Record) WithCustomData(state bool) *Record

WithCustomData toggles the export/serialization of custom data fields (false by default).

type RecordAuthRefreshRequestEvent added in v0.23.0

type RecordAuthRefreshRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	// contains filtered or unexported fields
}

func (*RecordAuthRefreshRequestEvent) Tags added in v0.23.0

func (e *RecordAuthRefreshRequestEvent) Tags() []string

type RecordAuthRequestEvent added in v0.23.0

type RecordAuthRequestEvent struct {
	hook.Event
	*RequestEvent

	Record     *Record
	Token      string
	Meta       any
	AuthMethod string
	// contains filtered or unexported fields
}

func (*RecordAuthRequestEvent) Tags added in v0.23.0

func (e *RecordAuthRequestEvent) Tags() []string

type RecordAuthWithOAuth2RequestEvent added in v0.23.0

type RecordAuthWithOAuth2RequestEvent struct {
	hook.Event
	*RequestEvent

	ProviderName   string
	ProviderClient auth.Provider
	Record         *Record
	OAuth2User     *auth.AuthUser
	CreateData     map[string]any
	IsNewRecord    bool
	// contains filtered or unexported fields
}

func (*RecordAuthWithOAuth2RequestEvent) Tags added in v0.23.0

func (e *RecordAuthWithOAuth2RequestEvent) Tags() []string

type RecordAuthWithOTPRequestEvent added in v0.23.0

type RecordAuthWithOTPRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	OTP    *OTP
	// contains filtered or unexported fields
}

func (*RecordAuthWithOTPRequestEvent) Tags added in v0.23.0

func (e *RecordAuthWithOTPRequestEvent) Tags() []string

type RecordAuthWithPasswordRequestEvent added in v0.23.0

type RecordAuthWithPasswordRequestEvent struct {
	hook.Event
	*RequestEvent

	Record        *Record
	Identity      string
	IdentityField string
	Password      string
	// contains filtered or unexported fields
}

func (*RecordAuthWithPasswordRequestEvent) Tags added in v0.23.0

func (e *RecordAuthWithPasswordRequestEvent) Tags() []string

type RecordConfirmEmailChangeRequestEvent added in v0.23.0

type RecordConfirmEmailChangeRequestEvent struct {
	hook.Event
	*RequestEvent

	Record   *Record
	NewEmail string
	// contains filtered or unexported fields
}

func (*RecordConfirmEmailChangeRequestEvent) Tags added in v0.23.0

func (e *RecordConfirmEmailChangeRequestEvent) Tags() []string

type RecordConfirmPasswordResetRequestEvent added in v0.23.0

type RecordConfirmPasswordResetRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	// contains filtered or unexported fields
}

func (*RecordConfirmPasswordResetRequestEvent) Tags added in v0.23.0

func (e *RecordConfirmPasswordResetRequestEvent) Tags() []string

type RecordConfirmVerificationRequestEvent added in v0.23.0

type RecordConfirmVerificationRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	// contains filtered or unexported fields
}

func (*RecordConfirmVerificationRequestEvent) Tags added in v0.23.0

func (e *RecordConfirmVerificationRequestEvent) Tags() []string

type RecordCreateOTPRequestEvent added in v0.23.0

type RecordCreateOTPRequestEvent struct {
	hook.Event
	*RequestEvent

	Record   *Record
	Password string
	// contains filtered or unexported fields
}

func (*RecordCreateOTPRequestEvent) Tags added in v0.23.0

func (e *RecordCreateOTPRequestEvent) Tags() []string

type RecordEnrichEvent added in v0.23.0

type RecordEnrichEvent struct {
	hook.Event
	App App

	RequestInfo *RequestInfo
	// contains filtered or unexported fields
}

func (*RecordEnrichEvent) Tags added in v0.23.0

func (e *RecordEnrichEvent) Tags() []string

type RecordErrorEvent added in v0.23.0

type RecordErrorEvent struct {
	RecordEvent
	Error error
}

func (*RecordErrorEvent) Tags added in v0.23.0

func (e *RecordErrorEvent) Tags() []string

type RecordEvent added in v0.23.0

type RecordEvent struct {
	hook.Event
	App App

	Context context.Context

	// Could be any of the ModelEventType* constants, like:
	// - create
	// - update
	// - delete
	// - validate
	Type string
	// contains filtered or unexported fields
}

func (*RecordEvent) Tags added in v0.23.0

func (e *RecordEvent) Tags() []string

type RecordFieldResolver added in v0.23.0

type RecordFieldResolver struct {
	// contains filtered or unexported fields
}

RecordFieldResolver defines a custom search resolver struct for managing Record model search fields.

Usually used together with `search.Provider`. Example:

resolver := resolvers.NewRecordFieldResolver(
    app,
    myCollection,
    &models.RequestInfo{...},
    true,
)
provider := search.NewProvider(resolver)
...

func NewRecordFieldResolver added in v0.23.0

func NewRecordFieldResolver(
	app App,
	baseCollection *Collection,
	requestInfo *RequestInfo,
	allowHiddenFields bool,
) *RecordFieldResolver

NewRecordFieldResolver creates and initializes a new `RecordFieldResolver`.

func (*RecordFieldResolver) Resolve added in v0.23.0

func (r *RecordFieldResolver) Resolve(fieldName string) (*search.ResolverResult, error)

Resolve implements `search.FieldResolver` interface.

Example of some resolvable fieldName formats:

id
someSelect.each
project.screen.status
screen.project_via_prototype.name
@request.context
@request.method
@request.query.filter
@request.headers.x_token
@request.auth.someRelation.name
@request.body.someRelation.name
@request.body.someField
@request.body.someSelect:each
@request.body.someField:isset
@collection.product.name

func (*RecordFieldResolver) UpdateQuery added in v0.23.0

func (r *RecordFieldResolver) UpdateQuery(query *dbx.SelectQuery) error

UpdateQuery implements `search.FieldResolver` interface.

Conditionally updates the provided search query based on the resolved fields (eg. dynamically joining relations).

type RecordInterceptor added in v0.23.0

type RecordInterceptor interface {
	// Interceptor is invoked when a specific record action occurs
	// allowing you to perform extra validations and normalization
	// (ex. uploading or deleting files).
	//
	// Note that users must call actionFunc() manually if they want to
	// execute the specific record action.
	Intercept(
		ctx context.Context,
		app App,
		record *Record,
		actionName string,
		actionFunc func() error,
	) error
}

RecordInterceptor defines a field interface for reacting to various Record related operations (create, delete, validate, etc.).

type RecordProxy added in v0.23.0

type RecordProxy interface {
	// ProxyRecord returns the proxied Record model.
	ProxyRecord() *Record

	// SetProxyRecord loads the specified record model into the current proxy.
	SetProxyRecord(record *Record)
}

RecordProxy defines an interface for a Record proxy/project model, aka. custom model struct that acts on behalve the proxied Record to allow for example typed getter/setters for the Record fields.

To implement the interface it is usually enough to embed the BaseRecordProxy struct.

type RecordRequestEmailChangeRequestEvent added in v0.23.0

type RecordRequestEmailChangeRequestEvent struct {
	hook.Event
	*RequestEvent

	Record   *Record
	NewEmail string
	// contains filtered or unexported fields
}

func (*RecordRequestEmailChangeRequestEvent) Tags added in v0.23.0

func (e *RecordRequestEmailChangeRequestEvent) Tags() []string

type RecordRequestEvent added in v0.23.0

type RecordRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	// contains filtered or unexported fields
}

func (*RecordRequestEvent) Tags added in v0.23.0

func (e *RecordRequestEvent) Tags() []string

type RecordRequestPasswordResetRequestEvent added in v0.23.0

type RecordRequestPasswordResetRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	// contains filtered or unexported fields
}

func (*RecordRequestPasswordResetRequestEvent) Tags added in v0.23.0

func (e *RecordRequestPasswordResetRequestEvent) Tags() []string

type RecordRequestVerificationRequestEvent added in v0.23.0

type RecordRequestVerificationRequestEvent struct {
	hook.Event
	*RequestEvent

	Record *Record
	// contains filtered or unexported fields
}

func (*RecordRequestVerificationRequestEvent) Tags added in v0.23.0

func (e *RecordRequestVerificationRequestEvent) Tags() []string

type RecordsListRequestEvent added in v0.23.0

type RecordsListRequestEvent struct {
	hook.Event
	*RequestEvent

	// @todo consider removing and maybe add as generic to the search.Result?
	Records []*Record
	Result  *search.Result
	// contains filtered or unexported fields
}

func (*RecordsListRequestEvent) Tags added in v0.23.0

func (e *RecordsListRequestEvent) Tags() []string

type RelationField added in v0.23.0

type RelationField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// CollectionId is the id of the related collection.
	CollectionId string `form:"collectionId" json:"collectionId"`

	// CascadeDelete indicates whether the root model should be deleted
	// in case of delete of all linked relations.
	CascadeDelete bool `form:"cascadeDelete" json:"cascadeDelete"`

	// MinSelect indicates the min number of allowed relation records
	// that could be linked to the main model.
	//
	// No min limit is applied if it is zero or negative value.
	MinSelect int `form:"minSelect" json:"minSelect"`

	// MaxSelect indicates the max number of allowed relation records
	// that could be linked to the main model.
	//
	// For multiple select the value must be > 1, otherwise fallbacks to single (default).
	//
	// If MinSelect is set, MaxSelect must be at least >= MinSelect.
	MaxSelect int `form:"maxSelect" json:"maxSelect"`

	// Required will require the field value to be non-empty.
	Required bool `form:"required" json:"required"`
}

RelationField defines "relation" type field for storing single or multiple collection record references.

Requires the CollectionId option to be set.

If MaxSelect is not set or <= 1, then the field value is expected to be a single record id.

If MaxSelect is > 1, then the field value is expected to be a slice of record ids.

The respective zero record field value is either empty string (single) or empty string slice (multiple).

---

The following additional setter keys are available:

  • "fieldName+" - append one or more values to the existing record one. For example:

    record.Set("categories+", []string{"new1", "new2"}) // []string{"old1", "old2", "new1", "new2"}

  • "+fieldName" - prepend one or more values to the existing record one. For example:

    record.Set("+categories", []string{"new1", "new2"}) // []string{"new1", "new2", "old1", "old2"}

  • "fieldName-" - subtract one or more values from the existing record one. For example:

    record.Set("categories-", "old1") // []string{"old2"}

func (*RelationField) ColumnType added in v0.23.0

func (f *RelationField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*RelationField) DriverValue added in v0.23.0

func (f *RelationField) DriverValue(record *Record) (driver.Value, error)

DriverValue implements the DriverValuer interface.

func (*RelationField) FindSetter added in v0.23.0

func (f *RelationField) FindSetter(key string) SetterFunc

FindSetter implements SetterFinder interface method.

func (*RelationField) GetHidden added in v0.23.0

func (f *RelationField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*RelationField) GetId added in v0.23.0

func (f *RelationField) GetId() string

GetId implements [Field.GetId] interface method.

func (*RelationField) GetName added in v0.23.0

func (f *RelationField) GetName() string

GetName implements [Field.GetName] interface method.

func (*RelationField) GetSystem added in v0.23.0

func (f *RelationField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*RelationField) IsMultiple added in v0.23.0

func (f *RelationField) IsMultiple() bool

IsMultiple implements MultiValuer interface and checks whether the current field options support multiple values.

func (*RelationField) PrepareValue added in v0.23.0

func (f *RelationField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*RelationField) SetHidden added in v0.23.0

func (f *RelationField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*RelationField) SetId added in v0.23.0

func (f *RelationField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*RelationField) SetName added in v0.23.0

func (f *RelationField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*RelationField) SetSystem added in v0.23.0

func (f *RelationField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*RelationField) Type added in v0.23.0

func (f *RelationField) Type() string

Type implements [Field.Type] interface method.

func (*RelationField) ValidateSettings added in v0.23.0

func (f *RelationField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*RelationField) ValidateValue added in v0.23.0

func (f *RelationField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type RequestEvent added in v0.23.0

type RequestEvent struct {
	App App

	Auth *Record

	router.Event
	// contains filtered or unexported fields
}

RequestEvent defines the PocketBase router handler event.

func (*RequestEvent) HasSuperuserAuth added in v0.23.0

func (e *RequestEvent) HasSuperuserAuth() bool

HasSuperuserAuth checks whether the current RequestEvent has superuser authentication loaded.

func (*RequestEvent) RealIP added in v0.23.0

func (e *RequestEvent) RealIP() string

RealIP returns the "real" IP address from the configured trusted proxy headers.

If Settings.TrustedProxy is not configured or the found IP is empty, it fallbacks to e.RemoteIP().

NB! Be careful when used in a security critical context as it relies on the trusted proxy to be properly configured and your app to be accessible only through it. If you are not sure, use e.RemoteIP().

func (*RequestEvent) RequestInfo added in v0.23.0

func (e *RequestEvent) RequestInfo() (*RequestInfo, error)

RequestInfo parses the current request into RequestInfo instance.

Note that the returned result is cached to avoid copying the request data multiple times but the auth state and other common store items are always refreshed in case they were changed my another handler.

type RequestInfo added in v0.23.0

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.

func (*RequestInfo) Clone added in v0.23.0

func (info *RequestInfo) Clone() *RequestInfo

Clone creates a new shallow copy of the current RequestInfo and its Auth record (if any).

func (*RequestInfo) HasSuperuserAuth added in v0.23.0

func (info *RequestInfo) HasSuperuserAuth() bool

HasSuperuserAuth checks whether the current RequestInfo instance has superuser authentication loaded.

type S3Config

type S3Config struct {
	Enabled        bool   `form:"enabled" json:"enabled"`
	Bucket         string `form:"bucket" json:"bucket"`
	Region         string `form:"region" json:"region"`
	Endpoint       string `form:"endpoint" json:"endpoint"`
	AccessKey      string `form:"accessKey" json:"accessKey"`
	Secret         string `form:"secret" json:"secret,omitempty"`
	ForcePathStyle bool   `form:"forcePathStyle" json:"forcePathStyle"`
}

func (S3Config) Validate

func (c S3Config) Validate() error

Validate makes S3Config validatable by implementing validation.Validatable interface.

type SMTPConfig added in v0.23.0

type SMTPConfig struct {
	Enabled  bool   `form:"enabled" json:"enabled"`
	Port     int    `form:"port" json:"port"`
	Host     string `form:"host" json:"host"`
	Username string `form:"username" json:"username"`
	Password string `form:"password" json:"password,omitempty"`

	// SMTP AUTH - PLAIN (default) or LOGIN
	AuthMethod string `form:"authMethod" json:"authMethod"`

	// Whether to enforce TLS encryption for the mail server connection.
	//
	// When set to false StartTLS command is send, leaving the server
	// to decide whether to upgrade the connection or not.
	TLS bool `form:"tls" json:"tls"`

	// LocalName is optional domain name or IP address used for the
	// EHLO/HELO exchange (if not explicitly set, defaults to "localhost").
	//
	// This is required only by some SMTP servers, such as Gmail SMTP-relay.
	LocalName string `form:"localName" json:"localName"`
}

func (SMTPConfig) Validate added in v0.23.0

func (c SMTPConfig) Validate() error

Validate makes SMTPConfig validatable by implementing validation.Validatable interface.

type SelectField added in v0.23.0

type SelectField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// Values specifies the list of accepted values.
	Values []string `form:"values" json:"values"`

	// MaxSelect specifies the max allowed selected values.
	//
	// For multiple select the value must be > 1, otherwise fallbacks to single (default).
	MaxSelect int `form:"maxSelect" json:"maxSelect"`

	// Required will require the field value to be non-empty.
	Required bool `form:"required" json:"required"`
}

SelectField defines "select" type field for storing single or multiple string values from a predefined list.

Requires the Values option to be set.

If MaxSelect is not set or <= 1, then the field value is expected to be a single Values element.

If MaxSelect is > 1, then the field value is expected to be a subset of Values slice.

The respective zero record field value is either empty string (single) or empty string slice (multiple).

---

The following additional setter keys are available:

  • "fieldName+" - append one or more values to the existing record one. For example:

    record.Set("roles+", []string{"new1", "new2"}) // []string{"old1", "old2", "new1", "new2"}

  • "+fieldName" - prepend one or more values to the existing record one. For example:

    record.Set("+roles", []string{"new1", "new2"}) // []string{"new1", "new2", "old1", "old2"}

  • "fieldName-" - subtract one or more values from the existing record one. For example:

    record.Set("roles-", "old1") // []string{"old2"}

func (*SelectField) ColumnType added in v0.23.0

func (f *SelectField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*SelectField) DriverValue added in v0.23.0

func (f *SelectField) DriverValue(record *Record) (driver.Value, error)

DriverValue implements the DriverValuer interface.

func (*SelectField) FindSetter added in v0.23.0

func (f *SelectField) FindSetter(key string) SetterFunc

FindSetter implements the SetterFinder interface.

func (*SelectField) GetHidden added in v0.23.0

func (f *SelectField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*SelectField) GetId added in v0.23.0

func (f *SelectField) GetId() string

GetId implements [Field.GetId] interface method.

func (*SelectField) GetName added in v0.23.0

func (f *SelectField) GetName() string

GetName implements [Field.GetName] interface method.

func (*SelectField) GetSystem added in v0.23.0

func (f *SelectField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*SelectField) IsMultiple added in v0.23.0

func (f *SelectField) IsMultiple() bool

IsMultiple implements MultiValuer interface and checks whether the current field options support multiple values.

func (*SelectField) PrepareValue added in v0.23.0

func (f *SelectField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*SelectField) SetHidden added in v0.23.0

func (f *SelectField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*SelectField) SetId added in v0.23.0

func (f *SelectField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*SelectField) SetName added in v0.23.0

func (f *SelectField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*SelectField) SetSystem added in v0.23.0

func (f *SelectField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*SelectField) Type added in v0.23.0

func (f *SelectField) Type() string

Type implements [Field.Type] interface method.

func (*SelectField) ValidateSettings added in v0.23.0

func (f *SelectField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*SelectField) ValidateValue added in v0.23.0

func (f *SelectField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type ServeEvent

type ServeEvent struct {
	hook.Event
	App         App
	Router      *router.Router[*RequestEvent]
	Server      *http.Server
	CertManager *autocert.Manager
}

type SetterFinder added in v0.23.0

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.

type SetterFunc added in v0.23.0

type SetterFunc func(record *Record, raw any)

type Settings

type Settings struct {
	// contains filtered or unexported fields
}

Settings defines the PocketBase app settings.

func (*Settings) Clone

func (s *Settings) Clone() (*Settings, error)

Clone creates a new deep copy of the current settings.

func (*Settings) DBExport added in v0.23.0

func (s *Settings) DBExport(app App) (map[string]any, error)

DBExport prepares and exports the current settings for db persistence.

func (*Settings) IsNew added in v0.23.0

func (s *Settings) IsNew() bool

IsNew implements [Model.IsNew] interface method.

func (*Settings) LastSavedPK added in v0.23.0

func (s *Settings) LastSavedPK() any

PK implements [Model.LastSavedPK] interface method.

func (*Settings) MarkAsNew added in v0.23.0

func (s *Settings) MarkAsNew()

MarkAsNew implements [Model.MarkAsNew] interface method.

func (*Settings) MarkAsNotNew added in v0.23.0

func (s *Settings) MarkAsNotNew()

MarkAsNew implements [Model.MarkAsNotNew] interface method.

func (*Settings) MarshalJSON added in v0.23.0

func (s *Settings) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

Note that sensitive fields (S3 secret, SMTP password, etc.) are excluded.

func (*Settings) Merge

func (s *Settings) Merge(other *Settings) error

Merge merges the "other" settings into the current one.

func (*Settings) PK added in v0.23.0

func (s *Settings) PK() any

PK implements [Model.PK] interface method.

func (*Settings) PostScan added in v0.23.0

func (s *Settings) PostScan() error

PostScan implements [Model.PostScan] interface method.

func (*Settings) PostValidate added in v0.23.0

func (s *Settings) PostValidate(ctx context.Context, app App) error

PostValidate implements the PostValidator interface and defines the Settings model validations.

func (*Settings) String added in v0.23.0

func (s *Settings) String() string

String returns a serialized string representation of the current settings.

func (*Settings) TableName added in v0.23.0

func (s *Settings) TableName() string

TableName implements [Model.TableName] interface method.

type SettingsListRequestEvent added in v0.23.0

type SettingsListRequestEvent struct {
	hook.Event
	*RequestEvent

	Settings *Settings
}

type SettingsReloadEvent added in v0.23.0

type SettingsReloadEvent struct {
	hook.Event
	App App
}

type SettingsUpdateRequestEvent added in v0.23.0

type SettingsUpdateRequestEvent struct {
	hook.Event
	*RequestEvent

	OldSettings *Settings
	NewSettings *Settings
}

type TableInfoRow added in v0.23.0

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"`
}

type TerminateEvent added in v0.16.0

type TerminateEvent struct {
	hook.Event
	App       App
	IsRestart bool
}

type TextField added in v0.23.0

type TextField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// Min specifies the minimum required string characters.
	//
	// if zero value, no min limit is applied.
	Min int `form:"min" json:"min"`

	// Max specifies the maximum allowed string characters.
	//
	// If zero, a default limit of 5000 is applied.
	Max int `form:"max" json:"max"`

	// Pattern specifies an optional regex pattern to match against the field value.
	//
	// Leave it empty to skip the pattern check.
	Pattern string `form:"pattern" json:"pattern"`

	// AutogeneratePattern specifies an optional regex pattern that could
	// be used to generate random string from it and set it automatically
	// on record create if no explicit value is set or when the `:autogenerate` modifier is used.
	//
	// Note: the generated value still needs to satisfy min, max, pattern (if set)
	AutogeneratePattern string `form:"autogeneratePattern" json:"autogeneratePattern"`

	// Required will require the field value to be non-empty string.
	Required bool `form:"required" json:"required"`

	// PrimaryKey will mark the field as primary key.
	//
	// A single collection can have only 1 field marked as primary key.
	PrimaryKey bool `form:"primaryKey" json:"primaryKey"`
}

TextField defines "text" type field for storing any string value.

The respective zero record field value is empty string.

The following additional setter keys are available:

- "fieldName:autogenerate" - autogenerate field value if AutogeneratePattern is set. For example:

record.Set("slug:autogenerate", "") // [random value]
record.Set("slug:autogenerate", "abc-") // abc-[random value]

func (*TextField) ColumnType added in v0.23.0

func (f *TextField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*TextField) FindSetter added in v0.23.0

func (f *TextField) FindSetter(key string) SetterFunc

FindSetter implements the SetterFinder interface.

func (*TextField) GetHidden added in v0.23.0

func (f *TextField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*TextField) GetId added in v0.23.0

func (f *TextField) GetId() string

GetId implements [Field.GetId] interface method.

func (*TextField) GetName added in v0.23.0

func (f *TextField) GetName() string

GetName implements [Field.GetName] interface method.

func (*TextField) GetSystem added in v0.23.0

func (f *TextField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*TextField) Intercept added in v0.23.0

func (f *TextField) Intercept(
	ctx context.Context,
	app App,
	record *Record,
	actionName string,
	actionFunc func() error,
) error

Intercept implements the RecordInterceptor interface.

func (*TextField) PrepareValue added in v0.23.0

func (f *TextField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*TextField) SetHidden added in v0.23.0

func (f *TextField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*TextField) SetId added in v0.23.0

func (f *TextField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*TextField) SetName added in v0.23.0

func (f *TextField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*TextField) SetSystem added in v0.23.0

func (f *TextField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*TextField) Type added in v0.23.0

func (f *TextField) Type() string

Type implements [Field.Type] interface method.

func (*TextField) ValidatePlainValue added in v0.23.0

func (f *TextField) ValidatePlainValue(value string) error

ValidatePlainValue validates the provided string against the field options.

func (*TextField) ValidateSettings added in v0.23.0

func (f *TextField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*TextField) ValidateValue added in v0.23.0

func (f *TextField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

type TokenConfig

type TokenConfig struct {
	Secret string `form:"secret" json:"secret,omitempty"`

	// Duration specifies how long an issued token to be valid (in seconds)
	Duration int64 `form:"duration" json:"duration"`
}

func (TokenConfig) DurationTime added in v0.23.0

func (c TokenConfig) DurationTime() time.Duration

DurationTime returns the current Duration as time.Duration.

func (TokenConfig) Validate

func (c TokenConfig) Validate() error

Validate makes TokenConfig validatable by implementing validation.Validatable interface.

type TrustedProxyConfig added in v0.23.0

type TrustedProxyConfig struct {
	// Headers is a list of explicit trusted header(s) to check.
	Headers []string `form:"headers" json:"headers"`

	// UseLeftmostIP specifies to use the left-mostish IP from the trusted headers.
	//
	// Note that this could be insecure when used with X-Forward-For header
	// because some proxies like AWS ELB allow users to prepend their own header value
	// before appending the trusted ones.
	UseLeftmostIP bool `form:"useLeftmostIP" json:"useLeftmostIP"`
}

func (TrustedProxyConfig) MarshalJSON added in v0.23.0

func (c TrustedProxyConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (TrustedProxyConfig) Validate added in v0.23.0

func (c TrustedProxyConfig) Validate() error

Validate makes RateLimitRule validatable by implementing validation.Validatable interface.

type URLField added in v0.23.0

type URLField struct {
	// Name (required) is the unique name of the field.
	Name string `form:"name" json:"name"`

	// Id is the unique stable field identifier.
	//
	// It is automatically generated from the name when adding to a collection FieldsList.
	Id string `form:"id" json:"id"`

	// System prevents the renaming and removal of the field.
	System bool `form:"system" json:"system"`

	// Hidden hides the field from the API response.
	Hidden bool `form:"hidden" json:"hidden"`

	// Presentable hints the Dashboard UI to use the underlying
	// field record value in the relation preview label.
	Presentable bool `form:"presentable" json:"presentable"`

	// ExceptDomains will require the URL domain to NOT be included in the listed ones.
	//
	// This validator can be set only if OnlyDomains is empty.
	ExceptDomains []string `form:"exceptDomains" json:"exceptDomains"`

	// OnlyDomains will require the URL domain to be included in the listed ones.
	//
	// This validator can be set only if ExceptDomains is empty.
	OnlyDomains []string `form:"onlyDomains" json:"onlyDomains"`

	// Required will require the field value to be non-empty URL string.
	Required bool `form:"required" json:"required"`
}

URLField defines "url" type field for storing a single URL string value.

The respective zero record field value is empty string.

func (*URLField) ColumnType added in v0.23.0

func (f *URLField) ColumnType(app App) string

ColumnType implements [Field.ColumnType] interface method.

func (*URLField) GetHidden added in v0.23.0

func (f *URLField) GetHidden() bool

GetHidden implements [Field.GetHidden] interface method.

func (*URLField) GetId added in v0.23.0

func (f *URLField) GetId() string

GetId implements [Field.GetId] interface method.

func (*URLField) GetName added in v0.23.0

func (f *URLField) GetName() string

GetName implements [Field.GetName] interface method.

func (*URLField) GetSystem added in v0.23.0

func (f *URLField) GetSystem() bool

GetSystem implements [Field.GetSystem] interface method.

func (*URLField) PrepareValue added in v0.23.0

func (f *URLField) PrepareValue(record *Record, raw any) (any, error)

PrepareValue implements [Field.PrepareValue] interface method.

func (*URLField) SetHidden added in v0.23.0

func (f *URLField) SetHidden(hidden bool)

SetHidden implements [Field.SetHidden] interface method.

func (*URLField) SetId added in v0.23.0

func (f *URLField) SetId(id string)

SetId implements [Field.SetId] interface method.

func (*URLField) SetName added in v0.23.0

func (f *URLField) SetName(name string)

SetName implements [Field.SetName] interface method.

func (*URLField) SetSystem added in v0.23.0

func (f *URLField) SetSystem(system bool)

SetSystem implements [Field.SetSystem] interface method.

func (*URLField) Type added in v0.23.0

func (f *URLField) Type() string

Type implements [Field.Type] interface method.

func (*URLField) ValidateSettings added in v0.23.0

func (f *URLField) ValidateSettings(ctx context.Context, app App, collection *Collection) error

ValidateSettings implements [Field.ValidateSettings] interface method.

func (*URLField) ValidateValue added in v0.23.0

func (f *URLField) ValidateValue(ctx context.Context, app App, record *Record) error

ValidateValue implements [Field.ValidateValue] interface method.

Directories

Path Synopsis
Package validators implements some common custom PocketBase validators.
Package validators implements some common custom PocketBase validators.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL