database

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License: Apache-2.0 Imports: 26 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

View Source
const (
	// ManagerKey is the DI key for the database manager.
	ManagerKey = "forge.database.manager"
	// DatabaseKey is the DI key for the default database.
	DatabaseKey = "forge.database.database"
	// SQLKey is the DI key for the default SQL database (Bun DB).
	SQLKey = "forge.database.sql"
	// MongoKey is the DI key for the default MongoDB client.
	MongoKey = "forge.database.mongo"
)

DI container keys for database extension services.

View Source
const (
	CodeDatabaseError       = "DATABASE_ERROR"
	CodeDatabaseNotFound    = "DATABASE_NOT_FOUND"
	CodeDatabaseExists      = "DATABASE_ALREADY_EXISTS"
	CodeDatabaseNotOpened   = "DATABASE_NOT_OPENED"
	CodeDatabaseInvalidType = "DATABASE_INVALID_TYPE"
	CodeDatabaseConnection  = "DATABASE_CONNECTION_ERROR"
	CodeDatabaseQuery       = "DATABASE_QUERY_ERROR"
	CodeDatabaseTransaction = "DATABASE_TRANSACTION_ERROR"
	CodeDatabasePanic       = "DATABASE_PANIC_RECOVERED"
	CodeDatabaseConfig      = "DATABASE_CONFIG_ERROR"
)

Error codes for database operations.

Variables

View Source
var (
	// Migrations is the global migration collection
	// All migrations should register themselves here using init().
	Migrations = migrate.Migrations

	// RegisterMigration is a helper to register a migration.
	RegisterMigration = migrate.RegisterMigration

	// RegisterModel adds a model to the auto-registration list.
	RegisterModel = migrate.RegisterModel

	// Models is the list of all models that should be auto-registered.
	Models = &migrate.Models
)

Re-export migrate package for convenience This allows users to import "github.com/xraph/forge/extensions/database" and use database.Migrations instead of importing the migrate subpackage.

Functions

func ErrConnectionFailed added in v0.4.0

func ErrConnectionFailed(dbName string, dbType DatabaseType, cause error) error

func ErrDatabaseAlreadyExists

func ErrDatabaseAlreadyExists(name string) error

func ErrDatabaseNotFound

func ErrDatabaseNotFound(name string) error

func ErrDatabaseNotOpened

func ErrDatabaseNotOpened(name string) error

func ErrInvalidDSN

func ErrInvalidDSN(dsn string) error

func ErrInvalidDatabaseName

func ErrInvalidDatabaseName(name string) error

func ErrInvalidDatabaseType

func ErrInvalidDatabaseType(dbType string) error

func ErrInvalidDatabaseTypeOp

func ErrInvalidDatabaseTypeOp(name string, expectedType, actualType DatabaseType) error

func ErrInvalidPoolConfig

func ErrInvalidPoolConfig(reason string) error

func ErrNoDatabasesConfigured

func ErrNoDatabasesConfigured() error

Error constructors for common database errors.

func ErrPanicRecovered added in v0.4.0

func ErrPanicRecovered(dbName string, dbType DatabaseType, panicValue any) error

func ErrQueryFailed added in v0.4.0

func ErrQueryFailed(dbName string, dbType DatabaseType, cause error) error

func ErrTransactionFailed added in v0.4.0

func ErrTransactionFailed(dbName string, dbType DatabaseType, cause error) error

func GetMongo added in v0.5.0

func GetMongo(c forge.Container) (*mongo.Client, error)

GetMongo retrieves the default MongoDB client from the container Returns error if not found, type assertion fails, or default is not MongoDB.

func GetMongoFromApp added in v0.5.0

func GetMongoFromApp(app forge.App) (*mongo.Client, error)

GetMongoFromApp retrieves the default MongoDB client from the app Returns error if not found, type assertion fails, or default is not MongoDB.

func GetNamedMongo added in v0.5.0

func GetNamedMongo(c forge.Container, name string) (*mongo.Client, error)

GetNamedMongo retrieves a named MongoDB database as mongo.Client Returns error if database not found or is not MongoDB.

