unitofwork

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: MIT Imports: 9 Imported by: 0

README

工作单元模式 GORM 插件

这是一个为 GORM 设计的工作单元模式插件,提供了完整的工作单元模式实现,包括自动事务管理、实体跟踪、依赖关系管理、脏检查等功能。

功能特性

  • 自动事务管理: 自动管理数据库事务的开始、提交和回滚
  • 实体跟踪: 自动跟踪实体的创建、更新和删除操作
  • 依赖关系管理: 基于实体依赖关系自动排序操作执行顺序
  • 脏检查: 自动检测实体变更,只更新发生变化的字段
  • 批量优化: 自动合并和优化数据库操作
  • 乐观锁: 支持乐观锁并发控制
  • 软删除: 支持软删除机制
  • 并发安全: 线程安全的实现
  • 上下文管理: 完善的上下文传递和管理
  • 详细日志: 可配置的详细操作日志

快速开始

1. 安装插件
import "github.com/unionj-cloud/toolkit/unitofwork"
2. 定义实体

实体需要实现 Entity 接口,推荐继承 BaseEntity

type User struct {
    unitofwork.BaseEntity
    Name  string `gorm:"size:100;not null" json:"name"`
    Email string `gorm:"size:255;uniqueIndex" json:"email"`
    Age   int    `json:"age"`
}

func (u *User) GetTableName() string {
    return "users"
}

func (u *User) Validate() error {
    if u.Name == "" {
        return fmt.Errorf("用户名不能为空")
    }
    if u.Email == "" {
        return fmt.Errorf("邮箱不能为空")
    }
    return nil
}
3. 注册插件
// 创建数据库连接
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
    panic("数据库连接失败")
}

// 注册工作单元插件
plugin := unitofwork.NewPlugin()
if err := db.Use(plugin); err != nil {
    panic("插件注册失败")
}
4. 使用工作单元
err := unitofwork.WithUnitOfWork(context.Background(), db, func(db *gorm.DB, uow *unitofwork.UnitOfWork) error {
    // 创建用户
    user := &User{
        Name:  "张三",
        Email: "zhangsan@example.com",
        Age:   25,
    }
    if err := db.Create(user).Error; err != nil {
        return err
    }

    // 创建文章
    post := &Post{
        Title:   "我的第一篇文章",
        Content: "文章内容...",
        UserID:  user.GetID(),
    }
    return db.Create(post).Error
})

配置选项

插件配置
plugin := unitofwork.NewPlugin(
    // 启用/禁用自动管理
    unitofwork.WithPluginAutoManage(true),
    
    // 自定义上下文键名
    unitofwork.WithPluginContextKey("my_uow"),
    
    // 配置工作单元选项
    unitofwork.WithPluginUnitOfWorkConfig(&unitofwork.Config{
        EnableDirtyCheck:     true,  // 启用脏检查
        BatchSize:            1000,  // 批量操作大小
        EnableOperationMerge: true,  // 启用操作合并
        MaxEntityCount:       5000,  // 最大实体数量
        EnableDetailLog:      false, // 启用详细日志
    }),
    
    // 配置实体依赖关系
    unitofwork.WithPluginDependencyMapping(map[reflect.Type][]reflect.Type{
        reflect.TypeOf(&Post{}): {reflect.TypeOf(&User{})}, // Post 依赖于 User
        reflect.TypeOf(&Tag{}):  {reflect.TypeOf(&User{})}, // Tag 依赖于 User
    }),
)
工作单元配置
uow := unitofwork.NewUnitOfWork(db,
    unitofwork.WithDirtyCheck(true),      // 启用脏检查
    unitofwork.WithBatchSize(500),        // 批量大小
    unitofwork.WithOperationMerge(true),  // 操作合并
    unitofwork.WithMaxEntityCount(1000),  // 实体数量限制
    unitofwork.WithDetailLog(true),       // 详细日志
)

高级用法

依赖关系管理
// 配置实体依赖关系
dependencyMapping := map[reflect.Type][]reflect.Type{
    reflect.TypeOf(&Post{}): {reflect.TypeOf(&User{})},
    reflect.TypeOf(&Tag{}):  {reflect.TypeOf(&User{})},
}

