Documentation
¶
Overview ¶
Package db 提供基于 GORM 的数据库组件,是 Genesis L1 基础设施层的一部分。
db 在 connector 提供的连接之上封装 GORM 的初始化、事务管理与可观测性接入。 业务代码通过 DB(ctx) 获得 *gorm.DB,继续使用原生 GORM API, 在注入 logger / tracer 时可接入 clog SQL 日志与 OpenTelemetry trace 能力。
基本用法 ¶
pgConn, _ := connector.NewPostgreSQL(&cfg.PostgreSQL, connector.WithLogger(logger))
defer pgConn.Close()
pgConn.Connect(ctx)
database, err := db.New(&db.Config{Driver: "postgresql"},
db.WithPostgreSQLConnector(pgConn),
db.WithLogger(logger),
db.WithTracer(otel.GetTracerProvider()),
)
if err != nil {
return err
}
// GORM 操作
gormDB := database.DB(ctx)
gormDB.Where("status = ?", "active").Find(&users)
// 事务
err = database.Transaction(ctx, func(ctx context.Context, tx *gorm.DB) error {
return tx.Create(&Order{UserID: 1001}).Error
})
资源所有权 ¶
db 采用借用模型:connector 拥有 SQL 池,db 拥有独立 GORM 句柄及语句缓存。 应用层先注册 connector.Close,再注册 db.Close,保证组件先于借用池清理。
分表 ¶
分表属于数据库层面的能力,推荐使用数据库原生分区:
- PostgreSQL 10+:PARTITION BY HASH / RANGE / LIST
- MySQL:PARTITION BY HASH / RANGE / LIST
原生分区对应用层完全透明,无需任何应用代码改动。
Example ¶
package main
import (
"context"
"github.com/ceyewan/genesis/connector"
"github.com/ceyewan/genesis/db"
)
func main() {
conn, err := connector.NewSQLite(&connector.SQLiteConfig{Path: ":memory:"})
if err != nil || conn.Connect(context.Background()) != nil {
return
}
defer conn.Close()
database, err := db.New(&db.Config{Driver: "sqlite"}, db.WithSQLiteConnector(conn))
if err != nil {
return
}
_ = database.DB(context.Background())
}
Output:
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 WithSlowThreshold(threshold time.Duration) Option
- func WithTracer(tp trace.TracerProvider) Option
Examples ¶
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") // ErrConnectorNotReady 表示连接器尚未 Connect 或已被关闭。 // New 返回此错误时也会保留 connector.ErrClientNil 分类。 ErrConnectorNotReady = xerrors.New("db: connector is not ready") // ErrNilTransaction 表示 Transaction 收到了 nil 回调。 ErrNilTransaction = xerrors.New("db: transaction function is nil") )
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Driver string `json:"driver" yaml:"driver" mapstructure:"driver"`
}
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 WithSlowThreshold ¶ added in v1.0.0
WithSlowThreshold 配置慢 SQL 阈值。零值使用默认 200ms,负值会使 New 返回 ErrInvalidConfig。
func WithTracer ¶
func WithTracer(tp trace.TracerProvider) Option
WithTracer 将 TracerProvider 注入组件自己的 GORM 句柄,不修改 Connector 或其他 DB 实例。