database

package
v0.0.0-...-91e0906 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

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

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 GetDB

func GetDB() *bun.DB

GetDB returns the global Bun database instance.

func InitDB

func InitDB(cfg *Config) (*bun.DB, error)

InitDB initializes the global database using the provided configuration.

func InitData

func InitData() error

InitData seeds initial data using the configured environment (backward compatibility).

func InitDataWithSQL

func InitDataWithSQL(environment string) error

InitDataWithSQL seeds initial data by executing SQL files for the environment.

func InitDatabaseWithOptions

func InitDatabaseWithOptions(cfg *Config, runMigrations bool) (*bun.DB, error)

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

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

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

func (fkm *ForeignKeyManager) AddAllForeignKeys(ctx context.Context, db bun.IDB) error

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 LogLevel

type LogLevel int
const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

func (LogLevel) String

func (l LogLevel) String() string

type Logger

type Logger interface {
	SetLevel(LogLevel)
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
}

func GetLogger

func GetLogger() Logger

type Migration

type Migration struct {
	bun.BaseModel `bun:"bun_migrations"`
	Version       string    `bun:"version,pk"`
	Name          string    `bun:"name"`
	AppliedAt     time.Time `bun:"applied_at"`
	Description   string    `bun:"description"`
}

type MigrationFunc

type MigrationFunc func(ctx context.Context, db bun.IDB) error

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

func (mm *MigrationManager) InitData(ctx context.Context) error

func (*MigrationManager) InvalidateSchemaMetadataCaches

func (mm *MigrationManager) InvalidateSchemaMetadataCaches()

func (*MigrationManager) RefreshSchemaMetadataForTables

func (mm *MigrationManager) RefreshSchemaMetadataForTables(ctx context.Context, db bun.IDB, tables []string) error

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

func (mm *MigrationManager) SynchronizeSchema(ctx context.Context, db bun.IDB) error

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

type ModelRegistry interface {
	Register(model SQLModel)
	Models() []SQLModel
}

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

func (h *QueryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context

type SQLError

type SQLError int
const (
	UnknownErr SQLError = iota
	NoRowsErr
	NoIndexErr
	NoColumnErr
	ExistIndexErr
	ExistColumnErr
	NoTableErr
	ExistTableErr
	DuplicateKeyErr
	NotNullViolationErr
	ForeignKeyViolationErr
	CheckConstraintViolationErr
	DataTruncatedErr
	InvalidTypeCastErr
)

func IsSqlError

func IsSqlError(err error) (is bool, sqlErr SQLError)

type SQLFileInfo

type SQLFileInfo struct {
	Path        string
	Name        string
	Order       int
	Environment string
	ModTime     time.Time
}

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

func NewModelAdapter(instance interface{}, priority int) SQLModel

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

Jump to

Keyboard shortcuts

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