Documentation
¶
Index ¶
- Constants
- Variables
- func IsConnectionError(err error) bool
- func IsValidLogLevel(level string) bool
- func IsValidationError(err error) bool
- func NewGormLogger(l SimpleLogger, logLevel string) logger.Interface
- type Config
- type Connector
- type ContextualLogger
- type DB
- type Database
- func (d *Database) AutoMigrate(dst ...interface{}) error
- func (d *Database) BeginTx(ctx context.Context, opts ...*sql.TxOptions) (*gorm.DB, error)
- func (d *Database) Close() error
- func (d *Database) CloseWithContext(ctx context.Context) error
- func (d *Database) Exec(ctx context.Context, query string, args ...interface{}) error
- func (d *Database) GetConfig() Config
- func (d *Database) GetDB() *gorm.DB
- func (d *Database) GetDriver() string
- func (d *Database) HealthCheck() error
- func (d *Database) HealthCheckWithContext(ctx context.Context) *HealthStatus
- func (d *Database) IsConnected() bool
- func (d *Database) IsReadOnly() bool
- func (d *Database) Ping() error
- func (d *Database) Query(ctx context.Context, dest interface{}, query string, args ...interface{}) error
- func (d *Database) Raw() *gorm.DB
- func (d *Database) SQLDB() (*sql.DB, error)
- func (d *Database) Stats() PoolStats
- func (d *Database) Transaction(fn func(*gorm.DB) error) error
- func (d *Database) TransactionWithContext(ctx context.Context, fn func(*gorm.DB) error) error
- func (d *Database) Tx(ctx context.Context, fn func(tx *gorm.DB) error, opts ...*sql.TxOptions) error
- func (d *Database) WithContext(ctx context.Context) *gorm.DB
- type DatabaseError
- type ErrorType
- type Executor
- type GORMLogger
- func (g *GORMLogger) Error(ctx context.Context, msg string, data ...interface{})
- func (g *GORMLogger) Info(ctx context.Context, msg string, data ...interface{})
- func (g *GORMLogger) LogMode(l logger.LogLevel) logger.Interface
- func (g *GORMLogger) Trace(ctx context.Context, begin time.Time, ...)
- func (g *GORMLogger) Warn(ctx context.Context, msg string, data ...interface{})
- type HealthChecker
- type HealthStatus
- type Hooks
- type Option
- type PoolConfigurator
- type PoolStats
- type SimpleLogger
Constants ¶
const ( DefaultMaxIdleConns = 10 DefaultMaxOpenConns = 100 DefaultConnMaxLifetime = time.Hour DefaultConnMaxIdleTime = 10 * time.Minute DefaultSlowThreshold = time.Second DefaultLogLevel = "silent" DefaultCharset = "utf8mb4" DefaultTimezone = "Local" DefaultPostgresSSLMode = "disable" DefaultPostgresTimezone = "UTC" // 重试配置默认值 DefaultRetryMaxAttempts = 3 DefaultRetryInitialDelay = 1 * time.Second DefaultRetryMaxDelay = 30 * time.Second DefaultRetryBackoffFactor = 2.0 DefaultRetryJitterEnabled = true MaxRetryAttempts = 100 )
默认配置常量
Variables ¶
var ( ErrMissingDriver = errors.New("数据库驱动不能为空") ErrUnsupportedDriver = errors.New("不支持的数据库驱动") ErrMissingHost = errors.New("数据库主机不能为空") ErrInvalidPort = errors.New("数据库端口无效") ErrMissingUsername = errors.New("数据库用户名不能为空") ErrMissingDatabase = errors.New("数据库名不能为空") ErrMissingDBPath = errors.New("SQLite数据库路径不能为空") ErrInvalidLogLevel = errors.New("无效的日志级别") ErrInvalidCharset = errors.New("无效的字符集") ErrInvalidSSLMode = errors.New("无效的SSL模式") ErrInvalidConnPool = errors.New("连接池配置无效") ErrInvalidTimeout = errors.New("超时配置无效") ErrConnectionFailed = errors.New("数据库连接失败") ErrTransactionFailed = errors.New("事务执行失败") ErrQueryFailed = errors.New("查询执行失败") ErrMigrationFailed = errors.New("数据库迁移失败") )
预定义错误
Functions ¶
func NewGormLogger ¶
func NewGormLogger(l SimpleLogger, logLevel string) logger.Interface
NewGormLogger 构造函数
- l: 你的 zap / logrus / zerolog ... 实例
- level: GORM 日志级别,不想打印 SQL 就传 logger.Silent
Types ¶
type Config ¶
type Config struct {
// 基础连接配置
Driver string `mapstructure:"driver" json:"driver" yaml:"driver"`
Host string `mapstructure:"host" json:"host" yaml:"host"`
Port int `mapstructure:"port" json:"port" yaml:"port"`
Username string `mapstructure:"username" json:"username" yaml:"username"`
Password string `mapstructure:"password" json:"password" yaml:"password"`
Database string `mapstructure:"database" json:"database" yaml:"database"`
Charset string `mapstructure:"charset" json:"charset" yaml:"charset"`
SSLMode string `mapstructure:"ssl_mode" json:"ssl_mode" yaml:"ssl_mode"`
Timezone string `mapstructure:"timezone" json:"timezone" yaml:"timezone"`
// 连接池配置
MaxIdleConns int `mapstructure:"max_idle_conns" json:"max_idle_conns" yaml:"max_idle_conns"`
MaxOpenConns int `mapstructure:"max_open_conns" json:"max_open_conns" yaml:"max_open_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime" json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time" json:"conn_max_idle_time" yaml:"conn_max_idle_time"`
// GORM日志配置
CustomLogger logger.Interface `mapstructure:"-" json:"-" yaml:"-"`
LogLevel string `mapstructure:"log_level" json:"log_level" yaml:"log_level"`
SlowThreshold time.Duration `mapstructure:"slow_threshold" json:"slow_threshold" yaml:"slow_threshold"`
IgnoreRecordNotFoundError bool `mapstructure:"ignore_record_not_found_error" json:"ignore_record_not_found_error" yaml:"ignore_record_not_found_error"`
ParameterizedQueries bool `mapstructure:"parameterized_queries" json:"parameterized_queries" yaml:"parameterized_queries"`
Colorful bool `mapstructure:"colorful" json:"colorful" yaml:"colorful"`
// 连接重试配置
RetryMaxAttempts int `mapstructure:"retry_max_attempts" json:"retry_max_attempts" yaml:"retry_max_attempts"`
RetryInitialDelay time.Duration `mapstructure:"retry_initial_delay" json:"retry_initial_delay" yaml:"retry_initial_delay"`
RetryMaxDelay time.Duration `mapstructure:"retry_max_delay" json:"retry_max_delay" yaml:"retry_max_delay"`
RetryBackoffFactor float64 `mapstructure:"retry_backoff_factor" json:"retry_backoff_factor" yaml:"retry_backoff_factor"`
RetryJitterEnabled bool `mapstructure:"retry_jitter_enabled" json:"retry_jitter_enabled" yaml:"retry_jitter_enabled"`
RetryEnabled bool `mapstructure:"retry_enabled" json:"retry_enabled" yaml:"retry_enabled"`
// 其他配置
TablePrefix string `mapstructure:"table_prefix" json:"table_prefix" yaml:"table_prefix"`
SingularTable bool `mapstructure:"singular_table" json:"singular_table" yaml:"singular_table"`
DisableForeignKey bool `mapstructure:"disable_foreign_key" json:"disable_foreign_key" yaml:"disable_foreign_key"`
PrepareStmt bool `mapstructure:"prepare_stmt" json:"prepare_stmt" yaml:"prepare_stmt"`
DryRun bool `mapstructure:"dry_run" json:"dry_run" yaml:"dry_run"`
}
Config 数据库配置
func (*Config) SetCustomLogger ¶
func (c *Config) SetCustomLogger(l SimpleLogger, level string)
SetCustomLogger 允许在 Config 层设置 GORM 日志实现,便于与外部 logger 对齐。
type ContextualLogger ¶
type ContextualLogger interface {
SimpleLogger
InfoWithContext(ctx context.Context, msg string, fields ...interface{})
WarnWithContext(ctx context.Context, msg string, fields ...interface{})
ErrorWithContext(ctx context.Context, msg string, fields ...interface{})
}
ContextualLogger 定义支持Context的日志接口
type DB ¶ added in v1.1.0
type DB interface {
// Exec 执行写操作,适用于 INSERT/UPDATE/DELETE 等语句。
Exec(ctx context.Context, query string, args ...interface{}) error
// Query 执行查询并将结果扫描到 dest。
Query(ctx context.Context, dest interface{}, query string, args ...interface{}) error
// Tx 启动事务并在回调中执行业务逻辑,支持传入可选的 sql.TxOptions。
Tx(ctx context.Context, fn func(tx *gorm.DB) error, opts ...*sql.TxOptions) error
// Raw 返回底层 *gorm.DB 以支持少数无法封装的高级用法(请谨慎使用)。
Raw() *gorm.DB
// SQLDB 返回底层 *sql.DB,便于执行需要专用连接的场景(如 PostgreSQL LISTEN/NOTIFY、
// 使用特定扩展或 Driver 原生能力)。调用方负责确保合理的生命周期管理。
SQLDB() (*sql.DB, error)
}
DB 定义对外暴露的最小能力集合,便于业务代码依赖接口而非具体实现。
绝大多数场景建议通过这些方法完成常规操作;若确需底层能力,可使用 Raw() 受控地获取底层 *gorm.DB。
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database 数据库管理器,组合 Connector、Executor、HealthChecker 等职责。
func NewWithOptions ¶ added in v1.1.0
NewWithOptions 支持通过可选参数注入日志、钩子或自定义组件。
func (*Database) AutoMigrate ¶
AutoMigrate 自动迁移数据库表
func (*Database) CloseWithContext ¶ added in v1.1.0
CloseWithContext 允许调用方传入上下文,配合生命周期钩子完成优雅关闭。
func (*Database) HealthCheckWithContext ¶
func (d *Database) HealthCheckWithContext(ctx context.Context) *HealthStatus
HealthCheckWithContext 带Context的健康检查
func (*Database) Query ¶ added in v1.1.0
func (d *Database) Query(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Query 执行查询
func (*Database) Transaction ¶
Transaction 事务便利方法,自动处理提交和回滚
func (*Database) TransactionWithContext ¶
TransactionWithContext 带Context的事务便利方法
type DatabaseError ¶
type DatabaseError struct {
Type ErrorType
Operation string
Err error
Context map[string]interface{}
}
DatabaseError 数据库错误结构
func NewDatabaseError ¶
func NewDatabaseError(errorType ErrorType, operation string, err error) *DatabaseError
NewDatabaseError 创建数据库错误
func (*DatabaseError) WithContext ¶
func (e *DatabaseError) WithContext(key string, value interface{}) *DatabaseError
WithContext 添加错误上下文
type Executor ¶ added in v1.1.0
type Executor interface {
Exec(ctx context.Context, query string, args ...interface{}) error
Query(ctx context.Context, dest interface{}, query string, args ...interface{}) error
Tx(ctx context.Context, fn func(tx *gorm.DB) error, opts ...*sql.TxOptions) error
BeginTx(ctx context.Context, opts ...*sql.TxOptions) (*gorm.DB, error)
}
Executor 承载常规执行能力,便于与连接/健康检查解耦。
type GORMLogger ¶
type GORMLogger struct {
// contains filtered or unexported fields
}
GORMLogger 把任意 SimpleLogger 转成 gorm.logger.Interface
func (*GORMLogger) Error ¶
func (g *GORMLogger) Error(ctx context.Context, msg string, data ...interface{})
Error 实现logger.Interface
func (*GORMLogger) Info ¶
func (g *GORMLogger) Info(ctx context.Context, msg string, data ...interface{})
Info 实现logger.Interface
func (*GORMLogger) LogMode ¶
func (g *GORMLogger) LogMode(l logger.LogLevel) logger.Interface
LogMode 实现接口
type HealthChecker ¶ added in v1.1.0
type HealthChecker interface {
Ping() error
HealthCheck() error
HealthCheckWithContext(ctx context.Context) *HealthStatus
}
HealthChecker 定义健康探测接口,支持 context 取消。
type HealthStatus ¶
type HealthStatus struct {
Healthy bool `json:"healthy"`
Timestamp time.Time `json:"timestamp"`
Driver string `json:"driver"`
Errors []string `json:"errors,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Stats PoolStats `json:"stats"`
}
HealthStatus 健康检查状态
type Hooks ¶ added in v1.1.0
type Hooks struct {
BeforeConnect func(cfg *Config)
AfterConnect func(db *gorm.DB)
BeforeClose func(ctx context.Context, db *gorm.DB) error
AfterClose func(ctx context.Context, closeErr error)
BeforeProbe func(ctx context.Context) error
AfterProbe func(ctx context.Context, probeErr error)
}
Hooks 定义生命周期扩展点,便于调用方在关键节点插入自定义逻辑。
type Option ¶ added in v1.1.0
type Option func(*Database)
Option 允许在构建 Database 时注入可选配置,例如 Logger、Hooks 等。
func WithConnector ¶ added in v1.1.0
Option helpers for custom components
func WithExecutor ¶ added in v1.1.0
func WithHealthChecker ¶ added in v1.1.0
func WithHealthChecker(healthChecker HealthChecker) Option
func WithLogger ¶ added in v1.1.0
func WithLogger(l SimpleLogger) Option
WithLogger 设置用于启动、重试和健康检查日志的 SimpleLogger。
type PoolConfigurator ¶ added in v1.1.0
PoolConfigurator 允许对底层 *sql.DB 进行池参数配置。
type PoolStats ¶
type PoolStats struct {
OpenConnections int
IdleConnections int
WaitCount int64
WaitDuration time.Duration
MaxIdleClosed int64
MaxLifetimeClosed int64
}
PoolStats 连接池统计信息
type SimpleLogger ¶
type SimpleLogger interface {
Info(msg string, fields ...interface{})
Warn(msg string, fields ...interface{})
Error(msg string, fields ...interface{})
}
SimpleLogger 定义基础日志接口