postgres

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 13 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var ErrDSNRequired = errors.New("dsn is required")

ErrDSNRequired is returned when DSN is empty in Config.

Functions

func InMemoryTransaction added in v0.8.0

func InMemoryTransaction(ctx context.Context) (any, bool)

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

func NewPool(ctx context.Context, cfg Config) (*pgxpool.Pool, error)

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

func OnComplete(ctx context.Context, done func())

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

func OnRollback(ctx context.Context, undo func())

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

func Ping(ctx context.Context, pool *pgxpool.Pool) error

Ping verifies database connectivity. Returns nil if the database is reachable, error otherwise.

func Stage added in v0.8.0

func Stage(ctx context.Context, apply func())

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

func TxFromContext(ctx context.Context) pgx.Tx

TxFromContext returns the transaction opened by PgUnitOfWork.Execute, or nil outside one.

func WithTx

func WithTx(ctx context.Context, pool *pgxpool.Pool, fn func(tx pgx.Tx) error) error

WithTx executes fn within a database transaction. The transaction is committed if fn returns nil; rolled back otherwise. Panics within fn cause rollback and re-panic.

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.

func (*HealthChecker) Check

func (c *HealthChecker) Check(ctx context.Context) bool

Check returns true if the database is reachable.

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.

func (*InMemoryUnitOfWork) Execute added in v0.5.0

func (u *InMemoryUnitOfWork) Execute(ctx context.Context, fn func(ctx context.Context) error) error

Execute runs fn in an in-memory transaction and applies its staged writes when fn returns nil. If ctx already carries an in-memory transaction, fn joins it and its staged writes apply when the outer transaction commits.

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.

func (*PgUnitOfWork) Execute added in v0.5.0

func (u *PgUnitOfWork) Execute(ctx context.Context, fn func(ctx context.Context) error) error

Execute runs fn in a transaction available through TxFromContext and Conn. It commits when fn returns nil and rolls back on error or panic. If ctx already carries a transaction, fn joins it and the outer Execute decides the outcome.

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.

func Conn added in v0.8.0

func Conn(ctx context.Context, pool *pgxpool.Pool) Querier

Conn returns the open transaction from ctx, or pool outside one. Pass the result to sqlc's New so queries run inside the UnitOfWork when there is one.

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.

Jump to

Keyboard shortcuts

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