Help us shape the future of Go! Take the 2026 Go Developer Survey

database

package module
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 11 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 manages a SQL database connection for a Gas app, with a database/sql backend for any registered driver and a native pgx backend for PostgreSQL. It adds transaction helpers, sqlc support in both modes, and connection retries with exponential backoff.

Role in the framework

Service implements the core interfaces gas.Service, gas.DatabaseProvider, gas.HealthReporter and gas.ReadyReporter. Other modules and app services depend on gas.DatabaseProvider, not on this package, and reach the *sql.DB through DB. In ModePgx, Pool returns the native *pgxpool.Pool, and PoolFrom recovers it from a gas.DatabaseProvider without a type assertion in the caller.

Wiring

New takes Options (WithConfig, WithConnector) and returns a constructor that the DI container calls with gas.ConfigProvider and gas.Logger. The app registers that constructor; the container builds the Service. The package registers nothing itself.

Configuration

Unless WithConfig is given, Init binds Config from the gas.ConfigProvider over DefaultConfig, so a key that is not set keeps its default. The keys sit under database: mode ("sql" by default, or "pgx"), driver ("postgres" by default; "pgx" and "sqlite" are also accepted; sql mode only), dsn (required unless a connector is set), maxopenconns (25, range 1 to 1000), maxidleconns (5, range 1 to 1000 and at most maxopenconns; sql mode only), connmaxlifetime (30m, range 1s to 2h), connmaxidletime (5m, range 1s to 1h and at most connmaxlifetime), connretries (0, no retry) and connretryinterval (2s). WithConfig replaces the whole Config and skips the provider, so start from DefaultConfig. WithConnector supplies a driver.Connector, which is used instead of driver and dsn and is rejected outside sql mode. Config.Validate enforces these rules, and an invalid Config fails Init.

Lifecycle

Init runs at startup. It validates the configuration, opens the connection (sql.Open, or sql.OpenDB with a connector, in sql mode; a pgxpool.Pool, with a *sql.DB derived from it, in pgx mode), applies the pool limits and pings the database with a 5-second timeout. A failed attempt is retried connretries times, waiting connretryinterval before the first retry and doubling the wait each time; Init blocks while it waits. The ping runs under Init's context, and when that context ends during a wait, Init stops retrying and returns an error wrapping both the context's error and the last connection error. When every attempt fails, Init returns the last error.

Close runs at shutdown. It marks the Service closed and closes the *sql.DB and, in pgx mode, the pool. After Close, Query, Exec, BeginTx, WithTx, BeginPgxTx and WithPgxTx return an error instead of touching the connection, and CheckHealth and CheckReady report the Service as closed.

The Service starts no goroutines of its own. database/sql and pgxpool manage their connection pools in the background until Close.

Health

CheckHealth fails only when the Service is closed or not initialized, states a restart would fix; a lost connection does not fail it, because both backends reconnect on their own. CheckReady pings the database, so it fails while the database is unreachable.

Transactions

WithTx and WithPgxTx run a function in a transaction: they commit when it returns nil and roll back when it returns an error or panics. A failed rollback is joined onto the function's error; after a panic it is logged and the panic propagates unchanged. A rollback that finds the transaction already finished is not an error. WithPgxTx rolls back with a context detached from cancellation and commits with the caller's context, so a canceled context fails the commit. BeginPgxTx and WithPgxTx return an error outside pgx mode.

Errors

Errors from an operation start with the service name, "gas/database", and wrap the driver's error with %w, so callers can match it with errors.Is or errors.As. Errors from Validate name the offending field instead, for example Database.DSN. The package defines no sentinel errors.

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, error)

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 {
	gas.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.

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(context.Context) 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(ctx context.Context) error

Init opens the database connection, configures the pool, and pings the database to verify connectivity. The ping and the retry backoff use ctx, so a canceled or expired ctx stops the retries.

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 `validate:"oneof=sql pgx"`

	// 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 `validate:"min=1,max=1000"`

	// 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 `validate:"min=1s,max=2h"`

	// ConnMaxIdleTime is the maximum amount of time a connection may be idle.
	ConnMaxIdleTime time.Duration `validate:"min=1s,max=1h,ltefield=ConnMaxLifetime"`

	// 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