Documentation ¶
Overview ¶
Package core is the backbone of PocketBase.
It defines the main PocketBase App interface and its base implementation.
Index ¶
- Constants
- Variables
- func DefaultDBConnect(dbPath string) (*dbx.DB, error)
- func DefaultFieldIdValidationRule(value any) error
- func DefaultFieldNameValidationRule(value any) error
- func GenerateDefaultRandomId() string
- type App
- type AuthAlertConfig
- type AuthOrigin
- func (m *AuthOrigin) CollectionRef() string
- func (m *AuthOrigin) Created() types.DateTime
- func (m *AuthOrigin) Fingerprint() string
- func (m *AuthOrigin) PreValidate(ctx context.Context, app App) error
- func (m *AuthOrigin) ProxyRecord() *Record
- func (m *AuthOrigin) RecordRef() string
- func (m *AuthOrigin) SetCollectionRef(collectionId string)
- func (m *AuthOrigin) SetFingerprint(fingerprint string)
- func (m *AuthOrigin) SetProxyRecord(record *Record)
- func (m *AuthOrigin) SetRecordRef(recordId string)
- func (m *AuthOrigin) Updated() types.DateTime
- type AutodateField
- func (f *AutodateField) ColumnType(app App) string
- func (f *AutodateField) FindSetter(key string) SetterFunc
- func (f *AutodateField) GetHidden() bool
- func (f *AutodateField) GetId() string
- func (f *AutodateField) GetName() string
- func (f *AutodateField) GetSystem() bool
- func (f *AutodateField) Intercept(ctx context.Context, app App, record *Record, actionName string, ...) error
- func (f *AutodateField) PrepareValue(record *Record, raw any) (any, error)
- func (f *AutodateField) SetHidden(hidden bool)
- func (f *AutodateField) SetId(id string)
- func (f *AutodateField) SetName(name string)
- func (f *AutodateField) SetSystem(system bool)
- func (f *AutodateField) Type() string
- func (f *AutodateField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *AutodateField) ValidateValue(ctx context.Context, app App, record *Record) error
- type BackupEvent
- type BackupsConfig
- type BaseApp
- func (app *BaseApp) AuxDB() dbx.Builder
- func (app *BaseApp) AuxDelete(model Model) error
- func (app *BaseApp) AuxDeleteWithContext(ctx context.Context, model Model) error
- func (app *BaseApp) AuxHasTable(tableName string) bool
- func (app *BaseApp) AuxModelQuery(m Model) *dbx.SelectQuery
- func (app *BaseApp) AuxNonconcurrentDB() dbx.Builder
- func (app *BaseApp) AuxRunInTransaction(fn func(txApp App) error) error
- func (app *BaseApp) AuxSave(model Model) error
- func (app *BaseApp) AuxSaveNoValidate(model Model) error
- func (app *BaseApp) AuxSaveNoValidateWithContext(ctx context.Context, model Model) error
- func (app *BaseApp) AuxSaveWithContext(ctx context.Context, model Model) error
- func (app *BaseApp) AuxVacuum() error
- func (app *BaseApp) Bootstrap() error
- func (app *BaseApp) CanAccessRecord(record *Record, requestInfo *RequestInfo, accessRule *string) (bool, error)
- func (app *BaseApp) CollectionQuery() *dbx.SelectQuery
- func (app *BaseApp) CountRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) (int64, error)
- func (app *BaseApp) CreateBackup(ctx context.Context, name string) error
- func (app *BaseApp) CreateViewFields(selectQuery string) (FieldsList, error)
- func (app *BaseApp) Cron() *cron.Cron
- func (app *BaseApp) DB() dbx.Builder
- func (app *BaseApp) DataDir() string
- func (app *BaseApp) Delete(model Model) error
- func (app *BaseApp) DeleteAllAuthOriginsByRecord(authRecord *Record) error
- func (app *BaseApp) DeleteAllMFAsByRecord(authRecord *Record) error
- func (app *BaseApp) DeleteAllOTPsByRecord(authRecord *Record) error
- func (app *BaseApp) DeleteExpiredMFAs() error
- func (app *BaseApp) DeleteExpiredOTPs() error
- func (app *BaseApp) DeleteOldLogs(createdBefore time.Time) error
- func (app *BaseApp) DeleteTable(tableName string) error
- func (app *BaseApp) DeleteView(name string) error
- func (app *BaseApp) DeleteWithContext(ctx context.Context, model Model) error
- func (app *BaseApp) EncryptionEnv() string
- func (app *BaseApp) ExpandRecord(record *Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
- func (app *BaseApp) ExpandRecords(records []*Record, expands []string, optFetchFunc ExpandFetchFunc) map[string]error
- func (app *BaseApp) FindAllAuthOriginsByCollection(collection *Collection) ([]*AuthOrigin, error)
- func (app *BaseApp) FindAllAuthOriginsByRecord(authRecord *Record) ([]*AuthOrigin, error)
- func (app *BaseApp) FindAllCollections(collectionTypes ...string) ([]*Collection, error)
- func (app *BaseApp) FindAllExternalAuthsByCollection(collection *Collection) ([]*ExternalAuth, error)
- func (app *BaseApp) FindAllExternalAuthsByRecord(authRecord *Record) ([]*ExternalAuth, error)
- func (app *BaseApp) FindAllMFAsByCollection(collection *Collection) ([]*MFA, error)
- func (app *BaseApp) FindAllMFAsByRecord(authRecord *Record) ([]*MFA, error)
- func (app *BaseApp) FindAllOTPsByCollection(collection *Collection) ([]*OTP, error)
- func (app *BaseApp) FindAllOTPsByRecord(authRecord *Record) ([]*OTP, error)
- func (app *BaseApp) FindAllRecords(collectionModelOrIdentifier any, exprs ...dbx.Expression) ([]*Record, error)
- func (app *BaseApp) FindAuthOriginById(id string) (*AuthOrigin, error)
- func (app *BaseApp) FindAuthOriginByRecordAndFingerprint(authRecord *Record, fingerprint string) (*AuthOrigin, error)
- func (app *BaseApp) FindAuthRecordByEmail(collectionModelOrIdentifier any, email string) (*Record, error)
- func (app *BaseApp) FindAuthRecordByToken(token string, validTypes ...string) (*Record, error)
- func (app *BaseApp) FindCachedCollectionByNameOrId(nameOrId string) (*Collection, error)
- func (app *BaseApp) FindCollectionByNameOrId(nameOrId string) (*Collection, error)
- func (app *BaseApp) FindCollectionReferences(collection *Collection, excludeIds ...string) (map[*Collection][]Field, error)
- func (app *BaseApp) FindFirstExternalAuthByExpr(expr dbx.Expression) (*ExternalAuth, error)
- func (app *BaseApp) FindFirstRecordByData(collectionModelOrIdentifier any, key string, value any) (*Record, error)
- func (app *BaseApp) FindFirstRecordByFilter(collectionModelOrIdentifier any, filter string, params ...dbx.Params) (*Record, error)
- func (app *BaseApp) FindLogById(id string) (*Log, error)
- func (app *BaseApp) FindMFAById(id string) (*MFA, error)
- func (app *BaseApp) FindOTPById(id string) (*OTP, error)
- func (app *BaseApp) FindRecordById(collectionModelOrIdentifier any, recordId string, ...) (*Record, error)
- func (app *BaseApp) FindRecordByViewFile(viewCollectionModelOrIdentifier any, fileFieldName string, filename string) (*Record, error)
- func (app *BaseApp) FindRecordsByFilter(collectionModelOrIdentifier any, filter string, sort string, limit int, ...) ([]*Record, error)
- func (app *BaseApp) FindRecordsByIds(collectionModelOrIdentifier any, recordIds []string, ...) ([]*Record, error)
- func (app *BaseApp) HasTable(tableName string) bool
- func (app *BaseApp) ImportCollections(toImport []map[string]any, deleteMissing bool) error
- func (app *BaseApp) ImportCollectionsByMarshaledJSON(rawSliceOfMaps []byte, deleteMissing bool) error
- func (app *BaseApp) IsBootstrapped() bool
- func (app *BaseApp) IsCollectionNameUnique(name string, excludeIds ...string) bool
- func (app *BaseApp) IsDev() bool
- func (app *BaseApp) IsTransactional() bool
- func (app *BaseApp) LogQuery() *dbx.SelectQuery
- func (app *BaseApp) Logger() *slog.Logger
- func (app *BaseApp) LogsStats(expr dbx.Expression) ([]*LogsStatsItem, error)
- func (app *BaseApp) ModelQuery(m Model) *dbx.SelectQuery
- func (app *BaseApp) NewBackupsFilesystem() (*filesystem.System, error)
- func (app *BaseApp) NewFilesystem() (*filesystem.System, error)
- func (app *BaseApp) NewMailClient() mailer.Mailer
- func (app *BaseApp) NonconcurrentDB() dbx.Builder
- func (app *BaseApp) OnBackupCreate() *hook.Hook[*BackupEvent]
- func (app *BaseApp) OnBackupRestore() *hook.Hook[*BackupEvent]
- func (app *BaseApp) OnBatchRequest() *hook.Hook[*BatchRequestEvent]
- func (app *BaseApp) OnBootstrap() *hook.Hook[*BootstrapEvent]
- func (app *BaseApp) OnCollectionAfterCreateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
- func (app *BaseApp) OnCollectionAfterCreateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionAfterDeleteError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
- func (app *BaseApp) OnCollectionAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionAfterUpdateError(tags ...string) *hook.TaggedHook[*CollectionErrorEvent]
- func (app *BaseApp) OnCollectionAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionCreate(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionCreateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionCreateRequest() *hook.Hook[*CollectionRequestEvent]
- func (app *BaseApp) OnCollectionDelete(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionDeleteExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionDeleteRequest() *hook.Hook[*CollectionRequestEvent]
- func (app *BaseApp) OnCollectionUpdate(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionUpdateExecute(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionUpdateRequest() *hook.Hook[*CollectionRequestEvent]
- func (app *BaseApp) OnCollectionValidate(tags ...string) *hook.TaggedHook[*CollectionEvent]
- func (app *BaseApp) OnCollectionViewRequest() *hook.Hook[*CollectionRequestEvent]
- func (app *BaseApp) OnCollectionsImportRequest() *hook.Hook[*CollectionsImportRequestEvent]
- func (app *BaseApp) OnCollectionsListRequest() *hook.Hook[*CollectionsListRequestEvent]
- func (app *BaseApp) OnFileDownloadRequest(tags ...string) *hook.TaggedHook[*FileDownloadRequestEvent]
- func (app *BaseApp) OnFileTokenRequest(tags ...string) *hook.TaggedHook[*FileTokenRequestEvent]
- func (app *BaseApp) OnMailerRecordAuthAlertSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
- func (app *BaseApp) OnMailerRecordEmailChangeSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
- func (app *BaseApp) OnMailerRecordOTPSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
- func (app *BaseApp) OnMailerRecordPasswordResetSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
- func (app *BaseApp) OnMailerRecordVerificationSend(tags ...string) *hook.TaggedHook[*MailerRecordEvent]
- func (app *BaseApp) OnMailerSend() *hook.Hook[*MailerEvent]
- func (app *BaseApp) OnModelAfterCreateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
- func (app *BaseApp) OnModelAfterCreateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelAfterDeleteError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
- func (app *BaseApp) OnModelAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelAfterUpdateError(tags ...string) *hook.TaggedHook[*ModelErrorEvent]
- func (app *BaseApp) OnModelAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelCreate(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelCreateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelDelete(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelDeleteExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelUpdate(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelUpdateExecute(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnModelValidate(tags ...string) *hook.TaggedHook[*ModelEvent]
- func (app *BaseApp) OnRealtimeConnectRequest() *hook.Hook[*RealtimeConnectRequestEvent]
- func (app *BaseApp) OnRealtimeMessageSend() *hook.Hook[*RealtimeMessageEvent]
- func (app *BaseApp) OnRealtimeSubscribeRequest() *hook.Hook[*RealtimeSubscribeRequestEvent]
- func (app *BaseApp) OnRecordAfterCreateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
- func (app *BaseApp) OnRecordAfterCreateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordAfterDeleteError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
- func (app *BaseApp) OnRecordAfterDeleteSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordAfterUpdateError(tags ...string) *hook.TaggedHook[*RecordErrorEvent]
- func (app *BaseApp) OnRecordAfterUpdateSuccess(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordAuthRefreshRequest(tags ...string) *hook.TaggedHook[*RecordAuthRefreshRequestEvent]
- func (app *BaseApp) OnRecordAuthRequest(tags ...string) *hook.TaggedHook[*RecordAuthRequestEvent]
- func (app *BaseApp) OnRecordAuthWithOAuth2Request(tags ...string) *hook.TaggedHook[*RecordAuthWithOAuth2RequestEvent]
- func (app *BaseApp) OnRecordAuthWithOTPRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithOTPRequestEvent]
- func (app *BaseApp) OnRecordAuthWithPasswordRequest(tags ...string) *hook.TaggedHook[*RecordAuthWithPasswordRequestEvent]
- func (app *BaseApp) OnRecordConfirmEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordConfirmEmailChangeRequestEvent]
- func (app *BaseApp) OnRecordConfirmPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordConfirmPasswordResetRequestEvent]
- func (app *BaseApp) OnRecordConfirmVerificationRequest(tags ...string) *hook.TaggedHook[*RecordConfirmVerificationRequestEvent]
- func (app *BaseApp) OnRecordCreate(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordCreateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordCreateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
- func (app *BaseApp) OnRecordDelete(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordDeleteExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordDeleteRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
- func (app *BaseApp) OnRecordEnrich(tags ...string) *hook.TaggedHook[*RecordEnrichEvent]
- func (app *BaseApp) OnRecordRequestEmailChangeRequest(tags ...string) *hook.TaggedHook[*RecordRequestEmailChangeRequestEvent]
- func (app *BaseApp) OnRecordRequestOTPRequest(tags ...string) *hook.TaggedHook[*RecordCreateOTPRequestEvent]
- func (app *BaseApp) OnRecordRequestPasswordResetRequest(tags ...string) *hook.TaggedHook[*RecordRequestPasswordResetRequestEvent]
- func (app *BaseApp) OnRecordRequestVerificationRequest(tags ...string) *hook.TaggedHook[*RecordRequestVerificationRequestEvent]
- func (app *BaseApp) OnRecordUpdate(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordUpdateExecute(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordUpdateRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
- func (app *BaseApp) OnRecordValidate(tags ...string) *hook.TaggedHook[*RecordEvent]
- func (app *BaseApp) OnRecordViewRequest(tags ...string) *hook.TaggedHook[*RecordRequestEvent]
- func (app *BaseApp) OnRecordsListRequest(tags ...string) *hook.TaggedHook[*RecordsListRequestEvent]
- func (app *BaseApp) OnServe() *hook.Hook[*ServeEvent]
- func (app *BaseApp) OnSettingsListRequest() *hook.Hook[*SettingsListRequestEvent]
- func (app *BaseApp) OnSettingsReload() *hook.Hook[*SettingsReloadEvent]
- func (app *BaseApp) OnSettingsUpdateRequest() *hook.Hook[*SettingsUpdateRequestEvent]
- func (app *BaseApp) OnTerminate() *hook.Hook[*TerminateEvent]
- func (app *BaseApp) RecordQuery(collectionModelOrIdentifier any) *dbx.SelectQuery
- func (app *BaseApp) ReloadCachedCollections() error
- func (app *BaseApp) ReloadSettings() error
- func (app *BaseApp) ResetBootstrapState() error
- func (app *BaseApp) Restart() error
- func (app *BaseApp) RestoreBackup(ctx context.Context, name string) error
- func (app *BaseApp) RunAllMigrations() error
- func (app *BaseApp) RunAppMigrations() error
- func (app *BaseApp) RunInTransaction(fn func(txApp App) error) error
- func (app *BaseApp) RunSystemMigrations() error
- func (app *BaseApp) Save(model Model) error
- func (app *BaseApp) SaveNoValidate(model Model) error
- func (app *BaseApp) SaveNoValidateWithContext(ctx context.Context, model Model) error
- func (app *BaseApp) SaveView(name string, selectQuery string) error
- func (app *BaseApp) SaveWithContext(ctx context.Context, model Model) error
- func (app *BaseApp) Settings() *Settings
- func (app *BaseApp) Store() *store.Store[any]
- func (app *BaseApp) SubscriptionsBroker() *subscriptions.Broker
- func (app *BaseApp) SyncRecordTableSchema(newCollection *Collection, oldCollection *Collection) error
- func (app *BaseApp) TableColumns(tableName string) ([]string, error)
- func (app *BaseApp) TableIndexes(tableName string) (map[string]string, error)
- func (app *BaseApp) TableInfo(tableName string) ([]*TableInfoRow, error)
- func (app *BaseApp) TruncateCollection(collection *Collection) error
- func (app *BaseApp) UnsafeWithoutHooks() App
- func (app *BaseApp) Vacuum() error
- func (app *BaseApp) Validate(model Model) error
- func (app *BaseApp) ValidateWithContext(ctx context.Context, model Model) error
- type BaseAppConfig
- type BaseModel
- type BaseRecordProxy
- type BatchConfig
- type BatchRequestEvent
- type BoolField
- func (f *BoolField) ColumnType(app App) string
- func (f *BoolField) GetHidden() bool
- func (f *BoolField) GetId() string
- func (f *BoolField) GetName() string
- func (f *BoolField) GetSystem() bool
- func (f *BoolField) PrepareValue(record *Record, raw any) (any, error)
- func (f *BoolField) SetHidden(hidden bool)
- func (f *BoolField) SetId(id string)
- func (f *BoolField) SetName(name string)
- func (f *BoolField) SetSystem(system bool)
- func (f *BoolField) Type() string
- func (f *BoolField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *BoolField) ValidateValue(ctx context.Context, app App, record *Record) error
- type BootstrapEvent
- type Collection
- func (m *Collection) AddIndex(name string, unique bool, columnsExpr string, optWhereExpr string)
- func (m *Collection) BaseFilesPath() string
- func (m *Collection) DBExport(app App) (map[string]any, error)
- func (m *Collection) GetIndex(name string) string
- func (m *Collection) IntegrityChecks(enable bool)
- func (m *Collection) IsAuth() bool
- func (m *Collection) IsBase() bool
- func (m *Collection) IsView() bool
- func (m Collection) MarshalJSON() ([]byte, error)
- func (m *Collection) PostScan() error
- func (m *Collection) RemoveIndex(name string)
- func (m Collection) String() string
- func (m *Collection) TableName() string
- func (m *Collection) UnmarshalJSON(b []byte) error
- type CollectionErrorEvent
- type CollectionEvent
- type CollectionRequestEvent
- type CollectionsImportRequestEvent
- type CollectionsListRequestEvent
- type DBConnectFunc
- type DBExporter
- type DateField
- func (f *DateField) ColumnType(app App) string
- func (f *DateField) GetHidden() bool
- func (f *DateField) GetId() string
- func (f *DateField) GetName() string
- func (f *DateField) GetSystem() bool
- func (f *DateField) PrepareValue(record *Record, raw any) (any, error)
- func (f *DateField) SetHidden(hidden bool)
- func (f *DateField) SetId(id string)
- func (f *DateField) SetName(name string)
- func (f *DateField) SetSystem(system bool)
- func (f *DateField) Type() string
- func (f *DateField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *DateField) ValidateValue(ctx context.Context, app App, record *Record) error
- type DriverValuer
- type EditorField
- func (f *EditorField) CalculateMaxBodySize() int64
- func (f *EditorField) ColumnType(app App) string
- func (f *EditorField) GetHidden() bool
- func (f *EditorField) GetId() string
- func (f *EditorField) GetName() string
- func (f *EditorField) GetSystem() bool
- func (f *EditorField) PrepareValue(record *Record, raw any) (any, error)
- func (f *EditorField) SetHidden(hidden bool)
- func (f *EditorField) SetId(id string)
- func (f *EditorField) SetName(name string)
- func (f *EditorField) SetSystem(system bool)
- func (f *EditorField) Type() string
- func (f *EditorField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *EditorField) ValidateValue(ctx context.Context, app App, record *Record) error
- type EmailField
- func (f *EmailField) ColumnType(app App) string
- func (f *EmailField) GetHidden() bool
- func (f *EmailField) GetId() string
- func (f *EmailField) GetName() string
- func (f *EmailField) GetSystem() bool
- func (f *EmailField) PrepareValue(record *Record, raw any) (any, error)
- func (f *EmailField) SetHidden(hidden bool)
- func (f *EmailField) SetId(id string)
- func (f *EmailField) SetName(name string)
- func (f *EmailField) SetSystem(system bool)
- func (f *EmailField) Type() string
- func (f *EmailField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *EmailField) ValidateValue(ctx context.Context, app App, record *Record) error
- type EmailTemplate
- type ExpandFetchFunc
- type ExternalAuth
- func (m *ExternalAuth) CollectionRef() string
- func (m *ExternalAuth) Created() types.DateTime
- func (m *ExternalAuth) PreValidate(ctx context.Context, app App) error
- func (m *ExternalAuth) Provider() string
- func (m *ExternalAuth) ProviderId() string
- func (m *ExternalAuth) ProxyRecord() *Record
- func (m *ExternalAuth) RecordRef() string
- func (m *ExternalAuth) SetCollectionRef(collectionId string)
- func (m *ExternalAuth) SetProvider(provider string)
- func (m *ExternalAuth) SetProviderId(providerId string)
- func (m *ExternalAuth) SetProxyRecord(record *Record)
- func (m *ExternalAuth) SetRecordRef(recordId string)
- func (m *ExternalAuth) Updated() types.DateTime
- type Field
- type FieldFactoryFunc
- type FieldsList
- func (l *FieldsList) Add(fields ...Field)
- func (l *FieldsList) AddAt(pos int, fields ...Field)
- func (l *FieldsList) AddMarshaledJSON(rawJSON []byte) error
- func (l *FieldsList) AddMarshaledJSONAt(pos int, rawJSON []byte) error
- func (l FieldsList) AsMap() map[string]Field
- func (l FieldsList) Clone() (FieldsList, error)
- func (l FieldsList) FieldNames() []string
- func (l FieldsList) GetById(fieldId string) Field
- func (l FieldsList) GetByName(fieldName string) Field
- func (l FieldsList) MarshalJSON() ([]byte, error)
- func (l *FieldsList) RemoveById(fieldId string)
- func (l *FieldsList) RemoveByName(fieldName string)
- func (l *FieldsList) Scan(value any) error
- func (l FieldsList) String() string
- func (l *FieldsList) UnmarshalJSON(data []byte) error
- func (l FieldsList) Value() (driver.Value, error)
- type FileDownloadRequestEvent
- type FileField
- func (f *FileField) CalculateMaxBodySize() int64
- func (f *FileField) ColumnType(app App) string
- func (f *FileField) DriverValue(record *Record) (driver.Value, error)
- func (f *FileField) FindGetter(key string) GetterFunc
- func (f *FileField) FindSetter(key string) SetterFunc
- func (f *FileField) GetHidden() bool
- func (f *FileField) GetId() string
- func (f *FileField) GetName() string
- func (f *FileField) GetSystem() bool
- func (f *FileField) Intercept(ctx context.Context, app App, record *Record, actionName string, ...) error
- func (f *FileField) IsMultiple() bool
- func (f *FileField) PrepareValue(record *Record, raw any) (any, error)
- func (f *FileField) SetHidden(hidden bool)
- func (f *FileField) SetId(id string)
- func (f *FileField) SetName(name string)
- func (f *FileField) SetSystem(system bool)
- func (f *FileField) Type() string
- func (f *FileField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *FileField) ValidateValue(ctx context.Context, app App, record *Record) error
- type FileTokenRequestEvent
- type FilesManager
- type GetterFinder
- type GetterFunc
- type HookTagger
- type InternalRequest
- type JSONField
- func (f *JSONField) CalculateMaxBodySize() int64
- func (f *JSONField) ColumnType(app App) string
- func (f *JSONField) GetHidden() bool
- func (f *JSONField) GetId() string
- func (f *JSONField) GetName() string
- func (f *JSONField) GetSystem() bool
- func (f *JSONField) PrepareValue(record *Record, raw any) (any, error)
- func (f *JSONField) SetHidden(hidden bool)
- func (f *JSONField) SetId(id string)
- func (f *JSONField) SetName(name string)
- func (f *JSONField) SetSystem(system bool)
- func (f *JSONField) Type() string
- func (f *JSONField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *JSONField) ValidateValue(ctx context.Context, app App, record *Record) error
- type Log
- type LogsConfig
- type LogsStatsItem
- type MFA
- func (m *MFA) CollectionRef() string
- func (m *MFA) Created() types.DateTime
- func (m *MFA) HasExpired(maxElapsed time.Duration) bool
- func (m *MFA) Method() string
- func (m *MFA) PreValidate(ctx context.Context, app App) error
- func (m *MFA) ProxyRecord() *Record
- func (m *MFA) RecordRef() string
- func (m *MFA) SetCollectionRef(collectionId string)
- func (m *MFA) SetMethod(method string)
- func (m *MFA) SetProxyRecord(record *Record)
- func (m *MFA) SetRecordRef(recordId string)
- func (m *MFA) Updated() types.DateTime
- type MFAConfig
- type MailerEvent
- type MailerRecordEvent
- type MaxBodySizeCalculator
- type MetaConfig
- type Migration
- type MigrationsList
- func (l *MigrationsList) Add(m *Migration)
- func (l *MigrationsList) Copy(list MigrationsList)
- func (l *MigrationsList) Item(index int) *Migration
- func (l *MigrationsList) Items() []*Migration
- func (l *MigrationsList) Register(up func(txApp App) error, down func(txApp App) error, optFilename ...string)
- type MigrationsRunner
- type Model
- type ModelErrorEvent
- type ModelEvent
- type MultiValuer
- type NumberField
- func (f *NumberField) ColumnType(app App) string
- func (f *NumberField) FindSetter(key string) SetterFunc
- func (f *NumberField) GetHidden() bool
- func (f *NumberField) GetId() string
- func (f *NumberField) GetName() string
- func (f *NumberField) GetSystem() bool
- func (f *NumberField) PrepareValue(record *Record, raw any) (any, error)
- func (f *NumberField) SetHidden(hidden bool)
- func (f *NumberField) SetId(id string)
- func (f *NumberField) SetName(name string)
- func (f *NumberField) SetSystem(system bool)
- func (f *NumberField) Type() string
- func (f *NumberField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *NumberField) ValidateValue(ctx context.Context, app App, record *Record) error
- type OAuth2Config
- type OAuth2KnownFields
- type OAuth2ProviderConfig
- type OTP
- func (m *OTP) CollectionRef() string
- func (m *OTP) Created() types.DateTime
- func (m *OTP) HasExpired(maxElapsed time.Duration) bool
- func (m *OTP) PreValidate(ctx context.Context, app App) error
- func (m *OTP) ProxyRecord() *Record
- func (m *OTP) RecordRef() string
- func (m *OTP) SentTo() string
- func (m *OTP) SetCollectionRef(collectionId string)
- func (m *OTP) SetProxyRecord(record *Record)
- func (m *OTP) SetRecordRef(recordId string)
- func (m *OTP) SetSentTo(val string)
- func (m *OTP) Updated() types.DateTime
- type OTPConfig
- type Param
- type PasswordAuthConfig
- type PasswordField
- func (f *PasswordField) ColumnType(app App) string
- func (f *PasswordField) DriverValue(record *Record) (driver.Value, error)
- func (f *PasswordField) FindGetter(key string) GetterFunc
- func (f *PasswordField) FindSetter(key string) SetterFunc
- func (f *PasswordField) GetHidden() bool
- func (f *PasswordField) GetId() string
- func (f *PasswordField) GetName() string
- func (f *PasswordField) GetSystem() bool
- func (f *PasswordField) Intercept(ctx context.Context, app App, record *Record, actionName string, ...) error
- func (f *PasswordField) PrepareValue(record *Record, raw any) (any, error)
- func (f *PasswordField) SetHidden(hidden bool)
- func (f *PasswordField) SetId(id string)
- func (f *PasswordField) SetName(name string)
- func (f *PasswordField) SetSystem(system bool)
- func (f *PasswordField) Type() string
- func (f *PasswordField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *PasswordField) ValidateValue(ctx context.Context, app App, record *Record) error
- type PasswordFieldValue
- type PostValidator
- type PreValidator
- type RateLimitRule
- type RateLimitsConfig
- type RealtimeConnectRequestEvent
- type RealtimeMessageEvent
- type RealtimeSubscribeRequestEvent
- type Record
- func (m *Record) BaseFilesPath() string
- func (m *Record) Clone() *Record
- func (m *Record) Collection() *Collection
- func (m *Record) CustomData() map[string]any
- func (m *Record) DBExport(app App) (map[string]any, error)
- func (m *Record) Email() string
- func (m *Record) EmailVisibility() bool
- func (m *Record) Expand() map[string]any
- func (m *Record) ExpandedAll(relField string) []*Record
- func (m *Record) ExpandedOne(relField string) *Record
- func (m *Record) FieldsData() map[string]any
- func (m *Record) FindFileFieldByFile(filename string) *FileField
- func (m *Record) Fresh() *Record
- func (m *Record) Get(key string) any
- func (m *Record) GetBool(key string) bool
- func (m *Record) GetDateTime(key string) types.DateTime
- func (m *Record) GetFloat(key string) float64
- func (m *Record) GetInt(key string) int
- func (m *Record) GetRaw(key string) any
- func (m *Record) GetString(key string) string
- func (m *Record) GetStringSlice(key string) []string
- func (m *Record) GetUploadedFiles(key string) []*filesystem.File
- func (record *Record) Hide(fieldNames ...string) *Record
- func (m *Record) HookTags() []string
- func (m *Record) IgnoreEmailVisibility(state bool) *Record
- func (m *Record) IgnoreUnchangedFields(state bool) *Record
- func (m *Record) IsSuperuser() bool
- func (m *Record) Load(data map[string]any)
- func (m Record) MarshalJSON() ([]byte, error)
- func (m *Record) MergeExpand(expand map[string]any)
- func (m *Record) NewAuthToken() (string, error)
- func (m *Record) NewEmailChangeToken(newEmail string) (string, error)
- func (m *Record) NewFileToken() (string, error)
- func (m *Record) NewPasswordResetToken() (string, error)
- func (m *Record) NewStaticAuthToken(duration time.Duration) (string, error)
- func (m *Record) NewVerificationToken() (string, error)
- func (m *Record) Original() *Record
- func (m *Record) PostScan() error
- func (record *Record) PublicExport() map[string]any
- func (m *Record) RefreshTokenKey()
- func (m *Record) ReplaceModifiers(data map[string]any) map[string]any
- func (m *Record) Set(key string, value any)
- func (m *Record) SetEmail(email string)
- func (m *Record) SetEmailVisibility(visible bool)
- func (m *Record) SetExpand(expand map[string]any)
- func (m *Record) SetIfFieldExists(key string, value any) Field
- func (m *Record) SetPassword(password string)
- func (m *Record) SetRaw(key string, value any)
- func (m *Record) SetTokenKey(key string)
- func (m *Record) SetVerified(verified bool)
- func (m *Record) TableName() string
- func (m *Record) TokenKey() string
- func (record *Record) Unhide(fieldNames ...string) *Record
- func (m *Record) UnmarshalJSON(data []byte) error
- func (m *Record) UnmarshalJSONField(key string, result any) error
- func (m *Record) ValidatePassword(password string) bool
- func (m *Record) Verified() bool
- func (m *Record) WithCustomData(state bool) *Record
- type RecordAuthRefreshRequestEvent
- type RecordAuthRequestEvent
- type RecordAuthWithOAuth2RequestEvent
- type RecordAuthWithOTPRequestEvent
- type RecordAuthWithPasswordRequestEvent
- type RecordConfirmEmailChangeRequestEvent
- type RecordConfirmPasswordResetRequestEvent
- type RecordConfirmVerificationRequestEvent
- type RecordCreateOTPRequestEvent
- type RecordEnrichEvent
- type RecordErrorEvent
- type RecordEvent
- type RecordFieldResolver
- type RecordInterceptor
- type RecordProxy
- type RecordRequestEmailChangeRequestEvent
- type RecordRequestEvent
- type RecordRequestPasswordResetRequestEvent
- type RecordRequestVerificationRequestEvent
- type RecordsListRequestEvent
- type RelationField
- func (f *RelationField) ColumnType(app App) string
- func (f *RelationField) DriverValue(record *Record) (driver.Value, error)
- func (f *RelationField) FindSetter(key string) SetterFunc
- func (f *RelationField) GetHidden() bool
- func (f *RelationField) GetId() string
- func (f *RelationField) GetName() string
- func (f *RelationField) GetSystem() bool
- func (f *RelationField) IsMultiple() bool
- func (f *RelationField) PrepareValue(record *Record, raw any) (any, error)
- func (f *RelationField) SetHidden(hidden bool)
- func (f *RelationField) SetId(id string)
- func (f *RelationField) SetName(name string)
- func (f *RelationField) SetSystem(system bool)
- func (f *RelationField) Type() string
- func (f *RelationField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *RelationField) ValidateValue(ctx context.Context, app App, record *Record) error
- type RequestEvent
- type RequestInfo
- type S3Config
- type SMTPConfig
- type SelectField
- func (f *SelectField) ColumnType(app App) string
- func (f *SelectField) DriverValue(record *Record) (driver.Value, error)
- func (f *SelectField) FindSetter(key string) SetterFunc
- func (f *SelectField) GetHidden() bool
- func (f *SelectField) GetId() string
- func (f *SelectField) GetName() string
- func (f *SelectField) GetSystem() bool
- func (f *SelectField) IsMultiple() bool
- func (f *SelectField) PrepareValue(record *Record, raw any) (any, error)
- func (f *SelectField) SetHidden(hidden bool)
- func (f *SelectField) SetId(id string)
- func (f *SelectField) SetName(name string)
- func (f *SelectField) SetSystem(system bool)
- func (f *SelectField) Type() string
- func (f *SelectField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *SelectField) ValidateValue(ctx context.Context, app App, record *Record) error
- type ServeEvent
- type SetterFinder
- type SetterFunc
- type Settings
- func (s *Settings) Clone() (*Settings, error)
- func (s *Settings) DBExport(app App) (map[string]any, error)
- func (s *Settings) IsNew() bool
- func (s *Settings) LastSavedPK() any
- func (s *Settings) MarkAsNew()
- func (s *Settings) MarkAsNotNew()
- func (s *Settings) MarshalJSON() ([]byte, error)
- func (s *Settings) Merge(other *Settings) error
- func (s *Settings) PK() any
- func (s *Settings) PostScan() error
- func (s *Settings) PostValidate(ctx context.Context, app App) error
- func (s *Settings) String() string
- func (s *Settings) TableName() string
- type SettingsListRequestEvent
- type SettingsReloadEvent
- type SettingsUpdateRequestEvent
- type TableInfoRow
- type TerminateEvent
- type TextField
- func (f *TextField) ColumnType(app App) string
- func (f *TextField) FindSetter(key string) SetterFunc
- func (f *TextField) GetHidden() bool
- func (f *TextField) GetId() string
- func (f *TextField) GetName() string
- func (f *TextField) GetSystem() bool
- func (f *TextField) Intercept(ctx context.Context, app App, record *Record, actionName string, ...) error
- func (f *TextField) PrepareValue(record *Record, raw any) (any, error)
- func (f *TextField) SetHidden(hidden bool)
- func (f *TextField) SetId(id string)
- func (f *TextField) SetName(name string)
- func (f *TextField) SetSystem(system bool)
- func (f *TextField) Type() string
- func (f *TextField) ValidatePlainValue(value string) error
- func (f *TextField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *TextField) ValidateValue(ctx context.Context, app App, record *Record) error
- type TokenConfig
- type TrustedProxyConfig
- type URLField
- func (f *URLField) ColumnType(app App) string
- func (f *URLField) GetHidden() bool
- func (f *URLField) GetId() string
- func (f *URLField) GetName() string
- func (f *URLField) GetSystem() bool
- func (f *URLField) PrepareValue(record *Record, raw any) (any, error)
- func (f *URLField) SetHidden(hidden bool)
- func (f *URLField) SetId(id string)
- func (f *URLField) SetName(name string)
- func (f *URLField) SetSystem(system bool)
- func (f *URLField) Type() string
- func (f *URLField) ValidateSettings(ctx context.Context, app App, collection *Collection) error
- func (f *URLField) ValidateValue(ctx context.Context, app App, record *Record) error
Constants ¶
const ( DefaultDataMaxOpenConns int = 120 DefaultDataMaxIdleConns int = 15 DefaultAuxMaxOpenConns int = 20 DefaultAuxMaxIdleConns int = 3 DefaultQueryTimeout time.Duration = 30 * time.Second LocalStorageDirName string = "storage" LocalBackupsDirName string = "backups" LocalTempDirName string = ".pb_temp_to_delete" // temp pb_data sub directory that will be deleted on each app.Bootstrap() LocalAutocertCacheDirName string = ".autocert_cache" )
const ( CollectionTypeBase = "base" CollectionTypeAuth = "auth" CollectionTypeView = "view" )
const ( EmailPlaceholderAppName string = "{APP_NAME}" EmailPlaceholderAppURL string = "{APP_URL}" EmailPlaceholderToken string = "{TOKEN}" EmailPlaceholderOTP string = "{OTP}" EmailPlaceholderOTPId string = "{OTP_ID}" )
Common settings placeholder tokens
const ( // DefaultIdLength is the default length of the generated model id. DefaultIdLength int = 15 // DefaultIdAlphabet is the default characters set used for generating the model id. DefaultIdAlphabet string = "abcdefghijklmnopqrstuvwxyz0123456789" )
const ( RequestInfoContextDefault = "default" RequestInfoContextExpand = "expand" RequestInfoContextRealtime = "realtime" RequestInfoContextProtectedFile = "protectedFile" RequestInfoContextOAuth2 = "oauth2" RequestInfoContextBatch = "batch" )
const ( ModelEventTypeCreate = "create" ModelEventTypeUpdate = "update" ModelEventTypeDelete = "delete" ModelEventTypeValidate = "validate" )
const ( FieldNameId = "id" FieldNameCollectionId = "collectionId" FieldNameCollectionName = "collectionName" FieldNameExpand = "expand" FieldNameEmail = "email" FieldNameEmailVisibility = "emailVisibility" FieldNameVerified = "verified" FieldNameTokenKey = "tokenKey" FieldNamePassword = "password" )
Commonly used field names.
const ( InterceptorActionValidate = "validate" InterceptorActionDelete = "delete" InterceptorActionDeleteExecute = "deleteExecute" InterceptorActionAfterDelete = "afterDelete" InterceptorActionAfterDeleteError = "afterDeleteError" InterceptorActionCreate = "create" InterceptorActionCreateExecute = "createExecute" InterceptorActionAfterCreate = "afterCreate" InterceptorActionAfterCreateError = "afterCreateFailure" InterceptorActionUpdate = "update" InterceptorActionUpdateExecute = "updateExecute" InterceptorActionAfterUpdate = "afterUpdate" InterceptorActionAfterUpdateError = "afterUpdateError" )
Common RecordInterceptor action names.
const ( MFAMethodPassword = "password" MFAMethodOAuth2 = "oauth2" MFAMethodOTP = "otp" )
const ( TokenTypeAuth = "auth" TokenTypeFile = "file" TokenTypeVerification = "verification" TokenTypePasswordReset = "passwordReset" TokenTypeEmailChange = "emailChange" )
Supported record token types
const ( TokenClaimId = "id" TokenClaimType = "type" TokenClaimCollectionId = "collectionId" TokenClaimEmail = "email" TokenClaimNewEmail = "newEmail" TokenClaimRefreshable = "refreshable" )
List with commonly used record token claims
const ( RateLimitRuleAudienceAll = "" RateLimitRuleAudienceGuest = "@guest" RateLimitRuleAudienceAuth = "@auth" )
The allowed RateLimitRule.Audience values
const CollectionNameAuthOrigins = "_authOrigins"
const CollectionNameExternalAuths = "_externalAuths"
const CollectionNameMFAs = "_mfas"
const CollectionNameOTPs = "_otps"
const CollectionNameSuperusers = "_superusers"
const DefaultEditorFieldMaxSize int64 = 5 << 20
const DefaultFileFieldMaxSize int64 = 5 << 20
const DefaultInstallerEmail = "__pbinstaller@example.com"
DefaultInstallerEmail is the default superuser email address for the initial autogenerated superuser account.
const DefaultJSONFieldMaxSize int64 = 5 << 20
const DefaultMigrationsTable = "_migrations"
const FieldTypeAutodate = "autodate"
const FieldTypeBool = "bool"
const FieldTypeDate = "date"
const FieldTypeEditor = "editor"
const FieldTypeEmail = "email"
const FieldTypeFile = "file"
const FieldTypeJSON = "json"
const FieldTypeNumber = "number"
const FieldTypePassword = "password"
const FieldTypeRelation = "relation"
const FieldTypeSelect = "select"
const FieldTypeText = "text"
const FieldTypeURL = "url"
const LogsTableName = "_logs"
const (
RequestEventKeyInfoContext = "infoContext"
)
Common request store keys used by the middlewares and api handlers.
const (
StoreKeyActiveBackup = "@activeBackup"
)
const StoreKeyCachedCollections = "pbAppCachedCollections"
Variables ¶
var ( ErrUnknownField = validation.NewError("validation_unknown_field", "Unknown or invalid field.") ErrInvalidFieldValue = validation.NewError("validation_invalid_field_value", "Invalid field value.") ErrMustBeSystemAndHidden = validation.NewError("validation_must_be_system_and_hidden", `The field must be marked as "System" and "Hidden".`) ErrMustBeSystem = validation.NewError("validation_must_be_system", `The field must be marked as "System".`) )
Common field errors.
var ( ErrNotAuthRecord = errors.New("not an auth collection record") ErrMissingSigningKey = errors.New("missing or invalid signing key") )
Common token related errors
var DefaultIdRegex = regexp.MustCompile(`^\w+$`)
DefaultIdRegex specifies the default regex pattern for an id value.
var Fields = map[string]FieldFactoryFunc{}
Fields holds all available collection fields.
var SystemDynamicFieldNames = []string{ FieldNameCollectionId, FieldNameCollectionName, FieldNameExpand, }
SystemFields returns special internal field names that are usually readonly.
Functions ¶
func DefaultFieldIdValidationRule ¶ added in v0.23.0
DefaultFieldIdValidationRule performs base validation on a field id value.
func DefaultFieldNameValidationRule ¶ added in v0.23.0
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
ValidateValue implements [Field.ValidateValue] interface method.
type BackupEvent ¶ added in v0.23.0
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
AuxDB returns the default app auxiliary db instance (pb_data/auxiliary.db).
func (*BaseApp) AuxDelete ¶ added in v0.23.0
AuxDelete deletes the specified model from the auxiliary database.
func (*BaseApp) AuxDeleteWithContext ¶ added in v0.23.0
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
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
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
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
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
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
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
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
AuxVacuum executes VACUUM on the current app.AuxDB() instance in order to reclaim unused auxiliary db disk space.
func (*BaseApp) Bootstrap ¶
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
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) Delete ¶ added in v0.23.0
Delete deletes the specified model from the regular app database.
func (*BaseApp) DeleteAllAuthOriginsByRecord ¶ added in v0.23.0
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
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
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
DeleteExpiredMFAs deletes the expired MFAs for all auth collections.
func (*BaseApp) DeleteExpiredOTPs ¶ added in v0.23.0
DeleteExpiredOTPs deletes the expired OTPs for all auth collections.
func (*BaseApp) DeleteOldLogs ¶ added in v0.23.0
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
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
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
Delete deletes the specified model from the regular app database (the context could be used to limit the query execution).
func (*BaseApp) EncryptionEnv ¶
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
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
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
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
FindLogById finds a single Log entry by its id.
func (*BaseApp) FindMFAById ¶ added in v0.23.0
FindMFAById returns a single MFA model by its id.
func (*BaseApp) FindOTPById ¶ added in v0.23.0
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
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
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
IsBootstrapped checks if the application was initialized (aka. whether Bootstrap() was called).
func (*BaseApp) IsCollectionNameUnique ¶ added in v0.23.0
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
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
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
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 ¶
NewMailClient creates and returns a new SMTP or Sendmail client based on the current app settings.
func (*BaseApp) NonconcurrentDB ¶ added in v0.23.0
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) 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
ReloadCachedCollections fetches all collections and caches them into the app store.
func (*BaseApp) ReloadSettings ¶ added in v0.23.0
ReloadSettings initializes and reloads the stored application settings.
If no settings were stored it will persist the current app ones.
func (*BaseApp) ResetBootstrapState ¶
ResetBootstrapState releases the initialized core app resources (closing db connections, stopping cron ticker, etc.).
func (*BaseApp) Restart ¶ added in v0.16.0
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
RestoreBackup restores the backup with the specified name and restarts the current running application process.
NB! This feature is experimental and currently is expected to work only on UNIX based systems.
To safely perform the restore it is recommended to have free disk space for at least 2x the size of the restored pb_data backup.
The performed steps are:
Download the backup with the specified name in a temp location (this is in case of S3; otherwise it creates a temp copy of the zip)
Extract the backup in a temp directory inside the app "pb_data" (eg. "pb_data/.pb_temp_to_delete/pb_restore").
Move the current app "pb_data" content (excluding the local backups and the special temp dir) under another temp sub dir that will be deleted on the next app start up (eg. "pb_data/.pb_temp_to_delete/old_pb_data"). This is because on some environments it may not be allowed to delete the currently open "pb_data" files.
Move the extracted dir content to the app "pb_data".
Restart the app (on successful app 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
RunAllMigrations applies all system and app migrations (aka. from both core.SystemMigrations and core.AppMigrations).
func (*BaseApp) RunAppMigrations ¶ added in v0.23.0
RunAppMigrations applies all new migrations registered in the core.AppMigrations list.
func (*BaseApp) RunInTransaction ¶ added in v0.23.0
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
RunSystemMigrations applies all new migrations registered in the core.SystemMigrations list.
func (*BaseApp) Save ¶ added in v0.23.0
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
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
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
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
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) 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
TableColumns returns all column names of a single table by its name.
func (*BaseApp) TableIndexes ¶ added in v0.23.0
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
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
Vacuum executes VACUUM on the current app.DB() instance in order to reclaim unused data db disk space.
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
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
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) PostScan ¶ added in v0.23.0
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
ColumnType implements [Field.ColumnType] interface method.
func (*BoolField) GetHidden ¶ added in v0.23.0
GetHidden implements [Field.GetHidden] interface method.
func (*BoolField) GetSystem ¶ added in v0.23.0
GetSystem implements [Field.GetSystem] interface method.
func (*BoolField) PrepareValue ¶ added in v0.23.0
PrepareValue implements [Field.PrepareValue] interface method.
func (*BoolField) SetHidden ¶ added in v0.23.0
SetHidden implements [Field.SetHidden] interface method.
func (*BoolField) SetSystem ¶ added in v0.23.0
SetSystem implements [Field.SetSystem] interface method.
func (*BoolField) ValidateSettings ¶ added in v0.23.0
ValidateSettings implements [Field.ValidateSettings] interface method.
type BootstrapEvent ¶ added in v0.9.0
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 }
type CollectionEvent ¶ added in v0.23.0
type CollectionRequestEvent ¶ added in v0.23.0
type CollectionRequestEvent struct { hook.Event *RequestEvent // contains filtered or unexported fields }
type CollectionsImportRequestEvent ¶ added in v0.23.0
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
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
ColumnType implements [Field.ColumnType] interface method.
func (*DateField) GetHidden ¶ added in v0.23.0
GetHidden implements [Field.GetHidden] interface method.
func (*DateField) GetSystem ¶ added in v0.23.0
GetSystem implements [Field.GetSystem] interface method.
func (*DateField) PrepareValue ¶ added in v0.23.0
PrepareValue implements [Field.PrepareValue] interface method.
func (*DateField) SetHidden ¶ added in v0.23.0
SetHidden implements [Field.SetHidden] interface method.
func (*DateField) SetSystem ¶ added in v0.23.0
SetSystem implements [Field.SetSystem] interface method.
func (*DateField) ValidateSettings ¶ added in v0.23.0
ValidateSettings implements [Field.ValidateSettings] 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
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
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 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
CalculateMaxBodySize implements the MaxBodySizeCalculator interface.
func (*FileField) ColumnType ¶ added in v0.23.0
ColumnType implements [Field.ColumnType] interface method.
func (*FileField) DriverValue ¶ added in v0.23.0
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
GetHidden implements [Field.GetHidden] interface method.
func (*FileField) GetSystem ¶ added in v0.23.0
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
IsMultiple implements MultiValuer interface and checks whether the current field options support multiple values.
func (*FileField) PrepareValue ¶ added in v0.23.0
PrepareValue implements [Field.PrepareValue] interface method.
func (*FileField) SetHidden ¶ added in v0.23.0
SetHidden implements [Field.SetHidden] interface method.
func (*FileField) SetSystem ¶ added in v0.23.0
SetSystem implements [Field.SetSystem] interface method.
func (*FileField) ValidateSettings ¶ added in v0.23.0
ValidateSettings implements [Field.ValidateSettings] interface method.
type FileTokenRequestEvent ¶ added in v0.23.0
type FileTokenRequestEvent struct { hook.Event *RequestEvent Token string // contains filtered or unexported fields }
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 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
CalculateMaxBodySize implements the MaxBodySizeCalculator interface.
func (*JSONField) ColumnType ¶ added in v0.23.0
ColumnType implements [Field.ColumnType] interface method.
func (*JSONField) GetHidden ¶ added in v0.23.0
GetHidden implements [Field.GetHidden] interface method.
func (*JSONField) GetSystem ¶ added in v0.23.0
GetSystem implements [Field.GetSystem] interface method.
func (*JSONField) PrepareValue ¶ added in v0.23.0
PrepareValue implements [Field.PrepareValue] interface method.
func (*JSONField) SetHidden ¶ added in v0.23.0
SetHidden implements [Field.SetHidden] interface method.
func (*JSONField) SetSystem ¶ added in v0.23.0
SetSystem implements [Field.SetSystem] interface method.
func (*JSONField) ValidateSettings ¶ added in v0.23.0
ValidateSettings implements [Field.ValidateSettings] interface method.
type Log ¶ added in v0.23.0
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
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
CollectionRef returns the "collectionRef" field value.
func (*MFA) HasExpired ¶ added in v0.23.0
HasExpired checks if the mfa is expired, aka. whether it has been more than maxElapsed time since its creation.
func (*MFA) PreValidate ¶ added in v0.23.0
PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.
func (*MFA) ProxyRecord ¶ added in v0.23.0
ProxyRecord returns the proxied Record model.
func (*MFA) SetCollectionRef ¶ added in v0.23.0
SetCollectionRef updates the "collectionRef" record field value.
func (*MFA) SetProxyRecord ¶ added in v0.23.0
SetProxyRecord loads the specified record model into the current proxy.
func (*MFA) SetRecordRef ¶ added in v0.23.0
SetRecordRef updates the "recordRef" 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
DurationTime returns the current Duration as time.Duration.
func (MFAConfig) Validate ¶ added in v0.23.0
Validate makes MFAConfig validatable by implementing validation.Validatable interface.
type MailerEvent ¶ added in v0.23.0
type MailerRecordEvent ¶ added in v0.8.0
type MailerRecordEvent struct { MailerEvent Meta map[string]any // contains filtered or unexported fields }
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 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 }
type ModelEvent ¶
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
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 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
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
CollectionRef returns the "collectionRef" field value.
func (*OTP) HasExpired ¶ added in v0.23.0
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
PreValidate implements the PreValidator interface and checks whether the proxy is properly loaded.
func (*OTP) ProxyRecord ¶ added in v0.23.0
ProxyRecord returns the proxied Record model.
func (*OTP) SentTo ¶ added in v0.23.0
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
SetCollectionRef updates the "collectionRef" record field value.
func (*OTP) SetProxyRecord ¶ added in v0.23.0
SetProxyRecord loads the specified record model into the current proxy.
func (*OTP) SetRecordRef ¶ added in v0.23.0
SetRecordRef updates the "recordRef" 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
DurationTime returns the current Duration as time.Duration.
func (OTPConfig) Validate ¶ added in v0.23.0
Validate makes OTPConfig validatable by implementing validation.Validatable interface.
type Param ¶ added in v0.23.0
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.