db

package
v1.1.8 Latest Latest
Warning

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

Go to latest
Published: May 7, 2025 License: MIT Imports: 30 Imported by: 0

README

Flow框架数据库模块

Flow框架数据库模块提供了强大的数据库连接和ORM管理功能,支持多种数据库系统,并提供了便捷的配置方式。

配置格式

Flow数据库模块现在支持两种配置格式:

1. 嵌套格式(推荐)
# config.yaml
database:
  default: "mysql"  # 默认连接名
  connections:
    mysql:
      driver: "mysql"
      host: "localhost"
      port: 3306
      database: "mydatabase"
      username: "root"
      password: "password"
      charset: "utf8mb4"
      # 其他配置...
    
    postgres:
      driver: "postgres"
      host: "postgres_host"
      port: 5432
      database: "postgres_db"
      username: "postgres_user"
      password: "postgres_password"
      # 其他配置...
2. 平铺格式(旧版,保留向后兼容)
# config.yaml
database:
  driver: "mysql"
  host: "localhost"
  port: 3306
  database: "mydatabase"
  username: "root"
  password: "password"
  charset: "utf8mb4"
  # 其他配置...

在应用中使用

基本用法
package main

import (
    "github.com/zzliekkas/flow"
    "github.com/zzliekkas/flow/config"
)

func main() {
    // 创建engine
    engine := flow.New()
    
    // 使用配置文件初始化数据库
    engine.WithConfig("config.yaml").WithDatabase()
    
    // 或者直接传入配置
    engine.WithDatabase(map[string]interface{}{
        "database": map[string]interface{}{
            "default": "mysql",
            "connections": map[string]interface{}{
                "mysql": map[string]interface{}{
                    "driver": "mysql",
                    "host": "localhost",
                    "port": 3306,
                    "database": "testdb",
                    "username": "root",
                    "password": "password",
                },
            },
        },
    })
    
    // 启动应用
    engine.Run(":8080")
}
依赖注入使用
type UserRepository struct {
    DB *gorm.DB
}

func NewUserRepository(dbProvider *db.DbProvider) *UserRepository {
    return &UserRepository{
        DB: dbProvider.DB,
    }
}

// 在engine上注册
engine.Provide(NewUserRepository)

支持的数据库类型

  • MySQL
  • PostgreSQL
  • SQLite

连接池配置

数据库连接池可以通过以下选项配置:

database:
  connections:
    mysql:
      # ...基本配置
      max_idle_conns: 10     # 最大空闲连接数
      max_open_conns: 100    # 最大打开连接数
      conn_max_lifetime: 1h  # 连接最大生存时间
      conn_max_idle_time: 30m # 空闲连接最大存活时间

健康检查配置

您还可以配置数据库连接的健康检查:

database:
  connections:
    mysql:
      # ...基本配置
      health_check: true                 # 启用健康检查
      health_check_period: 30s           # 健康检查周期
      health_check_timeout: 5s           # 健康检查超时时间
      health_check_sql: "SELECT 1"       # 健康检查SQL

错误处理

数据库模块定义了以下错误类型以便于错误处理:

  • ErrUnsupportedDriver - 不支持的数据库驱动类型
  • ErrConnectionNotFound - 连接未找到
  • ErrInvalidConfiguration - 无效的数据库配置
  • ErrDatabaseNotFound - 未找到指定的数据库
  • ErrConnectionFailed - 数据库连接失败

扩展与自定义

您可以通过以下方式扩展数据库功能:

  1. 创建自定义的连接配置选项
  2. 实现自定义的Repository
  3. 添加数据库中间件

请参考文档以获取更多详细信息。

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

Examples

Constants

View Source
const (
	// MySQL 数据库
	MySQL = "mysql"
	// PostgreSQL 数据库
	PostgreSQL = "postgres"
	// SQLite 数据库
	SQLite = "sqlite"
)

数据库驱动类型常量

View Source
const (
	// 迁移表名
	MigrationTable = "migrations"
	// 迁移文件模板
	MigrationTemplate = `` /* 340-byte string literal not displayed */

)

定义迁移相关常量

Variables

