Help us shape the future of Go! Take the 2026 Go Developer Survey

gorm

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package gorm 提供 infra 内部共用的 GORM 日志、连接池初始化和主从路由能力。 数据库模块负责提供 GORM Logger 入口、下游名称、端点信息及方言连接。 例如模块内部可以创建不带端点的日志核心:

const downstreamSQLiteMessage = "SQLite"
name := "local"
core := gorm.New(gorm.Config{
    Message:        downstreamSQLiteMessage,
    Name:           name,
    DurationPrefix: downstreamSQLiteMessage + "_" + name,
    SlowThreshold:  200 * time.Millisecond,
})
_, _ = core.ParamsFilter(ctx, "SELECT ?", 1)

模块通过 BuildCluster 创建主从连接,open 回调只接收 context 和端点配置; 应用停止查询后关闭:

var cluster gorm.Cluster
if err := gorm.BuildCluster(ctx, &cluster, master, slaves, open); err != nil {
    return err
}
defer cluster.Close()
readDB := cluster.Slave(ctx)
_ = readDB

Open 接收可选的 GORM 配置函数;模块可设置方言所需选项,同时沿用共享的 Logger、禁用自动 Ping 和初始化失败时关闭连接池的约定。

ConfigureAndPing 验活失败时,先按 context 状态及初始化期限归一化超时,再关闭连接池。 context 的取消错误优先;仅当网络超时且期限已到时补充返回 context.DeadlineExceeded。 无期限或期限未到的独立网络超时保留原错误,清理耗时不改变验活错误分类。

上例需导入 time 和 github.com/bpcoder16/pixiu/infra/internal/gorm。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildCluster

func BuildCluster[T any](
	ctx context.Context,
	cluster *Cluster,
	master T,
	slaves []T,
	open func(context.Context, T) (*gormlib.DB, *sql.DB, error),
) (err error)

BuildCluster 依次打开主库与从库;回调失败时关闭已登记的连接池。 回调失败时若返回了连接池,由此函数关闭;否则回调须自行关闭尚未交出的连接池。 构建失败后的 Cluster 不可重用。

func ConfigureAndPing

func ConfigureAndPing(ctx context.Context, pool *sql.DB, cfg PoolConfig) error

ConfigureAndPing 设置池参数并验活;验活失败时关闭连接池。 context 错误优先;网络超时且初始化期限已到时统一返回 context.DeadlineExceeded。

func Open

func Open(pool *sql.DB, dialector gormlib.Dialector, diagnostic logger.Interface, configure ...func(*gormlib.Config)) (*gormlib.DB, error)

Open 用已验活的连接池初始化 GORM;可选配置不能覆盖共享的 Logger 和禁用自动 Ping 约定。 方言初始化失败时关闭连接池。

Types

type Cluster

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

Cluster 持有 GORM 主从会话及其底层连接池。初始化阶段登记,查询阶段只读。

func (*Cluster) Close

func (c *Cluster) Close() error

Close 关闭所有连接池;重复调用返回首次关闭结果。

func (*Cluster) Master

func (c *Cluster) Master(ctx context.Context) *gormlib.DB

Master 返回绑定请求 context 的主库 GORM 会话;调用方保证 ctx 非 nil。

func (*Cluster) Slave

func (c *Cluster) Slave(ctx context.Context) *gormlib.DB

Slave 返回绑定请求 context 的从库会话;无从库时回退主库。

type Config

type Config struct {
	Message        string
	Name           string
	DurationPrefix string
	// Endpoint 是可选的端点标识;空值时不输出端点字段。
	Endpoint       string
	SlowThreshold  time.Duration
	LogSQL         bool
	InterpolateSQL bool
	// ErrorDetails 在查询错误日志写入前补充驱动特有字段。
	ErrorDetails func(error, map[string]any)
}

Config 配置 GORM 日志核心。调用方负责先归一化慢查询阈值。

type Logger

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

Logger 处理 GORM 查询与诊断日志;数据库模块实现 GORM Logger 入口。

func New

func New(cfg Config) *Logger

New 创建日志核心。

func (*Logger) Diagnostic

func (l *Logger) Diagnostic(ctx context.Context, gormLevel logger.LogLevel, level logit.Level, format string, args ...any)

Diagnostic 记录 GORM 诊断消息;caller 指向数据库模块对应的级别入口。

func (*Logger) LogTrace

func (l *Logger) LogTrace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

LogTrace 记录查询结果和请求耗时;caller 指向数据库模块的 Trace 入口。

func (*Logger) ParamsFilter

func (l *Logger) ParamsFilter(_ context.Context, sql string, params ...any) (string, []any)

ParamsFilter 控制是否将 SQL 参数交给 GORM 方言展开。

func (*Logger) WithLevel

func (l *Logger) WithLevel(level logger.LogLevel) *Logger

WithLevel 复制日志核心并设置 GORM 日志级别。

type PoolConfig

type PoolConfig struct {
	// MaxOpenConns 限制同时打开的连接数;零值使用模块默认值。
	MaxOpenConns int `mapstructure:"maxOpenConns"`
	// MaxIdleConns 限制保留的空闲连接数;零值使用模块默认值。
	MaxIdleConns int `mapstructure:"maxIdleConns"`
	// ConnMaxLifetime 限制连接可被复用的最长时间;零值使用模块默认值。
	ConnMaxLifetime time.Duration `mapstructure:"connMaxLifetime"`
	// ConnMaxIdleTime 限制连接的空闲时间;零值使用模块默认值。
	ConnMaxIdleTime time.Duration `mapstructure:"connMaxIdleTime"`
}

PoolConfig 是数据库模块共用的连接池配置;零值默认值由使用它的模块决定。

func NormalizePool

func NormalizePool(pool, defaults PoolConfig) (PoolConfig, error)

NormalizePool 校验参数并应用模块默认值;默认空闲数不超过生效后的打开数。

Jump to

Keyboard shortcuts

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