Documentation
¶
Overview ¶
Package database provides unified database access with support for SQL (Postgres, MySQL, SQLite) and NoSQL (MongoDB) databases. It exposes native drivers for maximum flexibility while providing production-ready features like connection pooling, health checks, and observability.
Index ¶
- Variables
- func NewExtension(config Config) forge.Extension
- type Config
- type Database
- type DatabaseConfig
- type DatabaseManager
- func (m *DatabaseManager) CloseAll(ctx context.Context) error
- func (m *DatabaseManager) Get(name string) (Database, error)
- func (m *DatabaseManager) HealthCheckAll(ctx context.Context) map[string]HealthStatus
- func (m *DatabaseManager) List() []string
- func (m *DatabaseManager) Mongo(name string) (*mongo.Client, error)
- func (m *DatabaseManager) MongoDatabase(name string) (*MongoDatabase, error)
- func (m *DatabaseManager) OpenAll(ctx context.Context) error
- func (m *DatabaseManager) Register(name string, db Database) error
- func (m *DatabaseManager) SQL(name string) (*bun.DB, error)
- type DatabaseStats
- type DatabaseType
- type Extension
- func (e *Extension) Dependencies() []string
- func (e *Extension) Description() string
- func (e *Extension) Health(ctx context.Context) error
- func (e *Extension) Name() string
- func (e *Extension) Register(app forge.App) error
- func (e *Extension) Start(ctx context.Context) error
- func (e *Extension) Stop(ctx context.Context) error
- func (e *Extension) Version() string
- type HealthStatus
- type MigrationStatus
- type MongoDatabase
- func (d *MongoDatabase) Client() *mongo.Client
- func (d *MongoDatabase) Close(ctx context.Context) error
- func (d *MongoDatabase) Collection(name string) *mongo.Collection
- func (d *MongoDatabase) Database() *mongo.Database
- func (d *MongoDatabase) Driver() interface{}
- func (d *MongoDatabase) Health(ctx context.Context) HealthStatus
- func (d *MongoDatabase) Name() string
- func (d *MongoDatabase) Open(ctx context.Context) error
- func (d *MongoDatabase) Ping(ctx context.Context) error
- func (d *MongoDatabase) Stats() DatabaseStats
- func (d *MongoDatabase) Transaction(ctx context.Context, fn func(sessCtx mongo.SessionContext) error) error
- func (d *MongoDatabase) TransactionWithOptions(ctx context.Context, opts *options.TransactionOptions, ...) error
- func (d *MongoDatabase) Type() DatabaseType
- type QueryHook
- type SQLDatabase
- func (d *SQLDatabase) Bun() *bun.DB
- func (d *SQLDatabase) Close(ctx context.Context) error
- func (d *SQLDatabase) DB() *sql.DB
- func (d *SQLDatabase) Driver() interface{}
- func (d *SQLDatabase) Health(ctx context.Context) HealthStatus
- func (d *SQLDatabase) Name() string
- func (d *SQLDatabase) Open(ctx context.Context) error
- func (d *SQLDatabase) Ping(ctx context.Context) error
- func (d *SQLDatabase) Stats() DatabaseStats
- func (d *SQLDatabase) Transaction(ctx context.Context, fn func(tx bun.Tx) error) error
- func (d *SQLDatabase) TransactionWithOptions(ctx context.Context, opts *sql.TxOptions, fn func(tx bun.Tx) error) error
- func (d *SQLDatabase) Type() DatabaseType
Constants ¶
This section is empty.
Variables ¶
var ( // Configuration errors ErrNoDatabasesConfigured = errors.New("no databases configured") ErrInvalidDatabaseName = errors.New("invalid database name") ErrInvalidDatabaseType = errors.New("invalid database type") ErrInvalidDSN = errors.New("invalid DSN") ErrInvalidPoolConfig = errors.New("invalid connection pool configuration") // Runtime errors ErrDatabaseNotFound = errors.New("database not found") ErrDatabaseAlreadyExists = errors.New("database already exists") ErrDatabaseNotOpened = errors.New("database not opened") ErrInvalidDatabaseTypeOp = errors.New("invalid database type for operation") )
Functions ¶
func NewExtension ¶
NewExtension creates a new database extension
Types ¶
type Config ¶
type Config struct {
// List of database configurations
Databases []DatabaseConfig `yaml:"databases" json:"databases"`
// Default database name (first one if not specified)
Default string `yaml:"default" json:"default"`
}
Config is the configuration for the database extension
type Database ¶
type Database interface {
// Identity
Name() string
Type() DatabaseType
// Lifecycle
Open(ctx context.Context) error
Close(ctx context.Context) error
Ping(ctx context.Context) error
// Health
Health(ctx context.Context) HealthStatus
Stats() DatabaseStats
// Access to native driver/ORM
Driver() interface{}
}
Database represents a database connection
type DatabaseConfig ¶
type DatabaseConfig struct {
Name string `yaml:"name" json:"name"`
Type DatabaseType `yaml:"type" json:"type"`
DSN string `yaml:"dsn" json:"dsn"`
// Connection pool settings
MaxOpenConns int `yaml:"max_open_conns" json:"max_open_conns" default:"25"`
MaxIdleConns int `yaml:"max_idle_conns" json:"max_idle_conns" default:"5"`
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" json:"conn_max_lifetime" default:"5m"`
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time" json:"conn_max_idle_time" default:"5m"`
// Retry settings
MaxRetries int `yaml:"max_retries" json:"max_retries" default:"3"`
RetryDelay time.Duration `yaml:"retry_delay" json:"retry_delay" default:"1s"`
// Health check
HealthCheckInterval time.Duration `yaml:"health_check_interval" json:"health_check_interval" default:"30s"`
// Additional config (database-specific)
Config map[string]interface{} `yaml:"config" json:"config"`
}
DatabaseConfig is the configuration for a database connection
type DatabaseManager ¶
type DatabaseManager struct {
// contains filtered or unexported fields
}
DatabaseManager manages multiple database connections
func NewDatabaseManager ¶
func NewDatabaseManager(logger forge.Logger, metrics forge.Metrics) *DatabaseManager
NewDatabaseManager creates a new database manager
func (*DatabaseManager) CloseAll ¶
func (m *DatabaseManager) CloseAll(ctx context.Context) error
CloseAll closes all registered databases
func (*DatabaseManager) Get ¶
func (m *DatabaseManager) Get(name string) (Database, error)
Get retrieves a database by name
func (*DatabaseManager) HealthCheckAll ¶
func (m *DatabaseManager) HealthCheckAll(ctx context.Context) map[string]HealthStatus
HealthCheckAll performs health checks on all databases
func (*DatabaseManager) List ¶
func (m *DatabaseManager) List() []string
List returns the names of all registered databases
func (*DatabaseManager) Mongo ¶
func (m *DatabaseManager) Mongo(name string) (*mongo.Client, error)
Mongo retrieves a MongoDB client by name
func (*DatabaseManager) MongoDatabase ¶
func (m *DatabaseManager) MongoDatabase(name string) (*MongoDatabase, error)
MongoDatabase retrieves a MongoDB database wrapper by name
func (*DatabaseManager) OpenAll ¶
func (m *DatabaseManager) OpenAll(ctx context.Context) error
OpenAll opens all registered databases
type DatabaseStats ¶
type DatabaseStats struct {
OpenConnections int `json:"open_connections"`
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"`
MaxLifetimeClosed int64 `json:"max_lifetime_closed"`
}
DatabaseStats provides connection pool statistics
type DatabaseType ¶
type DatabaseType string
DatabaseType represents the type of database
const ( TypePostgres DatabaseType = "postgres" TypeMySQL DatabaseType = "mysql" TypeSQLite DatabaseType = "sqlite" TypeMongoDB DatabaseType = "mongodb" TypeRedis DatabaseType = "redis" )
type Extension ¶
type Extension struct {
// contains filtered or unexported fields
}
Extension implements the database extension
func (*Extension) Dependencies ¶
Dependencies returns the list of extension dependencies
func (*Extension) Description ¶
Description returns the extension description
type HealthStatus ¶
type HealthStatus struct {
Healthy bool `json:"healthy"`
Message string `json:"message"`
Latency time.Duration `json:"latency"`
CheckedAt time.Time `json:"checked_at"`
}
HealthStatus provides database health status
type MigrationStatus ¶
type MigrationStatus struct {
ID int64 `json:"id"`
Applied bool `json:"applied"`
AppliedAt time.Time `json:"applied_at"`
}
MigrationStatus provides migration status
type MongoDatabase ¶
type MongoDatabase struct {
// contains filtered or unexported fields
}
MongoDatabase wraps MongoDB client
func NewMongoDatabase ¶
func NewMongoDatabase(config DatabaseConfig, logger forge.Logger, metrics forge.Metrics) (*MongoDatabase, error)
NewMongoDatabase creates a new MongoDB database instance
func (*MongoDatabase) Client ¶
func (d *MongoDatabase) Client() *mongo.Client
Client returns the MongoDB client
func (*MongoDatabase) Close ¶
func (d *MongoDatabase) Close(ctx context.Context) error
Close closes the MongoDB connection
func (*MongoDatabase) Collection ¶
func (d *MongoDatabase) Collection(name string) *mongo.Collection
Collection returns a MongoDB collection
func (*MongoDatabase) Database ¶
func (d *MongoDatabase) Database() *mongo.Database
Database returns the MongoDB database
func (*MongoDatabase) Driver ¶
func (d *MongoDatabase) Driver() interface{}
Driver returns the *mongo.Client for native driver access
func (*MongoDatabase) Health ¶
func (d *MongoDatabase) Health(ctx context.Context) HealthStatus
Health returns the health status
func (*MongoDatabase) Open ¶
func (d *MongoDatabase) Open(ctx context.Context) error
Open establishes the MongoDB connection
func (*MongoDatabase) Ping ¶
func (d *MongoDatabase) Ping(ctx context.Context) error
Ping checks MongoDB connectivity
func (*MongoDatabase) Stats ¶
func (d *MongoDatabase) Stats() DatabaseStats
Stats returns MongoDB statistics
func (*MongoDatabase) Transaction ¶
func (d *MongoDatabase) Transaction(ctx context.Context, fn func(sessCtx mongo.SessionContext) error) error
Transaction executes a function in a MongoDB transaction
func (*MongoDatabase) TransactionWithOptions ¶
func (d *MongoDatabase) TransactionWithOptions(ctx context.Context, opts *options.TransactionOptions, fn func(sessCtx mongo.SessionContext) error) error
TransactionWithOptions executes a function in a MongoDB transaction with options
func (*MongoDatabase) Type ¶
func (d *MongoDatabase) Type() DatabaseType
Type returns the database type
type QueryHook ¶
type QueryHook struct {
// contains filtered or unexported fields
}
QueryHook provides observability for Bun queries
func (*QueryHook) AfterQuery ¶
func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent)
AfterQuery is called after query execution
func (*QueryHook) BeforeQuery ¶
BeforeQuery is called before query execution
type SQLDatabase ¶
type SQLDatabase struct {
// contains filtered or unexported fields
}
SQLDatabase wraps Bun ORM for SQL databases
func NewSQLDatabase ¶
func NewSQLDatabase(config DatabaseConfig, logger forge.Logger, metrics forge.Metrics) (*SQLDatabase, error)
NewSQLDatabase creates a new SQL database instance
func (*SQLDatabase) Close ¶
func (d *SQLDatabase) Close(ctx context.Context) error
Close closes the database connection
func (*SQLDatabase) Driver ¶
func (d *SQLDatabase) Driver() interface{}
Driver returns the raw *sql.DB for native driver access
func (*SQLDatabase) Health ¶
func (d *SQLDatabase) Health(ctx context.Context) HealthStatus
Health returns the health status
func (*SQLDatabase) Open ¶
func (d *SQLDatabase) Open(ctx context.Context) error
Open establishes the database connection
func (*SQLDatabase) Ping ¶
func (d *SQLDatabase) Ping(ctx context.Context) error
Ping checks database connectivity
func (*SQLDatabase) Stats ¶
func (d *SQLDatabase) Stats() DatabaseStats
Stats returns connection pool statistics
func (*SQLDatabase) Transaction ¶
Transaction executes a function in a SQL transaction