func GetNamedMongoFromApp added in v0.5.0

func GetNamedMongoFromApp(app forge.App, name string) (*mongo.Client, error)

GetNamedMongoFromApp retrieves a named MongoDB database from the app.

func GetNamedSQL added in v0.5.0

func GetNamedSQL(c forge.Container, name string) (*bun.DB, error)

GetNamedSQL retrieves a named SQL database as Bun DB Returns error if database not found or is not a SQL database.

func GetNamedSQLFromApp added in v0.5.0

func GetNamedSQLFromApp(app forge.App, name string) (*bun.DB, error)

GetNamedSQLFromApp retrieves a named SQL database from the app.

func GetSQL added in v0.5.0

func GetSQL(c forge.Container) (*bun.DB, error)

GetSQL retrieves the default Bun SQL database from the container Returns error if not found, type assertion fails, or default is not a SQL database.

func GetSQLFromApp added in v0.5.0

func GetSQLFromApp(app forge.App) (*bun.DB, error)

GetSQLFromApp retrieves the default Bun SQL database from the app Returns error if not found, type assertion fails, or default is not a SQL database.

func GetUserID added in v0.4.0

func GetUserID(ctx context.Context) (int64, bool)

GetUserID retrieves user ID from context.

func GetXIDUserID added in v0.4.0

func GetXIDUserID(ctx context.Context) (xid.ID, bool)

func MaskDSN added in v0.4.0

func MaskDSN(dsn string, dbType DatabaseType) string

MaskDSN masks sensitive information in DSN for logging.

func MustGetMongo added in v0.5.0

func MustGetMongo(c forge.Container) *mongo.Client

MustGetMongo retrieves the default MongoDB client from the container Panics if not found, type assertion fails, or default is not MongoDB.

func MustGetMongoFromApp added in v0.5.0

func MustGetMongoFromApp(app forge.App) *mongo.Client

MustGetMongoFromApp retrieves the default MongoDB client from the app Panics if not found, type assertion fails, or default is not MongoDB.

func MustGetNamedMongo added in v0.5.0

func MustGetNamedMongo(c forge.Container, name string) *mongo.Client

MustGetNamedMongo retrieves a named MongoDB database as mongo.Client Panics if database not found or is not MongoDB.

func MustGetNamedMongoFromApp added in v0.5.0

func MustGetNamedMongoFromApp(app forge.App, name string) *mongo.Client

MustGetNamedMongoFromApp retrieves a named MongoDB database from the app Panics if not found.

func MustGetNamedSQL added in v0.5.0

func MustGetNamedSQL(c forge.Container, name string) *bun.DB

MustGetNamedSQL retrieves a named SQL database as Bun DB Panics if database not found or is not a SQL database.

func MustGetNamedSQLFromApp added in v0.5.0

func MustGetNamedSQLFromApp(app forge.App, name string) *bun.DB

MustGetNamedSQLFromApp retrieves a named SQL database from the app Panics if not found.

func MustGetSQL added in v0.5.0

func MustGetSQL(c forge.Container) *bun.DB

MustGetSQL retrieves the default Bun SQL database from the container Panics if not found, type assertion fails, or default is not a SQL database.

func MustGetSQLFromApp added in v0.5.0

func MustGetSQLFromApp(app forge.App) *bun.DB

MustGetSQLFromApp retrieves the default Bun SQL database from the app Panics if not found, type assertion fails, or default is not a SQL database.

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new database extension with variadic options.

func NewExtensionWithConfig added in v0.4.0

func NewExtensionWithConfig(config Config) forge.Extension

NewExtensionWithConfig creates a new database extension with a complete config.

func SetUserID added in v0.4.0

func SetUserID(ctx context.Context, userID int64) context.Context

SetUserID is a helper to set user ID in context for audit tracking.

func SetXIDUserID added in v0.4.0

func SetXIDUserID(ctx context.Context, userID xid.ID) context.Context

Types

type AppliedMigration added in v0.4.0

type AppliedMigration struct {
	Name      string
	GroupID   int64
	AppliedAt time.Time
}