View Source
var (
	// ErrUnsupportedDriver 不支持的驱动类型错误
	ErrUnsupportedDriver = errors.New("不支持的数据库驱动类型")
	// ErrConnectionNotFound 连接未找到错误
	ErrConnectionNotFound = errors.New("数据库连接未找到")
	// ErrInvalidConfiguration 无效的数据库配置
	ErrInvalidConfiguration = errors.New("无效的数据库配置")
	// ErrDatabaseNotFound 未找到指定的数据库
	ErrDatabaseNotFound = errors.New("未找到指定的数据库连接")
	// ErrConnectionFailed 数据库连接失败
	ErrConnectionFailed = errors.New("数据库连接失败")
)

定义错误类型

View Source
var (
	ErrMigrationFailed    = errors.New("迁移执行失败")
	ErrMigrationNotFound  = errors.New("找不到指定的迁移")
	ErrMigrationExists    = errors.New("迁移已存在")
	ErrInvalidMigration   = errors.New("无效的迁移")
	ErrInvalidMigrationID = errors.New("无效的迁移ID")
)

迁移错误定义

View Source
var (
	ErrSeederFailed   = errors.New("种子数据执行失败")
	ErrSeederNotFound = errors.New("找不到指定的种子数据")
	ErrSeederExists   = errors.New("种子数据已存在")
	ErrInvalidSeeder  = errors.New("无效的种子数据")
)

定义种子数据相关错误

Functions

func GetConnection

func GetConnection(engine interface{}, name string) (*gorm.DB, error)

GetConnection 获取指定名称的数据库连接

func GetConnectionDetails added in v1.1.6

func GetConnectionDetails(config Config) map[string]interface{}

GetConnectionDetails 从配置中获取连接详情,用于测试和调试

func GetDefaultConnection

func GetDefaultConnection(engine interface{}) (*gorm.DB, error)

GetDefaultConnection 获取默认数据库连接

func GetNestedConfigDetails added in v1.1.6

func GetNestedConfigDetails(config map[string]interface{}) (map[string]interface{}, error)

GetNestedConfigDetails 从嵌套配置中获取所有连接详情

func GetTransaction

func GetTransaction(ctx context.Context) (*gorm.DB, bool)

GetTransaction 从上下文中获取事务

func InitializeDatabase added in v1.0.4

func InitializeDatabase(options []interface{}) (interface{}, error)

InitializeDatabase 初始化数据库

func IsTestMode added in v1.1.6

func IsTestMode() bool

IsTestMode 返回当前测试模式状态

func NewTransactionContext

func NewTransactionContext(parent context.Context, tx *gorm.DB) context.Context

NewTransactionContext 创建一个包含事务信息的上下文

func OrderBy

func OrderBy(db *gorm.DB, field string, direction string) *gorm.DB

OrderBy 排序辅助函数

func ParseMigrationID

func ParseMigrationID(id string) (time.Time, error)

ParseMigrationID 解析迁移ID

func Preload

func Preload(db *gorm.DB, relations ...string) *gorm.DB

Preload 预加载关联

func PreloadAll

func PreloadAll(db *gorm.DB) *gorm.DB

PreloadAll 预加载所有关联

func RegisterDatabaseInitializer added in v1.0.4

func RegisterDatabaseInitializer(registerFunc func(DbInitializer))

RegisterDatabaseInitializer 注册数据库初始化器到flow框架 此函数由flow包调用,用于建立flow包与db包的连接

func RegisterMigration

func RegisterMigration(id, name string, up, down func(db *gorm.DB) error)

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

func Transaction(db *gorm.DB, fn func(tx *gorm.DB) error) error

Transaction 执行数据库事务

func WithCache

func WithCache(db *gorm.DB, cache Cache, key string, expiration time.Duration) *gorm.DB

WithCache 使用缓存查询

func WithContext

func WithContext(ctx context.Context, db *gorm.DB) *gorm.DB

WithContext 在已有数据库连接上设置上下文

func WithLock

func WithLock(db *gorm.DB, mode LockMode) *gorm.DB

WithLock 使用锁查询

func WithScope

func WithScope(db *gorm.DB, scopes ...Scope) *gorm.DB

WithScope 应用查询范围

Types

type BaseMigration

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

BaseMigration 基础迁移实现

func (*BaseMigration) Down

func (m *BaseMigration) Down(db *gorm.DB) error

Down 回滚迁移

func (*BaseMigration) ID

func (m *BaseMigration) ID() string

ID 获取迁移ID

func (*BaseMigration) Name

func (m *BaseMigration) Name() string

Name 获取迁移名称

func (*BaseMigration) Up

func (m *BaseMigration) Up(db *gorm.DB) error

Up 执行迁移

