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 ContextualLogger
- type Database
- func (d *Database) AutoMigrate(dst ...interface{}) error
- func (d *Database) Close() 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) 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) WithContext(ctx context.Context) *gorm.DB
- type DatabaseError
- type ErrorType
- 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 HealthStatus
- type PoolStats
- type SimpleLogger
Constants ¶
View Source
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 )
默认配置常量
Variables ¶
View Source
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 (d *Config) SetCustomLogger(l SimpleLogger, level string)
SetLogger 设置自定义日志记录器
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 Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database 数据库管理器
func (*Database) AutoMigrate ¶
AutoMigrate 自动迁移数据库表
func (*Database) HealthCheckWithContext ¶
func (d *Database) HealthCheckWithContext(ctx context.Context) *HealthStatus
HealthCheckWithContext 带Context的健康检查
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 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 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 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 定义基础日志接口
Click to show internal directories.
Click to hide internal directories.