Verify / verify (push) Canceled after 0s
抽取 Gin、配置、日志、数据库、Redis 与出站 HTTP 基础能力。 新增统一接入指南,将能力清单和相对链接检查纳入 make verify。 对齐远端 module 路径,修正 Redis 读写超时特殊值映射。 验证:make verify、make race-check 均通过。
163 lines
6.3 KiB
Go
163 lines
6.3 KiB
Go
// Package database 创建进程拥有的 GORM 连接,不保存应用全局句柄。
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"net"
|
|
"strconv"
|
|
"time"
|
|
|
|
"git.zhangdeman.cn/github/ginframework/database/sqllog"
|
|
fault "git.zhangdeman.cn/github/ginframework/internal/failure"
|
|
mysqlDriver "github.com/go-sql-driver/mysql"
|
|
"go.uber.org/zap"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
const (
|
|
// CodeConfig 表示数据库连接配置无效。
|
|
CodeConfig = 900201
|
|
// CodeOpen 表示数据库打开失败。
|
|
CodeOpen = 900202
|
|
// CodePool 表示取得底层连接池失败。
|
|
CodePool = 900203
|
|
// CodeProbe 表示启动探测失败。
|
|
CodeProbe = 900204
|
|
// CodePlugin 表示应用声明的 GORM 插件安装失败。
|
|
CodePlugin = 900205
|
|
// CodeClose 表示连接池关闭失败。
|
|
CodeClose = 900206
|
|
// CodeTimezone 表示 MySQL 时区解析失败。
|
|
CodeTimezone = 900207
|
|
// CodeTarget 表示 MySQL 缺少必须的连接目标。
|
|
CodeTarget = 900208
|
|
)
|
|
|
|
// Config 描述 MySQL 和连接池数据,数值指针区分缺省与显式零值。
|
|
type Config struct {
|
|
Name string `json:"name" yaml:"name" dc:"应用声明的实例名,仅用于诊断"`
|
|
Host string `json:"host" yaml:"host" dc:"MySQL 主机"`
|
|
Port int `json:"port" yaml:"port" dc:"MySQL 端口,缺省 3306"`
|
|
Username string `json:"username" yaml:"username" dc:"数据库账号"`
|
|
Password string `json:"password" yaml:"password" dc:"部署注入的数据库密码"`
|
|
Database string `json:"database" yaml:"database" dc:"数据库名称"`
|
|
Charset string `json:"charset" yaml:"charset" dc:"字符集,缺省 utf8mb4"`
|
|
Timezone string `json:"timezone" yaml:"timezone" dc:"IANA 时区,缺省 UTC"`
|
|
MaxOpen *int `json:"max_open" yaml:"max_open" dc:"最大打开连接数,缺省 50,零表示不限制"`
|
|
MaxIdle *int `json:"max_idle" yaml:"max_idle" dc:"最大空闲连接数,缺省 10,零表示不保留"`
|
|
ProbeTimeoutMS int `json:"probe_timeout_ms" yaml:"probe_timeout_ms" dc:"启动探测超时毫秒,缺省 5000"`
|
|
}
|
|
|
|
// Options 是启动时注入的原生运行依赖,不参与 YAML 解码。
|
|
type Options struct {
|
|
Dialector gorm.Dialector `json:"-" dc:"可选原生方言,SQLite 测试等场景显式传入"`
|
|
Logger *zap.Logger `json:"-" dc:"已有日志输出,nil 表示禁用 SQL 执行流水"`
|
|
Plugins []gorm.Plugin `json:"-" dc:"应用在发布连接前必须安装的插件"`
|
|
}
|
|
|
|
// Connection 拥有单个读写共用的连接池,由应用统一关闭。
|
|
type Connection struct {
|
|
root *gorm.DB `dc:"不可保存请求条件的 GORM 根会话"`
|
|
pool *sql.DB `dc:"当前对象拥有的原生连接池"`
|
|
}
|
|
|
|
// Open 创建并探测数据库,全部成功后才返回可发布的对象。
|
|
// 入参:ctx 为启动上下文,cfg 为连接配置,options 为原生运行依赖。
|
|
// 返回:连接对象;失败回收本次创建的连接并保留原因链。
|
|
func Open(ctx context.Context, cfg Config, options Options) (result *Connection, err error) {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
maxOpen, maxIdle := 50, 10
|
|
if cfg.MaxOpen != nil {
|
|
maxOpen = *cfg.MaxOpen
|
|
}
|
|
if cfg.MaxIdle != nil {
|
|
maxIdle = *cfg.MaxIdle
|
|
}
|
|
if cfg.ProbeTimeoutMS < 0 || maxOpen < 0 || maxIdle < 0 || cfg.Port < 0 || cfg.Port > 65535 || (maxOpen > 0 && maxIdle > maxOpen) {
|
|
return nil, fault.Wrap(CodeConfig, "validate database configuration failed", errors.New("invalid pool, port or probe setting"))
|
|
}
|
|
dialect := options.Dialector
|
|
if dialect == nil {
|
|
if cfg.Host == "" || cfg.Database == "" {
|
|
return nil, fault.Wrap(CodeTarget, "validate MySQL target failed", errors.New("MySQL host and database are required"))
|
|
}
|
|
if cfg.Port == 0 {
|
|
cfg.Port = 3306
|
|
}
|
|
if cfg.Charset == "" {
|
|
cfg.Charset = "utf8mb4"
|
|
}
|
|
if cfg.Timezone == "" {
|
|
cfg.Timezone = "UTC"
|
|
}
|
|
location, locationErr := time.LoadLocation(cfg.Timezone)
|
|
if locationErr != nil {
|
|
return nil, fault.Wrap(CodeTimezone, "resolve MySQL timezone failed", locationErr)
|
|
}
|
|
driver := mysqlDriver.NewConfig()
|
|
driver.User, driver.Passwd, driver.Net, driver.Addr, driver.DBName = cfg.Username, cfg.Password, "tcp", net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)), cfg.Database
|
|
driver.ParseTime, driver.Loc = true, location
|
|
driver.Timeout = 5 * time.Second
|
|
driver.Params = map[string]string{"charset": cfg.Charset}
|
|
dialect = mysql.Open(driver.FormatDSN())
|
|
}
|
|
orm, openErr := gorm.Open(dialect, &gorm.Config{DisableAutomaticPing: true, Logger: sqllog.New(options.Logger, cfg.Name)})
|
|
if openErr != nil {
|
|
if orm != nil {
|
|
if pool, poolErr := orm.DB(); poolErr == nil {
|
|
openErr = errors.Join(openErr, fault.Wrap(CodeClose, "close failed database pool failed", pool.Close()))
|
|
}
|
|
}
|
|
return nil, fault.Wrap(CodeOpen, "open database failed", openErr)
|
|
}
|
|
pool, poolErr := orm.DB()
|
|
if poolErr != nil {
|
|
return nil, fault.Wrap(CodePool, "resolve database pool failed", poolErr)
|
|
}
|
|
defer func() {
|
|
if err != nil {
|
|
err = errors.Join(err, fault.Wrap(CodeClose, "close pending database pool failed", pool.Close()))
|
|
}
|
|
}()
|
|
pool.SetMaxOpenConns(maxOpen)
|
|
pool.SetMaxIdleConns(maxIdle)
|
|
if cfg.ProbeTimeoutMS == 0 {
|
|
cfg.ProbeTimeoutMS = 5000
|
|
}
|
|
probe, cancel := context.WithTimeout(ctx, time.Duration(cfg.ProbeTimeoutMS)*time.Millisecond)
|
|
defer cancel()
|
|
if err = pool.PingContext(probe); err != nil {
|
|
return nil, fault.Wrap(CodeProbe, "probe database failed", err)
|
|
}
|
|
for _, plugin := range options.Plugins {
|
|
if plugin == nil {
|
|
return nil, fault.Wrap(CodePlugin, "install database plugin failed", errors.New("database plugin is nil"))
|
|
}
|
|
if err = orm.Use(plugin); err != nil {
|
|
return nil, fault.Wrap(CodePlugin, "install database plugin failed", err)
|
|
}
|
|
}
|
|
return &Connection{root: orm, pool: pool}, nil
|
|
}
|
|
|
|
// Session 派生独立的 GORM 会话,保留调用取消及诊断上下文。
|
|
// 入参:ctx 为当前可信调用上下文,允许 nil。
|
|
// 返回:共享连接池的原生 GORM 会话,不增加事务封装。
|
|
func (c *Connection) Session(ctx context.Context) *gorm.DB {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
return c.root.WithContext(ctx)
|
|
}
|
|
|
|
// Close 在请求和业务协程结束后释放连接池。
|
|
// 返回:关闭失败时返回内部错误;重复关闭遵循 database/sql 的幂等语义。
|
|
func (c *Connection) Close() error {
|
|
return fault.Wrap(CodeClose, "close database pool failed", c.pool.Close())
|
|
}
|