BaseApp implements CoreApp and defines the base PocketBase app structure.

Hierarchy

  • BaseApp

Methods

auxDB auxDelete auxDeleteWithContext auxHasTable auxModelQuery auxNonconcurrentDB auxRunInTransaction auxSave auxSaveNoValidate auxSaveNoValidateWithContext auxSaveWithContext auxVacuum bootstrap canAccessRecord collectionQuery countRecords createBackup createViewFields cron dataDir db delete deleteAllAuthOriginsByRecord deleteAllMFAsByRecord deleteAllOTPsByRecord deleteExpiredMFAs deleteExpiredOTPs deleteOldLogs deleteTable deleteView deleteWithContext encryptionEnv expandRecord expandRecords findAllAuthOriginsByCollection findAllAuthOriginsByRecord findAllCollections findAllExternalAuthsByCollection findAllExternalAuthsByRecord findAllMFAsByCollection findAllMFAsByRecord findAllOTPsByCollection findAllOTPsByRecord findAllRecords findAuthOriginById findAuthOriginByRecordAndFingerprint findAuthRecordByEmail findAuthRecordByToken findCachedCollectionByNameOrId findCollectionByNameOrId findCollectionReferences findFirstExternalAuthByExpr findFirstRecordByData findFirstRecordByFilter findLogById findMFAById findOTPById findRecordById findRecordByViewFile findRecordsByFilter findRecordsByIds hasTable importCollections importCollectionsByMarshaledJSON isBootstrapped isCollectionNameUnique isDev isTransactional logQuery logger logsStats modelQuery newBackupsFilesystem newFilesystem newMailClient nonconcurrentDB onBackupCreate onBackupRestore onBatchRequest onBootstrap onCollectionAfterCreateError onCollectionAfterCreateSuccess onCollectionAfterDeleteError onCollectionAfterDeleteSuccess onCollectionAfterUpdateError onCollectionAfterUpdateSuccess onCollectionCreate onCollectionCreateExecute onCollectionCreateRequest onCollectionDelete onCollectionDeleteExecute onCollectionDeleteRequest onCollectionUpdate onCollectionUpdateExecute onCollectionUpdateRequest onCollectionValidate onCollectionViewRequest onCollectionsImportRequest onCollectionsListRequest onFileDownloadRequest onFileTokenRequest onMailerRecordAuthAlertSend onMailerRecordEmailChangeSend onMailerRecordOTPSend onMailerRecordPasswordResetSend onMailerRecordVerificationSend onMailerSend onModelAfterCreateError onModelAfterCreateSuccess onModelAfterDeleteError onModelAfterDeleteSuccess onModelAfterUpdateError onModelAfterUpdateSuccess onModelCreate onModelCreateExecute onModelDelete onModelDeleteExecute onModelUpdate onModelUpdateExecute onModelValidate onRealtimeConnectRequest onRealtimeMessageSend onRealtimeSubscribeRequest onRecordAfterCreateError onRecordAfterCreateSuccess onRecordAfterDeleteError onRecordAfterDeleteSuccess onRecordAfterUpdateError onRecordAfterUpdateSuccess onRecordAuthRefreshRequest onRecordAuthRequest onRecordAuthWithOAuth2Request onRecordAuthWithOTPRequest onRecordAuthWithPasswordRequest onRecordConfirmEmailChangeRequest onRecordConfirmPasswordResetRequest onRecordConfirmVerificationRequest onRecordCreate onRecordCreateExecute onRecordCreateRequest onRecordDelete onRecordDeleteExecute onRecordDeleteRequest onRecordEnrich onRecordRequestEmailChangeRequest onRecordRequestOTPRequest onRecordRequestPasswordResetRequest onRecordRequestVerificationRequest onRecordUpdate onRecordUpdateExecute onRecordUpdateRequest onRecordValidate onRecordViewRequest onRecordsListRequest onServe onSettingsListRequest onSettingsReload onSettingsUpdateRequest onTerminate recordQuery reloadCachedCollections reloadSettings resetBootstrapState restart restoreBackup runAllMigrations runAppMigrations runInTransaction runSystemMigrations save saveNoValidate saveNoValidateWithContext saveView saveWithContext settings store subscriptionsBroker syncRecordTableSchema tableColumns tableIndexes tableInfo truncateCollection unsafeWithoutHooks vacuum validate validateWithContext

