Documentation
¶
Overview ¶
Package db 提供数据库访问和仓储模式支持
Package db 提供数据库访问和事务管理功能
Example ¶
TestIntegrationExample 集成测试示例 这不是实际执行的测试,只是展示如何使用数据库模块
// 跳过数据库连接,这只是示例
skipDatabaseConnection = true
// 方式1: 直接使用数据库配置
dbConfig := Config{
Driver: "mysql",
Host: "localhost",
Port: 3306,
Database: "my_app",
Username: "root",
Password: "password",
Charset: "utf8mb4",
}
provider, err := InitializeDatabase([]interface{}{dbConfig})
if err != nil {
fmt.Println("初始化数据库失败:", err)
return
}
dbProvider := provider.(*DbProvider)
fmt.Printf("数据库连接成功: %s\n", dbProvider.Manager.defaultConnection)
// 方式2: 使用嵌套配置格式
nestedConfig := map[string]interface{}{
"database": map[string]interface{}{
"default": "master",
"connections": map[string]interface{}{
"master": map[string]interface{}{
"driver": "mysql",
"host": "master.example.com",
"port": 3306,
"database": "my_app",
"username": "root",
"password": "secret",
"charset": "utf8mb4",
"max_open_conns": 100,
"max_idle_conns": 10,
},
"slave": map[string]interface{}{
"driver": "mysql",
"host": "slave.example.com",
"port": 3306,
"database": "my_app",
"username": "readonly",
"password": "readonly",
"charset": "utf8mb4",
"max_open_conns": 50,
"max_idle_conns": 5,
},
},
},
}
provider, err = InitializeDatabase([]interface{}{nestedConfig})
if err != nil {
fmt.Println("初始化嵌套配置数据库失败:", err)
return
}
dbProvider = provider.(*DbProvider)
fmt.Printf("嵌套配置数据库连接成功: %s\n", dbProvider.Manager.defaultConnection)
fmt.Printf("配置的连接数: %d\n", len(dbProvider.Manager.configs))
// 恢复标志,避免影响其他测试
skipDatabaseConnection = false
Output: 数据库连接成功: default 嵌套配置数据库连接成功: master 配置的连接数: 2
Index ¶
- Constants
- Variables
- func GetConnection(engine interface{}, name string) (*gorm.DB, error)
- func GetConnectionDetails(config Config) map[string]interface{}
- func GetDefaultConnection(engine interface{}) (*gorm.DB, error)
- func GetNestedConfigDetails(config map[string]interface{}) (map[string]interface{}, error)
- func GetTransaction(ctx context.Context) (*gorm.DB, bool)
- func InitializeDatabase(options []interface{}) (interface{}, error)
- func IsTestMode() bool
- func NewTransactionContext(parent context.Context, tx *gorm.DB) context.Context
- func OrderBy(db *gorm.DB, field string, direction string) *gorm.DB
- func ParseMigrationID(id string) (time.Time, error)
- func Preload(db *gorm.DB, relations ...string) *gorm.DB
- func PreloadAll(db *gorm.DB) *gorm.DB
- func RegisterDatabaseInitializer(registerFunc func(DbInitializer))
- func RegisterMigration(id, name string, up, down func(db *gorm.DB) error)
- func RegisterSeeder(manager *SeederManager, seeder Seeder) error
- func SetDatabaseOptions(options []interface{})
- func SetRegisterFunction(registerFunc func(DbInitializer))
- func SetTestMode(enabled bool)
- func Transaction(db *gorm.DB, fn func(tx *gorm.DB) error) error
- func WithCache(db *gorm.DB, cache Cache, key string, expiration time.Duration) *gorm.DB
- func WithContext(ctx context.Context, db *gorm.DB) *gorm.DB
- func WithLock(db *gorm.DB, mode LockMode) *gorm.DB
- func WithScope(db *gorm.DB, scopes ...Scope) *gorm.DB
- type BaseMigration
- type BaseRepository
- func (r *BaseRepository) All() (interface{}, error)
- func (r *BaseRepository) Count() (int64, error)
- func (r *BaseRepository) Create(entity interface{}) error
- func (r *BaseRepository) Delete(id interface{}) error
- func (r *BaseRepository) Exists(id interface{}) (bool, error)
- func (r *BaseRepository) Find(id interface{}) (interface{}, error)
- func (r *BaseRepository) FindBy(conditions map[string]interface{}) (interface{}, error)
- func (r *BaseRepository) Paginate(page, pageSize int) (*Pagination, error)
- func (r *BaseRepository) Query() *QueryBuilder
- func (r *BaseRepository) Transaction(fn func(Repository) error) error
- func (r *BaseRepository) Update(entity interface{}) error
- func (r *BaseRepository) WithContext(ctx context.Context) Repository
- func (r *BaseRepository) WithPrimaryKey(key string) *BaseRepository
- func (r *BaseRepository) WithTx(tx *gorm.DB) Repository
- type BaseSeeder
- type BeginWithOptionsResult
- type Cache
- type Config
- type ConnectionOption
- func WithAutoMigrate(models ...interface{}) ConnectionOption
- func WithConnMaxLifetime(name string, lifetime time.Duration) ConnectionOption
- func WithConnection(name string, config Config) ConnectionOption
- func WithDebug(enable bool) ConnectionOption
- func WithDefaultConnection(name string) ConnectionOption
- func WithMaxIdleConns(name string, maxIdle int) ConnectionOption
- func WithMaxOpenConns(name string, maxOpen int) ConnectionOption
- type DatabaseProvider
- type DbInitializer
- type DbProvider
- type EnumValue
- type GenericRepository
- func (r *GenericRepository[T]) Count(ctx context.Context, condition interface{}, args ...interface{}) (int64, error)
- func (r *GenericRepository[T]) Create(ctx context.Context, entity *T) error
- func (r *GenericRepository[T]) DB() *gorm.DB
- func (r *GenericRepository[T]) Delete(ctx context.Context, entity *T) error
- func (r *GenericRepository[T]) DeleteByID(ctx context.Context, id interface{}) error
- func (r *GenericRepository[T]) FindAll(ctx context.Context) ([]T, error)
- func (r *GenericRepository[T]) FindByCondition(ctx context.Context, condition interface{}, args ...interface{}) ([]T, error)
- func (r *GenericRepository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)
- func (r *GenericRepository[T]) First(ctx context.Context, condition interface{}, args ...interface{}) (*T, error)
- func (r *GenericRepository[T]) ModelName() string
- func (r *GenericRepository[T]) Paginate(ctx context.Context, page, pageSize int, condition interface{}, ...) ([]T, int64, error)
- func (r *GenericRepository[T]) Update(ctx context.Context, entity *T) error
- func (r *GenericRepository[T]) WithTx(tx *gorm.DB) *GenericRepository[T]
- type GenericRepositoryInterface
- type JSONField
- type LockMode
- type Manager
- func (m *Manager) AllHealthStatus() map[string]bool
- func (m *Manager) Close() error
- func (m *Manager) Configs() map[string]Config
- func (m *Manager) Connect(name string) (*gorm.DB, error)
- func (m *Manager) Connection(name string) (*gorm.DB, error)
- func (m *Manager) ConnectionCount() int
- func (m *Manager) Default() (*gorm.DB, error)
- func (m *Manager) DefaultConnectionName() string
- func (m *Manager) FromConfig(configManager *config.ConfigManager) error
- func (m *Manager) HasConnection(name string) bool
- func (m *Manager) IsHealthy(name string) bool
- func (m *Manager) Register(name string, config Config) error
- func (m *Manager) SetDefaultConnection(name string)
- type Migration
- type MigrationRecord
- type Migrator
- func (m *Migrator) CreateMigrationFile(name string) (string, error)
- func (m *Migrator) GetMigrations() []Migration
- func (m *Migrator) GetPending() ([]Migration, error)
- func (m *Migrator) GetRan() ([]string, error)
- func (m *Migrator) LoadMigrationsFromConfig(config []map[string]interface{}) error
- func (m *Migrator) LoadMigrationsFromDirectory(directory string) error
- func (m *Migrator) Migrate() error
- func (m *Migrator) Register(migration Migration) error
- func (m *Migrator) Reset() error
- func (m *Migrator) Rollback() error
- func (m *Migrator) RollbackTo(id string) error
- func (m *Migrator) Status() ([]map[string]interface{}, error)
- type Model
- type ModelSeeder
- type ModelSeederOption
- type Pagination
- type QueryBuilder
- func (qb *QueryBuilder) Commit() error
- func (qb *QueryBuilder) Context(ctx context.Context) *QueryBuilder
- func (qb *QueryBuilder) Count(count *int64) error
- func (qb *QueryBuilder) Create(value interface{}) error
- func (qb *QueryBuilder) Delete(value interface{}, conds ...interface{}) error
- func (qb *QueryBuilder) Exec(sql string, values ...interface{}) error
- func (qb *QueryBuilder) Exists() (bool, error)
- func (qb *QueryBuilder) Find(dest interface{}) error
- func (qb *QueryBuilder) FindByID(id interface{}, dest interface{}) error
- func (qb *QueryBuilder) FindOne(dest interface{}) error
- func (qb *QueryBuilder) First(dest interface{}) error
- func (qb *QueryBuilder) Group(group string) *QueryBuilder
- func (qb *QueryBuilder) Last(dest interface{}) error
- func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
- func (qb *QueryBuilder) Lock(mode LockMode) *QueryBuilder
- func (qb *QueryBuilder) Model(model interface{}) *QueryBuilder
- func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
- func (qb *QueryBuilder) Order(order string) *QueryBuilder
- func (qb *QueryBuilder) OrderBy(field string, direction string) *QueryBuilder
- func (qb *QueryBuilder) Paginate(page, pageSize int) *QueryBuilder
- func (qb *QueryBuilder) PaginateQuery(result interface{}) (*Pagination, error)
- func (qb *QueryBuilder) Pluck(column string, dest interface{}) error
- func (qb *QueryBuilder) Preload(relations ...string) *QueryBuilder
- func (qb *QueryBuilder) PreloadAll() *QueryBuilder
- func (qb *QueryBuilder) QueryMap() ([]map[string]interface{}, error)
- func (qb *QueryBuilder) QueryStruct(dest interface{}) error
- func (qb *QueryBuilder) Raw(sql string, values ...interface{}) *gorm.DB
- func (qb *QueryBuilder) Rollback() error
- func (qb *QueryBuilder) Row() *sql.Row
- func (qb *QueryBuilder) Rows() (*sql.Rows, error)
- func (qb *QueryBuilder) Save(value interface{}) error
- func (qb *QueryBuilder) Scan(dest interface{}) error
- func (qb *QueryBuilder) ScanRows(rows *sql.Rows, dest interface{}) error
- func (qb *QueryBuilder) Scope(scopes ...Scope) *QueryBuilder
- func (qb *QueryBuilder) Select(fields ...string) *QueryBuilder
- func (qb *QueryBuilder) Take(dest interface{}) error
- func (qb *QueryBuilder) ToSQL() string
- func (qb *QueryBuilder) Transaction() *QueryBuilder
- func (qb *QueryBuilder) Update(column string, value interface{}) error
- func (qb *QueryBuilder) UpdateColumn(column string, value interface{}) error
- func (qb *QueryBuilder) UpdateColumns(values interface{}) error
- func (qb *QueryBuilder) Updates(values interface{}) error
- func (qb *QueryBuilder) Where(condition string, args ...interface{}) *QueryBuilder
- type ReplicaConfig
- type Repository
- type Scope
- func BetweenTime(field string, timeRange TimeRange) Scope
- func EndsWith(field string, value string) Scope
- func In(field string, values ...interface{}) Scope
- func IsNotNull(field string) Scope
- func IsNull(field string) Scope
- func Like(field string, value string) Scope
- func NotIn(field string, values ...interface{}) Scope
- func StartsWith(field string, value string) Scope
- type Seeder
- type SeederManager
- func (m *SeederManager) GetPending() ([]Seeder, error)
- func (m *SeederManager) GetRan() ([]string, error)
- func (m *SeederManager) GetSeeders() []Seeder
- func (m *SeederManager) LoadSeedersFromDirectory(directory string, modelType interface{}) error
- func (m *SeederManager) Register(seeder Seeder) error
- func (m *SeederManager) Reset() error
- func (m *SeederManager) Run() error
- func (m *SeederManager) RunSeeder(name string) error
- func (m *SeederManager) Status() ([]map[string]interface{}, error)
- type SeederRecord
- type SoftDeleteModel
- type TimeRange
- type TimestampModel
- type TransactionKey
- type TransactionManager
- func (tm *TransactionManager) Begin(ctx context.Context) *gorm.DB
- func (tm *TransactionManager) BeginWithOptions(ctx context.Context, opts *TxOptions) BeginWithOptionsResult
- func (tm *TransactionManager) Commit(tx *gorm.DB) error
- func (tm *TransactionManager) Rollback(tx *gorm.DB) error
- func (tm *TransactionManager) RunInTransaction(ctx context.Context, fn func(tx *gorm.DB) (interface{}, error)) (interface{}, error)
- func (tm *TransactionManager) Transaction(ctx context.Context, fn func(tx *gorm.DB) error) error
- func (tm *TransactionManager) WithTransaction(ctx context.Context, fn func(tx context.Context) error) error
- type TxOptions
Examples ¶
Constants ¶
const ( // MySQL 数据库 MySQL = "mysql" // PostgreSQL 数据库 PostgreSQL = "postgres" // SQLite 数据库 SQLite = "sqlite" )
数据库驱动类型常量
const ( // 迁移表名 MigrationTable = "migrations" // 迁移文件模板 MigrationTemplate = `` /* 340-byte string literal not displayed */ )
定义迁移相关常量
Variables ¶
var ( // ErrUnsupportedDriver 不支持的驱动类型错误 ErrUnsupportedDriver = errors.New("不支持的数据库驱动类型") // ErrConnectionNotFound 连接未找到错误 ErrConnectionNotFound = errors.New("数据库连接未找到") // ErrInvalidConfiguration 无效的数据库配置 ErrInvalidConfiguration = errors.New("无效的数据库配置") // ErrDatabaseNotFound 未找到指定的数据库 ErrDatabaseNotFound = errors.New("未找到指定的数据库连接") // ErrConnectionFailed 数据库连接失败 ErrConnectionFailed = errors.New("数据库连接失败") )
定义错误类型
var ( ErrMigrationFailed = errors.New("迁移执行失败") ErrMigrationNotFound = errors.New("找不到指定的迁移") ErrMigrationExists = errors.New("迁移已存在") ErrInvalidMigration = errors.New("无效的迁移") ErrInvalidMigrationID = errors.New("无效的迁移ID") )
迁移错误定义
var ( ErrSeederFailed = errors.New("种子数据执行失败") ErrSeederNotFound = errors.New("找不到指定的种子数据") ErrSeederExists = errors.New("种子数据已存在") ErrInvalidSeeder = errors.New("无效的种子数据") )
定义种子数据相关错误
Functions ¶
func GetConnection ¶
GetConnection 获取指定名称的数据库连接
func GetConnectionDetails ¶ added in v1.1.6
GetConnectionDetails 从配置中获取连接详情,用于测试和调试
func GetDefaultConnection ¶
GetDefaultConnection 获取默认数据库连接
func GetNestedConfigDetails ¶ added in v1.1.6
GetNestedConfigDetails 从嵌套配置中获取所有连接详情
func GetTransaction ¶
GetTransaction 从上下文中获取事务
func InitializeDatabase ¶ added in v1.0.4
func InitializeDatabase(options []interface{}) (interface{}, error)
InitializeDatabase 初始化数据库
func NewTransactionContext ¶
NewTransactionContext 创建一个包含事务信息的上下文
func RegisterDatabaseInitializer ¶ added in v1.0.4
func RegisterDatabaseInitializer(registerFunc func(DbInitializer))
RegisterDatabaseInitializer 注册数据库初始化器到flow框架 此函数由flow包调用,用于建立flow包与db包的连接
func RegisterMigration ¶
RegisterMigration 注册迁移
func RegisterSeeder ¶
func RegisterSeeder(manager *SeederManager, seeder Seeder) error
RegisterSeeder 注册种子数据(全局函数)
func SetDatabaseOptions ¶ added in v1.0.4
func SetDatabaseOptions(options []interface{})
SetDatabaseOptions 设置数据库配置选项 在WithDatabase选项中使用
func SetRegisterFunction ¶ added in v1.0.4
func SetRegisterFunction(registerFunc func(DbInitializer))
SetRegisterFunction 设置注册函数,由flow包调用 已被新的RegisterDatabaseInitializer替代,保留以兼容旧代码
func SetTestMode ¶ added in v1.1.6
func SetTestMode(enabled bool)
SetTestMode 设置测试模式状态 当测试模式开启时,会跳过实际的数据库连接,使用mock连接
func Transaction ¶
Transaction 执行数据库事务
func WithContext ¶
WithContext 在已有数据库连接上设置上下文
Types ¶
type BaseMigration ¶
type BaseMigration struct {
// contains filtered or unexported fields
}
BaseMigration 基础迁移实现
type BaseRepository ¶
type BaseRepository struct {
// contains filtered or unexported fields
}
BaseRepository 基础存储库实现
func NewRepository ¶
func NewRepository(db *gorm.DB, model interface{}) *BaseRepository
NewRepository 创建新的存储库
func (*BaseRepository) Create ¶
func (r *BaseRepository) Create(entity interface{}) error
Create 创建实体
func (*BaseRepository) Exists ¶
func (r *BaseRepository) Exists(id interface{}) (bool, error)
Exists 检查是否存在
func (*BaseRepository) Find ¶
func (r *BaseRepository) Find(id interface{}) (interface{}, error)
Find 根据ID查找实体
func (*BaseRepository) FindBy ¶
func (r *BaseRepository) FindBy(conditions map[string]interface{}) (interface{}, error)
FindBy 根据条件查找实体
func (*BaseRepository) Paginate ¶
func (r *BaseRepository) Paginate(page, pageSize int) (*Pagination, error)
Paginate 分页查询
func (*BaseRepository) Transaction ¶
func (r *BaseRepository) Transaction(fn func(Repository) error) error
Transaction 执行事务
func (*BaseRepository) Update ¶
func (r *BaseRepository) Update(entity interface{}) error
Update 更新实体
func (*BaseRepository) WithContext ¶
func (r *BaseRepository) WithContext(ctx context.Context) Repository
WithContext 设置上下文
func (*BaseRepository) WithPrimaryKey ¶
func (r *BaseRepository) WithPrimaryKey(key string) *BaseRepository
WithPrimaryKey 设置主键名称
type BaseSeeder ¶
type BaseSeeder struct {
// contains filtered or unexported fields
}
BaseSeeder 基础种子数据实现
func (*BaseSeeder) Dependencies ¶
func (s *BaseSeeder) Dependencies() []string
Dependencies 获取依赖的其他种子数据
type BeginWithOptionsResult ¶
BeginWithOptionsResult 包含事务开始的结果
type Cache ¶
type Cache interface {
// Get 获取缓存数据
Get(ctx context.Context, key string) (interface{}, error)
// Set 设置缓存数据
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
// Delete 删除缓存数据
Delete(ctx context.Context, key string) error
// Has 检查缓存是否存在
Has(ctx context.Context, key string) bool
}
Cache 查询缓存接口
type Config ¶
type Config struct {
// 驱动类型:mysql, postgres, sqlite等
Driver string `yaml:"driver" json:"driver"`
// 连接信息
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
Database string `yaml:"database" json:"database"`
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
// 其他连接参数
Charset string `yaml:"charset" json:"charset"`
SSLMode string `yaml:"sslmode" json:"sslmode"`
TimeZone string `yaml:"timezone" json:"timezone"`
// 连接池配置
MaxIdleConns int `yaml:"max_idle_conns" json:"max_idle_conns"`
MaxOpenConns int `yaml:"max_open_conns" json:"max_open_conns"`
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" json:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time" json:"conn_max_idle_time"`
// 日志配置
LogLevel logger.LogLevel `yaml:"log_level" json:"log_level"`
SlowThreshold time.Duration `yaml:"slow_threshold" json:"slow_threshold"`
// 主从配置
Replicas []ReplicaConfig `yaml:"replicas" json:"replicas"`
// 健康检查配置
HealthCheck bool `yaml:"health_check" json:"health_check"`
HealthCheckPeriod time.Duration `yaml:"health_check_period" json:"health_check_period"`
HealthCheckTimeout time.Duration `yaml:"health_check_timeout" json:"health_check_timeout"`
HealthCheckSQL string `yaml:"health_check_sql" json:"health_check_sql"`
}
Config 数据库配置
type ConnectionOption ¶ added in v1.0.4
type ConnectionOption func(*Manager)
ConnectionOption 用于配置数据库连接管理器的函数选项
func WithAutoMigrate ¶ added in v1.0.4
func WithAutoMigrate(models ...interface{}) ConnectionOption
WithAutoMigrate 自动迁移模型
func WithConnMaxLifetime ¶ added in v1.0.4
func WithConnMaxLifetime(name string, lifetime time.Duration) ConnectionOption
WithConnMaxLifetime 设置连接最大生存时间
func WithConnection ¶ added in v1.0.4
func WithConnection(name string, config Config) ConnectionOption
WithConnection 创建一个自定义连接的选项
func WithDefaultConnection ¶ added in v1.0.4
func WithDefaultConnection(name string) ConnectionOption
WithDefaultConnection 设置默认连接
func WithMaxIdleConns ¶ added in v1.0.4
func WithMaxIdleConns(name string, maxIdle int) ConnectionOption
WithMaxIdleConns 设置最大空闲连接数
func WithMaxOpenConns ¶ added in v1.0.4
func WithMaxOpenConns(name string, maxOpen int) ConnectionOption
WithMaxOpenConns 设置最大打开连接数
type DatabaseProvider ¶
DatabaseProvider 数据库服务提供者
func NewDatabaseProvider ¶
func NewDatabaseProvider(container *di.Container) *DatabaseProvider
NewDatabaseProvider 创建数据库服务提供者
func (*DatabaseProvider) GetPriority ¶ added in v1.0.4
func (p *DatabaseProvider) GetPriority() int
GetPriority 返回提供者优先级
func (*DatabaseProvider) GetProviderName ¶ added in v1.0.4
func (p *DatabaseProvider) GetProviderName() string
GetProviderName 返回提供者名称
func (*DatabaseProvider) Register ¶
func (p *DatabaseProvider) Register(app interface{}) error
Register 注册数据库服务
type DbInitializer ¶ added in v1.0.4
type DbInitializer func([]interface{}) (interface{}, error)
DbInitializer 数据库初始化器类型
type DbProvider ¶ added in v1.0.4
DbProvider 数据库服务提供者(重命名以避免冲突)
type GenericRepository ¶
type GenericRepository[T any] struct { // contains filtered or unexported fields }
GenericRepository 提供通用的仓储实现,可用作所有特定模型仓储的基类
func NewGenericRepository ¶
func NewGenericRepository[T any](db *gorm.DB) *GenericRepository[T]
NewGenericRepository 创建一个新的基础仓储实例
func (*GenericRepository[T]) Count ¶
func (r *GenericRepository[T]) Count(ctx context.Context, condition interface{}, args ...interface{}) (int64, error)
Count 计算满足条件的实体数量
func (*GenericRepository[T]) Create ¶
func (r *GenericRepository[T]) Create(ctx context.Context, entity *T) error
Create 创建一个新的实体记录
func (*GenericRepository[T]) DB ¶
func (r *GenericRepository[T]) DB() *gorm.DB
DB 返回原始的gorm.DB实例,用于高级查询
func (*GenericRepository[T]) Delete ¶
func (r *GenericRepository[T]) Delete(ctx context.Context, entity *T) error
Delete 删除实体记录
func (*GenericRepository[T]) DeleteByID ¶
func (r *GenericRepository[T]) DeleteByID(ctx context.Context, id interface{}) error
DeleteByID 根据ID删除实体记录
func (*GenericRepository[T]) FindAll ¶
func (r *GenericRepository[T]) FindAll(ctx context.Context) ([]T, error)
FindAll 获取所有实体
func (*GenericRepository[T]) FindByCondition ¶
func (r *GenericRepository[T]) FindByCondition(ctx context.Context, condition interface{}, args ...interface{}) ([]T, error)
FindByCondition 根据条件查找实体
func (*GenericRepository[T]) FindByID ¶
func (r *GenericRepository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)
FindByID 根据ID查找实体
func (*GenericRepository[T]) First ¶
func (r *GenericRepository[T]) First(ctx context.Context, condition interface{}, args ...interface{}) (*T, error)
First 获取满足条件的第一个实体
func (*GenericRepository[T]) ModelName ¶
func (r *GenericRepository[T]) ModelName() string
ModelName 返回模型的名称
func (*GenericRepository[T]) Paginate ¶
func (r *GenericRepository[T]) Paginate(ctx context.Context, page, pageSize int, condition interface{}, args ...interface{}) ([]T, int64, error)
Paginate 分页查询
func (*GenericRepository[T]) Update ¶
func (r *GenericRepository[T]) Update(ctx context.Context, entity *T) error
Update 更新实体记录
func (*GenericRepository[T]) WithTx ¶
func (r *GenericRepository[T]) WithTx(tx *gorm.DB) *GenericRepository[T]
WithTx 返回带有事务上下文的仓储实例
type GenericRepositoryInterface ¶
type GenericRepositoryInterface[T any] interface { // 基础操作方法 Create(ctx context.Context, entity *T) error Update(ctx context.Context, entity *T) error Delete(ctx context.Context, entity *T) error DeleteByID(ctx context.Context, id interface{}) error FindByID(ctx context.Context, id interface{}) (*T, error) FindAll(ctx context.Context) ([]T, error) FindByCondition(ctx context.Context, condition interface{}, args ...interface{}) ([]T, error) First(ctx context.Context, condition interface{}, args ...interface{}) (*T, error) Count(ctx context.Context, condition interface{}, args ...interface{}) (int64, error) Paginate(ctx context.Context, page, pageSize int, condition interface{}, args ...interface{}) ([]T, int64, error) // 工具方法 WithTx(tx *gorm.DB) *GenericRepository[T] DB() *gorm.DB ModelName() string }
GenericRepositoryInterface 定义了泛型仓储接口
type JSONField ¶
type JSONField map[string]interface{}
JSONField JSON字段类型
func (JSONField) GormDBDataType ¶
GormDBDataType 实现数据库特定的类型定义
func (JSONField) GormDataType ¶
GormDataType 实现 schema.GormDataType 接口
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager 数据库连接管理器
func (*Manager) AllHealthStatus ¶
AllHealthStatus 获取所有数据库连接的健康状态
func (*Manager) Connection ¶
Connection 获取指定名称的数据库连接
func (*Manager) ConnectionCount ¶ added in v1.1.6
ConnectionCount 返回配置的连接数量
func (*Manager) DefaultConnectionName ¶ added in v1.1.6
DefaultConnectionName 返回默认连接名称
func (*Manager) FromConfig ¶
func (m *Manager) FromConfig(configManager *config.ConfigManager) error
FromConfig 从配置管理器加载数据库配置
func (*Manager) HasConnection ¶
HasConnection 检查是否存在指定名称的数据库连接
func (*Manager) SetDefaultConnection ¶
SetDefaultConnection 设置默认数据库连接
type Migration ¶
type Migration interface {
// ID 获取迁移ID
ID() string
// Name 获取迁移名称
Name() string
// Up 执行迁移
Up(db *gorm.DB) error
// Down 回滚迁移
Down(db *gorm.DB) error
}
Migration 迁移接口
type MigrationRecord ¶
type MigrationRecord struct {
ID string `gorm:"primaryKey"`
Name string `gorm:"size:255;not null"`
Batch int `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"`
}
MigrationRecord 迁移记录
type Migrator ¶
type Migrator struct {
// contains filtered or unexported fields
}
Migrator 迁移管理器
func (*Migrator) CreateMigrationFile ¶
CreateMigrationFile 创建新的迁移文件
func (*Migrator) GetMigrations ¶
GetMigrations 获取所有迁移
func (*Migrator) GetPending ¶
GetPending 获取待执行的迁移
func (*Migrator) LoadMigrationsFromConfig ¶
LoadMigrationsFromConfig 从配置中加载迁移
func (*Migrator) LoadMigrationsFromDirectory ¶
LoadMigrationsFromDirectory 从目录加载迁移
type Model ¶
type Model struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Model 基础模型结构
type ModelSeeder ¶
type ModelSeeder struct {
BaseSeeder
// contains filtered or unexported fields
}
ModelSeeder 模型种子数据,用于从JSON/YAML文件填充数据
func NewModelSeeder ¶
func NewModelSeeder(name string, model interface{}, dataFile string, opts ...ModelSeederOption) *ModelSeeder
NewModelSeeder 创建模型种子数据
type ModelSeederOption ¶
type ModelSeederOption func(*ModelSeeder)
ModelSeederOption 模型种子数据选项
func WithDependencies ¶
func WithDependencies(dependencies ...string) ModelSeederOption
WithDependencies 设置依赖的其他种子数据
func WithIgnoreErrors ¶
func WithIgnoreErrors(ignore bool) ModelSeederOption
WithIgnoreErrors 设置是否忽略错误
type Pagination ¶
type Pagination struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
Total int64 `json:"total"`
TotalPage int `json:"total_page"`
}
Paginate 分页查询辅助函数
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder 查询构建器
func (*QueryBuilder) Context ¶
func (qb *QueryBuilder) Context(ctx context.Context) *QueryBuilder
Context 设置上下文
func (*QueryBuilder) Delete ¶
func (qb *QueryBuilder) Delete(value interface{}, conds ...interface{}) error
Delete 删除记录
func (*QueryBuilder) Exec ¶
func (qb *QueryBuilder) Exec(sql string, values ...interface{}) error
Exec 执行原生SQL
func (*QueryBuilder) FindByID ¶
func (qb *QueryBuilder) FindByID(id interface{}, dest interface{}) error
FindByID 根据ID查询
func (*QueryBuilder) FindOne ¶
func (qb *QueryBuilder) FindOne(dest interface{}) error
FindOne 查询单条记录
func (*QueryBuilder) Model ¶
func (qb *QueryBuilder) Model(model interface{}) *QueryBuilder
Model 设置模型
func (*QueryBuilder) OrderBy ¶
func (qb *QueryBuilder) OrderBy(field string, direction string) *QueryBuilder
OrderBy 按字段排序
func (*QueryBuilder) Paginate ¶
func (qb *QueryBuilder) Paginate(page, pageSize int) *QueryBuilder
Paginate 分页
func (*QueryBuilder) PaginateQuery ¶
func (qb *QueryBuilder) PaginateQuery(result interface{}) (*Pagination, error)
PaginateQuery 分页查询
func (*QueryBuilder) Pluck ¶
func (qb *QueryBuilder) Pluck(column string, dest interface{}) error
Pluck 提取单个列的值
func (*QueryBuilder) Preload ¶
func (qb *QueryBuilder) Preload(relations ...string) *QueryBuilder
Preload 预加载关系
func (*QueryBuilder) PreloadAll ¶
func (qb *QueryBuilder) PreloadAll() *QueryBuilder
PreloadAll 预加载所有关系
func (*QueryBuilder) QueryMap ¶
func (qb *QueryBuilder) QueryMap() ([]map[string]interface{}, error)
QueryMap 将查询结果转换为map
func (*QueryBuilder) QueryStruct ¶
func (qb *QueryBuilder) QueryStruct(dest interface{}) error
QueryStruct 将查询结果转换为结构体
func (*QueryBuilder) Raw ¶
func (qb *QueryBuilder) Raw(sql string, values ...interface{}) *gorm.DB
Raw 执行原生查询
func (*QueryBuilder) ScanRows ¶
func (qb *QueryBuilder) ScanRows(rows *sql.Rows, dest interface{}) error
ScanRows 扫描多行
func (*QueryBuilder) Scope ¶
func (qb *QueryBuilder) Scope(scopes ...Scope) *QueryBuilder
Scope 应用查询范围
func (*QueryBuilder) Select ¶
func (qb *QueryBuilder) Select(fields ...string) *QueryBuilder
Select 选择字段
func (*QueryBuilder) Transaction ¶
func (qb *QueryBuilder) Transaction() *QueryBuilder
Transaction 启用事务
func (*QueryBuilder) Update ¶
func (qb *QueryBuilder) Update(column string, value interface{}) error
Update 更新记录
func (*QueryBuilder) UpdateColumn ¶
func (qb *QueryBuilder) UpdateColumn(column string, value interface{}) error
UpdateColumn 更新列
func (*QueryBuilder) UpdateColumns ¶
func (qb *QueryBuilder) UpdateColumns(values interface{}) error
UpdateColumns 批量更新列
func (*QueryBuilder) Updates ¶
func (qb *QueryBuilder) Updates(values interface{}) error
Updates 批量更新
func (*QueryBuilder) Where ¶
func (qb *QueryBuilder) Where(condition string, args ...interface{}) *QueryBuilder
Where 添加条件
type ReplicaConfig ¶
type ReplicaConfig struct {
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
SSLMode string `yaml:"sslmode" json:"sslmode"`
Weight int `yaml:"weight" json:"weight"` // 权重,用于负载均衡
}
ReplicaConfig 从库配置
type Repository ¶
type Repository interface {
// 基础操作方法
Find(id interface{}) (interface{}, error)
FindBy(conditions map[string]interface{}) (interface{}, error)
All() (interface{}, error)
Create(entity interface{}) error
Update(entity interface{}) error
Delete(id interface{}) error
// 构建器相关
Query() *QueryBuilder
WithContext(ctx context.Context) Repository
WithTx(tx *gorm.DB) Repository
}
Repository 存储库接口
type Seeder ¶
type Seeder interface {
// Name 获取种子数据名称
Name() string
// Run 执行种子数据填充
Run(db *gorm.DB) error
// Dependencies 获取依赖的其他种子数据
Dependencies() []string
// SetOrder 设置执行顺序
SetOrder(order int)
// GetOrder 获取执行顺序
GetOrder() int
}
Seeder 种子数据接口
type SeederManager ¶
type SeederManager struct {
// contains filtered or unexported fields
}
SeederManager 种子数据管理器
func GetSeederManager ¶
func GetSeederManager(engine interface{}) (*SeederManager, error)
GetSeederManager 获取种子数据管理器
func NewSeederManager ¶
func NewSeederManager(db *gorm.DB) *SeederManager
NewSeederManager 创建种子数据管理器
func (*SeederManager) GetPending ¶
func (m *SeederManager) GetPending() ([]Seeder, error)
GetPending 获取待执行的种子数据
func (*SeederManager) GetSeeders ¶
func (m *SeederManager) GetSeeders() []Seeder
GetSeeders 获取所有种子数据
func (*SeederManager) LoadSeedersFromDirectory ¶
func (m *SeederManager) LoadSeedersFromDirectory(directory string, modelType interface{}) error
LoadSeedersFromDirectory 从目录加载种子数据文件
func (*SeederManager) Register ¶
func (m *SeederManager) Register(seeder Seeder) error
Register 注册种子数据
func (*SeederManager) RunSeeder ¶
func (m *SeederManager) RunSeeder(name string) error
RunSeeder 执行指定名称的种子数据
func (*SeederManager) Status ¶
func (m *SeederManager) Status() ([]map[string]interface{}, error)
Status 获取种子数据状态
type SeederRecord ¶
type SeederRecord struct {
Name string `gorm:"primaryKey;size:255"`
Batch int `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"`
}
SeederRecord 种子数据记录
type SoftDeleteModel ¶
type SoftDeleteModel struct {
Model
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
SoftDeleteModel 带软删除的基础模型结构
type TimestampModel ¶
type TimestampModel struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
TimestampModel 只有时间戳的基础模型
type TransactionManager ¶
type TransactionManager struct {
// contains filtered or unexported fields
}
TransactionManager 提供事务管理功能
func NewTransactionManager ¶
func NewTransactionManager(db *gorm.DB) *TransactionManager
NewTransactionManager 创建新的事务管理器
func (*TransactionManager) Begin ¶
func (tm *TransactionManager) Begin(ctx context.Context) *gorm.DB
Begin 开始一个事务
func (*TransactionManager) BeginWithOptions ¶
func (tm *TransactionManager) BeginWithOptions(ctx context.Context, opts *TxOptions) BeginWithOptionsResult
BeginWithOptions 使用选项开始一个事务,返回事务和可能的错误
func (*TransactionManager) Commit ¶
func (tm *TransactionManager) Commit(tx *gorm.DB) error
Commit 提交事务
func (*TransactionManager) Rollback ¶
func (tm *TransactionManager) Rollback(tx *gorm.DB) error
Rollback 回滚事务
func (*TransactionManager) RunInTransaction ¶
func (tm *TransactionManager) RunInTransaction(ctx context.Context, fn func(tx *gorm.DB) (interface{}, error)) (interface{}, error)
RunInTransaction 执行事务并返回结果,适用于需要返回值的情况
func (*TransactionManager) Transaction ¶
Transaction 在事务上下文中执行函数,自动处理提交和回滚
func (*TransactionManager) WithTransaction ¶
func (tm *TransactionManager) WithTransaction(ctx context.Context, fn func(tx context.Context) error) error
WithTransaction 在事务上下文中操作多个仓储