Documentation
¶
Overview ¶
Package database provides a GORM-based database component with connection pooling, health checks, transactions, and migration support.
Architecture ¶
The database module follows gokit's component pattern with a driver-agnostic design. Users provide the database driver (postgres, mysql, sqlite, etc.) via WithDriver(), keeping the module lightweight and flexible.
Quick Start ¶
Bootstrap the database component in your application:
import (
"github.com/kbukum/gokit/bootstrap"
"github.com/kbukum/gokit/database"
"gorm.io/driver/postgres"
)
func main() {
app := bootstrap.New()
cfg := database.Config{Enabled: true, DSN: "host=localhost user=myuser password=mypass dbname=mydb"}
app.Register(database.NewComponent(cfg, log).
WithDriver(func(dsn string) gorm.Dialector {
return postgres.Open(dsn)
}))
app.Start(context.Background())
}
Subpackages ¶
- errors: Database error utilities and translation to AppError
- types: Common database types like BaseModel
- migration: File-based database migrations using golang-migrate
- query: Advanced query builders and helpers
- testutil: Testing utilities for database-dependent tests
Optional Component ¶
The database component respects the Enabled flag in configuration. When disabled, Start() returns immediately without initializing the connection, and Health() reports "disabled" status.
cfg := database.Config{Enabled: false} // Component will be disabled
See component.go for full lifecycle documentation.
Index ¶
- type Component
- func (c *Component) DB() *DB
- func (c *Component) Describe() component.Description
- func (c *Component) Health(ctx context.Context) component.Health
- func (c *Component) Name() string
- func (c *Component) Start(ctx context.Context) error
- func (c *Component) Stop(_ context.Context) error
- func (c *Component) WithAutoMigrate(models ...interface{}) *Component
- func (c *Component) WithDriver(fn DriverFunc) *Component
- type Config
- type DB
- func (d *DB) AutoMigrate(models ...interface{}) error
- func (d *DB) Close() error
- func (db *DB) IsAvailable(ctx context.Context) bool
- func (db *DB) Name() string
- func (d *DB) Ping() error
- func (d *DB) PingContext(ctx context.Context) error
- func (d *DB) Transaction(fn func(*gorm.DB) error) error
- func (d *DB) WithContext(ctx context.Context) *gorm.DB
- func (d *DB) WithReadOnlyTransaction(ctx context.Context, fn TransactionFunc) error
- func (d *DB) WithTransaction(ctx context.Context, fn TransactionFunc) error
- type DriverFunc
- type TransactionFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Component ¶
type Component struct {
// contains filtered or unexported fields
}
Component wraps DB and implements component.Component for lifecycle management.
func NewComponent ¶
NewComponent creates a database component for use with the component registry. By default, SQLite is used. Call WithDriver to specify a different database. The Config.Enabled flag can be used to skip initialization at runtime.
func (*Component) Describe ¶
func (c *Component) Describe() component.Description
Describe returns infrastructure summary info for the bootstrap display.
func (*Component) Health ¶
Health returns the current health status of the database. If Config.Enabled is false, returns StatusHealthy with "disabled" message. The context is used for the ping operation and honors cancellation.
func (*Component) Start ¶
Start connects to the database and optionally runs auto-migration. If Config.Enabled is false, this method returns immediately without error. The context is used for connection retries and can be canceled to abort startup.
func (*Component) WithAutoMigrate ¶
WithAutoMigrate registers models for auto-migration on Start. Models are only migrated if Config.AutoMigrate is true and the component is enabled.
func (*Component) WithDriver ¶
func (c *Component) WithDriver(fn DriverFunc) *Component
WithDriver sets the database driver function. Pass the Open function from your chosen driver (not the result of calling it).
Example:
import "gorm.io/driver/postgres" db := database.NewComponent(cfg, log).
WithDriver(postgres.Open).
WithAutoMigrate(&User{}, &Post{})
If not set, SQLite is used as the default driver (useful for tests).
type Config ¶
type Config struct {
// Name identifies this adapter instance (used by provider.Provider interface).
Name string `yaml:"name" mapstructure:"name"`
// Enabled controls whether the database component is active.
Enabled bool `yaml:"enabled" mapstructure:"enabled"`
// DSN is the database connection string.
DSN string `yaml:"dsn" mapstructure:"dsn"`
// MaxOpenConns sets the maximum number of open connections to the database.
MaxOpenConns int `yaml:"max_open_conns" mapstructure:"max_open_conns"`
// MaxIdleConns sets the maximum number of idle connections in the pool.
MaxIdleConns int `yaml:"max_idle_conns" mapstructure:"max_idle_conns"`
// ConnMaxLifetime is the maximum time a connection may be reused (e.g. "1h", "30m").
ConnMaxLifetime string `yaml:"conn_max_lifetime" mapstructure:"conn_max_lifetime"`
// ConnMaxIdleTime is the maximum time a connection may sit idle (e.g. "5m", "10m").
// If empty, no idle timeout is set.
ConnMaxIdleTime string `yaml:"conn_max_idle_time" mapstructure:"conn_max_idle_time"`
// MaxRetries is the number of connection attempts before giving up.
MaxRetries int `yaml:"max_retries" mapstructure:"max_retries"`
// AutoMigrate controls whether GORM auto-migration runs on startup.
AutoMigrate bool `yaml:"auto_migrate" mapstructure:"auto_migrate"`
// SlowQueryThreshold is the duration above which queries are logged as slow (e.g. "200ms").
SlowQueryThreshold string `yaml:"slow_query_threshold" mapstructure:"slow_query_threshold"`
// LogLevel controls GORM's log verbosity: "silent", "error", "warn", "info" (default).
LogLevel string `yaml:"log_level" mapstructure:"log_level"`
}
Config holds database connection configuration.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets sensible defaults for zero-valued fields.
type DB ¶
DB wraps a GORM database with gokit logging.
func New ¶
New opens a database connection with retry logic and connection pooling. For most use cases, use Component instead which provides driver flexibility via WithDriver().
func NewWithContext ¶
func NewWithContext(ctx context.Context, dialector interface{}, cfg Config, log *logger.Logger) (*DB, error)
NewWithContext creates a database connection with context-aware retry logic. The context allows cancellation of connection attempts during retries.
func (*DB) AutoMigrate ¶
AutoMigrate runs GORM auto-migration for the given models.
func (*DB) IsAvailable ¶
IsAvailable checks if the database connection is healthy (implements provider.Provider).
func (*DB) PingContext ¶
PingContext verifies the database connection is alive, respecting the context.
func (*DB) Transaction ¶
Transaction executes fn inside a database transaction.
func (*DB) WithContext ¶
WithContext returns a GORM session scoped to the given context.
func (*DB) WithReadOnlyTransaction ¶
func (d *DB) WithReadOnlyTransaction(ctx context.Context, fn TransactionFunc) error
WithReadOnlyTransaction executes fn in a read-only transaction (always rolls back).
func (*DB) WithTransaction ¶
func (d *DB) WithTransaction(ctx context.Context, fn TransactionFunc) error
WithTransaction executes fn within a transaction with panic recovery.
type DriverFunc ¶
DriverFunc is a factory function that creates a GORM dialector. Standard GORM drivers (postgres.Open, mysql.Open, sqlite.Open) all match this signature.
type TransactionFunc ¶
TransactionFunc defines a function that runs within a transaction.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package errors provides database error utilities and translation to gokit AppError types for consistent error handling.
|
Package errors provides database error utilities and translation to gokit AppError types for consistent error handling. |
|
Package migration provides file-based database migration utilities for GORM.
|
Package migration provides file-based database migration utilities for GORM. |
|
Package query provides a PostgREST-style query builder for GORM with pagination, sorting, filtering, facets, and eager-loading support.
|
Package query provides a PostgREST-style query builder for GORM with pagination, sorting, filtering, facets, and eager-loading support. |
|
Package types provides common database types and models used across database operations.
|
Package types provides common database types and models used across database operations. |