daos

package
v0.0.0-...-89d1b08 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2022 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package daos handles common PocketBase DB model manipulations.

Think of daos as DB repository and service layer in one.

Index

Constants

View Source
const MaxExpandDepth = 6

MaxExpandDepth specifies the max allowed nested expand depth path.

Variables

This section is empty.

Functions

This section is empty.

Types

type Dao

type Dao struct {
	BeforeCreateFunc func(eventDao *Dao, m models.Model) error
	AfterCreateFunc  func(eventDao *Dao, m models.Model)
	BeforeUpdateFunc func(eventDao *Dao, m models.Model) error
	AfterUpdateFunc  func(eventDao *Dao, m models.Model)
	BeforeDeleteFunc func(eventDao *Dao, m models.Model) error
	AfterDeleteFunc  func(eventDao *Dao, m models.Model)
	// contains filtered or unexported fields
}

Dao handles various db operations. Think of Dao as a repository and service layer in one.

func New

func New(db dbx.Builder) *Dao

New creates a new Dao instance with the provided db builder.

func (*Dao) AdminQuery

func (dao *Dao) AdminQuery() *dbx.SelectQuery

AdminQuery returns a new Admin select query.

func (*Dao) CollectionQuery

func (dao *Dao) CollectionQuery() *dbx.SelectQuery

CollectionQuery returns a new Collection select query.

func (*Dao) DB

func (dao *Dao) DB() dbx.Builder

DB returns the internal db builder (*dbx.DB or *dbx.TX).

func (*Dao) Delete

func (dao *Dao) Delete(m models.Model) error

Delete deletes the provided model.

func (*Dao) DeleteAdmin

func (dao *Dao) DeleteAdmin(admin *models.Admin) error

DeleteAdmin deletes the provided Admin model.

Returns an error if there is only 1 admin.

func (*Dao) DeleteCollection

func (dao *Dao) DeleteCollection(collection *models.Collection) error

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

func (*Dao) DeleteExternalAuth

func (dao *Dao) DeleteExternalAuth(model *models.ExternalAuth) error

DeleteExternalAuth deletes the provided ExternalAuth model.

The delete may fail if the linked user doesn't have an email and there are no other linked ExternalAuth models available.

func (*Dao) DeleteOldRequests

func (dao *Dao) DeleteOldRequests(createdBefore time.Time) error

DeleteOldRequests delete all requests that are created before createdBefore.

func (*Dao) DeleteParam

func (dao *Dao) DeleteParam(param *models.Param) error

DeleteParam deletes the provided Param model.

func (*Dao) DeleteRecord

func (dao *Dao) DeleteRecord(record *models.Record) error

DeleteRecord deletes the provided Record model.

This method will also cascade the delete operation to all linked relational records (delete or set to NULL, 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 set to NULL).

func (*Dao) DeleteTable

func (dao *Dao) DeleteTable(tableName string) error

DeleteTable drops the specified table.

func (*Dao) DeleteUser

func (dao *Dao) DeleteUser(user *models.User) error

DeleteUser deletes the provided User model.

This method will also cascade the delete operation to all Record models that references the provided User model (delete or set to NULL, depending on the related user shema field settings).

The delete operation may fail if the user is part of a required reference in another Record model (aka. cannot be deleted or set to NULL).

func (*Dao) ExpandRecord

