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

einherjar/db-postgres

version license go health

The runes carved in stone do not fade when the runemaster dies. They outlast the hand that carved them.

code.nochebuena.dev/einherjar/db-postgres is the PostgreSQL database component of the Einherjar framework. It wraps pgxpool behind a lifecycle-aware Component, exposes a uniform Executor interface for queries and transactions, and provides a UnitOfWork that injects the active transaction into context — so repositories never need to know whether they are inside a transaction or not.


Usage

Setup

import dbpg "code.nochebuena.dev/einherjar/db-postgres"

db := dbpg.New(logger, dbpg.DefaultConfig())
launcher.Append(db)   // OnInit opens pool; OnStop closes it
health.Register(db)   // PING health check; LevelCritical

Querying

// GetExecutor returns the pool when called outside a UnitOfWork.
rows, err := db.GetExecutor(ctx).Query(ctx, "SELECT id, name FROM users WHERE active = $1", true)
defer rows.Close()

var name string
err := db.GetExecutor(ctx).QueryRow(ctx, "SELECT name FROM users WHERE id = $1", id).Scan(&name)

Manual transaction

tx, err := db.Begin(ctx)
if err != nil {
    return err
}
defer tx.Rollback(ctx)

_, err = tx.Exec(ctx, "UPDATE accounts SET balance = balance - $1 WHERE id = $2", amount, fromID)
if err != nil {
    return err
}
return tx.Commit(ctx)

BeginTx is available when you need explicit isolation level control:

tx, err := db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})

UnitOfWork wraps the transaction in context so every call to GetExecutor inside uow.Do automatically returns the active transaction. Repositories require no changes.

uow := dbpg.NewUnitOfWork(logger, db)

err := uow.Do(ctx, func(ctx context.Context) error {
    _, err := db.GetExecutor(ctx).Exec(ctx, "INSERT INTO orders (...) VALUES (...)", ...)
    return err
})

If the function returns an error, the transaction is rolled back. If it returns nil, the transaction is committed.

Error handling

if err := db.HandleError(someErr); err != nil {
    // pgconn error codes mapped to xerrors:
    // 23505 unique_violation      → ErrAlreadyExists
    // 23503 foreign_key_violation → ErrPreconditionFailed
    // 23502 not_null_violation    → ErrInvalidInput
    // context.Canceled            → ErrCancelled
    // context.DeadlineExceeded    → ErrDeadlineExceeded
}

HandleError is also available as a package-level function: dbpg.HandleError(err).


Environment variables

Variable Required Default Description
EINHERJAR_PG_HOST Yes PostgreSQL host
EINHERJAR_PG_PORT No 5432 Listen port
EINHERJAR_PG_USER Yes Database user
EINHERJAR_PG_PASSWORD Yes Database password
EINHERJAR_PG_NAME Yes Database name
EINHERJAR_PG_SSL_MODE No disable disable, require, verify-full
EINHERJAR_PG_TIMEZONE No UTC Session timezone
EINHERJAR_PG_MAX_CONNS No 5 Maximum connections in pool
EINHERJAR_PG_MIN_CONNS No 2 Minimum idle connections
EINHERJAR_PG_MAX_CONN_LIFETIME No 1h Maximum connection lifetime
EINHERJAR_PG_MAX_CONN_IDLE_TIME No 30m Maximum idle time before connection is closed
EINHERJAR_PG_HEALTH_CHECK_PERIOD No 1m pgxpool background health check interval

Dependency graph

contracts  (zero dependencies)
    ↑
  core
    ↑
db-postgres  (contracts, core, pgx/v5, pgerrcode)
    ↑
  your app

Verification

cd db-postgres/
go build ./...
go vet ./...
go test ./...
gofmt -l .

The hall is built before the warriors arrive. That is the only guarantee worth making.

Description
PostgreSQL component with pgxpool connection pooling and unit-of-work transactions
Readme 62 KiB
2026-05-29 09:50:41 -06:00
Languages
Go 100%