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

database

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

go-database

go-database is an SQL infrastructure library for Standards Lab's Go Elemental standard. It holds four things:

  • the connection pool, with its configuration, lifecycle, and readiness
  • the database admin service, built over the sqlate library
  • the sweeper, which runs a service's reclaimers
  • the Postgres provider

github.com/standards-lab/go-database is the base module, holding the database package at its root and admin and sweep beside it. github.com/standards-lab/go-database/postgres is a nested sub-module that pins the driver and is released on its own tags.

Standard

go-database is an infrastructure library of Go Elemental, the minimal-dependency Go standard. This README and each package's doc.go document the repository; the standard's principles it enhances are stated below. Its repository-level principles:

  • The base module depends on the standard library, go-core, and sqlate; the driver enters a consumer's graph only through the postgres sub-module, imported once at the composition root.
  • sqlate owns the SQL layer above the pool: statements, sessions, transactions, and the dialect. The composition root wraps the pool this library constructs with sqlate.Wrap and the engine's dialect from sqlate/postgres, and the provider's native API stays reachable through DB.Conn() and the Options map.
  • Swapping the SQL provider is a port. The consumer owns its schema, its migrations, and its domain SQL, and those are what a swap rewrites. A library that ships its own migration set, such as blobfs, owns that set; the consumer declares it beneath its own.

Packages

  • database wraps a database/sql pool with lifecycle integration and holds the service's configuration block and its connectivity error sentinels.
  • admin is the database admin service: schema verification, migration, seeding, named states, and diagnostics, run at startup and on demand as operations over sqlate's functions. One service administers every migration set its migrator runs: status and reset cover them all, and the verbs that target one set, including force for dirty-set repair, take its name.
  • sweep runs a service's reclaimers, the bounded passes its libraries' garbage is removed in, as one go-core reactor: each on its own interval or when nudged by name, under a per-reclaimer advisory lock so one replica reclaims at a time, and paused under the service's quiesce gate. It imports no reclaimer; blobfs's sweep and go-messaging's retention satisfy its interface.
  • postgres is the PostgreSQL provider: it constructs the pool over pgx's database/sql adapter from the configuration block.

Development

The repository uses a Go workspace and mise:

mise run check      # build, vet, format, fix, tidy, test, and lint every module; writes nothing
mise run currency   # report requirements, Go, tools, and actions behind their latest
mise run upgrade    # upgrade every module's go directive and requirements, and the tools, to their latest

License

Apache License 2.0.

Documentation

Overview

Package database wraps a database/sql connection pool with lifecycle hooks, readiness, and the Config block that sizes it. Drivers live in provider sub-modules (postgres) that construct the pool and call New; sqlate owns the SQL layer above the pool, and the composition root wraps DB.Conn with sqlate.Wrap. A wiring defect, such as an unfinalized config, panics; a defect in configuration content is an error.

Configuration

Config holds the connection identity, pool sizing, and timeouts. Config.Merge overlays another block's set fields, Config.Finalize applies defaults and environment overrides and validates, and Config.Finalized reports whether New can use the result. NewEnv composes the override names from a prefix into an Env, which Finalize records on the config.

Pool

New wraps a provider-constructed pool in a DB. DB.Start and DB.Shutdown are its lifecycle hooks, DB.Ready and DB.Ping check connectivity, DB.Conn returns the pool, and DB.ConnTimeout returns the bound Start and Ready apply to a ping.

A composition root defines the DB as a node of a go-core graph and hands the built System to a lifecycle Coordinator. The DB is a lifecycle Starter, Stopper, and ReadinessChecker, so the Coordinator starts it in its layer, shuts it down, and lists its readiness among its Checks under the node's name. The DB needs no adapter:

g := graph.New()
db := g.Define("database", func(*graph.Scope) (*database.DB, error) {
	return postgres.New(cfg)
})
// The nodes that query the database call s.Use(db).
sys, err := g.Build(roots...)
if err != nil {
	return err
}
return lifecycle.New(sys, lifecycleCfg).Run(ctx)

The Coordinator also calls Shutdown after a failed Start, which DB.Shutdown allows.

Errors