func (dao *Dao) ExpandRecord(record *models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error

ExpandRecord expands the relations of a single Record model.

Returns a map with the failed expand parameters and their errors.

func (*Dao) ExpandRecords

func (dao *Dao) ExpandRecords(records []*models.Record, expands []string, fetchFunc ExpandFetchFunc) map[string]error

ExpandRecords expands the relations of the provided Record models list.

Returns a map with the failed expand parameters and their errors.

func (*Dao) ExternalAuthQuery

func (dao *Dao) ExternalAuthQuery() *dbx.SelectQuery

ExternalAuthQuery returns a new ExternalAuth select query.

func (*Dao) FindAdminByEmail

func (dao *Dao) FindAdminByEmail(email string) (*models.Admin, error)

FindAdminByEmail finds the admin with the provided email address.

func (*Dao) FindAdminById

func (dao *Dao) FindAdminById(id string) (*models.Admin, error)

FindAdminById finds the admin with the provided id.

func (*Dao) FindAdminByToken

func (dao *Dao) FindAdminByToken(token string, baseTokenKey string) (*models.Admin, error)

FindAdminByToken finds the admin associated with the provided JWT token.

Returns an error if the JWT token is invalid or expired.

func (*Dao) FindAllExternalAuthsByUserId

func (dao *Dao) FindAllExternalAuthsByUserId(userId string) ([]*models.ExternalAuth, error)

/ FindAllExternalAuthsByUserId returns all ExternalAuth models / linked to the provided userId.

func (*Dao) FindById

func (dao *Dao) FindById(m models.Model, id string) error

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

func (*Dao) FindCollectionByNameOrId

func (dao *Dao) FindCollectionByNameOrId(nameOrId string) (*models.Collection, error)

FindCollectionByNameOrId finds the first collection by its name or id.

func (*Dao) FindCollectionReferences

func (dao *Dao) FindCollectionReferences(collection *models.Collection, excludeId string) (map[*models.Collection][]*schema.SchemaField, error)

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 exlude it, pass the collection id as the excludeId argument.

func (*Dao) FindCollectionsWithUserFields

func (dao *Dao) FindCollectionsWithUserFields() ([]*models.Collection, error)

FindCollectionsWithUserFields finds all collections that has at least one user schema field.

func (*Dao) FindExternalAuthByProvider

func (dao *Dao) FindExternalAuthByProvider(provider, providerId string) (*models.ExternalAuth, error)

FindExternalAuthByProvider returns the first available ExternalAuth model for the specified provider and providerId.

func (*Dao) FindExternalAuthByUserIdAndProvider

func (dao *Dao) FindExternalAuthByUserIdAndProvider(userId, provider string) (*models.ExternalAuth, error)

FindExternalAuthByUserIdAndProvider returns the first available ExternalAuth model for the specified userId and provider.

func (*Dao) FindFirstRecordByData

func (dao *Dao) FindFirstRecordByData(collection *models.Collection, key string, value any) (*models.Record, error)

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

func (*Dao) FindParamByKey

func (dao *Dao) FindParamByKey(key string) (*models.Param, error)

FindParamByKey finds the first Param model with the provided key.

func (*Dao) FindRecordById

func (dao *Dao) FindRecordById(
	collection *models.Collection,
	recordId string,
	filter func(q *dbx.SelectQuery) error,
) (*models.Record, error)

FindRecordById finds the Record model by its id.

func (*Dao) FindRecordsByExpr

func (dao *Dao) FindRecordsByExpr(collection *models.Collection, expr dbx.Expression) ([]*models.Record, error)

FindRecordsByExpr finds all records by the provided db expression. If no records are found, returns an empty slice.

Example:

expr := dbx.HashExp{"email": "test@example.com"}
dao.FindRecordsByExpr(collection, expr)

func (*Dao) FindRecordsByIds

func (dao *Dao) FindRecordsByIds(
	collection *models.Collection,
	recordIds []string,
	filter func(q *dbx.SelectQuery) error,
) ([]*models.Record, error)

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

func (*Dao) FindRequestById

func (dao *Dao) FindRequestById(id string) (*models.Request, error)

FindRequestById finds a single Request log by its id.

func (*Dao) FindUserByEmail

func (dao *Dao) FindUserByEmail(email string) (*models.User, error)

FindUserByEmail finds a single User model by its non-empty email address.

This method also auto loads the related user profile record into the found model.

func (*Dao) FindUserById

func (dao *Dao) FindUserById(id string) (*models.User, error)

FindUserById finds a single User model by its id.

This method also auto loads the related user profile record into the found model.

func (*Dao) FindUserByToken

func (dao *Dao) FindUserByToken(token string, baseTokenKey string) (*models.User, error)

FindUserByToken finds the user associated with the provided JWT token. Returns an error if the JWT token is invalid or expired.

This method also auto loads the related user profile record into the found model.

func (*Dao) FindUserRelatedRecords

func (dao *Dao) FindUserRelatedRecords(user *models.User) ([]*models.Record, error)

FindUserRelatedRecords returns all records that has a reference to the provided User model (via the user shema field).

func (*Dao) GetTableColumns

func (dao *Dao) GetTableColumns(tableName string) ([]string, error)

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

func (*Dao) HasTable

func (dao *Dao) HasTable(tableName string) bool

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

func (*Dao) ImportCollections

func (dao *Dao) ImportCollections(
	importedCollections []*models.Collection,
	deleteMissing bool,
	beforeRecordsSync func(txDao *Dao, mappedImported, mappedExisting map[string]*models.Collection) error,
) error

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

func (*Dao) IsAdminEmailUnique

func (dao *Dao) IsAdminEmailUnique(email string, excludeId string) bool

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

func (*Dao) IsCollectionNameUnique

func (dao *Dao) IsCollectionNameUnique(name string, excludeId string) bool

IsCollectionNameUnique checks that there is no existing collection with the provided name (case insensitive!).

Note: case sensitive check because the name is used also as a table name for the records.

func (*Dao) IsRecordValueUnique

func (dao *Dao) IsRecordValueUnique(
	collection *models.Collection,
	key string,
	value any,
	excludeId string,
) bool

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

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

func (*Dao) IsUserEmailUnique

func (dao *Dao) IsUserEmailUnique(email string, excludeId string) bool

IsUserEmailUnique checks if the provided email address is not already in use by other users.

func (*Dao) LoadProfile

func (dao *Dao) LoadProfile(user *models.User) error

LoadProfile loads the profile record associated to the provided user.

func (*Dao) LoadProfiles

func (dao *Dao) LoadProfiles(users []*models.User) error

LoadProfiles loads the profile records associated to the provied users list.

func (*Dao) ModelQuery

func (dao *Dao) ModelQuery(m models.Model) *dbx.SelectQuery

ModelQuery creates a new query with preset Select and From fields based on the provided model argument.

func (*Dao) ParamQuery

func (dao *Dao) ParamQuery() *dbx.SelectQuery

ParamQuery returns a new Param select query.

func (*Dao) RecordQuery

func (dao *Dao) RecordQuery(collection *models.Collection) *dbx.SelectQuery

RecordQuery returns a new Record select query.

func (*Dao) RequestQuery

func (dao *Dao) RequestQuery() *dbx.SelectQuery

RequestQuery returns a new Request logs select query.

func (*Dao) RequestsStats

func (dao *Dao) RequestsStats(expr dbx.Expression) ([]*RequestsStatsItem, error)

RequestsStats returns hourly grouped requests logs statistics.

func (*Dao) RunInTransaction

func (dao *Dao) RunInTransaction(fn func(txDao *Dao) error) error

RunInTransaction wraps fn into a transaction.

It is safe to nest RunInTransaction calls.

func (*Dao) Save

func (dao *Dao) Save(m models.Model) error

Save upserts (update or create if primary key is not set) the provided model.

func (*Dao) SaveAdmin

func (dao *Dao) SaveAdmin(admin *models.Admin) error

SaveAdmin upserts the provided Admin model.

func (*Dao) SaveCollection

func (dao *Dao) SaveCollection(collection *models.Collection) error

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

func (*Dao) SaveExternalAuth

func (dao *Dao) SaveExternalAuth(model *models.ExternalAuth) error

SaveExternalAuth upserts the provided ExternalAuth model.

func (*Dao) SaveParam

func (dao *Dao) SaveParam(key string, value any, optEncryptionKey ...string) error

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.

func (*Dao) SaveRecord

func (dao *Dao) SaveRecord(record *models.Record) error

SaveRecord upserts the provided Record model.

func (*Dao) SaveRequest

func (dao *Dao) SaveRequest(request *models.Request) error

SaveRequest upserts the provided Request model.

func (*Dao) SaveUser

func (dao *Dao) SaveUser(user *models.User) error

SaveUser upserts the provided User model.

An empty profile record will be created if the user doesn't have a profile record set yet.

func (*Dao) SyncRecordTableSchema

func (dao *Dao) SyncRecordTableSchema(newCollection *models.Collection, oldCollection *models.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.

func (*Dao) TotalAdmins

func (dao *Dao) TotalAdmins() (int, error)

TotalAdmins returns the number of existing admin records.

func (*Dao) UserQuery

func (dao *Dao) UserQuery() *dbx.SelectQuery

UserQuery returns a new User model select query.

type ExpandFetchFunc

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

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

type RequestsStatsItem

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL