entity

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: May 1, 2024 License: BSD-3-Clause Imports: 15 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

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrConflict 发生了数据冲突
	ErrConflict = fmt.Errorf("database record conflict")

	// 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 interface{}, db DB, stmt *goqu.SelectDataset) error

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

func GetRecords added in v0.2.2

func GetRecords(ctx context.Context, dest interface{}, 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 Load

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

Load 从数据库载入entity

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 Transaction

func Transaction(db *sqlx.DB, fn func(tx *sqlx.Tx) error) (err error)

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

func TryTransaction added in v0.5.1

func TryTransaction(db DB, fn func(DB) error) error

TryTransaction 尝试执行事务,如果DB不是*sqlx.DB,则直接执行fn

func Update

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

Update 更新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 interface{}, query string, args ...interface{}) error
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	Select(dest interface{}, query string, args ...interface{}) error
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	NamedExec(query string, arg interface{}) (sql.Result, error)
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)
	NamedQuery(query string, arg interface{}) (*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, interface{}) (string, []interface{}, error)
}

DB 数据库接口 sqlx.DB 和 sqlx.Tx 公共方法

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值

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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