db

package module
v0.4.4-preview Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 24 Imported by: 0

README

EIT-DB - Go 数据库抽象层

一个受 Ecto (Elixir) 启发的 Go 数据库抽象层,提供类型安全的 Schema、Changeset 和跨数据库适配器支持。

✨ 特性

  • Schema 系统 - 声明式数据结构定义,支持验证器和默认值
  • Changeset 验证 - 数据变更追踪和验证,类似 Ecto.Changeset,支持丰富的验证规则
  • Query Constructor - 三层查询构造架构,支持 MySQL/PostgreSQL/SQLite 方言 (v0.4.1+)
  • Migration 工具 - 灵活的数据库迁移工具,支持 Schema-based 和 Raw SQL 两种方式
  • 跨数据库适配器 - 支持 MySQL, PostgreSQL, SQLite, SQL Server
  • 查询构建器 - 类型安全的查询接口
  • GORM 集成 - 完全兼容 GORM v1/v2,可无缝协作
  • 动态建表 - 支持运行时动态创建表,PostgreSQL 用触发器,MySQL/SQLite 用 GORM Hook
  • 定时任务 - 跨数据库的定时任务支持

📦 安装

go get github.com/eit-cms/eit-db

🚀 快速开始

1. 配置数据库连接

使用 YAML 配置文件:

# config.yaml
database:
  adapter: sqlite
  database: ./data/app.db
  pool:
    max_connections: 25
    idle_timeout: 300

多 Adapter YAML 配置(新):

# adapters.yaml
adapters:
    primary:
        adapter: postgres
        host: localhost
        port: 5432
        username: postgres
        password: ""
        database: app
        ssl_mode: disable

    search:
        adapter: mongodb
        database: search_db
        options:
            uri: "mongodb://localhost:27017"

使用多 Adapter 配置:

registry, err := eit_db.LoadAdapterRegistry("adapters.yaml")
if err != nil {
        panic(err)
}

if err := eit_db.RegisterAdapterConfigs(registry); err != nil {
        panic(err)
}

repo, err := eit_db.NewRepositoryFromAdapterConfig("primary")
if err != nil {
        panic(err)
}
defer repo.Close()

或使用代码配置:

package main

import "github.com/eit-cms/eit-db"

func main() {
    config := &eit_db.Config{
        Adapter:   "sqlite",
        Database:  "./data/app.db",
        Pool: &eit_db.PoolConfig{
            MaxConnections: 25,
            IdleTimeout:    300,
        },
    }
    
    repo, err := eit_db.NewRepository(config)
    if err != nil {
        panic(err)
    }
    defer repo.Close()
    
    // 现在可以使用 GORM
    gormDB := repo.GetGormDB()
}
2. 定义 Schema
func BuildUserSchema() db.Schema {
    schema := db.NewBaseSchema("users")
    
    schema.AddField(
        db.NewField("id", db.TypeInteger).
            PrimaryKey().
            Build(),
    )
    
    schema.AddField(
        db.NewField("email", db.TypeString).
            Null(false).
            Unique().
            Validate(&db.EmailValidator{}).
            Build(),
    )
    
    schema.AddField(
        db.NewField("created_at", db.TypeTime).Build(),
    )
    
    return schema
}
3. 使用 GORM ORM
type User struct {
    ID    uint
    Email string
}

repo, _ := eit_db.InitDB("config.yaml")
gormDB := repo.GetGormDB()

// 使用 GORM 的所有功能
var users []User
gormDB.Find(&users)

gormDB.Create(&User{Email: "test@example.com"})
4. 使用 Changeset 进行数据验证 (v0.3.1+)
// 创建 Changeset
cs := db.NewChangeset(userSchema)
cs.Cast(map[string]interface{}{
    "name":  "Alice",
    "email": "alice@example.com",
    "age":   25,
})

// 链式验证
cs.ValidateRequired([]string{"name", "email"}).
   ValidateLength("name", 2, 50).
   ValidateFormat("email", `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`).
   ValidateNumber("age", map[string]interface{}{"greater_than_or_equal_to": 18.0})

// 检查验证结果
if cs.IsValid() {
    // 数据有效,可以保存
    data := cs.GetChanges()
} else {
    // 显示错误
    for field, errors := range cs.Errors() {
        fmt.Printf("%s: %v\n", field, errors)
    }
}

可用的验证方法:

  • ValidateRequired(fields) - 验证必填字段
  • ValidateLength(field, min, max) - 验证字符串长度
  • ValidateFormat(field, pattern) - 正则表达式验证
  • ValidateInclusion(field, list) - 白名单验证
  • ValidateExclusion(field, list) - 黑名单验证
  • ValidateNumber(field, opts) - 数字范围验证
5. 数据库迁移工具 (v0.4.0+)

EIT-DB 提供了强大的迁移工具,支持两种迁移方式:

初始化迁移项目:

# 安装工具
go install github.com/eit-cms/eit-db/cmd/eit-migrate@latest

# 或直接构建
cd /path/to/eit-db
go build -o ~/bin/eit-migrate ./cmd/eit-migrate

# 初始化迁移项目
eit-migrate init

生成迁移文件:

# 生成 Schema-based 迁移(类型安全)
eit-migrate generate create_users_table

# 生成 Raw SQL 迁移(完全控制)
eit-migrate generate add_indexes --type sql

运行迁移:

cd migrations
cp .env.example .env
# 编辑 .env 配置数据库连接

# 运行迁移
go run . up

# 查看状态
go run . status

# 回滚最后一个迁移
go run . down

Schema-based Migration 示例:

func NewMigration_20260203150405_CreateUsersTable() db.MigrationInterface {
    migration := db.NewSchemaMigration("20260203150405", "create_users_table")

    userSchema := db.NewBaseSchema("users")
    userSchema.AddField(&db.Field{
        Name:    "id",
        Type:    db.TypeInteger,
        Primary: true,
        Autoinc: true,
    })
    userSchema.AddField(&db.Field{
        Name: "email",
        Type: db.TypeString,
        Null: false,
        Unique: true,
    })

    migration.CreateTable(userSchema)
    return migration
}

Raw SQL Migration 示例:

func NewMigration_20260203160000_AddIndexes() db.MigrationInterface {
    migration := db.NewRawSQLMigration("20260203160000", "add_indexes")

    migration.AddUpSQL(`
        CREATE INDEX idx_users_email ON users(email);
        CREATE INDEX idx_posts_user_id ON posts(user_id);
    `)

    migration.AddDownSQL(`
        DROP INDEX idx_users_email;
        DROP INDEX idx_posts_user_id;
    `)

    return migration
}

详细文档:

🗄️ 支持的数据库

数据库 适配器 状态
SQLite sqlite
MySQL mysql
PostgreSQL postgres

📖 文档

❓ 常见问题

GetGormDB() 返回 nil

确保 Repository 已成功初始化。如果创建时返回错误,GetGormDB() 会返回 nil。

repo, err := eit_db.NewRepository(config)
if err != nil {
    log.Fatal(err)
}

gormDB := repo.GetGormDB() // 现在返回有效实例
PostgreSQL 连接失败

检查是否在使用信任认证。如果使用信任认证,确保密码字段为空字符串:

config := &eit_db.Config{
    Adapter:   "postgres",
    Username:  "postgres",
    Password:  "", // 信任认证
    Database:  "myapp",
    SSLMode:   "disable",
}
MySQL 连接失败

确保 MySQL 服务器正在运行,用户名和密码正确:

config := &eit_db.Config{
    Adapter:   "mysql",
    Host:      "localhost",
    Port:      3306,
    Username:  "root",
    Password:  "password",
    Database:  "myapp",
}

🧪 测试

运行所有测试:

go test -v ./...

运行特定测试:

# Changeset 验证测试
go test -v -run TestValidate

# 适配器测试
go test -v -run TestSQLiteAdapterInitialization

# 动态表测试
go test -v -run TestDynamicTable

性能基准测试:

go test -bench=BenchmarkGetGormDB -benchmem

📊 版本更新

v0.4.2 - SQL Server Adapter (2026-02-03)

核心新增:SQL Server 数据库支持,验证三层查询构造架构的扩展性

SQLServerDialect 实现

  • ✅ 方括号标识符引用:[table].[column] 而非反引号或双引号
  • ✅ @pN 参数占位符:@p1, @p2 而非 ?$1
  • ✅ SQL Server 专属分页语法:OFFSET n ROWS FETCH NEXT m ROWS ONLY
  • ✅ 完整的三层架构兼容性验证

SQLServerAdapter 实现

  • ✅ 基于 github.com/microsoft/go-mssqldb 和 gorm.io/driver/sqlserver
  • ✅ 默认端口 1433,支持连接池配置
  • ✅ 完整的事务支持(Commit/Rollback/Exec/Query/QueryRow)
  • ✅ GetQueryBuilderProvider() 返回 SQL Server 方言提供者

测试覆盖

  • ✅ TestSQLServerDialect:5个测试用例验证 SQL 生成
  • ✅ TestSQLServerIdentifierQuoting:方括号引用验证
  • ✅ TestSQLServerComplexQuery:复杂查询验证
  • ✅ TestSQLServerDialectQuotingComparison:跨方言对比测试
  • ✅ 所有现有测试继续通过,100% 向后兼容

架构验证:SQL Server 的独特语法完美融入三层架构,证明设计的可扩展性


v0.4.1 - 查询构造器三层架构 (2026-02-03)

核心改进:建立查询构造器的三层分离架构,为 v0.5.0+ 多 Adapter 支持打基础

顶层 - 用户 API 层

  • QueryConstructor 接口:用户通过此接口构建查询
  • ✅ 流式 API:Where(), WhereAll(), WhereAny(), Select(), OrderBy(), Limit(), Offset()
  • ✅ 灵活的条件构造器:Eq(), Ne(), Gt(), Lt(), Gte(), Lte(), In(), Between(), Like()
  • ✅ 复合条件:And(), Or(), Not()

中层 - Adapter 转义层

  • QueryConstructorProvider 接口:每个 Adapter 通过此接口提供数据库特定的实现
  • QueryBuilderCapabilities 结构体:声明 Adapter 支持的操作和优化特性
  • ✅ 方言无关的 API 设计

底层 - 数据库执行层

  • SQLQueryConstructor 实现:标准 SQL 生成
  • SQLDialect 接口:支持不同的 SQL 方言
  • ✅ 方言实现:MySQLDialect, PostgreSQLDialect, SQLiteDialect
  • ✅ 参数化查询:防止 SQL 注入,自动转换为 ?$1 等占位符

测试覆盖:20+ 单元测试,验证每个条件、操作符和组合的 SQL 生成正确性

v0.4.0 - Migration 工具 (2026-02-03)

✅ 全新的数据库迁移工具
✅ 支持 Schema-based 和 Raw SQL 两种迁移方式
✅ 命令行工具 eit-migrate
✅ 自动版本管理和状态追踪
✅ 支持跨数据库和非关系型数据库

v0.3.1 - Changeset 增强 (2026-02-03)

✅ 新增 7 个验证方法(Required, Length, Format, Inclusion, Exclusion, Number, GetChange)
✅ 完整的测试套件
✅ 修复 TestDynamicTableConfigBuilder 测试

v0.1.4 - 稳定性修复 (2026-02-02)

✅ 修复 MySQL 驱动 GetGormDB() 返回 nil 问题
✅ 修复 PostgreSQL 认证 "role does not exist" 问题
✅ 改进连接池配置,完整支持 MaxLifetime
✅ 增强错误诊断信息,包含完整的连接参数
✅ 添加完整的测试套件(10+ 测试用例)
✅ 100% 向后兼容

详见 版本修复说明

🔗 相关链接

🧪 测试

单元测试

运行核心库测试:

go test ./... -v
集成测试

测试所有适配器(SQLite 无需依赖,PostgreSQL/MySQL 需要 Docker):

# 仅 SQLite 测试(推荐开发期间使用)
go test ./adapter-application-tests -v

# 或使用测试脚本
./test.sh integration

# 完整测试(启动所有数据库 + 运行测试)
./test.sh all-keep
使用 Docker 运行完整测试
# 启动 PostgreSQL、MySQL、SQL Server 容器
./test.sh start

# 运行所有测试
./test.sh integration

# 停止容器
./test.sh stop

# 或一步完成
./test.sh all
测试覆盖范围

详见 测试覆盖范围文档

已验证的功能:

  • ✅ SQLite: CRUD、CTE、窗口函数、JSON、事务、UPSERT
  • ✅ 多适配器管理:反射注册、YAML 配置、工厂模式
  • ✅ QueryFeatures:版本感知、优先级路由、特性声明
  • ⏭️ PostgreSQL:物化视图、数组、全文搜索、JSONB
  • ⏭️ MySQL:全文搜索、JSON、窗口函数、ON DUPLICATE KEY
  • ⏭️ SQL Server:MERGE、递归 CTE、临时表

📝 许可证

MIT License

📧 支持

如有问题或建议,欢迎提交 Issue 或 Pull Request。