type BaseRepository

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

BaseRepository 基础存储库实现

func NewRepository

func NewRepository(db *gorm.DB, model interface{}) *BaseRepository

NewRepository 创建新的存储库

func (*BaseRepository) All

func (r *BaseRepository) All() (interface{}, error)

All 获取所有实体

func (*BaseRepository) Count

func (r *BaseRepository) Count() (int64, error)

Count 计数

func (*BaseRepository) Create

func (r *BaseRepository) Create(entity interface{}) error

Create 创建实体

func (*BaseRepository) Delete

func (r *BaseRepository) Delete(id interface{}) error

Delete 删除实体

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) Query

func (r *BaseRepository) Query() *QueryBuilder

Query 创建查询构建器

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 设置主键名称

func (*BaseRepository) WithTx

func (r *BaseRepository) WithTx(tx *gorm.DB) Repository

WithTx 使用事务

type BaseSeeder

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

BaseSeeder 基础种子数据实现

func (*BaseSeeder) Dependencies

func (s *BaseSeeder) Dependencies() []string

Dependencies 获取依赖的其他种子数据

func (*BaseSeeder) GetOrder

func (s *BaseSeeder) GetOrder() int

GetOrder 获取执行顺序

func (*BaseSeeder) Name

func (s *BaseSeeder) Name() string

Name 获取种子数据名称

func (*BaseSeeder) Run

func (s *BaseSeeder) Run(db *gorm.DB) error

Run 执行种子数据填充

func (*BaseSeeder) SetOrder

func (s *BaseSeeder) SetOrder(order int)

SetOrder 设置执行顺序

type BeginWithOptionsResult

type BeginWithOptionsResult struct {
	TX  *gorm.DB
	Err error
}

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 WithDebug added in v1.0.4

func WithDebug(enable bool) ConnectionOption

WithDebug 启用GORM调试模式

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

type DatabaseProvider struct {
	Name     string
	Priority int
	// contains filtered or unexported fields
}

DatabaseProvider 数据库服务提供者

func NewDatabaseProvider

func NewDatabaseProvider(container *di.Container) *DatabaseProvider

NewDatabaseProvider 创建数据库服务提供者

func (*DatabaseProvider) Boot

func (p *DatabaseProvider) Boot(app interface{}) error

Boot 启动数据库服务

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

type DbProvider struct {
	Manager *Manager
	DB      *gorm.DB
}

DbProvider 数据库服务提供者(重命名以避免冲突)

func (*DbProvider) Close added in v1.0.4

func (p *DbProvider) Close() error

Close 关闭数据库连接

type EnumValue

type EnumValue interface {
	String() string
	Value() int
}

EnumValue 枚举类型接口

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

func (j JSONField) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType 实现数据库特定的类型定义

func (JSONField) GormDataType

func (JSONField) GormDataType() string

GormDataType 实现 schema.GormDataType 接口

func (*JSONField) Scan

func (j *JSONField) Scan(value interface{}) error

Scan 实现 sql.Scanner 接口

func (JSONField) Value

func (j JSONField) Value() (driver.Value, error)

Value 实现 driver.Valuer 接口

type LockMode

type LockMode string

Lock 锁定查询

const (
	// LockForUpdate FOR UPDATE锁
	LockForUpdate LockMode = "FOR UPDATE"
	// LockInShareMode SHARE MODE锁
	LockInShareMode LockMode = "LOCK IN SHARE MODE"
)

type Manager

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

Manager 数据库连接管理器

func GetInstance

func GetInstance(engine interface{}) (*Manager, error)

GetInstance 获取数据库管理器实例

func NewManager

func NewManager() *Manager

NewManager 创建数据库连接管理器

func (*Manager) AllHealthStatus

func (m *Manager) AllHealthStatus() map[string]bool

AllHealthStatus 获取所有数据库连接的健康状态

func (*Manager) Close

func (m *Manager) Close() error

Close 关闭所有数据库连接

func (*Manager) Configs added in v1.1.6

func (m *Manager) Configs() map[string]Config

Configs 返回所有配置的映射

func (*Manager) Connect

func (m *Manager) Connect(name string) (*gorm.DB, error)

Connect 建立数据库连接

func (*Manager) Connection

func (m *Manager) Connection(name string) (*gorm.DB, error)

Connection 获取指定名称的数据库连接

func (*Manager) ConnectionCount added in v1.1.6

func (m *Manager) ConnectionCount() int

