entity

package module
v0.8.4 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 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 发生了数据冲突
	ErrConflict = errors.New("record conflict")

	// ErrNotFound 记录未找到错误
	ErrNotFound = errors.New("record not found")

	// ReadTimeout 读取entity数据的默认超时时间
	ReadTimeout = 3 * time.Second
	// WriteTimeout 写入entity数据的默认超时时间
	WriteTimeout = 3 * time.Second
)

Functions

func Delete

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

Delete 删除entity

func DeleteCache

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

DeleteCache 删除entity缓存

func ExecDelete

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

ExecDelete 执行删除语句

func ExecInsert added in v0.2.3

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

ExecInsert 执行插入语句

func ExecUpdate

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

ExecUpdate 执行更新语句

func GetRecord added in v0.2.2

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

GetRecord 执行查询语句,返回单条结果

func GetRecords added in v0.2.2

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

GetRecords 执行查询语句,返回多条结果

func GetTotalCount

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

GetTotalCount 符合条件的总记录数量

func Insert

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

Insert 插入新entity

func IsNotFound added in v0.6.1

func IsNotFound(err error) bool

IsNotFound 判断是否是未找到错误

repository在没有找到记录时返回ErrNotFound错误 GetRecord()在没有找到记录时返回sql.ErrNoRows错误 使用这个方法来统一处理错误判断

func Load

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

Load 从数据库载入entity

func NewUpsertRecord added in v0.8.0

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

NewUpsertRecord 构建upsert更新的记录

凡是refuse update的字段都不会被更新,如果需要更新其他字段,可以通过columns参数指定

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 查询并使用回调函数处理游标

func SaveCache

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

SaveCache 保存entity缓存

func SavePoint added in v0.8.2

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

SavePoint 在事务中创建保存点,并在fn执行成功后释放保存点,fn执行失败或panic时回滚到保存点

func Transaction deprecated

func Transaction[T Tx, U TxInitiator[T]](db U, fn func(db DB) error) (err error)

Transaction 执行事务过程,根据结果选择提交或回滚

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 执行事务过程,根据结果选择提交或回滚

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 执行事务过程,根据结果选择提交或回滚

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 执行事务过程,根据结果选择提交或回滚

func TrySavePoint added in v0.8.2

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

TrySavePoint 尝试创建保存点,如果db不是Tx类型,则返回错误

func TryTransaction deprecated added in v0.5.1

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

TryTransaction 尝试执行事务,如果DB是Tx类型,则直接执行fn,如果DB是TxInitiator类型,则开启事务执行fn

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 尝试执行事务,如果DB不是*sqlx.DB,则直接执行fn,如果DB是TxInitiator类型,则开启事务执行fn

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 尝试执行事务,如果DB是Tx类型,则直接执行fn,如果DB是TxInitiator类型,则开启事务执行fn

由于入参是DB接口,无法直接推导出具体的Tx类型,所以需要在调用时显式指定Tx类型参数

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 尝试执行事务,如果DB是Tx类型,则直接执行fn,如果DB是TxInitiator类型,则开启事务执行fn

由于入参是DB接口,无法直接推导出具体的Tx类型,所以需要在调用时显式指定Tx类型参数

