Documentation
¶
Overview ¶
Package ormx 提供基于 GORM 的企业级 MySQL 数据访问封装: 连接管理、集群读写分离、健康探活、事务死锁自动重试与写后读一致性窗口。
基本用法:
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.WithTx 执行,遇 MySQL 死锁(1213)或锁等待超时(1205) 自动按带抖动的指数退避重试。
读写分离由 Cluster 提供:写请求路由主库,读请求在健康副本间轮询; 写入后用 ContextWithWriteWindow 打写标记,可在时间窗口内保证写后读一致性。
Client 与 Cluster 均并发安全,可在多个 goroutine 间共享。 GORM 的 zap 日志适配见子包 zlogger。
Index ¶
- Constants
- Variables
- func ContextClearWriteFlag(ctx context.Context) context.Context
- func ContextWithWriteFlag(ctx context.Context) context.Context
- func ContextWithWriteWindow(ctx context.Context, ttl time.Duration) context.Context
- func HasWriteFlag(ctx context.Context) bool
- 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) Metrics() []MetricSample
- func (c *Client) Name() string
- func (c *Client) PingContext(ctx context.Context) error
- func (c *Client) SQLDB() *sql.DB
- func (c *Client) Stats() sql.DBStats
- func (c *Client) StatsSnapshot() DBStatsSnapshot
- 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 Cluster
- func NewCluster(primary *Client, replicas ...*Client) (*Cluster, error)
- func NewClusterWithOptions(primary *Client, replicas []*Client, opts ...ClusterOption) (*Cluster, error)
- func OpenCluster(ctx context.Context, primary Config, replicas ...Config) (*Cluster, error)
- func OpenClusterWithOptions(ctx context.Context, primary Config, replicas []Config, opts ...ClusterOption) (_ *Cluster, err error)
- func (c *Cluster) Close() error
- func (c *Cluster) DrainReplica(name string, cause error) error
- func (c *Cluster) HealthCheck(ctx context.Context) ClusterHealthReport
- func (c *Cluster) MarkPrimaryDown(cause error) error
- func (c *Cluster) Metrics() []MetricSample
- func (c *Cluster) MustReadDB() *gorm.DB
- func (c *Cluster) MustWriteDB() *gorm.DB
- func (c *Cluster) Nodes() []Node
- func (c *Cluster) Primary() *Client
- func (c *Cluster) PrimaryNode() Node
- func (c *Cluster) ReadDB() *gorm.DBdeprecated
- func (c *Cluster) ReadDBCtx(ctx context.Context) *gorm.DBdeprecated
- func (c *Cluster) Reader() *Client
- func (c *Cluster) ReaderClient() (*Client, error)
- func (c *Cluster) ReaderClientCtx(ctx context.Context) (*Client, error)
- func (c *Cluster) RecoverReplica(ctx context.Context, name string) error
- func (c *Cluster) Refresh(ctx context.Context) ClusterHealthReport
- func (c *Cluster) ReplicaNodes() []Node
- func (c *Cluster) RunHealthLoop(ctx context.Context, interval time.Duration) error
- func (c *Cluster) SwitchPrimary(ctx context.Context, name string) (Node, error)
- func (c *Cluster) WithReadTx(ctx context.Context, fn func(tx *gorm.DB) error) error
- func (c *Cluster) WithTx(ctx context.Context, fn func(tx *gorm.DB) error, txOpts ...TxOption) error
- func (c *Cluster) WriteClient() (*Client, error)
- func (c *Cluster) WriteDB() *gorm.DBdeprecated
- type ClusterHealthReport
- type ClusterOption
- type Config
- func (c Config) Clone() Config
- func (c Config) DriverConfig() (*mysqldriver.Config, error)
- 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 MetricSample
- type MySQLConfig
- type MySQLDialectConfig
- type Node
- func (n Node) Client() *Client
- func (n Node) HealthCheck(ctx context.Context) HealthReport
- func (n Node) Healthy() bool
- func (n Node) LastError() error
- func (n Node) Metrics() []MetricSample
- func (n Node) Name() string
- func (n Node) Role() NodeRole
- func (n Node) State() NodeState
- func (n Node) UpdatedAt() time.Time
- type NodeRole
- type NodeState
- type Option
- func WithAddress(addr 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 WithDSNParam(key, value string) Option
- func WithDSNParams(params map[string]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 WithDriverName(name string) 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 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
- type PoolConfig
- type TxOption
- type TxRetryEvent
- type TxRetryObserver
Examples ¶
Constants ¶
const ( HealthStatusUp HealthStatus = "up" HealthStatusDown HealthStatus = "down" HealthStatusDegraded HealthStatus = "degraded" RoleStandalone NodeRole = "standalone" RolePrimary NodeRole = "primary" RoleReplica NodeRole = "replica" NodeStateReady NodeState = "ready" NodeStateDraining NodeState = "draining" NodeStateDown NodeState = "down" )
健康状态(HealthStatus)、节点角色(NodeRole)与节点状态(NodeState)的预定义枚举值。
const Version = "v1.1.2"
Version 是 ormx 当前发布的版本号。
Variables ¶
var ( // ErrNoReadableNode 表示没有可用的读节点:所有副本均不可读, // 且回退主库被关闭或主库也不可读。 ErrNoReadableNode = errors.New("ormx: no readable node available") ErrPrimaryUnavailable = errors.New("ormx: primary unavailable") // ErrClusterClosed 表示集群已关闭,不再接受任何操作。 ErrClusterClosed = errors.New("ormx: cluster is closed") )
集群路由的可判断错误,调用方可用 errors.Is 区分失败类型。
Functions ¶
func ContextClearWriteFlag ¶
ContextClearWriteFlag 清除 ctx 携带的写标记。
func ContextWithWriteFlag ¶
ContextWithWriteFlag 在 ctx 上打写标记,表示刚发生过一次写入。 带该标记的 ctx 传给 Cluster.ReaderClientCtx 或 Cluster.ReadDBCtx 时, 读请求会被路由到主库而非副本,保证写后读一致性。
典型用法:写入成功后立即调用,本次请求内的后续读操作复用返回的 ctx。
ctx = ormx.ContextWithWriteFlag(ctx) // 之后经 ReaderClientCtx(ctx) 的读请求会命中主库
func ContextWithWriteWindow ¶
ContextWithWriteWindow 在 ctx 上打带时限的写标记:ttl 内读请求路由主库, ttl 过后 HasWriteFlag 返回 false,读请求自动恢复走副本; ttl ≤ 0 等价于清除写标记。
func HasWriteFlag ¶
HasWriteFlag 报告 ctx 是否携带仍然有效的写标记 (由 ContextWithWriteFlag 或 ContextWithWriteWindow 设置)。
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 封装单个数据库连接,持有 GORM 实例与底层 *sql.DB。 Client 并发安全,可在多个 goroutine 间共享。
func OpenWithDB ¶
OpenWithDB 包装既有的 *sql.DB:GORM 初始化前会把 opts 中的连接池设置应用到 sqlDB。 无论成败,sqlDB 的所有权始终归调用方(Client.Close 不会关闭它)。
func (*Client) HealthCheck ¶
func (c *Client) HealthCheck(ctx context.Context) HealthReport
HealthCheck 以 RoleStandalone 角色执行一次健康检查(Ping 加可选的 HealthProbe)并返回报告。 当 ctx 未设置 deadline 时使用内置默认超时,避免无限阻塞。
func (*Client) Metrics ¶
func (c *Client) Metrics() []MetricSample
Metrics 返回连接池的指标采样列表,标签含客户端名称与 RoleStandalone 角色。
func (*Client) PingContext ¶
PingContext 检测数据库连接是否可用。
func (*Client) StatsSnapshot ¶
func (c *Client) StatsSnapshot() DBStatsSnapshot
StatsSnapshot 返回当前连接池统计信息的快照。
func (*Client) WithReadTx ¶
WithReadTx 在只读事务中执行 fn,重试行为与 WithTx 的默认值一致。
type Cluster ¶
type Cluster struct {
// contains filtered or unexported fields
}
Cluster 管理一主多副本的数据库节点拓扑,提供读写分离路由、 健康检查、副本摘除/恢复与主库切换能力。 所有方法并发安全(内部由 RWMutex 保护)。
func NewCluster ¶
NewCluster 用已有的主库与副本客户端构建 Cluster。 等价于使用默认选项调用 NewClusterWithOptions。
func NewClusterWithOptions ¶
func NewClusterWithOptions(primary *Client, replicas []*Client, opts ...ClusterOption) (*Cluster, error)
NewClusterWithOptions 用已有客户端与选项构建 Cluster。 primary 不能为 nil;副本不能为 nil 且节点名不能重复,否则返回错误。
func OpenCluster ¶
OpenCluster 按给定配置打开主库与各副本连接,并构建 Cluster。 等价于使用默认选项调用 OpenClusterWithOptions。
func OpenClusterWithOptions ¶
func OpenClusterWithOptions( ctx context.Context, primary Config, replicas []Config, opts ...ClusterOption, ) (_ *Cluster, err error)
OpenClusterWithOptions 按给定配置打开主库连接,并行打开所有副本连接, 再按选项构建 Cluster。任一连接打开失败时会关闭已打开的连接并返回错误。
func (*Cluster) DrainReplica ¶
DrainReplica 把指定名称的副本置为 draining 状态,将其从读流量中摘除; cause 记录为该节点的最近错误。副本不存在或集群已关闭时返回错误。
注意:draining 不是长期粘性状态。若该副本随后探活失败被 Refresh 置为 down, 待其探活恢复且开启 autoRecoverReplicas 时会被自动拉回 ready、重新接收读流量, 摘除意图即告失效——维护窗口内节点重启(Ping 短暂失败)恰好会触发这一路径。 需要长期摘除时,请在运维侧暂停健康循环(停止 RunHealthLoop / 不再调用 Refresh), 或在节点恢复后重新调用 DrainReplica。
func (*Cluster) HealthCheck ¶
func (c *Cluster) HealthCheck(ctx context.Context) ClusterHealthReport
HealthCheck 并行探活所有节点并返回集群健康报告; 该方法只读,不修改任何节点状态。
func (*Cluster) MarkPrimaryDown ¶
MarkPrimaryDown 将当前主库标记为 down。 注意:如果后续调用 Refresh() 且主库 Ping 恢复成功,状态会自动回到 Ready。 如果你的目标是长期隔离主库,请在运维侧同时停止健康循环或避免继续触发 Refresh()。
func (*Cluster) MustReadDB ¶
MustReadDB 返回副本 *gorm.DB,没有可读节点时 panic。 仅适用于可接受 panic 的场景(如启动期 wiring)。
func (*Cluster) MustWriteDB ¶
MustWriteDB 返回主库 *gorm.DB,不可用时 panic。 仅适用于可接受 panic 的场景(如启动期 wiring)。
func (*Cluster) PrimaryNode ¶
PrimaryNode 返回当前主库节点的快照;主库不存在时返回零值 Node。
func (*Cluster) ReaderClient ¶
ReaderClient 按轮询(round-robin)从 ready 状态的副本中选出一个读客户端; 没有可用副本且开启 readFallbackToPrimary 时回退到主库, 否则返回 ErrNoReadableNode。
func (*Cluster) ReaderClientCtx ¶
ReaderClientCtx 返回读客户端,并感知 ctx 中的写标记: ctx 带有效写标记(ContextWithWriteFlag)时路由到主库,保证写后读一致性。
func (*Cluster) RecoverReplica ¶
RecoverReplica 对指定名称的副本执行 Ping 探活: 成功则恢复为 ready 重新接收读流量,失败则置为 down 并返回探活错误。 副本不存在或集群已关闭时返回错误。
func (*Cluster) Refresh ¶
func (c *Cluster) Refresh(ctx context.Context) ClusterHealthReport
Refresh 并行探活所有节点并据此更新节点状态: 探活失败的节点置为 down;主库探活成功时恢复为 ready; 开启 autoRecoverReplicas 时,down 状态的副本探活成功后自动恢复为 ready。 返回更新后的集群健康报告。
func (*Cluster) RunHealthLoop ¶
RunHealthLoop 按 interval 周期性刷新集群健康状态(调用 Refresh),直到 ctx 取消; interval ≤ 0 时返回错误。由调用方自起 goroutine,以掌控退出语义。
func (*Cluster) SwitchPrimary ¶
SwitchPrimary 切换主库节点。 注意:如果后续调用 Refresh() 且主库 Ping 恢复成功,状态会自动回到 Ready。 如果你的目标是长期隔离主库,请在运维侧同时停止健康循环或避免继续触发 Refresh()。
注意:如果目标节点已经是主节点,则只做连通性确认; 如果目标节点是副本节点,则把它提升为主节点。
func (*Cluster) WithReadTx ¶
WithReadTx 在按 ReaderClientCtx 路由选出的读节点上执行只读事务函数 fn; ctx 携带写标记时会路由到主库,没有可读节点时返回错误。
func (*Cluster) WriteClient ¶
WriteClient 返回用于写操作的主库客户端; 集群已关闭或主库不可用(不存在或处于 down 状态)时返回错误。
type ClusterHealthReport ¶
type ClusterHealthReport struct {
Status HealthStatus
CheckedAt time.Time
Nodes []HealthReport
}
ClusterHealthReport 描述一次集群健康检查的整体结果, 包含集群级状态、检查时间和各节点的健康报告。
func (ClusterHealthReport) Healthy ¶
func (r ClusterHealthReport) Healthy() bool
Healthy 报告集群整体状态是否为 HealthStatusUp。
type ClusterOption ¶
type ClusterOption func(*clusterOptions)
ClusterOption 用于在构建 Cluster 时定制集群行为的函数式选项。
func WithAutoRecoverReplicas ¶
func WithAutoRecoverReplicas(enabled bool) ClusterOption
WithAutoRecoverReplicas 设置 Refresh 探活成功时是否自动把 down 状态的副本恢复为 ready。 默认开启。
func WithHealthCheckTimeout ¶
func WithHealthCheckTimeout(timeout time.Duration) ClusterOption
WithHealthCheckTimeout 设置健康检查 Ping 的默认超时; 调用方 context 已带更短 deadline 时以后者优先。默认 5s。
func WithReadFallbackToPrimary ¶
func WithReadFallbackToPrimary(enabled bool) ClusterOption
WithReadFallbackToPrimary 设置当没有可用副本时读请求是否回退到主库。 默认开启。
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
}
Config 汇总建立 MySQL 连接所需的全部配置:驱动连接参数(MySQL)、 连接池(Pool)、GORM 行为(GORM)、方言(Dialect)以及启动期 Ping 重试策略。 Config 为值语义,可安全复制;通过 With 应用 Option 会返回新副本,不修改原值。 字段全部导出以便从配置文件直接映射,但直接修改字段会绕过 Option 的防御逻辑, 合法性由调用方自行保证;优先使用 Option 构建配置。 注意:从配置文件映射时必须以 DefaultConfig()(或 NewConfig)的返回值为基底再覆盖字段; 对零值 Config 直接反序列化会缺少 Pool 各字段的"已设置"标记,连接池配置将被静默忽略。
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) DriverConfig ¶
func (c Config) DriverConfig() (*mysqldriver.Config, error)
DriverConfig 根据 MySQL 连接配置生成 go-sql-driver/mysql 的 *mysqldriver.Config, 配置非法(如缺少必填项或参数校验失败)时返回错误。
func (Config) Open ¶
Open 按当前配置构建 MySQL 连接器并打开 *sql.DB,应用连接池配置后初始化 GORM, 返回拥有该 *sql.DB 所有权的 Client(Close 时会一并关闭)。 若 StartupPing 开启,会先按重试策略 Ping 数据库;任一步骤失败时关闭已打开的连接并返回错误。
func (Config) OpenWithDB ¶
OpenWithDB 包装既有的 *sql.DB:GORM 初始化前会把 Config.Pool 的连接池设置应用到 sqlDB。 无论成败,sqlDB 的所有权始终归调用方(Client.Close 不会关闭它)。
func (Config) RedactedDSN ¶
RedactedDSN 返回密码脱敏后的 DSN 字符串:密码非空时替换为 "******", 可安全用于日志输出;底层 DriverConfig 构建失败时返回错误。
func (Config) With ¶
With 返回应用 opts 后的 Config 副本,原 Config 不受影响;nil Option 会被跳过。
Example ¶
Config 是值语义:With 返回应用新 Option 后的副本,原配置不受影响。
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
Role NodeRole
State NodeState
Status HealthStatus
CheckedAt time.Time
Duration time.Duration
Error error
Stats DBStatsSnapshot
}
HealthReport 描述一次健康检查的结果。
func (HealthReport) Healthy ¶
func (r HealthReport) Healthy() bool
Healthy 报告本次检查状态是否为 HealthStatusUp。
type MetricSample ¶
MetricSample 表示一条带标签的指标采样。
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"`
Params map[string]string `json:"params" yaml:"params"`
ConnectionAttributes string `json:"connection_attributes" yaml:"connection_attributes"`
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 优先。 建议通过 Option 辅助函数设置,以保证 Addr/Host/Port 的优先级语义一致。
type MySQLDialectConfig ¶
type MySQLDialectConfig struct {
DriverName string
ServerVersion string
DefaultStringSize uint
DefaultDatetimePrecision *int
SkipInitializeWithVersion bool
DisableWithReturning bool
DisableDatetimePrecision bool
DontSupportRenameIndex bool
DontSupportRenameColumn bool
DontSupportNullAsDefaultValue bool
DontSupportRenameColumnUnique bool
DontSupportDropConstraint bool
}
MySQLDialectConfig 描述透传给 GORM MySQL 方言(gorm.io/driver/mysql)的配置, 字段与其 Config 中的同名字段一一对应。
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node 是集群节点在某一时刻的不可变快照, 包含节点名称、角色、客户端、状态、最近错误及状态更新时间。
func (Node) HealthCheck ¶
func (n Node) HealthCheck(ctx context.Context) HealthReport
HealthCheck 对该节点执行一次探活,并结合快照中的节点状态修饰健康报告后返回。
type Option ¶
type Option func(*Config)
Option 是修改 Config 的函数式配置项,配合 NewConfig、Open 等入口使用。
func WithAddress ¶
WithAddress 设置完整连接地址(如 "127.0.0.1:3306"); Addr 非空时优先于 Host/Port 生效。
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 WithDSNParam ¶
WithDSNParam 设置单个额外的 DSN 连接参数; Params 为 nil 时自动初始化,同名 key 会被覆盖。
func WithDSNParams ¶
WithDSNParams 批量合并额外的 DSN 连接参数,同名 key 会被覆盖; 传入 nil 或空 map 时不做任何修改。
func WithDefaultContextTimeout ¶
WithDefaultContextTimeout 设置 GORM 操作的默认 context 超时时间。
func WithDefaultStringSize ¶
WithDefaultStringSize 设置 string 类型字段建表时的默认长度。
func WithDefaultTransactionTimeout ¶
WithDefaultTransactionTimeout 设置 GORM 事务的默认超时时间。
func WithDisableDatetimePrecision ¶
WithDisableDatetimePrecision 设置是否禁用 datetime 字段的精度支持。
func WithDisableWithReturning ¶
WithDisableWithReturning 设置是否禁用方言的 RETURNING 子句支持。
func WithDriverName ¶
WithDriverName 设置 GORM MySQL 方言使用的底层 SQL 驱动名。
func WithGormLogger ¶
func WithGormLogger(log gormlogger.Interface) Option
WithGormLogger 设置 GORM 使用的日志实现。
func WithHealthProbe ¶
func WithHealthProbe(probe HealthProbeFunc) Option
WithHealthProbe 设置自定义健康探针;健康检查在 Ping 成功后调用该探针, 探针返回错误则判定为不健康。
func WithLocation ¶
WithLocation 设置解析时间值使用的时区。默认 time.Local。
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"。
func WithNowFunc ¶
WithNowFunc 设置 GORM 生成时间戳时使用的当前时间函数。
func WithParseTime ¶
WithParseTime 设置是否将 DATE/DATETIME 列解析为 time.Time。默认开启。
func WithPrepareStmt ¶
WithPrepareStmt 设置 GORM 是否缓存预编译语句以提升后续执行性能。
func WithPrepareStmtCache ¶
WithPrepareStmtCache 设置预编译语句缓存的最大条数 maxSize 与存活时间 ttl。
func WithQueryFields ¶
WithQueryFields 设置查询时是否按模型字段名逐列展开 SELECT,而非 SELECT *。
func WithReadTimeout ¶
WithReadTimeout 设置 I/O 读超时时间。默认 30s。
func WithServerVersion ¶
WithServerVersion 手动指定 MySQL 服务端版本号,供方言据此调整行为。
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 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。
type PoolConfig ¶
type PoolConfig struct {
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
ConnMaxIdleTime time.Duration
// contains filtered or unexported fields
}
PoolConfig 描述 *sql.DB 连接池参数。 每个字段仅在通过 DefaultConfig 或对应 Option 显式设置后才会应用到连接池, 未设置的字段保持 database/sql 的原有行为。
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 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 关联等配置。 |