database

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 20 Imported by: 4

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

Constants

This section is empty.

Variables

View Source
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

func NewExtension(config Config) forge.Extension

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

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default configuration

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration

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

func (*DatabaseManager) Register

func (m *DatabaseManager) Register(name string, db Database) error

Register adds a database to the manager

func (*DatabaseManager) SQL

func (m *DatabaseManager) SQL(name string) (*bun.DB, error)

SQL retrieves an SQL database with Bun ORM by name

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

func (e *Extension) Dependencies() []string

Dependencies returns the list of extension dependencies

func (*Extension) Description

func (e *Extension) Description() string

Description returns the extension description

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks the extension health

func (*Extension) Name

func (e *Extension) Name() string

Name returns the extension name

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the extension with the application

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the extension

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop stops the extension

func (*Extension) Version

func (e *Extension) Version() string

Version returns the extension version

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

func (d *MongoDatabase) Name() string

Name returns the database name

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

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

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

func (d *SQLDatabase) Bun() *bun.DB

Bun returns the Bun ORM instance

func (*SQLDatabase) Close

func (d *SQLDatabase) Close(ctx context.Context) error

Close closes the database connection

func (*SQLDatabase) DB

func (d *SQLDatabase) DB() *sql.DB

DB returns the raw *sql.DB

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

func (d *SQLDatabase) Name() string

Name returns the database name

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

func (d *SQLDatabase) Transaction(ctx context.Context, fn func(tx bun.Tx) error) error

Transaction executes a function in a SQL transaction

func (*SQLDatabase) TransactionWithOptions

func (d *SQLDatabase) TransactionWithOptions(ctx context.Context, opts *sql.TxOptions, fn func(tx bun.Tx) error) error

TransactionWithOptions executes a function in a SQL transaction with options

func (*SQLDatabase) Type

func (d *SQLDatabase) Type() DatabaseType

Type returns the database type

Jump to

Keyboard shortcuts

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