Documentation
¶
Overview ¶
Package ormx 提供基于 GORM 的 MySQL 数据访问便捷封装: 连接与连接池配置、事务死锁自动重试、单机连接健康探活与可观测,以及 GORM 的 zap 日志适配。
基本用法:
client, err := ormx.Open(ctx,
ormx.WithHost("127.0.0.1"),
ormx.WithPort("3306"),
ormx.WithDatabase("app"),
ormx.WithUser("root"),
ormx.WithPassword(os.Getenv("DB_PASSWORD")),
)
if err != nil {
return err
}
defer client.Close()
db := client.DB() // *gorm.DB,直接走 GORM API
事务通过 Client.Transaction(或需要 *sql.TxOptions 时的 Client.WithTx)执行, 遇 MySQL 死锁(1213)或锁等待超时(1205)自动按带抖动的指数退避重试。
连接健康检查与连接池统计见 Client.HealthCheck 与 Client.StatsSnapshot。
Client 可在多个 goroutine 间并发使用;调用方注入的 logger、HealthProbe、 TxRetryObserver 的并发安全由调用方保证。 GORM 的 zap 日志适配见子包 zlogger;通用分页查询执行器见子包 paginator。
Index ¶
- Constants
- Variables
- type Client
- func (c *Client) Close() error
- func (c *Client) Config() Config
- func (c *Client) DB() *gorm.DB
- func (c *Client) HealthCheck(ctx context.Context) HealthReport
- func (c *Client) Name() string
- func (c *Client) PingContext(ctx context.Context) error
- func (c *Client) SQLDB() *sql.DB
- func (c *Client) StatsSnapshot() DBStatsSnapshot
- func (c *Client) Transaction(ctx context.Context, fn func(tx *gorm.DB) error, txOpts ...TxOption) error
- func (c *Client) WithReadTx(ctx context.Context, fn func(tx *gorm.DB) error) error
- func (c *Client) WithTx(ctx context.Context, opts *sql.TxOptions, fn func(tx *gorm.DB) error, ...) error
- type Config
- func (c Config) Clone() Config
- func (c Config) GoString() string
- func (c Config) MustOpen(ctx context.Context) *Client
- func (c Config) Open(ctx context.Context) (*Client, error)
- func (c Config) OpenWithDB(ctx context.Context, sqlDB *sql.DB) (*Client, error)
- func (c Config) RedactedDSN() (string, error)
- func (c Config) String() string
- func (c Config) With(opts ...Option) Config
- type DBStatsSnapshot
- type GORMConfig
- type HealthProbeFunc
- type HealthReport
- type HealthStatus
- type MySQLConfig
- type MySQLDialectConfig
- type Option
- func WithAddress(addr string) Option
- func WithCharset(charset string) Option
- func WithCollation(collation string) Option
- func WithConnMaxIdleTime(duration time.Duration) Option
- func WithConnMaxLifetime(duration time.Duration) Option
- func WithConnectionAttributes(attrs string) Option
- func WithCreateBatchSize(size int) Option
- func WithDSN(dsn string) Option
- func WithDatabase(name string) Option
- func WithDefaultContextTimeout(timeout time.Duration) Option
- func WithDefaultStringSize(size uint) Option
- func WithDefaultTransactionTimeout(timeout time.Duration) Option
- func WithDisableDatetimePrecision(disable bool) Option
- func WithDisableWithReturning(disable bool) Option
- func WithDryRun(enabled bool) Option
- func WithGormLogger(log gormlogger.Interface) Option
- func WithHealthProbe(probe HealthProbeFunc) Option
- func WithHost(host string) Option
- func WithLocation(loc *time.Location) Option
- func WithMaxIdleConns(size int) Option
- func WithMaxOpenConns(size int) Option
- func WithName(name string) Option
- func WithNamingStrategy(strategy schema.NamingStrategy) Option
- func WithNetwork(network string) Option
- func WithNowFunc(now func() time.Time) Option
- func WithParseTime(enabled bool) Option
- func WithPassword(password string) Option
- func WithPort(port string) Option
- func WithPrepareStmt(enabled bool) Option
- func WithPrepareStmtCache(maxSize int, ttl time.Duration) Option
- func WithQueryFields(enabled bool) Option
- func WithReadTimeout(timeout time.Duration) Option
- func WithServerVersion(version string) Option
- func WithSingularTable(enabled bool) Option
- func WithSkipDefaultTransaction(skip bool) Option
- func WithSkipInitializeWithVersion(skip bool) Option
- func WithStartupPing(enabled bool) Option
- func WithStartupPingRetry(maxRetries int, baseWait, maxWait time.Duration) Option
- func WithSystemVariable(key, value string) Option
- func WithSystemVariables(params map[string]string) Option
- func WithTLSConfig(name string) Option
- func WithTablePrefix(prefix string) Option
- func WithTimeout(timeout time.Duration) Option
- func WithTranslateError(enabled bool) Option
- func WithTxRetryObserver(observer TxRetryObserver) Option
- func WithUser(user string) Option
- func WithWriteTimeout(timeout time.Duration) Option
- func WithZapLogger(zlog *zap.Logger, opts ...zlogger.Option) Option
- func WithZlogger(opts ...zlogger.Option) Option
- type PoolConfig
- type TxOption
- type TxRetryEvent
- type TxRetryObserver
Examples ¶
Constants ¶
const Version = "v1.5.0"
Version 是 ormx 当前发布的版本号。
Variables ¶
var ErrAddressRequired = errors.New("ormx: mysql address is required")
ErrAddressRequired 表示缺少连接地址:既未提供 Addr、又未同时提供 Host 与 Port, 或使用 unix 网络(Net=="unix")时未用 WithAddress 指定 socket 路径。可用 errors.Is 判定。
var ErrDSNUnsupported = errors.New("ormx: dsn settings not supported")
ErrDSNUnsupported 表示 DSN 级设置无法经当前 API 表达:WithCharset 传入 charset 回退列表 (如 "utf8mb4,utf8",回退列表仅能经 WithDSN 的 charset 参数设置)、试图用 WithCharset("") 清除来自 WithDSN 的 charset,或 DSN 使用驱动已移除的参数(如 strict)。可用 errors.Is 判定。
var ErrNilSQLDB = errors.New("ormx: nil *sql.DB")
ErrNilSQLDB 表示向 OpenWithDB 传入了 nil *sql.DB;可用 errors.Is 判定。
var ErrNilTxFunc = errors.New("ormx: nil transaction function")
ErrNilTxFunc 表示向 WithTx 传入了 nil 事务函数;可用 errors.Is 判定。
var ErrSystemVariableNameRequired = errors.New("ormx: system variable name must not be empty")
ErrSystemVariableNameRequired 表示系统变量名为空或纯空白字符;可用 errors.Is 判定。
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 封装单个数据库连接,持有 GORM 实例与底层 *sql.DB。 Client 自身状态只读,可在多个 goroutine 间并发使用;但调用方注入的 Logger、HealthProbe、TxRetryObserver 会在并发下被调用,其并发安全由调用方保证。
func OpenWithDB ¶
OpenWithDB 包装既有的 *sql.DB:只把 opts 中显式传入的连接池参数应用到 sqlDB, 不强加包内默认(借用的外部连接池由调用方自行配置,未显式覆盖的项保持不变)。 成功打开后 Client.Close 不会关闭该外部 *sql.DB;但注意:若 GORM 初始化失败, GORM 的清理逻辑可能关闭传入的 *sql.DB,失败后请勿再复用它(见 Config.OpenWithDB)。
func (*Client) Close ¶
Close 先释放 GORM 预编译语句缓存(启用 WithPrepareStmt 时;GORM 以异步方式关闭已缓存语句), 再关闭底层 *sql.DB——仅当 Client 拥有该连接时才真正关闭,否则(OpenWithDB 场景)不关闭外部 DB。
func (*Client) Config ¶
Config 返回客户端配置的脱敏快照:深拷贝后把密码、连接参数值与连接属性替换为占位符, 不含明文凭据或敏感绑定值,仅供检视。需要真实值请由调用方保留原始配置。
func (*Client) HealthCheck ¶
func (c *Client) HealthCheck(ctx context.Context) HealthReport
HealthCheck 执行一次健康检查(Ping 加可选的 HealthProbe)并返回报告。 当 ctx 未设置 deadline 时使用内置默认超时,避免无限阻塞。
func (*Client) PingContext ¶
PingContext 检测数据库连接是否可用。
func (*Client) StatsSnapshot ¶
func (c *Client) StatsSnapshot() DBStatsSnapshot
StatsSnapshot 返回当前连接池统计信息的快照。
func (*Client) Transaction ¶ added in v1.3.0
func (c *Client) Transaction(ctx context.Context, fn func(tx *gorm.DB) error, txOpts ...TxOption) error
Transaction 在事务中执行 fn,等价于 WithTx(ctx, nil, fn, txOpts...), 是最常见调用(默认事务选项)的便捷入口:提交/回滚、死锁自动重试与 panic 回滚后原样上抛的语义均见 WithTx。需要指定 *sql.TxOptions (隔离级别、只读)时用 WithTx;只读事务另有便捷入口 WithReadTx。
Example ¶
Transaction 是最常见事务调用的便捷入口:fn 返回 nil 提交、返回 error 回滚, 遇 MySQL 死锁/锁等待超时自动重试(示例用进程内 stub 数据库,可执行验证)。
sqlDB, _ := newStubDB()
defer sqlDB.Close()
client, err := OpenWithDB(context.Background(), sqlDB,
WithStartupPing(false), WithSkipInitializeWithVersion(true))
if err != nil {
fmt.Println("open:", err)
return
}
defer client.Close()
txErr := client.Transaction(context.Background(), func(tx *gorm.DB) error {
// 在事务中执行业务操作;返回 nil 则提交,返回 error 则回滚。
return tx.Exec("UPDATE widgets SET active = 1").Error
})
fmt.Println(txErr == nil)
Output: true
func (*Client) WithReadTx ¶
WithReadTx 在只读事务中执行 fn,重试行为与 WithTx 的默认值一致。
func (*Client) WithTx ¶
func (c *Client) WithTx( ctx context.Context, opts *sql.TxOptions, fn func(tx *gorm.DB) error, txOpts ...TxOption, ) error
WithTx 在事务中执行 fn:fn 返回 nil 则提交,返回 error 则回滚。 遇到 MySQL 死锁(1213)或锁等待超时(1205)时按带抖动的指数退避自动重试, 重试行为可通过 TxOption 调整;fn 为 nil 时返回错误。 由于会重试,fn 可能被多次调用,必须可重入且幂等(不要依赖闭包外的一次性副作用)。 若 fn 发生 panic,事务会先回滚,随后 panic 继续向上传播(不被吞没为 error), 以保留调用方自身的 panic 处理语义。
type Config ¶
type Config struct {
Name string
MySQL MySQLConfig
Pool PoolConfig
GORM GORMConfig
Dialect MySQLDialectConfig
HealthProbe HealthProbeFunc
TxRetryObserver TxRetryObserver
StartupPing bool
StartupPingMaxRetries int
StartupPingRetryBaseWait time.Duration
StartupPingRetryMaxWait time.Duration
// contains filtered or unexported fields
}
Config 汇总建立 MySQL 连接所需的全部配置:驱动连接参数(MySQL)、 连接池(Pool)、GORM 行为(GORM)、方言(Dialect)以及启动期 Ping 重试策略。 Config 通过 With / Clone 返回隔离副本(仅复制包内可变字段),不修改原值。注意普通赋值(cfg2 := cfg) 只是浅拷贝,仍与原值共享 SystemVariables map 与连接池等指针字段;需要独立副本时用 Clone 或 With。 Config 是运行期配置,推荐用 Option(Open / NewConfig / With)构建;直接改字段会绕过 Option 的防御逻辑, 合法性由调用方自行保证。它不承诺可整体序列化——仅 MySQL、Pool 带 JSON/YAML 标签, 而 Logger、HealthProbe、TxRetryObserver、NowFunc、NamingStrategy 等运行时字段无法从配置文件映射; 配置文件驱动的场景建议由业务侧维护自己的 DTO,再转换成 ormx.Option。 注意:零值 Config 不携带任何默认值——需要默认值时以 DefaultConfig()(或 NewConfig)的返回值为基底再覆盖字段。 Pool 各字段为指针,nil 表示不设置、保持 database/sql 默认。
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig 返回带合理默认值的 Config: MySQL 默认通过 tcp 连接 127.0.0.1:3306,时区为 time.Local,启用 ParseTime, 并设置拨号/读/写超时;连接池四项参数均设为包内默认值; GORM 使用默认命名策略;StartupPing 默认开启,重试基础等待 1 秒、上限 5 秒、 默认不重试(StartupPingMaxRetries 为 0)。
func NewConfig ¶
NewConfig 在 DefaultConfig 的基础上依次应用 opts 并返回结果。
Example ¶
用 Functional Options 构建配置,并通过 RedactedDSN 输出密码脱敏后的 DSN(可安全打印到日志)。实际连库使用 cfg.Open(ctx) 或包级 ormx.Open。
package main
import (
"fmt"
"github.com/gtkit/ormx"
)
func main() {
cfg := ormx.NewConfig(
ormx.WithUser("alice"),
ormx.WithPassword("secret"),
ormx.WithDatabase("app"),
)
dsn, err := cfg.RedactedDSN()
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println(dsn)
}
Output: alice:******@tcp(127.0.0.1:3306)/app?loc=Local&parseTime=true&readTimeout=30s&timeout=10s&writeTimeout=30s
func (Config) Clone ¶
Clone 隔离复制包内可变的配置字段:MySQL.SystemVariables 映射、连接池与方言中的可选指针字段, 使副本与原值互不影响。注意它不深拷贝调用方注入的引用型字段—— GORM.Logger、HealthProbe、TxRetryObserver、NamingStrategy.NameReplacer 以及 MySQL.Loc(*time.Location,按不可变共享)仍与原值共享同一实例; WithDSN 的内部解析状态解析后只读,同样按不可变共享。
func (Config) Open ¶
Open 按当前配置构建 MySQL 连接器并打开 *sql.DB,应用连接池配置后初始化 GORM, 返回拥有该 *sql.DB 所有权的 Client(Close 时会一并关闭)。 若 StartupPing 开启,会先按重试策略 Ping 数据库;任一步骤失败时关闭已打开的连接并返回错误。 注意:ctx 仅约束启动 Ping;GORM 初始化时的 SELECT VERSION() 探测由驱动以内部 context.Background() 执行,受连接读超时(WithReadTimeout)约束而非 ctx。若需严格超时, 设置合理的 ReadTimeout,或用 WithSkipInitializeWithVersion + WithServerVersion 跳过该探测。
func (Config) OpenWithDB ¶
OpenWithDB 包装既有的 *sql.DB:GORM 初始化前会把 Config.Pool 中已设置的连接池参数应用到 sqlDB。 打开成功后 Client.Close 不会关闭该外部 *sql.DB(所有权归调用方)。 但注意:若 GORM 初始化(方言初始化/版本探测 SELECT VERSION())失败,GORM 会调用 sqlDB.Close() 清理, 因此打开失败后不应再复用传入的 *sql.DB——这是 GORM 的行为,本库无法在不引入包装层的前提下规避。 另注意:本方法不修改 Config.MySQL,而外部 *sql.DB 的真实连接地址由调用方决定, 因此返回 Client 的 Config().MySQL 未必反映其真实 DSN。
func (Config) RedactedDSN ¶
RedactedDSN 返回敏感值脱敏后的 DSN 字符串,可安全用于日志输出; 底层驱动配置构建失败时返回错误。为避免泄露,密码、全部连接系统变量(SystemVariables)值 与连接属性(ConnectionAttributes)在非空时统一替换为 "******",仅保留变量名等结构信息。
func (Config) String ¶
String 返回敏感值(密码、连接参数值、连接属性)已脱敏的可读表示, 底层复用 RedactedDSN,防止经 fmt.Print / 日志输出意外泄露。
func (Config) With ¶
With 返回应用 opts 后的 Config 副本,原 Config 不受影响;nil Option 会被跳过。
Example ¶
With 返回应用新 Option 后的隔离副本,原配置不受影响 (普通赋值 cfg2 := cfg 只是浅拷贝、仍共享 map 与指针字段,隔离请用 With/Clone)。
package main
import (
"fmt"
"github.com/gtkit/ormx"
)
func main() {
base := ormx.NewConfig(ormx.WithName("base"))
derived := base.With(ormx.WithName("derived"))
fmt.Println(base.Name, derived.Name)
}
Output: base derived
type DBStatsSnapshot ¶
type DBStatsSnapshot struct {
MaxOpenConnections int
OpenConnections int
InUse int
Idle int
WaitCount int64
WaitDuration time.Duration
MaxIdleClosed int64
MaxIdleTimeClosed int64
MaxLifetimeClosed int64
Utilization float64
}
DBStatsSnapshot 是 sql.DBStats 的快照,并附带连接利用率 Utilization (InUse / MaxOpenConnections,MaxOpenConnections 为 0 时取 0)。
type GORMConfig ¶
type GORMConfig struct {
Logger gormlogger.Interface
NowFunc func() time.Time
NamingStrategy schema.NamingStrategy
DefaultTransactionTimeout time.Duration
DefaultContextTimeout time.Duration
PrepareStmt bool
PrepareStmtMaxSize int
PrepareStmtTTL time.Duration
SkipDefaultTransaction bool
DisableForeignKeyConstraintWhenMigrating bool
IgnoreRelationshipsWhenMigrating bool
DisableNestedTransaction bool
AllowGlobalUpdate bool
QueryFields bool
CreateBatchSize int
TranslateError bool
PropagateUnscoped bool
DryRun bool
}
GORMConfig 描述透传给 gorm.Config 的行为配置, 字段与 gorm.Config 中的同名字段一一对应。
type HealthProbeFunc ¶
HealthProbeFunc 是自定义健康探测函数,在 Ping 成功后执行额外检查,返回非 nil 错误表示连接不健康。
type HealthReport ¶
type HealthReport struct {
Name string
Status HealthStatus
CheckedAt time.Time
Duration time.Duration
Error error
Stats DBStatsSnapshot
}
HealthReport 描述一次健康检查的结果。
func (HealthReport) Healthy ¶
func (r HealthReport) Healthy() bool
Healthy 报告本次检查状态是否为 HealthStatusUp。
type HealthStatus ¶
type HealthStatus string
HealthStatus 表示健康检查结果的状态。
const ( HealthStatusUp HealthStatus = "up" HealthStatusDown HealthStatus = "down" )
健康状态(HealthStatus)的预定义枚举值。
type MySQLConfig ¶
type MySQLConfig struct {
User string `json:"user" yaml:"user"`
Password string `json:"-" yaml:"-"`
Net string `json:"net" yaml:"net"`
Host string `json:"host" yaml:"host"`
Port string `json:"port" yaml:"port"`
Addr string `json:"addr" yaml:"addr"`
Database string `json:"database" yaml:"database"`
SystemVariables map[string]string `json:"system_variables" yaml:"system_variables"`
ConnectionAttributes string `json:"connection_attributes" yaml:"connection_attributes"`
Charset string `json:"charset" yaml:"charset"`
Collation string `json:"collation" yaml:"collation"`
Loc *time.Location `json:"-" yaml:"-"`
TLSConfig string `json:"tls_config" yaml:"tls_config"`
Timeout time.Duration `json:"timeout" yaml:"timeout"`
ReadTimeout time.Duration `json:"read_timeout" yaml:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout" yaml:"write_timeout"`
ParseTime bool `json:"parse_time" yaml:"parse_time"`
}
MySQLConfig 描述驱动层连接设置。 Addr 与 Host/Port 同时设置时 Addr 优先。 Charset 为单一连接字符集(如 "utf8mb4"),不支持逗号分隔的回退列表(见 WithCharset)。 建议通过 Option 辅助函数设置,以保证 Addr/Host/Port 的优先级语义一致。
func (MySQLConfig) GoString ¶ added in v1.2.0
func (c MySQLConfig) GoString() string
GoString 实现 fmt.GoStringer,使 %#v 输出同样脱敏。
func (MySQLConfig) String ¶ added in v1.2.0
func (c MySQLConfig) String() string
String 返回敏感值脱敏后的 MySQLConfig 表示,使 fmt 的 %v/%+v/%s 打印 不泄露密码、连接参数值与连接属性;用于安全日志输出。 注意:脱敏仅覆盖 fmt/Stringer 路径,结构化日志器(如 slog.Any)会反射字段、绕过本方法, 因此请勿将原始 Config/MySQLConfig 直接传给结构化日志,改用 String() 或 RedactedDSN()。
type MySQLDialectConfig ¶
type MySQLDialectConfig struct {
ServerVersion string
DefaultStringSize uint
DefaultDatetimePrecision *int
SkipInitializeWithVersion bool
DisableWithReturning bool
DisableDatetimePrecision bool
}
MySQLDialectConfig 描述透传给 GORM MySQL 方言(gorm.io/driver/mysql)的配置, 字段与其 Config 中的同名字段一一对应。
type Option ¶
type Option func(*Config)
Option 是修改 Config 的函数式配置项,配合 NewConfig、Open 等入口使用。
func WithAddress ¶
WithAddress 设置完整连接地址(如 "127.0.0.1:3306"); Addr 非空时优先于 Host/Port 生效。
func WithCharset ¶ added in v1.3.0
WithCharset 设置连接字符集(如 "utf8mb4"):连接建立后驱动执行 `SET NAMES <charset>`, 与 WithCollation 同时设置时执行 `SET NAMES <charset> COLLATE <collation>`。 驱动默认连接字符集已是 utf8mb4(默认 collation utf8mb4_general_ci),并非必须设置, 仅在需要显式指定 charset 或与 WithCollation 联用时使用;显式设置会让每条新连接 多执行一次 SET NAMES。
仅支持单一字符集,且标识符只允许字母、数字与下划线(charset 拼入原始 SQL,库层校验 以降低误配置与注入风险)。逗号分隔的回退列表(如 "utf8mb4,utf8")无法经本 Option 设置(需要时用 WithDSN 的 charset 参数),传入会在 Open 时返回包装 ErrDSNUnsupported 的错误;同理,来自 WithDSN 的 charset 无法用 WithCharset("") 清除。
Example ¶
WithCharset 一行设置连接字符集,连接建立后驱动执行 SET NAMES <charset> (配 WithCollation 时执行 SET NAMES <charset> COLLATE <collation>)。
package main
import (
"fmt"
"github.com/gtkit/ormx"
)
func main() {
cfg := ormx.NewConfig(
ormx.WithUser("alice"),
ormx.WithPassword("secret"),
ormx.WithDatabase("app"),
ormx.WithCharset("utf8mb4"),
)
dsn, err := cfg.RedactedDSN()
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println(dsn)
}
Output: alice:******@tcp(127.0.0.1:3306)/app?charset=utf8mb4&loc=Local&parseTime=true&readTimeout=30s&timeout=10s&writeTimeout=30s
func WithConnMaxIdleTime ¶
WithConnMaxIdleTime 设置连接最长空闲时间。默认 10 分钟。 取值透传给 sql.DB.SetConnMaxIdleTime:duration ≤ 0 表示空闲连接不因闲置被关闭。
func WithConnMaxLifetime ¶
WithConnMaxLifetime 设置连接可被复用的最长时间。默认 30 分钟。 取值透传给 sql.DB.SetConnMaxLifetime:duration ≤ 0 表示连接不过期。
func WithConnectionAttributes ¶
WithConnectionAttributes 设置 MySQL 连接属性(connection attributes)字符串。
func WithCreateBatchSize ¶
WithCreateBatchSize 设置批量插入时的默认分批大小。
func WithDSN ¶ added in v1.3.0
WithDSN 以完整 MySQL DSN(如 "user:pass@tcp(host:3306)/db?parseTime=true")初始化 连接配置,适合配置里已有现成 DSN 的场景。本库未单独建模的驱动参数(multiStatements、 maxAllowedPacket、charset 回退列表等)会原样保留并透传给驱动,连接行为与直接使用该 DSN 一致。注意语义:
- 整体替换:MySQL 连接子配置以该 DSN 为准,DSN 未写的参数按驱动默认生效 (如 parseTime=false、时区 UTC、无超时),本包 DefaultConfig 的 MySQL 默认不再叠加; 连接池、GORM 行为等非 DSN 配置不受影响。
- 可继续覆盖:建议把 WithDSN 放在其它连接 Option 之前——之后的 Option 仍可按序 覆盖单个字段(TCP 地址已同步拆出 Host/Port,WithHost/WithPort 覆盖可用)。
- 失败不 panic:DSN 解析失败(含驱动已移除的 strict 等参数,此类可用 errors.Is(err, ErrDSNUnsupported) 判定)会保留到 Open/RedactedDSN 时报错, 即便后续 Option 覆盖了字段。
安全边界:DSN 仅应来自可信静态配置,不得直接接收用户输入,也不要记录包含凭据的 原始 DSN(日志用 RedactedDSN);未建模的驱动参数会被原样透传,包括可能影响安全 边界的驱动开关(如 allowCleartextPasswords、tls=skip-verify)。
Example ¶
WithDSN 直接以完整 DSN 初始化连接配置(整体替换 MySQL 子配置, DSN 未写的参数按驱动默认),后续 Option 仍可覆盖单个字段。
package main
import (
"fmt"
"github.com/gtkit/ormx"
)
func main() {
cfg := ormx.NewConfig(
ormx.WithDSN("alice:secret@tcp(db.internal:3307)/app?charset=utf8mb4&parseTime=true"),
ormx.WithName("orders"),
)
dsn, err := cfg.RedactedDSN()
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println(dsn)
}
Output: alice:******@tcp(db.internal:3307)/app?charset=utf8mb4&parseTime=true
func WithDefaultContextTimeout ¶
WithDefaultContextTimeout 设置 GORM 操作的默认 context 超时时间。
func WithDefaultStringSize ¶
WithDefaultStringSize 设置 string 类型字段建表时的默认长度。
func WithDefaultTransactionTimeout ¶
WithDefaultTransactionTimeout 设置 GORM 事务的默认超时时间。
func WithDisableDatetimePrecision ¶
WithDisableDatetimePrecision 设置是否禁用 datetime 字段的精度支持。
func WithDisableWithReturning ¶
WithDisableWithReturning 设置是否禁用方言的 RETURNING 子句支持。
func WithGormLogger ¶
func WithGormLogger(log gormlogger.Interface) Option
WithGormLogger 设置 GORM 使用的日志实现。
func WithHealthProbe ¶
func WithHealthProbe(probe HealthProbeFunc) Option
WithHealthProbe 设置自定义健康探针;健康检查在 Ping 成功后调用该探针, 探针返回错误则判定为不健康。
func WithLocation ¶
WithLocation 设置解析时间值使用的时区。默认 time.Local。 传入 nil 会被忽略并保留原值,避免覆盖默认后在时间解析时因 nil Location 触发 panic。
func WithMaxIdleConns ¶
WithMaxIdleConns 设置连接池最大空闲连接数。默认 10。 取值透传给 sql.DB.SetMaxIdleConns:size ≤ 0 表示不保留空闲连接。
func WithMaxOpenConns ¶
WithMaxOpenConns 设置连接池最大打开连接数。默认 50。 取值透传给 sql.DB.SetMaxOpenConns:size ≤ 0 表示不限制。
func WithNamingStrategy ¶
func WithNamingStrategy(strategy schema.NamingStrategy) Option
WithNamingStrategy 整体替换 GORM 的命名策略,会覆盖之前设置的表前缀等字段。
func WithNetwork ¶
WithNetwork 设置连接 MySQL 使用的网络类型(如 "tcp"、"unix")。默认 "tcp"。 使用 "unix" 时必须配合 WithAddress 指定 socket 路径,否则 Open 返回 ErrAddressRequired。
func WithNowFunc ¶
WithNowFunc 设置 GORM 生成时间戳时使用的当前时间函数。
func WithParseTime ¶
WithParseTime 设置是否将 DATE/DATETIME 列解析为 time.Time。默认开启。
func WithPrepareStmt ¶
WithPrepareStmt 设置 GORM 是否缓存预编译语句以提升后续执行性能。
func WithPrepareStmtCache ¶
WithPrepareStmtCache 设置预编译语句缓存的最大条数 maxSize 与存活时间 ttl。 仅在 WithPrepareStmt(true) 时生效;未设置时沿用 GORM 的缓存默认。
func WithQueryFields ¶
WithQueryFields 设置查询时是否按模型字段名逐列展开 SELECT,而非 SELECT *。
func WithReadTimeout ¶
WithReadTimeout 设置 I/O 读超时时间。默认 30s。
func WithServerVersion ¶
WithServerVersion 手动指定 MySQL 服务端版本号,供方言据此调整行为。 仅在 WithSkipInitializeWithVersion(true) 时生效——否则会被 GORM 的 SELECT VERSION() 结果覆盖; 且跳过版本探测后,GORM 不再据版本自动推导兼容标志,需要时由调用方自行处理。
func WithSingularTable ¶
WithSingularTable 设置是否使用单数表名(如 User 对应表 user 而非 users)。
func WithSkipDefaultTransaction ¶
WithSkipDefaultTransaction 设置是否跳过 GORM 对单条写操作的默认事务包装。
func WithSkipInitializeWithVersion ¶
WithSkipInitializeWithVersion 设置是否跳过初始化时根据服务端版本自动配置方言。
func WithStartupPing ¶
WithStartupPing 设置打开连接时是否先执行 Ping 验证连通性。默认开启。
func WithStartupPingRetry ¶
WithStartupPingRetry 配置启动 Ping 的重试策略:maxRetries 为最大重试次数, baseWait、maxWait 为退避等待的基准值与上限。maxRetries 为负、baseWait 或 maxWait 非正时,对应项被忽略并保留原值。默认不重试,基准 1s,上限 5s。
func WithSystemVariable ¶ added in v1.2.0
WithSystemVariable 追加一个连接系统变量:连接建立后驱动会执行 `SET key = value`, 因此 value 必须是合法的 SQL 表达式(如字符串需自带引号)。它不是 DSN 内置参数—— loc、parseTime、timeout、charset 等 DSN 内置参数由专用 Option (WithLocation/WithParseTime/WithTimeout/WithCharset)处理,请勿经此设置。 SystemVariables 为 nil 时自动初始化,同名 key 会被覆盖;空 key 会在 Open 时返回错误。
安全边界:key/value 作为原始 SQL 直接拼接为 `SET` 语句执行,仅接受可信的静态配置; 切勿传入 HTTP 参数、用户配置等不可信输入,否则存在会话级 SQL 注入风险。
func WithSystemVariables ¶ added in v1.2.0
WithSystemVariables 批量追加连接系统变量(语义同 WithSystemVariable:连接后 `SET key = value`),同名 key 会被覆盖; 传入 nil 或空 map 时不做任何修改。
func WithTLSConfig ¶
WithTLSConfig 设置 MySQL 驱动使用的 TLS 配置名称。支持驱动内置值 "true"、"false"、"skip-verify"、"preferred",也支持经 mysql.RegisterTLSConfig 注册的名称。生产环境推荐 "true" 或启用证书验证的自定义配置; "preferred" 在服务端不支持 TLS 时会回退为明文连接, "skip-verify" 加密但不验证服务端证书,两者仅适合受控环境。
func WithTablePrefix ¶
WithTablePrefix 设置命名策略中的表名前缀,仅修改该字段,不影响策略的其他配置。
func WithTimeout ¶
WithTimeout 设置建立连接(拨号)超时时间。默认 10s。
func WithTranslateError ¶
WithTranslateError 设置是否将驱动错误翻译为 GORM 统一错误类型(如 gorm.ErrDuplicatedKey)。
func WithTxRetryObserver ¶
func WithTxRetryObserver(observer TxRetryObserver) Option
WithTxRetryObserver 设置事务重试观察者,事务发生重试时回调通知重试事件。
func WithWriteTimeout ¶
WithWriteTimeout 设置 I/O 写超时时间。默认 30s。
func WithZapLogger ¶ added in v1.3.0
WithZapLogger 用给定的 *zap.Logger 构造 GORM 日志器并注入,是接入 zap 的最短路径, 等价于 WithZlogger(zlogger.WithLogger(zlog), opts...)。zlog 为 nil 时回退为 no-op(静默丢弃)。 opts 在 logger 注入之后按序应用;默认级别 Warn、慢查询 200ms、参数化查询开启(不记录绑定参数值)。
Example ¶
WithZapLogger 直传 *zap.Logger 一步接入 SQL 日志, 等价于 WithZlogger(zlogger.WithLogger(zlog), opts...)。
package main
import (
"fmt"
"time"
"github.com/gtkit/ormx"
"github.com/gtkit/ormx/zlogger"
"go.uber.org/zap"
)
func main() {
cfg := ormx.NewConfig(
ormx.WithZapLogger(zap.NewNop(), zlogger.WithSlowThreshold(300*time.Millisecond)),
)
fmt.Println(cfg.GORM.Logger != nil)
}
Output: true
func WithZlogger ¶ added in v1.1.3
WithZlogger 用给定的 zlogger.Option 构造 GORM 日志器并注入, 等价于 WithGormLogger(zlogger.New(opts...)),省去调用方显式调用 zlogger.New。 不传任何 Option 时使用 zlogger 默认配置(no-op logger、慢查询 200ms、级别 Warn)。 需要注入自定义 gormlogger.Interface 实现时改用 WithGormLogger。
Example ¶
WithZlogger 一步注入 GORM SQL 日志器,无需显式调用 zlogger.New, 等价于 WithGormLogger(zlogger.New(opts...))。
package main
import (
"fmt"
"github.com/gtkit/ormx"
"github.com/gtkit/ormx/zlogger"
"go.uber.org/zap"
gormlogger "gorm.io/gorm/logger"
)
func main() {
cfg := ormx.NewConfig(
ormx.WithZlogger(
zlogger.WithLogger(zap.NewNop()),
zlogger.WithLogLevel(gormlogger.Info),
zlogger.WithIgnoreRecordNotFoundError(true),
),
)
fmt.Println(cfg.GORM.Logger != nil)
}
Output: true
type PoolConfig ¶
type PoolConfig struct {
MaxOpenConns *int `json:"max_open_conns" yaml:"max_open_conns"`
MaxIdleConns *int `json:"max_idle_conns" yaml:"max_idle_conns"`
ConnMaxLifetime *time.Duration `json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
ConnMaxIdleTime *time.Duration `json:"conn_max_idle_time" yaml:"conn_max_idle_time"`
}
PoolConfig 描述 *sql.DB 连接池参数。 字段均为指针:nil 表示不设置、保持 database/sql 的原有行为; 非 nil(含显式 0)表示应用该值到连接池。 可直接赋值、经 JSON/YAML 映射,或用 DefaultConfig 与对应 Option 设置,效果一致。
type TxOption ¶
type TxOption func(*txOptions)
TxOption 配置事务重试行为。
func WithMaxRetries ¶
WithMaxRetries 设置死锁后的最大重试次数。 设为 0 表示禁用重试。默认值:3。
func WithRetryBaseWait ¶
WithRetryBaseWait 设置指数退避的基础等待时间。 默认值:5ms。
func WithRetryMaxWait ¶
WithRetryMaxWait 设置单次重试退避的最大等待时间。 默认值:50ms。
type TxRetryEvent ¶
type TxRetryEvent struct {
ClientName string
Attempt int
MaxRetries int
Wait time.Duration
Err error
}
TxRetryEvent 描述一次事务死锁重试事件。
type TxRetryObserver ¶
type TxRetryObserver func(ctx context.Context, event TxRetryEvent)
TxRetryObserver 在每次事务重试等待前被调用,用于观测重试事件(如记录日志、上报指标)。
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package paginator 提供基于 GORM 的通用分页查询执行器。
|
Package paginator 提供基于 GORM 的通用分页查询执行器。 |
|
Package zlogger 提供基于 zap 的 GORM 日志适配器, 实现 gorm.io/gorm/logger 的 Interface,支持慢查询阈值、 日志级别、忽略 ErrRecordNotFound、参数化 SQL 以及 trace ID 关联等配置。
|
Package zlogger 提供基于 zap 的 GORM 日志适配器, 实现 gorm.io/gorm/logger 的 Interface,支持慢查询阈值、 日志级别、忽略 ErrRecordNotFound、参数化 SQL 以及 trace ID 关联等配置。 |