Dao handles various db operations.

You can think of Dao as a repository and service layer in one.

Hierarchy

Implements

Constructors

  • Parameters

    Returns Dao

Methods

  • 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.Admin is set.

    The returned error indicate that something unexpected happened during the check (eg. invalid rule or db error).

    The method always return false on invalid access rule or db error.

    Example:

     requestInfo := apis.RequestInfo(c /* echo.Context */)
    record, _ := dao.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, _ := dao.CanAccessRecord(record, requestInfo, rule); ok { ... }

    Parameters

    Returns boolean

  • ConcurrentDB returns the dao concurrent (aka. multiple open connections) db builder (*dbx.DB or *dbx.TX).

    In a transaction the concurrentDB and nonconcurrentDB refer to the same *dbx.TX instance.

    Returns Builder

  • CreateViewSchema creates a new view schema 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 schema.Schema

  • DB returns the default dao db builder (*dbx.DB or *dbx.TX).

    Currently the default db builder is dao.concurrentDB but that may change in the future.

    Returns Builder

  • DeleteAdmin deletes the provided Admin model.

    Returns an error if there is only 1 admin.

    Parameters

    Returns void

  • DeleteCollection deletes the provided Collection model. This method automatically deletes the related collection records table.

    NB! The collection cannot be deleted, if:

    • is system collection (aka. collection.System is true)
    • is referenced as part of a relation field in another collection

    Parameters

    Returns void

  • DeleteOldLogs delete all requests that are created before createdBefore.

    Parameters

    • createdBefore: Time

    Returns void

  • DeleteRecord deletes the provided Record model.

    This method will also cascade the delete operation to all linked relational records (delete or unset, depending on the rel settings).

    The delete operation may fail if the record is part of a required reference in another record (aka. cannot be deleted or unset).

    Parameters

    Returns void

  • DeleteTable drops the specified table.

    This method is a no-op if a table with the provided name doesn't exist.

    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.

    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

  • 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

  • FindAdminByToken finds the admin associated with the provided JWT.

    Returns an error if the JWT is invalid or expired.

    Parameters

    • token: string
    • baseTokenKey: string

    Returns models.Admin

  • 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

    • collectionNameOrId: string
    • email: string

    Returns models.Record

  • FindAuthRecordByToken finds the auth record associated with the provided JWT.

    Returns an error if the JWT is invalid, expired or not associated to an auth collection record.

    Parameters

    • token: string
    • baseTokenKey: string

    Returns models.Record

  • FindAuthRecordByUsername finds the auth record associated with the provided username (case insensitive).

    Returns an error if it is not an auth collection or the record is not found.

    Parameters

    • collectionNameOrId: string
    • username: string

    Returns models.Record

  • FindById finds a single db record with the specified id and scans the result into m.

    Parameters

    Returns void

  • FindCollectionReferences returns information for all relation schema 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 excludeId argument.

    Parameters

    Returns _TygojaDict

  • FindFirstRecordByFilter returns the first available record matching the provided filter.

    NB! Use the last params argument to bind untrusted user variables!

    Example:

     dao.FindFirstRecordByFilter("posts", "slug={:slug} && status='public'", dbx.Params{"slug": "test"})
    

    Parameters

    • collectionNameOrId: string
    • filter: string
    • Rest ...params: Params[]

    Returns models.Record

  • FindRecordById finds the Record model by its id.

    Parameters

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

    Returns models.Record

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

    Parameters

    • viewCollectionNameOrId: string
    • fileFieldName: string
    • filename: string

    Returns models.Record

  • FindRecordsByExpr finds all records by the specified db expression.

    Returns all collection records if no expressions are provided.

    Returns an empty slice if no records are found.

    Example:

     expr1 := dbx.HashExp{"email": "test@example.com"}
    expr2 := dbx.NewExp("LOWER(username) = {:username}", dbx.Params{"username": "test"})
    dao.FindRecordsByExpr("example", expr1, expr2)

    Parameters

    • collectionNameOrId: string
    • Rest ...exprs: Expression[]

    Returns models.Record[]

  • FindRecordsByFilter returns limit number of records matching the provided string filter.

    NB! Use the last "params" argument to bind untrusted user variables!

    The sort argument is optional and can be empty string OR the same format used in the web APIs, eg. "-created,title".

    If the limit argument is <= 0, no limit is applied to the query and all matching records are returned.

    Example:

     dao.FindRecordsByFilter(
    "posts",
    "title ~ {:title} && visible = {:visible}",
    "-created",
    10,
    0,
    dbx.Params{"title": "lorem ipsum", "visible": true}
    )

    Parameters

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

    Returns models.Record[]

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

    Parameters

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

    Returns models.Record[]

  • FindSettings returns and decode the serialized app settings param value.

    The method will first try to decode the param value without decryption. If it fails and optEncryptionKey is set, it will try again by first decrypting the value and then decode it again.

    Returns an error if it fails to decode the stored serialized param value.

    Parameters

    • Rest ...optEncryptionKey: string[]

    Returns Settings

  • HasTable checks if a table (or view) with the provided name exists (case insensitive).

    Parameters

    • tableName: string

    Returns boolean

  • ImportCollections imports the provided collections list within a single transaction.

    NB1! If deleteMissing is set, all local collections and schema fields, that are not present in the imported configuration, WILL BE DELETED (including their related records data).

    NB2! This method doesn't perform validations on the imported collections data! If you need validations, use [forms.CollectionsImport].

    Parameters

    • importedCollections: models.Collection[]
    • deleteMissing: boolean
    • afterSync: ((txDao, mappedImported, mappedExisting) => void)

    Returns void

  • IsAdminEmailUnique checks if the provided email address is not already in use by other admins.

    Parameters

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

    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 a table name for the records.

    Parameters

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

    Returns boolean

  • IsRecordValueUnique checks if the provided key-value pair is a unique Record value.

    For correctness, if the collection is "auth" and the key is "username", the unique check will be case insensitive.

    NB! Array values (eg. from multiple select fields) are matched as a serialized json strings (eg. ["a","b"]), so the value uniqueness depends on the elements order. Or in other words the following values are considered different: []string{"a","b"} and []string{"b","a"}

    Parameters

    • collectionNameOrId: string
    • key: string
    • value: any
    • Rest ...excludeIds: string[]

    Returns boolean

  • NonconcurrentDB returns the dao nonconcurrent (aka. single open connection) db builder (*dbx.DB or *dbx.TX).

    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

  • RunInTransaction wraps fn into a transaction.

    It is safe to nest RunInTransaction calls as long as you use the txDao.

    Parameters

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

          Returns void

    Returns void

  • Save persists the provided model in the database.

    If m.IsNew() is true, the method will perform a create, otherwise an update. To explicitly mark a model for update you can use m.MarkAsNotNew().

    Parameters

    Returns void

  • SaveCollection persists the provided Collection model and updates its related records table schema.

    If collection.IsNew() is true, the method will perform a create, otherwise an update. To explicitly mark a collection for update you can use collection.MarkAsNotNew().

    Parameters

    Returns void

  • SaveLog upserts the provided Log model.

    Parameters

    Returns void

  • SaveParam creates or updates a Param model by the provided key-value pair. The value argument will be encoded as json string.

    If optEncryptionKey is provided it will encrypt the value before storing it.

    Parameters

    • key: string
    • value: any
    • Rest ...optEncryptionKey: string[]

    Returns void

  • SaveRecord persists the provided Record model in the database.

    If record.IsNew() is true, the method will perform a create, otherwise an update. To explicitly mark a record for update you can use record.MarkAsNotNew().

    Parameters

    Returns void

  • SaveSettings persists the specified settings configuration.

    If optEncryptionKey is set, then the stored serialized value will be encrypted with it.

    Parameters

    • newSettings: Settings
    • Rest ...optEncryptionKey: string[]

    Returns void

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

    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

  • SuggestUniqueAuthRecordUsername checks if the provided username is unique and return a new "unique" username with appended random numeric part (eg. "existingName" -> "existingName583").

    The same username will be returned if the provided string is already unique.

    Parameters

    • collectionNameOrId: string
    • baseUsername: string
    • Rest ...excludeIds: string[]

    Returns string

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

    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

  • TotalAdmins returns the number of existing admin records.

    Returns number

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

    Returns void

  • WithoutHooks returns a new Dao with the same configuration options as the current one, but without create/update/delete hooks.

    Returns daos.Dao

