database

package
v0.0.0-...-e143326 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2026 License: Apache-2.0 Imports: 25 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

View Source
const (
	LogLevelDebug = engine.LogLevelDebug
	LogLevelInfo  = engine.LogLevelInfo
	LogLevelWarn  = engine.LogLevelWarn
	LogLevelError = engine.LogLevelError

	UnknownErr                  = engine.UnknownErr
	NoRowsErr                   = engine.NoRowsErr
	NoIndexErr                  = engine.NoIndexErr
	NoColumnErr                 = engine.NoColumnErr
	ExistIndexErr               = engine.ExistIndexErr
	ExistColumnErr              = engine.ExistColumnErr
	NoTableErr                  = engine.NoTableErr
	ExistTableErr               = engine.ExistTableErr
	DuplicateKeyErr             = engine.DuplicateKeyErr
	NotNullViolationErr         = engine.NotNullViolationErr
	ForeignKeyViolationErr      = engine.ForeignKeyViolationErr
	CheckConstraintViolationErr = engine.CheckConstraintViolationErr
	DataTruncatedErr            = engine.DataTruncatedErr
	InvalidTypeCastErr          = engine.InvalidTypeCastErr
)
View Source
const (
	// TraceIDKey is the context key for trace ID.
	TraceIDKey contextKey = "trace_id"
	// RequestIDKey is the context key for request ID.
	RequestIDKey contextKey = "request_id"
	// UserIDKey is the context key for user ID.
	UserIDKey contextKey = "user_id"
)

Variables

View Source
var (
	// IsSqlError classifies a driver error into a portable SQLError.
	IsSqlError = engine.IsSqlError
	// DefaultConnectionConfig returns sensible connection defaults.
	DefaultConnectionConfig = engine.DefaultConnectionConfig
)

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 GetDatabaseType

func GetDatabaseType() string

GetDatabaseType returns the normalized database type for the current global config.

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 RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext extracts the request ID from context.

func RunMigrations

func RunMigrations() error

RunMigrations executes database migrations (backward compatibility).

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext extracts the trace ID from context.

func UserIDFromContext

func UserIDFromContext(ctx context.Context) string

UserIDFromContext extracts the user ID from context.

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID returns a new context with the given request ID.

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID returns a new context with the given trace ID.

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID returns a new context with the given user ID.

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" toml:"connection_config"`
	DataMigrateConfig DataMigrateConfig `json:"data_migrate_config" toml:"data_migrate_config"`
	DataInitConfig    DataInitConfig    `json:"data_init_config" toml:"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 = engine.ConnectionConfig

ConnectionConfig describes how to connect to a database.

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" toml:"auto_init_on_startup"`
	AutoInitOnMigration bool   `json:"auto_init_on_migration" toml:"auto_init_on_migration"`
	Filepath            string `json:"filepath" toml:"filepath"`
	Env                 string `json:"env" toml:"env"`
	Environment         string `json:"environment" toml:"environment"`
}

DataInitConfig controls data seeding behavior and environment selection.

func (DataInitConfig) ResolveEnvironment

func (c DataInitConfig) ResolveEnvironment() string

ResolveEnvironment returns the configured data initialization environment. Environment is kept as the long-form name for backward compatibility, while Env is the shorter alias for new configuration files.

type DataMigrateConfig