plugin := unitofwork.NewPlugin(
    unitofwork.WithPluginDependencyMapping(dependencyMapping),
)

// 使用时,操作会自动按依赖关系排序
err := unitofwork.WithUnitOfWork(ctx, db, func(db *gorm.DB, uow *unitofwork.UnitOfWork) error {
    // 即使先创建 Post,实际执行时会先创建 User
    post := &Post{Title: "文章", Content: "内容", UserID: 1}
    db.Create(post)
    
    user := &User{Name: "作者", Email: "author@example.com", Age: 30}
    user.ID = 1
    db.Create(user)
    
    return nil
})
脏检查
// 启用脏检查后,只有实际发生变化的字段才会被更新
err := unitofwork.WithUnitOfWork(ctx, db, func(db *gorm.DB, uow *unitofwork.UnitOfWork) error {
    // 加载实体并创建快照
    var user User
    db.First(&user, 1)
    uow.TakeSnapshot(&user)
    
    // 修改实体
    user.Age = 26  // 只有这个字段会被更新
    
    return db.Save(&user).Error
})
手动工作单元管理
// 禁用自动管理,手动控制工作单元
plugin := unitofwork.NewPlugin(unitofwork.WithPluginAutoManage(false))
db.Use(plugin)

// 手动创建工作单元
uow := unitofwork.NewUnitOfWork(db)

// 手动注册实体
user := &User{Name: "手动用户", Email: "manual@example.com", Age: 25}
if err := uow.Create(user); err != nil {
    return err
}

// 手动提交
if err := uow.Commit(); err != nil {
    return err
}
错误处理和回滚
err := unitofwork.WithUnitOfWork(ctx, db, func(db *gorm.DB, uow *unitofwork.UnitOfWork) error {
    // 创建用户
    user := &User{Name: "用户", Email: "user@example.com", Age: 25}
    if err := db.Create(user).Error; err != nil {
        return err
    }
    
    // 模拟业务逻辑错误
    if someCondition {
        return errors.New("业务逻辑错误")
    }
    
    return nil
})

if err != nil {
    // 发生错误时,所有操作都会自动回滚
    fmt.Printf("操作失败: %v", err)
}

实体接口

基础接口
type Entity interface {
    GetID() uint
    SetID(id uint)
    GetTableName() string
    IsNew() bool
}
扩展接口
// 乐观锁支持
type HasRevision interface {
    Entity
    GetRevision() int64
    SetRevision(revision int64)
    GetRevisionNext() int64
}

// 时间戳支持
type HasTimestamps interface {
    Entity
    GetCreatedAt() time.Time
    SetCreatedAt(createdAt time.Time)
    GetUpdatedAt() time.Time
    SetUpdatedAt(updatedAt time.Time)
}

// 软删除支持
type SoftDelete interface {
    Entity
    GetDeletedAt() gorm.DeletedAt
    SetDeletedAt(deletedAt gorm.DeletedAt)
    IsDeleted() bool
}

// 验证支持
type Validatable interface {
    Entity
    Validate() error
}

性能优化

  1. 批量操作: 自动将相同类型的操作合并为批量操作
  2. 操作优化: 移除冗余操作(如创建后立即删除)
  3. 依赖排序: 按依赖关系优化执行顺序
  4. 内存保护: 可配置的实体数量限制
  5. 连接池: 复用数据库连接

最佳实践

  1. 实体设计: 继承 BaseEntity 并实现必要的接口
  2. 依赖配置: 提前配置好实体间的依赖关系
  3. 错误处理: 适当处理验证错误和业务逻辑错误
  4. 批量大小: 根据数据量调整合适的批量大小
  5. 日志配置: 在开发环境启用详细日志,生产环境关闭
  6. 并发控制: 利用乐观锁处理并发更新

注意事项

  1. 实体必须实现 Entity 接口才能被工作单元管理
  2. 启用自动管理时,GORM 的默认 CRUD 操作会被拦截
  3. 依赖关系配置应该在插件初始化时完成
  4. 脏检查会增加内存使用,大量数据时需要注意
  5. 工作单元是线程安全的,但建议每个请求使用独立的工作单元

