Building a Library on pgdorm#
Shipping a reusable async Python package (my-library[pgdorm]) — such as a job queue, workflow checkpointer, auth extension, or event store — has different requirements from an application. Your library must never pollute the host app's global registry, must participate cleanly in the caller's transactions, and must behave predictably behind PgBouncer.
This guide covers the exact contracts for embedding pgdorm inside a downstream package.
1. Isolated pg.Registry() & FrozenRegistry#
pgdorm does not require a global metaclass registry. Construct a private pg.Registry(), register your library's tables into it, and call .freeze() to produce an immutable FrozenRegistry validated by validate_schema_set:
class Job(pg.Table):
job_id: pg.Col[int] = pg.pk(default=pg.identity())
queue: pg.Col[str] = pg.col(index=True)
payload: pg.Col[pg.Jsonb[dict[str, object]]] = pg.col()
class JobAttempt(pg.Table):
job_attempt_id: pg.Col[int] = pg.pk(default=pg.identity())
job_id: pg.Col[int] = pg.fk(Job.job_id)
def build_registry() -> pg.FrozenRegistry:
reg = pg.Registry()
reg.register(Job, JobAttempt)
return reg.freeze()
LIB_REGISTRY: pg.FrozenRegistry = build_registry()
Passing LIB_REGISTRY (or list(LIB_REGISTRY.tables)) to pool.create_all(...) or MigrationApp keeps your package's schema completely isolated from the host application's tables.
2. Accepting Caller Connections via pgdorm.typing#
Never force host applications to hand your library a raw DSN and spin up a second connection pool. Accept the caller's Pool or active Transaction using the protocols in pgdorm.typing (see Typing & Testing Reference):
| Protocol / Type | Accepts | Use When |
|---|---|---|
ReadPool |
Pool, Transaction (read-only surface) |
Read-only queries (select, all, one, one_or_none, first) |
Pool |
Top-level connection pool | Library manages its own transactions or pipelines |
ReadTransaction |
Active read-only transaction | Consistent multi-query reads inside caller's snapshot |
Transaction |
Active read/write transaction | Library mutations must commit/rollback atomically with caller's work |
ReadQuery[Row] |
Select[Row] |
Helper functions that compose or execute read queries |
Executable[Row] |
Select, Insert, Update, Delete, Merge |
Generic execution helpers accepting reads or writes |
async def get_job(conn: ReadPool | Transaction, job_id: int) -> Job | None:
return await conn.one_or_none(pg.select(Job).where(Job.job_id == job_id))
async def enqueue_job(tx: Transaction, queue: str, payload: dict[str, object]) -> Job:
return await tx.one(pg.insert(Job).values(Job(queue=queue, payload=payload)).returning(Job))
Because Transaction satisfies ReadPool, get_job(tx, ...) and get_job(pool, ...) both type-check cleanly under a strict type checker.
3. Schema-Scoped Embedded Migrations#
Isolate your library's tables into a dedicated PostgreSQL schema (schema="my_lib") and run migrations programmatically inside your library's async def setup(pool: pg.Pool) lifecycle hook using pgdorm.migrate (see Migrations & CLI Reference):
APP = MigrationApp(
tables=LIB_REGISTRY.tables,
schema="my_lib",
)
async def setup_library(pool: pg.Pool, schema: str = "my_lib") -> None:
await sync_schema(pool, tables=LIB_REGISTRY.tables, schema=schema)
async def ensure_no_drift(pool: pg.Pool, schema: str = "my_lib") -> None:
report = await check_drift(pool, tables=LIB_REGISTRY.tables, schema=schema)
if not report.in_sync:
raise RuntimeError(f"my_lib schema drift detected: {report}")
For development or ephemeral test databases, await sync_schema(pool, tables=LIB_REGISTRY.tables, schema="my_lib") reconciles schema state directly without maintaining revision files.
4. Error Contracts & Retries#
Catch specific pgdorm exceptions rather than parsing error strings (see Errors & Linters Reference):
pg.UniqueViolationError(23505): Idempotent inserts or duplicate natural keys.pg.LockNotAvailableError(55P03):NOWAITlock contention when claiming a resource.pg.RetryablePgError(40001serialization failure,40P01deadlock): Wrap retryable library operations inpool.retry_transaction(...).pg.PostgresError: Base class for all server-returned PostgreSQL errors (exposes.sqlstate,.message,.constraint_name).
async def claim_idempotent(pool: pg.Pool, job_id: int) -> bool:
try:
await pool.execute(
pg.insert(Job).values(Job(job_id=job_id, queue="default", payload={"id": job_id}))
)
except pg.UniqueViolationError:
return False
return True
5. Observability & PgBouncer Compatibility#
Telemetry (TelemetryHook & set_telemetry)#
pgdorm ships zero built-in OpenTelemetry or logging adapters. Instead, host applications register a lightweight TelemetryHook via pg.set_telemetry(hook) (see Runtime & Pool Reference). As a library author, attach .tag("my_lib.<operation>") to every query you build — pgdorm emits /* op:my_lib.<operation> */ and forwards the tag to the host's telemetry hook automatically.
PoolMode Capability Contract (DIRECT vs TRANSACTION)#
Host applications frequently run behind PgBouncer or Supavisor in transaction-pooling mode (Pool.connect(..., pool_mode=pg.enums.PoolMode.TRANSACTION)). Design your library against this capability matrix:
| Capability | PoolMode.DIRECT |
PoolMode.TRANSACTION |
Library Author Guidance |
|---|---|---|---|
Standard queries & tx.pipeline() |
Supported | Supported | Safe everywhere |
local_settings= (set_config(..., true)) |
Supported | Supported | Always use transaction-scoped settings |
pg_temp staging (on_commit=pg.enums.OnCommit.DROP) |
Supported | Supported | Always use OnCommit.DROP (never OnCommit.DELETE_ROWS) |
| Prepared statements | Enabled by default | Optional (prepared_statements=False) |
Works transparently with unnamed statements |
Session-level LISTEN / NOTIFY |
Supported | Not supported | Require a dedicated direct connection for listeners |
Session advisory locks (pg_advisory_lock) |
Supported | Not safe | Use transaction-scoped pg_advisory_xact_lock instead |
6. Downstream Pytest Harness (pgdorm.testing)#
Install the optional pgdorm[testing] extra in your package's dev dependencies to reuse pgdorm's zero-mock PostgreSQL test harness in your own conftest.py (see Typing & Testing Reference):
PG18_IMAGE&postgres_container(...): Launches a stock PostgreSQL container at the supported baseline (lazy-importstestcontainers).TestDB: Per-test isolated schema fixture (t_<hex>) so parallel pytest workers never collide.assert_compiles(query, expected_sql): Fast, zero-Docker unit assertion for verifying compiled SQL shapes.make_syrupy_extension(...): Deterministic snapshot extension for pinning SQL andEXPLAINplans in CI.
@pytest.fixture(scope="session")
def example_pg_dsn() -> Iterator[str]:
with postgres_container(image=PG18_IMAGE) as pg_container:
yield pg_container.get_connection_url().replace("postgresql+psycopg2://", "postgresql://")
@pytest.fixture
async def example_db(example_pg_dsn: str) -> AsyncIterator[TestDB]:
async with await pg.Pool.connect(example_pg_dsn) as pool:
test_db = TestDB(pool, schema="public")
await test_db.create_all(*LIB_REGISTRY.tables)
yield test_db
7. Type-Checker Guarantees & Wheel Packaging#
py.typedmarker:pgdormships inline type annotations and a strict_pgdorm.pyistub with zeroAnyleaks.- Strict type checkers: The public API is fully annotated and checked in strict mode, so your type checker sees precise types without stubs or plugins.
- Stable-ABI wheels: The Rust core compiles against the free-threading-compatible stable ABI, supporting both standard and free-threaded CPython builds without recompiling per minor release.