Documentation
¶
Overview ¶
Provides database management and Repository infrastructure
本文件管理 database.Manager 可用的 GORM 方言工厂。 MySQL 与 PostgreSQL 是框架内建生产驱动;SQLite 等可选驱动必须由消费方显式注册, 避免仅使用 MySQL 的生产二进制被迫编译 CGO 驱动。新增驱动时应提供独立注册包, 业务仓库只配置驱动名称,不应直接依赖 registry 内部状态。
本文件统一识别数据库唯一键冲突。 production Manager 会启用 GORM TranslateError,正常入口应得到 gorm.ErrDuplicatedKey; MySQL 1062 分支兼容调用方直接注入未开启翻译的 *gorm.DB。SQLite 测试必须开启 TranslateError,禁止在本包引用 go-sqlite3 的 CGO-only 错误类型。
本文件声明数据库公共 sentinel;驱动错误分类实现见 duplicate_key_error.go。 消费方应通过 errors.Is 判断这些稳定契约,不应识别驱动错误文案。
Index ¶
- Variables
- func IsDuplicateKeyError(err error) bool
- func RegisterDialector(name string, factory DialectorFactory) error
- type BaseRepository
- func (r *BaseRepository[T]) Count(ctx context.Context) (int64, error)
- func (r *BaseRepository[T]) Create(ctx context.Context, entity *T) error
- func (r *BaseRepository[T]) DB() *gorm.DB
- func (r *BaseRepository[T]) Delete(ctx context.Context, id interface{}) error
- func (r *BaseRepository[T]) Exists(ctx context.Context, id interface{}) (bool, error)
- func (r *BaseRepository[T]) FindAll(ctx context.Context) ([]T, error)
- func (r *BaseRepository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)
- func (r *BaseRepository[T]) Paginate(ctx context.Context, page, pageSize int) ([]T, int64, error)
- func (r *BaseRepository[T]) Transaction(ctx context.Context, fn func(tx *gorm.DB) error) error
- func (r *BaseRepository[T]) Update(ctx context.Context, entity *T) error
- type Config
- type DBMetrics
- type DialectorFactory
- type GormLoggerFactory
- type HealthChecker
- type Manager
- func (m *Manager) Close() error
- func (m *Manager) DB(name string) *gorm.DB
- func (m *Manager) GetDBNames() []string
- func (m *Manager) Ping() error
- func (m *Manager) SetMetricsPlugin(dbName string, dbMetrics *DBMetrics) error
- func (m *Manager) SetOtelPlugin(plugin *OtelPlugin) error
- func (m *Manager) Shutdown() error
- func (m *Manager) Stats(name string) (sql.DBStats, error)
- type OtelPlugin
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidConfig Invalid Configuration ErrInvalidConfig = errors.New("invalid database config") // ErrRecordNotFound Record not found ErrRecordNotFound = errors.New("record not found") // ErrDuplicateKey Primary key or unique key conflict ErrDuplicateKey = errors.New("duplicate key") // ErrConnectionFailed Connection failed ErrConnectionFailed = errors.New("database connection failed") )
Functions ¶
func IsDuplicateKeyError ¶
IsDuplicateKeyError 判断错误链是否表示唯一键冲突。
func RegisterDialector ¶
func RegisterDialector(name string, factory DialectorFactory) error
RegisterDialector 注册可选数据库方言。 同名驱动不允许覆盖,避免 import 顺序改变生产数据库实现。
Types ¶
type BaseRepository ¶
type BaseRepository[T any] struct { // contains filtered or unexported fields }
BaseRepository generic Repository base class
func NewBaseRepository ¶
func NewBaseRepository[T any](db *gorm.DB) *BaseRepository[T]
NewBaseRepository creates the base class for Repository
func (*BaseRepository[T]) Count ¶
func (r *BaseRepository[T]) Count(ctx context.Context) (int64, error)
Count Statistic record count
func (*BaseRepository[T]) Create ¶
func (r *BaseRepository[T]) Create(ctx context.Context, entity *T) error
Create record
func (*BaseRepository[T]) Delete ¶
func (r *BaseRepository[T]) Delete(ctx context.Context, id interface{}) error
Delete soft delete record
func (*BaseRepository[T]) Exists ¶
func (r *BaseRepository[T]) Exists(ctx context.Context, id interface{}) (bool, error)
Exists check if record exists
func (*BaseRepository[T]) FindAll ¶
func (r *BaseRepository[T]) FindAll(ctx context.Context) ([]T, error)
FindAll query all records
func (*BaseRepository[T]) FindByID ¶
func (r *BaseRepository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)
FindByID queries by ID (Laravel findOrFail style)
func (*BaseRepository[T]) Transaction ¶
Transaction execution
type Config ¶
type Config struct {
Driver string `mapstructure:"driver"` // Driver types: mysql, postgres, sqlite
DSN string `mapstructure:"dsn"` // data source name
MaxOpenConns int `mapstructure:"max_open_conns"` // Maximum number of open connections
MaxIdleConns int `mapstructure:"max_idle_conns"` // Maximum number of idle connections
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"` // Connection maximum lifetime (seconds)
EnableLog bool `mapstructure:"enable_log"` // Whether logging is enabled
SlowThreshold time.Duration `mapstructure:"slow_threshold"` // slow query threshold (milliseconds)
EnableAudit bool `mapstructure:"enable_audit"` // Whether to enable SQL auditing
// OpenTelemetry tracing configuration
TraceSQL bool `mapstructure:"trace_sql"` // Whether to log SQL statements in an OTel Span (default false)
TraceSQLMaxLen int `mapstructure:"trace_sql_max_len"` // SQL statement maximum length (default 1000)
}
Configuration database configuration
type DBMetrics ¶
type DBMetrics struct {
// contains filtered or unexported fields
}
DBMetrics database layer metrics collector
func NewDBMetrics ¶
NewDBMetrics creates a database metrics collector
func (*DBMetrics) GORMPlugin ¶
GORMPlugin returns the GORM plugin (for registering callbacks)
type DialectorFactory ¶
DialectorFactory 根据 DSN 创建 GORM 方言。
type GormLoggerFactory ¶
type GormLoggerFactory func(cfg Config) gormlogger.Interface
GormLoggerFactory GORM Logger factory function type
type HealthChecker ¶
type HealthChecker struct {
// contains filtered or unexported fields
}
HealthChecker database health checker
func NewHealthChecker ¶
func NewHealthChecker(manager *Manager) *HealthChecker
Create database health checker
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager database manager (supports multiple instances)
func NewManager ¶
func NewManager(configs map[string]Config, loggerFactory GormLoggerFactory, logger *logger.CtxZapLogger) (*Manager, error)
Create database manager configs: database configuration loggerFactory: GORM Logger factory function for creating custom loggers (dependency injection) logger: business loggger (injected CtxZapLogger instance, must not be nil)
func (*Manager) GetDBNames ¶
GetDBNames Retrieve all database instance names
func (*Manager) SetMetricsPlugin ¶
SetMetricsPlugin sets the Metrics Plugin for the specified database instance dbName: database instance name dbMetrics: Database metric collector
func (*Manager) SetOtelPlugin ¶
func (m *Manager) SetOtelPlugin(plugin *OtelPlugin) error
SetOtelPlugin Set OpenTelemetry plugin Note: Will re-register plugin to all existing database instances
type OtelPlugin ¶
type OtelPlugin struct {
// contains filtered or unexported fields
}
OtelPlugin GORM OpenTelemetry plugin
func NewOtelPlugin ¶
func NewOtelPlugin(tracerProvider trace.TracerProvider) *OtelPlugin
Create NewOtelPlugin for OpenTelemetry plugin If tracerProvider is nil, use the global TracerProvider
func (*OtelPlugin) Initialize ¶
func (p *OtelPlugin) Initialize(db *gorm.DB) error
Initialize plugin (register callbacks)
func (*OtelPlugin) WithSQLMaxLen ¶
func (p *OtelPlugin) WithSQLMaxLen(maxLen int) *OtelPlugin
WithSQLMaxLen sets the maximum length of SQL
func (*OtelPlugin) WithTraceSQL ¶
func (p *OtelPlugin) WithTraceSQL(enabled bool) *OtelPlugin
WithTraceSQL setting whether to record SQL statements
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
本文件把 SQLite 方言作为可选能力注册到 framework database.Manager。
|
本文件把 SQLite 方言作为可选能力注册到 framework database.Manager。 |