许可证

MIT License

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertToTypedSlice

func ConvertToTypedSlice(input []Entity, elemType reflect.Type) interface{}

func SetUnitOfWorkToContext

func SetUnitOfWorkToContext(ctx context.Context, uow *UnitOfWork, key string) context.Context

SetUnitOfWorkToContext 将工作单元设置到上下文

func WithUnitOfWork

func WithUnitOfWork(ctx context.Context, db *gorm.DB, fn func(*gorm.DB, *UnitOfWork) error, options ...ConfigOption) error

WithUnitOfWork 在上下文中使用工作单元

Types

type BaseEntity

type BaseEntity struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	CreatedAt time.Time      `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt time.Time      `gorm:"autoUpdateTime" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
	Revision  int64          `gorm:"default:1" json:"revision"`
}

BaseEntity 基础实体结构,可嵌入到业务实体中

func (*BaseEntity) GetCreatedAt

func (b *BaseEntity) GetCreatedAt() time.Time

GetCreatedAt 实现HasTimestamps接口

func (*BaseEntity) GetDeletedAt

func (b *BaseEntity) GetDeletedAt() gorm.DeletedAt

GetDeletedAt 实现SoftDelete接口

func (*BaseEntity) GetID

func (b *BaseEntity) GetID() uint

GetID 实现Entity接口

func (*BaseEntity) GetRevision

func (b *BaseEntity) GetRevision() int64

GetRevision 实现HasRevision接口

func (*BaseEntity) GetRevisionNext

func (b *BaseEntity) GetRevisionNext() int64

GetRevisionNext 实现HasRevision接口

func (*BaseEntity) GetTableName

func (b *BaseEntity) GetTableName() string

GetTableName 默认实现,子类应重写

func (*BaseEntity) GetUpdatedAt

func (b *BaseEntity) GetUpdatedAt() time.Time

GetUpdatedAt 实现HasTimestamps接口

func (*BaseEntity) IsDeleted

func (b *BaseEntity) IsDeleted() bool

IsDeleted 实现SoftDelete接口

func (*BaseEntity) IsNew

func (b *BaseEntity) IsNew() bool

IsNew 实现Entity接口

func (*BaseEntity) SetCreatedAt

func (b *BaseEntity) SetCreatedAt(createdAt time.Time)

SetCreatedAt 实现HasTimestamps接口

func (*BaseEntity) SetDeletedAt

func (b *BaseEntity) SetDeletedAt(deletedAt gorm.DeletedAt)

SetDeletedAt 实现SoftDelete接口

func (*BaseEntity) SetID

func (b *BaseEntity) SetID(id uint)

SetID 实现Entity接口

func (*BaseEntity) SetRevision

func (b *BaseEntity) SetRevision(revision int64)

SetRevision 实现HasRevision接口

func (*BaseEntity) SetUpdatedAt

func (b *BaseEntity) SetUpdatedAt(updatedAt time.Time)

SetUpdatedAt 实现HasTimestamps接口

func (*BaseEntity) Validate

func (b *BaseEntity) Validate() error

Validate 默认验证实现

type BulkDeleteOperation

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

BulkDeleteOperation 批量删除操作

func NewBulkDeleteOperation

func NewBulkDeleteOperation(entities []Entity) *BulkDeleteOperation

NewBulkDeleteOperation 创建批量删除操作

func (*BulkDeleteOperation) CanMerge

func (op *BulkDeleteOperation) CanMerge(other Operation) bool

CanMerge 实现Operation接口

func (*BulkDeleteOperation) Execute

func (op *BulkDeleteOperation) Execute(db *gorm.DB) error

Execute 实现Operation接口

func (*BulkDeleteOperation) GetEntities

func (op *BulkDeleteOperation) GetEntities() []Entity

GetEntities 获取所有实体

func (*BulkDeleteOperation) GetEntity

func (op *BulkDeleteOperation) GetEntity() Entity

GetEntity 实现Operation接口

