Documentation
¶
Overview ¶
Package postgres provides database access utilities with tracing integration.
It offers pool initialization with tracing, health checks, connection metrics, and transaction management with auto-rollback.
Index ¶
- Variables
- func InMemoryTransaction(ctx context.Context) (any, bool)
- func NewPool(ctx context.Context, cfg Config) (*pgxpool.Pool, error)
- func OnComplete(ctx context.Context, done func())
- func OnRollback(ctx context.Context, undo func())
- func Ping(ctx context.Context, pool *pgxpool.Pool) error
- func Stage(ctx context.Context, apply func())
- func TxFromContext(ctx context.Context) pgx.Tx
- func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(tx pgx.Tx) error) error
- type Config
- type HealthChecker
- type InMemoryUnitOfWork
- type PgUnitOfWork
- type Querier
- type UnitOfWork
- type UnitOfWorkOption
Constants ¶
This section is empty.
Variables ¶
var ErrDSNRequired = errors.New("dsn is required")
ErrDSNRequired is returned when DSN is empty in Config.
Functions ¶
func InMemoryTransaction ¶ added in v0.8.0
InMemoryTransaction returns a comparable token that identifies the in-memory transaction in ctx, the same for every Execute that joins it. It reports false outside one.
func NewPool ¶
NewPool creates a new PostgreSQL connection pool with tracing. It registers a shutdown handler to close the pool gracefully. Returns *pgxpool.Pool directly for sqlc compatibility.
func OnComplete ¶ added in v0.8.0
OnComplete registers done to run once the in-memory transaction in ctx has ended, after its staged writes were applied or its undos ran, such as releasing a lock that must outlive the commit. Callbacks run in registration order. Outside a transaction, done runs immediately.
func OnRollback ¶ added in v0.8.0
OnRollback registers undo for an in-memory write that was applied eagerly, such as a reservation other transactions must see at once. Inside an in-memory transaction undo runs when it fails or panics, in reverse registration order, and is dropped on commit. Outside one, undo never runs.
func Ping ¶
Ping verifies database connectivity. Returns nil if the database is reachable, error otherwise.
func Stage ¶ added in v0.8.0
Stage registers apply as an in-memory write. Inside an in-memory transaction it is buffered and run in order on commit, or dropped on error. Outside one, apply runs immediately.
func TxFromContext ¶ added in v0.8.0
TxFromContext returns the transaction opened by PgUnitOfWork.Execute, or nil outside one.
Types ¶
type Config ¶
type Config struct {
// DSN is the PostgreSQL connection string.
// Required. Example: "postgres://user:pass@localhost:5432/db?sslmode=disable"
DSN string `koanf:"dsn"`
// MaxConns is the maximum number of connections in the pool.
MaxConns int32 `koanf:"max_conns"`
// MinConns is the minimum number of connections to keep open.
MinConns int32 `koanf:"min_conns"`
// MaxConnLifetime is the maximum lifetime of a connection.
MaxConnLifetime time.Duration `koanf:"max_conn_lifetime"`
// MaxConnIdleTime is the maximum time a connection can be idle.
MaxConnIdleTime time.Duration `koanf:"max_conn_idle_time"`
// HealthCheckPeriod is the interval between health checks.
HealthCheckPeriod time.Duration `koanf:"health_check_period"`
}
Config holds configuration for PostgreSQL pool initialization.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible default values. DSN is required and must be set by the caller.
type HealthChecker ¶
type HealthChecker struct {
// contains filtered or unexported fields
}
HealthChecker checks PostgreSQL pool connectivity. Implements grpchealth.HealthChecker interface.
func NewHealthChecker ¶
func NewHealthChecker(pool *pgxpool.Pool) *HealthChecker
NewHealthChecker creates a health checker for the given pool.
type InMemoryUnitOfWork ¶ added in v0.5.0
type InMemoryUnitOfWork struct{}
InMemoryUnitOfWork implements UnitOfWork without a database. Writes registered with Stage inside Execute are applied in order when fn succeeds and dropped when it fails or panics, so map-backed prototypes roll back like real transactions. Eager writes undo themselves through OnRollback.
func NewInMemoryUnitOfWork ¶ added in v0.5.0
func NewInMemoryUnitOfWork() *InMemoryUnitOfWork
NewInMemoryUnitOfWork creates an in-memory UnitOfWork.
type PgUnitOfWork ¶ added in v0.5.0
type PgUnitOfWork struct {
// contains filtered or unexported fields
}
PgUnitOfWork implements UnitOfWork with a PostgreSQL transaction stored in the context.
func NewUnitOfWork ¶ added in v0.5.0
func NewUnitOfWork(pool *pgxpool.Pool, opts ...UnitOfWorkOption) *PgUnitOfWork
NewUnitOfWork creates a UnitOfWork backed by the given connection pool.
type Querier ¶ added in v0.8.0
type Querier interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
}
Querier is the query surface shared by pgx.Tx and *pgxpool.Pool. It is compatible with the DBTX interface generated by sqlc for pgx/v5.
type UnitOfWork ¶ added in v0.5.0
type UnitOfWork interface {
Execute(ctx context.Context, fn func(ctx context.Context) error) error
}
UnitOfWork runs a function inside a transaction carried by its context. An already open transaction in ctx is joined silently.
type UnitOfWorkOption ¶ added in v0.8.0
type UnitOfWorkOption func(*PgUnitOfWork)
UnitOfWorkOption configures a PgUnitOfWork.
func SetLocalTenant ¶ added in v0.8.0
func SetLocalTenant() UnitOfWorkOption
SetLocalTenant makes each transaction issue SET LOCAL app.tenant_id with the Tenant from ctxutil.TenantID, so row-level security policies can read it via current_setting('app.tenant_id', true). Without a Tenant in ctx the setting stays unset. Off by default.
func TxOptions ¶ added in v0.8.0
func TxOptions(opts pgx.TxOptions) UnitOfWorkOption
TxOptions sets the options used to begin each transaction.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package guard enforces tenant-scoped uniqueness rules, such as "one user per e-mail address".
|
Package guard enforces tenant-scoped uniqueness rules, such as "one user per e-mail address". |
|
Package lease grants mutual exclusion between processes through Postgres session advisory locks, all held on one connection per process.
|
Package lease grants mutual exclusion between processes through Postgres session advisory locks, all held on one connection per process. |
|
Package notify multiplexes Postgres LISTEN/NOTIFY over one connection per process.
|
Package notify multiplexes Postgres LISTEN/NOTIFY over one connection per process. |
|
Package numbering hands out gapless numbers per (tenant, context, name), such as invoice numbers.
|
Package numbering hands out gapless numbers per (tenant, context, name), such as invoice numbers. |