Documentation
¶
Overview ¶
Package entity is an ORM framework based on sqlx.
Index ¶
- Variables
- func Delete(ctx context.Context, ent Entity, db DB) error
- func DeleteCache(ctx context.Context, ent Cacheable) error
- func ExecDelete(ctx context.Context, db DB, stmt *goqu.DeleteDataset) (sql.Result, error)
- func ExecInsert(ctx context.Context, db DB, stmt *goqu.InsertDataset) (sql.Result, error)
- func ExecUpdate(ctx context.Context, db DB, stmt *goqu.UpdateDataset) (sql.Result, error)
- func GetRecord(ctx context.Context, dest any, db DB, stmt *goqu.SelectDataset) error
- func GetRecords(ctx context.Context, dest any, db DB, stmt *goqu.SelectDataset) error
- func GetTotalCount(ctx context.Context, db DB, stmt *goqu.SelectDataset) (int, error)
- func Insert(ctx context.Context, ent Entity, db DB) (int64, error)
- func IsNotFound(err error) bool
- func Load(ctx context.Context, ent Entity, db DB) error
- func NewUpsertRecord(ent Entity, otherColumns ...string) goqu.Record
- func NewUpsertTarget(ent Entity) string
- func QueryBy(ctx context.Context, db DB, stmt *goqu.SelectDataset, ...) error
- func SaveCache(ctx context.Context, ent Cacheable) error
- func SavePoint(ctx context.Context, tx Tx, name string, fn func() error) (err error)
- func Transaction[T Tx, U TxInitiator[T]](db U, fn func(db DB) error) (err error)deprecated
- func TransactionWithOptions[T Tx, U TxInitiator[T]](db U, opt *sql.TxOptions, fn func(db DB) error) (err error)deprecated
- func TransactionWithOptionsX[T Tx, U TxInitiator[T]](ctx context.Context, db U, opt *sql.TxOptions, fn func(db DB) error) (err error)
- func TransactionX[T Tx, U TxInitiator[T]](ctx context.Context, db U, fn func(db DB) error) (err error)
- func TrySavePoint(ctx context.Context, db DB, name string, fn func() error) error
- func TryTransaction[T Tx](db DB, fn func(db DB) error) errordeprecated
- func TryTransactionWithOptions[T Tx](db DB, opt *sql.TxOptions, fn func(db DB) error) errordeprecated
- func TryTransactionWithOptionsX[T Tx](ctx context.Context, db DB, opt *sql.TxOptions, fn func(db DB) error) error
- func TryTransactionX[T Tx](ctx context.Context, db DB, fn func(db DB) error) error
- func Update(ctx context.Context, ent Entity, db DB) error
- func Upsert(ctx context.Context, ent Entity, db DB) error
- type AfterDeleteHook
- type AfterInsertHook
- type AfterUpdateHook
- type BeforeDeleteHook
- type BeforeInsertHook
- type BeforeUpdateHook
- type CacheOption
- type Cacheable
- type Cacher
- type Column
- type DB
- type DomainObjectRepository
- func (r *DomainObjectRepository[ID, DO, PO]) Create(ctx context.Context, do DO) error
- func (r *DomainObjectRepository[ID, DO, PO]) Delete(ctx context.Context, do DO) error
- func (r *DomainObjectRepository[ID, DO, PO]) Find(ctx context.Context, id ID) (DO, error)
- func (r *DomainObjectRepository[ID, DO, PO]) ForEach(ctx context.Context, stmt *goqu.SelectDataset, ...) error
- func (r *DomainObjectRepository[ID, DO, PO]) Get(ctx context.Context, stmt *goqu.SelectDataset) (DO, error)
- func (r *DomainObjectRepository[ID, DO, PO]) NewPersistentObject(ctx context.Context, do DO) (PO, error)
- func (r *DomainObjectRepository[ID, DO, PO]) PageQuery(ctx context.Context, stmt *goqu.SelectDataset, currentPage, pageSize int) ([]DO, Pagination, error)
- func (r *DomainObjectRepository[ID, DO, PO]) Query(ctx context.Context, stmt *goqu.SelectDataset) ([]DO, error)
- func (r *DomainObjectRepository[ID, DO, PO]) ToDomainObjects(src []PO) ([]DO, error)
- func (r *DomainObjectRepository[ID, DO, PO]) Update(ctx context.Context, do DO) error
- func (r *DomainObjectRepository[ID, DO, PO]) UpdateBy(ctx context.Context, id ID, apply func(do DO) (bool, error)) error
- func (r *DomainObjectRepository[ID, DO, PO]) UpdateByQuery(ctx context.Context, stmt *goqu.SelectDataset, apply func(do DO) (bool, error)) error
- func (r *DomainObjectRepository[ID, DO, PO]) Upsert(ctx context.Context, do DO) error
- type Entity
- type Event
- type EventHook
- type Metadata
- type Pagination
- type PersistentObject
- type PrepareInsertStatement
- type PrepareUpdateStatement
- type Repository
- func (r *Repository[ID, R]) Create(ctx context.Context, row R) error
- func (r *Repository[ID, R]) Delete(ctx context.Context, row R) error
- func (r *Repository[ID, R]) Find(ctx context.Context, id ID) (R, error)
- func (r *Repository[ID, R]) ForEach(ctx context.Context, stmt *goqu.SelectDataset, ...) error
- func (r *Repository[ID, R]) Get(ctx context.Context, stmt *goqu.SelectDataset) (R, error)
- func (r *Repository[ID, R]) GetDB() DB
- func (r *Repository[ID, R]) NewEntity(id ID) (R, error)
- func (r *Repository[ID, R]) PageQuery(ctx context.Context, stmt *goqu.SelectDataset, currentPage, pageSize int) (rows []R, page Pagination, err error)
- func (r *Repository[ID, R]) Query(ctx context.Context, stmt *goqu.SelectDataset) ([]R, error)
- func (r *Repository[ID, R]) Update(ctx context.Context, row R) error
- func (r *Repository[ID, R]) UpdateBy(ctx context.Context, id ID, apply func(row R) (bool, error)) error
- func (r *Repository[ID, R]) UpdateByQuery(ctx context.Context, stmt *goqu.SelectDataset, apply func(row R) (bool, error)) error
- func (r *Repository[ID, R]) Upsert(ctx context.Context, row R) error
- type Row
- type Tx
- type TxInitiator
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ( // ErrConflict is returned when a data conflict is detected. ErrConflict = errors.New("record conflict") // ErrNotFound is returned when a record is not found. ErrNotFound = errors.New("record not found") // ReadTimeout is the default timeout for reading entity data. ReadTimeout = 3 * time.Second // WriteTimeout is the default timeout for writing entity data. WriteTimeout = 3 * time.Second )
Functions ¶
func DeleteCache ¶
DeleteCache removes an entity from the cache.
func ExecDelete ¶
ExecDelete executes a delete statement.
func ExecInsert ¶ added in v0.2.3
ExecInsert executes an insert statement.
func ExecUpdate ¶
ExecUpdate executes an update statement.
func GetRecords ¶ added in v0.2.2
GetRecords executes a select query and returns multiple results.
func GetTotalCount ¶
GetTotalCount returns the total number of records matching the query conditions.
func IsNotFound ¶ added in v0.6.1
IsNotFound checks whether an error is a not found error. Repository returns ErrNotFound when a record is not found. GetRecord returns sql.ErrNoRows when a record is not found. Use this function to unify error checking.
func NewUpsertRecord ¶ added in v0.8.0
NewUpsertRecord builds a record for upsert operations. Fields marked as refuse update will not be updated. Use the columns parameter to update additional fields.
func NewUpsertTarget ¶ added in v0.8.4
NewUpsertTarget build "INSERT ... ON CONFLICT target DO UPDATE" target string based on primary keys
func QueryBy ¶ added in v0.5.1
func QueryBy(ctx context.Context, db DB, stmt *goqu.SelectDataset, fn func(ctx context.Context, rows *sqlx.Rows) error) error
QueryBy executes a select query and processes the result set using the provided callback function.
func SavePoint ¶ added in v0.8.2
SavePoint creates a savepoint in a transaction and releases it after the function executes successfully. If the function fails or panics, it rolls back to the savepoint.
func Transaction
deprecated
func Transaction[T Tx, U TxInitiator[T]](db U, fn func(db DB) error) (err error)
Transaction executes a function within a database transaction, committing on success or rolling back on error.
Deprecated: Use TransactionX instead.
func TransactionWithOptions
deprecated
added in
v0.6.4
func TransactionWithOptionsX ¶ added in v0.8.1
func TransactionWithOptionsX[T Tx, U TxInitiator[T]](ctx context.Context, db U, opt *sql.TxOptions, fn func(db DB) error) (err error)
TransactionWithOptionsX executes a function within a database transaction with context and custom options.
func TransactionX ¶ added in v0.8.1
func TransactionX[T Tx, U TxInitiator[T]](ctx context.Context, db U, fn func(db DB) error) (err error)
TransactionX executes a function within a database transaction with context support.
func TrySavePoint ¶ added in v0.8.2
TrySavePoint attempts to create a savepoint in a transaction. Returns an error if the database is not in a transaction.
func TryTransaction
deprecated
added in
v0.5.1
TryTransaction attempts to execute a function within a transaction. If the database is already a transaction, the function is executed directly. If it's a transaction initiator, a transaction is started.
Deprecated: Use TryTransactionX instead.
func TryTransactionWithOptions
deprecated
added in
v0.6.4
func TryTransactionWithOptionsX ¶ added in v0.8.1
func TryTransactionWithOptionsX[T Tx](ctx context.Context, db DB, opt *sql.TxOptions, fn func(db DB) error) error
TryTransactionWithOptionsX attempts to execute a function within a transaction with context and custom options. If the database is already a transaction, the function is executed directly. If it's a transaction initiator, a transaction is started. The specific Tx type must be explicitly specified as it cannot be derived from the DB interface.
Example: TryTransactionWithOptionsX[*sqlx.Tx](ctx, db, opt, func(db entity.DB) error { ... })
func TryTransactionX ¶ added in v0.8.1
TryTransactionX attempts to execute a function within a transaction with context support. If the database is already a transaction, the function is executed directly. If it's a transaction initiator, a transaction is started. The specific Tx type must be explicitly specified as it cannot be derived from the DB interface.
Example: TryTransactionX[*sqlx.Tx](ctx, db, func(db entity.DB) error { ... })
Types ¶
type AfterDeleteHook ¶ added in v0.5.2
AfterDeleteHook is called after deleting an entity.
type AfterInsertHook ¶ added in v0.5.2
AfterInsertHook is called after inserting an entity.
type AfterUpdateHook ¶ added in v0.5.2
AfterUpdateHook is called after updating an entity.
type BeforeDeleteHook ¶ added in v0.5.2
BeforeDeleteHook is called before deleting an entity.
type BeforeInsertHook ¶ added in v0.5.2
BeforeInsertHook is called before inserting an entity.
type BeforeUpdateHook ¶ added in v0.5.2
BeforeUpdateHook is called before updating an entity.
type CacheOption ¶
type CacheOption struct {
Cacher Cacher
Key string
Expiration time.Duration
Compress bool
// If true, no cache will be generated.
// This configuration only controls cache generation, not cache reading.
// Because there is not enough information to make a judgment before data is read.
Disable bool
// Some caches constructed elsewhere have field content that is json encoded before entering the cache.
// These field cache results need to be decoded twice to be used.
RecursiveDecode []string
}
CacheOption contains cache configuration parameters.
type Cacheable ¶
type Cacheable interface {
CacheOption() CacheOption
}
Cacheable is an interface for cacheable entity objects.
type Cacher ¶
type Cacher interface {
Get(ctx context.Context, key string) ([]byte, error)
Put(ctx context.Context, key string, data []byte, expiration time.Duration) error
Delete(ctx context.Context, key string) error
}
Cacher is an interface for cache data storage.
var DefaultCacher Cacher
DefaultCacher is the default cache storage instance.
type Column ¶
type Column struct {
StructField string
DBField string
PrimaryKey bool
AutoIncrement bool
RefuseUpdate bool
ReturningInsert bool
ReturningUpdate bool
}
Column contains field metadata information.
type DB ¶
type DB interface {
sqlx.Queryer
sqlx.QueryerContext
sqlx.Execer
sqlx.ExecerContext
sqlx.Preparer
sqlx.PreparerContext
Get(dest any, query string, args ...any) error
GetContext(ctx context.Context, dest any, query string, args ...any) error
Select(dest any, query string, args ...any) error
SelectContext(ctx context.Context, dest any, query string, args ...any) error
NamedExec(query string, arg any) (sql.Result, error)
NamedExecContext(ctx context.Context, query string, arg any) (sql.Result, error)
NamedQuery(query string, arg any) (*sqlx.Rows, error)
PrepareNamed(query string) (*sqlx.NamedStmt, error)
PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)
Preparex(query string) (*sqlx.Stmt, error)
PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error)
DriverName() string
Rebind(string) string
BindNamed(string, any) (string, []any, error)
}
DB is the database interface that provides common methods for sqlx.DB and sqlx.Tx.
type DomainObjectRepository ¶ added in v0.7.1
type DomainObjectRepository[ID comparable, DO any, PO PersistentObject[ID, DO]] struct { // contains filtered or unexported fields }
DomainObjectRepository is a repository for domain objects.
Note: Some methods accept *goqu.SelectDataset parameters, which exposes technical implementation details and violates DDD principles. Therefore, DomainObjectRepository should not be used as a final implementation but rather as a component of the final implementation.
func NewDomainObjectRepository ¶ added in v0.7.1
func NewDomainObjectRepository[ID comparable, DO any, PO PersistentObject[ID, DO]]( persistentRepository *Repository[ID, PO], ) *DomainObjectRepository[ID, DO, PO]
NewDomainObjectRepository creates a new DomainObjectRepository.
func (*DomainObjectRepository[ID, DO, PO]) Create ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) Create(ctx context.Context, do DO) error
Create saves a new domain object to the database.
func (*DomainObjectRepository[ID, DO, PO]) Delete ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) Delete(ctx context.Context, do DO) error
Delete removes a domain object from the database.
func (*DomainObjectRepository[ID, DO, PO]) Find ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) Find(ctx context.Context, id ID) (DO, error)
Find retrieves a domain object by ID.
func (*DomainObjectRepository[ID, DO, PO]) ForEach ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) ForEach(ctx context.Context, stmt *goqu.SelectDataset, iteratee func(do DO) (bool, error)) error
ForEach iterates over domain objects matching the query. The iteratee function should return false to stop iteration.
func (*DomainObjectRepository[ID, DO, PO]) Get ¶ added in v0.7.4
func (r *DomainObjectRepository[ID, DO, PO]) Get(ctx context.Context, stmt *goqu.SelectDataset) (DO, error)
Get retrieves a single domain object matching the query statement.
func (*DomainObjectRepository[ID, DO, PO]) NewPersistentObject ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) NewPersistentObject(ctx context.Context, do DO) (PO, error)
NewPersistentObject creates a new persistent object from a domain object.
func (*DomainObjectRepository[ID, DO, PO]) PageQuery ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) PageQuery(ctx context.Context, stmt *goqu.SelectDataset, currentPage, pageSize int) ([]DO, Pagination, error)
PageQuery retrieves a paginated list of domain objects matching the query statement.
func (*DomainObjectRepository[ID, DO, PO]) Query ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) Query(ctx context.Context, stmt *goqu.SelectDataset) ([]DO, error)
Query retrieves a list of domain objects matching the query statement.
func (*DomainObjectRepository[ID, DO, PO]) ToDomainObjects ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) ToDomainObjects(src []PO) ([]DO, error)
ToDomainObjects converts a slice of persistent objects to domain objects.
func (*DomainObjectRepository[ID, DO, PO]) Update ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) Update(ctx context.Context, do DO) error
Update updates an existing domain object in the database.
func (*DomainObjectRepository[ID, DO, PO]) UpdateBy ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) UpdateBy(ctx context.Context, id ID, apply func(do DO) (bool, error)) error
UpdateBy retrieves a domain object by ID and updates it using the apply function.
func (*DomainObjectRepository[ID, DO, PO]) UpdateByQuery ¶ added in v0.7.1
func (r *DomainObjectRepository[ID, DO, PO]) UpdateByQuery(ctx context.Context, stmt *goqu.SelectDataset, apply func(do DO) (bool, error)) error
UpdateByQuery queries for domain objects and updates them using the apply function.
type Entity ¶
type Entity interface {
TableName() string
}
Entity is an interface that all entity objects must implement.
type Event ¶
type Event int
Event represents a storage event type.
const ( // EventUnknown is an undefined event constant. EventUnknown Event = iota // EventBeforeInsert before insert entity EventBeforeInsert // EventAfterInsert after insert entity EventAfterInsert // EventBeforeUpdate before update entity EventBeforeUpdate // EventAfterUpdate after update entity EventAfterUpdate // EventBeforeDelete before delete entity EventBeforeDelete // EventAfterDelete after delete entity EventAfterDelete )
type Metadata ¶
type Metadata struct {
Type reflect.Type
TableName string
Columns []Column
PrimaryKeys []Column
// contains filtered or unexported fields
}
Metadata contains entity metadata such as table name, columns, and primary keys.
func NewMetadata ¶
NewMetadata constructs and returns the metadata for an entity object.
type Pagination ¶ added in v0.3.4
type Pagination struct {
First int `json:"first"`
Last int `json:"last"`
Previous int `json:"previous"`
Current int `json:"current"`
Next int `json:"next"`
Size int `json:"size"`
Items int `json:"items"`
}
Pagination contains pagination calculation information for database queries.
func NewPagination ¶ added in v0.3.4
func NewPagination(current, size, items int) Pagination
NewPagination calculates and returns pagination information based on current page, page size, and total items.
func (Pagination) Limit ¶ added in v0.3.4
func (p Pagination) Limit() int
Limit returns the LIMIT value for database queries.
func (Pagination) Offset ¶ added in v0.3.4
func (p Pagination) Offset() int
Offset returns the OFFSET value for database queries.
func (Pagination) ULimit ¶ added in v0.6.1
func (p Pagination) ULimit() uint
ULimit returns the LIMIT value as an unsigned integer for database queries.
func (Pagination) UOffset ¶ added in v0.6.1
func (p Pagination) UOffset() uint
UOffset returns the OFFSET value as an unsigned integer for database queries.
type PersistentObject ¶ added in v0.7.1
type PersistentObject[ID comparable, DO any] interface { Row[ID] GetID() ID Set(context.Context, DO) error ToDomainObject() (DO, error) }
PersistentObject is an interface for domain objects that can be persisted to the database.
type PrepareInsertStatement ¶
type PrepareInsertStatement struct {
// contains filtered or unexported fields
}
PrepareInsertStatement is a prepared statement for inserting entities.
func PrepareInsert ¶
PrepareInsert creates a prepared statement for inserting entities.
func (*PrepareInsertStatement) Close ¶
func (pis *PrepareInsertStatement) Close() error
Close closes the prepared statement
func (*PrepareInsertStatement) ExecContext ¶
func (pis *PrepareInsertStatement) ExecContext(ctx context.Context, ent Entity) (lastID int64, err error)
ExecContext executes the prepared insert statement with the provided entity.
type PrepareUpdateStatement ¶
type PrepareUpdateStatement struct {
// contains filtered or unexported fields
}
PrepareUpdateStatement is a prepared statement for updating entities.
func PrepareUpdate ¶
PrepareUpdate creates a prepared statement for updating entities.
func (*PrepareUpdateStatement) Close ¶
func (pus *PrepareUpdateStatement) Close() error
Close closes the prepared statement
func (*PrepareUpdateStatement) ExecContext ¶
func (pus *PrepareUpdateStatement) ExecContext(ctx context.Context, ent Entity) error
ExecContext executes the prepared update statement with the provided entity.
type Repository ¶ added in v0.6.0
type Repository[ID comparable, R Row[ID]] struct { // contains filtered or unexported fields }
Repository is a generic repository for entity objects.
func NewRepository ¶ added in v0.6.0
func NewRepository[ID comparable, R Row[ID]](db DB) *Repository[ID, R]
NewRepository creates a new Repository instance.
func (*Repository[ID, R]) Create ¶ added in v0.6.0
func (r *Repository[ID, R]) Create(ctx context.Context, row R) error
Create saves a new entity to the database.
func (*Repository[ID, R]) Delete ¶ added in v0.6.0
func (r *Repository[ID, R]) Delete(ctx context.Context, row R) error
Delete removes an entity from the database.
func (*Repository[ID, R]) Find ¶ added in v0.6.0
func (r *Repository[ID, R]) Find(ctx context.Context, id ID) (R, error)
Find retrieves an entity by its primary key.
func (*Repository[ID, R]) ForEach ¶ added in v0.6.0
func (r *Repository[ID, R]) ForEach(ctx context.Context, stmt *goqu.SelectDataset, iteratee func(row R) (bool, error)) error
ForEach iterates over entities matching the query statement. The iteratee function should return false to stop iteration.
func (*Repository[ID, R]) Get ¶ added in v0.7.4
func (r *Repository[ID, R]) Get(ctx context.Context, stmt *goqu.SelectDataset) (R, error)
Get retrieves a single entity matching the query statement.
func (*Repository[ID, R]) GetDB ¶ added in v0.6.3
func (r *Repository[ID, R]) GetDB() DB
GetDB returns the database connection used by the repository.
func (*Repository[ID, R]) NewEntity ¶ added in v0.6.1
func (r *Repository[ID, R]) NewEntity(id ID) (R, error)
NewEntity creates a new entity object with the given ID.
func (*Repository[ID, R]) PageQuery ¶ added in v0.6.0
func (r *Repository[ID, R]) PageQuery(ctx context.Context, stmt *goqu.SelectDataset, currentPage, pageSize int) (rows []R, page Pagination, err error)
PageQuery retrieves a paginated list of entities matching the query statement.
func (*Repository[ID, R]) Query ¶ added in v0.6.3
func (r *Repository[ID, R]) Query(ctx context.Context, stmt *goqu.SelectDataset) ([]R, error)
Query retrieves a list of entities matching the query statement.
func (*Repository[ID, R]) Update ¶ added in v0.6.0
func (r *Repository[ID, R]) Update(ctx context.Context, row R) error
Update updates an existing entity.
func (*Repository[ID, R]) UpdateBy ¶ added in v0.7.1
func (r *Repository[ID, R]) UpdateBy(ctx context.Context, id ID, apply func(row R) (bool, error)) error
UpdateBy retrieves an entity by ID and executes the apply function to update it. If apply returns false, changes are not saved.
func (*Repository[ID, R]) UpdateByQuery ¶ added in v0.6.0
func (r *Repository[ID, R]) UpdateByQuery(ctx context.Context, stmt *goqu.SelectDataset, apply func(row R) (bool, error)) error
UpdateByQuery queries for entities and updates them using the apply function. If apply returns false for a row, that update is skipped.
type Row ¶ added in v0.7.0
type Row[ID comparable] interface { Entity SetID(ID) error }
Row is an entity row interface.
type TxInitiator ¶ added in v0.8.0
TxInitiator is an interface for initiating database transactions.