Properties

afterCreateFunc: ((eventDao, m) => void)

Type declaration

    • (eventDao, m): void
    • Parameters

      Returns void

afterDeleteFunc: ((eventDao, m) => void)

Type declaration

    • (eventDao, m): void
    • Parameters

      Returns void

afterUpdateFunc: ((eventDao, m) => void)

Type declaration

    • (eventDao, m): void
    • Parameters

      Returns void

beforeCreateFunc: ((eventDao, m, action) => void)

Type declaration

    • (eventDao, m, action): void
    • write hooks

      Parameters

      • eventDao: daos.Dao
      • m: Model
      • action: (() => void)
          • (): void
          • Returns void

      Returns void

beforeDeleteFunc: ((eventDao, m, action) => void)

Type declaration

    • (eventDao, m, action): void
    • Parameters

      • eventDao: daos.Dao
      • m: Model
      • action: (() => void)
          • (): void
          • Returns void

      Returns void

beforeUpdateFunc: ((eventDao, m, action) => void)

Type declaration

    • (eventDao, m, action): void
    • Parameters

      • eventDao: daos.Dao
      • m: Model
      • action: (() => void)
          • (): void
          • Returns void

      Returns void

maxLockRetries: number

MaxLockRetries specifies the default max "database is locked" auto retry attempts.

modelQueryTimeout: Duration

ModelQueryTimeout is the default max duration of a running ModelQuery().

This field has no effect if an explicit query context is already specified.

Generated using TypeDoc