最后更新:2026-02-04
当前版本:v0.4.2
下一版本:v0.5.0 (多适配器+集成测试完成)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	PostgreSQLSupport = &RelationshipSupport{
		OneToOne:           true,
		OneToMany:          true,
		ManyToMany:         true,
		SupportsForeignKey: true,
		SupportsJoin:       true,
		SupportsNested:     true,
		Strategy:           StrategyNative,
	}

	SQLServerSupport = &RelationshipSupport{
		OneToOne:           true,
		OneToMany:          true,
		ManyToMany:         true,
		SupportsForeignKey: true,
		SupportsJoin:       true,
		SupportsNested:     true,
		Strategy:           StrategyNative,
	}

	MySQLSupport = &RelationshipSupport{
		OneToOne:           true,
		OneToMany:          true,
		ManyToMany:         false,
		SupportsForeignKey: true,
		SupportsJoin:       true,
		SupportsNested:     false,
		Strategy:           StrategyJoinTable,
	}

	SQLiteSupport = &RelationshipSupport{
		OneToOne:           true,
		OneToMany:          true,
		ManyToMany:         false,
		SupportsForeignKey: false,
		SupportsJoin:       true,
		SupportsNested:     false,
		Strategy:           StrategyJoinTable,
	}

	MongoDBSupport = &RelationshipSupport{
		OneToOne:           true,
		OneToMany:          true,
		ManyToMany:         true,
		SupportsForeignKey: false,
		SupportsJoin:       false,
		SupportsNested:     true,
		Strategy:           StrategyApplication,
	}

	GraphDatabaseSupport = &RelationshipSupport{
		OneToOne:           true,
		OneToMany:          true,
		ManyToMany:         true,
		SupportsForeignKey: false,
		SupportsJoin:       false,
		SupportsNested:     true,
		Strategy:           StrategyNative,
	}

	NoRelationshipSupport = &RelationshipSupport{
		OneToOne:           false,
		OneToMany:          false,
		ManyToMany:         false,
		SupportsForeignKey: false,
		SupportsJoin:       false,
		SupportsNested:     false,
		Strategy:           StrategyNotSupported,
	}
)

预定义的常见数据库支持情况

Functions

func CompareQueryFeatures

func CompareQueryFeatures(qf1, qf2 *QueryFeatures) map[string]interface{}

CompareQueryFeatures 对比两个数据库的查询特性

func ConvertValue

func ConvertValue(value interface{}, targetType FieldType) (interface{}, error)

ConvertValue 值类型转换

func ExampleMySQLDynamicTable

func ExampleMySQLDynamicTable()

ExampleMySQLDynamicTable MySQL 动态建表示例 场景:在电商系统中,为每个店铺创建独立的订单表来分离数据

func ExamplePostgreSQLDynamicTable

func ExamplePostgreSQLDynamicTable()

ExamplePostgreSQLDynamicTable PostgreSQL 动态建表示例 场景:在 CMS 系统中,当创建自定义字段时,自动为该自定义字段创建专属表存储字段数据

func ExampleSQLiteDynamicTable

func ExampleSQLiteDynamicTable()

ExampleSQLiteDynamicTable SQLite 动态建表示例 场景:在日志系统中,为每个应用创建独立的日志表

func GetStructFields

func GetStructFields(v interface{}) []string

GetStructFields 获取结构体的字段名列表(按 db tag 顺序)

func GetStructValues

func GetStructValues(v interface{}) []interface{}

GetStructValues 获取结构体的字段值列表

func LoadAdapterRegistry

func LoadAdapterRegistry(filename string) (map[string]*Config, error)

LoadAdapterRegistry 从文件加载多 Adapter 配置(支持 JSON 和 YAML)

func PrintQueryFeatureMatrix

func PrintQueryFeatureMatrix(databases ...string) string

PrintQueryFeatureMatrix 打印查询特性矩阵

func RealWorldExample

func RealWorldExample(repo *Repository, ctx context.Context) error

RealWorldExample 真实业务场景示例 场景:SaaS CMS 系统 - 为每个客户项目创建独立的内容表

func RegisterAdapter

func RegisterAdapter(factory AdapterFactory)

RegisterAdapter 注册适配器工厂

func RegisterAdapterConfig

func RegisterAdapterConfig(name string, config *Config) error

RegisterAdapterConfig 注册 Adapter 配置(支持多 Adapter 注册)

func RegisterAdapterConfigs

func RegisterAdapterConfigs(configs map[string]*Config) error

RegisterAdapterConfigs 批量注册 Adapter 配置

func RegisterAdapterConstructor

func RegisterAdapterConstructor(name string, ctor interface{}) error

RegisterAdapterConstructor 使用构造函数动态注册 Adapter 允许的构造函数签名:func(*Config) (Adapter, error) 或 func(*Config) (*T, error)

func RegisterCustomSQLiteDriver

func RegisterCustomSQLiteDriver(driverName string, functions map[string]interface{}) error

RegisterCustomSQLiteDriver 注册带有自定义函数的 SQLite 驱动 这是推荐的方式来添加自定义函数支持

func SaveConfig

func SaveConfig(filename string, config *Config) error

SaveConfig 保存配置到文件

func ScanStruct

func ScanStruct(row *sql.Row, dest interface{}) error

ScanStruct 从 sql.Row 扫描单个结构体

func ScanStructs

func ScanStructs(rows *sql.Rows, dest interface{}) error

ScanStructs 从 sql.Rows 扫描多个结构体

func Timestamp

func Timestamp() time.Time

Timestamp 获取当前时间(用于 created_at/updated_at 字段)

Types

type Action

type Action string

Action 表示 Changeset 的操作类型

const (
	ActionInsert Action = "insert"
	ActionUpdate Action = "update"
	ActionDelete Action = "delete"
)

type Adapter

type Adapter interface {
	// 连接管理
	Connect(ctx context.Context, config *Config) error
	Close() error
	Ping(ctx context.Context) error

	// 事务管理
	Begin(ctx context.Context, opts ...interface{}) (Tx, error)

	// 查询接口 (用于 SELECT)
	Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row

	// 执行接口 (用于 INSERT/UPDATE/DELETE)
	Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)

	// 获取底层连接 (用于 GORM 等高级操作)
	GetRawConn() interface{}

	// 定时任务管理 - 允许数据库通过自己的方式实现后台任务
	// 例如: PostgreSQL 使用触发器 + pg_cron, MySQL 使用 EVENT, 应用层使用 cron 库
	RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error
	UnregisterScheduledTask(ctx context.Context, taskName string) error
	ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

	// QueryBuilder 提供者接口 (v0.4.1) - 中层转义层
	// Adapter 通过此接口提供特定数据库的 QueryConstructor 实现
	GetQueryBuilderProvider() QueryConstructorProvider

	// DatabaseFeatures 声明 (v0.4.3) - 数据库特性声明
	// 返回此 Adapter 支持的数据库特性集合
	GetDatabaseFeatures() *DatabaseFeatures

	// QueryFeatures 声明 (v0.4.4) - 查询特性声明
	// 返回此数据库支持的查询构造特性(JOIN、CTE、窗口函数等)
	GetQueryFeatures() *QueryFeatures
}

Adapter 定义通用的数据库适配器接口 (参考 Ecto 设计) 每个数据库实现都必须满足这个接口

type AdapterFactory

type AdapterFactory interface {
	Name() string
	Create(config *Config) (Adapter, error)
}

AdapterFactory 适配器工厂接口

type AdapterRegistryFile

type AdapterRegistryFile struct {
	Adapters map[string]*Config `yaml:"adapters" json:"adapters"`
}

AdapterRegistryFile 多 Adapter 配置文件结构

type BaseMigration

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

BaseMigration 基础迁移结构,提供通用字段

func NewBaseMigration

func NewBaseMigration(version, description string) *BaseMigration

NewBaseMigration 创建基础迁移

func (*BaseMigration) Description

func (m *BaseMigration) Description() string

Description 返回描述

func (*BaseMigration) Version

func (m *BaseMigration) Version() string

Version 返回版本号

type BaseSchema

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

BaseSchema 基础模式实现

func InferSchema

func InferSchema(v interface{}) (*BaseSchema, error)

InferSchema 从 Go struct 推导 Schema 支持 struct tag: `db:"column_name,primary_key,not_null,unique,index,auto_increment"`

func NewBaseSchema

func NewBaseSchema(tableName string) *BaseSchema

NewBaseSchema 创建基础模式

func (*BaseSchema) AddField

func (s *BaseSchema) AddField(field *Field) *BaseSchema

AddField 添加字段

func (*BaseSchema) Fields

func (s *BaseSchema) Fields() []*Field

Fields 返回所有字段

func (*BaseSchema) GetField

func (s *BaseSchema) GetField(name string) *Field

GetField 获取字段

func (*BaseSchema) PrimaryKeyField

func (s *BaseSchema) PrimaryKeyField() *Field

PrimaryKeyField 获取主键字段

func (*BaseSchema) TableName

func (s *BaseSchema) TableName() string

TableName 返回表名

type Changeset

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

Changeset 代表对数据的变更(参考 Ecto.Changeset)

func FromMap

func FromMap(schema Schema, dataMap map[string]interface{}) *Changeset

FromMap 从 map 创建 Changeset

func NewChangeset

func NewChangeset(schema Schema) *Changeset

NewChangeset 创建新的 Changeset

func (*Changeset) ApplyAction

func (cs *Changeset) ApplyAction(action Action) *Changeset

ApplyAction 根据操作类型应用不同的验证逻辑

func (*Changeset) Cast

func (cs *Changeset) Cast(data map[string]interface{}) *Changeset

Cast 设置字段值(类似 Ecto 的 cast)

func (*Changeset) Changes

func (cs *Changeset) Changes() map[string]interface{}

Changes 获取变更的数据

func (*Changeset) ClearError

func (cs *Changeset) ClearError(fieldName string) *Changeset

ClearError 清除错误

func (*Changeset) Data

func (cs *Changeset) Data() map[string]interface{}

Data 获取所有数据

func (*Changeset) ErrorString

func (cs *Changeset) ErrorString() string

ErrorString 返回格式化的错误字符串

func (*Changeset) Errors

func (cs *Changeset) Errors() map[string][]string

Errors 获取所有错误

func (*Changeset) ForceChanges

func (cs *Changeset) ForceChanges() *Changeset

ForceChanges 强制所有字段为变更状态(用于插入操作)

func (*Changeset) Get

func (cs *Changeset) Get(fieldName string) interface{}

Get 获取字段值

func (*Changeset) GetChange

func (cs *Changeset) GetChange(fieldName string) interface{}

GetChange 获取变更的字段值(便捷方法)

func (*Changeset) GetChanged

func (cs *Changeset) GetChanged(fieldName string) (interface{}, bool)

GetChanged 获取变更的字段值

func (*Changeset) GetChangedFields

func (cs *Changeset) GetChangedFields() []string

GetChangedFields 获取所有被修改的字段名列表

func (*Changeset) GetError

func (cs *Changeset) GetError(fieldName string) []string

GetError 获取字段的错误

func (*Changeset) GetPrevious

func (cs *Changeset) GetPrevious(fieldName string) interface{}

GetPrevious 获取变更前的值

func (*Changeset) HasChanged

func (cs *Changeset) HasChanged(fieldName string) bool

HasChanged 检查字段是否被修改

func (*Changeset) IsValid

func (cs *Changeset) IsValid() bool

IsValid 检查 Changeset 是否有效

func (*Changeset) PutChange

func (cs *Changeset) PutChange(fieldName string, value interface{}) *Changeset

PutChange 手动添加变更

func (*Changeset) ToMap

func (cs *Changeset) ToMap() map[string]interface{}

ToMap 转换为 map(用于数据库操作)

func (*Changeset) Validate

func (cs *Changeset) Validate() *Changeset

Validate 验证 Changeset

func (*Changeset) ValidateChange

func (cs *Changeset) ValidateChange(fieldName string, validator Validator) *Changeset

ValidateChange 验证特定字段的变更

func (*Changeset) ValidateExclusion

func (cs *Changeset) ValidateExclusion(fieldName string, list []interface{}) *Changeset

ValidateExclusion 验证字段值不在指定列表中

func (*Changeset) ValidateFormat

func (cs *Changeset) ValidateFormat(fieldName string, pattern string, message ...string) *Changeset

ValidateFormat 验证字段格式(使用正则表达式)

func (*Changeset) ValidateInclusion

func (cs *Changeset) ValidateInclusion(fieldName string, list []interface{}) *Changeset

ValidateInclusion 验证字段值在指定列表中

func (*Changeset) ValidateLength

func (cs *Changeset) ValidateLength(fieldName string, min, max int) *Changeset

ValidateLength 验证字符串长度

func (*Changeset) ValidateNumber

func (cs *Changeset) ValidateNumber(fieldName string, opts map[string]interface{}) *Changeset

ValidateNumber 验证数字范围

func (*Changeset) ValidateRequired

func (cs *Changeset) ValidateRequired(fields []string) *Changeset

ValidateRequired 验证必填字段

type CompositeCondition

type CompositeCondition struct {
	Operator   string // "and" | "or"
	Conditions []Condition
}

CompositeCondition 复合条件(AND/OR)

func (*CompositeCondition) Translate

func (c *CompositeCondition) Translate(translator ConditionTranslator) (string, []interface{}, error)

func (*CompositeCondition) Type

func (c *CompositeCondition) Type() string

type Condition

type Condition interface {
	// 获取条件类型
	Type() string

	// 将条件转换为 SQL/Cypher/etc
	Translate(translator ConditionTranslator) (string, []interface{}, error)
}

Condition 条件接口 - 中层转义 Adapter 实现此接口将条件转换为数据库特定的形式

func And

func And(conditions ...Condition) Condition

And AND 条件

func Between

func Between(field string, min, max interface{}) Condition

Between BETWEEN 条件

func Eq

func Eq(field string, value interface{}) Condition

Eq 等于条件

func Gt

func Gt(field string, value interface{}) Condition

