Documentation
¶
Overview ¶
Package database provides connection management, migrations, foreign key handling, SQL initialization, configuration types, logging, health checks, and related utilities built on top of Bun.
Index ¶
- func CloseDB() error
- func EnableBunSqlSilent(b bool)
- func GetDB() *bun.DB
- func InitDB(cfg *Config) (*bun.DB, error)
- func InitData() error
- func InitDataWithSQL(environment string) error
- func InitDatabaseWithOptions(cfg *Config, runMigrations bool) (*bun.DB, error)
- func InitLogger(log Logger)
- func RegisteredModel(instance interface{}, priority int)
- func RegisteredModelInstances() []interface{}
- func RegisteredSQlModel(model SQLModel)
- func RunMigrations() error
- type AbstractDatabaseConfigProvider
- type AbstractDatabaseManager
- type BaseDatabaseFactory
- func (f *BaseDatabaseFactory) Close() error
- func (f *BaseDatabaseFactory) CreateFromConfig(cfg *ConnectionConfig) (AbstractDatabaseManager, error)
- func (f *BaseDatabaseFactory) GetDB() *bun.DB
- func (f *BaseDatabaseFactory) GetHealthStatus(ctx context.Context) *HealthStatus
- func (f *BaseDatabaseFactory) GetManager() AbstractDatabaseManager
- func (f *BaseDatabaseFactory) GetStats() *DBStats
- func (f *BaseDatabaseFactory) InitializeDatabase(ctx context.Context, runMigrations bool) error
- func (f *BaseDatabaseFactory) SetLogger(logger Logger)
- type Config
- type ConfigurableForeignKeyManager
- type ConnectionConfig
- type DBStats
- type DataInitConfig
- type DataMigrateConfig
- type DefaultLogger
- func (l *DefaultLogger) Debug(msg string, fields ...interface{})
- func (l *DefaultLogger) Error(msg string, fields ...interface{})
- func (l *DefaultLogger) Info(msg string, fields ...interface{})
- func (l *DefaultLogger) SetLevel(level LogLevel)
- func (l *DefaultLogger) Warn(msg string, fields ...interface{})
- type ExecutionResult
- type ForeignKeyConfig
- type ForeignKeyConstraint
- type ForeignKeyConstraintConfig
- type ForeignKeyManager
- func (fkm *ForeignKeyManager) AddAllForeignKeys(ctx context.Context, db bun.IDB) error
- func (fkm *ForeignKeyManager) GetConstraintsByTable(tableName string) []ForeignKeyConstraint
- func (fkm *ForeignKeyManager) ListAllConstraints() []ForeignKeyConstraint
- func (fkm *ForeignKeyManager) RemoveForeignKey(ctx context.Context, db bun.IDB, tableName, constraintName string) error
- func (fkm *ForeignKeyManager) ValidateConstraints() []error
- type HealthStatus
- type LogLevel
- type Logger
- type Migration
- type MigrationFunc
- type MigrationItem
- type MigrationManager
- func (mm *MigrationManager) GetAppliedMigrations(ctx context.Context) ([]Migration, error)
- func (mm *MigrationManager) InitData(ctx context.Context) error
- func (mm *MigrationManager) InvalidateSchemaMetadataCaches()
- func (mm *MigrationManager) RefreshSchemaMetadataForTables(ctx context.Context, db bun.IDB, tables []string) error
- func (mm *MigrationManager) RollbackMigration(ctx context.Context, version string) error
- func (mm *MigrationManager) RunMigrations(ctx context.Context) error
- func (mm *MigrationManager) SetEnvironment(env string)
- func (mm *MigrationManager) SynchronizeSchema(ctx context.Context, db bun.IDB) error
- type ModelAdapter
- type ModelRegistry
- type QueryHook
- type SQLError
- type SQLFileInfo
- type SQLInitManager
- func (s *SQLInitManager) ExecuteFile(file SQLFileInfo) ExecutionResult
- func (s *SQLInitManager) ExecuteInitialization() error
- func (s *SQLInitManager) GetExecutionHistory() ([]ExecutionResult, error)
- func (s *SQLInitManager) GetSQLFiles() ([]SQLFileInfo, error)
- func (s *SQLInitManager) SetSQLRootPath(path string)
- type SQLModel
- type SlowQueryHook
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CloseDB ¶
func CloseDB() error
CloseDB closes the global database connection (backward compatibility).
func EnableBunSqlSilent ¶
func EnableBunSqlSilent(b bool)
func InitData ¶
func InitData() error
InitData seeds initial data using the configured environment (backward compatibility).
func InitDataWithSQL ¶
InitDataWithSQL seeds initial data by executing SQL files for the environment.
func InitDatabaseWithOptions ¶
InitDatabaseWithOptions initializes the database and optionally runs migrations.
func InitLogger ¶
func InitLogger(log Logger)
func RegisteredModel ¶
func RegisteredModel(instance interface{}, priority int)
RegisteredModel adds a instance to the default registry.
func RegisteredModelInstances ¶
func RegisteredModelInstances() []interface{}
func RegisteredSQlModel ¶
func RegisteredSQlModel(model SQLModel)
RegisteredSQlModel adds a model to the default registry.
func RunMigrations ¶
func RunMigrations() error
RunMigrations executes database migrations (backward compatibility).
Types ¶
type AbstractDatabaseConfigProvider ¶
type AbstractDatabaseConfigProvider interface {
ConfigLoader() *Config
}
AbstractDatabaseConfigProvider exposes configuration loading.
type AbstractDatabaseManager ¶
type AbstractDatabaseManager interface {
Connect(ctx context.Context) error
Disconnect() error
Reconnect(ctx context.Context) error
Ping(ctx context.Context) error
HealthCheck(ctx context.Context) *HealthStatus
GetDB() *bun.DB
GetSQLDB() *sql.DB
RunMigrations(ctx context.Context) error
InitData(ctx context.Context) error
GetStats() *DBStats
SetLogger(logger Logger)
}
AbstractDatabaseManager defines the operations for managing a database connection, running migrations, initializing data, and reporting health.
func GetDatabaseManager ¶
func GetDatabaseManager() AbstractDatabaseManager
GetDatabaseManager returns the global database manager.
func NewDatabaseManager ¶
func NewDatabaseManager(config *ConnectionConfig) AbstractDatabaseManager
type BaseDatabaseFactory ¶
type BaseDatabaseFactory struct {
// contains filtered or unexported fields
}
BaseDatabaseFactory creates and manages a configured database manager and provides helpers for initialization, health checks, and statistics.
func GetDatabaseFactory ¶
func GetDatabaseFactory() *BaseDatabaseFactory
GetDatabaseFactory returns the global database factory.
func NewDatabaseFactory ¶
func NewDatabaseFactory() *BaseDatabaseFactory
NewDatabaseFactory returns a new database factory using the global logger.
func (*BaseDatabaseFactory) Close ¶
func (f *BaseDatabaseFactory) Close() error
Close closes the database connection managed by the factory.
func (*BaseDatabaseFactory) CreateFromConfig ¶
func (f *BaseDatabaseFactory) CreateFromConfig(cfg *ConnectionConfig) (AbstractDatabaseManager, error)
CreateFromConfig constructs a database manager from the given connection configuration, applying environment overrides and setting the factory logger.
func (*BaseDatabaseFactory) GetDB ¶
func (f *BaseDatabaseFactory) GetDB() *bun.DB
GetDB returns the Bun database instance, or nil if not initialized.
func (*BaseDatabaseFactory) GetHealthStatus ¶
func (f *BaseDatabaseFactory) GetHealthStatus(ctx context.Context) *HealthStatus
GetHealthStatus returns the current database health status from the manager.
func (*BaseDatabaseFactory) GetManager ¶
func (f *BaseDatabaseFactory) GetManager() AbstractDatabaseManager
GetManager returns the underlying database manager.
func (*BaseDatabaseFactory) GetStats ¶
func (f *BaseDatabaseFactory) GetStats() *DBStats
GetStats returns database connection statistics from the manager.
func (*BaseDatabaseFactory) InitializeDatabase ¶
func (f *BaseDatabaseFactory) InitializeDatabase(ctx context.Context, runMigrations bool) error
InitializeDatabase connects to the database and optionally runs migrations.
func (*BaseDatabaseFactory) SetLogger ¶
func (f *BaseDatabaseFactory) SetLogger(logger Logger)
SetLogger sets the logger on the factory and the underlying manager.
type Config ¶
type Config struct {
ConnectionConfig ConnectionConfig `json:"connection_config"`
DataMigrateConfig DataMigrateConfig `json:"data_migrate_config"`
DataInitConfig DataInitConfig `json:"data_init_config"`
}
Config aggregates connection, migration, and data initialization settings.
type ConfigurableForeignKeyManager ¶
type ConfigurableForeignKeyManager struct {
*ForeignKeyManager
// contains filtered or unexported fields
}
ConfigurableForeignKeyManager loads foreign key constraints from a YAML configuration file and falls back to code-defined defaults.
func NewConfigurableForeignKeyManager ¶
func NewConfigurableForeignKeyManager(logger Logger, configPath string) (*ConfigurableForeignKeyManager, error)
NewConfigurableForeignKeyManager creates a foreign key manager using the provided YAML configuration file path.
func (*ConfigurableForeignKeyManager) ExportToConfig ¶
func (cfm *ConfigurableForeignKeyManager) ExportToConfig(outputPath string) error
func (*ConfigurableForeignKeyManager) GetConfigPath ¶
func (cfm *ConfigurableForeignKeyManager) GetConfigPath() string
func (*ConfigurableForeignKeyManager) ReloadConfig ¶
func (cfm *ConfigurableForeignKeyManager) ReloadConfig() error
type ConnectionConfig ¶
type ConnectionConfig struct {
Type string `json:"type"` // postgres、mysql、sqlite
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
DBName string `json:"dbname"`
SSLMode string `json:"sslmode"`
MaxIdleConns int `json:"max_idle_conns"`
MaxOpenConns int `json:"max_open_conns"`
ConnMaxLifetime time.Duration `json:"conn_max_lifetime"`
ConnMaxIdleTime time.Duration `json:"conn_max_idle_time"`
ConnectTimeout time.Duration `json:"connect_timeout"`
ReadTimeout time.Duration `json:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout"`
HealthCheckInterval time.Duration `json:"health_check_interval"`
EnableQueryLog bool `json:"enable_query_log"`
SlowQueryTime time.Duration `json:"slow_query_time"`
AutoCreate bool `json:"auto_create"`
Charset string `json:"charset"` // MySQL:utf8mb4 、Postgres:UTF8
Template string `json:"template"`
}
ConnectionConfig describes how to connect to a database and tune its pool.
func DefaultConnectionConfig ¶
func DefaultConnectionConfig() *ConnectionConfig
DefaultConnectionConfig returns a connection config with sensible defaults.
type DBStats ¶
type DBStats struct {
MaxOpenConns int `json:"max_open_conns"`
OpenConns int `json:"open_conns"`
InUse int `json:"in_use"`
Idle int `json:"idle"`
WaitCount int64 `json:"wait_count"`
WaitDuration time.Duration `json:"wait_duration"`
MaxIdleClosed int64 `json:"max_idle_closed"`
MaxIdleTimeClosed int64 `json:"max_idle_time_closed"`
MaxLifetimeClosed int64 `json:"max_lifetime_closed"`
}
DBStats mirrors database/sql stats returned by the manager.
func GetDatabaseStats ¶
func GetDatabaseStats() *DBStats
GetDatabaseStats returns global database statistics.
type DataInitConfig ¶
type DataInitConfig struct {
AutoInitOnStartup bool `json:"auto_init_on_startup"`
AutoInitOnMigration bool `json:"auto_init_on_migration"`
Filepath string `json:"filepath"`
Environment string `json:"environment"`
}
DataInitConfig controls data seeding behavior and environment selection.
type DataMigrateConfig ¶
type DataMigrateConfig struct {
EnableMigrateOnStartup bool `json:"enable_migrate_on_startup"`
EnableForeignKey bool `json:"enable_foreign_key"`
ForeignKeyFile string `json:"foreign_key_file"`
EnableSchemaSync bool `json:"enable_schema_sync"`
AllowColumnAdd bool `json:"allow_column_add"`
AllowColumnModify bool `json:"allow_column_modify"`
AllowColumnDrop bool `json:"allow_column_drop"`
AllowIndexAdd bool `json:"allow_index_add"`
AllowIndexDrop bool `json:"allow_index_drop"`
EnforceNotNullWithDefault bool `json:"enforce_not_null_with_default"`
SchemaMetaCacheTTL time.Duration `json:"schema_meta_cache_ttl"`
SchemaMetaCacheLoadOnce bool `json:"schema_meta_cache_load_once"`
SchemaMetaAuditLog bool `json:"schema_meta_audit_log"`
}
DataMigrateConfig controls schema migration behavior on startup.
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
func (*DefaultLogger) Debug ¶
func (l *DefaultLogger) Debug(msg string, fields ...interface{})
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(msg string, fields ...interface{})
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(msg string, fields ...interface{})
func (*DefaultLogger) SetLevel ¶
func (l *DefaultLogger) SetLevel(level LogLevel)
func (*DefaultLogger) Warn ¶
func (l *DefaultLogger) Warn(msg string, fields ...interface{})
type ExecutionResult ¶
type ExecutionResult struct {
File string
Success bool
Error error
Duration time.Duration
RowsAffected int64
}
ExecutionResult contains the outcome of executing a single SQL file.
type ForeignKeyConfig ¶
type ForeignKeyConfig struct {
ForeignKeys []ForeignKeyConstraintConfig `yaml:"foreign_keys"`
}
ForeignKeyConfig is the YAML structure that lists foreign key constraints.
type ForeignKeyConstraint ¶
type ForeignKeyConstraint struct {
Table string
Column string
ReferenceTable string
ReferenceColumn string
OnDelete string // CASCADE, RESTRICT, SET NULL, NO ACTION
OnUpdate string // CASCADE, RESTRICT, SET NULL, NO ACTION
ConstraintName string
}
ForeignKeyConstraint describes a foreign key relationship between tables.
func (*ForeignKeyConstraint) GenerateConstraintName ¶
func (fk *ForeignKeyConstraint) GenerateConstraintName() string
GenerateConstraintName returns the explicit name or a derived name.
func (*ForeignKeyConstraint) GenerateSQL ¶
func (fk *ForeignKeyConstraint) GenerateSQL() string
GenerateSQL returns the ALTER TABLE statement to add the constraint.
type ForeignKeyConstraintConfig ¶
type ForeignKeyConstraintConfig struct {
Table string `yaml:"table"`
Column string `yaml:"column"`
ReferenceTable string `yaml:"reference_table"`
ReferenceColumn string `yaml:"reference_column"`
OnDelete string `yaml:"on_delete"`
OnUpdate string `yaml:"on_update"`
ConstraintName string `yaml:"constraint_name"`
Description string `yaml:"description"`
}
ForeignKeyConstraintConfig describes a single foreign key in configuration.
func (*ForeignKeyConstraintConfig) ToForeignKeyConstraint ¶
func (fkc *ForeignKeyConstraintConfig) ToForeignKeyConstraint() ForeignKeyConstraint
ToForeignKeyConstraint converts the config entry into a runtime constraint.
type ForeignKeyManager ¶
type ForeignKeyManager struct {
// contains filtered or unexported fields
}
ForeignKeyManager manages adding and validating foreign key constraints.
func NewForeignKeyManager ¶
func NewForeignKeyManager(logger Logger) *ForeignKeyManager
NewForeignKeyManager creates a manager with code-defined constraints.
func (*ForeignKeyManager) AddAllForeignKeys ¶
AddAllForeignKeys iterates through all constraints and adds them to the DB.
func (*ForeignKeyManager) GetConstraintsByTable ¶
func (fkm *ForeignKeyManager) GetConstraintsByTable(tableName string) []ForeignKeyConstraint
GetConstraintsByTable returns the constraints defined for a table.
func (*ForeignKeyManager) ListAllConstraints ¶
func (fkm *ForeignKeyManager) ListAllConstraints() []ForeignKeyConstraint
ListAllConstraints returns all configured constraints.
func (*ForeignKeyManager) RemoveForeignKey ¶
func (fkm *ForeignKeyManager) RemoveForeignKey(ctx context.Context, db bun.IDB, tableName, constraintName string) error
RemoveForeignKey drops a named foreign key from a table.
func (*ForeignKeyManager) ValidateConstraints ¶
func (fkm *ForeignKeyManager) ValidateConstraints() []error
ValidateConstraints checks the configured constraints for common issues.
type HealthStatus ¶
type HealthStatus struct {
Healthy bool `json:"healthy"`
Connected bool `json:"connected"`
ResponseTime time.Duration `json:"response_time"`
ActiveConns int `json:"active_conns"`
IdleConns int `json:"idle_conns"`
MaxOpenConns int `json:"max_open_conns"`
LastError string `json:"last_error,omitempty"`
LastCheckTime time.Time `json:"last_check_time"`
}
HealthStatus holds the result of a health check against the database.
func GetHealthStatus ¶
func GetHealthStatus(ctx context.Context) *HealthStatus
GetHealthStatus returns the current database health status.
type Logger ¶
type MigrationItem ¶
type MigrationItem struct {
Version string
Name string
Description string
Up MigrationFunc
Down MigrationFunc
}
type MigrationManager ¶
type MigrationManager struct {
// contains filtered or unexported fields
}
func NewMigrationManager ¶
func NewMigrationManager(db *bun.DB, logger Logger) *MigrationManager
func (*MigrationManager) GetAppliedMigrations ¶
func (mm *MigrationManager) GetAppliedMigrations(ctx context.Context) ([]Migration, error)
func (*MigrationManager) InvalidateSchemaMetadataCaches ¶
func (mm *MigrationManager) InvalidateSchemaMetadataCaches()
func (*MigrationManager) RefreshSchemaMetadataForTables ¶
func (*MigrationManager) RollbackMigration ¶
func (mm *MigrationManager) RollbackMigration(ctx context.Context, version string) error
func (*MigrationManager) RunMigrations ¶
func (mm *MigrationManager) RunMigrations(ctx context.Context) error
func (*MigrationManager) SetEnvironment ¶
func (mm *MigrationManager) SetEnvironment(env string)
func (*MigrationManager) SynchronizeSchema ¶
type ModelAdapter ¶
type ModelAdapter struct {
// contains filtered or unexported fields
}
func (*ModelAdapter) Instance ¶
func (a *ModelAdapter) Instance() interface{}
Instance returns the underlying struct used for migrations/initialization.
func (*ModelAdapter) Priority ¶
func (a *ModelAdapter) Priority() int
Priority returns the model's ordering value; lower values run earlier.
type ModelRegistry ¶
ModelRegistry stores SQL models and exposes them in a deterministic order.
type QueryHook ¶
type QueryHook struct {
// contains filtered or unexported fields
}
func (*QueryHook) AfterQuery ¶
func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent)
func (*QueryHook) BeforeQuery ¶
type SQLFileInfo ¶
SQLFileInfo describes a SQL file to be executed during initialization.
type SQLInitManager ¶
type SQLInitManager struct {
// contains filtered or unexported fields
}
SQLInitManager discovers and executes SQL files to seed data.
func NewSQLInitManager ¶
func NewSQLInitManager(db *bun.DB, environment string) *SQLInitManager
NewSQLInitManager creates a SQL initializer for the given environment.
func (*SQLInitManager) ExecuteFile ¶
func (s *SQLInitManager) ExecuteFile(file SQLFileInfo) ExecutionResult
func (*SQLInitManager) ExecuteInitialization ¶
func (s *SQLInitManager) ExecuteInitialization() error
ExecuteInitialization runs all discovered SQL files in the correct order.
func (*SQLInitManager) GetExecutionHistory ¶
func (s *SQLInitManager) GetExecutionHistory() ([]ExecutionResult, error)
GetExecutionHistory returns past execution results if recorded.
func (*SQLInitManager) GetSQLFiles ¶
func (s *SQLInitManager) GetSQLFiles() ([]SQLFileInfo, error)
GetSQLFiles returns the list of SQL files from common and environment dirs.
func (*SQLInitManager) SetSQLRootPath ¶
func (s *SQLInitManager) SetSQLRootPath(path string)
SetSQLRootPath sets the root directory from which SQL files are loaded.
type SQLModel ¶
type SQLModel interface {
Instance() interface{}
Priority() int
}
SQLModel represents a database model used for automatic migration/initialization. Instance should return a struct pointer compatible with Bun, and Priority controls ordering when initializing models (lower values first).
func GetRegisteredModels ¶
func GetRegisteredModels() []SQLModel
GetRegisteredModels returns all models registered in the default registry sorted by ascending priority.
func NewModelAdapter ¶
NewModelAdapter wraps a struct instance and priority into an SQLModel.
type SlowQueryHook ¶
type SlowQueryHook struct {
// contains filtered or unexported fields
}
func (*SlowQueryHook) AfterQuery ¶
func (h *SlowQueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent)
func (*SlowQueryHook) BeforeQuery ¶
func (h *SlowQueryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context