func (*BulkDeleteOperation) GetEntityType

func (op *BulkDeleteOperation) GetEntityType() reflect.Type

GetEntityType 实现Operation接口

func (*BulkDeleteOperation) GetOperationType

func (op *BulkDeleteOperation) GetOperationType() OperationType

GetOperationType 实现Operation接口

func (*BulkDeleteOperation) Merge

func (op *BulkDeleteOperation) Merge(other Operation) Operation

Merge 实现Operation接口

func (*BulkDeleteOperation) SameIdentity

func (op *BulkDeleteOperation) SameIdentity(other Operation) bool

SameIdentity 实现Operation接口

type BulkInsertOperation

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

BulkInsertOperation 批量插入操作

func NewBulkInsertOperation

func NewBulkInsertOperation(entities []Entity, insertOperation *InsertOperation) *BulkInsertOperation

NewBulkInsertOperation 创建批量插入操作

func (*BulkInsertOperation) CanMerge

func (op *BulkInsertOperation) CanMerge(other Operation) bool

CanMerge 实现Operation接口

func (*BulkInsertOperation) Execute

func (op *BulkInsertOperation) Execute(db *gorm.DB) error

Execute 实现Operation接口

func (*BulkInsertOperation) GetEntities

func (op *BulkInsertOperation) GetEntities() []Entity

GetEntities 获取所有实体

func (*BulkInsertOperation) GetEntity

func (op *BulkInsertOperation) GetEntity() Entity

GetEntity 实现Operation接口

func (*BulkInsertOperation) GetEntityType

func (op *BulkInsertOperation) GetEntityType() reflect.Type

GetEntityType 实现Operation接口

func (*BulkInsertOperation) GetOperationType

func (op *BulkInsertOperation) GetOperationType() OperationType

GetOperationType 实现Operation接口

func (*BulkInsertOperation) Merge

func (op *BulkInsertOperation) Merge(other Operation) Operation

Merge 实现Operation接口

func (*BulkInsertOperation) SameIdentity

func (op *BulkInsertOperation) SameIdentity(other Operation) bool

SameIdentity 实现Operation接口

type BulkUpdateOperation

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

BulkUpdateOperation 批量更新操作

func NewBulkUpdateOperation

func NewBulkUpdateOperation(entities []Entity) *BulkUpdateOperation

NewBulkUpdateOperation 创建批量更新操作

func (*BulkUpdateOperation) CanMerge

func (op *BulkUpdateOperation) CanMerge(other Operation) bool

CanMerge 实现Operation接口

func (*BulkUpdateOperation) Execute

func (op *BulkUpdateOperation) Execute(db *gorm.DB) error

Execute 实现Operation接口

func (*BulkUpdateOperation) GetEntities

func (op *BulkUpdateOperation) GetEntities() []Entity

GetEntities 获取所有实体

func (*BulkUpdateOperation) GetEntity

func (op *BulkUpdateOperation) GetEntity() Entity

GetEntity 实现Operation接口

func (*BulkUpdateOperation) GetEntityType

func (op *BulkUpdateOperation) GetEntityType() reflect.Type

GetEntityType 实现Operation接口

func (*BulkUpdateOperation) GetOperationType

func (op *BulkUpdateOperation) GetOperationType() OperationType

GetOperationType 实现Operation接口

func (*BulkUpdateOperation) Merge

func (op *BulkUpdateOperation) Merge(other Operation) Operation

Merge 实现Operation接口

func (*BulkUpdateOperation) SameIdentity

func (op *BulkUpdateOperation) SameIdentity(other Operation) bool

SameIdentity 实现Operation接口

type Callback

type Callback func(*UnitOfWork) error

Callback 工作单元回调函数

type Config

type Config struct {
	// 是否启用自动脏检查
	EnableDirtyCheck bool

	// 批量操作大小
	BatchSize int

	// 是否启用操作合并
	EnableOperationMerge bool

	// 最大实体数量(内存保护)
	// 零值表示无限制
	MaxEntityCount int

	// 是否启用详细日志
	EnableDetailLog bool
}

Config 工作单元配置

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 默认配置

