Documentation
¶
Overview ¶
Package postgres carries a PostgreSQL connection on the request context, runs work inside transactions installed on that context, and applies migrations.
The presets subpackage builds the connection pools behind Config. The postgrestest subpackage builds the databases tests run against.
Index ¶
- Constants
- Variables
- func GetContext(ctx context.Context) (bun.IDB, error)
- func Health(ctx context.Context) error
- func InTx(ctx context.Context) bool
- func NewContext(ctx context.Context, config Config) (context.Context, error)
- func NewContextSchema(ctx context.Context, config Config, schema string, create bool) (context.Context, error)
- func Ping(ctx context.Context, client *bun.DB) error
- func RunMigrations(ctx context.Context, db *bun.DB, migrations fs.FS) error
- func RunMigrationsContext(ctx context.Context, migrations fs.FS) error
- func TransferContext(baseCtx, destCtx context.Context) context.Context
- func WithTx(ctx context.Context, tx bun.IDB) context.Context
- func WithinTx(ctx context.Context, opts *sql.TxOptions, ...) error
- type Config
- type ContextKey
- type Transactor
Constants ¶
const ( // PingTimeout bounds how long Ping keeps retrying before giving up. PingTimeout = 10 * time.Second // PingRetryInterval is the wait between failed ping attempts, keeping Ping // from tight-looping reconnects on an unreachable database. PingRetryInterval = 100 * time.Millisecond )
const HealthTimeout = time.Second
HealthTimeout bounds one database health probe when the caller has not already supplied a shorter deadline.
Variables ¶
var ErrNoDBInContext = errors.New("context does not contain a bun.DB")
ErrNoDBInContext is returned by an operation that needs the connection pool, such as RunMigrationsContext or Health, when the context carries a transaction instead. ErrNoIDBInContext covers the case of no connection at all.
var ErrNoIDBInContext = errors.New("context does not contain a bun.IDB")
ErrNoIDBInContext is returned by GetContext when the context carries no bun.IDB, meaning it was never seeded by NewContext or one of its variants. ErrNoDBInContext covers the stricter case where a connection is present but is not a full *bun.DB.
Functions ¶
func GetContext ¶
GetContext returns the bun.IDB stored in ctx by NewContext or one of its variants, or ErrNoIDBInContext when none is present.
func Health ¶ added in v0.35.0
Health probes the connection pool ctx carries, once. It retries a discarded connection, or a server that is restarting, within HealthTimeout, or within the deadline of ctx when that comes first. Any other error is unhealthy, and so is a ctx carrying no database, or only a transaction.
func InTx ¶ added in v0.23.0
InTx reports whether ctx carries an open transaction. It reports false when ctx carries the connection pool, and false when it carries no database at all.
Work that must not hold a pooled connection, such as a call to an external service, guards itself with it.
It reports true under `postgrestest.RunTransactionalTest`, which puts a transaction on the context. A test covering an outbound call must therefore use `postgrestest.RunDBTest`, which puts a real pool on the context.
func NewContext ¶
NewContext derives a context carrying a connection to the primary database, for later retrieval with GetContext.
func NewContextSchema ¶
func NewContextSchema(ctx context.Context, config Config, schema string, create bool) (context.Context, error)
NewContextSchema derives a context carrying a connection scoped to the named schema, creating the schema first when create is true.
func Ping ¶
Ping retries a database connection until it answers or PingTimeout passes. It honors ctx cancellation both for each attempt and for the wait between attempts.
func RunMigrations ¶
RunMigrations runs all the migrations found in the provided filesystem.
Runners against one schema apply migrations one at a time: a runner waits for another to finish, then applies what is left. A runner keeps one connection of the pool for that wait, so the pool needs room for two. A migration is recorded once it succeeds, so a failed one runs again next time. PostgreSQL runs a migration file as a single transaction, so a failure leaves nothing of it behind, unless the file is split with --bun:split.
Give the connection a lock_timeout. Without one, a migration waits on any lock a long transaction holds, and every query on its table queues behind it. With one, the migration gives up instead, then runs again after a pause, a few times.
func RunMigrationsContext ¶
RunMigrationsContext runs all the migrations found in the provided filesystem, using the database connection from the context.
func TransferContext ¶
TransferContext copies the database handle baseCtx carries onto destCtx, such as onto a detached context a background task runs under. It returns destCtx unchanged when baseCtx carries none.
func WithTx ¶ added in v0.23.0
WithTx derives a context carrying tx, so GetContext resolves that transaction.
WithinTx applies it and is what callers normally want. WithTx serves a caller that owns the transaction lifecycle itself, such as a test harness wrapping a whole suite.
func WithinTx ¶ added in v0.23.0
func WithinTx(ctx context.Context, opts *sql.TxOptions, callback func(ctx context.Context) error) error
WithinTx runs callback inside a transaction opened on the connection ctx carries. The context callback receives carries that transaction, so every call made with that context joins it.
The callback takes no transaction argument: the context it receives is the only database handle reachable inside it, so no call can escape unnoticed.
A nested call joins the transaction already in progress, so one unit of work has one outcome and a rollback anywhere discards all of it. A nested call never reaches opts: an operation depending on a specific isolation level must be the outermost transaction.
Types ¶
type Config ¶
type Config interface {
// DB returns a connection to the primary database, opening it on first call
// and reusing it thereafter.
DB(ctx context.Context) (*bun.DB, error)
// DBSchema returns a connection scoped to the named schema, creating the
// schema first when create is true. An empty schema name yields the primary
// connection.
DBSchema(ctx context.Context, schema string, create bool) (*bun.DB, error)
}
Config supplies pooled bun database connections. It owns the driver options and the lifecycle of each connection. The context, migration and test helpers obtain their handles through it. postgrespresets.Default is the standard implementation.
type ContextKey ¶
type ContextKey struct{}
ContextKey is the context value key under which the package stores the active bun.IDB connection.
type Transactor ¶ added in v0.23.0
type Transactor struct {
// contains filtered or unexported fields
}
A Transactor is the PostgreSQL implementation of github.com/a-novel-kit/golib/transaction.Transactor.
func NewTransactor ¶ added in v0.23.0
func NewTransactor(opts *sql.TxOptions) *Transactor
NewTransactor returns a Transactor opening its transactions with opts. A nil opts leaves the database defaults in place, which is read-committed isolation.
func (*Transactor) WithinTx ¶ added in v0.23.0
func (transactor *Transactor) WithinTx(ctx context.Context, fn func(ctx context.Context) error) error
WithinTx satisfies github.com/a-novel-kit/golib/transaction.Transactor.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package postgrestest provides PostgreSQL test harnesses backed by postgres.
|
Package postgrestest provides PostgreSQL test harnesses backed by postgres. |
|
Package postgrespresets builds the PostgreSQL connection pools behind github.com/a-novel-kit/golib/postgres.Config, from a URL or from discrete connection settings.
|
Package postgrespresets builds the PostgreSQL connection pools behind github.com/a-novel-kit/golib/postgres.Config, from a URL or from discrete connection settings. |