entity

package module
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: BSD-3-Clause Imports: 17 Imported by: 0

README

介绍

Go Reference

基于sqlx库,封装了实体对象的基本CRUD方法,除数据库读写外,还实现了自定义缓存机制,在数据库读写过程中,自动使用和更新缓存

样例代码见example.go

Struct Tag

type User struct {
	ID       int64 `db:"user_id,primaryKey,autoIncrement"`
	CreateAt int64 `db:"create_at,refuseUpdate,returningInsert"`
	UpdateAt int64 `db:"update_at"`
	Other    bool  `db:"-"`
}

实体配置,写在db

可用tag:

  • primaryKey 主键字段,每个实体对象至少要声明一个。别名:primary_key
  • refuseUpdate 不允许更新,UPDATE时会被忽略,当设置了primaryKeyautoIncrementreturningUpdate时,这个配置会自动生效。别名: refuse_update
  • autoIncrement 自增长主键,构造INSERT时此字段会被忽略。别名: auto_increment
  • returningInsert insert时,这个字段会被放到RETURNING子句内返回,无论使用的数据库是否支持RETURNING。别名: returning_insert
  • returningUpdate update时,这个字段会被放到RETURNING子句内返回,无论使用的数据库是否支持RETURNING。别名: returning_update
  • returning 等于同时使用returningInsertreturningUpdate

Documentation

Overview

Package entity is an ORM framework based on sqlx.

Index

Constants

This section is empty.

Variables

View Source
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 Delete

func Delete(ctx context.Context, ent Entity, db DB) error

Delete removes an entity from the database.

func DeleteCache

func DeleteCache(ctx context.Context, ent Cacheable) error

DeleteCache removes an entity from the cache.

func ExecDelete

func ExecDelete(ctx context.Context, db DB, stmt *goqu.DeleteDataset) (sql.Result, error)

ExecDelete executes a delete statement.

func ExecInsert added in v0.2.3

func ExecInsert(ctx context.Context, db DB, stmt *goqu.InsertDataset) (sql.Result, error)

ExecInsert executes an insert statement.

func ExecUpdate

func ExecUpdate(ctx context.Context, db DB, stmt *goqu.UpdateDataset) (sql.Result, error)

ExecUpdate executes an update statement.

func GetRecord added in v0.2.2

func GetRecord(ctx context.Context, dest any, db DB, stmt *goqu.SelectDataset) error

GetRecord executes a select query and returns a single result.

func GetRecords added in v0.2.2

func GetRecords(ctx context.Context, dest any, db DB, stmt *goqu.SelectDataset) error

GetRecords executes a select query and returns multiple results.

func GetTotalCount

func GetTotalCount(ctx context.Context, db DB, stmt *goqu.SelectDataset) (int, error)

GetTotalCount returns the total number of records matching the query conditions.

func Insert

func Insert(ctx context.Context, ent Entity, db DB) (int64, error)

Insert saves a new entity to the database.

func IsNotFound added in v0.6.1

func IsNotFound(err error) bool

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 Load

func Load(ctx context.Context, ent Entity, db DB) error

Load retrieves an entity from the database.

func NewUpsertRecord added in v0.8.0

func NewUpsertRecord(ent Entity, otherColumns ...string) goqu.Record

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

func NewUpsertTarget(ent Entity) string

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 SaveCache

func SaveCache(ctx context.Context, ent Cacheable) error

SaveCache saves an entity to the cache.

func SavePoint added in v0.8.2

func SavePoint(ctx context.Context, tx Tx, name string, fn func() error) (err error)

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 TransactionWithOptions[T Tx, U TxInitiator[T]](db U, opt *sql.TxOptions, fn func(db DB) error) (err error)

TransactionWithOptions executes a function within a database transaction with custom options.

Deprecated: Use TransactionWithOptionsX instead.

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

func TrySavePoint(ctx context.Context, db DB, name string, fn func() error) error

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

func TryTransaction[T Tx](db DB, fn func(db DB) error) error

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 TryTransactionWithOptions[T Tx](db DB, opt *sql.TxOptions, fn func(db DB) error) error

TryTransactionWithOptions attempts to execute a function within a transaction with custom options.

Deprecated: Use TryTransactionWithOptionsX instead.

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

func TryTransactionX[T Tx](ctx context.Context, db DB, fn func(db DB) error) error

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

func Update

func Update(ctx context.Context, ent Entity, db DB) error

Update updates an existing entity in the database.

func Upsert added in v0.7.2

func Upsert(ctx context.Context, ent Entity, db DB) error

Upsert inserts a new entity or updates an existing one in the database.

Types

type AfterDeleteHook added in v0.5.2

type AfterDeleteHook interface {
	AfterDelete(ctx context.Context) error
}

AfterDeleteHook is called after deleting an entity.

type AfterInsertHook added in v0.5.2

type AfterInsertHook interface {
	AfterInsert(ctx context.Context) error
}

AfterInsertHook is called after inserting an entity.

type AfterUpdateHook added in v0.5.2

type AfterUpdateHook interface {
	AfterUpdate(ctx context.Context) error
}

AfterUpdateHook is called after updating an entity.

type BeforeDeleteHook added in v0.5.2

type BeforeDeleteHook interface {
	BeforeDelete(ctx context.Context) error
}

BeforeDeleteHook is called before deleting an entity.

type BeforeInsertHook added in v0.5.2

type BeforeInsertHook interface {
	BeforeInsert(ctx context.Context) error
}

BeforeInsertHook is called before inserting an entity.

type BeforeUpdateHook added in v0.5.2

type BeforeUpdateHook interface {
	BeforeUpdate(ctx context.Context) error
}

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.

func (Column) String

func (c Column) String() string

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.

func (*DomainObjectRepository[ID, DO, PO]) Upsert added in v0.7.2

func (r *DomainObjectRepository[ID, DO, PO]) Upsert(ctx context.Context, do DO) error

Upsert inserts a new domain object or updates an existing one.

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 EventHook added in v0.5.2

type EventHook interface {
	OnEntityEvent(ctx context.Context, ev Event) error
}

EventHook is an interface for event-style hooks.

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

func NewMetadata(ent Entity) (*Metadata, error)

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

func PrepareInsert(ctx context.Context, ent Entity, db DB) (*PrepareInsertStatement, error)

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

func PrepareUpdate(ctx context.Context, ent Entity, db DB) (*PrepareUpdateStatement, error)

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.

func (*Repository[ID, R]) Upsert added in v0.7.2

func (r *Repository[ID, R]) Upsert(ctx context.Context, row R) error

Upsert inserts a new entity or updates an existing one.

type Row added in v0.7.0

type Row[ID comparable] interface {
	Entity

	SetID(ID) error
}

Row is an entity row interface.

type Tx added in v0.8.0

type Tx interface {
	DB

	Commit() error
	Rollback() error
}

Tx is a database transaction interface.

type TxInitiator added in v0.8.0

type TxInitiator[T Tx] interface {
	BeginTxx(ctx context.Context, opts *sql.TxOptions) (T, error)
}

TxInitiator is an interface for initiating database transactions.

type Validator added in v0.8.5

type Validator interface {
	Validate() error
}

Validator is an interface for domain objects that can validate themselves. If a domain object implements this interface, DomainObjectRepository will call Validate() before write operations.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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