type ConfigOption

type ConfigOption func(*Config)

ConfigOption 配置选项函数

func WithBatchSize

func WithBatchSize(size int) ConfigOption

WithBatchSize 配置批量大小

func WithDetailLog

func WithDetailLog(enabled bool) ConfigOption

WithDetailLog 配置详细日志

func WithDirtyCheck

func WithDirtyCheck(enabled bool) ConfigOption

WithDirtyCheck 配置脏检查

func WithMaxEntityCount

func WithMaxEntityCount(count int) ConfigOption

WithMaxEntityCount 配置最大实体数量

func WithOperationMerge

func WithOperationMerge(enabled bool) ConfigOption

WithOperationMerge 配置操作合并

type ContextUnitOfWork

type ContextUnitOfWork string

ContextUnitOfWork 上下文工作单元键

type DeleteOperation

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

DeleteOperation 删除操作

func NewDeleteOperation

func NewDeleteOperation(entity Entity) *DeleteOperation

NewDeleteOperation 创建删除操作

func (*DeleteOperation) CanMerge

func (op *DeleteOperation) CanMerge(other Operation) bool

CanMerge 实现Operation接口

func (*DeleteOperation) Execute

func (op *DeleteOperation) Execute(db *gorm.DB) error

Execute 实现Operation接口

func (*DeleteOperation) GetEntity

func (op *DeleteOperation) GetEntity() Entity

GetEntity 实现Operation接口

func (*DeleteOperation) GetEntityType

func (op *DeleteOperation) GetEntityType() reflect.Type

GetEntityType 实现Operation接口

func (*DeleteOperation) GetOperationType

func (op *DeleteOperation) GetOperationType() OperationType

GetOperationType 实现Operation接口

func (*DeleteOperation) Merge

func (op *DeleteOperation) Merge(other Operation) Operation

Merge 实现Operation接口

func (*DeleteOperation) SameIdentity

func (op *DeleteOperation) SameIdentity(other Operation) bool

SameIdentity 实现Operation接口

type DependencyManager

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

DependencyManager 实体依赖关系管理器

func DefaultDependencyManager

func DefaultDependencyManager() *DependencyManager

DefaultDependencyManager 默认依赖管理器,包含常见的实体依赖关系

func NewDependencyManager

func NewDependencyManager() *DependencyManager

NewDependencyManager 创建依赖管理器

func (*DependencyManager) Clear

func (dm *DependencyManager) Clear()

Clear 清空所有依赖关系

func (*DependencyManager) GetAllEntityTypes

func (dm *DependencyManager) GetAllEntityTypes() []reflect.Type

GetAllEntityTypes 获取依赖图中的所有实体类型

func (*DependencyManager) GetDeletionOrder

func (dm *DependencyManager) GetDeletionOrder(entities []Entity) ([]Entity, error)

GetDeletionOrder 获取删除顺序(被依赖的实体后删除)

func (*DependencyManager) GetInsertionOrder

func (dm *DependencyManager) GetInsertionOrder(entities []Entity) ([]Entity, error)

GetInsertionOrder 获取插入顺序(依赖的实体先插入)

func (*DependencyManager) HasDependency

func (dm *DependencyManager) HasDependency(dependent, dependency reflect.Type) bool

HasDependency 检查是否存在依赖关系

func (*DependencyManager) RegisterDependency

func (dm *DependencyManager) RegisterDependency(dependent, dependency reflect.Type)

RegisterDependency 注册实体依赖关系 dependent 依赖于 dependency

func (*DependencyManager) RegisterEntityWeight

func (dm *DependencyManager) RegisterEntityWeight(entityType reflect.Type, weight int)

RegisterEntityWeight 注册实体权重(用于同级排序)

func (*DependencyManager) RemoveDependency

func (dm *DependencyManager) RemoveDependency(dependent, dependency reflect.Type)

RemoveDependency 移除依赖关系

type Entity

type Entity interface {
	// GetID 获取实体ID
	GetID() uint

	// SetID 设置实体ID
	SetID(id uint)

	// GetTableName 获取表名
	GetTableName() string

	// IsNew 判断是否为新实体
	IsNew() bool
}