Gt 大于条件

func Gte

func Gte(field string, value interface{}) Condition

Gte 大于等于条件

func In

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

In IN 条件

func Like

func Like(field string, pattern string) Condition

Like LIKE 条件(模糊匹配)

func Lt

func Lt(field string, value interface{}) Condition

Lt 小于条件

func Lte

func Lte(field string, value interface{}) Condition

Lte 小于等于条件

func Ne

func Ne(field string, value interface{}) Condition

Ne 不等于条件

func Not

func Not(condition Condition) Condition

Not NOT 条件

func Or

func Or(conditions ...Condition) Condition

Or OR 条件

type ConditionBuilder

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

ConditionBuilder 条件构造器 - 流式 API

type ConditionTranslator

type ConditionTranslator interface {
	TranslateCondition(condition Condition) (string, []interface{}, error)
	TranslateComposite(operator string, conditions []Condition) (string, []interface{}, error)
}

ConditionTranslator 条件转义器接口 由每个 Adapter 的 QueryConstructor 实现

type Config

type Config struct {
	// 适配器类型: "sqlite" | "postgres" | "mysql" | "sqlserver"
	Adapter string `json:"adapter" yaml:"adapter"`

	// SQLite 特定配置
	Database string `json:"database" yaml:"database"` // 数据库文件路径或数据库名

	// PostgreSQL/MySQL/SQL Server 通用配置
	Host     string `json:"host" yaml:"host"`
	Port     int    `json:"port" yaml:"port"`
	Username string `json:"username" yaml:"username"`
	Password string `json:"password" yaml:"password"`

	// PostgreSQL 特定配置
	SSLMode string `json:"ssl_mode" yaml:"ssl_mode"`

	// 连接池配置
	Pool *PoolConfig `json:"pool" yaml:"pool"`

	// 其他参数 (可选的适配器特定参数)
	Options map[string]interface{} `json:"options" yaml:"options"`
}

Config 数据库配置结构 (参考 Ecto 的 Repo 配置)

func DefaultConfig

func DefaultConfig(adapterType string) *Config

DefaultConfig 返回默认配置

func GetAdapterConfig

func GetAdapterConfig(name string) (*Config, bool)

GetAdapterConfig 获取已注册的 Adapter 配置

func LoadConfig

func LoadConfig(filename string) (*Config, error)

LoadConfig 从文件加载数据库配置(支持 JSON 和 YAML 格式)

func LoadConfigWithDefaults

func LoadConfigWithDefaults(filename string, defaults *Config) (*Config, error)

LoadConfigWithDefaults 从文件加载配置并应用默认值

func (*Config) Validate

func (c *Config) Validate() error

Validate 验证配置有效性

type ConfigFile

type ConfigFile struct {
	Database *Config `yaml:"database" json:"database"`
}

ConfigFile 配置文件结构 (从 YAML 或 JSON 加载)

type DatabaseFeatures

type DatabaseFeatures struct {
	// ===== 索引和约束 =====
	SupportsCompositeKeys    bool // 复合主键 (所有数据库都支持)
	SupportsCompositeIndexes bool // 复合索引 (所有数据库都支持)
	SupportsPartialIndexes   bool // 部分索引 (WHERE 子句)
	SupportsDeferrable       bool // 延迟约束 (PostgreSQL, SQLite)

	// ===== 自定义类型 =====
	SupportsEnumType      bool // ENUM 类型
	SupportsCompositeType bool // 复合/结构体类型 (PostgreSQL)
	SupportsDomainType    bool // DOMAIN 类型 (PostgreSQL)
	SupportsUDT           bool // User-Defined Types (SQL Server, PostgreSQL)

	// ===== 函数和过程 =====
	SupportsStoredProcedures bool     // 存储过程
	SupportsFunctions        bool     // 自定义函数
	SupportsAggregateFuncs   bool     // 自定义聚合函数
	FunctionLanguages        []string // 支持的函数语言 (如 "plpgsql", "tsql", "sql")

	// ===== 高级查询 =====
	SupportsWindowFunctions bool // 窗口函数 (ROW_NUMBER, RANK, etc.)
	SupportsCTE             bool // 公共表表达式 (WITH)
	SupportsRecursiveCTE    bool // 递归 CTE
	SupportsMaterializedCTE bool // 物化 CTE (PostgreSQL)

	// ===== JSON 支持 =====
	HasNativeJSON     bool // 原生 JSON 类型
	SupportsJSONPath  bool // JSON 路径查询
	SupportsJSONIndex bool // JSON 索引

	// ===== 全文搜索 =====
	SupportsFullTextSearch bool     // 全文搜索
	FullTextLanguages      []string // 支持的语言

	// ===== 其他特性 =====
	SupportsArrays       bool // 数组类型 (PostgreSQL)
	SupportsGenerated    bool // 生成列 (Computed/Generated columns)
	SupportsReturning    bool // RETURNING 子句 (PostgreSQL, SQLite 3.35+)
	SupportsUpsert       bool // UPSERT 操作 (ON CONFLICT / ON DUPLICATE KEY)
	SupportsListenNotify bool // LISTEN/NOTIFY (PostgreSQL)

	// ===== 元信息 =====
	DatabaseName    string // 数据库名称
	DatabaseVersion string // 版本信息
	Description     string // 特性描述
}

DatabaseFeatures 数据库特性声明 每个 Adapter 通过此结构声明其支持的数据库特性

func NewMongoDatabaseFeatures

func NewMongoDatabaseFeatures() *DatabaseFeatures

NewMongoDatabaseFeatures MongoDB 数据库特性(最小占位实现)

func (*DatabaseFeatures) GetFeaturesByCategory

func (f *DatabaseFeatures) GetFeaturesByCategory(category FeatureCategory) []string

GetFeaturesByCategory 按分类获取支持的特性列表

func (*DatabaseFeatures) HasFeature

func (f *DatabaseFeatures) HasFeature(feature string) bool

HasFeature 检查是否支持特定特性

type DefaultSQLDialect

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

DefaultSQLDialect 默认 SQL 方言(MySQL 兼容)

func (*DefaultSQLDialect) GenerateLimitOffset

func (d *DefaultSQLDialect) GenerateLimitOffset(limit *int, offset *int) string

func (*DefaultSQLDialect) GetPlaceholder

func (d *DefaultSQLDialect) GetPlaceholder(index int) string

func (*DefaultSQLDialect) Name

func (d *DefaultSQLDialect) Name() string

func (*DefaultSQLDialect) QuoteIdentifier

func (d *DefaultSQLDialect) QuoteIdentifier(name string) string

func (*DefaultSQLDialect) QuoteValue

func (d *DefaultSQLDialect) QuoteValue(value interface{}) string

func (*DefaultSQLDialect) TranslateCondition

func (d *DefaultSQLDialect) TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)

type DefaultSQLQueryConstructorProvider

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

DefaultSQLQueryConstructorProvider 默认 SQL 查询构造器提供者

func NewDefaultSQLQueryConstructorProvider

func NewDefaultSQLQueryConstructorProvider(dialect SQLDialect) *DefaultSQLQueryConstructorProvider

NewDefaultSQLQueryConstructorProvider 创建默认 SQL 查询构造器提供者

func (*DefaultSQLQueryConstructorProvider) GetCapabilities

GetCapabilities 获取查询能力声明

func (*DefaultSQLQueryConstructorProvider) NewQueryConstructor

func (p *DefaultSQLQueryConstructorProvider) NewQueryConstructor(schema Schema) QueryConstructor

NewQueryConstructor 创建新的查询构造器

type DefaultSQLTranslator

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

DefaultSQLTranslator 默认 SQL 转义器

func (*DefaultSQLTranslator) TranslateComposite

func (t *DefaultSQLTranslator) TranslateComposite(operator string, conditions []Condition) (string, []interface{}, error)

TranslateComposite 转义复合条件(AND/OR)

func (*DefaultSQLTranslator) TranslateCondition

func (t *DefaultSQLTranslator) TranslateCondition(condition Condition) (string, []interface{}, error)

TranslateCondition 转义单个条件

type DynamicTableConfig

type DynamicTableConfig struct {
	// 表名称
	TableName string

	// 表描述
	Description string

	// 表字段定义
	Fields []*DynamicTableField

	// 触发条件:关联的父表(当父表插入或更新时触发建表)
	ParentTable string

	// 触发条件:检查父表的字段值
	// 例如:type = 'custom' 时才创建此动态表
	TriggerCondition string

	// 表创建策略:auto 自动创建,manual 手动创建
	Strategy string // "auto" or "manual"

	// 额外参数(适配器特定)
	Options map[string]interface{}
}

DynamicTableConfig 动态表配置 定义触发条件和表的创建规则

func NewDynamicTableConfig

func NewDynamicTableConfig(tableName string) *DynamicTableConfig

NewDynamicTableConfig 创建新的动态表配置

func (*DynamicTableConfig) AddField

AddField 添加字段到动态表配置

func (*DynamicTableConfig) WithDescription

func (c *DynamicTableConfig) WithDescription(desc string) *DynamicTableConfig

WithDescription 设置描述

func (*DynamicTableConfig) WithOption

func (c *DynamicTableConfig) WithOption(key string, value interface{}) *DynamicTableConfig

WithOption 设置选项

func (*DynamicTableConfig) WithParentTable

func (c *DynamicTableConfig) WithParentTable(parentTable, triggerCondition string) *DynamicTableConfig

WithParentTable 设置父表(用于自动触发)

func (*DynamicTableConfig) WithStrategy

func (c *DynamicTableConfig) WithStrategy(strategy string) *DynamicTableConfig

WithStrategy 设置创建策略

type DynamicTableField

type DynamicTableField struct {
	Name        string
	Type        FieldType
	Primary     bool
	Autoinc     bool
	Null        bool
	Default     interface{}
	Index       bool
	Unique      bool
	Description string
}

DynamicTableField 动态表的字段定义

func NewDynamicTableField

func NewDynamicTableField(name string, fieldType FieldType) *DynamicTableField

NewDynamicTableField 创建新的字段

func (*DynamicTableField) AsNotNull

func (f *DynamicTableField) AsNotNull() *DynamicTableField

AsNotNull 设置为 NOT NULL

func (*DynamicTableField) AsPrimaryKey

func (f *DynamicTableField) AsPrimaryKey() *DynamicTableField

AsPrimaryKey 设置为主键

func (*DynamicTableField) WithAutoinc

func (f *DynamicTableField) WithAutoinc() *DynamicTableField

WithAutoinc 启用自增

func (*DynamicTableField) WithDefault

func (f *DynamicTableField) WithDefault(value interface{}) *DynamicTableField

WithDefault 设置默认值

func (*DynamicTableField) WithDescription

func (f *DynamicTableField) WithDescription(desc string) *DynamicTableField

WithDescription 设置字段描述

func (*DynamicTableField) WithIndex

func (f *DynamicTableField) WithIndex() *DynamicTableField

WithIndex 添加索引

func (*DynamicTableField) WithUnique

func (f *DynamicTableField) WithUnique() *DynamicTableField

WithUnique 添加唯一约束

type DynamicTableHook

type DynamicTableHook interface {
	// 注册动态表配置
	RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error

	// 注销动态表配置
	UnregisterDynamicTable(ctx context.Context, configName string) error

	// 列出所有已注册的动态表配置
	ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)

	// 获取特定的动态表配置
	GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)

	// 手动触发动态表创建(当 Strategy = manual 时)
	CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)

	// 获取已创建的动态表列表
	ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)
}

DynamicTableHook 动态表钩子接口 实现者需要在适配器中实现此接口

type DynamicTableRegistry

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

DynamicTableRegistry 动态表配置注册表

func NewDynamicTableRegistry

func NewDynamicTableRegistry() *DynamicTableRegistry

NewDynamicTableRegistry 创建动态表注册表

func (*DynamicTableRegistry) Get

Get 获取配置

func (*DynamicTableRegistry) List

List 列出所有配置

func (*DynamicTableRegistry) Register

func (r *DynamicTableRegistry) Register(name string, config *DynamicTableConfig) error

Register 注册配置

func (*DynamicTableRegistry) Unregister

func (r *DynamicTableRegistry) Unregister(name string) error

Unregister 注销配置

type EmailValidator

type EmailValidator struct{}

EmailValidator 邮箱格式验证器

func (*EmailValidator) Validate

func (v *EmailValidator) Validate(value interface{}) error

type FeatureCategory

type FeatureCategory string

FeatureCategory 特性分类

const (
	CategoryIndexing  FeatureCategory = "indexing"  // 索引和约束
	CategoryTypes     FeatureCategory = "types"     // 自定义类型
	CategoryFunctions FeatureCategory = "functions" // 函数和存储过程
	CategoryAdvanced  FeatureCategory = "advanced"  // 高级查询
	CategoryJSON      FeatureCategory = "json"      // JSON 支持
	CategoryFullText  FeatureCategory = "full_text" // 全文搜索
	CategoryOther     FeatureCategory = "other"     // 其他特性
)

type FeatureComparison

type FeatureComparison struct {
	Database1      string
	Database2      string
	CommonFeatures []string // 共同支持的特性
	OnlyInFirst    []string // 仅第一个数据库支持
	OnlyInSecond   []string // 仅第二个数据库支持
}

FeatureComparison 特性比较结果

func CompareFeatures

func CompareFeatures(f1, f2 *DatabaseFeatures) *FeatureComparison

CompareFeatures 比较两个数据库的特性差异

type FeatureFallback

type FeatureFallback string

