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
- func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) *Service
- func PoolFrom(provider gas.DatabaseProvider) (*pgxpool.Pool, bool)
- type Config
- type Option
- type Service
- func (s *Service) BeginPgxTx(ctx context.Context, opts *pgx.TxOptions) (pgx.Tx, error)
- func (s *Service) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
- func (s *Service) CheckHealth(_ context.Context) error
- func (s *Service) CheckReady(ctx context.Context) error
- func (s *Service) Close() error
- func (s *Service) DB() *sql.DB
- func (s *Service) Driver() string
- func (s *Service) Exec(ctx context.Context, query string, args ...any) (gas.Result, error)
- func (s *Service) Init() error
- func (s *Service) Name() string
- func (s *Service) Ping(ctx context.Context) error
- func (s *Service) Pool() *pgxpool.Pool
- func (s *Service) Query(ctx context.Context, query string, args ...any) (gas.Rows, error)
- func (s *Service) WithPgxTx(ctx context.Context, opts *pgx.TxOptions, fn func(pgx.Tx) error) (err error)
- func (s *Service) WithTx(ctx context.Context, opts *sql.TxOptions, fn func(*sql.Tx) error) (err error)
- type Settings
Constants ¶
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.
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 ¶
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.
type Option ¶
type Option func(*Service)
Option configures a Service.
func WithConnector ¶
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 ¶
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 ¶
BeginTx starts a new database transaction. The caller is responsible for calling Commit or Rollback on the returned *sql.Tx.
func (*Service) CheckHealth ¶
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 ¶
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) DB ¶
DB returns the underlying *sql.DB. This satisfies gas.DatabaseProvider and works in both ModeSQL and ModePgx (via stdlib adapter).
func (*Service) Driver ¶
Driver returns the database driver name based on the configured mode and settings.
func (*Service) Exec ¶
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 ¶
Init opens the database connection, configures the pool, and pings the database to verify connectivity.
func (*Service) 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 ¶
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.