AuxDB returns the app auxiliary.db builder instance.
To minimize SQLITE_BUSY errors, it automatically routes the SELECT queries to the underlying concurrent db pool and everything else to the nonconcurrent one.
For more finer control over the used connections pools you can call directly AuxConcurrentDB() or AuxNonconcurrentDB().
AuxDelete deletes the specified model from the auxiliary database.
AuxModelQuery creates a new preconfigured select auxiliary.db query with preset SELECT, FROM and other common fields based on the provided model.
AuxNonconcurrentDB returns the nonconcurrent app auxiliary.db builder instance.
The returned db instance is limited only to a single open connection, meaning that it can process only 1 db operation at a time (other queries queue up).
This method is used mainly internally and in the tests to execute write (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
Most users should use simply AuxDB() as it will automatically route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.
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.
AuxSave validates and saves the specified model into the auxiliary app database.
If you don't want to run validations, use [App.AuxSaveNoValidate()].
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()].
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 { ... }
CollectionQuery returns a new Collection select query.
ConcurrentDB returns the concurrent app data.db builder instance.
This method is used mainly internally for executing db read operations in a concurrent/non-blocking manner.
Most users should use simply DB() as it will automatically route the query execution to ConcurrentDB() or NonconcurrentDB().
In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
CountRecords returns the total number of records in a collection.
Rest ...exprs: Expression[]CreateViewFields creates a new FieldsList from the provided select query.
There are some caveats:
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousSelectQuery" argument must come only from trusted input!
DB returns the default app data.db builder instance.
To minimize SQLITE_BUSY errors, it automatically routes the SELECT queries to the underlying concurrent db pool and everything else to the nonconcurrent one.
For more finer control over the used connections pools you can call directly ConcurrentDB() or NonconcurrentDB().
Delete deletes the specified model from the regular app database.
DeleteOldLogs delete all logs that are created before createdBefore.
DeleteTable drops the specified table.
This method is a no-op if a table with the provided name doesn't exist.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousTableName" argument must come only from trusted input!
DeleteView drops the specified view name.
This method is a no-op if a view with the provided name doesn't exist.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousViewName" argument must come only from trusted input!
DryRunView executes the provided query by creating a temporary view collection and returning a sample of the resulting query records (if valid).
The same caveats from CreateViewFields apply here too.
NB! Be aware that this method is vulnerable to SQL injection and the "dangerousSelectQuery" argument must come only from trusted input!
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.
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.
FindAllAuthOriginsByCollection returns all AuthOrigin models linked to the provided collection (in DESC order).
FindAllAuthOriginsByRecord returns all AuthOrigin models linked to the provided auth record (in DESC order).
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
Rest ...collectionTypes: string[]FindAllExternalAuthsByCollection returns all ExternalAuth models linked to the provided auth collection.
FindAllExternalAuthsByRecord returns all ExternalAuth models linked to the provided auth record.
FindAllMFAsByCollection returns all MFA models linked to the provided collection.
FindAllOTPsByCollection returns all OTP models linked to the provided collection.
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)
Rest ...exprs: Expression[]FindAuthOriginById returns a single AuthOrigin model by its id.
FindAuthOriginByRecordAndFingerprint returns a single AuthOrigin model by its authRecord relation and fingerprint.
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.
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.
Rest ...validTypes: string[]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]
FindCachedCollectionReferences is similar to [App.FindCollectionReferences] but retrieves the Collection from the app cache instead of making a db call.
NB! This method is suitable for read-only Collection operations.
If you plan making changes to the returned Collection model, use [App.FindCollectionReferences] instead.
Caveats:
- The returned Collection should be used only for read-only operations.
Avoid directly modifying the returned cached Collection as it will affect
the global cached value even if you don't persist the changes in the database!
- If you are updating a Collection in a transaction and then call this method before commit,
it'll return the cached Collection state and not the one from the uncommitted transaction.
- The cache is automatically updated on collections db change (create/update/delete).
To manually reload the cache you can call [App.ReloadCachedCollections].
Rest ...excludeIds: string[]FindCollectionByNameOrId finds a single collection by its name (case insensitive) or id.s
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.
Rest ...excludeIds: string[]FindFirstExternalAuthByExpr returns the first available (the most recent created) ExternalAuth model that satisfies the non-nil expression.
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"})
Rest ...params: Params[]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}
)
Rest ...params: Params[]FindRecordsByIds finds all records by the specified ids. If no records are found, returns an empty slice.
Rest ...optFilters: ((q) => void)[]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).
ImportCollectionsByMarshaledJSON is the same as [ImportCollections] but accept marshaled json array as import data (usually used for the autogenerated snapshots).
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.
Rest ...excludeIds: string[]LogQuery returns a new Log select query.
LogsStatsItem returns hourly grouped logs statistics.
ModelQuery creates a new preconfigured select data.db query with preset SELECT, FROM and other common fields based on the provided model.
NonconcurrentDB returns the nonconcurrent app data.db builder instance.
The returned db instance is limited only to a single open connection, meaning that it can process only 1 db operation at a time (other queries queue up).
This method is used mainly internally and in the tests to execute write (save/delete) db operations as it helps with minimizing the SQLITE_BUSY errors.
Most users should use simply DB() as it will automatically route the query execution to ConcurrentDB() or NonconcurrentDB().
In a transaction the ConcurrentDB() and NonconcurrentDB() refer to the same *dbx.TX instance.
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.
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 CoreApp implementation for details on the restore procedures.
NB! This feature is experimental and currently is expected to work only on UNIX based systems.
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.
Save validates and saves the specified model into the regular app database.
If you don't want to run validations, use [App.SaveNoValidate()].
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()].
SaveView creates (or updates already existing) persistent SQL view.
NB! Be aware that this method is vulnerable to SQL injection and its arguments must come only from trusted input!
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.
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.
TableInfo returns the "table_info" pragma result for the specified table.
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.
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.
Validate triggers the OnModelValidate hook for the specified model.
Optional rootRootCmd is the main console command
Generated using TypeDoc
AuxConcurrentDB returns the concurrent app auxiliary.db builder instance.
This method is used mainly internally for executing db read operations in a concurrent/non-blocking manner.
Most users should use simply AuxDB() as it will automatically route the query execution to AuxConcurrentDB() or AuxNonconcurrentDB().
In a transaction the AuxConcurrentDB() and AuxNonconcurrentDB() refer to the same *dbx.TX instance.