AppliedMigration represents an applied migration.

type AuditModel added in v0.4.0

type AuditModel struct {
	ID        int64      `bun:"id,pk,autoincrement"                                   json:"id"`
	CreatedAt time.Time  `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	CreatedBy *int64     `bun:"created_by"                                            json:"created_by,omitempty"`
	UpdatedAt time.Time  `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
	UpdatedBy *int64     `bun:"updated_by"                                            json:"updated_by,omitempty"`
	DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero"                       json:"deleted_at,omitempty"`
	DeletedBy *int64     `bun:"deleted_by"                                            json:"deleted_by,omitempty"`
}

AuditModel provides comprehensive audit trail with user tracking Use this when you need to track who created/updated records.

func (*AuditModel) BeforeDelete added in v0.4.0

func (m *AuditModel) BeforeDelete(ctx context.Context, query *bun.DeleteQuery) error

BeforeDelete hook - performs soft delete and tracks deleter.

func (*AuditModel) BeforeInsert added in v0.4.0

func (m *AuditModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - sets timestamps and tracks creator.

func (*AuditModel) BeforeUpdate added in v0.4.0

func (m *AuditModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt and tracks updater.

func (*AuditModel) IsDeleted added in v0.4.0

func (m *AuditModel) IsDeleted() bool

IsDeleted checks if the record is soft deleted.

func (*AuditModel) Restore added in v0.4.0

func (m *AuditModel) Restore()

Restore restores a soft-deleted record.

type BaseModel added in v0.4.0

type BaseModel struct {
	ID        int64     `bun:"id,pk,autoincrement"                                   json:"id"`
	CreatedAt time.Time `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
}

BaseModel provides common fields and hooks for all models Use this for models that need ID, timestamps, and standard hooks.

func (*BaseModel) BeforeInsert added in v0.4.0

func (m *BaseModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - sets timestamps on insert.

func (*BaseModel) BeforeUpdate added in v0.4.0

func (m *BaseModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt on every update.

type Config

type Config struct {
	// List of database configurations
	Databases []DatabaseConfig `json:"databases" mapstructure:"databases" yaml:"databases"`

	// Default database name (first one if not specified)
	Default string `json:"default" mapstructure:"default" yaml:"default"`

	// Config loading flags
	RequireConfig bool `json:"-" yaml:"-"`
}

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 ConfigOption added in v0.4.0

type ConfigOption func(*Config)

ConfigOption is a functional option for Config.

func WithConfig added in v0.4.0

func WithConfig(config Config) ConfigOption

WithConfig replaces the entire config.

func WithDatabase added in v0.4.0

func WithDatabase(db DatabaseConfig) ConfigOption

WithDatabase adds a single database configuration.

func WithDatabases added in v0.4.0

func WithDatabases(databases ...DatabaseConfig) ConfigOption

WithDatabases sets the list of database configurations.

func WithDefault added in v0.4.0

func WithDefault(name string) ConfigOption

WithDefault sets the default database name.

func WithRequireConfig added in v0.4.0

func WithRequireConfig(require bool) ConfigOption

WithRequireConfig requires config from YAML.

type ConnectionState added in v0.4.0

type ConnectionState int32

ConnectionState represents the state of a database connection.

const (
	StateDisconnected ConnectionState = iota
	StateConnecting
	StateConnected
	StateError
	StateReconnecting
)

func (ConnectionState) String added in v0.4.0

func (s ConnectionState) String() string

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

	// State
	IsOpen() bool
	State() ConnectionState

	// Health
	Health(ctx context.Context) HealthStatus
	Stats() DatabaseStats

	// Access to native driver/ORM
	Driver() any
}

Database represents a database connection.

func GetDatabase added in v0.5.0

func GetDatabase(c forge.Container) (Database, error)

GetDatabase retrieves the default Database from the container Returns error if not found or type assertion fails.

func GetDatabaseFromApp added in v0.5.0

func GetDatabaseFromApp(app forge.App) (Database, error)

GetDatabaseFromApp retrieves the default Database from the app Returns error if not found or type assertion fails.

func GetNamedDatabase added in v0.5.0

func GetNamedDatabase(c forge.Container, name string) (Database, error)

GetNamedDatabase retrieves a named database through the DatabaseManager This is useful when you have multiple databases configured.

func GetNamedDatabaseFromApp added in v0.5.0

func GetNamedDatabaseFromApp(app forge.App, name string) (Database, error)

GetNamedDatabaseFromApp retrieves a named database from the app.

func MustGetDatabase added in v0.5.0

func MustGetDatabase(c forge.Container) Database

MustGetDatabase retrieves the default Database from the container Panics if not found or type assertion fails.

func MustGetDatabaseFromApp added in v0.5.0

func MustGetDatabaseFromApp(app forge.App) Database

MustGetDatabaseFromApp retrieves the default Database from the app Panics if not found or type assertion fails.

func MustGetNamedDatabase added in v0.5.0

func MustGetNamedDatabase(c forge.Container, name string) Database

MustGetNamedDatabase retrieves a named database through the DatabaseManager Panics if manager not found or database not found.

func MustGetNamedDatabaseFromApp added in v0.5.0

func MustGetNamedDatabaseFromApp(app forge.App, name string) Database

MustGetNamedDatabaseFromApp retrieves a named database from the app Panics if not found.

type DatabaseConfig

type DatabaseConfig struct {
	Name string       `json:"name" yaml:"name"`
	Type DatabaseType `json:"type" yaml:"type"`
	DSN  string       `json:"dsn"  yaml:"dsn"`

	// Connection pool settings
	MaxOpenConns    int           `default:"25" json:"max_open_conns"     yaml:"max_open_conns"`
	MaxIdleConns    int           `default:"5"  json:"max_idle_conns"     yaml:"max_idle_conns"`
	ConnMaxLifetime time.Duration `default:"5m" json:"conn_max_lifetime"  yaml:"conn_max_lifetime"`
	ConnMaxIdleTime time.Duration `default:"5m" json:"conn_max_idle_time" yaml:"conn_max_idle_time"`

	// Retry settings
	MaxRetries int           `default:"3"  json:"max_retries" yaml:"max_retries"`
	RetryDelay time.Duration `default:"1s" json:"retry_delay" yaml:"retry_delay"`

	// Timeout settings
	ConnectionTimeout time.Duration `default:"10s" json:"connection_timeout" yaml:"connection_timeout"`
	QueryTimeout      time.Duration `default:"30s" json:"query_timeout"      yaml:"query_timeout"`

	// Observability settings
	SlowQueryThreshold time.Duration `default:"100ms" json:"slow_query_threshold" yaml:"slow_query_threshold"`

	// Health check
	HealthCheckInterval time.Duration `default:"30s" json:"health_check_interval" yaml:"health_check_interval"`

	// Additional config (database-specific)
	Config map[string]any `json:"config" yaml:"config"`
}

DatabaseConfig is the configuration for a database connection.

type DatabaseError added in v0.4.0

type DatabaseError struct {
	DBName    string
	DBType    DatabaseType
	Operation string
	Code      string
	Err       error
}

DatabaseError wraps database-specific errors with context.

func NewDatabaseError added in v0.4.0

func NewDatabaseError(dbName string, dbType DatabaseType, operation string, err error) *DatabaseError

NewDatabaseError creates a new database error with context.

func (*DatabaseError) Error added in v0.4.0

func (e *DatabaseError) Error() string

func (*DatabaseError) Unwrap added in v0.4.0

func (e *DatabaseError) Unwrap() error

type DatabaseManager

type DatabaseManager struct {
	// contains filtered or unexported fields
}

DatabaseManager manages multiple database connections.

func GetManager added in v0.5.0

func GetManager(c forge.Container) (*DatabaseManager, error)

GetManager retrieves the DatabaseManager from the container Returns error if not found or type assertion fails.

func GetManagerFromApp added in v0.5.0

func GetManagerFromApp(app forge.App) (*DatabaseManager, error)

GetManagerFromApp retrieves the DatabaseManager from the app Returns error if not found or type assertion fails.

func MustGetManager added in v0.5.0

func MustGetManager(c forge.Container) *DatabaseManager

MustGetManager retrieves the DatabaseManager from the container Panics if not found or type assertion fails.

func MustGetManagerFromApp added in v0.5.0

func MustGetManagerFromApp(app forge.App) *DatabaseManager

MustGetManagerFromApp retrieves the DatabaseManager from the app Panics if not found or type assertion fails.

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, collecting errors without stopping.

func (*DatabaseManager) Get

func (m *DatabaseManager) Get(name string) (Database, error)

Get retrieves a database by name.

func (*DatabaseManager) Health added in v0.4.0

func (m *DatabaseManager) Health(ctx context.Context) error

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, collecting errors without stopping.

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 {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements the database extension.

func (*Extension) Health

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

Health checks the extension health.

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.

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 Logger added in v0.4.0

type Logger interface {
	Info(msg string, fields ...any)
	Error(msg string, fields ...any)
	Warn(msg string, fields ...any)
}

Logger interface for migration logging.

type MigrationManager added in v0.4.0

type MigrationManager struct {
	// contains filtered or unexported fields
}

MigrationManager manages database migrations.

func NewMigrationManager added in v0.4.0

func NewMigrationManager(db *bun.DB, migrations *migrate.Migrations, logger Logger) *MigrationManager

NewMigrationManager creates a new migration manager.

func (*MigrationManager) AutoMigrate added in v0.4.0

func (m *MigrationManager) AutoMigrate(ctx context.Context, models ...any) error

AutoMigrate automatically creates/updates tables for registered models This is a development convenience - use migrations for production.

func (*MigrationManager) CreateMigration added in v0.4.0

func (m *MigrationManager) CreateMigration(ctx context.Context) error

CreateMigration creates the migration tables and initial structure.

func (*MigrationManager) CreateTables added in v0.4.0

func (m *MigrationManager) CreateTables(ctx context.Context) error

CreateTables creates the migrations table.

func (*MigrationManager) Migrate added in v0.4.0

func (m *MigrationManager) Migrate(ctx context.Context) error

Migrate runs all pending migrations.

func (*MigrationManager) Reset added in v0.4.0

func (m *MigrationManager) Reset(ctx context.Context) error

Reset drops all tables and re-runs all migrations.

func (*MigrationManager) Rollback added in v0.4.0

func (m *MigrationManager) Rollback(ctx context.Context) error

Rollback rolls back the last migration group.

func (*MigrationManager) Status added in v0.4.0

Status returns the current migration 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 MigrationStatusResult added in v0.4.0

type MigrationStatusResult struct {
	Applied []AppliedMigration
	Pending []string
}

MigrationStatusResult represents the current state of migrations.

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() any

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) IsOpen added in v0.4.0

func (d *MongoDatabase) IsOpen() bool

IsOpen returns whether the database is connected.

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 with retry logic.

func (*MongoDatabase) Ping

func (d *MongoDatabase) Ping(ctx context.Context) error

Ping checks MongoDB connectivity.

func (*MongoDatabase) State added in v0.4.0

func (d *MongoDatabase) State() ConnectionState

State returns the current connection state.

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) (err error)

Transaction executes a function in a MongoDB transaction with panic recovery.

func (*MongoDatabase) TransactionWithOptions

func (d *MongoDatabase) TransactionWithOptions(ctx context.Context, opts *options.TransactionOptions, fn func(sessCtx mongo.SessionContext) error) (err error)

TransactionWithOptions executes a function in a MongoDB transaction with options and panic recovery.

func (*MongoDatabase) Type

func (d *MongoDatabase) Type() DatabaseType

Type returns the database type.

type MultiError added in v0.4.0

type MultiError struct {
	Errors map[string]error
}

MultiError represents multiple database errors.

func (*MultiError) Error added in v0.4.0

func (e *MultiError) Error() string

func (*MultiError) HasErrors added in v0.4.0

func (e *MultiError) HasErrors() bool

HasErrors returns true if there are any errors.

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() any

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) IsOpen added in v0.4.0

func (d *SQLDatabase) IsOpen() bool

IsOpen returns whether the database is connected.

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 with retry logic.

func (*SQLDatabase) Ping

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

Ping checks database connectivity.

func (*SQLDatabase) State added in v0.4.0

func (d *SQLDatabase) State() ConnectionState

State returns the current connection state.

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) (err error)

Transaction executes a function in a SQL transaction with panic recovery.

func (*SQLDatabase) TransactionWithOptions

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

TransactionWithOptions executes a function in a SQL transaction with options and panic recovery.

func (*SQLDatabase) Type

func (d *SQLDatabase) Type() DatabaseType

Type returns the database type.

type SoftDeleteModel added in v0.4.0

type SoftDeleteModel struct {
	ID        int64      `bun:"id,pk,autoincrement"                                   json:"id"`
	CreatedAt time.Time  `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time  `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
	DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero"                       json:"deleted_at,omitempty"`
}

SoftDeleteModel provides soft delete functionality with timestamps Soft-deleted records are not permanently removed, just marked as deleted.

func (*SoftDeleteModel) BeforeDelete added in v0.4.0

func (m *SoftDeleteModel) BeforeDelete(ctx context.Context, query *bun.DeleteQuery) error

BeforeDelete hook - performs soft delete.

func (*SoftDeleteModel) BeforeInsert added in v0.4.0

func (m *SoftDeleteModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - sets timestamps.

func (*SoftDeleteModel) BeforeUpdate added in v0.4.0

func (m *SoftDeleteModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt.

func (*SoftDeleteModel) IsDeleted added in v0.4.0

func (m *SoftDeleteModel) IsDeleted() bool

IsDeleted checks if the record is soft deleted.

func (*SoftDeleteModel) Restore added in v0.4.0

func (m *SoftDeleteModel) Restore()

Restore restores a soft-deleted record.

type TimestampModel added in v0.4.0

type TimestampModel struct {
	CreatedAt time.Time `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
}

TimestampModel provides only timestamp fields without ID Use this when you want to add your own ID field type.

func (*TimestampModel) BeforeInsert added in v0.4.0

func (m *TimestampModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - sets timestamps.

func (*TimestampModel) BeforeUpdate added in v0.4.0

func (m *TimestampModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt.

type UUIDModel added in v0.4.0

type UUIDModel struct {
	ID        uuid.UUID `bun:"id,pk,type:uuid,default:gen_random_uuid()"             json:"id"`
	CreatedAt time.Time `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
}

UUIDModel provides UUID-based primary key with timestamps Use this for distributed systems or when you need globally unique IDs.

func (*UUIDModel) BeforeInsert added in v0.4.0

func (m *UUIDModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - generates UUID and sets timestamps.

func (*UUIDModel) BeforeUpdate added in v0.4.0

func (m *UUIDModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt.

type UUIDSoftDeleteModel added in v0.4.0

type UUIDSoftDeleteModel struct {
	ID        uuid.UUID  `bun:"id,pk,type:uuid,default:gen_random_uuid()"             json:"id"`
	CreatedAt time.Time  `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time  `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
	DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero"                       json:"deleted_at,omitempty"`
}

UUIDSoftDeleteModel combines UUID primary key with soft delete.

func (*UUIDSoftDeleteModel) BeforeDelete added in v0.4.0

func (m *UUIDSoftDeleteModel) BeforeDelete(ctx context.Context, query *bun.DeleteQuery) error

BeforeDelete hook - performs soft delete.

func (*UUIDSoftDeleteModel) BeforeInsert added in v0.4.0

func (m *UUIDSoftDeleteModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - generates UUID and sets timestamps.

func (*UUIDSoftDeleteModel) BeforeUpdate added in v0.4.0

func (m *UUIDSoftDeleteModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt.

func (*UUIDSoftDeleteModel) IsDeleted added in v0.4.0

func (m *UUIDSoftDeleteModel) IsDeleted() bool

IsDeleted checks if the record is soft deleted.

func (*UUIDSoftDeleteModel) Restore added in v0.4.0

func (m *UUIDSoftDeleteModel) Restore()

Restore restores a soft-deleted record.

type XIDAuditModel added in v0.4.0

type XIDAuditModel struct {
	ID        xid.ID     `bun:"id,pk,type:varchar(20)"                                json:"id"`
	CreatedAt time.Time  `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	CreatedBy *xid.ID    `bun:"created_by"                                            json:"created_by,omitempty"`
	UpdatedAt time.Time  `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
	UpdatedBy *xid.ID    `bun:"updated_by"                                            json:"updated_by,omitempty"`
	DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero"                       json:"deleted_at,omitempty"`
	DeletedBy *xid.ID    `bun:"deleted_by"                                            json:"deleted_by,omitempty"`
}

XIDAuditModel provides comprehensive audit trail with XID primary key and user tracking Combines XID with full audit capabilities: tracks who created/updated/deleted records.

func (*XIDAuditModel) BeforeDelete added in v0.4.0

func (m *XIDAuditModel) BeforeDelete(ctx context.Context, query *bun.DeleteQuery) error

BeforeDelete hook - performs soft delete and tracks deleter.

func (*XIDAuditModel) BeforeInsert added in v0.4.0

func (m *XIDAuditModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - generates XID, sets timestamps and tracks creator.

func (*XIDAuditModel) BeforeUpdate added in v0.4.0

func (m *XIDAuditModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt and tracks updater.

func (*XIDAuditModel) IsDeleted added in v0.4.0

func (m *XIDAuditModel) IsDeleted() bool

IsDeleted checks if the record is soft deleted.

func (*XIDAuditModel) Restore added in v0.4.0

func (m *XIDAuditModel) Restore()

Restore restores a soft-deleted record.

type XIDModel added in v0.4.0

type XIDModel struct {
	ID        xid.ID    `bun:"id,pk,type:varchar(20)"                                json:"id"`
	CreatedAt time.Time `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
}

XIDModel provides XID primary key with timestamps XID is a globally unique, sortable, compact, URL-safe identifier It's shorter than UUID (20 bytes vs 36) and sortable by creation time.

func (*XIDModel) BeforeInsert added in v0.4.0

func (m *XIDModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - generates XID and sets timestamps.

func (*XIDModel) BeforeUpdate added in v0.4.0

func (m *XIDModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt.

type XIDSoftDeleteModel added in v0.4.0

type XIDSoftDeleteModel struct {
	ID        xid.ID     `bun:"id,pk,type:varchar(20)"                                json:"id"`
	CreatedAt time.Time  `bun:"created_at,nullzero,notnull,default:current_timestamp" json:"created_at"`
	UpdatedAt time.Time  `bun:"updated_at,nullzero,notnull,default:current_timestamp" json:"updated_at"`
	DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero"                       json:"deleted_at,omitempty"`
}

XIDSoftDeleteModel combines XID primary key with soft delete.

func (*XIDSoftDeleteModel) BeforeDelete added in v0.4.0

func (m *XIDSoftDeleteModel) BeforeDelete(ctx context.Context, query *bun.DeleteQuery) error

BeforeDelete hook - performs soft delete.

func (*XIDSoftDeleteModel) BeforeInsert added in v0.4.0

func (m *XIDSoftDeleteModel) BeforeInsert(ctx context.Context, query *bun.InsertQuery) error

BeforeInsert hook - generates XID and sets timestamps.

func (*XIDSoftDeleteModel) BeforeUpdate added in v0.4.0

func (m *XIDSoftDeleteModel) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

BeforeUpdate hook - updates UpdatedAt.

func (*XIDSoftDeleteModel) IsDeleted added in v0.4.0

func (m *XIDSoftDeleteModel) IsDeleted() bool

IsDeleted checks if the record is soft deleted.

func (*XIDSoftDeleteModel) Restore added in v0.4.0

func (m *XIDSoftDeleteModel) Restore()

Restore restores a soft-deleted record.

Directories

Path Synopsis
Package migrate provides migration management for the database extension
Package migrate provides migration management for the database extension

Jump to

Keyboard shortcuts

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