Documentation
¶
Overview ¶
Package pg opens a Postgres pool for dbx through the pgx driver, with query tracing, pool metrics and a Classifier of Postgres error codes.
Usage ¶
db, err := pg.Open(pg.Config{
User: "postgres", Password: "postgres",
Host: "localhost:5432", Name: "app",
DisableTLS: true,
Metrics: reg, TracerProvider: tp,
})
if err != nil {
return err
}
defer db.Close()
if err := dbx.StatusCheck(ctx, db); err != nil {
return err
}
The returned *dbx.DB runs every dbx helper; its errors are classified by Classify: a unique violation (23505) wraps dbx.ErrDBDuplicatedEntry, a deadlock (40P01) or a serialization failure (40001) wraps dbx.ErrDBRetryable, on which dbx.WithinTran re-runs the transaction. The driver error stays reachable through errors.As, with its constraint and detail. Classify also serves a pool opened another way, such as through lib/pq: dbx.New(db, "postgres", pg.Classify).
Metrics ¶
With Config.Metrics set, Open registers the pool metrics there: go_sql_* (open, in-use and idle connections, waits, closes) labeled db_name with Config.Name and host with Config.Host, so a replica on another host is its own series. They read the pool stats on each scrape, without a query. A second pool of the same Host and Name on one registry is an error of Open.
Tracing ¶
Open records every query of the pool as a CLIENT span on Config.TracerProvider, named after the database (Config.Name). BEGIN and COMMIT are queries too, so a transaction shows as its own spans; dbx.StatusCheck pings past the tracer. The span carries db.system.name, db.namespace, server.address, server.port and db.query.text: the query as written, cut to 2 KiB. The arguments are never recorded — pass values as arguments, never in the query text. A Postgres error sets db.response.status_code and error.type to its SQLSTATE; no rows is not an error. A query from a suppressed context (otel.Suppress, the ticks of worker.Loop) records nothing.
Config ¶
Config fields: User, Password, Host, Name, Schema (sets search_path), MaxIdleConns and MaxOpenConns (zero keeps 5 idle and 20 open connections), ConnMaxLifetime and ConnMaxIdleTime (zero keeps 1h and 30m, as pgxpool), DisableTLS (true selects sslmode=disable, otherwise sslmode=require), Metrics (the registry of the pool metrics; nil disables them), TracerProvider (nil → the global provider). Open always sets timezone=utc.
Example ¶
Open builds the pool; StatusCheck waits until Postgres answers. Every query is a span, and the pool metrics are on the registry.
package main
import (
"context"
"log/slog"
"github.com/prometheus/client_golang/prometheus"
"github.com/assanoff/skit/dbx"
"github.com/assanoff/skit/dbx/pg"
)
func main() {
ctx := context.Background()
log := slog.Default()
db, err := pg.Open(pg.Config{
User: "postgres", Password: "postgres",
Host: "localhost:5432", Name: "shop",
DisableTLS: true,
Metrics: prometheus.NewRegistry(),
})
if err != nil {
log.ErrorContext(ctx, "open", "err", err)
return
}
defer func() { _ = db.Close() }()
if err := dbx.StatusCheck(ctx, db); err != nil {
log.ErrorContext(ctx, "status check", "err", err)
return
}
// pgx binds a slice as one Postgres array: ANY(:ids) keeps the query text
// the same for any number of ids.
const q = `SELECT name FROM widgets WHERE id = ANY(:ids)`
names, err := dbx.NamedQueryList[string](ctx, db, q, map[string]any{"ids": []int64{1, 3}})
if err != nil {
log.ErrorContext(ctx, "query", "err", err)
return
}
log.InfoContext(ctx, "widgets", "names", names)
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Classify ¶ added in v0.15.0
Classify is the dbx.Classifier of Postgres. It maps SQLSTATE codes onto the dbx sentinels: 23505 (unique violation) → dbx.ErrDBDuplicatedEntry, 40P01 (deadlock) and 40001 (serialization failure) → dbx.ErrDBRetryable. It wraps the driver error, so errors.As still reaches it with its constraint and detail.
Example ¶
Classify maps a SQLSTATE onto the dbx sentinels and keeps the driver error, so its constraint stays reachable.
package main
import (
"errors"
"fmt"
"github.com/jackc/pgx/v5/pgconn"
"github.com/assanoff/skit/dbx"
"github.com/assanoff/skit/dbx/pg"
)
func main() {
driverErr := &pgconn.PgError{Code: "23505", ConstraintName: "widgets_name_key"}
err := pg.Classify(fmt.Errorf("insert widget: %w", driverErr))
fmt.Println(errors.Is(err, dbx.ErrDBDuplicatedEntry))
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
fmt.Println(pgErr.ConstraintName)
}
err = pg.Classify(&pgconn.PgError{Code: "40P01"})
fmt.Println(errors.Is(err, dbx.ErrDBRetryable))
}
Output: true widgets_name_key true
func Open ¶
Open opens a pool through the pgx driver, bound to Classify. It does not verify connectivity; call dbx.StatusCheck for that. Every query is recorded as a span on cfg.TracerProvider. With cfg.Metrics set it registers the pool metrics; a pool of the same Host and Name already registered there is an error, and the new pool is closed.
Types ¶
type Config ¶
type Config struct {
User string
Password string
Host string
Name string
Schema string
// MaxIdleConns and MaxOpenConns bound the pool; zero keeps 5 idle and 20
// open connections.
MaxIdleConns int
MaxOpenConns int
// ConnMaxLifetime and ConnMaxIdleTime close a connection after that long
// open or idle; zero keeps 1h and 30m.
ConnMaxLifetime time.Duration
ConnMaxIdleTime time.Duration
DisableTLS bool
// Metrics is the registry of the pool metrics (go_sql_*, labeled db_name
// with Name and host with Host); nil disables them.
Metrics prometheus.Registerer
// TracerProvider records a span of every query; nil → the global
// provider.
TracerProvider trace.TracerProvider
}
Config holds connection settings.