database

package module
v0.4.4 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 12 Imported by: 0

README

gas/database

Test Go Reference Go Version License

Part of the Gas monorepo · Documentation · All modules

Database connections for the Gas framework. Wraps database/sql and native pgxpool with connection management, transaction helpers, and sqlc compatibility.

Implements gas.DatabaseProvider.

go get github.com/gasmod/gas/database
gas.WithSingletonService[gas.DatabaseProvider](database.New()),

database.New() needs gas.ConfigProvider and gas.Logger.

Mode Backend
database.ModeSQL (default) Any database/sql driver: PostgreSQL, SQLite, MySQL
database.ModePgx Native pgxpool for PostgreSQL, for pgx types and batching

Documentation

The full guide, with configuration, testing, and worked examples, is on the docs site. This README is deliberately a signpost: keeping a second copy here is how the docs drifted before.

License

MIT

Documentation

Overview

Package database provides database connection management for the Gas ecosystem with database/sql and pgx backends. Provides transaction helpers, sqlc integration, and connection retry with exponential backoff.

See the module README for usage examples and design rationale.

SPDX-License-Identifier: MIT

Index

Constants

View Source
const (
	// ModeSQL uses database/sql with any registered driver.
	ModeSQL = "sql"

	// ModePgx uses native pgxpool.Pool for PostgreSQL. DB() still works
	// via the pgx stdlib adapter. Pool() returns the native pool for
	// sqlc pgx mode.
	ModePgx = "pgx"
)

Mode selects the database backend.

View Source
const (
	// DriverPostgres defines the constant for the PostgreSQL database driver.
	DriverPostgres = "postgres"

	// DriverPgx represents the const string identifier for the "pgx" database driver.
	DriverPgx = "pgx"

	// DriverSQLite represents the identifier for the SQLite database driver.
	DriverSQLite = "sqlite"
)

Variables

This section is empty.

Functions

func New

func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) *Service

New captures options and returns a DI-injectable constructor. The returned func receives gas.ConfigProvider and gas.Logger from the DI container.

func PoolFrom

func PoolFrom(provider gas.DatabaseProvider) (*pgxpool.Pool, bool)

PoolFrom returns the native pgxpool.Pool behind a gas.DatabaseProvider. The second return value is false when the provider is not pgx-backed or is running in ModeSQL, in which case callers should fall back to DB().

Types

type Config

type Config struct {
	env.WithGasEnv

	Database Settings
	// contains filtered or unexported fields
}

Config holds database connection settings.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with sensible defaults using database/sql.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the Config struct for correctness and returns an error if any validation rule is violated. nolint:cyclop,gocyclo // intentionally complex

type Option

type Option func(*Service)

Option configures a Service.

func WithConfig

func WithConfig(cfg *Config) Option

WithConfig sets the database configuration.

func WithConnector

func WithConnector(c driver.Connector) Option

WithConnector sets a driver.Connector for ModeSQL. When provided, sql.OpenDB(connector) is used instead of sql.Open(driver, dsn), and Database.Driver / Database.DSN are not required.

type Service

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

Service manages a database connection and implements both gas.Service and gas.DatabaseProvider. In ModeSQL it wraps *sql.DB with any driver. In ModePgx it creates a native pgxpool.Pool and derives *sql.DB from it via the pgx stdlib adapter, so DB() always works regardless of mode.

func (*Service) BeginPgxTx

func (s *Service) BeginPgxTx(ctx context.Context, opts *pgx.TxOptions) (pgx.Tx, error)

BeginPgxTx starts a new native pgx transaction. Pass nil opts for pgx defaults. The caller is responsible for calling Commit or Rollback on the returned pgx.Tx. It returns an error when the service is closed or is not running in ModePgx.

func (*Service) BeginTx

func (s *Service) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)

BeginTx starts a new database transaction. The caller is responsible for calling Commit or Rollback on the returned *sql.Tx.

func (*Service) CheckHealth

func (s *Service) CheckHealth(_ context.Context) error

