Documentation
¶
Overview ¶
Package db 提供了基于 GORM 的数据库组件,支持分库分表功能。
db 组件是 Genesis 基础设施层的核心组件,它在连接器的基础上提供了: - GORM ORM 功能封装 - 事务管理支持 - 分库分表能力(基于 gorm.io/sharding) - 与 L0 基础组件(日志、链路追踪、错误)的深度集成
## 基本使用(MySQL)
mysqlConn, _ := connector.NewMySQL(&cfg.MySQL, connector.WithLogger(logger))
defer mysqlConn.Close()
mysqlConn.Connect(ctx)
database, _ := db.New(&db.Config{
Driver: "mysql",
EnableSharding: true,
ShardingRules: []db.ShardingRule{
{
ShardingKey: "user_id",
NumberOfShards: 64,
Tables: []string{"orders"},
},
},
},
db.WithLogger(logger),
db.WithTracer(otel.GetTracerProvider()),
db.WithMySQLConnector(mysqlConn),
)
## 使用 PostgreSQL
pgConn, _ := connector.NewPostgreSQL(&cfg.PostgreSQL, connector.WithLogger(logger))
defer pgConn.Close()
pgConn.Connect(ctx)
database, _ := db.New(&db.Config{Driver: "postgresql"},
db.WithLogger(logger),
db.WithTracer(otel.GetTracerProvider()),
db.WithPostgreSQLConnector(pgConn),
)
// 使用 GORM 进行数据库操作
gormDB := database.DB(ctx)
var users []User
gormDB.Where("status = ?", "active").Find(&users)
// 事务操作
err := database.Transaction(ctx, func(ctx context.Context, tx *gorm.DB) error {
return tx.Create(&User{Name: "test"}).Error
})
## 分片配置
分片功能通过配置 ShardingRule 启用:
type ShardingRule struct {
ShardingKey string // 分片键,如 "user_id"
NumberOfShards uint // 分片数量
Tables []string // 应用规则的表名列表
}
## 设计原则
- **借用模型**:db 组件借用连接器的连接,不负责连接的生命周期 - **配置驱动**:通过 Config.Driver 字段控制底层实现(mysql/postgresql/sqlite) - **显式依赖**:通过构造函数显式注入连接器和选项 - **简单设计**:使用 Go 原生模式,避免复杂的抽象 - **可观测性**:集成 clog 和 OpenTelemetry trace,提供完整的日志和链路追踪能力
Index ¶
- Variables
- type Config
- type DB
- type Option
- func WithLogger(l clog.Logger) Option
- func WithMySQLConnector(conn connector.MySQLConnector) Option
- func WithPostgreSQLConnector(conn connector.PostgreSQLConnector) Option
- func WithSQLiteConnector(conn connector.SQLiteConnector) Option
- func WithSilentMode() Option
- func WithTracer(tp trace.TracerProvider) Option
- type ShardingRule
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidConfig 配置无效 ErrInvalidConfig = xerrors.New("db: invalid config") // ErrMySQLConnectorRequired MySQL 连接器未提供 ErrMySQLConnectorRequired = xerrors.New("db: mysql connector is required") // ErrPostgreSQLConnectorRequired PostgreSQL 连接器未提供 ErrPostgreSQLConnectorRequired = xerrors.New("db: postgresql connector is required") // ErrSQLiteConnectorRequired SQLite 连接器未提供 ErrSQLiteConnectorRequired = xerrors.New("db: sqlite connector is required") )
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Driver string `json:"driver" yaml:"driver"`
EnableSharding bool `json:"enable_sharding" yaml:"enable_sharding"`
ShardingRules []ShardingRule `json:"sharding_rules" yaml:"sharding_rules"`
}
Config DB 组件配置
type DB ¶
type DB interface {
DB(ctx context.Context) *gorm.DB
Transaction(ctx context.Context, fn func(ctx context.Context, tx *gorm.DB) error) error
Close() error
}
DB 定义了数据库组件的核心能力
type Option ¶
type Option func(*options)
Option 配置 DB 实例的选项
func WithMySQLConnector ¶
func WithMySQLConnector(conn connector.MySQLConnector) Option
WithMySQLConnector 注入 MySQL 连接器
func WithPostgreSQLConnector ¶
func WithPostgreSQLConnector(conn connector.PostgreSQLConnector) Option
WithPostgreSQLConnector 注入 PostgreSQL 连接器
func WithSQLiteConnector ¶
func WithSQLiteConnector(conn connector.SQLiteConnector) Option
WithSQLiteConnector 注入 SQLite 连接器
func WithSilentMode ¶
func WithSilentMode() Option
WithSilentMode 启用静默模式,禁用 SQL 日志输出 适用于测试环境或不需要 SQL 日志的场景
func WithTracer ¶
func WithTracer(tp trace.TracerProvider) Option
WithTracer 注入 TracerProvider(用于 OpenTelemetry trace)
type ShardingRule ¶
type ShardingRule struct {
ShardingKey string `json:"sharding_key" yaml:"sharding_key"`
NumberOfShards uint `json:"number_of_shards" yaml:"number_of_shards"`
Tables []string `json:"tables" yaml:"tables"`
}
ShardingRule 分片规则