FeatureFallback 特性降级策略

const (
	FallbackNone             FeatureFallback = "none"              // 不支持,返回错误
	FallbackCheckConstraint  FeatureFallback = "check_constraint"  // 使用 CHECK 约束
	FallbackDynamicTable     FeatureFallback = "dynamic_table"     // 使用动态类型表
	FallbackApplicationLayer FeatureFallback = "application_layer" // 应用层处理
)

type FeatureSupport

type FeatureSupport struct {
	Supported  bool   // 是否支持
	MinVersion string // 最低支持版本(可选)
	Notes      string // 备注说明(可选)
}

FeatureSupport 特性支持建模(支持版本与备注)

type Field

type Field struct {
	Name         string
	Type         FieldType
	Default      interface{}
	Null         bool
	Primary      bool
	Autoinc      bool
	Index        bool
	Unique       bool
	Validators   []Validator
	Transformers []Transformer
}

Field 定义模式中的字段

type FieldBuilder

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

FieldBuilder 字段构造器

func NewField

func NewField(name string, fieldType FieldType) *FieldBuilder

NewField 创建新字段

func (*FieldBuilder) Build

func (fb *FieldBuilder) Build() *Field

Build 构建字段

func (*FieldBuilder) Default

func (fb *FieldBuilder) Default(value interface{}) *FieldBuilder

Default 设置默认值

func (*FieldBuilder) Index

func (fb *FieldBuilder) Index() *FieldBuilder

Index 添加索引

func (*FieldBuilder) Null

func (fb *FieldBuilder) Null(allow bool) *FieldBuilder

Null 设置是否允许为空

func (*FieldBuilder) PrimaryKey

func (fb *FieldBuilder) PrimaryKey() *FieldBuilder

PrimaryKey 标记为主键

func (*FieldBuilder) Transform

func (fb *FieldBuilder) Transform(transformer Transformer) *FieldBuilder

Transform 添加转换器

func (*FieldBuilder) Unique

func (fb *FieldBuilder) Unique() *FieldBuilder

Unique 添加唯一约束

func (*FieldBuilder) Validate

func (fb *FieldBuilder) Validate(validator Validator) *FieldBuilder

Validate 添加验证器

type FieldType

type FieldType string

FieldType 字段类型定义

const (
	TypeString  FieldType = "string"
	TypeInteger FieldType = "integer"
	TypeFloat   FieldType = "float"
	TypeBoolean FieldType = "boolean"
	TypeTime    FieldType = "time"
	TypeBinary  FieldType = "binary"
	TypeDecimal FieldType = "decimal"
	TypeMap     FieldType = "map"
	TypeArray   FieldType = "array"
	TypeJSON    FieldType = "json"
)

type ForeignKeyAction

type ForeignKeyAction string
const (
	ActionRestrict ForeignKeyAction = "RESTRICT"
	ActionCascade  ForeignKeyAction = "CASCADE"
	ActionSetNull  ForeignKeyAction = "SET NULL"
	ActionNoAction ForeignKeyAction = "NO ACTION"
)

type ForeignKeyDef

type ForeignKeyDef struct {
	// 源表的列
	FromColumn string

	// 目标表的列
	ToColumn string

	// 级联删除
	OnDelete ForeignKeyAction
	OnUpdate ForeignKeyAction
}

ForeignKeyDef 外键定义

type JoinTableDef

type JoinTableDef struct {
	// 关联表名称
	TableName string

	// 源表外键列和目标表外键列
	FromForeignKey string
	ToForeignKey   string

	// 额外的列(如时间戳等)
	ExtraColumns []*Field
}

JoinTableDef 关联表定义(多对多)

type LengthValidator

type LengthValidator struct {
	Min int
	Max int
}

LengthValidator 长度验证器

func (*LengthValidator) Validate

func (v *LengthValidator) Validate(value interface{}) error

type LowercaseTransformer

type LowercaseTransformer struct{}

LowercaseTransformer 小写转换器

func (*LowercaseTransformer) Transform

func (t *LowercaseTransformer) Transform(value interface{}) (interface{}, error)

type MaxLengthValidator

type MaxLengthValidator struct {
	Length int
}

MaxLengthValidator 最大长度验证器

func (*MaxLengthValidator) Validate

func (v *MaxLengthValidator) Validate(value interface{}) error

type Migration

type Migration struct {
	// 版本号 (时间戳格式): 20260131100000
	Version string

	// 描述
	Description string

	// 迁移的 SQL 语句
	UpSQL []string

	// 回滚的 SQL 语句
	DownSQL []string
}

Migration 表示一个数据库迁移

type MigrationInterface

type MigrationInterface interface {
	// Up 执行迁移
	Up(ctx context.Context, repo *Repository) error

	// Down 回滚迁移
	Down(ctx context.Context, repo *Repository) error

	// Version 返回迁移版本号(通常是时间戳)
	Version() string

	// Description 返回迁移描述
	Description() string
}

Migration 接口 - 每个迁移文件都需要实现这个接口

type MigrationLog

type MigrationLog struct {
	ID         int64
	Version    string
	RunOn      time.Time
	ExecutedAt time.Time
}

MigrationLog 迁移日志记录

type MigrationRunner

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

MigrationRunner 迁移运行器

func NewMigrationRunner

func NewMigrationRunner(repo *Repository) *MigrationRunner

NewMigrationRunner 创建迁移运行器

func (*MigrationRunner) Down

func (r *MigrationRunner) Down(ctx context.Context) error

Down 回滚最后一个迁移

func (*MigrationRunner) Register

func (r *MigrationRunner) Register(migration MigrationInterface)

Register 注册迁移

func (*MigrationRunner) Status

func (r *MigrationRunner) Status(ctx context.Context) ([]MigrationStatus, error)

Status 显示迁移状态

func (*MigrationRunner) Up

func (r *MigrationRunner) Up(ctx context.Context) error

Up 执行所有待执行的迁移

type MigrationStatus

type MigrationStatus struct {
	Version     string
	Description string
	Applied     bool
	AppliedAt   time.Time
}

MigrationStatus 迁移状态

type Migrator

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

Migrator 迁移器

func NewMigrator

func NewMigrator(repo *Repository) *Migrator

NewMigrator 创建新的迁移器

func (*Migrator) Down

func (m *Migrator) Down(ctx context.Context) error

Down 回滚最后一个迁移

func (*Migrator) Register

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

Register 注册迁移

func (*Migrator) Status

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

Status 显示迁移状态

func (*Migrator) Up

func (m *Migrator) Up(ctx context.Context) error

Up 执行所有待执行的迁移

type MinLengthValidator

type MinLengthValidator struct {
	Length int
}

MinLengthValidator 最小长度验证器

func (*MinLengthValidator) Validate

func (v *MinLengthValidator) Validate(value interface{}) error

type MongoAdapter

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

MongoAdapter MongoDB 适配器(最小可用版本:连接/健康检查)

func NewMongoAdapter

func NewMongoAdapter(config *Config) (*MongoAdapter, error)

NewMongoAdapter 创建 MongoAdapter(不建立连接)

func (*MongoAdapter) Begin

func (a *MongoAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)

Begin MongoDB 不支持 SQL 事务接口

func (*MongoAdapter) Close

func (a *MongoAdapter) Close() error

Close 关闭连接

func (*MongoAdapter) Connect

func (a *MongoAdapter) Connect(ctx context.Context, config *Config) error

Connect 建立 MongoDB 连接

func (*MongoAdapter) Exec

func (a *MongoAdapter) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)

Exec MongoDB 不支持 SQL Exec

func (*MongoAdapter) GetDatabaseFeatures

func (a *MongoAdapter) GetDatabaseFeatures() *DatabaseFeatures

GetDatabaseFeatures MongoDB 特性声明(最小实现)

func (*MongoAdapter) GetQueryBuilderProvider

func (a *MongoAdapter) GetQueryBuilderProvider() QueryConstructorProvider

GetQueryBuilderProvider MongoDB 不提供 SQL Query Builder

func (*MongoAdapter) GetQueryFeatures

func (a *MongoAdapter) GetQueryFeatures() *QueryFeatures

GetQueryFeatures MongoDB 查询特性声明(最小实现)

func (*MongoAdapter) GetRawConn

func (a *MongoAdapter) GetRawConn() interface{}

GetRawConn 返回 mongo.Client

func (*MongoAdapter) ListScheduledTasks

func (a *MongoAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

ListScheduledTasks MongoDB 暂不支持定时任务

func (*MongoAdapter) Ping

func (a *MongoAdapter) Ping(ctx context.Context) error

Ping 测试连接

func (*MongoAdapter) Query

func (a *MongoAdapter) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)

Query MongoDB 不支持 SQL Query

func (*MongoAdapter) QueryRow

func (a *MongoAdapter) QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row

QueryRow MongoDB 不支持 SQL QueryRow

func (*MongoAdapter) RegisterScheduledTask