TryTransactionX[*sqlx.Tx](ctx, db, func(db entity.DB) error

func Update

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

Update 更新entity

func Upsert added in v0.7.2

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

Upsert 插入或更新entity

Types

type AfterDeleteHook added in v0.5.2

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

AfterDeleteHook 在删除后调用

type AfterInsertHook added in v0.5.2

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

AfterInsertHook 在插入后调用

type AfterUpdateHook added in v0.5.2

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

AfterUpdateHook 在更新后调用

type BeforeDeleteHook added in v0.5.2

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

BeforeDeleteHook 在删除前调用

type BeforeInsertHook added in v0.5.2

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

BeforeInsertHook 在插入前调用

type BeforeUpdateHook added in v0.5.2

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

BeforeUpdateHook 在更新前调用

type CacheOption

type CacheOption struct {
	Cacher     Cacher
	Key        string
	Expiration time.Duration
	Compress   bool
	// 如果为true,将不会生成缓存
	// 这个配置只控制缓存的生成,不控制缓存的读取
	// 因为在没有读到数据之前,没有足够的信息进行判断
	Disable bool
	// 某些由其它地方构造的缓存,其中存在字段内容进入缓存前先被json encode过
	// 这些字段缓存结果需要被decode两次才能使用
	RecursiveDecode []string
}

CacheOption 缓存参数

type Cacheable

type Cacheable interface {
	CacheOption() CacheOption
}

Cacheable 可缓存实体对象接口

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 缓存数据存储接口

var DefaultCacher Cacher

DefaultCacher 默认缓存存储

type Column

type Column struct {
	StructField     string
	DBField         string
	PrimaryKey      bool
	AutoIncrement   bool
	RefuseUpdate    bool
	ReturningInsert bool
	ReturningUpdate bool
}

Column 字段信息

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 数据库接口 sqlx.DB 和 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.

有些方法的入参使用了*goqu.SelectDataset,违背了DDD的基础设施层不应该暴露技术细节的原则, 因此DomainObjectRepository不应该作为最终的实现,应该作为最终实现的组件使用

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.

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.

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 use id to find a domain object.

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 based on the provided query statement.

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 domain object based on the provided 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 based on the provided 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 domain objects based on the provided 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 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 a domain object.

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 updates a domain object by id 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 updates domain objects by a query statement 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 or updates a domain object.

type Entity

type Entity interface {
	TableName() string
}

Entity 实体对象接口

type Event

type Event int

Event 存储事件

const (
	// EventUnknown 未定义事件
	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 事件风格钩子

type Metadata

type Metadata struct {
	Type        reflect.Type
	TableName   string
	Columns     []Column
	PrimaryKeys []Column
	// contains filtered or unexported fields
}

Metadata 元数据

func NewMetadata

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

NewMetadata 构造实体对象元数据

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 数据库分页计算

func NewPagination added in v0.3.4

func NewPagination(current, size, items int) Pagination

NewPagination 计算分页页码

func (Pagination) Limit added in v0.3.4

func (p Pagination) Limit() int

Limit 数据库查询LIMIT值

func (Pagination) Offset added in v0.3.4

func (p Pagination) Offset() int

Offset 数据库查询OFFSET值

func (Pagination) ULimit added in v0.6.1

func (p Pagination) ULimit() uint

ULimit 数据库查询LIMIT值

func (Pagination) UOffset added in v0.6.1

func (p Pagination) UOffset() uint

UOffset 数据库查询OFFSET值

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 持久化对象接口

type PrepareInsertStatement

type PrepareInsertStatement struct {
	// contains filtered or unexported fields
}

PrepareInsertStatement is a prepared insert statement for entity

func PrepareInsert

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

PrepareInsert returns a prepared insert statement for Entity

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 a prepared insert statement using the Entity passed.

type PrepareUpdateStatement

type PrepareUpdateStatement struct {
	// contains filtered or unexported fields
}

PrepareUpdateStatement is a prepared update statement for entity

func PrepareUpdate

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

PrepareUpdate returns a prepared update statement for Entity

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 a prepared update statement using the Entity passed.

type Repository added in v0.6.0

type Repository[ID comparable, R Row[ID]] struct {
	// contains filtered or unexported fields
}

Repository 实体仓库

func NewRepository added in v0.6.0

func NewRepository[ID comparable, R Row[ID]](db DB) *Repository[ID, R]

NewRepository 创建实体仓库

func (*Repository[ID, R]) Create added in v0.6.0

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

Create 保存新的实体

func (*Repository[ID, R]) Delete added in v0.6.0

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

Delete 删除实体

func (*Repository[ID, R]) Find added in v0.6.0

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

Find 根据主键查询实体

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 根据查询遍历实体,iteratee return false则停止遍历

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 根据查询条件获取单个实体

func (*Repository[ID, R]) GetDB added in v0.6.3

func (r *Repository[ID, R]) GetDB() DB

GetDB 获取数据库连接

func (*Repository[ID, R]) NewEntity added in v0.6.1

func (r *Repository[ID, R]) NewEntity(id ID) (R, error)

NewEntity 创建实体对象

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 分页查询

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 通过查询条件获取实体列表

func (*Repository[ID, R]) Update added in v0.6.0

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

Update 更新实体

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 根据ID查询实体并执行更新函数,apply return false则不保存

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 查询并更新,apply return false则放弃那一条的更新

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

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

Upsert 插入或更新实体

type Row added in v0.7.0

type Row[ID comparable] interface {
	Entity

	SetID(ID) error
}

Row 实体行接口

type Tx added in v0.8.0

type Tx interface {
	DB

	Commit() error
	Rollback() error
}

Tx 事务接口

type TxInitiator added in v0.8.0

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

TxInitiator 事务发起接口

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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