Entity 实体接口,所有参与工作单元的实体都必须实现此接口

type EntitySnapshot

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

EntitySnapshot 实体状态快照,用于脏检查

func NewEntitySnapshot

func NewEntitySnapshot(entity Entity) *EntitySnapshot

NewEntitySnapshot 创建实体状态快照

func (*EntitySnapshot) GetChangedFields

func (s *EntitySnapshot) GetChangedFields(entity Entity) map[string]FieldChange

GetChangedFields 获取发生变更的字段

func (*EntitySnapshot) IsDirty

func (s *EntitySnapshot) IsDirty(entity Entity) bool

IsDirty 检查实体是否发生变更

type FieldChange

type FieldChange struct {
	FieldName string
	OldValue  interface{}
	NewValue  interface{}
	Type      FieldChangeType
}

FieldChange 字段变更信息

type FieldChangeType

type FieldChangeType int

FieldChangeType 字段变更类型

const (
	FieldChangeTypeAdded FieldChangeType = iota
	FieldChangeTypeModified
	FieldChangeTypeDeleted
)

func (FieldChangeType) String

func (t FieldChangeType) String() string

String 返回字段变更类型的字符串表示

type HasRevision

type HasRevision interface {
	Entity

	// GetRevision 获取版本号
	GetRevision() int64

	// SetRevision 设置版本号
	SetRevision(revision int64)

	// GetRevisionNext 获取下一个版本号
	GetRevisionNext() int64
}

HasRevision 支持乐观锁的实体接口

type HasTimestamps

type HasTimestamps interface {
	Entity

	// GetCreatedAt 获取创建时间
	GetCreatedAt() time.Time

	// SetCreatedAt 设置创建时间
	SetCreatedAt(createdAt time.Time)

	// GetUpdatedAt 获取更新时间
	GetUpdatedAt() time.Time

	// SetUpdatedAt 设置更新时间
	SetUpdatedAt(updatedAt time.Time)
}

HasTimestamps 支持时间戳的实体接口

type InsertOperation

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

InsertOperation 插入操作

func NewInsertOperation

func NewInsertOperation(entity Entity, uow *UnitOfWork) *InsertOperation

NewInsertOperation 创建插入操作

func (*InsertOperation) CanMerge

func (op *InsertOperation) CanMerge(other Operation) bool

CanMerge 实现Operation接口

func (*InsertOperation) Execute

func (op *InsertOperation) Execute(db *gorm.DB) error

Execute 实现Operation接口

func (*InsertOperation) GetEntity

func (op *InsertOperation) GetEntity() Entity

GetEntity 实现Operation接口

func (*InsertOperation) GetEntityType

func (op *InsertOperation) GetEntityType() reflect.Type

GetEntityType 实现Operation接口

func (*InsertOperation) GetOperationType

func (op *InsertOperation) GetOperationType() OperationType

GetOperationType 实现Operation接口

func (*InsertOperation) Merge

func (op *InsertOperation) Merge(other Operation) Operation

Merge 实现Operation接口

func (*InsertOperation) SameIdentity

func (op *InsertOperation) SameIdentity(other Operation) bool

SameIdentity 实现Operation接口

type Manager

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

Manager 工作单元管理器

func NewManager

func NewManager(db *gorm.DB, options ...ConfigOption) *Manager

NewManager 创建工作单元管理器

func (*Manager) ExecuteInNewUnitOfWork

func (m *Manager) ExecuteInNewUnitOfWork(fn Callback) error

ExecuteInNewUnitOfWork 创建新的工作单元并执行

func (*Manager) ExecuteInUnitOfWork

func (m *Manager) ExecuteInUnitOfWork(ctx context.Context, fn Callback) error

ExecuteInUnitOfWork 在工作单元中执行操作

type Operation

