Files
db-postgres/doc.go
Rene Nochebuena 4b58f8e3d9 feat(db-postgres): initial implementation — pgx pool with lifecycle and UnitOfWork (v1.0.0)
Introduces code.nochebuena.dev/einherjar/db-postgres — the PostgreSQL database
starter for the Einherjar framework. Absorbs the postgres package from micro-lib,
replacing fmt.Errorf wrapping with core/xerrors and migrating from pgx v4 to pgx v5.

Interfaces (CT-6: one TypeSpec per file):
- Executor — Exec, Query, QueryRow (pgx-native types)
- Tx — Executor + Commit(ctx), Rollback(ctx)
- Provider — GetExecutor, Begin, BeginTx, Ping, HandleError
- Component — lifecycle.Component + observability.Checkable + Provider + Stats()
- UnitOfWork — Do(ctx, fn)

Implementation:
- New(logger, cfg) Component — pool not created until OnInit
- OnInit: pgxpool.NewWithConfig with duration parsing; 30s timeout
- OnStart: PING with 5s timeout; logs "postgres: connected"
- OnStop: pool.Close(); logs "postgres: closing pool"
- GetExecutor: returns active Tx from context (ctxTxKey) or pool; nil-safe
- Begin/BeginTx: wraps pgx.TxOptions; wrapped in xerrors on error
- HealthCheck: delegates to Ping; Priority LevelCritical
- Stats() *pgxpool.Stat — zero value when pool uninitialized
- NewUnitOfWork(logger, provider) UnitOfWork — Begin+inject+commit/rollback
- HandleError: UniqueViolation→ErrAlreadyExists, ForeignKey/Check→ErrInvalidInput,
  pgx.ErrNoRows→ErrNotFound, all others→ErrInternal

Config (EINHERJAR_PG_* env vars):
  Host, Port(5432), User, Password, Name, SSLMode(disable), Timezone(UTC),
  MaxConns(5), MinConns(2), MaxConnLifetime(1h), MaxConnIdleTime(30m),
  HealthCheckPeriod(1m)

- Component interface embeds observability.Identifiable; identifiable.go implements
  ModulePath and ModuleVersion via runtime/debug.ReadBuildInfo() — prints in launcher banner
2026-05-29 15:50:20 +00:00

58 lines
2.0 KiB
Go

// Package postgres provides a pgx-backed PostgreSQL client with lifecycle management,
// health checks, and unit-of-work transaction support for Einherjar applications.
//
// # Overview
//
// [New] returns a [Component] that manages a [pgxpool.Pool] connection pool,
// satisfies the [lifecycle.Component] lifecycle hooks (OnInit, OnStart, OnStop),
// and implements [observability.Checkable] with critical priority.
//
// [NewUnitOfWork] wraps multiple repository operations in a single transaction
// via context injection — no transaction object is passed between functions.
//
// # Lifecycle Registration
//
// db := postgres.New(logger, cfg)
// launcher.Register(db)
// health.Register(db)
//
// # Querying
//
// Repository code receives a [Provider] or [Executor] and calls [Provider.GetExecutor]
// to obtain the active transaction (if inside a [UnitOfWork]) or the pool:
//
// exec := db.GetExecutor(ctx)
// row := exec.QueryRow(ctx, "SELECT id FROM users WHERE email = $1", email)
// if err := row.Scan(&id); err != nil {
// return db.HandleError(err) // maps pgx.ErrNoRows → ErrNotFound, etc.
// }
//
// # Unit of Work
//
// [NewUnitOfWork] wraps operations in a single transaction. The transaction is
// injected into the context; [Provider.GetExecutor] returns it automatically.
//
// uow := postgres.NewUnitOfWork(logger, db)
// err := uow.Do(ctx, func(ctx context.Context) error {
// exec := db.GetExecutor(ctx) // returns active Tx
// _, err := exec.Exec(ctx, "INSERT INTO orders ...")
// return err
// })
//
// # Error Handling
//
// [HandleError] translates pgx and PostgreSQL error codes into typed
// [xerrors] values. Call it at every point where a pgx error is first observed:
//
// if err := row.Scan(&out); err != nil {
// return db.HandleError(err)
// }
//
// Mapped codes:
// - UniqueViolation → ErrAlreadyExists
// - ForeignKeyViolation → ErrInvalidInput
// - CheckViolation → ErrInvalidInput
// - pgx.ErrNoRows → ErrNotFound
// - all others → ErrInternal
package postgres