database

package
v0.0.0-...-1db6227 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 20 Imported by: 1

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

Constants

This section is empty.

Variables

View Source
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

func IsDuplicateKeyError(err error) bool

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]) DB

func (r *BaseRepository[T]) DB() *gorm.DB

Get database instance

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]) Paginate

func (r *BaseRepository[T]) Paginate(ctx context.Context, page, pageSize int) ([]T, int64, error)

Paginate query

func (*BaseRepository[T]) Transaction

func (r *BaseRepository[T]) Transaction(ctx context.Context, fn func(tx *gorm.DB) error) error

Transaction execution

func (*BaseRepository[T]) Update

func (r *BaseRepository[T]) Update(ctx context.Context, entity *T) error

Update record

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

func DefaultConfig

func DefaultConfig() Config

Return the default configuration

func (*Config) Validate

func (c *Config) Validate() error

Validate configuration

type DBMetrics

type DBMetrics struct {
	// contains filtered or unexported fields
}

DBMetrics database layer metrics collector

func NewDBMetrics

func NewDBMetrics(db *gorm.DB, recordSQLText bool, slowQueryThreshold float64) (*DBMetrics, error)

NewDBMetrics creates a database metrics collector

func (*DBMetrics) GORMPlugin

func (m *DBMetrics) GORMPlugin() gorm.Plugin

GORMPlugin returns the GORM plugin (for registering callbacks)

type DialectorFactory

type DialectorFactory func(dsn string) gorm.Dialector

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

func (*HealthChecker) Check

func (h *HealthChecker) Check(ctx context.Context) error

Check execution health check

func (*HealthChecker) Name

func (h *HealthChecker) Name() string

Name Check item name

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) Close

func (m *Manager) Close() error

Close all database connections

func (*Manager) DB

func (m *Manager) DB(name string) *gorm.DB

English: Get specified database instance

func (*Manager) GetDBNames

func (m *Manager) GetDBNames() []string

GetDBNames Retrieve all database instance names

func (*Manager) Ping

func (m *Manager) Ping() error

Ping check all database connections

func (*Manager) SetMetricsPlugin

func (m *Manager) SetMetricsPlugin(dbName string, dbMetrics *DBMetrics) error

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

func (*Manager) Shutdown

func (m *Manager) Shutdown() error

Implement the samber/do.Shutdownable interface for shutdown functionality For automatically closing database connections when the DI container shuts down

func (*Manager) Stats

func (m *Manager) Stats(name string) (sql.DBStats, error)

Get database connection pool statistics

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) Name

func (p *OtelPlugin) Name() string

Name Plugin Name

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

Directories

Path Synopsis
本文件把 SQLite 方言作为可选能力注册到 framework database.Manager。
本文件把 SQLite 方言作为可选能力注册到 framework database.Manager。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL