Documentation
¶
Index ¶
- func Connect(ctx context.Context, dbURL string, key string) (*pgxpool.Pool, error)
- func IsEmbeddedPostgres(dbURL string) bool
- func IsTestContainer(dbURL string) bool
- func OpenPool(ctx context.Context, dbcfg DBConfig, migrator *Migrator) (*pgxpool.Pool, error)
- func OpenPoolWithKey(ctx context.Context, dbcfg DBConfig, migrator *Migrator, key string) (*pgxpool.Pool, error)
- func WaitForGracefulShutdown()
- type DBConfig
- type Migrator
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Connect ¶
Connect returns a pgxpool.Pool for the given database URL.
The key parameter identifies this connection for tracking embedded Postgres instances used during graceful shutdown. When called via OpenPoolWithKey the key is the pool key; direct callers should supply a unique non-empty string.
If dbURL starts with "postgres:embedded:", it spins up an embedded Postgres instance automatically. Query parameters after the prefix are parsed as options (e.g. "?datapath=/tmp/pgdata" sets the Postgres data directory via Config.DataPath). Unrecognized parameters are ignored. If no datapath is specified, a temporary directory is created and cleaned up on failure.
Reused embedded Postgres instances (detected via an existing postmaster.pid at the data path) are registered for graceful shutdown and will be stopped (SIGTERM → SIGKILL) when the application exits via WaitForGracefulShutdown.
If dbURL starts with "postgres:tc:", it spins up a Testcontainer automatically. The testcontainer process lifetime is managed by the Docker daemon; callers should invoke pool.Close() when done with the connection.
func IsEmbeddedPostgres ¶ added in v0.4.0
IsEmbeddedPostgres reports whether dbURL starts with the "postgres:embedded:" prefix.
func IsTestContainer ¶ added in v0.4.0
IsTestContainer reports whether dbURL starts with the "postgres:tc:" prefix.
func OpenPool ¶
OpenPool returns the process-wide singleton pgxpool connection. The caller supplies the DBConfig (typically from AppConfig.DBConfig). The pool is created on the first call and reused on subsequent calls. A SIGTERM/SIGINT handler is registered to gracefully close the pool on shutdown.
func OpenPoolWithKey ¶ added in v0.0.8
func OpenPoolWithKey(ctx context.Context, dbcfg DBConfig, migrator *Migrator, key string) (*pgxpool.Pool, error)
OpenPoolWithKey returns a keyed pgxpool connection. If the pool is not found, it is created with the given key and save in the pools. the cached pool will be returned directly on the second time it is called with given key.
func WaitForGracefulShutdown ¶ added in v0.6.0
func WaitForGracefulShutdown()
WaitForGracefulShutdown blocks until the graceful shutdown handler has completed all cleanup (closing connection pools and stopping embedded Postgres instances). If no shutdown signal has been received, it blocks indefinitely.
This function only affects locally embedded Postgres instances (started via "postgres:embedded:" URLs). It does NOT stop, restart, or otherwise interfere with remote Postgres servers — for those, it merely closes the client-side connection pool (a normal disconnect) and returns almost instantly.
Consuming applications MUST call this at the end of main (or in their signal handler) to prevent the process from exiting before the embedded Postgres shutdown sequence completes. Without this call, main may return while the shutdown goroutine is still running, causing the Go runtime to terminate all goroutines — including the one performing cleanup.
func main() {
// ... start servers, open pools ...
<-waitForSignal() // app's own signal handling
// ... stop HTTP servers ...
postgres.WaitForGracefulShutdown() // block until pools and embedded PG are cleaned up
}
Types ¶
type DBConfig ¶
type DBConfig struct {
Host string `env:"HOST" envDefault:"localhost"`
Port int `env:"PORT" envDefault:"5432"`
User string `env:"USER"`
Password string `env:"PASSWORD"`
Name string `env:"NAME"`
CloudSQLInstance string `env:"CLOUD_SQL_INSTANCE"`
// MigrationSchema sets the PostgreSQL search_path for atlas migrations.
// Switching from the default "public" to another schema creates a new
// atlas_schema_revisions table in that schema; existing migration history
// in "public" is not carried over.
MigrationSchema string `env:"MIGRATION_SCHEMA" envDefault:"public"`
DatabaseURLTemplate string `env:"URL_TEMPLATE" envDefault:"postgres:tc://[username]:[password]@[host]:[port]/[database_name]"`
}
DBConfig holds the database connection parameters. Environment variables are read with the "DB_" prefix (e.g. DB_HOST, DB_PORT).
func (DBConfig) ResolveURL ¶
ResolveURL expands the DatabaseURLTemplate placeholders using the struct's own credential fields.
type Migrator ¶ added in v0.0.2
type Migrator struct {
// IsBaseline is invoked by runMigrations to determine whether the current
// run should only record a baseline (i.e. mark existing migrations as
// already applied without executing their SQL). A nil func disables
// baseline handling entirely.
IsBaseline func(ctx context.Context, pool *pgxpool.Pool) bool
// contains filtered or unexported fields
}
Migrator bundles the migration file source with a caller-supplied baseline predicate. It is passed to OpenPool (and internally to runMigrations) so that the baseline decision is made by the caller rather than hard-coded.
func NewMigrator ¶ added in v0.0.2
func NewMigrator(migrationFiles fs.FS, isBaseline func(context.Context, *pgxpool.Pool) bool) *Migrator
NewMigrator creates a Migrator with the supplied migration file source and baseline predicate. Either argument may be nil; a nil IsBaseline disables baseline detection.