type Operation interface {
	// GetEntityType 获取操作的实体类型
	GetEntityType() reflect.Type

	// GetOperationType 获取操作类型
	GetOperationType() OperationType

	// Execute 执行操作
	Execute(db *gorm.DB) error

	// GetEntity 获取操作的实体(如果有)
	GetEntity() Entity

	// SameIdentity 检查是否是同一个实体的操作
	SameIdentity(other Operation) bool

	// CanMerge 检查是否可以与其他操作合并
	CanMerge(other Operation) bool

	// Merge 与其他操作合并
	Merge(other Operation) Operation
}

Operation 数据库操作接口

type OperationType

type OperationType int

OperationType 操作类型

const (
	OperationTypeInsert OperationType = iota
	OperationTypeUpdate
	OperationTypeDelete
	OperationTypeBulkInsert
	OperationTypeBulkUpdate
	OperationTypeBulkDelete
)

func (OperationType) String

func (t OperationType) String() string

String 返回操作类型的字符串表示

type Plugin

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

Plugin 工作单元GORM插件

func NewPlugin

func NewPlugin(options ...PluginOption) *Plugin

NewPlugin 创建工作单元插件

func (*Plugin) Initialize

func (p *Plugin) Initialize(db *gorm.DB) error

Initialize 实现gorm.Plugin接口

func (*Plugin) Name

func (p *Plugin) Name() string

Name 实现gorm.Plugin接口

type PluginConfig

type PluginConfig struct {
	// 工作单元配置
	UnitOfWorkConfig *Config

	// 是否自动开启工作单元
	AutoManage bool

	// 上下文键名
	ContextKey string

	// 是否启用自动依赖注册
	AutoDependencyRegistration bool

	// 依赖关系映射
	DependencyMapping map[reflect.Type][]reflect.Type
}

PluginConfig 插件配置

func DefaultPluginConfig

func DefaultPluginConfig() *PluginConfig

DefaultPluginConfig 默认插件配置

type PluginOption

type PluginOption func(*PluginConfig)

PluginOption 插件配置选项

func WithPluginAutoManage

func WithPluginAutoManage(enabled bool) PluginOption

WithPluginAutoManage 配置自动管理

func WithPluginContextKey

func WithPluginContextKey(key string) PluginOption

WithPluginContextKey 配置上下文键名

func WithPluginDependencyMapping

func WithPluginDependencyMapping(mapping map[reflect.Type][]reflect.Type) PluginOption

WithPluginDependencyMapping 配置依赖关系映射

func WithPluginUnitOfWorkConfig

func WithPluginUnitOfWorkConfig(config *Config) PluginOption

WithPluginUnitOfWorkConfig 配置工作单元

type SnapshotManager

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

SnapshotManager 快照管理器

func NewSnapshotManager

func NewSnapshotManager() *SnapshotManager

NewSnapshotManager 创建快照管理器

func (*SnapshotManager) Clear

func (sm *SnapshotManager) Clear()

Clear 清空所有快照

func (*SnapshotManager) GetChangedFields

func (sm *SnapshotManager) GetChangedFields(entity Entity) map[string]FieldChange

GetChangedFields 获取实体变更字段

func (*SnapshotManager) IsDirty

func (sm *SnapshotManager) IsDirty(entity Entity) bool

IsDirty 检查实体是否脏

func (*SnapshotManager) RemoveSnapshot

func (sm *SnapshotManager) RemoveSnapshot(entity Entity)

RemoveSnapshot 移除实体快照

func (*SnapshotManager) TakeSnapshot

func (sm *SnapshotManager) TakeSnapshot(entity Entity)

TakeSnapshot 创建实体快照

type SoftDelete

type SoftDelete interface {
	Entity

	// GetDeletedAt 获取删除时间
	GetDeletedAt() gorm.DeletedAt

	// SetDeletedAt 设置删除时间
	SetDeletedAt(deletedAt gorm.DeletedAt)

	// IsDeleted 判断是否已删除
	IsDeleted() bool
}

SoftDelete 支持软删除的实体接口

type UnitOfWork

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

UnitOfWork 工作单元核心实现

func GetUnitOfWorkFromContext

func GetUnitOfWorkFromContext(ctx context.Context, key string) *UnitOfWork

GetUnitOfWorkFromContext 从上下文获取工作单元

func NewUnitOfWork