Methods

  • AuxDelete deletes the specified model from the auxiliary database.

    Parameters

    Returns void

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

    Parameters

    Returns void

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

    Parameters

    • tableName: string

    Returns boolean

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

    Parameters

    Returns SelectQuery

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

    Returns Builder

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

    Parameters

    • fn: ((txApp) => void)
        • (txApp): void
        • Parameters

          Returns void

    Returns void

  • AuxSave validates and saves the specified model into the auxiliary app database.

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

    Parameters

    Returns void

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

    Parameters

    Returns void

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

    Parameters

    Returns void

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

    Parameters

    Returns void

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

    Returns void

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

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

    Returns void

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

    Parameters

    Returns boolean

  • CountRecords returns the total number of records in a collection.

    Parameters

    • collectionModelOrIdentifier: any
    • Rest ...exprs: Expression[]

    Returns number

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

    Parameters

    Returns void

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

    Parameters

    • selectQuery: string

    Returns core.FieldsList

  • DataDir returns the app data directory path.

    Returns string

  • Delete deletes the specified model from the regular app database.

    Parameters

    Returns void

  • DeleteAllAuthOriginsByRecord deletes all AuthOrigin models associated with the provided record.

    Returns a combined error with the failed deletes.

    Parameters

    Returns void

  • DeleteAllMFAsByRecord deletes all MFA models associated with the provided record.

    Returns a combined error with the failed deletes.

    Parameters

    Returns void

  • DeleteAllOTPsByRecord deletes all OTP models associated with the provided record.

    Returns a combined error with the failed deletes.

    Parameters

    Returns void

  • DeleteExpiredMFAs deletes the expired MFAs for all auth collections.

    Returns void

  • DeleteExpiredOTPs deletes the expired OTPs for all auth collections.

    Returns void

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

    Parameters

    • createdBefore: Time

    Returns void

  • 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!

    Parameters

    • tableName: string

    Returns void

  • 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!

    Parameters

    • name: string

    Returns void

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

    Parameters

    Returns void

  • EncryptionEnv returns the name of the app secret env key (currently used primarily for optional settings encryption but this may change in the future).

    Returns string

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

    Parameters

    Returns _TygojaDict

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

    Parameters

    Returns _TygojaDict

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

    Parameters

    Returns AuthOrigin[]

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

    Parameters

    Returns AuthOrigin[]

  • 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

    Parameters

    • Rest ...collectionTypes: string[]

    Returns core.Collection[]

  • FindAllMFAsByCollection returns all MFA models linked to the provided collection.

    Parameters

    Returns MFA[]

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

    Parameters

    Returns MFA[]

  • FindAllOTPsByCollection returns all OTP models linked to the provided collection.

    Parameters

    Returns OTP[]

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

    Parameters

    Returns OTP[]

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

    Parameters

    • collectionModelOrIdentifier: any
    • Rest ...exprs: Expression[]

    Returns core.Record[]

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

    Parameters

    Returns AuthOrigin

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

    Parameters

    • collectionModelOrIdentifier: any
    • email: string

    Returns core.Record

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

    Parameters

    • token: string
    • Rest ...validTypes: string[]

    Returns core.Record

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

    Parameters

    • nameOrId: string

    Returns core.Collection

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

    Parameters

    • nameOrId: string

    Returns core.Collection

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

    Parameters

    Returns _TygojaDict

  • FindFirstExternalAuthByExpr returns the first available (the most recent created) ExternalAuth model that satisfies the non-nil expression.

    Parameters

    Returns ExternalAuth

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

    Parameters

    • collectionModelOrIdentifier: any
    • key: string
    • value: any

    Returns core.Record

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

    Parameters

    • collectionModelOrIdentifier: any
    • filter: string
    • Rest ...params: Params[]

    Returns core.Record

  • FindLogById finds a single Log entry by its id.

    Parameters

    • id: string

    Returns Log

  • FindMFAById returns a single MFA model by its id.

    Parameters

    • id: string

    Returns MFA

  • FindOTPById returns a single OTP model by its id.

    Parameters

    • id: string

    Returns OTP

  • FindRecordById finds the Record model by its id.

    Parameters

    • collectionModelOrIdentifier: any
    • recordId: string
    • Rest ...optFilters: ((q) => void)[]

    Returns core.Record

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

    Parameters

    • viewCollectionModelOrIdentifier: any
    • fileFieldName: string
    • filename: string

    Returns core.Record

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

    Parameters

    • collectionModelOrIdentifier: any
    • filter: string
    • sort: string
    • limit: number
    • offset: number
    • Rest ...params: Params[]

    Returns core.Record[]

  • FindRecordsByIds finds all records by the specified ids. If no records are found, returns an empty slice.

    Parameters

    • collectionModelOrIdentifier: any
    • recordIds: string[]
    • Rest ...optFilters: ((q) => void)[]

    Returns core.Record[]

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

    Parameters

    • tableName: string

    Returns boolean

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

    Parameters

    Returns void

  • ImportCollectionsByMarshaledJSON is the same as [ImportCollections] but accept marshaled json array as import data (usually used for the autogenerated snapshots).

    Parameters

    • rawSliceOfMaps: string | number[]
    • deleteMissing: boolean

    Returns void

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

    Returns boolean

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

    Parameters

    • name: string
    • Rest ...excludeIds: string[]

    Returns boolean

  • IsDev returns whether the app is in dev mode.

    When enabled logs, executed sql statements, etc. are printed to the stderr.

    Returns boolean

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

    Returns boolean

  • Logger returns the default app logger.

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

    Returns Logger

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

    Parameters

    Returns SelectQuery

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

    Returns System

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

    Returns System

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

    Returns Mailer

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

    Returns Builder

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

    Parameters

    • collectionModelOrIdentifier: any

    Returns SelectQuery

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

    Returns void

  • ReloadSettings initializes and reloads the stored application settings.

    If no settings were stored it will persist the current app ones.

    Returns void

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

    Returns void

  • Restart restarts (aka. replaces) the current running application process.

    NB! It relies on execve which is supported only on UNIX based systems.

    Returns void

  • RestoreBackup restores the backup with the specified name and restarts the current running application process.

    NB! This feature is experimental and currently is expected to work only on UNIX based systems.

    To safely perform the restore it is recommended to have free disk space for at least 2x the size of the restored pb_data backup.

    The performed steps are:

    1. Download the backup with the specified name in a temp location
        (this is in case of S3; otherwise it creates a temp copy of the zip)
    
    1. Extract the backup in a temp directory inside the app "pb_data"
        (eg. "pb_data/.pb_temp_to_delete/pb_restore").
    
    1. 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.
    1. Move the extracted dir content to the app "pb_data".

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

    Parameters

    Returns void

  • RunAllMigrations applies all system and app migrations (aka. from both [core.SystemMigrations] and [CoreAppMigrations]).

    Returns void

  • RunAppMigrations applies all new migrations registered in the [CoreAppMigrations] list.

    Returns void

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

    Parameters

    • fn: ((txApp) => void)
        • (txApp): void
        • Parameters

          Returns void

    Returns void

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

    Returns void

  • Save validates and saves the specified model into the regular app database.

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

    Parameters

    Returns void

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

    Parameters

    Returns void

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

    Parameters

    Returns void

  • 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!

    Parameters

    • name: string
    • selectQuery: string

    Returns void

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

    Parameters

    Returns void

  • SubscriptionsBroker returns the app realtime subscriptions broker instance.

    Returns Broker

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

    Parameters

    Returns void

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

    Parameters

    • tableName: string

    Returns string[]

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

    Parameters

    • tableName: string

    Returns _TygojaDict

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

    Parameters

    Returns void

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

    Returns App

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

    Returns void

  • Validate triggers the OnModelValidate hook for the specified model.

    Parameters

    Returns void

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

    Parameters

    Returns void

Generated using TypeDoc