ConnectionCount 返回配置的连接数量

func (*Manager) Default

func (m *Manager) Default() (*gorm.DB, error)

Default 获取默认数据库连接

func (*Manager) DefaultConnectionName added in v1.1.6

func (m *Manager) DefaultConnectionName() string

DefaultConnectionName 返回默认连接名称

func (*Manager) FromConfig

func (m *Manager) FromConfig(configManager *config.Manager) error

FromConfig 从配置管理器加载数据库配置

func (*Manager) HasConnection

func (m *Manager) HasConnection(name string) bool

HasConnection 检查是否存在指定名称的数据库连接

func (*Manager) IsHealthy

func (m *Manager) IsHealthy(name string) bool

IsHealthy 检查数据库连接是否健康

func (*Manager) Register

func (m *Manager) Register(name string, config Config) error

Register 注册数据库配置

func (*Manager) SetDefaultConnection

func (m *Manager) SetDefaultConnection(name string)

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 迁移接口

func NewMigration

func NewMigration(id, name string, up, down func(db *gorm.DB) error) Migration

NewMigration 创建新的迁移

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 迁移记录

func (MigrationRecord) TableName

func (MigrationRecord) TableName() string

TableName 表名

type Migrator

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

Migrator 迁移管理器

func NewMigrator

func NewMigrator(db *gorm.DB, directory string) *Migrator

NewMigrator 创建迁移管理器

func (*Migrator) CreateMigrationFile

func (m *Migrator) CreateMigrationFile(name string) (string, error)

CreateMigrationFile 创建新的迁移文件

func (*Migrator) GetMigrations

func (m *Migrator) GetMigrations() []Migration

GetMigrations 获取所有迁移

func (*Migrator) GetPending

func (m *Migrator) GetPending() ([]Migration, error)

GetPending 获取待执行的迁移

func (*Migrator) GetRan

func (m *Migrator) GetRan() ([]string, error)

GetRan 获取已执行的迁移

func (*Migrator) LoadMigrationsFromConfig

func (m *Migrator) LoadMigrationsFromConfig(config []map[string]interface{}) error

LoadMigrationsFromConfig 从配置中加载迁移

func (*Migrator) LoadMigrationsFromDirectory

func (m *Migrator) LoadMigrationsFromDirectory(directory string) error

LoadMigrationsFromDirectory 从目录加载迁移

func (*Migrator) Migrate

func (m *Migrator) Migrate() error

Migrate 执行所有待执行的迁移

func (*Migrator) Register

func (m *Migrator) Register(migration Migration) error

Register 注册迁移

func (*Migrator) Reset

func (m *Migrator) Reset() error

Reset 重置所有迁移

func (*Migrator) Rollback

func (m *Migrator) Rollback() error

Rollback 回滚最后一批次的迁移

func (*Migrator) RollbackTo

func (m *Migrator) RollbackTo(id string) error

RollbackTo 回滚到指定的迁移

func (*Migrator) Status

func (m *Migrator) Status() ([]map[string]interface{}, error)

Status 获取迁移状态

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 设置是否忽略错误

func WithOrder

func WithOrder(order int) ModelSeederOption

WithOrder 设置执行顺序

func WithTruncate

func WithTruncate(truncate bool) ModelSeederOption

WithTruncate 设置是否在填充前清空表

type Pagination

type Pagination struct {
	Page      int   `json:"page"`
	PageSize  int   `json:"page_size"`
	Total     int64 `json:"total"`
	TotalPage int   `json:"total_page"`
}

Paginate 分页查询辅助函数

func Paginate

func Paginate(page, pageSize int, db *gorm.DB, result interface{}) (*Pagination, error)

Paginate 执行分页查询

type QueryBuilder

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

QueryBuilder 查询构建器

func NewQueryBuilder

func NewQueryBuilder(db *gorm.DB) *QueryBuilder

NewQueryBuilder 创建查询构建器

func (*QueryBuilder) Commit

func (qb *QueryBuilder) Commit() error

Commit 提交事务

func (*QueryBuilder) Context

func (qb *QueryBuilder) Context(ctx context.Context) *QueryBuilder

Context 设置上下文

func (*QueryBuilder) Count

func (qb *QueryBuilder) Count(count *int64) error

Count 计数

func (*QueryBuilder) Create

func (qb *QueryBuilder) Create(value interface{}) error

Create 创建记录

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) Exists