type DataMigrateConfig struct {
	EnableMigrateOnStartup    bool          `json:"enable_migrate_on_startup" toml:"enable_migrate_on_startup"`
	EnableForeignKey          bool          `json:"enable_foreign_key" toml:"enable_foreign_key"`
	ForeignKeyFile            string        `json:"foreign_key_file" toml:"foreign_key_file"`
	EnableSchemaSync          bool          `json:"enable_schema_sync" toml:"enable_schema_sync"`
	AllowColumnAdd            bool          `json:"allow_column_add" toml:"allow_column_add"`
	AllowColumnModify         bool          `json:"allow_column_modify" toml:"allow_column_modify"`
	AllowColumnDrop           bool          `json:"allow_column_drop" toml:"allow_column_drop"`
	AllowIndexAdd             bool          `json:"allow_index_add" toml:"allow_index_add"`
	AllowIndexDrop            bool          `json:"allow_index_drop" toml:"allow_index_drop"`
	EnforceNotNullWithDefault bool          `json:"enforce_not_null_with_default" toml:"enforce_not_null_with_default"`
	SchemaSyncDryRun          bool          `json:"schema_sync_dry_run" toml:"schema_sync_dry_run"`
	SchemaMetaCacheTTL        time.Duration `json:"schema_meta_cache_ttl" toml:"schema_meta_cache_ttl"`
	SchemaMetaCacheLoadOnce   bool          `json:"schema_meta_cache_load_once" toml:"schema_meta_cache_load_once"`
	SchemaMetaAuditLog        bool          `json:"schema_meta_audit_log" toml:"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(ctx context.Context, msg string, fields ...interface{})

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(ctx context.Context, msg string, fields ...interface{})

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(ctx context.Context, msg string, fields ...interface{})

func (*DefaultLogger) SetLevel

func (l *DefaultLogger) SetLevel(level LogLevel)

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(ctx context.Context, msg string, fields ...interface{})

type Engine

type Engine = engine.Engine

Engine is the public database capability surface.

func EngineForDB

func EngineForDB(db *bun.DB) Engine

EngineForDB resolves the engine backing a live bun.DB from its dialect.

func GetEngine

func GetEngine(dbType string) (Engine, error)

GetEngine returns the public engine capability surface for a database type.

func MustEngine

func MustEngine(dbType string) Engine

MustEngine is like GetEngine but panics for unknown database types.

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 = engine.LogLevel

LogLevel selects logging verbosity.

type Logger

type Logger = engine.Logger

Logger is the logging contract used across the package.

func GetLogger

func GetLogger() Logger

type Migration

type Migration = engine.Migration

Migration records one applied migration step.

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 NewMigrationManagerWithEngine

func NewMigrationManagerWithEngine(db *bun.DB, logger Logger, engine schemaEngine, cfg *Config) *MigrationManager

func (*MigrationManager) ApplySchemaSyncPlan

func (mm *MigrationManager) ApplySchemaSyncPlan(ctx context.Context, db bun.IDB, plan *SchemaSyncPlan) error

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

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

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

func (*QueryHook) SetColorEnabled

func (h *QueryHook) SetColorEnabled(enabled bool)

SetColorEnabled enables or disables colored output for the query hook.

type SQLError

type SQLError = engine.SQLError

SQLError classifies driver errors into portable categories.

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 SchemaSyncOpKind

type SchemaSyncOpKind string
const (
	SchemaSyncAddColumn    SchemaSyncOpKind = "add_column"
	SchemaSyncModifyColumn SchemaSyncOpKind = "modify_column"
	SchemaSyncDropColumn   SchemaSyncOpKind = "drop_column"
	SchemaSyncRenameColumn SchemaSyncOpKind = "rename_column"
	SchemaSyncAddIndex     SchemaSyncOpKind = "add_index"
	SchemaSyncDropIndex    SchemaSyncOpKind = "drop_index"
)

type SchemaSyncOperation

type SchemaSyncOperation struct {
	Table       string           `json:"table"`
	Kind        SchemaSyncOpKind `json:"kind"`
	Name        string           `json:"name"`
	FromName    string           `json:"from_name,omitempty"`
	SQL         string           `json:"sql"`
	Destructive bool             `json:"destructive"`
}

type SchemaSyncPlan

type SchemaSyncPlan struct {
	Engine      string                `json:"engine"`
	GeneratedAt time.Time             `json:"generated_at"`
	Tables      []SchemaSyncTablePlan `json:"tables"`
}

func (*SchemaSyncPlan) Empty

func (p *SchemaSyncPlan) Empty() bool

func (*SchemaSyncPlan) OperationCount

func (p *SchemaSyncPlan) OperationCount() int

type SchemaSyncTablePlan

type SchemaSyncTablePlan struct {
	Table      string                `json:"table"`
	Version    string                `json:"version"`
	Hash       string                `json:"hash"`
	PlanText   string                `json:"plan_text"`
	Operations []SchemaSyncOperation `json:"operations"`
}

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

func (*SlowQueryHook) SetColorEnabled

func (h *SlowQueryHook) SetColorEnabled(enabled bool)

SetColorEnabled enables or disables colored output for the slow query hook.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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