database

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 22 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var (
	DB     *gorm.DB
	DBSite *gorm.DB
)

defaultDB, defaultDBSite, DB, DBSite are the legacy global singleton state; compatMu protects concurrent access.

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

func GetDB() *gorm.DB

GetDB returns the global primary *gorm.DB. Panics if database not initialized (call Setup first).

func GetDBSite

func GetDBSite() *gorm.DB

GetDBSite returns the global site *gorm.DB if configured; otherwise returns GetDB().

func HealthCheck added in v0.1.14

func HealthCheck(ctx context.Context) error

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 NewFintechLogger added in v0.2.0

func NewFintechLogger(cfg logger.Config) logger.Interface

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

func New(cfg *config.DatabaseConfiguration, opts Options, override ...Option) (*Database, error)

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

func (d *Database) Close() error

Close runs all registered cleanup functions (e.g. Cloud SQL connector close) and clears the list. Returns the first error if any cleanup fails.

func (*Database) DB added in v0.2.0

func (d *Database) DB() *gorm.DB

DB returns the underlying *gorm.DB for queries. Safe to call after New; do not close it directly.

func (*Database) Health added in v0.2.0

func (d *Database) Health(ctx context.Context) error

Health pings the database using a context with timeout d.opts.PingTimeout. Returns an error if db is nil, *sql.DB cannot be obtained, or ping 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

func WithConnMaxIdleTime(d time.Duration) Option

WithConnMaxIdleTime sets the maximum time a connection may be idle.

func WithConnMaxLifetime added in v0.2.0

func WithConnMaxLifetime(d time.Duration) Option

WithConnMaxLifetime sets the maximum lifetime of a connection.

func WithIAM added in v0.2.0

func WithIAM(v bool) Option

WithIAM sets whether to use IAM authentication for Cloud SQL.

func WithLogLevel added in v0.2.0

func WithLogLevel(level logger.LogLevel) Option

WithLogLevel sets the GORM log level (e.g. logger.Warn, logger.Info).

func WithMaxIdleConns added in v0.2.0

func WithMaxIdleConns(n int) Option

WithMaxIdleConns sets the maximum number of idle connections in the pool.

func WithMaxOpenConns added in v0.2.0

func WithMaxOpenConns(n int) Option

WithMaxOpenConns sets the maximum number of open connections to the database.

func WithPrivateIP added in v0.2.0

func WithPrivateIP(v bool) Option

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.

Jump to

Keyboard shortcuts

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