func (qb *QueryBuilder) Exists() (bool, error)

Exists 检查记录是否存在

func (*QueryBuilder) Find

func (qb *QueryBuilder) Find(dest interface{}) error

Find 查询多条记录

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) First

func (qb *QueryBuilder) First(dest interface{}) error

First 查询第一条记录

func (*QueryBuilder) Group

func (qb *QueryBuilder) Group(group string) *QueryBuilder

Group 分组

func (*QueryBuilder) Last

func (qb *QueryBuilder) Last(dest interface{}) error

Last 查询最后一条记录

func (*QueryBuilder) Limit

func (qb *QueryBuilder) Limit(limit int) *QueryBuilder

Limit 限制数量

func (*QueryBuilder) Lock

func (qb *QueryBuilder) Lock(mode LockMode) *QueryBuilder

Lock 锁定查询

func (*QueryBuilder) Model

func (qb *QueryBuilder) Model(model interface{}) *QueryBuilder

Model 设置模型

func (*QueryBuilder) Offset

func (qb *QueryBuilder) Offset(offset int) *QueryBuilder

Offset 偏移

func (*QueryBuilder) Order

func (qb *QueryBuilder) Order(order string) *QueryBuilder

Order 排序

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) Rollback

func (qb *QueryBuilder) Rollback() error

Rollback 回滚事务

func (*QueryBuilder) Row

func (qb *QueryBuilder) Row() *sql.Row

Row 获取单行

func (*QueryBuilder) Rows

func (qb *QueryBuilder) Rows() (*sql.Rows, error)

Rows 获取多行

func (*QueryBuilder) Save

func (qb *QueryBuilder) Save(value interface{}) error

Save 保存记录

func (*QueryBuilder) Scan

func (qb *QueryBuilder) Scan(dest interface{}) error

Scan 扫描结果

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) Take

func (qb *QueryBuilder) Take(dest interface{}) error

Take 查询一条记录

func (*QueryBuilder) ToSQL

func (qb *QueryBuilder) ToSQL() string

ToSQL 获取SQL

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 Scope

type Scope func(*gorm.DB) *gorm.DB

Scope 定义查询范围

func BetweenTime

func BetweenTime(field string, timeRange TimeRange) Scope

BetweenTime 时间范围查询

func EndsWith

func EndsWith(field string, value string) Scope

EndsWith 后缀查询

func In

func In(field string, values ...interface{}) Scope

In 包含查询

func IsNotNull

func IsNotNull(field string) Scope

IsNotNull 非空值查询

func IsNull

func IsNull(field string) Scope

IsNull 空值查询

func Like

func Like(field string, value string) Scope

Like 模糊查询

func NotIn

func NotIn(field string, values ...interface{}) Scope

NotIn 不包含查询

func StartsWith

func StartsWith(field string, value string) Scope

StartsWith 前缀查询

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 种子数据接口

func NewSeeder

func NewSeeder(name string, run func(db *gorm.DB) error, dependencies ...string) Seeder

NewSeeder 创建新的种子数据

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) GetRan

func (m *SeederManager) GetRan() ([]string, error)

GetRan 获取已执行的种子数据

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) Reset

func (m *SeederManager) Reset() error

Reset 重置所有种子数据

func (*SeederManager) Run

func (m *SeederManager) Run() error

Run 执行所有待执行的种子数据

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 种子数据记录

func (SeederRecord) TableName

func (SeederRecord) TableName() string

TableName 表名

type SoftDeleteModel

type SoftDeleteModel struct {
	Model
	DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}

SoftDeleteModel 带软删除的基础模型结构

type TimeRange

type TimeRange struct {
	Start time.Time
	End   time.Time
}

TimeRange 时间范围结构

type TimestampModel

type TimestampModel struct {
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

TimestampModel 只有时间戳的基础模型

type TransactionKey

type TransactionKey struct{}

TransactionKey 表示事务上下文的键

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

func (tm *TransactionManager) Transaction(ctx context.Context, fn func(tx *gorm.DB) error) error

Transaction 在事务上下文中执行函数,自动处理提交和回滚

func (*TransactionManager) WithTransaction

func (tm *TransactionManager) WithTransaction(ctx context.Context, fn func(tx context.Context) error) error

WithTransaction 在事务上下文中操作多个仓储

type TxOptions

type TxOptions struct {
	Isolation string
	ReadOnly  bool
}

TxOptions 表示事务选项

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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