ErrNotReady reports a call before Start or after Shutdown. ErrConnectionFailed, which is sqlate's sentinel, reports a failure to reach the database.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotReady reports a call against a [DB] before a successful Start
	// or after Shutdown.
	ErrNotReady = errors.New("database not ready")

	// ErrConnectionFailed reports a failure to reach the database; it is
	// sqlate's sentinel.
	ErrConnectionFailed = sqlate.ErrConnectionFailed
)

Functions

This section is empty.

Types

type Config

type Config struct {
	Host            string            `json:"host"`
	Name            string            `json:"name"`
	User            string            `json:"user"`
	Password        string            `json:"password"`
	Port            *int              `json:"port"`
	MaxOpenConns    *int              `json:"max_open_conns"`
	MaxIdleConns    *int              `json:"max_idle_conns"`
	ConnMaxLifetime *config.Duration  `json:"conn_max_lifetime"`
	ConnMaxIdleTime *config.Duration  `json:"conn_max_idle_time"`
	ConnTimeout     *config.Duration  `json:"conn_timeout"`
	Options         map[string]string `json:"options"`
	Env             Env               `json:"-"`
}

Config holds the connection identity, pool sizing, and timeouts. Its numeric and duration fields are tri-state pointers: nil takes the default, and an explicit zero means what it says; a nil Port takes the provider's default. Password comes from the secrets layer, never a committed file. Options passes dialect-specific keys through to the provider.

func (*Config) Finalize

func (c *Config) Finalize(envPrefix string) error

Finalize applies defaults, then the environment overrides NewEnv names from envPrefix (none for an empty prefix), and validates; Name is required.

func (*Config) Finalized added in v0.7.0

func (c *Config) Finalized() bool

Finalized reports whether Finalize has filled every field New reads.

func (*Config) Merge

func (c *Config) Merge(src *Config)

Merge overlays src's set fields onto the receiver. Options merges key-wise, so an overlay can set one connection option without dropping the rest.

type DB

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

DB is a provider-constructed connection pool with lifecycle hooks.

func New

func New(conn *sql.DB, cfg Config) *DB

New wraps a provider-constructed pool and applies cfg's pool settings. It panics on an unfinalized cfg or a nil conn.

func (*DB) Conn

func (d *DB) Conn() *sql.DB

Conn returns the underlying connection pool.

func (*DB) ConnTimeout added in v0.7.0

func (d *DB) ConnTimeout() time.Duration

ConnTimeout returns the configured conn_timeout, the bound Start and Ready apply to a ping.

func (*DB) Ping

func (d *DB) Ping(ctx context.Context) error

Ping pings the database under the caller's context: ErrNotReady before Start or after Shutdown, and a failure wraps ErrConnectionFailed.

func (*DB) Ready

func (d *DB) Ready() bool

Ready reports whether Start succeeded and a ping bounded by conn_timeout succeeds now.

func (*DB) Shutdown

func (d *DB) Shutdown(ctx context.Context) error

Shutdown clears readiness and closes the pool, returning the close error; closing a pool that never connected is a no-op.

func (*DB) Start

func (d *DB) Start(ctx context.Context) error

Start pings the database, bounded by conn_timeout, and marks it started; a failure wraps ErrConnectionFailed around the driver's error.

type Env

type Env struct {
	Host            string
	Name            string
	User            string
	Password        string
	Port            string
	MaxOpenConns    string
	MaxIdleConns    string
	ConnMaxLifetime string
	ConnMaxIdleTime string
	ConnTimeout     string
}

Env holds the environment-variable names Config.Finalize read.

func NewEnv

func NewEnv(prefix string) Env

NewEnv composes the override names under prefix, such as PREFIX_DATABASE_HOST.

Directories

Path Synopsis
Package admin is the database admin service: schema state, verification, correction, seeding, named states, and diagnostics as operations over the sqlate library's functions, run once at startup and on demand from an administrative surface.
Package admin is the database admin service: schema state, verification, correction, seeding, named states, and diagnostics as operations over the sqlate library's functions, run once at startup and on demand from an administrative surface.
postgres module
Package sweep runs a service's reclaimers, the bounded passes that remove what its libraries leave behind, as one go-core reactor.
Package sweep runs a service's reclaimers, the bounded passes that remove what its libraries leave behind, as one go-core reactor.

Jump to

Keyboard shortcuts

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