func (a *MongoAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error

RegisterScheduledTask MongoDB 暂不支持定时任务

func (*MongoAdapter) UnregisterScheduledTask

func (a *MongoAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error

UnregisterScheduledTask MongoDB 暂不支持定时任务

type MongoFactory

type MongoFactory struct{}

MongoFactory AdapterFactory 实现

func (*MongoFactory) Create

func (f *MongoFactory) Create(config *Config) (Adapter, error)

func (*MongoFactory) Name

func (f *MongoFactory) Name() string

type MySQLAdapter

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

MySQLAdapter MySQL 数据库适配器

func (*MySQLAdapter) Begin

func (a *MySQLAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)

Begin 开始事务

func (*MySQLAdapter) Close

func (a *MySQLAdapter) Close() error

Close 关闭数据库连接

func (*MySQLAdapter) Connect

func (a *MySQLAdapter) Connect(ctx context.Context, config *Config) error

Connect 连接到 MySQL 数据库

func (*MySQLAdapter) Exec

func (a *MySQLAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 执行操作 (INSERT/UPDATE/DELETE)

func (*MySQLAdapter) GetDatabaseFeatures

func (a *MySQLAdapter) GetDatabaseFeatures() *DatabaseFeatures

GetDatabaseFeatures 返回 MySQL 数据库特性

func (*MySQLAdapter) GetGormDB

func (a *MySQLAdapter) GetGormDB() *gorm.DB

GetGormDB 获取GORM实例(用于直接访问GORM)

func (*MySQLAdapter) GetQueryBuilderProvider

func (a *MySQLAdapter) GetQueryBuilderProvider() QueryConstructorProvider

GetQueryBuilderProvider 返回查询构造器提供者

func (*MySQLAdapter) GetQueryFeatures

func (a *MySQLAdapter) GetQueryFeatures() *QueryFeatures

GetQueryFeatures 返回 MySQL 的查询特性

func (*MySQLAdapter) GetRawConn

func (a *MySQLAdapter) GetRawConn() interface{}

GetRawConn 获取底层连接 (返回 *gorm.DB)

func (*MySQLAdapter) ListScheduledTasks

func (a *MySQLAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

ListScheduledTasks MySQL 适配器暂不支持

func (*MySQLAdapter) Ping

func (a *MySQLAdapter) Ping(ctx context.Context) error

Ping 测试数据库连接

func (*MySQLAdapter) Query

func (a *MySQLAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 执行查询 (返回多行)

func (*MySQLAdapter) QueryRow

func (a *MySQLAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 执行查询 (返回单行)

func (*MySQLAdapter) RegisterScheduledTask

func (a *MySQLAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error

RegisterScheduledTask MySQL 适配器暂不支持通过 EVENT 方式实现定时任务 建议在应用层使用 cron 库处理定时任务

func (*MySQLAdapter) UnregisterScheduledTask

func (a *MySQLAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error

UnregisterScheduledTask MySQL 适配器暂不支持

type MySQLDialect

type MySQLDialect struct {
	DefaultSQLDialect
}

MySQL 方言

func NewMySQLDialect

func NewMySQLDialect() *MySQLDialect

type MySQLDynamicTableHook

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

MySQLDynamicTableHook MySQL 动态表钩子实现 使用 GORM 的 hook 机制实现基于触发的动态建表

func NewMySQLDynamicTableHook

func NewMySQLDynamicTableHook(adapter *MySQLAdapter) *MySQLDynamicTableHook

NewMySQLDynamicTableHook 创建 MySQL 动态表钩子

func (*MySQLDynamicTableHook) CreateDynamicTable

func (h *MySQLDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)

CreateDynamicTable 手动创建动态表 返回实际创建的表名称

func (*MySQLDynamicTableHook) GetDynamicTableConfig

func (h *MySQLDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)

GetDynamicTableConfig 获取特定的动态表配置

func (*MySQLDynamicTableHook) ListCreatedDynamicTables

func (h *MySQLDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)

ListCreatedDynamicTables 获取已创建的动态表列表

func (*MySQLDynamicTableHook) ListDynamicTableConfigs

func (h *MySQLDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)

ListDynamicTableConfigs 列出所有已注册的动态表配置

func (*MySQLDynamicTableHook) RegisterDynamicTable

func (h *MySQLDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error

RegisterDynamicTable 注册动态表配置 对于自动策略,在 GORM hook 中注册事件处理

func (*MySQLDynamicTableHook) UnregisterDynamicTable

func (h *MySQLDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error

UnregisterDynamicTable 注销动态表配置

type MySQLFactory

type MySQLFactory struct{}

MySQLFactory MySQL 适配器工厂

func (*MySQLFactory) Create

func (f *MySQLFactory) Create(config *Config) (Adapter, error)

Create 创建 MySQL 适配器

func (*MySQLFactory) Name

func (f *MySQLFactory) Name() string

Name 返回适配器名称

type MySQLTx

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

MySQLTx MySQL 事务实现

func (*MySQLTx) Commit

func (t *MySQLTx) Commit(ctx context.Context) error

Commit 提交事务

func (*MySQLTx) Exec

func (t *MySQLTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 在事务中执行

func (*MySQLTx) Query

func (t *MySQLTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 在事务中查询

func (*MySQLTx) QueryRow

func (t *MySQLTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 在事务中查询单行

func (*MySQLTx) Rollback

func (t *MySQLTx) Rollback(ctx context.Context) error

Rollback 回滚事务

type NotCondition

type NotCondition struct {
	Condition Condition
}

NotCondition 非条件

func (*NotCondition) Translate

func (c *NotCondition) Translate(translator ConditionTranslator) (string, []interface{}, error)

func (*NotCondition) Type

func (c *NotCondition) Type() string

type OrderBy

type OrderBy struct {
	Field     string
	Direction string // "ASC" | "DESC"
}

OrderBy 排序条件

type PatternValidator

type PatternValidator struct {
	Pattern string
}

PatternValidator 正则验证器

func (*PatternValidator) Validate

func (v *PatternValidator) Validate(value interface{}) error

type PoolConfig

type PoolConfig struct {
	MaxConnections int `json:"max_connections" yaml:"max_connections"`
	MinConnections int `json:"min_connections" yaml:"min_connections"`
	ConnectTimeout int `json:"connect_timeout" yaml:"connect_timeout"` // 秒
	IdleTimeout    int `json:"idle_timeout" yaml:"idle_timeout"`       // 秒
	MaxLifetime    int `json:"max_lifetime" yaml:"max_lifetime"`       // 秒
}

PoolConfig 连接池配置 (参考 Ecto 的设计)

type PostgreSQLAdapter

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

PostgreSQLAdapter PostgreSQL 数据库适配器

func (*PostgreSQLAdapter) Begin

func (a *PostgreSQLAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)

Begin 开始事务

func (*PostgreSQLAdapter) Close

func (a *PostgreSQLAdapter) Close() error

Close 关闭数据库连接

func (*PostgreSQLAdapter) Connect

func (a *PostgreSQLAdapter) Connect(ctx context.Context, config *Config) error

Connect 连接到 PostgreSQL 数据库

func (*PostgreSQLAdapter) Exec

func (a *PostgreSQLAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 执行操作 (INSERT/UPDATE/DELETE)

func (*PostgreSQLAdapter) GetDatabaseFeatures

func (a *PostgreSQLAdapter) GetDatabaseFeatures() *DatabaseFeatures

GetDatabaseFeatures 返回 PostgreSQL 数据库特性

func (*PostgreSQLAdapter) GetGormDB

func (a *PostgreSQLAdapter) GetGormDB() *gorm.DB

GetGormDB 获取GORM实例(用于直接访问GORM)

func (*PostgreSQLAdapter) GetQueryBuilderProvider

func (a *PostgreSQLAdapter) GetQueryBuilderProvider() QueryConstructorProvider

GetQueryBuilderProvider 返回查询构造器提供者

func (*PostgreSQLAdapter) GetQueryFeatures

func (a *PostgreSQLAdapter) GetQueryFeatures() *QueryFeatures

GetQueryFeatures 返回 PostgreSQL 的查询特性

func (*PostgreSQLAdapter) GetRawConn

func (a *PostgreSQLAdapter) GetRawConn() interface{}

GetRawConn 获取底层连接 (返回 *gorm.DB)

func (*PostgreSQLAdapter) ListScheduledTasks

func (a *PostgreSQLAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

ListScheduledTasks 列出所有已注册的定时任务 PostgreSQL 版本返回空列表,因为存储过程的管理比较复杂

func (*PostgreSQLAdapter) Ping

func (a *PostgreSQLAdapter) Ping(ctx context.Context) error

Ping 测试数据库连接

func (*PostgreSQLAdapter) Query

func (a *PostgreSQLAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 执行查询 (返回多行)

func (*PostgreSQLAdapter) QueryRow

func (a *PostgreSQLAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 执行查询 (返回单行)

func (*PostgreSQLAdapter) RegisterScheduledTask

func (a *PostgreSQLAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error

RegisterScheduledTask 在 PostgreSQL 中注册定时任务 使用 PostgreSQL 的触发器 + 函数来实现按月自动创建表的功能

func (*PostgreSQLAdapter) UnregisterScheduledTask

func (a *PostgreSQLAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error

UnregisterScheduledTask 注销定时任务

type PostgreSQLDialect

type PostgreSQLDialect struct {
	DefaultSQLDialect
	// contains filtered or unexported fields
}

PostgreSQL 方言

func NewPostgreSQLDialect

func NewPostgreSQLDialect() *PostgreSQLDialect

func (*PostgreSQLDialect) GetPlaceholder

func (d *PostgreSQLDialect) GetPlaceholder(index int) string

func (*PostgreSQLDialect) QuoteIdentifier

func (d *PostgreSQLDialect) QuoteIdentifier(name string) string

type PostgreSQLDynamicTableHook

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

PostgreSQLDynamicTableHook PostgreSQL 动态表钩子实现 使用触发器和自定义函数实现自动化动态建表

func NewPostgreSQLDynamicTableHook

func NewPostgreSQLDynamicTableHook(adapter *PostgreSQLAdapter) *PostgreSQLDynamicTableHook

NewPostgreSQLDynamicTableHook 创建 PostgreSQL 动态表钩子

func (*PostgreSQLDynamicTableHook) CreateDynamicTable

func (h *PostgreSQLDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)

CreateDynamicTable 手动创建动态表 返回实际创建的表名称

func (*PostgreSQLDynamicTableHook) GetDynamicTableConfig

func (h *PostgreSQLDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)

GetDynamicTableConfig 获取特定的动态表配置

func (*PostgreSQLDynamicTableHook) ListCreatedDynamicTables

func (h *PostgreSQLDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)

ListCreatedDynamicTables 获取已创建的动态表列表

func (*PostgreSQLDynamicTableHook) ListDynamicTableConfigs

func (h *PostgreSQLDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)

ListDynamicTableConfigs 列出所有已注册的动态表配置

func (*PostgreSQLDynamicTableHook) RegisterDynamicTable

func (h *PostgreSQLDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error

RegisterDynamicTable 注册动态表配置 对于自动策略,创建触发器和存储函数来自动化建表

func (*PostgreSQLDynamicTableHook) UnregisterDynamicTable

func (h *PostgreSQLDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error

UnregisterDynamicTable 注销动态表配置

type PostgreSQLFactory

type PostgreSQLFactory struct{}

PostgreSQLFactory PostgreSQL 适配器工厂

func (*PostgreSQLFactory) Create

func (f *PostgreSQLFactory) Create(config *Config) (Adapter, error)

Create 创建 PostgreSQL 适配器

func (*PostgreSQLFactory) Name

func (f *PostgreSQLFactory) Name() string

Name 返回适配器名称

type PostgreSQLTx

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

PostgreSQLTx PostgreSQL 事务实现

func (*PostgreSQLTx) Commit

func (t *PostgreSQLTx) Commit(ctx context.Context) error

Commit 提交事务

func (*PostgreSQLTx) Exec

func (t *PostgreSQLTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 在事务中执行

func (*PostgreSQLTx) Query

func (t *PostgreSQLTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 在事务中查询

func (*PostgreSQLTx) QueryRow

func (t *PostgreSQLTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 在事务中查询单行

func (*PostgreSQLTx) Rollback

func (t *PostgreSQLTx) Rollback(ctx context.Context) error

Rollback 回滚事务

type QueryBuilder

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

QueryBuilder 查询构建器 (使用 Changeset 进行数据操作)

func NewQueryBuilder

func NewQueryBuilder(schema Schema, repo *Repository) *QueryBuilder

NewQueryBuilder 创建查询构建器

func (*QueryBuilder) Delete

func (qb *QueryBuilder) Delete(whereClause string, whereArgs ...interface{}) (sql.Result, error)

Delete 删除数据

func (*QueryBuilder) DeleteByID

func (qb *QueryBuilder) DeleteByID(id interface{}) (sql.Result, error)

DeleteByID 按 ID 删除数据

func (*QueryBuilder) Insert

func (qb *QueryBuilder) Insert(cs *Changeset) (sql.Result, error)

Insert 插入数据

func (*QueryBuilder) Query

func (qb *QueryBuilder) Query() *QueryChain

Query 开始链式查询

func (*QueryBuilder) Select

func (qb *QueryBuilder) Select(columns string, whereClause string, whereArgs ...interface{}) (*sql.Rows, error)

Select 查询数据

func (*QueryBuilder) SelectAll

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

SelectAll 查询所有数据

func (*QueryBuilder) SelectByID

func (qb *QueryBuilder) SelectByID(id interface{}) (*sql.Row, error)

SelectByID 按 ID 查询单条数据

func (*QueryBuilder) SelectCount

func (qb *QueryBuilder) SelectCount(whereClause string, whereArgs ...interface{}) (int64, error)

SelectCount 查询数据总数

func (*QueryBuilder) SelectOne

func (qb *QueryBuilder) SelectOne(whereClause string, whereArgs ...interface{}) (*sql.Row, error)

SelectOne 查询单条数据

func (*QueryBuilder) SoftDelete

func (qb *QueryBuilder) SoftDelete(whereClause string, whereArgs ...interface{}) (sql.Result, error)

SoftDelete 软删除数据 (仅适用于有 deleted_at 字段的表)

func (*QueryBuilder) SoftDeleteByID

func (qb *QueryBuilder) SoftDeleteByID(id interface{}) (sql.Result, error)

SoftDeleteByID 按 ID 软删除数据

func (*QueryBuilder) Transaction

func (qb *QueryBuilder) Transaction(fn func(*QueryBuilder) error) error

Transaction 事务操作

func (*QueryBuilder) Update

func (qb *QueryBuilder) Update(cs *Changeset, whereClause string, whereArgs ...interface{}) (sql.Result, error)

Update 更新数据

func (*QueryBuilder) UpdateByID

func (qb *QueryBuilder) UpdateByID(id interface{}, cs *Changeset) (sql.Result, error)

UpdateByID 按 ID 更新数据

func (*QueryBuilder) WithContext

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

WithContext 设置上下文

type QueryBuilderCapabilities

type QueryBuilderCapabilities struct {
	// 支持的条件操作
	SupportsEq      bool
	SupportsNe      bool
	SupportsGt      bool
	SupportsLt      bool
	SupportsGte     bool
	SupportsLte     bool
	SupportsIn      bool
	SupportsBetween bool
	SupportsLike    bool
	SupportsAnd     bool
	SupportsOr      bool
	SupportsNot     bool

	// 支持的查询特性
	SupportsSelect   bool // 字段选择
	SupportsOrderBy  bool // 排序
	SupportsLimit    bool // LIMIT
	SupportsOffset   bool // OFFSET
	SupportsJoin     bool // JOIN(关系查询)
	SupportsSubquery bool // 子查询

	// 优化特性
	SupportsQueryPlan bool // 查询计划分析
	SupportsIndex     bool // 索引提示

	// 原生查询支持
	SupportsNativeQuery bool   // 是否支持原生查询(如 Cypher)
	NativeQueryLang     string // 原生查询语言名称(如 "cypher")

	// 其他标记
	Description string // 此 Adapter 的简要描述
}

QueryBuilderCapabilities 查询构造器能力声明 声明此 Adapter 的 QueryBuilder 支持哪些操作和优化

func DefaultQueryBuilderCapabilities

func DefaultQueryBuilderCapabilities() *QueryBuilderCapabilities

DefaultQueryBuilderCapabilities 返回默认的查询能力(SQL 兼容)

type QueryChain

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

QueryChain 链式查询构建器

func (*QueryChain) All

func (qc *QueryChain) All() (*sql.Rows, error)

All 查询所有

func (*QueryChain) Count

func (qc *QueryChain) Count() (int64, error)

Count 统计数量

func (*QueryChain) First

func (qc *QueryChain) First() (*sql.Row, error)

First 查询第一条

func (*QueryChain) Limit

func (qc *QueryChain) Limit(limit int) *QueryChain

Limit 设置 LIMIT

func (*QueryChain) Offset

func (qc *QueryChain) Offset(offset int) *QueryChain

Offset 设置 OFFSET

func (*QueryChain) OrderBy

func (qc *QueryChain) OrderBy(orderBy string) *QueryChain

OrderBy 设置排序

func (*QueryChain) Where

func (qc *QueryChain) Where(condition string, args ...interface{}) *QueryChain

Where 添加 WHERE 条件

type QueryConstructor

type QueryConstructor interface {
	// 条件查询
	Where(condition Condition) QueryConstructor

	// 多条件 AND 组合
	WhereAll(conditions ...Condition) QueryConstructor

	// 多条件 OR 组合
	WhereAny(conditions ...Condition) QueryConstructor

	// 字段选择
	Select(fields ...string) QueryConstructor

	// 排序
	OrderBy(field string, direction string) QueryConstructor // direction: "ASC" | "DESC"

	// 分页
	Limit(count int) QueryConstructor
	Offset(count int) QueryConstructor

	// 构建查询
	Build(ctx context.Context) (string, []interface{}, error)

	// 获取底层查询构造器(用于 Adapter 特定优化)
	GetNativeBuilder() interface{}
}

QueryConstructor 查询构造器接口 - 顶层 API 用户通过此接口构建查询,具体实现由适配器提供

type QueryConstructorProvider

type QueryConstructorProvider interface {
	// 创建新的查询构造器
	NewQueryConstructor(schema Schema) QueryConstructor

	// 获取此 Adapter 的查询能力声明
	GetCapabilities() *QueryBuilderCapabilities
}

QueryConstructorProvider 查询构造器提供者接口 - 中层转义层 每个 Adapter 实现此接口,提供数据库特定的 QueryConstructor

type QueryFallbackStrategy

type QueryFallbackStrategy string

QueryFallbackStrategy 查询特性不支持时的降级策略

const (
	// 不支持,无替代方案
	QueryFallbackNone QueryFallbackStrategy = "none"
	// 在应用层处理(客户端过滤/排序等)
	QueryFallbackApplicationLayer QueryFallbackStrategy = "application_layer"
	// 使用替代语法(例如 SQL Server vs PostgreSQL)
	QueryFallbackAlternativeSyntax QueryFallbackStrategy = "alternative_syntax"
	// 分解为多个简单查询
	QueryFallbackMultiQuery QueryFallbackStrategy = "multi_query"
	// 使用临时表
	QueryFallbackTemporaryTable QueryFallbackStrategy = "temporary_table"
)

type QueryFeature

type QueryFeature struct {
	Name        string                // 特性名称(如 "IN_RANGE_QUERY")
	Supported   bool                  // 是否支持
	Fallback    QueryFallbackStrategy // 不支持时的降级策略
	Notes       string                // 备注说明
	SQLExamples map[string]string     // 各数据库的 SQL 示例 (数据库名 => SQL)
}

QueryFeature 单个查询特性描述

type QueryFeatureCategory

type QueryFeatureCategory string

QueryFeatureCategory 查询特性分类

const (
	// 基础查询操作
	QueryCategoryBasicOps QueryFeatureCategory = "basic_operations"
	// JOIN 操作
	QueryCategoryJoinOps QueryFeatureCategory = "join_operations"
	// 高级查询特性
	QueryCategoryAdvancedQueries QueryFeatureCategory = "advanced_queries"
	// 聚合和分析
	QueryCategoryAggregation QueryFeatureCategory = "aggregation"
	// 文本搜索
	QueryCategoryTextSearch QueryFeatureCategory = "text_search"
	// JSON 相关操作
	QueryCategoryJSON QueryFeatureCategory = "json_operations"
)

type QueryFeatures

type QueryFeatures struct {
	// 基础查询特性
	SupportsIN       bool // IN (value1, value2, ...) 范围查询
	SupportsNotIN    bool // NOT IN 查询
	SupportsBetween  bool // BETWEEN 查询
	SupportsLike     bool // LIKE 模式匹配
	SupportsDistinct bool // DISTINCT 去重
	SupportsGroupBy  bool // GROUP BY 分组
	SupportsHaving   bool // HAVING 条件过滤

	// JOIN 操作
	SupportsInnerJoin     bool // INNER JOIN
	SupportsLeftJoin      bool // LEFT JOIN
	SupportsRightJoin     bool // RIGHT JOIN
	SupportsCrossJoin     bool // CROSS JOIN
	SupportsFullOuterJoin bool // FULL OUTER JOIN
	SupportsSelfJoin      bool // 自连接

	// 高级查询特性
	SupportsCTE                bool // 公用表表达式 (WITH ... AS)
	SupportsRecursiveCTE       bool // 递归 CTE
	SupportsWindowFunc         bool // 窗口函数 (ROW_NUMBER, RANK, etc)
	SupportsSubquery           bool // 子查询
	SupportsCorrelatedSubquery bool // 关联子查询
	SupportsUnion              bool // UNION / UNION ALL
	SupportsExcept             bool // EXCEPT / MINUS
	SupportsIntersect          bool // INTERSECT

	// 聚合和分析函数
	SupportsOrderByInAggregate bool // 聚合函数中的 ORDER BY (如 STRING_AGG(...ORDER BY...))
	SupportsArrayAggregate     bool // 数组聚合
	SupportsStringAggregate    bool // 字符串聚合

	// 文本搜索
	SupportsFullTextSearch bool // 全文搜索
	SupportsRegexMatch     bool // 正则表达式匹配
	SupportsFuzzyMatch     bool // 模糊匹配

	// JSON 操作
	SupportsJSONPath      bool // JSON 路径提取
	SupportsJSONType      bool // JSON 数据类型
	SupportsJSONOperators bool // JSON 运算符
	SupportsJSONAgg       bool // JSON 聚合

	// 案例表达式
	SupportsCase         bool // CASE WHEN THEN ELSE END
	SupportsCaseWithElse bool // CASE 带 ELSE

	// 其他特性
	SupportsLimit    bool // LIMIT 限制行数
	SupportsOffset   bool // OFFSET 偏移
	SupportsOrderBy  bool // ORDER BY 排序
	SupportsNulls    bool // IS NULL / IS NOT NULL
	SupportsCastType bool // CAST(...AS type)
	SupportsCoalesce bool // COALESCE 函数

	// 特殊数据库特性
	SupportsIfExists     bool // IF EXISTS 子句
	SupportsInsertIgnore bool // INSERT IGNORE (MySQL) 或 ON CONFLICT (PostgreSQL)
	SupportsUpsert       bool // INSERT ... ON DUPLICATE KEY UPDATE 或 ON CONFLICT

	// ==================== VIEW 支持 ====================
	SupportsView             bool // 是否支持 VIEW
	SupportsMaterializedView bool // 物化视图支持(如 PostgreSQL)
	SupportsViewForPreload   bool // 是否支持用 VIEW 实现 Preload 优化

	// ==================== 多 Adapter 路由优化信息 ====================
	// Search 操作优化
	SearchOptimizationSupported bool // 该 adapter 是否支持 search
	SearchOptimizationIsOptimal bool // 是否是 search 的最优 adapter
	SearchOptimizationPriority  int  // 路由优先级 (1=最优, 2=次优, 3=备选)

	// Recursive 查询优化
	RecursiveOptimizationSupported       bool // 是否支持递归查询
	RecursiveOptimizationIsOptimal       bool // 是否是递归查询的最优 adapter
	RecursiveOptimizationPriority        int  // 路由优先级
	RecursiveOptimizationHasNativeSyntax bool // 是否有原生递归语法(否则需要补偿)

	// Adapter 功能标签
	AdapterTags []string // 功能标签,如 ["text_search", "graph", "relational", "time_series"]

	// 优化说明
	OptimizationNotes map[string]string // 各种优化信息的说明

	// 映射:特性名 => 降级策略
	FallbackStrategies map[string]QueryFallbackStrategy
	// 特性说明
	FeatureNotes map[string]string
	// 替代语法映射
	AlternativeSyntax map[string]string

	// 版本化特性支持(可选)
	FeatureSupport map[string]FeatureSupport
}

QueryFeatures 数据库查询特性集合

func GetQueryFeatures

func GetQueryFeatures(dbType string) *QueryFeatures

GetQueryFeatures 获取数据库的查询特性

func NewMongoQueryFeatures

func NewMongoQueryFeatures() *QueryFeatures

NewMongoQueryFeatures MongoDB 查询特性(最小占位实现)

func NewMySQLQueryFeatures

func NewMySQLQueryFeatures() *QueryFeatures

NewMySQLQueryFeatures MySQL 查询特性

func NewPostgreSQLQueryFeatures

func NewPostgreSQLQueryFeatures() *QueryFeatures

NewPostgreSQLQueryFeatures PostgreSQL 查询特性

func NewSQLServerQueryFeatures

func NewSQLServerQueryFeatures() *QueryFeatures

NewSQLServerQueryFeatures SQL Server 查询特性

func NewSQLiteQueryFeatures

func NewSQLiteQueryFeatures() *QueryFeatures

NewSQLiteQueryFeatures SQLite 查询特性

func (*QueryFeatures) GetAlternativeSyntax

func (qf *QueryFeatures) GetAlternativeSyntax(feature string) string

GetAlternativeSyntax 获取替代语法

func (*QueryFeatures) GetFallbackStrategy

func (qf *QueryFeatures) GetFallbackStrategy(feature string) QueryFallbackStrategy

GetFallbackStrategy 获取不支持特性时的降级策略

func (*QueryFeatures) GetFeatureNote

func (qf *QueryFeatures) GetFeatureNote(feature string) string

GetFeatureNote 获取特性说明

func (*QueryFeatures) GetFeatureSupport

func (qf *QueryFeatures) GetFeatureSupport(feature string) FeatureSupport

GetFeatureSupport 获取特性支持详情(若未定义则返回零值)

func (*QueryFeatures) HasQueryFeature

func (qf *QueryFeatures) HasQueryFeature(feature string) bool

HasQueryFeature 检查是否支持某个查询特性

func (*QueryFeatures) SupportsFeatureWithVersion

func (qf *QueryFeatures) SupportsFeatureWithVersion(feature, version string) bool

SupportsFeatureWithVersion 根据版本判断特性支持(version 为空时退回到常规判断)

type RawSQLMigration

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

RawSQLMigration 原始 SQL 迁移

func NewRawSQLMigration

func NewRawSQLMigration(version, description string) *RawSQLMigration

NewRawSQLMigration 创建原始 SQL 迁移

func (*RawSQLMigration) AddDownSQL

func (m *RawSQLMigration) AddDownSQL(sql string) *RawSQLMigration

AddDownSQL 添加 Down SQL

func (*RawSQLMigration) AddUpSQL

func (m *RawSQLMigration) AddUpSQL(sql string) *RawSQLMigration

AddUpSQL 添加 Up SQL

func (*RawSQLMigration) Down

func (m *RawSQLMigration) Down(ctx context.Context, repo *Repository) error

Down 回滚迁移

func (*RawSQLMigration) ForAdapter

func (m *RawSQLMigration) ForAdapter(adapter string) *RawSQLMigration

ForAdapter 指定 adapter

func (*RawSQLMigration) Up

func (m *RawSQLMigration) Up(ctx context.Context, repo *Repository) error

Up 执行迁移

type RelationType

type RelationType string
const (
	OneToOne   RelationType = "one_to_one"
	OneToMany  RelationType = "one_to_many"
	ManyToOne  RelationType = "many_to_one"
	ManyToMany RelationType = "many_to_many"
)

type Relationship

type Relationship struct {
	// 关系名称(用于查询时引用)
	Name string

	// 源表和目标表
	FromSchema Schema
	ToSchema   Schema

	// 关系类型
	Type RelationType

	// 外键定义
	ForeignKey *ForeignKeyDef

	// 关联表(仅用于多对多)
	JoinTable *JoinTableDef
}

Relationship 表示表之间的关系定义

type RelationshipManager

type RelationshipManager interface {
	// 获取该 Adapter 的关系支持能力
	GetRelationshipSupport() *RelationshipSupport

	// 创建关系(创建外键、中间表等)
	CreateRelationship(ctx context.Context, rel *Relationship) error

	// 删除关系
	DropRelationship(ctx context.Context, fromTable, relName string) error

	// 查询关系(带关联数据)
	QueryWithRelation(ctx context.Context, schema Schema, rel *Relationship, query string, args ...interface{}) (interface{}, error)

	// 检查关系是否存在
	HasRelationship(ctx context.Context, fromTable, relName string) (bool, error)
}

RelationshipManager Adapter 需要实现的关系管理接口

type RelationshipStrategy

type RelationshipStrategy string
const (
	// 原生支持(PostgreSQL, SQL Server)
	StrategyNative RelationshipStrategy = "native"

	// 通过中间表模拟多对多(MySQL, SQLite)
	StrategyJoinTable RelationshipStrategy = "join_table"

	// 通过外键实现关系(所有关系型数据库)
	StrategyForeignKey RelationshipStrategy = "foreign_key"

	// 应用层实现(非关系型数据库)
	StrategyApplication RelationshipStrategy = "application"

	// 完全不支持
	StrategyNotSupported RelationshipStrategy = "not_supported"
)

type RelationshipSupport

type RelationshipSupport struct {
	// 基础关系类型支持
	OneToOne   bool
	OneToMany  bool
	ManyToMany bool

	// 关系特性
	SupportsForeignKey bool // 是否支持外键约束
	SupportsJoin       bool // 是否支持 JOIN 操作
	SupportsNested     bool // 是否支持嵌套关系查询

	// 实现方式
	Strategy RelationshipStrategy // 如何实现关系
}

RelationshipSupport 关系支持能力声明

type RelationshipValidator

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

RelationshipValidator 用于验证关系定义的有效性和兼容性

func NewRelationshipValidator

func NewRelationshipValidator(support *RelationshipSupport) *RelationshipValidator

NewRelationshipValidator 创建验证器

func (*RelationshipValidator) CanJoin

func (v *RelationshipValidator) CanJoin() bool

CanJoin 检查是否可以执行 JOIN 操作

func (*RelationshipValidator) GetSupportSummary

func (v *RelationshipValidator) GetSupportSummary() map[string]bool

GetSupportSummary 获取支持情况的总结

func (*RelationshipValidator) NeedsManyToManyEmulation

func (v *RelationshipValidator) NeedsManyToManyEmulation(rel *Relationship) bool

NeedsManyToManyEmulation 检查是否需要多对多转发

func (*RelationshipValidator) ValidateRelationship

func (v *RelationshipValidator) ValidateRelationship(rel *Relationship) error

ValidateRelationship 验证单个关系是否在 Adapter 支持范围内

type Repository

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

Repository 数据库仓储对象 (类似 Ecto.Repo)

func InitDB

func InitDB(configPath string) (*Repository, error)

InitDB 使用配置文件初始化数据库 这是推荐的使用方式,遵循 Ecto 的依赖注入模式

func InitDBFromAdapterRegistry

func InitDBFromAdapterRegistry(configPath, adapterName string) (*Repository, error)

InitDBFromAdapterRegistry 从多 Adapter 配置文件初始化指定 adapter configPath: YAML/JSON 配置文件路径 adapterName: 在 adapters 中注册的名称

func InitDBFromEnv

func InitDBFromEnv() (*Repository, error)

InitDBFromEnv 使用环境变量初始化数据库 环境变量:

DB_ADAPTER: 适配器类型 (sqlite/postgres/mysql)
DB_PATH: SQLite 数据库文件路径
DB_HOST: 数据库主机
DB_PORT: 数据库端口
DB_USER: 数据库用户名
DB_PASSWORD: 数据库密码
DB_NAME: 数据库名称
DB_SSL_MODE: PostgreSQL SSL 模式

func InitDBWithDefaults

func InitDBWithDefaults(adapterType string) (*Repository, error)

InitDBWithDefaults 使用默认配置初始化数据库

func NewRepository

func NewRepository(config *Config) (*Repository, error)

NewRepository 创建新的仓储实例 (通过配置注入)

func NewRepositoryFromAdapterConfig

func NewRepositoryFromAdapterConfig(name string) (*Repository, error)

NewRepositoryFromAdapterConfig 通过已注册的 Adapter 配置创建 Repository

func (*Repository) Begin

func (r *Repository) Begin(ctx context.Context, opts ...interface{}) (Tx, error)

Begin 开始事务

func (*Repository) Close

func (r *Repository) Close() error

Close 关闭数据库连接

func (*Repository) Connect

func (r *Repository) Connect(ctx context.Context) error

Connect 连接数据库

func (*Repository) Exec

func (r *Repository) Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)

Exec 执行操作

func (*Repository) GetAdapter

func (r *Repository) GetAdapter() Adapter

GetAdapter 获取底层适配器 (用于高级操作)

func (*Repository) GetGormDB

func (r *Repository) GetGormDB() *gorm.DB

GetGormDB 从 Repository 获取 GORM 实例 用于保持与现有 GORM 代码的兼容性

func (*Repository) ListScheduledTasks

func (r *Repository) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

ListScheduledTasks 列出所有已注册的定时任务

func (*Repository) Ping

func (r *Repository) Ping(ctx context.Context) error

Ping 测试数据库连接

func (*Repository) Query

func (r *Repository) Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)

Query 执行查询

func (*Repository) QueryRow

func (r *Repository) QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row

QueryRow 执行单行查询

func (*Repository) QueryStruct

func (r *Repository) QueryStruct(ctx context.Context, dest interface{}, sql string, args ...interface{}) error

QueryStruct 查询单个结构体 自动将查询结果映射到结构体

func (*Repository) QueryStructs

func (r *Repository) QueryStructs(ctx context.Context, dest interface{}, sql string, args ...interface{}) error

QueryStructs 查询多个结构体 自动将查询结果映射到结构体切片

func (*Repository) RegisterScheduledTask

func (r *Repository) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error

RegisterScheduledTask 注册定时任务 支持按月自动创建表等后台任务,具体实现由各个适配器决定:

  • PostgreSQL: 使用触发器和 pg_cron 扩展
  • MySQL: 使用 MySQL EVENT
  • SQLite/其他: 建议由应用层通过 cron 库处理

func (*Repository) UnregisterScheduledTask

func (r *Repository) UnregisterScheduledTask(ctx context.Context, taskName string) error

UnregisterScheduledTask 注销定时任务

type RequiredValidator

type RequiredValidator struct{}

RequiredValidator 必填验证器

func (*RequiredValidator) Validate

func (v *RequiredValidator) Validate(value interface{}) error

type SQLDialect

type SQLDialect interface {
	// 获取方言名称
	Name() string

	// 转义标识符(表名、列名)
	QuoteIdentifier(name string) string

	// 转义字符串值
	QuoteValue(value interface{}) string

	// 返回参数化占位符(? 或 $1 等)
	GetPlaceholder(index int) string

	// 生成 LIMIT/OFFSET 子句
	GenerateLimitOffset(limit *int, offset *int) string

	// 转换条件为 SQL(可选的方言特定优化)
	TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)
}

SQLDialect SQL 方言接口 不同的数据库可以实现此接口来提供方言特定的 SQL 生成

type SQLQueryConstructor

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

SQLQueryConstructor SQL 查询构造器 - 底层执行层 实现 QueryConstructor 接口,生成标准 SQL 每个 Adapter 可以通过继承和覆写方法来实现方言特定的 SQL 生成

func NewSQLQueryConstructor

func NewSQLQueryConstructor(schema Schema, dialect SQLDialect) *SQLQueryConstructor

NewSQLQueryConstructor 创建新的 SQL 查询构造器

func (*SQLQueryConstructor) Build

func (qb *SQLQueryConstructor) Build(ctx context.Context) (string, []interface{}, error)

Build 构建 SQL 查询

func (*SQLQueryConstructor) GetNativeBuilder

func (qb *SQLQueryConstructor) GetNativeBuilder() interface{}

GetNativeBuilder 获取底层查询构造器(返回自身)

func (*SQLQueryConstructor) Limit

func (qb *SQLQueryConstructor) Limit(count int) QueryConstructor

Limit 限制行数

func (*SQLQueryConstructor) Offset

func (qb *SQLQueryConstructor) Offset(count int) QueryConstructor

Offset 偏移行数

func (*SQLQueryConstructor) OrderBy

func (qb *SQLQueryConstructor) OrderBy(field string, direction string) QueryConstructor

OrderBy 排序

func (*SQLQueryConstructor) Select

func (qb *SQLQueryConstructor) Select(fields ...string) QueryConstructor

Select 选择字段

func (*SQLQueryConstructor) Where

func (qb *SQLQueryConstructor) Where(condition Condition) QueryConstructor

Where 添加单个条件

func (*SQLQueryConstructor) WhereAll

func (qb *SQLQueryConstructor) WhereAll(conditions ...Condition) QueryConstructor

WhereAll 添加多个 AND 条件

func (*SQLQueryConstructor) WhereAny

func (qb *SQLQueryConstructor) WhereAny(conditions ...Condition) QueryConstructor

WhereAny 添加多个 OR 条件

type SQLServerAdapter

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

SQLServerAdapter SQL Server 数据库适配器

func (*SQLServerAdapter) Begin

func (a *SQLServerAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)

Begin 开始事务

func (*SQLServerAdapter) Close

func (a *SQLServerAdapter) Close() error

Close 关闭数据库连接

func (*SQLServerAdapter) Connect

func (a *SQLServerAdapter) Connect(ctx context.Context, config *Config) error

Connect 连接到 SQL Server 数据库

func (*SQLServerAdapter) Exec

func (a *SQLServerAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 执行操作 (INSERT/UPDATE/DELETE)

func (*SQLServerAdapter) GetDatabaseFeatures

func (a *SQLServerAdapter) GetDatabaseFeatures() *DatabaseFeatures

GetDatabaseFeatures 返回 SQL Server 数据库特性

func (*SQLServerAdapter) GetGormDB

func (a *SQLServerAdapter) GetGormDB() *gorm.DB

GetGormDB 获取GORM实例(用于直接访问GORM)

func (*SQLServerAdapter) GetQueryBuilderProvider

func (a *SQLServerAdapter) GetQueryBuilderProvider() QueryConstructorProvider

GetQueryBuilderProvider 返回查询构造器提供者

func (*SQLServerAdapter) GetQueryFeatures

func (a *SQLServerAdapter) GetQueryFeatures() *QueryFeatures

GetQueryFeatures 返回 SQL Server 的查询特性

func (*SQLServerAdapter) GetRawConn

func (a *SQLServerAdapter) GetRawConn() interface{}

GetRawConn 获取底层连接 (返回 *gorm.DB)

func (*SQLServerAdapter) ListScheduledTasks

func (a *SQLServerAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

ListScheduledTasks SQL Server 适配器暂不支持

func (*SQLServerAdapter) Ping

func (a *SQLServerAdapter) Ping(ctx context.Context) error

Ping 测试数据库连接

func (*SQLServerAdapter) Query

func (a *SQLServerAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 执行查询 (返回多行)

func (*SQLServerAdapter) QueryRow

func (a *SQLServerAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 执行查询 (返回单行)

func (*SQLServerAdapter) RegisterScheduledTask

func (a *SQLServerAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error

RegisterScheduledTask SQL Server 适配器支持 SQL Server Agent 方式的定时任务 注意:需要 SQL Server Agent 服务运行,且用户需要相应权限

func (*SQLServerAdapter) UnregisterScheduledTask

func (a *SQLServerAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error

UnregisterScheduledTask SQL Server 适配器暂不支持

type SQLServerDialect

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

SQL Server 方言

func NewSQLServerDialect

func NewSQLServerDialect() *SQLServerDialect

func (*SQLServerDialect) GenerateLimitOffset

func (d *SQLServerDialect) GenerateLimitOffset(limit *int, offset *int) string

SQL Server 使用 OFFSET...ROWS FETCH...ROWS ONLY 语法

func (*SQLServerDialect) GetPlaceholder

func (d *SQLServerDialect) GetPlaceholder(index int) string

SQL Server 使用 @p1, @p2 形式的参数

func (*SQLServerDialect) Name

func (d *SQLServerDialect) Name() string

func (*SQLServerDialect) QuoteIdentifier

func (d *SQLServerDialect) QuoteIdentifier(name string) string

SQL Server 使用方括号引用标识符

func (*SQLServerDialect) QuoteValue

func (d *SQLServerDialect) QuoteValue(value interface{}) string

func (*SQLServerDialect) TranslateCondition

func (d *SQLServerDialect) TranslateCondition(condition Condition, argIndex *int) (string, []interface{}, error)

type SQLServerFactory

type SQLServerFactory struct{}

SQLServerFactory SQL Server 适配器工厂

func (*SQLServerFactory) Create

func (f *SQLServerFactory) Create(config *Config) (Adapter, error)

Create 创建 SQL Server 适配器

func (*SQLServerFactory) Name

func (f *SQLServerFactory) Name() string

Name 返回适配器名称

type SQLServerTx

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

SQLServerTx SQL Server 事务实现

func (*SQLServerTx) Commit

func (t *SQLServerTx) Commit(ctx context.Context) error

Commit 提交事务

func (*SQLServerTx) Exec

func (t *SQLServerTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 在事务中执行

func (*SQLServerTx) Query

func (t *SQLServerTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 在事务中查询

func (*SQLServerTx) QueryRow

func (t *SQLServerTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 在事务中查询单行

func (*SQLServerTx) Rollback

func (t *SQLServerTx) Rollback(ctx context.Context) error

Rollback 回滚事务

type SQLiteAdapter

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

SQLiteAdapter SQLite 数据库适配器

func NewSQLiteAdapter

func NewSQLiteAdapter(config *Config) (*SQLiteAdapter, error)

NewSQLiteAdapter 创建 SQLite 适配器

func (*SQLiteAdapter) Begin

func (a *SQLiteAdapter) Begin(ctx context.Context, opts ...interface{}) (Tx, error)

Begin 开始事务

func (*SQLiteAdapter) Close

func (a *SQLiteAdapter) Close() error

Close 关闭数据库连接

func (*SQLiteAdapter) Connect

func (a *SQLiteAdapter) Connect(ctx context.Context, config *Config) error

Connect 连接到 SQLite 数据库

func (*SQLiteAdapter) Exec

func (a *SQLiteAdapter) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 执行操作 (INSERT/UPDATE/DELETE)

func (*SQLiteAdapter) GetDatabaseFeatures

func (a *SQLiteAdapter) GetDatabaseFeatures() *DatabaseFeatures

GetDatabaseFeatures 返回 SQLite 数据库特性

func (*SQLiteAdapter) GetGormDB

func (a *SQLiteAdapter) GetGormDB() *gorm.DB

GetGormDB 获取GORM实例(用于直接访问GORM)

func (*SQLiteAdapter) GetQueryBuilderProvider

func (a *SQLiteAdapter) GetQueryBuilderProvider() QueryConstructorProvider

GetQueryBuilderProvider 返回查询构造器提供者

func (*SQLiteAdapter) GetQueryFeatures

func (a *SQLiteAdapter) GetQueryFeatures() *QueryFeatures

GetQueryFeatures 返回 SQLite 的查询特性

func (*SQLiteAdapter) GetRawConn

func (a *SQLiteAdapter) GetRawConn() interface{}

GetRawConn 获取底层连接 (返回 *gorm.DB)

func (*SQLiteAdapter) ListScheduledTasks

func (a *SQLiteAdapter) ListScheduledTasks(ctx context.Context) ([]*ScheduledTaskStatus, error)

ListScheduledTasks SQLite 适配器暂不支持

func (*SQLiteAdapter) Ping

func (a *SQLiteAdapter) Ping(ctx context.Context) error

Ping 测试数据库连接

func (*SQLiteAdapter) Query

func (a *SQLiteAdapter) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 执行查询 (返回多行)

func (*SQLiteAdapter) QueryRow

func (a *SQLiteAdapter) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 执行查询 (返回单行)

func (*SQLiteAdapter) RegisterCommonSQLiteFunctions

func (a *SQLiteAdapter) RegisterCommonSQLiteFunctions() error

RegisterCommonSQLiteFunctions 注册常用的 SQLite 自定义函数

func (*SQLiteAdapter) RegisterSQLiteAggregateFunction

func (a *SQLiteAdapter) RegisterSQLiteAggregateFunction(fn *SQLiteAggregateFunction) error

RegisterSQLiteAggregateFunction 注册自定义聚合函数

func (*SQLiteAdapter) RegisterSQLiteFunction

func (a *SQLiteAdapter) RegisterSQLiteFunction(fn *SQLiteCustomFunction) error

RegisterSQLiteFunction 注册 SQLite 自定义函数 这允许在 SQLite 中使用 Go 编写的函数,性能优于应用层处理

注意:此功能需要在连接时通过 sql.OpenDB 使用自定义连接器 由于 GORM 的封装,当前实现有限制,建议直接使用 sql.DB

func (*SQLiteAdapter) RegisterScheduledTask

func (a *SQLiteAdapter) RegisterScheduledTask(ctx context.Context, task *ScheduledTaskConfig) error

RegisterScheduledTask SQLite 适配器暂不支持通过触发器方式实现定时任务 建议在应用层使用 cron 库处理定时任务

func (*SQLiteAdapter) UnregisterScheduledTask

func (a *SQLiteAdapter) UnregisterScheduledTask(ctx context.Context, taskName string) error

UnregisterScheduledTask SQLite 适配器暂不支持

type SQLiteAggregateFunction

type SQLiteAggregateFunction struct {
	Name    string
	NumArgs int
	Step    func(ctx interface{}, args ...interface{}) (interface{}, error) // 每行调用
	Final   func(ctx interface{}) (interface{}, error)                      // 最终结果
}

SQLiteAggregateFunction 自定义聚合函数定义

type SQLiteCustomFunction

type SQLiteCustomFunction struct {
	Name    string                                         // 函数名称
	NumArgs int                                            // 参数数量 (-1 表示可变参数)
	Pure    bool                                           // 是否为纯函数(无副作用)
	Impl    func(args ...interface{}) (interface{}, error) // 函数实现
}

SQLiteCustomFunction 自定义函数定义

type SQLiteDialect

type SQLiteDialect struct {
	DefaultSQLDialect
}

SQLite 方言

func NewSQLiteDialect

func NewSQLiteDialect() *SQLiteDialect

type SQLiteDynamicTableHook

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

SQLiteDynamicTableHook SQLite 动态表钩子实现 使用 GORM 的 hook 机制实现基于触发的动态建表

func NewSQLiteDynamicTableHook

func NewSQLiteDynamicTableHook(adapter *SQLiteAdapter) *SQLiteDynamicTableHook

NewSQLiteDynamicTableHook 创建 SQLite 动态表钩子

func (*SQLiteDynamicTableHook) CreateDynamicTable

func (h *SQLiteDynamicTableHook) CreateDynamicTable(ctx context.Context, configName string, params map[string]interface{}) (string, error)

CreateDynamicTable 手动创建动态表 返回实际创建的表名称

func (*SQLiteDynamicTableHook) GetDynamicTableConfig

func (h *SQLiteDynamicTableHook) GetDynamicTableConfig(ctx context.Context, configName string) (*DynamicTableConfig, error)

GetDynamicTableConfig 获取特定的动态表配置

func (*SQLiteDynamicTableHook) ListCreatedDynamicTables

func (h *SQLiteDynamicTableHook) ListCreatedDynamicTables(ctx context.Context, configName string) ([]string, error)

ListCreatedDynamicTables 获取已创建的动态表列表

func (*SQLiteDynamicTableHook) ListDynamicTableConfigs

func (h *SQLiteDynamicTableHook) ListDynamicTableConfigs(ctx context.Context) ([]*DynamicTableConfig, error)

ListDynamicTableConfigs 列出所有已注册的动态表配置

func (*SQLiteDynamicTableHook) RegisterDynamicTable

func (h *SQLiteDynamicTableHook) RegisterDynamicTable(ctx context.Context, config *DynamicTableConfig) error

RegisterDynamicTable 注册动态表配置 对于自动策略,在 GORM hook 中注册事件处理

func (*SQLiteDynamicTableHook) UnregisterDynamicTable

func (h *SQLiteDynamicTableHook) UnregisterDynamicTable(ctx context.Context, configName string) error

UnregisterDynamicTable 注销动态表配置

type SQLiteTx

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

SQLiteTx SQLite 事务实现

func (*SQLiteTx) Commit

func (t *SQLiteTx) Commit(ctx context.Context) error

Commit 提交事务

func (*SQLiteTx) Exec

func (t *SQLiteTx) Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

Exec 在事务中执行

func (*SQLiteTx) Query

func (t *SQLiteTx) Query(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

Query 在事务中查询

func (*SQLiteTx) QueryRow

func (t *SQLiteTx) QueryRow(ctx context.Context, query string, args ...interface{}) *sql.Row

QueryRow 在事务中查询单行

func (*SQLiteTx) Rollback

func (t *SQLiteTx) Rollback(ctx context.Context) error

Rollback 回滚事务

type ScheduledTaskConfig

type ScheduledTaskConfig struct {
	// 任务的唯一标识符(如 "monthly_page_logs")
	Name string

	// 任务类型
	Type ScheduledTaskType

	// 任务的 Cron 表达式(如 "0 0 1 * *" 表示每月1号0点)
	// 某些数据库实现可能不使用此字段
	CronExpression string

	// 任务特定的配置参数,根据任务类型而定
	// 对于 TaskTypeMonthlyTableCreation,应包含:
	//   - tableName: string - 表名前缀
	//   - monthFormat: string - 月份格式(如 "2006_01")
	//   - fieldDefinitions: string - 表字段定义(SQL DDL)
	Config map[string]interface{}

	// 任务描述
	Description string

	// 是否启用此任务
	Enabled bool
}

ScheduledTaskConfig 定时任务配置 这个结构体定义了要执行的定时任务的参数,不同的数据库适配器 可以根据不同的实现方式(如 PostgreSQL 触发器、应用层 cron)来处理

func (*ScheduledTaskConfig) GetMonthlyTableConfig

func (c *ScheduledTaskConfig) GetMonthlyTableConfig() map[string]interface{}

GetMonthlyTableConfig 便捷方法:获取按月创建表的配置

func (*ScheduledTaskConfig) Validate

func (c *ScheduledTaskConfig) Validate() error

Validate 验证任务配置的有效性

type ScheduledTaskEventListener

type ScheduledTaskEventListener interface {
	OnTaskRegistered(ctx context.Context, config *ScheduledTaskConfig) error
	OnTaskUnregistered(ctx context.Context, taskName string) error
	OnTaskExecutionStarted(ctx context.Context, taskName string) error
	OnTaskExecutionCompleted(ctx context.Context, taskName string, err error) error
}

ScheduledTaskEventListener 定时任务事件监听器接口 用于监听定时任务的生命周期事件

type ScheduledTaskExecutor

type ScheduledTaskExecutor interface {
	// Execute 执行定时任务
	// taskName: 任务名称
	// config: 完整的任务配置
	Execute(ctx context.Context, taskName string, config *ScheduledTaskConfig) error
}

ScheduledTaskExecutor 定时任务执行器接口 由应用层实现,用于执行不同类型的定时任务

type ScheduledTaskStatus

type ScheduledTaskStatus struct {
	// 任务名称
	Name string

	// 任务类型
	Type ScheduledTaskType

	// 是否正在运行
	Running bool

	// 上次执行时间(Unix 时间戳)
	LastExecutedAt int64

	// 下次执行时间(Unix 时间戳,如果适用)
	NextExecutedAt int64

	// 任务创建者信息(可选)
	CreatedAt int64

	// 额外的状态信息
	Info map[string]interface{}
}

ScheduledTaskStatus 定时任务执行状态

type ScheduledTaskType

type ScheduledTaskType string

ScheduledTaskType 定时任务类型枚举

const (
	// TaskTypeMonthlyTableCreation 按月自动创建表的任务
	TaskTypeMonthlyTableCreation ScheduledTaskType = "monthly_table_creation"
)

type Schema

type Schema interface {
	// 获取模式名称(表名)
	TableName() string

	// 获取所有字段
	Fields() []*Field

	// 获取字段
	GetField(name string) *Field

	// 获取主键字段
	PrimaryKeyField() *Field
}

Schema 定义数据模式接口 (参考 Ecto.Schema)

type SchemaMigration

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

SchemaMigration 基于 Schema 的迁移

func NewSchemaMigration

func NewSchemaMigration(version, description string) *SchemaMigration

NewSchemaMigration 创建基于 Schema 的迁移

func (*SchemaMigration) CreateTable

func (m *SchemaMigration) CreateTable(schema Schema) *SchemaMigration

CreateTable 添加要创建的表

func (*SchemaMigration) Down

func (m *SchemaMigration) Down(ctx context.Context, repo *Repository) error

Down 回滚迁移

func (*SchemaMigration) DropTable

func (m *SchemaMigration) DropTable(schema Schema) *SchemaMigration

DropTable 添加要删除的表

func (*SchemaMigration) Up

func (m *SchemaMigration) Up(ctx context.Context, repo *Repository) error

Up 执行迁移

type SchemaRegistry

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

SchemaRegistry Schema 注册表,便于查找和管理多个 Schema

func NewSchemaRegistry

func NewSchemaRegistry() *SchemaRegistry

NewSchemaRegistry 创建空的 Schema 注册表

func (*SchemaRegistry) Get

func (r *SchemaRegistry) Get(name string) Schema

Get 获取指定名称的 Schema

func (*SchemaRegistry) GetAllSchemaNames

func (r *SchemaRegistry) GetAllSchemaNames() []string

GetAllSchemaNames 获取所有已注册的 Schema 名称

func (*SchemaRegistry) Register

func (r *SchemaRegistry) Register(name string, schema Schema)

Register 注册一个 Schema

type SchemaRelationshipBuilder

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

SchemaRelationshipBuilder Schema 中的关系构建

func NewSchemaRelationshipBuilder

func NewSchemaRelationshipBuilder(schema *BaseSchema) *SchemaRelationshipBuilder

NewSchemaRelationshipBuilder 创建关系构建器

func (*SchemaRelationshipBuilder) BelongsTo

func (b *SchemaRelationshipBuilder) BelongsTo(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder

BelongsTo 定义多对一关系(反向一对多)

func (*SchemaRelationshipBuilder) GetRelationships

func (b *SchemaRelationshipBuilder) GetRelationships() []*Relationship

GetRelationships 获取所有关系

func (*SchemaRelationshipBuilder) HasAndBelongsToMany

func (b *SchemaRelationshipBuilder) HasAndBelongsToMany(
	name string,
	toSchema Schema,
	joinTableName string,
	fromForeignKey string,
	toForeignKey string,
) *SchemaRelationshipBuilder

HasAndBelongsToMany 定义多对多关系

func (*SchemaRelationshipBuilder) HasMany

func (b *SchemaRelationshipBuilder) HasMany(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder

HasMany 定义一对多关系

func (*SchemaRelationshipBuilder) HasOne

func (b *SchemaRelationshipBuilder) HasOne(name string, toSchema Schema, foreignKey, primaryKey string) *SchemaRelationshipBuilder

HasOne 定义一对一关系

type SimpleCondition

type SimpleCondition struct {
	Field    string
	Operator string // "eq", "ne", "gt", "lt", "gte", "lte", "in", "like", "between"
	Value    interface{}
}

SimpleCondition 简单条件(字段 操作符 值)

func (*SimpleCondition) Translate

func (c *SimpleCondition) Translate(translator ConditionTranslator) (string, []interface{}, error)

func (*SimpleCondition) Type

func (c *SimpleCondition) Type() string

type Transformer

type Transformer interface {
	// 转换值
	Transform(value interface{}) (interface{}, error)
}

Transformer 转换器接口

type TrimTransformer

type TrimTransformer struct{}

TrimTransformer 字符串修剪转换器

func (*TrimTransformer) Transform

func (t *TrimTransformer) Transform(value interface{}) (interface{}, error)

type Tx

type Tx interface {
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error

	// 事务中的查询和执行
	Query(ctx context.Context, sql string, args ...interface{}) (*sql.Rows, error)
	QueryRow(ctx context.Context, sql string, args ...interface{}) *sql.Row
	Exec(ctx context.Context, sql string, args ...interface{}) (sql.Result, error)
}

Tx 定义事务接口

type TypeConversionError

type TypeConversionError struct {
	From string
	To   string
}

TypeConversionError 类型转换错误

func (*TypeConversionError) Error

func (e *TypeConversionError) Error() string

type UniqueValidator

type UniqueValidator struct {
	Schema Schema
	Field  string
}

UniqueValidator 唯一性验证器

func (*UniqueValidator) Validate

func (v *UniqueValidator) Validate(value interface{}) error

type ValidationError

type ValidationError struct {
	Code    string
	Message string
}

ValidationError 验证错误

func NewValidationError

func NewValidationError(code, message string) *ValidationError

NewValidationError 创建验证错误

func (*ValidationError) Error

func (e *ValidationError) Error() string

type Validator

type Validator interface {
	// 验证值,返回错误信息或 nil
	Validate(value interface{}) error
}

Validator 验证器接口

Directories

Path Synopsis
cmd
eit-migrate command

Jump to

Keyboard shortcuts

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