func NewUnitOfWork(db *gorm.DB, options ...ConfigOption) *UnitOfWork

NewUnitOfWork 创建工作单元

func (*UnitOfWork) Commit

func (uow *UnitOfWork) Commit() error

Commit 提交所有变更

func (*UnitOfWork) Create

func (uow *UnitOfWork) Create(entity Entity) error

Create 注册新实体

func (*UnitOfWork) Delete

func (uow *UnitOfWork) Delete(entity Entity) error

Delete 注册删除实体

func (*UnitOfWork) GetDependencyManager

func (uow *UnitOfWork) GetDependencyManager() *DependencyManager

GetDependencyManager 获取依赖管理器

func (*UnitOfWork) GetStats

func (uow *UnitOfWork) GetStats() map[string]interface{}

GetStats 获取统计信息

func (*UnitOfWork) IsCommitted

func (uow *UnitOfWork) IsCommitted() bool

IsCommitted 检查是否已提交

func (*UnitOfWork) IsRolledBack

func (uow *UnitOfWork) IsRolledBack() bool

IsRolledBack 检查是否已回滚

func (*UnitOfWork) Rollback

func (uow *UnitOfWork) Rollback() error

Rollback 回滚所有变更

Example

ExampleUnitOfWork_Rollback 回滚示例

db := setupTestDB()
uow := NewUnitOfWork(db)

// 创建一个无效的用户(邮箱为空,会验证失败)
user := &User{
	Name:  "测试用户",
	Email: "", // 空邮箱会导致验证失败
	Age:   25,
}

err := uow.Create(user)
if err != nil {
	log.Fatal(err)
}

// 尝试提交,应该会失败
err = uow.Commit()
if err != nil {
	fmt.Printf("提交失败,执行回滚: %v\n", err)

	// 执行回滚
	rollbackErr := uow.Rollback()
	if rollbackErr != nil {
		log.Fatal("回滚失败:", rollbackErr)
	}

	fmt.Println("回滚成功")
	return
}

fmt.Println("不应该到达这里")
Output:

提交失败,执行回滚: unit of work commit failed: operation 0 failed: validation failed for entity *unitofwork.User: 邮箱不能为空
回滚成功

func (*UnitOfWork) TakeSnapshot

func (uow *UnitOfWork) TakeSnapshot(entity Entity)

func (*UnitOfWork) Update

func (uow *UnitOfWork) Update(entity Entity) error

Update 注册脏实体

func (*UnitOfWork) WithContext

func (uow *UnitOfWork) WithContext(ctx context.Context) *UnitOfWork

WithContext 设置上下文

type UpdateOperation

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

UpdateOperation 更新操作

func NewUpdateOperation

func NewUpdateOperation(entity Entity, changes map[string]FieldChange) *UpdateOperation

NewUpdateOperation 创建更新操作

func (*UpdateOperation) CanMerge

func (op *UpdateOperation) CanMerge(other Operation) bool

CanMerge 实现Operation接口

func (*UpdateOperation) Execute

func (op *UpdateOperation) Execute(db *gorm.DB) error

Execute 实现Operation接口

func (*UpdateOperation) GetChanges

func (op *UpdateOperation) GetChanges() map[string]FieldChange

GetChanges 获取变更信息

func (*UpdateOperation) GetEntity

func (op *UpdateOperation) GetEntity() Entity

GetEntity 实现Operation接口

func (*UpdateOperation) GetEntityType

func (op *UpdateOperation) GetEntityType() reflect.Type

GetEntityType 实现Operation接口

func (*UpdateOperation) GetOperationType

func (op *UpdateOperation) GetOperationType() OperationType

GetOperationType 实现Operation接口

func (*UpdateOperation) Merge

func (op *UpdateOperation) Merge(other Operation) Operation

Merge 实现Operation接口

func (*UpdateOperation) SameIdentity

func (op *UpdateOperation) SameIdentity(other Operation) bool

SameIdentity 实现Operation接口

type Validatable

type Validatable interface {
	Entity

	// Validate 验证实体数据
	Validate() error
}

Validatable 支持验证的实体接口

Jump to

Keyboard shortcuts

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