CheckHealth reports liveness. It only fails for states a restart would resolve (uninitialized or closed). Transient connectivity issues are surfaced via CheckReady instead, since database/sql and pgxpool both auto-reconnect.

func (*Service) CheckReady

func (s *Service) CheckReady(ctx context.Context) error

CheckReady reports readiness by pinging the database. A failure here means traffic should not be routed to this instance until the dependency is reachable again.

func (*Service) Close

func (s *Service) Close() error

Close closes the underlying database connections.

func (*Service) DB

func (s *Service) DB() *sql.DB

DB returns the underlying *sql.DB. This satisfies gas.DatabaseProvider and works in both ModeSQL and ModePgx (via stdlib adapter).

func (*Service) Driver

func (s *Service) Driver() string

Driver returns the database driver name based on the configured mode and settings.

func (*Service) Exec

func (s *Service) Exec(ctx context.Context, query string, args ...any) (gas.Result, error)

Exec executes a query that doesn't return rows. The returned gas.Result is backed by sql.Result which natively satisfies the interface.

func (*Service) Init

func (s *Service) Init() error

Init opens the database connection, configures the pool, and pings the database to verify connectivity.

func (*Service) Name

func (s *Service) Name() string

Name returns the service identifier.

func (*Service) Ping

func (s *Service) Ping(ctx context.Context) error

Ping verifies the database connection is still alive.

func (*Service) Pool

func (s *Service) Pool() *pgxpool.Pool

Pool returns the native pgxpool.Pool. Returns nil when running in ModeSQL. Consuming services holding only a gas.DatabaseProvider can reach the pool with PoolFrom rather than type-asserting themselves.

func (*Service) Query

func (s *Service) Query(ctx context.Context, query string, args ...any) (gas.Rows, error)

Query executes a query that returns rows. The returned gas.Rows is backed by *sql.Rows which natively satisfies the interface.

func (*Service) WithPgxTx

func (s *Service) WithPgxTx(ctx context.Context, opts *pgx.TxOptions, fn func(pgx.Tx) error) (err error)

WithPgxTx executes fn within a native pgx transaction. If fn returns nil the transaction is committed; otherwise it is rolled back and a failing rollback is joined onto fn's error. Any panic inside fn also triggers a rollback, whose failure is logged rather than returned so the panic propagates unchanged. Rollback uses a context detached from ctx's cancellation so it still runs when ctx is already done; the commit uses ctx unchanged, so an already-canceled ctx fails the commit instead of persisting work the caller abandoned. It returns an error when the service is closed or is not running in ModePgx.

func (*Service) WithTx

func (s *Service) WithTx(ctx context.Context, opts *sql.TxOptions, fn func(*sql.Tx) error) (err error)

WithTx executes fn within a transaction. If fn returns nil the transaction is committed; otherwise it is rolled back and a failing rollback is joined onto fn's error. Any panic inside fn also triggers a rollback, whose failure is logged rather than returned so the panic propagates unchanged.

type Settings

type Settings struct {
	// Mode selects the backend: ModeSQL (default) or ModePgx.
	Mode string

	// Driver is the database/sql driver name (e.g., "postgres", "pgx", "sqlite").
	// Only used in ModeSQL.
	Driver string

	// DSN is the data source name (connection string).
	DSN string

	// MaxOpenConns is the maximum number of open connections to the database.
	MaxOpenConns int32

	// MaxIdleConns is the maximum number of idle connections in the pool.
	// Only used in ModeSQL; pgx manages idle connections internally.
	MaxIdleConns int

	// ConnMaxLifetime is the maximum amount of time a connection may be reused.
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime is the maximum amount of time a connection may be idle.
	ConnMaxIdleTime time.Duration

	// ConnRetries is the number of times to retry connecting to the database
	// on failure. 0 means no retries (fail immediately).
	ConnRetries int

	// ConnRetryInterval is the base interval between connection retry attempts.
	// The interval doubles after each failed attempt (exponential backoff).
	ConnRetryInterval time.Duration
}

Settings represents the configuration required to establish and manage database connections.

Jump to

Keyboard shortcuts

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