Documentation
¶
Overview ¶
Package database provides a GORM-based database layer with support for MySQL, Postgres, SQLite, SQL Server, and Google Cloud SQL (Postgres/MySQL with optional IAM and Private IP).
Role in architecture:
- Infrastructure: connects to the database, configures pool, exposes *gorm.DB. No business logic.
Responsibilities:
- Build DSN and open connection (standard drivers or Cloud SQL connector).
- Apply connection pool limits (MaxOpenConns, MaxIdleConns, ConnMaxLifetime, ConnMaxIdle).
- Expose Health(ctx) with PingTimeout-bounded ping and Close() for cleanup (including Cloud SQL connector).
- Optional GORM logger with SQL redaction (passwords, tokens, card numbers) and slow query logging.
- Legacy compat: Setup/GetDB/GetDBSite/HealthCheck/Cleanup/IsAlive for global singleton usage.
Constraints:
- Driver selection is by config only; no runtime provider switching.
- No retry, circuit breaker, or fallback; single connection path per Database instance.
- Cloud SQL IAM and Private IP are set via Options at construction, not from config.
This package must NOT:
- Define use-case or domain logic; only connection and pool management.
- Execute business queries; that belongs in repositories or use-case adapters.
Index ¶
- Variables
- func Cleanup() error
- func CreateDatabaseConnection(cfg *config.DatabaseConfiguration) (*gorm.DB, error)
- func GetDB() *gorm.DB
- func GetDBSite() *gorm.DB
- func HealthCheck(ctx context.Context) error
- func IsAlive() bool
- func NewFintechLogger(cfg logger.Config) logger.Interface
- func Setup() error
- func WithProductionPoolDefaults(o *Options)
- type Database
- type Option
- type Options
Constants ¶
This section is empty.
Variables ¶
var ( DB *gorm.DB DBSite *gorm.DB )
defaultDB, defaultDBSite, DB, DBSite are the legacy global singleton state; compatMu protects concurrent access.
var ErrNotInitialized = &errNotInitialized{}
ErrNotInitialized is returned by HealthCheck when Setup has not been called or defaultDB is nil.
Functions ¶
func Cleanup ¶
func Cleanup() error
Cleanup closes both defaultDB and defaultDBSite and clears globals. Returns the first error from Close if any.
func CreateDatabaseConnection ¶
func CreateDatabaseConnection(cfg *config.DatabaseConfiguration) (*gorm.DB, error)
CreateDatabaseConnection creates a Database from cfg, sets it as the global defaultDB, and returns its *gorm.DB. For legacy callers that need a raw *gorm.DB.
func GetDB ¶
GetDB returns the global primary *gorm.DB. Panics if database not initialized (call Setup first).
func GetDBSite ¶
GetDBSite returns the global site *gorm.DB if configured; otherwise returns GetDB().
func HealthCheck ¶ added in v0.1.14
HealthCheck pings both primary and site databases (if present). Returns ErrNotInitialized if Setup was not called.
func IsAlive ¶ added in v0.1.14
func IsAlive() bool
IsAlive returns true if the primary database responds to Health(context.Background()); false if not initialized or ping fails.
func Setup ¶
func Setup() error
Setup initializes the global database from config.GetConfig(): primary database always, site database if DatabaseSite.Dbname is set. Panics if New fails.
func WithProductionPoolDefaults ¶ added in v0.3.0
func WithProductionPoolDefaults(o *Options)
WithProductionPoolDefaults sets higher connection pool limits for high-throughput production (e.g. 1000+ RPS). Call as an override: database.New(cfg, opts, database.WithProductionPoolDefaults).
Types ¶
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database holds a GORM DB instance, options, and cleanup functions. Use New or NewContext to construct.
func New ¶ added in v0.2.0
New creates a Database from cfg and opts, applying any override Option funcs. Uses context.Background for connection.
func NewContext ¶ added in v0.2.0
func NewContext(ctx context.Context, cfg *config.DatabaseConfiguration, opts Options, override ...Option) (*Database, error)
NewContext creates a Database with the given context (used for connection timeout/cancellation). Driver is read from cfg; cloudsql-postgres and cloudsql-mysql use Cloud SQL connector; others use standard driver.
func (*Database) Close ¶ added in v0.2.0
Close runs all registered cleanup functions (e.g. Cloud SQL connector close) and clears the list. Returns the first error if any cleanup fails.
type Option ¶ added in v0.2.0
type Option func(*Options)
Option is a functional option applied to Options (e.g. WithMaxOpenConns, WithProductionPoolDefaults).
func WithConnMaxIdleTime ¶ added in v0.2.0
WithConnMaxIdleTime sets the maximum time a connection may be idle.
func WithConnMaxLifetime ¶ added in v0.2.0
WithConnMaxLifetime sets the maximum lifetime of a connection.
func WithLogLevel ¶ added in v0.2.0
WithLogLevel sets the GORM log level (e.g. logger.Warn, logger.Info).
func WithMaxIdleConns ¶ added in v0.2.0
WithMaxIdleConns sets the maximum number of idle connections in the pool.
func WithMaxOpenConns ¶ added in v0.2.0
WithMaxOpenConns sets the maximum number of open connections to the database.
func WithPrivateIP ¶ added in v0.2.0
WithPrivateIP sets whether to use Private IP for Cloud SQL.
type Options ¶ added in v0.2.0
type Options struct {
UseIAM bool
UsePrivateIP bool
LogLevel logger.LogLevel
MaxOpenConns int
MaxIdleConns int
ConnMaxLife time.Duration
ConnMaxIdle time.Duration
SlowThreshold time.Duration
PingTimeout time.Duration
}
Options holds database connection and pool settings. applyDefaults fills zero values with package defaults.