# pgdorm -- Full Guides & Reference (LLM Edition) Canonical site: https://wergstatt.gitlab.io/pgdorm/ --- # Before Your First Shift Never run PostgreSQL or `pgdorm` on your machine before? Sixty seconds from now you'll have a live PostgreSQL container humming on localhost and your first typed query running -- no repo clone required. ## 60-Second Single-File Quickstart **Requirements:** **Python 3.15+** (`abi3t` free-threaded wheels) and **PostgreSQL 18 or newer** (Docker, OrbStack, Colima, or local install). ### 1. Install Python 3.15 + `pgdorm` and start PostgreSQL ```bash uv python install 3.15 uv init my-pgdorm-app --python 3.15 && cd my-pgdorm-app uv add pgdorm docker run -d --name dorm-pg -e POSTGRES_PASSWORD=dorm -p 5432:5432 postgres:18-alpine export DATABASE_URL="postgresql://postgres:dorm@localhost:5432/postgres" ``` ### 2. Define a `pg.Table` model and run your first query ```python title="app.py | model" class Guest(pg.Table): guest_id: pg.Col[int] = pg.pk(default=pg.identity()) email: pg.Col[str] = pg.col(unique=True) full_name: pg.Col[str] = pg.col() ``` ```python title="app.py | create_all + insert + select" await pool.create_all(Guest) jumbo = await pool.one( pg.insert(Guest) .values(Guest(email="jumbo@dorm.example", full_name="Jumbo Kalahari")) .returning(Guest) ) found = await pool.one(pg.select(Guest).where(Guest.guest_id == jumbo.guest_id)) ``` ```bash uv run python app.py # => Checked in #1: Jumbo Kalahari ``` --- ## The 5 House Rules (and Feed `/pgdorm/llms.txt` to Your AI Agent) `pgdorm` enforces strict PostgreSQL guardrails at class-definition and query-build time. If you use Cursor, Claude Code, or Antigravity, feed it **[`/pgdorm/llms.txt`](../llms.txt)** (or **[`/pgdorm/llms-full.txt`](../llms-full.txt)**) so it follows these five rules on the first try: 1. **Singular `snake_case` table names**: `class OrderItem(pg.Table)` maps to `"order_item"`. Passing `name="order_items"` is forbidden (`SchemaLintError`). 2. **Own-PK `_id`**: Every permanent table declares `_id` (`guest_id`, not `id`). Binding a legacy database with `id`? Pass `strict_pk=False` (or use `pgdorm scaffold --mode bind`). 3. **`TypeTable` classes end in `Type`**: Use `class RoomStatusType(pg.TypeTable)` backed by an `IntEnum` -- string discriminators and unvalidated `status: Col[str]` enums are forbidden. 4. **Zero raw SQL execution**: Never call `pool.execute("SELECT ...")` or `pg.raw(...)` -- they do not exist. Compose everything with `pg.select`, `pg.insert`, `pg.update`, `pg.delete`, `pg.func`, `pg.cast`, and `pg.lit`. 5. **Explicit, indexed joins & `= ANY($1)`**: `JoinLintError` blocks ambiguous or unindexed foreign-key joins (opt out explicitly with `.allow_seq_scan(reason="...")`), and membership filters use `Col.in_any(values)` so PostgreSQL caches one prepared statement forever. Hit a linter or runtime error? Jump to **[House Rules & Error Fixes](house-rules-and-errors.md)** or look up any signature in the **[API Reference](../reference/index.md)**. --- ## Optional: Clone the Dormitory Repo to Run the 20-Chapter Book Want to run all 20 standalone tutorial chapters from **The Elephant Dormitory** locally? ### Requirements - **Python 3.15+** (minimum version declared in [`pyproject.toml`](../../pyproject.toml); ships free-threaded `abi3t` wheels) - **PostgreSQL 18 or newer** (run `pgdorm doctor` to verify server compatibility) - **`uv`** (recommended Python package manager) - **Rust toolchain** (`rustup` / `cargo`, minimum edition in [`Cargo.toml`](../../Cargo.toml)) -- only needed when building from source inside a repo clone ### Clone and build the Rust extension ```bash git clone https://gitlab.com/wergstatt/pgdorm.git cd pgdorm uv sync --group dev --group docs uv run --no-sync maturin develop ``` ### Run Chapter 1 live (from your clone) Every chapter in **The Elephant Dormitory** is a standalone Python file in [`examples/`](../../examples/README.md). Each script drops and recreates only its own `ex_` schema, so running it repeatedly is always clean: ```bash uv run --no-sync python examples/097_hello_dorm.py ``` You should see Jumbo Kalahari check in, get looked up, upgrade to `SILVER`, and check out -- matching every highlighted `# =>` line in [Chapter 1](../story/01_hello_dorm.md). ### Verify the whole book Want to run all 20 tutorial chapters against your local PostgreSQL and check every output and wire SQL snapshot? One advanced chapter needs a non-superuser role for Row-Level Security ([Chapter 14](../story/14_multitenancy_rls.md)). Normal `pgdorm` apps don't need it; create it once to run the full suite: ```bash # Optional: only needed to run the RLS chapter (Ch. 14) docker exec -i dorm-pg psql -U postgres -c "CREATE ROLE pgdorm_rls_user NOLOGIN NOBYPASSRLS;" uv run --no-sync pytest tests/docs/test_examples.py -v ``` Ready? It's Friday, 23:45 in Lisbon, and a woolly mammoth just crashed the spreadsheet. --- # House Rules & Error Fixes `pgdorm` catches schema mistakes, ambiguous joins, accidental full-table wipes, and invalid SQL shapes **before a query ever touches PostgreSQL**. If you or your AI coding agent (Cursor, Claude Code, Antigravity) hit a linter or runtime exception, find the error below for the exact cause and idiomatic fix. > **Tip for AI agents:** Load [`/pgdorm/llms.txt`](../llms.txt) into your agent's context so it follows these rules automatically. For full exception signatures and inheritance, see the [Errors & Linters Reference](../reference/errors-and-linters.md). ## Quick Symptom-to-Fix Index | Exception | Raised When | Typical Cause | Jump To | | :--- | :--- | :--- | :--- | | `SchemaLintError` | Class definition / `Registry.freeze()` | `name="..."`, `id` PK, missing `*Type` suffix, string discriminator, partition PK | [SchemaLintError](#schemalinterror) | | `JoinLintError` | Query build (`select().join(...)`) | Multiple FKs between two tables, unindexed FK, violated `require_using=True` | [JoinLintError](#joinlinterror) | | `UnsafeDmlError` | Query build (`update()` / `delete()`) | `UPDATE` or `DELETE` without `.where(...)` | [UnsafeDmlError](#unsafedmlerror) | | `QueryBuildError` | Query build | Writable CTE missing `.returning(...)`, invalid `GROUP BY` / window / expression | [QueryBuildError](#querybuilderror) | | `NoResultError` / `MultipleResultsError` | Wire execution (`.one()`, `.one_or_none()`) | Expected 1 row, got 0 or >1 | [Result Cardinality Errors](#noresulterror-multipleresultserror) | | `RetryablePgError` | Wire execution (`40001` / `40P01`) | Serialization failure or deadlock | [RetryablePgError](#retryablepgerror) | --- ## `SchemaLintError` Raised when a `pg.Table` or `pg.TypeTable` violates `pgdorm`'s schema hygiene rules. ### 1. Explicit `name="..."` or plural table name **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_table_name" class _Users(pg.Table, name="users"): # SchemaLintError: explicit name= is forbidden id: pg.Col[int] = pg.pk() ``` **Idiomatic `pgdorm` fix:** Name the class in singular `PascalCase`; `pgdorm` derives singular `snake_case` (`User` -> `"user"`, `OrderItem` -> `"order_item"`): ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_table_name" class User(pg.Table): user_id: pg.Col[int] = pg.pk() ``` ### 2. Generic `id` primary key instead of `_id` **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_pk_name" class _Guest(pg.Table): id: pg.Col[int] = pg.pk() # SchemaLintError: expected guest_id ``` **Idiomatic `pgdorm` fix:** Declare `_id` so joins emit `JOIN ... USING ("guest_id")` cleanly. Only opt out with `strict_pk=False` when binding an existing legacy schema (`pgdorm scaffold --mode bind`): ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_pk_name" class Guest(pg.Table): guest_id: pg.Col[int] = pg.pk() # Legacy bind exception only: class LegacyGuest(pg.Table, strict_pk=False): id: pg.Col[int] = pg.pk() ``` ### 3. `TypeTable` missing `*Type` suffix (or regular `Table` ending in `Type`) **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_type_table_suffix" class _BadRoomStatus( pg.TypeTable, enum=_RoomStatus ): # SchemaLintError: must end with 'Type' pass ``` **Idiomatic `pgdorm` fix:** `pg.TypeTable` subclasses must end with `Type` (`_type`), and regular `pg.Table` subclasses cannot: ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_type_table_suffix" class RoomStatus(IntEnum): AVAILABLE = 1 OCCUPIED = 2 class RoomStatusType(pg.TypeTable, enum=RoomStatus): room_status_type_id: pg.Col[RoomStatus] = pg.pk() ``` ### 4. String discriminators on polymorphic tables **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_discriminator" class _Payment(pg.Table): payment_id: pg.Col[int] = pg.pk() kind: pg.Col[str] = pg.discriminator(PaymentType.payment_type_id) # SchemaLintError ``` **Idiomatic `pgdorm` fix:** Point `pg.discriminator(...)` at a `TypeTable` primary key backed by an `IntEnum` (see [Chapter 7](../story/07_inheritance_payments_tasks.md)): ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_discriminator" class Payment(pg.Table): payment_id: pg.Col[int] = pg.pk() payment_type_id: pg.Col[PaymentKind] = pg.discriminator(PaymentType.payment_type_id) ``` ### 5. Partitioned table primary key missing the partition key PostgreSQL requires every `PRIMARY KEY` / `UNIQUE` constraint on a partitioned table to include all partition-key columns. Declare a composite primary key (e.g., `(door_event_id, scanned_at)`) when `pg.PartitionBy` is returned from `@classmethod def __constraints__(cls)` (see [Chapter 15](../story/15_partitioning_door_events.md)). --- ## `JoinLintError` Raised at query-build time when a `.join(...)` is ambiguous, unindexed, or violates `USING` symmetry. ### 1. Multiple foreign keys between the same two tables **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_ambiguous_join" # Message has both sender_guest_id and recipient_guest_id -> Guest pg.select(Message).join(Guest) # JoinLintError: ambiguous FK path ``` **Idiomatic `pgdorm` fix:** Pass an explicit `on=` condition (and alias the table with `.alias(...)` if joining twice): ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_ambiguous_join" q = pg.select(Message).join(Guest, on=Message.sender_guest_id == Guest.guest_id) ``` ### 2. Joining on an unindexed foreign key By default `auto_index_fk = True` indexes foreign keys automatically. If you disabled it or bound a legacy table without an index on the FK column, `pgdorm` refuses to silently trigger a sequential scan. **Idiomatic `pgdorm` fix:** Either add an index on the FK column, or explicitly acknowledge the sequential scan with a reason: ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_allow_seq_scan" q = ( pg.select(Order) .join(LegacyNote, on=LegacyNote.order_id == Order.order_id) .allow_seq_scan(reason="legacy_note has <200 lookup rows") ) ``` ### 3. `require_using=True` violated When `require_using=True` is set on a join, both sides must share the exact `_id` column name so PostgreSQL can emit `JOIN ... USING (...)`. For role-named FKs (like `approved_by_guest_id`), omit `require_using=True` and pass `on=...`. --- ## `UnsafeDmlError` Raised at query-build time when `pg.update(T)` or `pg.delete(T)` has no `.where(...)` predicate. **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_unsafe_dml" pg.compile(pg.delete(SessionToken)) # UnsafeDmlError: full-table DELETE blocked ``` **Idiomatic `pgdorm` fix:** Add a `.where(...)` clause -- or, if a full-table mutation is genuinely intentional, opt in explicitly with `.allow_full_table(reason="...")`: ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_safe_dml" # Scoped delete (almost always what you want): scoped = pg.delete(SessionToken).where(SessionToken.expired_at < pg.func("now")) # Intentional full-table clear: full = pg.delete(SessionToken).allow_full_table(reason="nightly staging reset") ``` --- ## `QueryBuildError` Raised at query-build time for structurally invalid SQL that would otherwise fail on PostgreSQL or produce undefined results. ### 1. Writable CTE (`pg.cte`) without `.returning(...)` **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_write_cte" # Missing .returning(...) -- outer query cannot reference columns from the CTE pg.cte("claimed", pg.update(Task).set(status=2).where(Task.status == 1)) ``` **Idiomatic `pgdorm` fix:** Always attach `.returning(...)` to a data-modifying CTE so its columns are typed and selectable downstream: ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_write_cte" claimed = pg.cte( "claimed", pg.update(Task).set(status=2).where(Task.status == 1).returning(Task.task_id, Task.room_id), ) ``` ### 2. Invalid `GROUP BY`, window, or scalar expression Common causes include mixing ungrouped columns with aggregates, passing a non-boolean expression to `.where(...)`, or referencing an unjoined table in `.select(...)`. Check the error message for the exact offending column and see the [Queries & DML Reference](../reference/queries-and-dml.md). --- ## `NoResultError` / `MultipleResultsError` Raised at execution time by cardinality-checked helpers: | Method | 0 rows | 1 row | 2+ rows | | :--- | :--- | :--- | :--- | | `pool.one(q)` | `NoResultError` | returns row | `MultipleResultsError` | | `pool.one_or_none(q)` | returns `None` | returns row | `MultipleResultsError` | | `pool.first(q)` | returns `None` | returns row | returns first row | | `pool.all(q)` | returns `[]` | returns `[row]` | returns `[...]` | **Idiomatic `pgdorm` fix:** Use `pool.one_or_none(q)` for lookups that may legitimately miss (e.g., `GET /guests/{id}` -> HTTP 404), and add a unique filter or `.limit(1)` when calling `.one()`. --- ## `RetryablePgError` PostgreSQL raises SQLSTATE `40001` (`serialization_failure`) under `SERIALIZABLE` / `REPEATABLE READ` contention and `40P01` (`deadlock_detected`) under conflicting lock orders. Both inherit from `pg.RetryablePgError`. **What your AI agent wrote:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | bad_raw_serializable_tx" # Raw transaction without retry -- crashes on transient 40001 / 40P01 async with pool.transaction(isolation=pg.enums.IsolationLevel.SERIALIZABLE) as tx: await transfer_balance(tx, from_id, to_id, amount) ``` **Idiomatic `pgdorm` fix:** Wrap idempotent transactional work in `pool.retry_transaction(...)`, which catches `RetryablePgError` and retries with bounded backoff: ```python title="tests/unit/docs/test_doc_guide_snippets.py | good_retry_transaction" async def _step(tx: pg.Transaction) -> None: await transfer_balance(tx, from_id, to_id, amount) await pool.retry_transaction( _step, isolation=pg.enums.IsolationLevel.SERIALIZABLE, max_attempts=5 ) ``` For the full exception class hierarchy and SQLSTATE mapping, see [Errors & Linters Reference](../reference/errors-and-linters.md). --- # Coming From Another ORM? Already comfortable with SQLAlchemy 2, SQLModel, Django ORM, Prisma, Supabase SDK, or Psycopg 3? Welcome -- this page translates your mental model onto **pgdorm** in five minutes so you can jump straight to the chapters you care about. Skeptical that you can build production PostgreSQL apps with **zero raw SQL**? Read **[The Zero-SQL Hall of Shame](../story/hall_of_shame.md)** for side-by-side Python, compiled SQL, and live PostgreSQL `EXPLAIN` proofs, or browse exact signatures in the **[API Reference](../reference/index.md)**. ## The three biggest shifts 1. **No Session, no identity map, no hidden lazy loads.** Models are lightweight `__slots__` objects. A `Guest` never quietly fires a SQL query when you access an attribute. If you want related rows, ask explicitly with `.join(...)` or `pool.split_load(...)` (see [Chapter 5](../story/05_joins_and_folios.md)), or read the full side-by-side comparison against SQLAlchemy 2 `AsyncSession` in [Field Note 1 | Unit of Work & Identity Map](../story/field_notes_uow_and_identity_map.md). 2. **PostgreSQL only -- by design.** Instead of lowest-common-denominator abstractions across five SQL dialects, pgdorm builds directly on modern PostgreSQL primitives (`RETURNING OLD/NEW`, `WITHOUT OVERLAPS`, `uuidv7()`, virtual generated columns, `MERGE ... RETURNING`, `COPY BINARY`, `LISTEN/NOTIFY`, `UNNEST WITH ORDINALITY`, and `= ANY($1)`). 3. **Zero raw SQL execution.** There is no `text()`, `raw()`, or `execute_raw()`. Every feature -- from recursive CTEs with `SEARCH`/`CYCLE` to `LATERAL` top-K, `ROLLUP`/`QUALIFY`, RLS policies, and online migrations -- is expressed in typed Python so your editor and type checker catches type errors before runtime. ## Quick stack comparison (SQLModel, Prisma, Supabase SDK & classic ORMs) | Stack | How it works | What changes in `pgdorm` | | :--- | :--- | :--- | | **SQLModel** | Pydantic + SQLAlchemy `Session` wrapper | Models are zero-`__dict__` `__slots__` classes (no Pydantic overhead on DB reads); `pg.Create[T]` / `pg.Patch[T]` generate API DTOs on demand; Rust wire client replaces Python driver + Session tracking. | | **Prisma** | External schema DSL (`.prisma`) + codegen | Pure Python `pg.Table` classes are the single source of truth -- no separate DSL or codegen step, and native PostgreSQL primitives (`MERGE`, `SKIP LOCKED`, `WITHOUT OVERLAPS`, `LATERAL`) work without `$queryRaw`. | | **Supabase SDK (`postgrest-py`)** | HTTP REST calls through PostgREST | Direct binary PostgreSQL v3 wire protocol in Rust: multi-statement transactions (`tx.pipeline(commit=True)`), `FOR UPDATE SKIP LOCKED`, `pg_temp` staging, and `local_settings=` RLS in **1 RTT** (and still works seamlessly against hosted Supabase + Supavisor via `pool_mode=pg.enums.PoolMode.TRANSACTION`). | | **SQLAlchemy 2 / Django / Psycopg 3** | Unit-of-work ORM or raw SQL strings | Explicit queries with zero implicit lazy loads, constant-shape prepared statements (`= ANY($1)` / `UNNEST`), compile-time `JoinLintError` / `UnsafeDmlError` guardrails, and 1-RTT pipelining. | ## Vocabulary map | If you know... | In `pgdorm` | Where to see it | | :--- | :--- | :--- | | `Session` / `AsyncSession` | `pg.Pool` + `async with pool.transaction() as tx:` | [Ch. 1](../story/01_hello_dorm.md), [Ch. 8](../story/08_transactions_locks_queue.md) | | `session.add(obj); session.commit()` | `await pool.one(pg.insert(T).values(obj).returning(T))` | [Ch. 1](../story/01_hello_dorm.md) | | `bulk_insert_mappings` / `bulk_create` | `pg.insert_many(T, rows)` (`UNNEST WITH ORDINALITY`) | [Ch. 3](../story/03_bulk_insert_and_upsert.md) | | `.where(Col.in_(values))` | `Col.in_any(values)` (always `= ANY($1)`) | [Ch. 3](../story/03_bulk_insert_and_upsert.md) | | `and_(a, b)` / `or_(a, b)` / query composition | `pg.and_(a, b)`, `pg.or_(a, b)`, and `query.pipe(fn)` | [Queries & DML Reference](../reference/queries-and-dml.md) | | `selectinload()` / `prefetch_related()` | `pool.split_load(parent_q, relations=(...))` (2 RTTs) | [Ch. 5](../story/05_joins_and_folios.md) | | Correlated `LATERAL` subquery / Top-K per group | `Select.join_lateral(subq, ...)` | [Field Note 6](../story/field_notes_search_json_and_dml.md) | | `UPDATE ... FROM` / `DELETE ... USING` | `pg.update(T).from_(S)` / `pg.delete(T).using(S)` | [Field Note 6](../story/field_notes_search_json_and_dml.md), [Ch. 13](../story/13_staging_and_merge_import.md) | | Data-modifying CTE (`WITH x AS (UPDATE ... RETURNING ...)`) | `pg.write_cte("x", stmt)` (`WriteCte`) | [Field Note 6](../story/field_notes_search_json_and_dml.md), [Ch. 8](../story/08_transactions_locks_queue.md) | | `exclude_unset=True` PATCH boilerplate | `pg.UNSET` + `pg.Patch[T]` + `.patch(body)` | [Ch. 2](../story/02_patch_and_returning.md), [Ch. 18](../story/18_web_api_and_telemetry.md) | | String `polymorphic_identity` | `pg.discriminator(TypeTable.pk)` + `variant=Enum.X` | [Ch. 7](../story/07_inheritance_payments_tasks.md) | | `with_for_update(skip_locked=True)` | `.for_update(skip_locked=True)` | [Ch. 8](../story/08_transactions_locks_queue.md) | | Multiple sequential `await`s | `pool.pipeline()` (reads) or `tx.pipeline(commit=True)` + `pg.currval()` (1 RTT) | [Ch. 10](../story/10_pipelining_prepared_stream.md) | | Server-side `json_agg` / fast JSON APIs | `await pool.json(q, mode="server")` (or `mode="wire"`) | [Ch. 18](../story/18_web_api_and_telemetry.md), [Runtime Reference](../reference/runtime-and-pool.md) | | Alembic autogenerate | `pgdorm.migrate` (`plan_migration`, `sync_schema`, `check_drift`) | [Ch. 19](../story/19_online_migrations.md) | | `inspectdb` / `sqlacodegen` | `pgdorm audit-schema` + `pgdorm scaffold` + `adopt-plan` | [Assimilation](../assimilation/index.md) | | `BaseModel` Create/Patch DTOs | `pg.Create[T]` and `pg.Patch[T]` | [Ch. 18](../story/18_web_api_and_telemetry.md) | | Pandas `read_sql` / CSV ETL | `pool.arrow()`, `copy_to_arrow()`, `copy_from_arrow()` | [Ch. 16](../story/16_arrow_polars_analytics.md), [Ch. 17](../story/17_arrow_duckdb_lakehouse.md) | ## House rules that will surprise you (in a good way) - **Strict `_id` PKs:** Permanent tables declare `_id` (for instance `guest_id`, `booking_id`). That lets `.join(Booking)` emit `JOIN "booking" USING ("booking_id")` automatically -- and fail loudly with `JoinLintError` on ambiguous or unindexed joins. - **No accidental full-table wipes:** `pg.delete(Room)` or `pg.update(Room).set(...)` without a `.where(...)` raises `UnsafeDmlError` at query-build time (before anything hits the wire) unless you explicitly pass `.allow_full_table(reason="...")`. - **Constant SQL shapes (one prepared statement forever):** `in_any(...)` always compiles to `= ANY($1)` and `insert_many(...)` always compiles to `UNNEST(...)`. Whether you send 3 items or 3,000, PostgreSQL sees **one** SQL text, **one** prepared statement, and **one** cached plan. (Modern PostgreSQL also squashes variable `IN` lists inside `pg_stat_statements`; pgdorm gives you the same stability at the wire protocol level and for bulk inserts too.) - **PgBouncer-first:** `Pool.connect(..., pool_mode=pg.enums.PoolMode.TRANSACTION)` handles transaction-pooling constraints cleanly, `local_settings=` uses transaction-scoped `set_config(..., true)`, and `on_commit=pg.enums.OnCommit.DROP` keeps temp staging tables collision-free. Ready to see how all 20 pieces fit together? Jump into the [Story Map](../story/index.md), migrate an existing schema in the [Assimilation Hub](../assimilation/index.md), compare numbers in [Benchmarks](../benchmarks/index.md), or start with the [Prologue](../story/00_prologue.md). --- # 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`: ```python title="tests/integration/docs/test_doc_quickstart_and_library.py | lib_registry" 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](../reference/typing-and-testing.md)): | 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 | ```python title="tests/integration/docs/test_doc_quickstart_and_library.py | lib_protocols" 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](../reference/migrations-and-assimilation.md)): ```python title="tests/integration/docs/test_doc_quickstart_and_library.py | lib_migrations" 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](../reference/errors-and-linters.md)): - **`pg.UniqueViolationError`** (`23505`): Idempotent inserts or duplicate natural keys. - **`pg.LockNotAvailableError`** (`55P03`): `NOWAIT` lock contention when claiming a resource. - **`pg.RetryablePgError`** (`40001` serialization failure, `40P01` deadlock): Wrap retryable library operations in `pool.retry_transaction(...)`. - **`pg.PostgresError`**: Base class for all server-returned PostgreSQL errors (exposes `.sqlstate`, `.message`, `.constraint_name`). ```python title="tests/integration/docs/test_doc_quickstart_and_library.py | lib_idempotent" 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](../reference/runtime-and-pool.md)). As a library author, attach `.tag("my_lib.")` to every query you build -- `pgdorm` emits `/* op:my_lib. */` 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](../reference/typing-and-testing.md)): - **`PG18_IMAGE`** & **`postgres_container(...)`**: Launches a stock PostgreSQL container at the supported baseline (lazy-imports `testcontainers`). - **`TestDB`**: Per-test isolated schema fixture (`t_`) 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 and `EXPLAIN` plans in CI. ```python title="tests/conftest.py" @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.typed` marker**: `pgdorm` ships inline type annotations and a strict `_pgdorm.pyi` stub with zero `Any` leaks. - **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. --- # Cloud & Managed Postgres `pgdorm` is **all-in on modern PostgreSQL**. Every managed, serverless, and lakehouse-attached PostgreSQL service that runs genuine upstream PostgreSQL works natively -- including 1-RTT pipelining, `UNNEST WITH ORDINALITY`, `RETURNING OLD/NEW`, `MERGE`, `uuidv7()`, `WITHOUT OVERLAPS`, Row-Level Security, Arrow `COPY BINARY`, and online migrations. Because `pgdorm-wire` speaks the PostgreSQL v3 binary protocol directly in Rust, cloud compatibility comes down to two things: 1. **Engine reality** -- does the service run genuine upstream PostgreSQL underneath (verified automatically by `pgdorm doctor`), or is it a wire-protocol rewrite? 2. **Transport & auth hygiene** -- TLS (`sslmode=prefer` by default), `SCRAM-SHA-256-PLUS` channel binding, OS root CAs (`sslrootcert=system`), mTLS (`sslcert`/`sslkey`), `options=`, `connect_timeout`, dynamic IAM/OAuth `password=` callbacks, and `pool_mode=pg.enums.PoolMode.TRANSACTION` for cloud poolers. --- ## Verify Your Database in One Command (`pgdorm doctor`) Before migrating any application code, point `pgdorm doctor` at your cloud database (read-only by default; add `--write-probe` to also test `pg_temp`, `UNNEST`, and `RETURNING OLD/NEW` inside an immediately rolled-back transaction): ```bash pgdorm --dsn "$DATABASE_URL" doctor --write-probe ``` Behind a transaction pooler (Neon `-pooler`, Supabase Supavisor, AWS RDS Proxy, Azure PgBouncer): ```bash pgdorm --dsn "$DATABASE_URL" --pool-mode transaction doctor --write-probe ``` *(If running from a source clone of this repository, prefix commands with `uv run --no-sync`.)* For CI pipelines, pass `--json` (exits `0` when all checks pass, `1` on failure) or call `await pg.doctor(pool, write_probe=True)` from Python. --- ## Compatibility Matrix (3 Architectural Tiers) ### Tier 1 -- Compatible (Upstream PostgreSQL) All of these run genuine upstream PostgreSQL backends (some with decoupled storage, serverless scale-to-zero, NVMe/CDC bridges, or managed connection poolers). Local CI exercises upstream PostgreSQL and PgBouncer on every push; run `pgdorm doctor --write-probe` or `-m cloud_smoke` against your own cloud instance to verify server compatibility (and optional extension allow-lists like `btree_gist` if you use temporal `WITHOUT OVERLAPS` keys): | Provider | Notes & Connection Profile | | :--- | :--- | | **AWS RDS for PostgreSQL** | Direct (`pool_mode=pg.enums.PoolMode.DIRECT`), `?sslmode=verify-full&sslrootcert=`, optional IAM `password=` factory | | **Amazon Aurora PostgreSQL** | Same as RDS; multi-host `writer,reader?target_session_attrs=read-write` or `prefer-standby` + `connect_timeout=5` | | **AWS RDS Proxy** | `pool_mode=pg.enums.PoolMode.TRANSACTION`, `prepared_statements=False` (avoids proxy session pinning), IAM `password=` factory | | **Google Cloud SQL** | Cloud SQL Auth Proxy (Unix socket `?host=/cloudsql/...` or localhost TCP), or direct mTLS (`sslcert`/`sslkey`) + IAM | | **Google AlloyDB / AlloyDB Omni** | Native PostgreSQL; same transport options as Cloud SQL (`google/alloydbomni` available for local Docker) | | **Azure Database for PostgreSQL (Flexible Server)** | Direct or built-in PgBouncer (`pool_mode=pg.enums.PoolMode.TRANSACTION`), `?sslmode=verify-full&sslrootcert=system`, Entra ID `password=` factory | | **Databricks Lakebase / Neon** | Default copy-paste DSN (`?sslmode=require&channel_binding=require`, optional `options=endpoint=...`) works out of the box; use `pool_mode=pg.enums.PoolMode.TRANSACTION` on `-pooler` hostnames and `password=` factory for Databricks OAuth | | **Snowflake Postgres (Crunchy Data)** | Upstream PostgreSQL support; `?sslmode=verify-full&sslrootcert=system`, `pool_mode=pg.enums.PoolMode.TRANSACTION` when using pooled endpoint | | **ClickHouse Managed Postgres (Ubicloud)** | Genuine Postgres on NVMe/CDC; `?sslmode=verify-full&sslrootcert=system`, `pool_mode=pg.enums.PoolMode.TRANSACTION` if pooled | | **Supabase** | Direct port `5432` (`pool_mode=pg.enums.PoolMode.DIRECT`) or Supavisor port `6543` (`pool_mode=pg.enums.PoolMode.TRANSACTION, prepared_statements=False`) | | **TigerData (formerly Timescale)** | PostgreSQL + TimescaleDB extensions (`timescale/timescaledb:latest-pg18` Docker image supported via `--pg-image`) | | **CloudNativePG / Crunchy PGO (K8s)** | Multi-host `rw,ro?target_session_attrs=read-write` + mTLS (`sslcert`/`sslkey`) + PgBouncer pooler support | | **PlanetScale Postgres, Aiven, DigitalOcean, Render, Railway** | Standard PostgreSQL DSNs with `?sslmode=verify-full&sslrootcert=system` (or provider CA PEM) | ### Tier 2 -- PG-Forked Distributed Engines (Tracks Upstream PG) | Engine | Status | | :--- | :--- | | **YugabyteDB (YSQL)** | Reuses a forked PostgreSQL query layer, but tracks an older upstream PostgreSQL major version below `pgdorm`'s baseline (`pgdorm doctor` checks this at handshake). | | **Citus** | Sharded PostgreSQL extension; supported on current upstream PostgreSQL builds (note distributed-table FK/DDL rules from Citus apply). | ### Tier 3 -- Wire-Protocol Rewrites (Explicitly Unsupported) > [!WARNING] > **All-in on genuine PostgreSQL** > > `pgdorm` intentionally does **not** support PostgreSQL wire-protocol emulators such as **CockroachDB**, **Amazon Aurora DSQL**, or **Google Cloud Spanner (PGAdapter)**. Supporting them would require giving up core `pgdorm` guarantees: FK-enforced joins (`JOIN USING`), range types and `TemporalPrimaryKey` (`WITHOUT OVERLAPS` / `btree_gist`, which also requires `btree_gist` to be installable/allow-listed on managed services), `pg_temp` staging + `MERGE`, binary `COPY` Arrow transfers, `pg_catalog` online migrations, and `RETURNING OLD/NEW`. --- ## Provider Connection Recipes ### Neon & Databricks Lakebase Neon's default connection string (including `channel_binding=require` and `SCRAM-SHA-256-PLUS`) works unmodified: ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_neon" # Pooled serverless endpoint (`-pooler` hostname) pool = await pg.Pool.connect( "postgresql://user:pass@ep-cool-darkness-pooler.us-east-2.aws.neon.tech/neondb" "?sslmode=require&channel_binding=require", pool_mode=pg.enums.PoolMode.TRANSACTION, ) ``` For **Databricks Lakebase** OAuth token rotation, pass an async `password=` factory paired with `max_lifetime`: ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_lakebase" async def lakebase_oauth_token() -> str: # Call your Databricks SDK credential helper to mint a fresh OAuth token return await fetch_databricks_pg_token() pool = await pg.Pool.connect( "postgresql://service_principal@instance.database.azuredatabricks.net/app" "?sslmode=verify-full&sslrootcert=system", password=lakebase_oauth_token, max_lifetime=2700.0, # recycle connections before 60-minute OAuth expiry ) ``` ### AWS RDS, Aurora & RDS Proxy (with IAM Auth) `Pool.connect(..., password=callable)` invokes your sync or async token generator every time a new physical connection is opened -- no AWS SDK dependency is required inside `pgdorm`: ```python import boto3 rds = boto3.client("rds", region_name="eu-central-1") def rds_iam_token() -> str: return rds.generate_db_auth_token( DBHostname="dorm-cluster.cluster-abc.eu-central-1.rds.amazonaws.com", Port=5432, DBUsername="app_iam", ) ``` ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_aws_rds" # Direct Aurora writer/reader failover with RDS Global CA bundle pool = await pg.Pool.connect( "postgresql://app_iam@writer.rds.amazonaws.com,reader.rds.amazonaws.com/dorm" "?sslmode=verify-full&sslrootcert=/etc/ssl/rds-global-bundle.pem" "&target_session_attrs=read-write&connect_timeout=5", password=rds_iam_token, max_lifetime=600.0, # rotate before 15-minute IAM token TTL ) # Behind AWS RDS Proxy: avoid backend pinning by disabling named prepared statements proxy_pool = await pg.Pool.connect( "postgresql://app_iam@dorm-proxy.proxy-abc.eu-central-1.rds.amazonaws.com/dorm" "?sslmode=verify-full&sslrootcert=/etc/ssl/rds-global-bundle.pem", password=rds_iam_token, pool_mode=pg.enums.PoolMode.TRANSACTION, prepared_statements=False, max_lifetime=600.0, ) ``` ### Google Cloud SQL & AlloyDB - **Via Cloud SQL Auth Proxy (Unix socket):** ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_gcp_proxy" pool = await pg.Pool.connect( "postgresql://app_user:secret@/dorm?host=/cloudsql/my-proj:europe-west1:dorm-pg", ) ``` - **Direct mTLS + IAM token:** ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_gcp_mtls" pool = await pg.Pool.connect( "postgresql://app@10.20.0.5:5432/dorm" "?sslmode=verify-ca&sslrootcert=/certs/server-ca.pem" "&sslcert=/certs/client-cert.pem&sslkey=/certs/client-key.pem", password=fetch_gcp_iam_token, max_lifetime=2700.0, ) ``` ### Azure Database for PostgreSQL (Flexible Server) ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_azure" pool = await pg.Pool.connect( "postgresql://app_aad@dorm.postgres.database.azure.com:5432/dorm" "?sslmode=verify-full&sslrootcert=system", password=fetch_entra_id_token, pool_mode=pg.enums.PoolMode.TRANSACTION, # when using built-in PgBouncer on port 6432 max_lifetime=2700.0, ) ``` ### Snowflake Postgres (Crunchy Data) & ClickHouse Managed Postgres (Ubicloud) ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_snowflake" pool = await pg.Pool.connect( "postgresql://app_user:secret@host.snowflake.postgres.example:5432/app" "?sslmode=verify-full&sslrootcert=system&connect_timeout=10", pool_mode=pg.enums.PoolMode.DIRECT, # switch to "transaction" on pooled endpoints ) ``` ### Supabase (Direct vs Supavisor) ```python title="tests/unit/docs/test_doc_guide_snippets.py | cloud_supabase" # Direct connection (port 5432): full session features + LISTEN/NOTIFY direct = await pg.Pool.connect( "postgresql://postgres:secret@db.projectref.supabase.co:5432/postgres" "?sslmode=verify-full&sslrootcert=system", ) # Supavisor transaction pooler (port 6543) pooled = await pg.Pool.connect( "postgresql://postgres.projectref:secret@aws-0-eu-central-1.pooler.supabase.com:6543/postgres" "?sslmode=require", pool_mode=pg.enums.PoolMode.TRANSACTION, prepared_statements=False, ) ``` --- ## Running the Conformance Suite Against Your Own Cloud DB `pgdorm` ships a portable `@pytest.mark.cloud_smoke` conformance suite in this repository (requires cloning the repo; `tests/` is excluded from the published wheel) that isolates every test inside a temporary `t_` schema and requires zero superuser privileges: ```bash uv run --no-sync pytest -m cloud_smoke \ --dsn "$DATABASE_URL" \ --pool-mode transaction \ -v ``` You can also run the local Docker suite against any vendor-packaged PostgreSQL Docker image using `--pg-image`: ```bash uv run --no-sync pytest -m cloud_smoke \ --pg-image=timescale/timescaledb:latest-pg18 \ -v ``` --- # Schema Reference Every example in **The Elephant Dormitory** imports from one shared, canonical model in [`examples/schema.py`](../../examples/schema.py). Instead of inventing toy `users` and `posts` tables per page, the entire twenty-chapter story grows cleanly out of this single schema. ## Full Entity-Relationship Diagram Generated directly from `ALL_TABLES` using `pg.to_svg_erd(*ALL_TABLES)` (pure Rust, zero Graphviz): [![Entity-relationship diagram of the full schema, generated by pg.to_svg_erd()](../assets/erd/schema_full.svg)](../assets/erd/schema_full.svg) ## Schema conventions - **Singular `snake_case` table names** (`OrderItem` -> `"order_item"`), derived strictly 1-to-1 from the Python class name. - **Strict `_id` primary keys** on every permanent table (including junction tables like `BookingGuest`), enabling automatic `JOIN ... USING (...)`. - **`TypeTable` lookups** (`INTEGER` PK + unique `code`) instead of free-text strings or PostgreSQL `ENUM` migrations. - **Automatic foreign-key indexes** (`auto_index_fk = True`) with leftmost-prefix deduplication. - **Zero raw SQL** -- constraints, generated columns, partial indexes, temporal keys, and partitions are all typed Python. ## Domain types & codecs `Annotated` aliases pick exact PostgreSQL types (`NUMERIC(10, 2)`, `VARCHAR(2)`, `VARCHAR(8)`), while `LowerEmail` normalizes emails on both bind and hydration, and `StayPreferences` maps a frozen dataclass to typed `JSONB`: ```python title="examples/schema.py | LowerEmail, StayPreferences" class LowerEmail(pg.TypeDecorator[str, str]): """Normalize guest email addresses to lowercase before binding and on hydration.""" impl = "text" def process_bind_param(self, value: str) -> str: return value.strip().lower() def process_result_value(self, value: str) -> str: return value.lower() @dataclass(frozen=True, kw_only=True, slots=True) class StayPreferences: reinforced_floor: bool = False extra_peanuts: bool = False mud_bath_access: bool = False pillow: str | None = None dietary: tuple[str, ...] = () ``` ## Lookup `TypeTable`s Every controlled vocabulary is backed by a Python `IntEnum` and a seeded lookup table: ```python title="examples/schema.py | SpeciesType, RoomCategoryType, LoyaltyTierType, BookingStatusType, BookingChannelType, ChargeKindType, PaymentMethodType, TaskKindType" class SpeciesType(pg.TypeTable, enum=Species): species_type_id: Col[Species] = pg.pk() class RoomCategoryType(pg.TypeTable, enum=RoomCategory): room_category_type_id: Col[RoomCategory] = pg.pk() class LoyaltyTierType(pg.TypeTable, enum=LoyaltyTier): loyalty_tier_type_id: Col[LoyaltyTier] = pg.pk() class BookingStatusType(pg.TypeTable, enum=BookingStatus): booking_status_type_id: Col[BookingStatus] = pg.pk() class BookingChannelType(pg.TypeTable, enum=BookingChannel): booking_channel_type_id: Col[BookingChannel] = pg.pk() class ChargeKindType(pg.TypeTable, enum=ChargeKind): charge_kind_type_id: Col[ChargeKind] = pg.pk() class PaymentMethodType(pg.TypeTable, enum=PaymentMethod): payment_method_type_id: Col[PaymentMethod] = pg.pk() class TaskKindType(pg.TypeTable, enum=TaskKind): task_kind_type_id: Col[TaskKind] = pg.pk() ``` ## Act I -- Core building & guests ```python title="examples/schema.py | Region, Dormitory, Room, Guest" class Region(pg.Table): region_id: Col[int] = pg.pk(default=pg.identity()) code: Col[Code] = pg.col(unique=True) name: Col[str] parent_region_id: Col[int | None] = pg.self_fk( on_delete=pg.enums.OnDelete.SET_NULL, default=None ) class Dormitory(pg.Table): dormitory_id: Col[int] = pg.pk(default=pg.identity()) region_id: Col[int | None] = pg.fk(Region, default=None) code: Col[Code] = pg.col(unique=True) name: Col[str] city: Col[str] country: Col[Country] timezone: Col[str] check_in: Col[time] = pg.col(default=time(15, 0)) check_out: Col[time] = pg.col(default=time(11, 0)) city_tax: Col[Money] = pg.col(default=Decimal("2.50")) opened_on: Col[date] class Room(pg.Table): room_id: Col[int] = pg.pk(default=pg.identity()) dormitory_id: Col[int] = pg.fk(Dormitory, on_delete=pg.enums.OnDelete.CASCADE) number: Col[Code] floor: Col[pg.Int2] category: Col[RoomCategory] = pg.fk(RoomCategoryType) max_weight_kg: Col[pg.Int4] = pg.col(default=6_000) max_guests: Col[pg.Int2] amenities: Col[list[str]] = pg.col(default_factory=list) out_of_service: Col[bool] = pg.col(default=False) @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]: return ( pg.Check(cls.max_weight_kg >= 500), pg.Check(cls.max_guests.between(1, 8)), pg.Unique(cls.dormitory_id, cls.number), pg.Index(cls.dormitory_id, cls.category, where=cls.out_of_service.is_false()), ) class Guest(pg.Table): guest_id: Col[int] = pg.pk(default=pg.identity()) public_id: Col[UUID] = pg.col(default=pg.uuidv7(), unique=True) email: Col[Email] = pg.col(unique=True) first_name: Col[str] last_name: Col[str] full_name: Col[str] = pg.generated(mode=pg.enums.GeneratedMode.VIRTUAL) species: Col[Species] = pg.fk(SpeciesType, default=Species.SAVANNA) phone: Col[str | None] = pg.col(default=None) country: Col[Country | None] = pg.col(default=None) birth_date: Col[date | None] = pg.col(default=None) loyalty_tier: Col[LoyaltyTier] = pg.fk(LoyaltyTierType, default=LoyaltyTier.CALF) peanut_points: Col[int] = pg.col(default=0) preferences: Col[pg.Jsonb[StayPreferences]] = pg.col(default_factory=StayPreferences) marketing_opt_in: Col[bool] = pg.col(default=False) created_at: Col[datetime] = pg.col(default=pg.now(), server_managed=True) @classmethod def __generated__(cls) -> tuple[pg.Generated, ...]: return (pg.Generated(cls.full_name, cls.first_name.concat(" ").concat(cls.last_name)),) @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]: return (pg.Index(cls.last_name, cls.guest_id),) ``` ## Act II -- Bookings, temporal guards, payments (STI) & tasks (CTI) ```python title="examples/schema.py | Booking, BookingGuest, Charge, RoomAssignment, Rate" class Booking(pg.Table): booking_id: Col[int] = pg.pk(default=pg.identity()) dormitory_id: Col[int] = pg.fk(Dormitory, on_delete=pg.enums.OnDelete.CASCADE) primary_guest_id: Col[int] = pg.fk(Guest) status: Col[BookingStatus] = pg.fk(BookingStatusType, default=BookingStatus.CONFIRMED) channel: Col[BookingChannel] = pg.fk(BookingChannelType, default=BookingChannel.DIRECT) stay: Col[Range[date]] reference_code: Col[str] = pg.col(unique=True) created_at: Col[datetime] = pg.col(default=pg.now(), server_managed=True) class BookingGuest(pg.Table): booking_guest_id: Col[int] = pg.pk(default=pg.identity()) booking_id: Col[int] = pg.fk(Booking, on_delete=pg.enums.OnDelete.CASCADE) guest_id: Col[int] = pg.fk(Guest) @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]: return (pg.Unique(cls.booking_id, cls.guest_id),) class Charge(pg.Table): charge_id: Col[int] = pg.pk(default=pg.identity()) booking_id: Col[int] = pg.fk(Booking, on_delete=pg.enums.OnDelete.CASCADE) kind: Col[ChargeKind] = pg.fk(ChargeKindType) description: Col[str] quantity: Col[pg.Int2] = pg.col(default=1) unit_price: Col[Money] amount: Col[Money] = pg.generated(mode=pg.enums.GeneratedMode.STORED) @classmethod def __generated__(cls) -> tuple[pg.Generated, ...]: return (pg.Generated(cls.amount, cls.quantity * cls.unit_price),) class RoomAssignment(pg.Table): room_id: Col[int] = pg.fk(Room, on_delete=pg.enums.OnDelete.CASCADE) stay: Col[Range[date]] booking_id: Col[int] = pg.fk(Booking, on_delete=pg.enums.OnDelete.CASCADE) @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]: return (pg.TemporalPrimaryKey(cls.room_id, cls.stay),) class Rate(pg.Table): rate_id: Col[int] = pg.pk(default=pg.identity()) dormitory_id: Col[int] = pg.fk(Dormitory, on_delete=pg.enums.OnDelete.CASCADE) category: Col[RoomCategory] = pg.fk(RoomCategoryType) valid_during: Col[Range[date]] nightly_price: Col[Money] @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]: return (pg.TemporalUnique(cls.dormitory_id, cls.category, cls.valid_during),) ``` ```python title="examples/schema.py | Payment, CardPayment, BankTransfer, VoucherPayment, Task, CleaningTask, MaintenanceTask" class Payment(pg.Table): payment_id: Col[int] = pg.pk(default=pg.identity()) payment_method_id: Col[PaymentMethod] = pg.discriminator( PaymentMethodType.payment_method_type_id ) booking_id: Col[int] = pg.fk(Booking, on_delete=pg.enums.OnDelete.CASCADE) amount: Col[Money] paid_at: Col[datetime] = pg.col(default=pg.now(), server_managed=True) class CardPayment(Payment, variant=PaymentMethod.CARD): card_last4: Col[str] class BankTransfer(Payment, variant=PaymentMethod.TRANSFER): iban: Col[str] class VoucherPayment(Payment, variant=PaymentMethod.VOUCHER): voucher_code: Col[str] class Task(pg.Table): task_id: Col[int] = pg.pk(default=pg.identity()) task_kind_id: Col[TaskKind] = pg.discriminator(TaskKindType.task_kind_type_id) room_id: Col[int] = pg.fk(Room, on_delete=pg.enums.OnDelete.CASCADE) summary: Col[str] claimed_by: Col[str | None] = pg.col(default=None) done: Col[bool] = pg.col(default=False) class CleaningTask(Task, joined=True, variant=TaskKind.CLEANING): extra_towels: Col[pg.Int2] = pg.col(default=2) peanut_refill_kg: Col[pg.Int2] = pg.col(default=5) class MaintenanceTask(Task, joined=True, variant=TaskKind.MAINTENANCE): requires_welder: Col[bool] = pg.col(default=False) parts_cost: Col[Money] = pg.col(default=Decimal("0.00")) ``` ## Act IV -- Partitioned telemetry & ephemeral staging ```python title="examples/schema.py | DoorEvent, StageBookingImport" class DoorEvent(pg.Table): door_event_id: Col[int] = pg.pk(default=pg.identity()) scanned_at: Col[datetime] = pg.pk() dormitory_id: Col[int] = pg.fk(Dormitory) room_number: Col[Code] badge_code: Col[str] species_code: Col[str] granted: Col[bool] weight_kg: Col[float] tariff_eur: Col[Money] tags: Col[list[str]] = pg.col(default_factory=list) @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]: return (pg.PartitionBy.range(cls.scanned_at),) class StageBookingImport(pg.Table, temp=True, on_commit=pg.enums.OnCommit.DROP): reference_code: Col[str] guest_email: Col[str] stay_start: Col[date] stay_end: Col[date] ``` --- # The Zero-SQL Hall of Shame > *After hours in Ferris' humming server room. The night shift is over, the lobby is quiet, and one last dare is taped to the rack.* > > ** Panda (smug):** Sure, typed ORM queries work for cute check-ins. Now try timezone business-hour buckets, gap-and-island streaks, recursive `CUBE` rollups, hybrid full-text + JSONPath, `SKIP LOCKED` write CTEs, and `LATERAL` percentiles -- *without* raw SQL! > > ** Ferris (smug):** Hold my coffee. Six production monsters, zero SQL strings, 1 round trip each, and every line strictly type-checked. > > ** Maya (happy):** Wait -- you actually built a Hall of Shame of the wildest things you can force through `pgdorm`? > *What's the wildest thing you might expect to write in `pgdorm` under a strict zero-raw-SQL & O(1)-SQL-shape policy -- and proof that it still compiles to 1-RTT canonical PostgreSQL.* `pgdorm` intentionally has **no** `text()`, `raw()`, `execute_raw()`, or `query_raw()` escape hatch. Every query in this page is a live-verified, 1-RTT PostgreSQL statement from the `hall_of_shame` example, strictly type-checked. --- ## Exhibit 1 () -- The Timezone Business-Hours Classifier Classify UTC timestamps in Lisbon local time into `"weekend"`, `"business"`, or `"after_hours"` in 1 RTT: - `pg.extract("ISODOW", ...)` and `pg.extract("HOUR", ...)` return `Expr[Decimal]` because PostgreSQL's `EXTRACT` returns `numeric`. Strict type checkers therefore require explicit `Decimal(6)` / `Decimal(9)` bounds instead of silently mixing `int` and `numeric`. - `.in_any([Decimal(6), Decimal(7)])` emits `= ANY($2)` with a single typed array parameter instead of variable-length `IN ($2, $3)`, preserving O(1) prepared-statement shapes. **Equivalent Raw SQL:** ```sql SELECT guest_name, CASE WHEN EXTRACT(ISODOW FROM occurred_at AT TIME ZONE 'Europe/Lisbon') = ANY(ARRAY[6, 7]) THEN 'weekend' WHEN EXTRACT(HOUR FROM occurred_at AT TIME ZONE 'Europe/Lisbon') BETWEEN 9 AND 17 THEN 'business' ELSE 'after_hours' END AS bucket FROM dorm_event ORDER BY dorm_event_id ASC; ``` **The zero-SQL `pgdorm` AST (1 RTT, statically typed):** ```python title="examples/406_hall_of_shame.py | exhibit_business_hours" hl_lines="21" async def exhibit_business_hours(pool: pg.Pool) -> None: local_ts = DormEvent.occurred_at.at_time_zone("Europe/Lisbon") isodow = pg.extract(pg.enums.ExtractField.ISODOW, local_ts) hour = pg.extract(pg.enums.ExtractField.HOUR, local_ts) bucket = ( pg.case( (isodow.in_any([Decimal(6), Decimal(7)]), "weekend"), (hour.between(Decimal(9), Decimal(17)), "business"), else_="after_hours", ) ).alias("bucket") async with pool.trace() as tr: rows = await pool.all( pg.select(DormEvent) .columns(DormEvent.guest_name, bucket) .order_by(DormEvent.dorm_event_id.asc()) ) assert tr.rtts == 1 print(f"exhibit 1 ({tr.rtts} RTT): {rows}") # => exhibit 1 (1 RTT): [('Jumbo', 'business'), ('Pip', 'after_hours'), ('Tusk', 'weekend')] ``` **Exact SQL PostgreSQL received on the wire (1 RTT):** ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql SELECT "guest_name", CASE WHEN EXTRACT(ISODOW FROM "occurred_at" AT TIME ZONE $1) = ANY($2) THEN $3 WHEN EXTRACT(HOUR FROM "occurred_at" AT TIME ZONE $4) BETWEEN $5 AND $6 THEN $7 ELSE $8 END AS "bucket" FROM "dorm_event" ORDER BY "dorm_event_id" ASC; ``` --- ## Exhibit 2 () -- The 2-CTE Gap-and-Island Streak Detector Find every guest's consecutive-night stay streaks of at least 2 nights using `LAG`, a `CASE` boundary flag, a running `SUM(...) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`, and a `HAVING COUNT(*) >= 2` aggregation. **Equivalent Raw SQL:** ```sql WITH ordered AS ( SELECT guest_name, stay_day, CASE WHEN (stay_day - LAG(stay_day) OVER (PARTITION BY guest_name ORDER BY stay_day)) = 1 THEN 0 ELSE 1 END AS is_new FROM stay_checkin ), islands AS ( SELECT guest_name, stay_day, SUM(is_new) OVER ( PARTITION BY guest_name ORDER BY stay_day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS island_id FROM ordered ) SELECT guest_name, MIN(stay_day) AS start_day, MAX(stay_day) AS end_day, COUNT(*) AS nights FROM islands GROUP BY guest_name, island_id HAVING COUNT(*) >= 2 ORDER BY guest_name ASC, MIN(stay_day) ASC; ``` **The zero-SQL `pgdorm` AST (1 RTT, statically typed):** ```python title="examples/406_hall_of_shame.py | exhibit_gap_and_island" hl_lines="53" async def exhibit_gap_and_island(pool: pg.Pool) -> None: prev_day = pg.lag(StayCheckin.stay_day).over( partition_by=[StayCheckin.guest_name], order_by=[StayCheckin.stay_day.asc()], ) ordered = pg.cte( "ordered", pg.select(StayCheckin).columns( StayCheckin.guest_name, StayCheckin.stay_day, pg.case( (pg.cast(StayCheckin.stay_day - prev_day, "int4") == 1, 0), else_=1, ).alias("is_new"), ), ) frame = pg.rows_between( pg.enums.FrameBoundKind.UNBOUNDED_PRECEDING, pg.enums.FrameBoundKind.CURRENT_ROW ) islands = pg.cte( "islands", pg.select(ordered).columns( ordered.col("guest_name"), ordered.col("stay_day"), pg.sum(ordered.col("is_new")) .over( partition_by=[ordered.col("guest_name")], order_by=[ordered.col("stay_day").asc()], frame=frame, ) .alias("island_id"), ), ) async with pool.trace() as tr: streaks = await pool.all( pg.with_( ordered, islands, query=pg.select(islands) .columns( islands.col("guest_name"), pg.min(islands.col("stay_day")).alias("start_day"), pg.max(islands.col("stay_day")).alias("end_day"), pg.count().alias("nights"), ) .group_by(islands.col("guest_name"), islands.col("island_id")) .having(pg.count() >= 2) .order_by(islands.col("guest_name").asc(), pg.min(islands.col("stay_day")).asc()), ) ) assert tr.rtts == 1 print(f"exhibit 2 ({tr.rtts} RTT): {[(g, n) for g, _s, _e, n in streaks]}") # => exhibit 2 (1 RTT): [('Jumbo', 3), ('Pip', 2)] ``` **Exact SQL PostgreSQL received on the wire (1 RTT):** ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql WITH "ordered" AS ( SELECT "guest_name", "stay_day", CASE WHEN CAST("stay_day" - LAG("stay_day") OVER (PARTITION BY "guest_name" ORDER BY "stay_day" ASC) AS INTEGER) = $1 THEN $2 ELSE $3 END AS "is_new" FROM "stay_checkin" ), "islands" AS ( SELECT "guest_name", "stay_day", SUM("is_new") OVER (PARTITION BY "guest_name" ORDER BY "stay_day" ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS "island_id" FROM "ordered" ) SELECT "guest_name", MIN("stay_day") AS "start_day", MAX("stay_day") AS "end_day", COUNT(*) AS "nights" FROM "islands" GROUP BY "guest_name", "island_id" HAVING COUNT(*) >= $4 ORDER BY "guest_name" ASC, MIN("stay_day") ASC; ``` --- ## Exhibit 3 () -- The Recursive Hierarchy Cube Rollup Walk a self-referencing wing tree with PostgreSQL's `WITH RECURSIVE ... SEARCH DEPTH FIRST ... CYCLE ... SET is_cycle USING path`, filter out cycles, and aggregate across `GROUP BY ROLLUP(...)` with `GROUPING(...)` bitmasks and conditional `SUM(...) FILTER (WHERE ...)`: **Equivalent Raw SQL:** ```sql WITH RECURSIVE wing_tree AS ( SELECT wing_node_id, region_code, tier, beds FROM wing_node WHERE parent_wing_id IS NULL UNION ALL SELECT w.wing_node_id, w.region_code, w.tier, w.beds FROM wing_node w INNER JOIN wing_tree t ON w.parent_wing_id = t.wing_node_id ) SEARCH DEPTH FIRST BY wing_node_id SET depth_ord CYCLE wing_node_id SET is_cycle USING path SELECT region_code, tier, GROUPING(region_code, tier) AS grp_mask, SUM(beds) FILTER (WHERE tier = 'vip') AS vip_beds, SUM(beds) AS total_beds FROM wing_tree WHERE is_cycle = FALSE GROUP BY ROLLUP (region_code, tier) ORDER BY GROUPING(region_code, tier) ASC, region_code ASC, tier ASC; ``` **The zero-SQL `pgdorm` AST (1 RTT, statically typed):** ```python title="examples/406_hall_of_shame.py | exhibit_recursive_cube" hl_lines="49" async def exhibit_recursive_cube(pool: pg.Pool) -> None: tree = pg.recursive_cte( "wing_tree", base=pg.select(WingNode) .columns( WingNode.wing_node_id, WingNode.region_code, WingNode.tier, WingNode.beds, ) .where(WingNode.parent_wing_id.is_null()), step=lambda ref: ( pg.select(WingNode) .join_cte(ref, WingNode.parent_wing_id, ref.col("wing_node_id")) .columns( WingNode.wing_node_id, WingNode.region_code, WingNode.tier, WingNode.beds, ) ), search=(pg.enums.SearchOrder.DEPTH, ["wing_node_id"], "depth_ord"), cycle=(["wing_node_id"], "is_cycle", "path"), ) async with pool.trace() as tr: rollup_rows = await pool.all( pg.with_( tree, query=pg.select(tree) .columns( tree.col("region_code"), tree.col("tier"), pg.grouping(tree.col("region_code"), tree.col("tier")).alias("grp_mask"), pg.sum(tree.col("beds")).filter(tree.col("tier") == "vip").alias("vip_beds"), pg.sum(tree.col("beds")).alias("total_beds"), ) .where(tree.col("is_cycle") == False) # noqa: E712 .group_by(pg.rollup(tree.col("region_code"), tree.col("tier"))) .order_by( pg.grouping(tree.col("region_code"), tree.col("tier")).asc(), tree.col("region_code").asc(), tree.col("tier").asc(), ), ) ) assert tr.rtts == 1 summary = [(t, m, str(tot)) for _r, t, m, _v, tot in rollup_rows] print(f"exhibit 3 ({tr.rtts} RTT): {summary}") # => exhibit 3 (1 RTT): [('std', 0, '12'), ('vip', 0, '12'), (None, 1, '24'), (None, 3, '24')] ``` **Exact SQL PostgreSQL received on the wire (1 RTT):** ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql WITH RECURSIVE "wing_tree" AS ( SELECT "wing_node_id", "region_code", "tier", "beds" FROM "wing_node" WHERE "parent_wing_id" IS NULL UNION ALL SELECT "wing_node"."wing_node_id", "wing_node"."region_code", "wing_node"."tier", "wing_node"."beds" FROM "wing_node" INNER JOIN "wing_tree" ON "wing_node"."parent_wing_id" = "wing_tree"."wing_node_id" ) SEARCH DEPTH FIRST BY "wing_node_id" SET "depth_ord" CYCLE "wing_node_id" SET "is_cycle" USING "path" SELECT "region_code", "tier", GROUPING("region_code", "tier") AS "grp_mask", SUM("beds") FILTER (WHERE "tier" = $1) AS "vip_beds", SUM("beds") AS "total_beds" FROM "wing_tree" WHERE "is_cycle" = $2 GROUP BY ROLLUP ("region_code", "tier") ORDER BY GROUPING("region_code", "tier") ASC, "region_code" ASC, "tier" ASC; ``` --- ## Exhibit 4 () -- The Hybrid Full-Text + SQL/JSON Path Concierge Ranker Blend cover-density full-text ranking (`pg.ts_rank_cd`) with a `CASE`-based `jsonb_path_exists` VIP multiplier and `pg.coalesce` / `pg.greatest` floor clamping -- all in a single 1-RTT statement: **Equivalent Raw SQL:** ```sql SELECT title, GREATEST( COALESCE(ts_rank_cd(to_tsvector('english', body), websearch_to_tsquery('english', 'mud spa OR peanuts')), 0.0) * CASE WHEN jsonb_path_exists(meta, '$.vip ? (@ == true)') THEN 2.0 ELSE 1.0 END, 0.01 ) AS score FROM concierge_item WHERE to_tsvector('english', body) @@ websearch_to_tsquery('english', 'mud spa OR peanuts') AND jsonb_path_exists(meta, '$.wing.floor') ORDER BY score DESC, concierge_item_id ASC; ``` **The zero-SQL `pgdorm` AST (1 RTT, statically typed):** ```python title="examples/406_hall_of_shame.py | exhibit_hybrid_fts_jsonpath" hl_lines="24" async def exhibit_hybrid_fts_jsonpath(pool: pg.Pool) -> None: vec = pg.to_tsvector(ConciergeItem.body, config="english") q_ts = pg.websearch_to_tsquery("mud spa OR peanuts", config="english") vip_boost = pg.case( (pg.jsonb_path_exists(ConciergeItem.meta, "$.vip ? (@ == true)"), 2.0), else_=1.0, ) blended = pg.greatest(pg.coalesce(pg.ts_rank_cd(vec, q_ts), 0.0) * vip_boost, 0.01) async with pool.trace() as tr: ranked = await pool.all( pg.select(ConciergeItem) .columns(ConciergeItem.title, blended.alias("score")) .where( pg.and_( vec.ts_match(q_ts), pg.jsonb_path_exists(ConciergeItem.meta, "$.wing.floor"), ) ) .order_by(blended.desc(), ConciergeItem.concierge_item_id.asc()) ) assert tr.rtts == 1 print(f"exhibit 4 ({tr.rtts} RTT): {[t for t, _s in ranked]}") # => exhibit 4 (1 RTT): ['VIP Mud Spa', 'Garden Mud Bath', 'Peanut Platter'] ``` **Exact SQL PostgreSQL received on the wire (1 RTT):** ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql SELECT "title", GREATEST(COALESCE(ts_rank_cd(to_tsvector(CAST($1 AS REGCONFIG), "body"), websearch_to_tsquery(CAST($2 AS REGCONFIG), $3)), $4) * CASE WHEN jsonb_path_exists("meta", $5) THEN $6 ELSE $7 END, $8) AS "score" FROM "concierge_item" WHERE to_tsvector(CAST($9 AS REGCONFIG), "body") @@ websearch_to_tsquery(CAST($10 AS REGCONFIG), $11) AND jsonb_path_exists("meta", $12) ORDER BY GREATEST(COALESCE(ts_rank_cd(to_tsvector(CAST($13 AS REGCONFIG), "body"), websearch_to_tsquery(CAST($14 AS REGCONFIG), $15)), $16) * CASE WHEN jsonb_path_exists("meta", $17) THEN $18 ELSE $19 END, $20) DESC, "concierge_item_id" ASC; ``` --- ## Exhibit 5 () -- Single-Statement Lock-Free Queue Claim & Atomic Archive Two classic concurrency patterns that usually force developers out of an ORM: 1. **Lock-free job claim**: `WITH candidate AS (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1) UPDATE ... FROM candidate ... RETURNING ...` 2. **Atomic archive**: `WITH purged AS (DELETE ... USING ... RETURNING ...) INSERT INTO ... SELECT ... RETURNING ...` **Equivalent Raw SQL:** ```sql -- 1. Lock-free queue claim WITH candidate AS ( SELECT dispatch_job_id FROM dispatch_job WHERE state = 'queued' ORDER BY priority DESC, dispatch_job_id ASC LIMIT 1 FOR UPDATE SKIP LOCKED ) UPDATE dispatch_job SET state = 'claimed' FROM candidate WHERE dispatch_job.dispatch_job_id = candidate.dispatch_job_id RETURNING wing_code, state, priority; -- 2. Atomic archive WITH purged AS ( DELETE FROM dispatch_job USING wing_node WHERE dispatch_job.wing_code = wing_node.code AND dispatch_job.state = 'done' RETURNING wing_code, priority ) INSERT INTO dispatch_archive (wing_code, priority) SELECT wing_code, priority FROM purged RETURNING wing_code, priority; ``` **The zero-SQL `pgdorm` AST (1+1 RTTs, statically typed):** ```python title="examples/406_hall_of_shame.py | exhibit_queue_claim_and_archive" hl_lines="51" async def exhibit_queue_claim_and_archive(pool: pg.Pool) -> None: # 1. Single-statement lock-free queue claim: FOR UPDATE SKIP LOCKED + UPDATE ... FROM. candidate = pg.cte( "candidate", pg.select(DispatchJob) .columns(DispatchJob.dispatch_job_id) .where(DispatchJob.state == "queued") .order_by(DispatchJob.priority.desc(), DispatchJob.dispatch_job_id.asc()) .for_update(skip_locked=True) .limit(1), ) async with pool.trace() as tr_claim: claimed = await pool.all( pg.with_( candidate, query=pg.update(DispatchJob) .from_(candidate) .set(state="claimed") .where(DispatchJob.dispatch_job_id == candidate.col("dispatch_job_id")) .returning(DispatchJob.wing_code, DispatchJob.state, DispatchJob.priority), ) ) assert tr_claim.rtts == 1 # 2. Writable CTE atomic archive: DELETE ... USING ... RETURNING -> INSERT ... SELECT. purged = pg.cte( "purged", pg.delete(DispatchJob) .using(WingNode) .where( pg.and_( DispatchJob.wing_code == WingNode.code, DispatchJob.state == "done", ) ) .returning(DispatchJob.wing_code, DispatchJob.priority), ) async with pool.trace() as tr_arch: archived = await pool.all( pg.with_( purged, query=pg.insert(DispatchArchive) .from_select( pg.select(purged).columns(purged.col("wing_code"), purged.col("priority")) ) .returning(DispatchArchive.wing_code, DispatchArchive.priority), ) ) assert tr_arch.rtts == 1 print(f"exhibit 5 ({tr_claim.rtts}+{tr_arch.rtts} RTTs): claimed={claimed} archived={archived}") # => exhibit 5 (1+1 RTTs): claimed=[('EAST', 'claimed', 10)] archived=[('EAST', 3)] ``` **Exact SQL PostgreSQL received on the wire (1 RTT each):** ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql WITH "candidate" AS ( SELECT "dispatch_job_id" FROM "dispatch_job" WHERE "state" = $1 ORDER BY "priority" DESC, "dispatch_job_id" ASC LIMIT $2 FOR UPDATE SKIP LOCKED ) UPDATE "dispatch_job" SET "state" = $3 FROM "candidate" WHERE "dispatch_job"."dispatch_job_id" = "candidate"."dispatch_job_id" RETURNING "wing_code", "state", "priority"; ``` ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql WITH "purged" AS ( DELETE FROM "dispatch_job" USING "wing_node" WHERE "dispatch_job"."wing_code" = "wing_node"."code" AND "dispatch_job"."state" = $1 RETURNING "wing_code", "priority" ) INSERT INTO "dispatch_archive" ("wing_code", "priority") SELECT "wing_code", "priority" FROM "purged" RETURNING "wing_code", "priority"; ``` --- ## Exhibit 6 () -- Correlated `LATERAL` Top-K + `WITHIN GROUP` Percentiles + Deep JSONB Surgery Join each wing to its top-2 concierge items via `LEFT JOIN LATERAL`, filter JSONB payloads with `.json_has_all_keys(...)` (`?&`), extract nested strings with `.json_path_text(...)` (`#>>`), and aggregate with `pg.percentile_cont(0.95, order_by=...)` and ordered `pg.string_agg(...)`: **Equivalent Raw SQL:** ```sql SELECT w.code, PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY top_two.fee ASC) AS p95_fee, STRING_AGG(top_two.floor, ',' ORDER BY top_two.fee DESC) AS floors FROM wing_node w LEFT JOIN LATERAL ( SELECT title, fee, meta #>> ARRAY['wing', 'floor'] AS floor FROM concierge_item WHERE wing_code = w.code AND meta ?& ARRAY['vip', 'wing'] ORDER BY fee DESC LIMIT 2 ) AS top_two ON TRUE WHERE w.parent_wing_id IS NOT NULL GROUP BY w.code ORDER BY w.code ASC; ``` **The zero-SQL `pgdorm` AST (1 RTT, statically typed):** ```python title="examples/406_hall_of_shame.py | exhibit_lateral_percentiles_jsonb" hl_lines="40" async def exhibit_lateral_percentiles_jsonb(pool: pg.Pool) -> None: top_two = pg.lateral( pg.select(ConciergeItem) .columns( ConciergeItem.title, ConciergeItem.fee, ConciergeItem.meta.json_path_text("wing", "floor").alias("floor"), ) .where( pg.and_( ConciergeItem.wing_code == WingNode.code, ConciergeItem.meta.json_has_all_keys(["vip", "wing"]), ) ) .order_by(ConciergeItem.fee.desc()) .limit(2), alias="top_two", ) async with pool.trace() as tr: rows = await pool.all( pg.select(WingNode) .join_lateral(top_two, kind=pg.enums.LateralJoinKind.LEFT) .columns( WingNode.code, pg.percentile_cont(0.95, order_by=top_two.col("fee", Decimal).asc()).alias( "p95_fee" ), pg.string_agg( top_two.col("floor", str), ",", order_by=[top_two.col("fee", Decimal).desc()], ).alias("floors"), ) .where(WingNode.parent_wing_id.is_not_null()) .group_by(WingNode.code) .order_by(WingNode.code.asc()) ) assert tr.rtts == 1 print(f"exhibit 6 ({tr.rtts} RTT): {[(c, p95, fl) for c, p95, fl in rows]}") # => exhibit 6 (1 RTT): [('EAST', 174.0, 'penthouse,terrace'), ('WEST', 90.0, 'garden')] ``` **Exact SQL PostgreSQL received on the wire (1 RTT):** ```sql -- captured live from PostgreSQL | examples/__wire__/hall_of_shame.sql SELECT "wing_node"."code", PERCENTILE_CONT($1) WITHIN GROUP (ORDER BY "top_two"."fee" ASC) AS "p95_fee", STRING_AGG("top_two"."floor", $2 ORDER BY "top_two"."fee" DESC) AS "floors" FROM "wing_node" LEFT JOIN LATERAL ( SELECT "title", "fee", "meta" #>> $3 AS "floor" FROM "concierge_item" WHERE "wing_code" = "code" AND "meta" ?& $4 ORDER BY "fee" DESC LIMIT $5 ) AS "top_two" ON $6 WHERE "wing_node"."parent_wing_id" IS NOT NULL GROUP BY "wing_node"."code" ORDER BY "wing_node"."code" ASC; ``` --- ## Where Zero-SQL Draws the Hard Line Zero-SQL is a deliberate architectural boundary, not a claim that Python should replace every PostgreSQL feature. `pgdorm` intentionally **never** expresses the following in Python AST: - **Server-side procedural code**: `CREATE FUNCTION ... LANGUAGE plpgsql`, stored procedures, and anonymous `DO $$ ... $$` blocks. - **Trigger definitions & event triggers**: `CREATE TRIGGER ... EXECUTE FUNCTION ...`. - **Unmodeled C-extension DDL**: custom operator classes, foreign data wrappers, or extension-specific storage DDL outside `pgdorm`'s schema IR. When your database owns views, triggers, or PL/pgSQL functions alongside `pgdorm`-managed tables, declare them as `UnmanagedObject` in `pgdorm.migrate` so the migration planner respects their dependency graph without attempting to drop or overwrite them. ### Further Reading - [Queries & DML Reference](../reference/queries-and-dml.md) - [Expressions & Functions Reference](../reference/expressions-and-functions.md) - [Coming From Other ORMs](../guide/coming-from-other-orms.md) --- # Reference Hand-crafted API reference covering every public export of `pgdorm`, `pgdorm.typing`, `pgdorm.migrate`, `pgdorm.testing`, and the `pgdorm` CLI. Signatures are checked against the source on every build, and symbol coverage is verified bidirectionally against each package's `__all__`. For concepts, tutorials, and end-to-end walkthroughs, start with [First Shift](../guide/first-shift.md) or [The Elephant Dormitory Story](../story/index.md). ## Layered Public Packages | Package | Purpose | Reference Page | | :--- | :--- | :--- | | `pgdorm` | Core ORM surface: models, types, query/DML builders, expressions, runtime pool, and typed exceptions | [Models & Types](models-and-types.md), [Queries & DML](queries-and-dml.md), [Expressions & Functions](expressions-and-functions.md), [Runtime & Pool](runtime-and-pool.md), [Errors & Linters](errors-and-linters.md) | | `pgdorm.typing` | Strictly typed protocols, type aliases, and helper types (zero runtime helper functions) | [Typing](typing-and-testing.md) | | `pgdorm.migrate` | Online schema migrations, AST diffing, lock-timeout guards, and rollback planning | [Migrations](migrations-and-assimilation.md) | | `pgdorm.testing` | Zero-mock test helpers, PostgreSQL container factories, and schema isolation fixtures | [Testing](typing-and-testing.md) | | `pgdorm` CLI | Command-line migration runner, schema inspection, and `doctor` diagnostics | [CLI](cli.md) | ## Type-Checker Guarantees The public API is written in modern, fully annotated Python and checked in strict mode, so standard type checkers infer precise types with no stubs or plugins. All `Table` subclasses are slot-backed (`__slots__`, zero `__dict__`), query builders propagate row and column types through `Select[T]`, `Executable[RetT]`, and `ReadQuery[RetT]`, and read-only pools (`ReadPool` / `ReadTransaction`) statically reject write statements at type-check time. ## Machine-Readable Indexes - [`/pgdorm/llms.txt`](../llms.txt) -- Concise site map and API overview for LLM agents - [`/pgdorm/llms-full.txt`](../llms-full.txt) -- Full concatenated documentation corpus ## Reference Pages 1. **[Models & Types](models-and-types.md)** -- `Table`, `TypeTable`, `Col`, column/constraint descriptors, `Registry`, `Create`/`Patch` DTOs, PostgreSQL type markers, `Range`, JSON/FTS types, ERD export, and version helpers. 2. **[Queries & DML](queries-and-dml.md)** -- `select`, `insert`, `insert_many`, `insert_subtype`, `update`, `delete`, `merge`, `RETURNING`, CTEs, `LATERAL` joins, set operations, subqueries, `compile`, `prepare`, and `ResultRow`. 3. **[Expressions & Functions](expressions-and-functions.md)** -- `Expr`, `OrderSpec`, `param`, `lit`, `func`, `cast`, `case`, aggregates, grouping sets, window functions & frames, full-text search, and JSONB/SQL-JSON helpers. 4. **[Runtime & Pool](runtime-and-pool.md)** -- `Pool`, `ReadPool`, `Connection`, `Transaction`, `Pipeline`, `RowStream`, `ArrowStream`, `SplitResult`, `Listener`, `ExplainPlan`, `Trace`, `TelemetryHook`, and `doctor`. 5. **[Errors & Linters](errors-and-linters.md)** -- `PgdormError` hierarchy, schema/join/DML linters, and typed PostgreSQL SQLSTATE exceptions with retryability rules. 6. **[Typing](typing-and-testing.md)** -- Public protocols, type aliases, and generic bounds in `pgdorm.typing`. 7. **[Migrations](migrations-and-assimilation.md)** -- `pgdorm.migrate` schema snapshots, diffs, operations, and online migration runner. 8. **[Testing](typing-and-testing.md)** -- `pgdorm.testing` container helpers and database fixtures. 9. **[CLI](cli.md)** -- `pgdorm` command-line subcommands and flags. --- # Models & Types `pgdorm` models are slot-backed Python classes (`__slots__`, zero `__dict__`) that compile directly to PostgreSQL DDL and Rust IR specs. See [Hello Dorm](../story/01_hello_dorm.md), [Column Types & DDL](../story/04_column_types_and_ddl.md), [Temporal Bookings](../story/06_temporal_bookings.md), [Inheritance, Payments & Tasks](../story/07_inheritance_payments_tasks.md), and [Partitioning Door Events](../story/15_partitioning_door_events.md). --- ## Tables & Columns ### `Table` {#Table} ```python title="signature" class Table(metaclass=TableMeta): @property def xmin(self) -> int | None: ... @classmethod def alias(cls, name: str) -> type[Self]: ... ``` Base class for all `pgdorm` entity tables. Derives the PostgreSQL table name strictly in singular `snake_case` from the class name (explicit `name="..."` overrides raise `SchemaLintError`). Enforces own-PK hygiene (`_id`), disjoint `TypeTable` naming, and `__slots__` layout. Supports class keyword options such as `schema=`, `temp=`, `on_commit=`, `partition_by=`, `strict_pk=`, and `inherits=` / `discriminator_value=` for class-table inheritance. ### `TypeTable` {#TypeTable} ```python title="signature" class TypeTable(Table, abstract=True): code: Col[str] = col(unique=True) ``` Base class for lookup / enum-backed reference tables. Subclass names must end with `Type` (`_type`), use an `int4` primary key, and declare a unique `code` column. Raises `SchemaLintError` on naming or `IntEnum` mapping collisions. See [Type Tables & Enums](../story/field_notes_type_tables_and_enums.md). ### `Col` {#Col} ```python title="signature" class Col[T](ColBase, _ExprOpsMixin[T], ValueExpr[T]): def alias(self, name: str) -> Expr[T]: ... def in_any( self, values: Sequence[T] | ParamRef[Sequence[T]] | ParamRef[list[T]] | UntypedParamRef, ) -> Expr[bool]: ... def ne_all(self, values: Sequence[T]) -> Expr[bool]: ... def overlaps(self, other: TypedOperand[T]) -> Expr[bool]: ... def contains(self, other: ExprArg) -> Expr[bool]: ... def to(self, value: TypedOperand[T] | UnsetType) -> Assign: ... @classmethod def from_resolved( cls, *, name: str, resolved: ResolvedColType, owner: TableRef, spec: _FieldSpec, pg_type: str | None = None, nullable: bool | None = None, py_type: TypeFormLike | UnsetType | None = UNSET, enum_type: type[Enum] | UnsetType | None = UNSET, ) -> ColBase: ... ``` Typed column descriptor bound to a `Table` class attribute. Accessing `MyTable.column_name` returns a `Col[T]` that supports typed comparison, arithmetic, ordering (`.asc()`, `.desc()`), JSONB, and full-text operators; accessing the same attribute on an instance returns the hydrated Python value `T`. ### `col` {#col} ```python title="signature" def col( *, unique: bool = False, index: bool = False, max_len: int | None = None, precision: int | None = None, scale: int | None = None, server_managed: bool = False, secret: bool = False, default: PgValue | ServerDefault | ServerDefaultExprBase | UnsetType = UNSET, default_factory: Callable[[], PgValue] | None = None, ) -> Any: ... ``` Declares column metadata on a `Table` field: uniqueness (`unique`), server-populated values (`server_managed`), redaction in `repr`/logs (`secret`), and literal, server-side, or client-side defaults. ### `pk` {#pk} ```python title="signature" def pk( *, default: ServerDefault | UnsetType = UNSET, server_managed: bool = False, ) -> Any: ... ``` Marks a field as the table's primary key (`_id`). Entity `int` PKs default to `BIGINT` (`int8`); `TypeTable` PKs default to `INTEGER` (`int4`). Pair with `identity()` or `uuidv7()`. ### `fk` {#fk} ```python title="signature" def fk( target: ColBase | TableRef, *, on_delete: OnDelete | None = None, auto_index: bool = True, unique: bool = False, deferrable: bool = False, initially_deferred: bool = False, default: PgValue | ServerDefault | ServerDefaultExprBase | UnsetType = UNSET, ) -> Any: ... ``` Declares a single-column foreign key referencing `target` (either a `Table` class or an explicit `Table.column`). Automatically generates a supporting B-tree index (`auto_index=True`, deduplicated against leftmost-prefix indexes) and supports `unique=True` and `DEFERRABLE` / `INITIALLY DEFERRED` constraints. ### `self_fk` {#self_fk} ```python title="signature" def self_fk( target_col: str | None = None, *, on_delete: OnDelete | None = None, auto_index: bool = True, unique: bool = False, deferrable: bool = False, initially_deferred: bool = False, default: PgValue | ServerDefault | ServerDefaultExprBase | UnsetType = UNSET, ) -> Any: ... ``` Declares an inline self-referential foreign key pointing to the table's own primary key (or `target_col`), eliminating the need for table-level `ForeignKey(...)` on tree/hierarchy models. ### `identity` {#identity} ```python title="signature" def identity() -> ServerDefault: ... ``` Returns a PostgreSQL `GENERATED BY DEFAULT AS IDENTITY` server default for `pk(default=identity())`. ### `uuidv7` {#uuidv7} ```python title="signature" def uuidv7(*, client_generated: bool = False) -> ServerDefault: ... ``` Returns a native `DEFAULT uuidv7()` server default (or a client-generated UUIDv7 default when `client_generated=True`). See [Column Types & DDL](../story/04_column_types_and_ddl.md). ### `new_uuidv7` {#new_uuidv7} ```python title="signature" def new_uuidv7() -> UUID: ... ``` Generates a monotonic RFC 9562 UUIDv7 in Rust without a database round-trip. ### `generated` {#generated} ```python title="signature" def generated( *, mode: GeneratedMode = GeneratedMode.VIRTUAL, init: Literal[False] = False, ) -> Any: ... ``` Declares a generated column (`GENERATED ALWAYS AS (...) VIRTUAL` by default, or `STORED`), paired with a `pg.Generated(cls., )` entry inside `@classmethod def __generated__(cls)`. Excluded from `__init__` and `INSERT` payloads. ### `Generated` {#Generated} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Generated: col: ColBase expr_sql: str ``` Typed binding between a `pg.generated()` column descriptor and its typed `pg.Expr[T]` expression, returned from `@classmethod def __generated__(cls) -> tuple[pg.Generated, ...]`. ### `TableConstraint` {#TableConstraint} ```python title="signature" type TableConstraint = ( PrimaryKey | Unique | Index | Check | ForeignKey | TemporalPrimaryKey | TemporalUnique | PartitionBy ) ``` Union of all table-level constraint and partitioning descriptors returned from `@classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...]`. ### `uuidv4` {#uuidv4} ```python title="signature" def uuidv4(*, client_generated: bool = False) -> ServerDefault: ... ``` PostgreSQL `gen_random_uuid()` default for random UUIDv4 keys (set `client_generated=True` to mint UUIDv4 values in Python). ### `current_date` {#current_date} ```python title="signature" def current_date() -> ServerDefault: ... ``` PostgreSQL `CURRENT_DATE` server-side default for `date` columns. ### `discriminator` {#discriminator} ```python title="signature" def discriminator( target: ColBase, *, on_delete: OnDelete = OnDelete.RESTRICT, auto_index: bool = True, init: Literal[False] = False, ) -> Any: ... ``` Declares an `IntEnum`/`TypeTable`-backed discriminator column for Class-Table Inheritance (CTI). String discriminators are forbidden (`SchemaLintError`). See [Inheritance, Payments & Tasks](../story/07_inheritance_payments_tasks.md). ### `xmin` {#xmin} ```python title="signature" def xmin(table: TableRef) -> Col[int]: ... ``` Returns a typed `Col[int]` descriptor for PostgreSQL's `xmin` system column on `table`, used for optimistic concurrency control. --- ## Table Constraints & Partitioning ### `PrimaryKey` {#PrimaryKey} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class PrimaryKey: col_refs: tuple[ColRefArg, ...] ``` Declares a composite table-level `PRIMARY KEY` inside `__constraints__`. ### `ForeignKey` {#ForeignKey} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ForeignKey: local_refs: tuple[ColRefArg, ...] ref_cols: tuple[ColRefArg, ...] on_delete: OnDelete | SetNull | None = None auto_index: bool = True deferrable: bool = False initially_deferred: bool = False ``` Declares a composite or table-level `FOREIGN KEY` constraint inside `__constraints__`. Supports `deferrable=True`, `initially_deferred=True`, `SetNull(...)` partial-column nullification, and `auto_index=True`. ### `Unique` {#Unique} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Unique: col_refs: tuple[ColRefArg, ...] ``` Declares a `UNIQUE` constraint across one or more columns. ### `Check` {#Check} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Check: expr_sql: str ``` Declares a `CHECK ()` constraint on a `Table`. ### `Index` {#Index} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Index: col_refs: tuple[IndexColArg, ...] unique: bool = False where_sql: str | None = None ``` Declares a B-tree, unique, or partial (`where_sql=...`) index inside `__indexes__`. ### `TemporalPrimaryKey` {#TemporalPrimaryKey} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TemporalPrimaryKey: col_refs: tuple[ColRefArg, ...] ``` Declares a PostgreSQL `PRIMARY KEY (..., WITHOUT OVERLAPS)` constraint. Exempts the table from the single-column `_id` lint rule. See [Temporal Bookings](../story/06_temporal_bookings.md). ### `TemporalUnique` {#TemporalUnique} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TemporalUnique: col_refs: tuple[ColRefArg, ...] ``` Declares a PostgreSQL `UNIQUE (..., WITHOUT OVERLAPS)` constraint. ### `PartitionBy` {#PartitionBy} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class PartitionBy: strategy: PartitionStrategy columns: tuple[str, ...] ``` Configures declarative PostgreSQL partitioning (`PARTITION BY RANGE | LIST | HASH (...)`) on a `Table`. See [Partitioning Door Events](../story/15_partitioning_door_events.md). ### `SetNull` {#SetNull} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SetNull: col_refs: tuple[ColRefArg, ...] ``` Specifies PostgreSQL `ON DELETE SET NULL ()` for partial-column nullification on composite `ForeignKey` constraints. --- ## Registry & DTOs ### `Registry` {#Registry} ```python title="signature" class Registry: def register(self, *tables: type[Table]) -> Self: ... def freeze(self) -> FrozenRegistry: ... ``` Mutable collector for a set of `Table` classes. Calling `.freeze()` validates schema-set uniqueness (`SchemaLintError` on duplicate physical tables, index names, `TypeTable` enum mappings, constraint names, or CTI parent collisions) and returns an immutable `FrozenRegistry`. ### `FrozenRegistry` {#FrozenRegistry} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class FrozenRegistry: tables: tuple[type[Table], ...] ir_specs: tuple[TableIrSpec, ...] ``` Immutable, validated snapshot of a `Registry` ready for DDL generation, migrations, and ERD rendering. ### `Create` {#Create} ```python title="signature" class Create[T: Table = Table](_DtoBase[T]): def to_dict(self) -> dict[str, PgValue]: ... def to_model(self, **overrides: PgValue | UnsetType) -> T: ... ``` Typed creation DTO for `Pool.insert(...)` and `insert(...)`, omitting server-managed and generated columns. See [Patch & Returning](../story/02_patch_and_returning.md). ### `Patch` {#Patch} ```python title="signature" class Patch[T: Table = Table](_DtoBase[T]): @property def dirty_mask(self) -> int: ... @overload def set(self, column: ColBase, value: UnsetType) -> Self: ... @overload def set[V: PgValue](self, column: Col[V], value: V | UnsetType) -> Self: ... def get[V: PgValue](self, column: Col[V]) -> V | UnsetType: ... def dirty_fields(self) -> tuple[str, ...]: ... def to_values(self) -> dict[str, PgValue]: ... ``` Typed partial-update DTO distinguishing omitted fields (`UNSET`) from explicit `None` (`NULL`) values. Used with `Update.patch(...)` and `Pool.update_versioned(...)`. ### `UNSET` {#UNSET} ```python title="signature" UNSET = UnsetType() ``` Singleton sentinel indicating an omitted field in a `Patch` or column default. ### `UnsetType` {#UnsetType} ```python title="signature" class UnsetType: ... ``` Type of the `UNSET` sentinel. --- ## Custom Types & PostgreSQL Type Markers ### `TypeDecorator` {#TypeDecorator} ```python title="signature" class TypeDecorator[PyT, WireT: PgValue]: impl: str = "text" def process_bind_param(self, value: PyT) -> WireT: ... def process_result_value(self, value: WireT) -> PyT: ... def apply_pg_type(self, inner: ResolvedColType) -> ResolvedColType: ... ``` Base class for user-defined Python-to-PostgreSQL value codecs. Subclass and attach via `Annotated[PyT, MyDecorator()]`. ### `CustomType` {#CustomType} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CustomType: pg_type: str ``` `Annotated` metadata marker that maps a Python field to an arbitrary PostgreSQL type name (e.g., `Annotated[str, CustomType("citext")]`). ### `Int2` {#Int2} ```python title="signature" type Int2 = Annotated[int, _PgTypeHint(pg_type="int2", explicit_int_width=True)] ``` Maps a Python `int` field to PostgreSQL `SMALLINT` (`int2`). ### `Int4` {#Int4} ```python title="signature" type Int4 = Annotated[int, _PgTypeHint(pg_type="int4", explicit_int_width=True)] ``` Maps a Python `int` field to PostgreSQL `INTEGER` (`int4`). ### `BigInt` {#BigInt} ```python title="signature" type BigInt = Annotated[int, _PgTypeHint(pg_type="int8", explicit_int_width=True)] ``` Maps a Python `int` field to PostgreSQL `BIGINT` (`int8`). ### `Float4` {#Float4} ```python title="signature" type Float4 = Annotated[float, _PgTypeHint(pg_type="float4")] ``` Maps a Python `float` field to PostgreSQL `REAL` (`float4`). ### `Numeric` {#Numeric} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Numeric: precision: int scale: int | None = None ``` `Annotated` metadata marker for `Decimal` fields, emitting `NUMERIC(precision)` or `NUMERIC(precision, scale)`. ### `MaxLen` {#MaxLen} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class MaxLen: length: int ``` `Annotated` metadata marker for `str` fields, emitting `VARCHAR(length)`. ### `Timestamp` {#Timestamp} ```python title="signature" type Timestamp = Annotated[datetime, _PgTypeHint(pg_type="timestamp")] ``` Maps a `datetime` field to `TIMESTAMP WITHOUT TIME ZONE` (bare `datetime` defaults to `TIMESTAMPTZ`). ### `Range` {#Range} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Range[T]: lower: T | None = None upper: T | None = None lower_inc: bool = True upper_inc: bool = False empty: bool = False ``` Immutable representation of PostgreSQL range types (`int4range`, `int8range`, `numrange`, `daterange`, `tsrange`, `tstzrange`). See [Temporal Bookings](../story/06_temporal_bookings.md). ### `Json` {#Json} ```python title="signature" type Json[T] = Annotated[T, _PgTypeHint(pg_type="json")] ``` Maps a field (dict, list, dataclass, or Pydantic model) to PostgreSQL `JSON`. ### `Jsonb` {#Jsonb} ```python title="signature" type Jsonb[T] = Annotated[T, _PgTypeHint(pg_type="jsonb")] ``` Maps a field (dict, list, dataclass, or Pydantic model) to PostgreSQL `JSONB`. ### `JsonValue` {#JsonValue} ```python title="signature" type JsonValue = JsonScalar | Sequence[JsonValue] | Mapping[str, JsonValue] ``` Recursive type alias for any JSON-compatible value. ### `JsonObject` {#JsonObject} ```python title="signature" type JsonObject = dict[str, JsonValue] ``` Type alias for a JSON object (`dict[str, JsonValue]`). ### `JsonPath` {#JsonPath} ```python title="signature" type JsonPath = Annotated[str, _PgTypeHint(pg_type="jsonpath")] ``` Maps a `str` field or parameter to PostgreSQL's `jsonpath` type. ### `JsonMode` {#JsonMode} ```python title="signature" class JsonMode(StrEnum): CLIENT = "client" SERVER = "server" ``` Controls whether `Pool.json(...)` / `Pool.json_one(...)` serializes JSON in Rust (`"client"`, zero Python object allocation) or via PostgreSQL (`"server"`). See [Wire & JSON](../story/field_notes_wire_and_json.md). ### `TsVector` {#TsVector} ```python title="signature" type TsVector = Annotated[str, _PgTypeHint(pg_type="tsvector")] ``` Maps a `str` field to PostgreSQL `tsvector` for full-text search. ### `TsQuery` {#TsQuery} ```python title="signature" type TsQuery = Annotated[str, _PgTypeHint(pg_type="tsquery")] ``` Maps a `str` field or parameter to PostgreSQL `tsquery`. ### `PgValue` {#PgValue} ```python title="signature" type PgValue = PgScalar | Sequence[PgValue] | Mapping[str, PgValue] ``` Union of all Python values accepted as bind parameters by the Rust wire encoder. --- ## ERD & Engine Introspection ### `to_svg_erd` {#to_svg_erd} ```python title="signature" def to_svg_erd(*tables: type[Table], focus: Sequence[type[Table]] = ()) -> str: ... ``` Validates the schema set (`SchemaLintError` on collisions) and renders a deterministic SVG Entity-Relationship Diagram in Rust. Pass `focus=(...)` to draw an *excerpt*: the focus tables in full with a highlighted border and a `NEW` tag, their direct foreign-key neighbours faded with key columns only, and every other table left out. The Renovations tutorial uses this to show each step's additions in context. ### `engine_version` {#engine_version} ```python title="signature" def engine_version() -> str: ... ``` Returns the compiled `pgdorm` Rust/Python package version string. ### `min_postgres_version` {#min_postgres_version} ```python title="signature" def min_postgres_version() -> int: ... ``` Returns the minimum supported PostgreSQL `server_version_num` (see [Requirements](../guide/first-shift.md#requirements)). --- # Queries & DML `pgdorm` compiles typed Python query and DML builders into deterministic PostgreSQL and a `ShapeHash` in Rust -- with zero raw SQL execution. See [Patch & Returning](../story/02_patch_and_returning.md), [Bulk Insert & Upsert](../story/03_bulk_insert_and_upsert.md), [Joins & Folios](../story/05_joins_and_folios.md), [Hierarchy Regions & CTEs](../story/12_hierarchy_regions_cte.md), and [Staging & Merge Import](../story/13_staging_and_merge_import.md). --- ## SELECT Builders ### `select` {#select} ```python title="signature" @overload def select[T: Table](table: type[T]) -> Select[T]: ... @overload def select(table: CteTarget) -> Select[ResultRow]: ... ``` Starts a typed `SELECT` query targeting a `Table`, `TableAlias`, or `CteTarget`. ### `select_expr` {#select_expr} ```python title="signature" @overload def select_expr[T1: PgValue](first: ProjectableExpr[T1], /) -> Select[tuple[T1]]: ... @overload def select_expr(first: ExprBase | ColBase, *rest: ExprBase | ColBase) -> Select[ResultRow]: ... ``` Starts a table-less `SELECT , ...` query (e.g., `select_expr(now())` or scalar function calls), returning `ResultRow` instances. ### `Select` {#Select} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Select[RetT](_WhereOrderLimitMixin, ReadQuery[RetT]): ... ``` Immutable `SELECT` query builder. Every fluent method returns a new `Select` instance. Enforces FK join hygiene (`JoinLintError` on ambiguous or unindexed FKs unless `.allow_seq_scan(reason=...)` is declared). --- ## INSERT, UPDATE, DELETE & MERGE ### `insert` {#insert} ```python title="signature" def insert[T: Table](table: type[T]) -> Insert[T]: ... ``` Starts a single-row `INSERT INTO ` builder. ### `Insert` {#Insert} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Insert[T: Table](_OnConflictMixin[T], Executable[T]): ... ``` Single-row `INSERT` builder with `ON CONFLICT DO NOTHING / DO UPDATE / DO SELECT` and `RETURNING` support. ### `InsertFromSelect` {#InsertFromSelect} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class InsertFromSelect[T: Table](_OnConflictMixin[T], Executable[T]): ... ``` `INSERT INTO
(...) SELECT ...` builder produced by `Insert.from_select(...)`. ### `insert_many` {#insert_many} ```python title="signature" @overload def insert_many[T: Table]( table: type[T], instances: Sequence[T], *, by_name: Literal[False] = False ) -> InsertMany[T]: ... @overload def insert_many[T: Table]( table: type[T], instances: Sequence[object], *, by_name: Literal[True], exclude: Sequence[ColBase | str] = (), ) -> InsertMany[T]: ... ``` Starts a constant-shape bulk `INSERT` using PostgreSQL `UNNEST(...) WITH ORDINALITY ORDER BY u.ord` so any batch size shares one prepared statement. See [Bulk Insert & Upsert](../story/03_bulk_insert_and_upsert.md). ### `InsertMany` {#InsertMany} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class InsertMany[T: Table](_OnConflictMixin[T], Executable[T]): ... ``` Bulk `UNNEST`-backed `INSERT` builder. ### `insert_subtype` {#insert_subtype} ```python title="signature" def insert_subtype[T: Table](table: type[T], **values: PgValue | UnsetType) -> InsertSubtype[T]: ... ``` Atomically inserts a Class-Table Inheritance (CTI) base row and subtype row in a single 1-RTT writable CTE. See [Inheritance, Payments & Tasks](../story/07_inheritance_payments_tasks.md). ### `InsertSubtype` {#InsertSubtype} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class InsertSubtype[T: Table](_ReturningMixin[T], Executable[T]): ... ``` Executable 1-RTT CTI subtype insert statement returned by `insert_subtype(...)`. ### `update` {#update} ```python title="signature" def update[T: Table](table: type[T]) -> Update[T]: ... ``` Starts an `UPDATE
` builder. Raises `UnsafeDmlError` on compile/execute if neither `.where(...)` nor `.allow_full_table(reason=...)` is called. ### `Update` {#Update} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Update[T: Table](_FilteredDmlMixin[T], Executable[T]): ... ``` Immutable `UPDATE` builder supporting `SET`, `Patch[T]`, `FROM`, and `RETURNING OLD.* / NEW.*`. ### `Assign` {#Assign} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Assign: column: ColBase value: PgValue | ExprBase | ColBase | ParamRefBase | UnsetType ``` Column assignment pair produced by `Col.set(value)` and passed to `Update.set(...)` or `on_conflict_do_update(set_=...)`. ### `delete` {#delete} ```python title="signature" def delete[T: Table](table: type[T]) -> Delete[T]: ... ``` Starts a `DELETE FROM
` builder. Raises `UnsafeDmlError` if neither `.where(...)` nor `.allow_full_table(reason=...)` is called. ### `Delete` {#Delete} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Delete[T: Table](_FilteredDmlMixin[T], Executable[T]): ... ``` Immutable `DELETE` builder supporting `USING` and `RETURNING`. ### `merge` {#merge} ```python title="signature" def merge[T: Table](target: type[T]) -> Merge[T, Table]: ... ``` Starts a `MERGE INTO ` builder. See [Staging & Merge Import](../story/13_staging_and_merge_import.md). ### `Merge` {#Merge} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Merge[TargetT: Table, SourceT: Table]( _FilterableReturningMixin[TargetT], Executable[TargetT] ): ... ``` Immutable `MERGE` builder supporting table, `SELECT`, or `UNNEST` sources and `RETURNING merge_action(), ...`. ### `merge_action` {#merge_action} ```python title="signature" def merge_action() -> ReturningRef[str]: ... ``` Emits PostgreSQL's `merge_action()` expression inside `Merge.returning(...)` (`'INSERT'`, `'UPDATE'`, or `'DELETE'`). --- ## RETURNING & Conflict References ### `excluded` {#excluded} ```python title="signature" @overload def excluded[T: PgValue](col: Col[T]) -> Expr[T]: ... @overload def excluded(col: ColBase) -> Expr[PgValue]: ... ``` References `EXCLUDED.` inside `Insert.on_conflict_do_update(...)` and `InsertMany.on_conflict_do_update(...)`. ### `old` {#old} ```python title="signature" def old[T: PgValue](col: Col[T]) -> ReturningRef[T]: ... ``` References `OLD.` inside `Update.returning(...)`, `Delete.returning(...)`, or `Merge.returning(...)`. See [Patch & Returning](../story/02_patch_and_returning.md). ### `new` {#new} ```python title="signature" def new[T: PgValue](col: Col[T]) -> ReturningRef[T]: ... ``` References `NEW.` inside `Insert.returning(...)`, `Update.returning(...)`, or `Merge.returning(...)`. ### `Returning` {#Returning} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Returning[RetT](_TimeoutMixin, Executable[RetT]): ... ``` Sentinel/type namespace representing `RETURNING` projections on DML statements. ### `ReturningRef` {#ReturningRef} ```python title="signature" class ReturningRef[T = PgValue](ReturningRefBase): ... ``` Typed reference to a column, `old(col)`, `new(col)`, or expression returned by a DML `RETURNING` clause. --- ## CTEs, LATERAL, Set Operations & Subqueries ### `cte` {#cte} ```python title="signature" @overload def cte( name: str, query: ReadQuery[object], *, materialized: bool | None = None, columns: Sequence[str] = (), ) -> Cte: ... @overload def cte( name: str, query: Executable[object], *, materialized: bool | None = None, columns: Sequence[str] = (), ) -> WriteCte: ... ``` Defines a named Common Table Expression (`WITH AS [NOT] MATERIALIZED (...)`). Returns `WriteCte` when wrapping a DML statement (`Insert`/`Update`/`Delete`/`Merge`), or `Cte` for read queries. ### `recursive_cte` {#recursive_cte} ```python title="signature" def recursive_cte( name: str, base: Select[object], step: Callable[[CteRef], Select[object]], *, union_all: bool = True, columns: Sequence[str] = (), search: tuple[SearchOrder, Sequence[str], str] | None = None, cycle: tuple[Sequence[str], str, str] | None = None, ) -> Cte: ... ``` Defines a `WITH RECURSIVE` CTE with optional SQL-standard `SEARCH DEPTH/BREADTH FIRST` and `CYCLE` detection clauses. See [Hierarchy Regions & CTEs](../story/12_hierarchy_regions_cte.md). ### `Cte` {#Cte} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Cte(_CteColMixin): name: str columns: tuple[str, ...] = () recursive: bool = False materialized: bool | None = None base: Select[object] | SetOpBase recursive_step: tuple[bool, Select[object]] | None = None search: tuple[SearchOrder, tuple[str, ...], str] | None = None cycle: tuple[tuple[str, ...], str, str] | None = None ``` Read-only CTE definition. Access columns via `my_cte.c.col_name` or `my_cte["col_name"]`. ### `WriteCte` {#WriteCte} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class WriteCte(_CteColMixin): name: str columns: tuple[str, ...] = () materialized: bool | None = None base: Executable[object] ``` Data-modifying CTE wrapping an `Insert`, `Update`, `Delete`, or `Merge` with `RETURNING`. ### `CteRef` {#CteRef} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CteRef(_CteColMixin): name: str ``` Self-reference handle passed into the `step` callback of `recursive_cte(...)`. ### `CteTarget` {#CteTarget} ```python title="signature" class CteTarget(Protocol): @property def __pg_is_cte__(self) -> bool: ... @property def name(self) -> str: ... def col(self, col_name: str) -> Expr: ... ``` Protocol satisfied by `Cte`, `WriteCte`, and `CteRef` when used as a `FROM` or `JOIN` target. ### `with_` {#with_} ```python title="signature" @overload def with_[RetT](first: Cte, *rest: Cte, query: Select[RetT] | SetOp[RetT]) -> WithQuery[RetT]: ... @overload def with_[RetT]( first: Cte | WriteCte, *rest: Cte | WriteCte, query: Executable[RetT] ) -> WriteWithQuery[RetT]: ... ``` Attaches one or more CTEs to a main query. Returns `WithQuery[RetT]` (a `ReadQuery`) when all CTEs and `query` are read-only, or `WriteWithQuery[RetT]` (an `Executable`) when any CTE or `query` writes. ### `WithQuery` {#WithQuery} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class WithQuery[RetT = ResultRow](_TaggableMixin, ReadQuery[RetT]): ... ``` Read-only `WITH ... SELECT ...` query accepted by `Pool`, `ReadPool`, `Transaction`, and `ReadTransaction`. ### `WriteWithQuery` {#WriteWithQuery} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class WriteWithQuery[RetT = ResultRow](_TaggableMixin, Executable[RetT]): ... ``` Data-modifying `WITH ...` query accepted by `Pool` and `Transaction` (statically rejected by `ReadPool` / `ReadTransaction`). ### `lateral` {#lateral} ```python title="signature" def lateral(subquery: SelectSubquery, *, alias: str) -> LateralSubquery: ... ``` Wraps a correlated `Select` as a `LATERAL (...) AS ` join source. ### `LateralSubquery` {#LateralSubquery} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class LateralSubquery: subquery: SelectSubquery alias: str ``` Correlated lateral subquery descriptor passed to `Select.join_lateral(...)`. ### `LateralJoinKind` {#LateralJoinKind} ```python title="signature" class LateralJoinKind(StrEnum): INNER = "inner" LEFT = "left" CROSS = "cross" ``` Join kind for `Select.join_lateral(...)` (`INNER JOIN LATERAL` or `LEFT JOIN LATERAL ... ON TRUE`). ### `lateral_jsonb` {#lateral_jsonb} ```python title="signature" def lateral_jsonb( parent: type[Table], child: type[Table], *, on: tuple[ColBase, ColBase], fields: Sequence[ColBase | tuple[str, str]], alias: str, parent_cols: Sequence[ColBase] | None = None, child_order_by: Sequence[OrderSpec] = (), ) -> LateralJsonb: ... ``` Builds a `LATERAL jsonb_to_recordset(...) AS (...)` set-returning join source. ### `LateralJsonb` {#LateralJsonb} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class LateralJsonb(_WhereOrderLimitMixin, ReadQuery[ResultRow]): ... ``` Descriptor for a `jsonb_to_recordset` lateral join. ### `JoinKind` {#JoinKind} ```python title="signature" class JoinKind(StrEnum): INNER = "inner" LEFT = "left" RIGHT = "right" FULL = "full" CROSS = "cross" ``` Join type accepted by `Select.join(..., kind=...)`. ### `RowLockWait` {#RowLockWait} ```python title="signature" class RowLockWait(StrEnum): WAIT = "wait" NOWAIT = "nowait" SKIP_LOCKED = "skip_locked" ``` Row-level lock wait policy for `Select.for_update(wait=...)` and `Select.for_share(wait=...)`. See [Transactions, Locks & Queues](../story/08_transactions_locks_queue.md). ### `union` {#union} ```python title="signature" def union[RetT](left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT]) -> SetOp[RetT]: ... ``` Combines two compatible queries with `UNION` (deduplicating rows). ### `union_all` {#union_all} ```python title="signature" def union_all[RetT]( left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT] ) -> SetOp[RetT]: ... ``` Combines two compatible queries with `UNION ALL`. ### `intersect` {#intersect} ```python title="signature" def intersect[RetT]( left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT] ) -> SetOp[RetT]: ... ``` Combines two compatible queries with `INTERSECT`. ### `except_` {#except_} ```python title="signature" def except_[RetT]( left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT] ) -> SetOp[RetT]: ... ``` Combines two compatible queries with `EXCEPT`. ### `SetOp` {#SetOp} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SetOp[RetT = ResultRow](SetOpBase, ReadQuery[RetT]): ... ``` Executable set-operation query (`UNION`, `UNION ALL`, `INTERSECT`, `EXCEPT`). ### `subquery` {#subquery} ```python title="signature" def subquery[RetT](sub: Select[RetT], *, pg_type: str | None = None) -> Expr[PgValue]: ... ``` Wraps a scalar `Select` as a parenthesized scalar subquery expression. ### `exists` {#exists} ```python title="signature" def exists[RetT](sub: Select[RetT]) -> Expr[bool]: ... ``` Emits `EXISTS ()`. ### `not_exists` {#not_exists} ```python title="signature" def not_exists[RetT](sub: Select[RetT]) -> Expr[bool]: ... ``` Emits `NOT EXISTS ()`. ### `in_subquery` {#in_subquery} ```python title="signature" def in_subquery[RetT](lhs: ColBase | ExprBase, sub: Select[RetT]) -> Expr[bool]: ... ``` Emits ` IN ()`. ### `not_in_subquery` {#not_in_subquery} ```python title="signature" def not_in_subquery[RetT](lhs: ColBase | ExprBase, sub: Select[RetT]) -> Expr[bool]: ... ``` Emits ` NOT IN ()`. --- ## Compilation, Preparation & Execution Contracts ### `compile` {#compile} ```python title="signature" def compile( stmt: Executable[object], *, search_path: str | None = None, ) -> CompiledQuery: ... ``` Compiles any `Executable` query or DML builder in Rust without a database connection and returns its canonical `CompiledQuery`. ### `CompiledQuery` {#CompiledQuery} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CompiledQuery: sql: str shape_hash: int param_types: tuple[str, ...] cacheable: bool requires_pg19: bool op_tag: str | None = None ``` Deterministic Rust compilation output containing canonical SQL, 64-bit `shape_hash`, PostgreSQL parameter type OIDs/names, and newer-server capability flag. ### `prepare` {#prepare} ```python title="signature" @overload def prepare[RetT]( stmt_or_fn: ReadQuery[RetT] | Callable[..., ReadQuery[RetT]], ) -> ReadPreparedQuery[RetT]: ... @overload def prepare[RetT]( stmt_or_fn: Executable[RetT] | Callable[..., Executable[RetT]], ) -> PreparedQuery[RetT]: ... ``` Pre-compiles a parameterized statement (using `param(...)` placeholders) once into a reusable `PreparedQuery[RetT]` (or `ReadPreparedQuery[RetT]`). See [Pipelining, Prepared & Streaming](../story/10_pipelining_prepared_stream.md). ### `PreparedQuery` {#PreparedQuery} ```python title="signature" class PreparedQuery[RetT]: @property def param_names(self) -> tuple[str, ...]: ... @property def sql(self) -> str: ... def bind(self, *args: PgValue, **kwargs: PgValue) -> BoundQuery[RetT]: ... ``` Pre-compiled statement ready to bind named `param(...)` arguments without re-running Python AST construction. ### `ReadPreparedQuery` {#ReadPreparedQuery} ```python title="signature" class ReadPreparedQuery[RetT](PreparedQuery[RetT]): def bind(self, *args: PgValue, **kwargs: PgValue) -> ReadBoundQuery[RetT]: ... ``` Read-only specialization of `PreparedQuery[RetT]` whose `.bind(...)` returns a `ReadBoundQuery[RetT]`. ### `BoundQuery` {#BoundQuery} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class BoundQuery[RetT](Executable[RetT]): ... ``` Executable statement pairing a `PreparedQuery[RetT]` with concrete parameter bindings. ### `ReadBoundQuery` {#ReadBoundQuery} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ReadBoundQuery[RetT](BoundQuery[RetT], ReadQuery[RetT]): ... ``` Read-only specialization of `BoundQuery[RetT]` accepted by `ReadPool` and `ReadTransaction`. ### `Executable` {#Executable} ```python title="signature" class Executable[RetT]: def pipe[R](self, fn: Callable[[Self], R]) -> R: ... ``` Base type for all executable statements (reads and writes) accepted by `Pool` and `Transaction`. ### `ReadQuery` {#ReadQuery} ```python title="signature" class ReadQuery[RetT](Executable[RetT]): ... ``` Base type for read-only queries (`Select`, `SetOp`, `WithQuery`, `ReadBoundQuery`) accepted by `ReadPool` and `ReadTransaction`. ### `ResultRow` {#ResultRow} ```python title="signature" type ResultRow = tuple[PgValue, ...] ``` Lightweight projected row returned by `.columns(...)`, `select_expr(...)`, and custom `RETURNING` projections. Supports both positional indexing and attribute/key access. ### `currval` {#currval} ```python title="signature" def currval(col: Col[int]) -> int: ... ``` References PostgreSQL `currval(pg_get_serial_sequence(...))` for an identity/serial column within a pipelined transaction. ### `CurrvalRef` {#CurrvalRef} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CurrvalRef: table: TableRef column: str ``` Descriptor returned by `currval(...)`. --- # Expressions & Functions Typed SQL expression builders, aggregates, grouping sets, window functions, PostgreSQL full-text search, and JSONB / SQL-JSON helpers. See [Analytics Revenue Report](../story/11_analytics_revenue_report.md), [Keyset Pagination & Plans](../story/09_keyset_pagination_plans.md), and [Column Types & DDL](../story/04_column_types_and_ddl.md). --- ## Core Expressions & Operators ### `Expr` {#Expr} ```python title="signature" class Expr[T = PgValue](ExprBase, _ExprOpsMixin[T], ValueExpr[T]): def alias(self, name: str) -> Self: ... def filter(self, predicate: Expr[bool]) -> Self: ... def within_group(self, *order_by: OrderSpec | _Orderable) -> Self: ... def over( self, *, partition_by: Sequence[ExprArg] = (), order_by: Sequence[OrderSpec] = (), frame: WindowFrame | None = None, ) -> Self: ... def in_any( self, values: Sequence[T] | ParamRef[Sequence[T]] | ParamRef[list[T]] | UntypedParamRef ) -> Expr[bool]: ... ``` Typed SQL expression node backed by `RustExpr`. Supports Python comparison (`==`, `!=`, `<`, `<=`, `>`, `>=`), arithmetic (`+`, `-`, `*`, `/`), boolean (`&`, `|`, `~`), aliasing (`.as_(...)`), ordering, and `.over(...)` window clauses. `.in_(...)` compiles to constant-shape `= ANY($1)`. ### `OrderSpec` {#OrderSpec} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class OrderSpec: column: str descending: bool = False nulls_first: bool = False nulls_last: bool = False table: str | None = None expr: RustExpr | None = None ``` Ordering specification produced by `.asc(...)` or `.desc(...)` on a `Col` or `Expr`, passed to `Select.order_by(...)`, `Index(...)`, or window/aggregate `order_by=`. ### `ParamRef` {#ParamRef} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ParamRef[T = PgValue](ParamRefBase, ValueExpr[T]): ... ``` Named typed parameter placeholder returned by `param(...)` for use with `prepare(...)`. ### `param` {#param} ```python title="signature" @overload def param[T](name: str, py_type: TypeForm[T], *, pg_type: str | None = None) -> ParamRef[T]: ... @overload def param(name: str, py_type: None = None, *, pg_type: str | None = None) -> UntypedParamRef: ... ``` Declares a named bind parameter placeholder for `prepare(...)`. ### `lit` {#lit} ```python title="signature" def lit[T: PgValue](value: T, pg_type: str | None = None) -> Expr[T]: ... ``` Wraps a Python value as a bound SQL expression parameter. ### `col_ref` {#col_ref} ```python title="signature" @overload def col_ref[R: PgValue](name: str, *, table: str | None = None, returns: type[R]) -> Expr[R]: ... @overload def col_ref(name: str, *, table: str | None = None, returns: None = None) -> Expr[PgValue]: ... ``` Constructs an explicit column reference expression (e.g., referencing a CTE or lateral alias column by name). ### `func` {#func} ```python title="signature" @overload def func[R: PgValue]( name: str, *args: ExprArg, pg_type: str | None = None, order_by: Sequence[OrderSpec] = (), returns: type[R], ) -> Expr[R]: ... @overload def func( name: str, *args: ExprArg, pg_type: str | None = None, order_by: Sequence[OrderSpec] = (), returns: None = None, ) -> Expr[PgValue]: ... ``` Dynamic namespace for calling arbitrary PostgreSQL SQL functions (e.g., `func.lower(Guest.email)`, `func.date_trunc("day", Booking.created_at)`). ### `cast` {#cast} ```python title="signature" @overload def cast[R: PgValue]( value: ColBase | ExprBase | PgValue, pg_type: str, *, returns: type[R] ) -> Expr[R]: ... @overload def cast( value: ColBase | ExprBase | PgValue, pg_type: str, *, returns: None = None ) -> Expr[PgValue]: ... ``` Emits `CAST( AS )`. ### `case` {#case} ```python title="signature" @overload def case[R: PgValue]( *whens: tuple[Expr[bool], TypedOperand[R]], else_: TypedOperand[R], pg_type: str | None = None ) -> Expr[R]: ... @overload def case[R: PgValue]( *whens: tuple[Expr[bool], TypedOperand[R]], else_: UnsetType = UNSET, pg_type: str | None = None ) -> Expr[R | None]: ... ``` Emits a SQL `CASE WHEN ... THEN ... ELSE ... END` expression. ### `extract` {#extract} ```python title="signature" def extract(field: ExtractField, source: ColBase | ExprBase | PgValue) -> Expr[Decimal]: ... ``` Emits `EXTRACT( FROM )`. ### `now` {#now} ```python title="signature" def now() -> ServerDefaultExpr[datetime]: ... ``` Emits PostgreSQL `now()` returning `TIMESTAMPTZ`. ### `tuple_` {#tuple_} ```python title="signature" @overload def tuple_[T1: PgValue, T2: PgValue]( c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], / ) -> Expr[tuple[T1, T2]]: ... @overload def tuple_[T1: PgValue, T2: PgValue, T3: PgValue]( c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], c3: Col[T3] | Expr[T3], / ) -> Expr[tuple[T1, T2, T3]]: ... @overload def tuple_[T1: PgValue, T2: PgValue, T3: PgValue, T4: PgValue]( c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], c3: Col[T3] | Expr[T3], c4: Col[T4] | Expr[T4], /, ) -> Expr[tuple[T1, T2, T3, T4]]: ... @overload def tuple_( first: ColBase | ExprBase, second: ColBase | ExprBase, *rest: ColBase | ExprBase ) -> Expr[tuple[PgValue, ...]]: ... ``` Builds a SQL row-value tuple `(a, b, ...)` for keyset pagination comparisons (`tuple_(Booking.created_at, Booking.booking_id) > (last_ts, last_id)`). See [Keyset Pagination & Plans](../story/09_keyset_pagination_plans.md). ### `and_` {#and_} ```python title="signature" @overload def and_(first: Expr[bool], /, *rest: Expr[bool] | None) -> Expr[bool]: ... @overload def and_(*exprs: Expr[bool] | None) -> Expr[bool] | None: ... ``` Combines boolean expressions with SQL `AND`. ### `or_` {#or_} ```python title="signature" @overload def or_(first: Expr[bool], /, *rest: Expr[bool] | None) -> Expr[bool]: ... @overload def or_(*exprs: Expr[bool] | None) -> Expr[bool] | None: ... ``` Combines boolean expressions with SQL `OR`. ### `coalesce` {#coalesce} ```python title="signature" def coalesce[T: PgValue]( first: ValueExpr[T | None] | ValueExpr[T], *rest: TypedOperand[T] ) -> Expr[T]: ... ``` Emits `COALESCE(arg1, arg2, ...)`. ### `nullif` {#nullif} ```python title="signature" def nullif[T: PgValue](a: ValueExpr[T] | ValueExpr[T | None], b: TypedOperand[T]) -> Expr[T | None]: ... ``` Emits `NULLIF(a, b)`. ### `greatest` {#greatest} ```python title="signature" def greatest[T: PgValue](first: ValueExpr[T] | T, *rest: TypedOperand[T]) -> Expr[T]: ... ``` Emits `GREATEST(arg1, arg2, ...)`. ### `least` {#least} ```python title="signature" def least[T: PgValue](first: ValueExpr[T] | T, *rest: TypedOperand[T]) -> Expr[T]: ... ``` Emits `LEAST(arg1, arg2, ...)`. --- ## Aggregates & Grouping Sets ### `count` {#count} ```python title="signature" def count(col: ColBase | ExprBase | None = None, *, distinct: bool = False) -> Expr[int]: ... ``` Emits `count(*)` (when `col is None`) or `count([DISTINCT] ) [FILTER (WHERE )]`. ### `sum` {#sum} ```python title="signature" @overload def sum(col: Col[Decimal] | Expr[Decimal], *, distinct: bool = False) -> Expr[Decimal | None]: ... @overload def sum(col: Col[int] | Expr[int], *, distinct: bool = False) -> Expr[int | Decimal | None]: ... @overload def sum(col: Col[float] | Expr[float], *, distinct: bool = False) -> Expr[float | None]: ... @overload def sum(col: ColBase | ExprBase, *, distinct: bool = False) -> Expr[PgValue]: ... ``` Emits `sum([DISTINCT] )`. ### `avg` {#avg} ```python title="signature" def avg(col: ColBase | ExprBase, *, distinct: bool = False) -> Expr[Decimal | None]: ... ``` Emits `avg([DISTINCT] )`. ### `min` {#min} ```python title="signature" def min[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ... ``` Emits `min()`. ### `max` {#max} ```python title="signature" def max[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ... ``` Emits `max()`. ### `array_agg` {#array_agg} ```python title="signature" def array_agg[T: PgValue]( expr: ValueExpr[T], *, distinct: bool = False, order_by: Sequence[OrderSpec] = (), filter: Expr[bool] | None = None, ) -> Expr[list[T] | None]: ... ``` Emits `array_agg([DISTINCT] [ORDER BY ...]) [FILTER (WHERE ...)]`. ### `string_agg` {#string_agg} ```python title="signature" def string_agg( expr: ValueExpr[str] | ValueExpr[str | None], sep: str | ValueExpr[str], *, distinct: bool = False, order_by: Sequence[OrderSpec] = (), filter: Expr[bool] | None = None, ) -> Expr[str | None]: ... ``` Emits `string_agg([DISTINCT] , [ORDER BY ...]) [FILTER (WHERE ...)]`. ### `jsonb_agg` {#jsonb_agg} ```python title="signature" def jsonb_agg( expr: ExprArg, *, distinct: bool = False, order_by: Sequence[OrderSpec] = (), filter: Expr[bool] | None = None, ) -> Expr[JsonValue | None]: ... ``` Emits `jsonb_agg([DISTINCT] [ORDER BY ...]) [FILTER (WHERE ...)]`. ### `bool_and` {#bool_and} ```python title="signature" def bool_and( expr: ValueExpr[bool] | ValueExpr[bool | None], *, filter: Expr[bool] | None = None ) -> Expr[bool | None]: ... ``` Emits `bool_and() [FILTER (WHERE ...)]`. ### `bool_or` {#bool_or} ```python title="signature" def bool_or( expr: ValueExpr[bool] | ValueExpr[bool | None], *, filter: Expr[bool] | None = None ) -> Expr[bool | None]: ... ``` Emits `bool_or() [FILTER (WHERE ...)]`. ### `percentile_cont` {#percentile_cont} ```python title="signature" def percentile_cont( fraction: float | ValueExpr[float], *, order_by: OrderSpec | ColBase | Sequence[OrderSpec | ColBase], ) -> Expr[float | None]: ... ``` Emits the ordered-set aggregate `percentile_cont() WITHIN GROUP (ORDER BY ...)`. ### `percentile_disc` {#percentile_disc} ```python title="signature" def percentile_disc[T: PgValue]( fraction: float | ValueExpr[float], *, order_by: OrderSpec | ColBase | Sequence[OrderSpec | ColBase], ) -> Expr[T | None]: ... ``` Emits the ordered-set aggregate `percentile_disc() WITHIN GROUP (ORDER BY ...)`. ### `rollup` {#rollup} ```python title="signature" def rollup(first: ColBase | ExprBase, *rest: ColBase | ExprBase) -> GroupBySpec: ... ``` Produces a `ROLLUP(...)` grouping specification for `Select.group_by(...)`. See [Analytics Revenue Report](../story/11_analytics_revenue_report.md). ### `cube` {#cube} ```python title="signature" def cube(first: ColBase | ExprBase, *rest: ColBase | ExprBase) -> GroupBySpec: ... ``` Produces a `CUBE(...)` grouping specification for `Select.group_by(...)`. ### `grouping_sets` {#grouping_sets} ```python title="signature" def grouping_sets(*sets: Sequence[ColBase | ExprBase]) -> GroupBySpec: ... ``` Produces a `GROUPING SETS ((...), ...)` specification for `Select.group_by(...)`. ### `grouping` {#grouping} ```python title="signature" def grouping(first: ColBase | ExprBase, *rest: ColBase | ExprBase) -> Expr[int]: ... ``` Emits PostgreSQL `GROUPING(...)` bitmask expression for distinguishing subtotal rows. ### `GroupBySpec` {#GroupBySpec} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class GroupBySpec: kind: GroupByKind sets: tuple[tuple[RustExpr, ...], ...] ``` Structured grouping-set specification returned by `rollup(...)`, `cube(...)`, and `grouping_sets(...)`. --- ## Window Functions & Frames ### `row_number` {#row_number} ```python title="signature" def row_number() -> Expr[int]: ... ``` Emits `row_number()`. Chain with `.over(...)`. ### `rank` {#rank} ```python title="signature" def rank() -> Expr[int]: ... ``` Emits `rank()`. Chain with `.over(...)`. ### `dense_rank` {#dense_rank} ```python title="signature" def dense_rank() -> Expr[int]: ... ``` Emits `dense_rank()`. Chain with `.over(...)`. ### `lag` {#lag} ```python title="signature" def lag[T: PgValue]( col: ValueExpr[T], offset: int | None = None, default: TypedOperand[T] | None = None, ) -> Expr[T | None]: ... ``` Emits `lag(, , )`. Chain with `.over(...)`. ### `lead` {#lead} ```python title="signature" def lead[T: PgValue]( col: ValueExpr[T], offset: int | None = None, default: TypedOperand[T] | None = None, ) -> Expr[T | None]: ... ``` Emits `lead(, , )`. Chain with `.over(...)`. ### `first_value` {#first_value} ```python title="signature" def first_value[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ... ``` Emits `first_value()`. Chain with `.over(...)`. ### `last_value` {#last_value} ```python title="signature" def last_value[T: PgValue](col: ValueExpr[T]) -> Expr[T | None]: ... ``` Emits `last_value()`. Chain with `.over(...)`. ### `WindowFrame` {#WindowFrame} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class WindowFrame: units: FrameUnits = FrameUnits.ROWS start: FrameBound = FrameBoundKind.UNBOUNDED_PRECEDING end: FrameBound | None = FrameBoundKind.CURRENT_ROW ``` Window frame clause passed to `Expr.over(frame=...)`. ### `FrameUnits` {#FrameUnits} ```python title="signature" class FrameUnits(StrEnum): ROWS = "rows" RANGE = "range" GROUPS = "groups" ``` Window frame mode (`ROWS`, `RANGE`, or `GROUPS`). ### `FrameBound` {#FrameBound} ```python title="signature" type FrameBound = FrameBoundKind | tuple[int, FrameOffsetDir] ``` Start or end boundary of a `WindowFrame`. ### `rows_between` {#rows_between} ```python title="signature" def rows_between(start: FrameBound, end: FrameBound | None = None) -> WindowFrame: ... ``` Constructs a `ROWS BETWEEN AND ` window frame. ### `range_between` {#range_between} ```python title="signature" def range_between(start: FrameBound, end: FrameBound | None = None) -> WindowFrame: ... ``` Constructs a `RANGE BETWEEN AND ` window frame. ### `groups_between` {#groups_between} ```python title="signature" def groups_between(start: FrameBound, end: FrameBound | None = None) -> WindowFrame: ... ``` Constructs a `GROUPS BETWEEN AND ` window frame. --- ## Full-Text Search ### `to_tsvector` {#to_tsvector} ```python title="signature" def to_tsvector(document: ExprArg, *, config: str | None = None) -> Expr[str]: ... ``` Emits `to_tsvector([, ])`. ### `to_tsquery` {#to_tsquery} ```python title="signature" def to_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ... ``` Emits `to_tsquery([, ])`. ### `plainto_tsquery` {#plainto_tsquery} ```python title="signature" def plainto_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ... ``` Emits `plainto_tsquery([, ])`. ### `phraseto_tsquery` {#phraseto_tsquery} ```python title="signature" def phraseto_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ... ``` Emits `phraseto_tsquery([, ])`. ### `websearch_to_tsquery` {#websearch_to_tsquery} ```python title="signature" def websearch_to_tsquery(query: ExprArg, *, config: str | None = None) -> Expr[str]: ... ``` Emits `websearch_to_tsquery([, ])`. ### `ts_rank` {#ts_rank} ```python title="signature" def ts_rank(vector: ExprArg, query: ExprArg) -> Expr[float]: ... ``` Emits `ts_rank(, )`. ### `ts_rank_cd` {#ts_rank_cd} ```python title="signature" def ts_rank_cd(vector: ExprArg, query: ExprArg) -> Expr[float]: ... ``` Emits `ts_rank_cd(, )` (cover-density ranking). --- ## JSONB & SQL/JSON Helpers ### `jsonb_path_exists` {#jsonb_path_exists} ```python title="signature" def jsonb_path_exists( target: ExprArg, path: str | ExprArg, *, vars: Mapping[str, JsonValue] | ExprBase | None = None, silent: bool | Expr[bool] | None = None, ) -> Expr[bool]: ... ``` Emits `jsonb_path_exists(, [, [, ]])`. ### `jsonb_path_match` {#jsonb_path_match} ```python title="signature" def jsonb_path_match( target: ExprArg, path: str | ExprArg, *, vars: Mapping[str, JsonValue] | ExprBase | None = None, silent: bool | Expr[bool] | None = None, ) -> Expr[bool]: ... ``` Emits `jsonb_path_match(, [, [, ]])`. ### `jsonb_path_query_array` {#jsonb_path_query_array} ```python title="signature" def jsonb_path_query_array( target: ExprArg, path: str | ExprArg, *, vars: Mapping[str, JsonValue] | ExprBase | None = None, silent: bool | Expr[bool] | None = None, ) -> Expr[list[JsonValue]]: ... ``` Emits `jsonb_path_query_array(, [, [, ]])`. ### `jsonb_path_query_first` {#jsonb_path_query_first} ```python title="signature" def jsonb_path_query_first( target: ExprArg, path: str | ExprArg, *, vars: Mapping[str, JsonValue] | ExprBase | None = None, silent: bool | Expr[bool] | None = None, ) -> Expr[JsonValue | None]: ... ``` Emits `jsonb_path_query_first(, [, [, ]])`. ### `table_row` {#table_row} ```python title="signature" def table_row(target: TableRef) -> Expr[JsonObject]: ... ``` References a whole-row composite value (`
`) for use with `row_to_json(...)` or `to_jsonb(...)`. ### `row_to_json` {#row_to_json} ```python title="signature" def row_to_json(target: type[Table] | TableAlias | ExprArg) -> Expr[JsonObject]: ... ``` Emits `row_to_json()`. ### `to_jsonb` {#to_jsonb} ```python title="signature" def to_jsonb(target: type[Table] | TableAlias | ExprArg) -> Expr[JsonValue]: ... ``` Emits `to_jsonb()`. ### `json_object` {#json_object} ```python title="signature" def json_object(**fields: ExprArg) -> Expr[JsonObject]: ... ``` Emits SQL/JSON `json_build_object(k1, v1, ...)` from keyword pairs. --- # Runtime & Pool The `pgdorm` runtime executes compiled queries over a Tokio PostgreSQL v3 binary wire pool with 1-RTT pipelining, prepared statement caching, zero-copy Arrow streaming, and structured diagnostics. See [Transactions, Locks & Queues](../story/08_transactions_locks_queue.md), [Pipelining, Prepared & Streaming](../story/10_pipelining_prepared_stream.md), [Arrow & Polars Analytics](../story/16_arrow_polars_analytics.md), and [Web API & Telemetry](../story/18_web_api_and_telemetry.md). --- ## Pools & Connections ### `Pool` {#Pool} ```python title="signature" class Pool(_WriteExecutor, ReadPool): def read_only(self) -> ReadPool: ... async def create_schema(self, name: str, *, if_not_exists: bool = True) -> None: ... async def drop_schema( self, name: str, *, if_exists: bool = True, cascade: bool = False ) -> None: ... async def create_all(self, *tables: type[Table]) -> list[str]: ... async def simulate_scale( self, table: type[Table], *, relpages: int, reltuples: float, ) -> None: ... async def create_partition( self, parent: type[Table], *, name: str, for_values: str | None = None, default: bool = False, ) -> str: ... async def listen(self, channel: str, *extra_channels: str) -> AsyncGenerator[Listener]: ... def pipeline(self) -> AbstractAsyncContextManager[Pipeline]: ... @overload def transaction( self, *, isolation: IsolationLevel | None = None, read_only: Literal[True], deferrable: bool = False, local_settings: Mapping[str, str] | None = None, max_savepoints: int = 64, ) -> AbstractAsyncContextManager[ReadTransaction]: ... @overload def transaction( self, *, isolation: IsolationLevel | None = None, read_only: Literal[False] = False, deferrable: bool = False, local_settings: Mapping[str, str] | None = None, max_savepoints: int = 64, ) -> AbstractAsyncContextManager[Transaction]: ... @overload def transaction( self, *, isolation: IsolationLevel | None = None, read_only: bool, deferrable: bool = False, local_settings: Mapping[str, str] | None = None, max_savepoints: int = 64, ) -> AbstractAsyncContextManager[ReadTransaction]: ... @overload async def retry_transaction[R]( self, fn: Callable[[ReadTransaction], Awaitable[R]], *, max_attempts: int = 3, base_delay: float = 0.05, max_delay: float = 1.0, isolation: IsolationLevel | None = None, read_only: Literal[True], deferrable: bool = False, local_settings: Mapping[str, str] | None = None, max_savepoints: int = 64, ) -> R: ... @overload async def retry_transaction[R]( self, fn: Callable[[Transaction], Awaitable[R]], *, max_attempts: int = 3, base_delay: float = 0.05, max_delay: float = 1.0, isolation: IsolationLevel | None = None, read_only: Literal[False] = False, deferrable: bool = False, local_settings: Mapping[str, str] | None = None, max_savepoints: int = 64, ) -> R: ... ``` Async PostgreSQL connection pool backed by Tokio. Supports `async with await Pool.connect(...) as pool:`. - **`pool_mode="transaction"`**: Enables PgBouncer transaction-pooling hygiene (omits startup `options`, injects `set_config('search_path', ..., true)` inside transactions, rejects `on_commit="delete_rows"`). - **`one` / `one_or_none`**: Raise `NoResultError` (for `one`) or `MultipleResultsError` (for both). - **`retry_transaction`**: Retries `RetryablePgError` (`40001`, `40P01`) with exponential backoff up to `max_attempts`. ### `ReadPool` {#ReadPool} ```python title="signature" class ReadPool(_ReadExecutor): @classmethod async def connect( cls, dsn: str, *, max_size: int = 8, search_path: str | Sequence[str] | None = None, pool_mode: PoolMode = PoolMode.DIRECT, prepared_statements: bool = True, prepare_threshold: int = 1, acquire_timeout: float | None = 30.0, max_waiting: int | None = None, max_queries: int | None = None, max_lifetime: float | None = None, idle_timeout: float | None = None, test_before_acquire: bool = False, application_name: str | None = None, after_connect: Callable[[Connection], Awaitable[None]] | None = None, telemetry: TelemetryHook | None = None, password: str | Callable[[], str | Awaitable[str]] | None = None, ) -> Self: ... def set_telemetry(self, hook: TelemetryHook | None) -> None: ... def stats(self) -> PoolStats: ... @property def server_version(self) -> str: ... @property def server_version_num(self) -> int: ... @property def is_pg19(self) -> bool: ... @property def tls_active(self) -> bool: ... @property def channel_binding(self) -> bool: ... @property def pool_mode(self) -> PoolMode: ... @property def prepared_statements(self) -> bool: ... def drain(self) -> None: ... async def close(self) -> None: ... async def explain( self, stmt: Executable[object], *, disable_seqscan: bool = True, analyze: bool = False, buffers: bool = False, ) -> ExplainPlan: ... def read_transaction( self, *, isolation: IsolationLevel | None = None, deferrable: bool = False, local_settings: Mapping[str, str] | None = None, ) -> AbstractAsyncContextManager[ReadTransaction]: ... async def split_load[ParentT: Table]( self, parent_stmt: Select[ParentT], *, relations: Sequence[SplitRelationProto], dedup: bool = True, ) -> SplitResult[ParentT]: ... async def trace(self) -> AsyncGenerator[Trace]: ... ``` Read-only view returned by `Pool.read_only()`. Statically restricts execution to `ReadQuery[RetT]` statements (type checkers reject `Insert`, `Update`, `Delete`, and `Merge`). ### `PoolMode` {#PoolMode} ```python title="signature" class PoolMode(StrEnum): DIRECT = "direct" TRANSACTION = "transaction" ``` Connection pooling mode: `"direct"` (default, direct PostgreSQL or session pooler) or `"transaction"` (PgBouncer / Supavisor transaction pooling). See [Cloud Postgres](../guide/cloud-postgres.md). ### `PoolStats` {#PoolStats} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class PoolStats: max_size: int connections_idle: int connections_in_use: int connections_opened: int connections_closed: int queries_executed: int rtts_total: int prepared_hits: int prepared_misses: int errors_total: int acquire_wait_us_total: int ``` Point-in-time snapshot of pool capacity, active/idle connections, waiter queue depth, and prepared statement cache size returned by `Pool.stats()`. ### `Connection` {#Connection} ```python title="signature" class Connection: async def all[RetT](self, stmt: Executable[RetT]) -> list[RetT]: ... async def execute(self, stmt: Executable[object]) -> int: ... async def set_config(self, setting: str, value: str) -> None: ... ``` Dedicated session wrapper passed to `Pool.connect(..., after_connect=...)` for per-connection initialization. --- ## Transactions & Pipelining ### `Transaction` {#Transaction} ```python title="signature" class Transaction(_WriteExecutor, ReadTransaction): def on_commit(self, callback: Callable[[], object]) -> None: ... async def advisory_xact_lock(self, key: str) -> None: ... @overload async def stage[T: Table]( self, table: type[T], rows: Sequence[T], *, index_on: Sequence[ColBase] = (), analyze: bool = True, by_name: Literal[False] = False, ) -> None: ... @overload async def stage[T: Table]( self, table: type[T], rows: Sequence[object], *, index_on: Sequence[ColBase] = (), analyze: bool = True, by_name: Literal[True], exclude: Sequence[ColBase | str] = (), ) -> None: ... def pipeline(self, *, commit: bool = False) -> AbstractAsyncContextManager[Pipeline]: ... async def savepoint(self) -> AsyncGenerator[str]: ... ``` Active read-write transaction context returned by `async with pool.transaction() as tx:`. Fuses lazy `BEGIN`, `local_settings` (`set_config(..., true)`), and `COMMIT` into minimal round-trips. Enforces `max_savepoints` (`SubtransactionLimitError`). ### `ReadTransaction` {#ReadTransaction} ```python title="signature" class ReadTransaction(_ReadExecutor): ... ``` Read-only transaction context returned by `pool.read_transaction(...)` or `pool.transaction(read_only=True)`. Statically restricts execution to `ReadQuery[RetT]`. ### `IsolationLevel` {#IsolationLevel} ```python title="signature" class IsolationLevel(StrEnum): READ_COMMITTED = "read_committed" REPEATABLE_READ = "repeatable_read" SERIALIZABLE = "serializable" ``` PostgreSQL transaction isolation level passed to `Pool.transaction(isolation=...)` and `Pool.retry_transaction(isolation=...)`. ### `Pipeline` {#Pipeline} ```python title="signature" class Pipeline: def add[RetT](self, stmt: Executable[RetT]) -> PipeHandle[RetT]: ... @overload def stage[T: Table]( self, table: type[T], rows: Sequence[T], *, index_on: Sequence[ColBase] = (), analyze: bool = True, by_name: Literal[False] = False, ) -> None: ... @overload def stage[T: Table]( self, table: type[T], rows: Sequence[object], *, index_on: Sequence[ColBase] = (), analyze: bool = True, by_name: Literal[True], exclude: Sequence[ColBase | str] = (), ) -> None: ... def wave(self, builder: Callable[[Pipeline], None]) -> Callable[[Pipeline], None]: ... async def flush(self) -> None: ... ``` Batches multiple statements into a single PostgreSQL v3 `Sync` flush (1 RTT). Statements queued via `pipe.add(...)` resolve when the `async with pool.pipeline() as pipe:` block exits. See [Pipelining, Prepared & Streaming](../story/10_pipelining_prepared_stream.md). ### `PipeHandle` {#PipeHandle} ```python title="signature" class PipeHandle[RetT]: def all(self) -> list[RetT]: ... def one(self) -> RetT: ... @property def rows_affected(self) -> int: ... ``` Future-like result handle returned by `Pipeline.add(...)`. Read its hydrated rows after the `pipeline()` context manager completes. --- ## Streaming, Arrow & Split Loading ### `RowStream` {#RowStream} ```python title="signature" class RowStream[RetT](AsyncIterator[list[RetT]]): async def aclose(self) -> None: ... ``` Async iterator returned by `Pool.stream(...)`, fetching rows in server-side portal batches (`batch_size`) without buffering the entire result set in memory. ### `ArrowStream` {#ArrowStream} ```python title="signature" class ArrowStream: @property @property def num_rows(self) -> int: ... @property def num_batches(self) -> int: ... @property def column_names(self) -> list[str]: ... ``` Zero-copy Arrow PyCapsule stream (`__arrow_c_stream__`) returned by `Pool.arrow(...)` and `Pool.copy_to_arrow(...)`. Consumed directly by Polars (`pl.from_arrow`), DuckDB, and PyArrow with minimal Python heap allocation. See [Arrow & Polars Analytics](../story/16_arrow_polars_analytics.md). ### `SplitResult` {#SplitResult} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SplitResult[ParentT: Table]: parents: tuple[ParentT, ...] children: Mapping[str, dict[PgValue, list[Table]]] ``` Structured result returned by `Pool.split_load(...)`, avoiding N+1 queries and Cartesian row explosion by executing parent and child queries in a single pipelined round-trip. See [Nested Hydration](../story/field_notes_nested_hydration.md). ### `SplitRelation` {#SplitRelation} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SplitRelation[ChildT: Table = Table]: name: str child_table: type[ChildT] child_fk: ColBase parent_key: ColBase where: Expr[bool] | None = None order_by: tuple[OrderSpec, ...] = () unfiltered_reason: str | None = None ``` Descriptor defining a child relation for `Pool.split_load(...)`. --- ## LISTEN / NOTIFY ### `Listener` {#Listener} ```python title="signature" class Listener: async def recv(self, *, timeout: float | None = None) -> Notification | None: ... async def listen(self, channel: str) -> None: ... async def unlisten(self, channel: str) -> None: ... async def close(self) -> None: ... ``` Dedicated PostgreSQL `LISTEN` session returned by `async with pool.listen(...) as listener:`. ### `Notification` {#Notification} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Notification: pid: int channel: str payload: str ``` Payload delivered by PostgreSQL `NOTIFY` and yielded by `Listener`. --- ## Explain, Trace, Telemetry & Doctor ### `ExplainPlan` {#ExplainPlan} ```python title="signature" class ExplainPlan: @property def node_types(self) -> list[str]: ... @property def index_names(self) -> list[str]: ... @property def total_cost(self) -> float: ... def summary(self) -> str: ... def assert_no_seq_scan(self, *, except_tables: Iterable[type[Table]] = ()) -> None: ... def assert_uses_index(self, index_name: str) -> None: ... def format_structure(self) -> str: ... ``` Parsed PostgreSQL `EXPLAIN (FORMAT JSON)` plan returned by `Pool.explain(...)`. See [Keyset Pagination & Plans](../story/09_keyset_pagination_plans.md). ### `PlanNode` {#PlanNode} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class PlanNode: node_type: str operation: str | None = None join_type: str | None = None relation_name: str | None = None index_name: str | None = None scan_direction: str | None = None parent_relationship: str | None = None total_cost: float = 0.0 sort_key: tuple[str, ...] = () index_cond: str | None = None recheck_cond: str | None = None hash_cond: str | None = None merge_cond: str | None = None join_filter: str | None = None filter: str | None = None plans: tuple[PlanNode, ...] = () ``` Typed node in an `ExplainPlan` tree. ### `Trace` {#Trace} ```python title="signature" class Trace: @property def events(self) -> list[WireFlushInfo]: ... @property def rtts(self) -> int: ... @property def statements(self) -> list[ExecutedStmtInfo]: ... @property def statement_count(self) -> int: ... @property def all_prepared_cache_hits(self) -> bool: ... def n_plus_1_patterns(self, *, threshold: int = 3) -> list[NPlusOnePattern]: ... def assert_no_n_plus_1(self, *, threshold: int = 3) -> None: ... def format_report(self) -> str: ... ``` Wire-level execution trace captured by `async with pool.trace() as tr:`. Records exact round-trip count (`tr.rtts`), wire flushes, and executed statements for deterministic 1-RTT assertions. ### `NPlusOnePattern` {#NPlusOnePattern} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class NPlusOnePattern: count: int shape_hash: int op_tag: str | None sql: str ``` Structured N+1 pattern entry returned by `Trace.n_plus_1_patterns()`. ### `WireFlushInfo` {#WireFlushInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class WireFlushInfo: wave_index: int statements: tuple[ExecutedStmtInfo, ...] sync_count: int bytes_sent: int bytes_recv: int wall_us: int pool_wait_us: int = 0 error_sqlstate: str | None = None error_message: str | None = None ``` Metadata for a single PostgreSQL wire `Sync` flush recorded inside `Trace.flushes`. ### `ExecutedStmtInfo` {#ExecutedStmtInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ExecutedStmtInfo: sql: str shape_hash: int prepared_hit: bool rows: int rows_affected: int op_tag: str | None = None ``` Per-statement execution metadata recorded inside `Trace.statements`. ### `TelemetryHook` {#TelemetryHook} ```python title="signature" class TelemetryHook(Protocol): def on_flush(self, event: WireFlushInfo) -> None: ... ``` Zero-dependency observability protocol passed to `Pool.connect(..., telemetry=...)`, `Pool.set_telemetry(...)`, or `pgdorm.runtime.set_telemetry(...)` (module-level default hook). See [Web API & Telemetry](../story/18_web_api_and_telemetry.md). ### `doctor` {#doctor} ```python title="signature" async def doctor(pool: ReadPool, *, write_probe: bool = False) -> DoctorReport: ... ``` Runs non-destructive PostgreSQL readiness checks against `pool` (server version, TLS, SCRAM channel binding, pooler compatibility, `search_path`, and an optional `write_probe=True` round-trip). Returns a `DoctorReport`. ### `DoctorReport` {#DoctorReport} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DoctorReport: server_version: str server_version_num: int pool_mode: PoolMode tls_active: bool channel_binding: bool checks: tuple[DoctorCheck, ...] recommended_connect_snippet: str ``` Structured diagnostic report returned by `doctor(...)`. ### `DoctorCheck` {#DoctorCheck} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DoctorCheck: name: str status: CheckStatus detail: str remediation: str | None = None ``` Individual check result inside `DoctorReport.checks`. ### `CheckStatus` {#CheckStatus} ```python title="signature" class CheckStatus(StrEnum): PASS = "pass" WARN = "warn" FAIL = "fail" SKIP = "skip" ``` Outcome status of a `DoctorCheck`. ### `DoctorCheckDict` {#DoctorCheckDict} ```python title="signature" class DoctorCheckDict(TypedDict): name: str status: CheckStatus detail: str remediation: str | None ``` Typed JSON dictionary shape returned by `DoctorCheck.to_dict()`. ### `DoctorReportDict` {#DoctorReportDict} ```python title="signature" class DoctorReportDict(TypedDict): ok: bool server_version: str server_version_num: int pool_mode: PoolMode tls_active: bool channel_binding: bool checks: list[DoctorCheckDict] recommended_connect_snippet: str ``` Typed JSON dictionary shape returned by `DoctorReport.to_dict()`. --- # Errors & Linters `pgdorm` separates client-side build/lint errors from server-side PostgreSQL protocol errors, mapping PostgreSQL SQLSTATE codes directly onto typed Python exception classes in the Rust wire layer. See [Transactions, Locks & Queues](../story/08_transactions_locks_queue.md) for retry loops with `RetryablePgError` and `OptimisticLockError`, and [Joins & Folios](../story/05_joins_and_folios.md) for `JoinLintError`. ## Master SQLSTATE & Retryability Matrix | Exception | Base Class | PostgreSQL SQLSTATE(s) | Retryable? | | :--- | :--- | :--- | :--- | | `UniqueViolationError` | `IntegrityError` | `23505` | No | | `ForeignKeyViolationError` | `IntegrityError` | `23503` | No | | `NotNullViolationError` | `IntegrityError` | `23502` | No | | `CheckViolationError` | `IntegrityError` | `23514` | No | | `ExclusionViolationError` | `IntegrityError` | `23P01` | No | | `RestrictViolationError` | `IntegrityError` | `23001` | No | | `IntegrityError` | `PostgresError` | `23***` (other class 23) | No | | `RetryablePgError` | `PostgresError` | `40001` (serialization failure), `40P01` (deadlock detected) | **Yes** (`Pool.retry_transaction`) | | `LockNotAvailableError` | `PostgresError` | `55P03` | Application-dependent | | `QueryCanceledError` | `PostgresError` | `57014` | Application-dependent | | `ReadOnlyTransactionError` | `PostgresError` | `25006` | No | | `InsufficientPrivilegeError` | `PostgresError` | `42501` | No | | `AdminShutdownError` | `PostgresError` | `57P01`, `57P02`, `57P03` | Reconnect / retry | | `TooManyRequestsError` | `PostgresError` | `53300` (too many connections) | Backoff & retry | | `SubtransactionLimitError` | `PostgresError` | Client/runtime savepoint guard (`max_savepoints`) | No | --- ## Client & Linter Errors ### `PgdormError` {#PgdormError} ```python title="signature" class PgdormError(Exception): ... ``` Base class for all client-side `pgdorm` exceptions (schema linting, query building, join linting, unsafe DML guards, result cardinality, and optimistic locking). ### `SchemaLintError` {#SchemaLintError} ```python title="signature" class SchemaLintError(PgdormError, ValueError): ... ``` Raised when a `Table` or `TypeTable` definition violates `pgdorm` schema invariants: explicit table name overrides, missing own-PK (`_id`), `TypeTable` naming/code rules, duplicate physical tables/indexes/constraints across a schema set, or string discriminators. See [Column Types & DDL](../story/04_column_types_and_ddl.md). ### `JoinLintError` {#JoinLintError} ```python title="signature" class JoinLintError(QueryBuildError): ... ``` Raised during `Select.join(...)` when a join is ambiguous (multiple FKs between tables without an explicit `on=`), violates `require_using=True`, or traverses an unindexed FK without `.allow_seq_scan(reason=...)`. See [Joins & Folios](../story/05_joins_and_folios.md). ### `QueryBuildError` {#QueryBuildError} ```python title="signature" class QueryBuildError(PgdormError, ValueError): ... ``` Raised when a query or DML builder is misconfigured (e.g., invalid projection, mismatched set-op arity, invalid `RETURNING` target, or a feature requested against a server version that lacks it). ### `UnsafeDmlError` {#UnsafeDmlError} ```python title="signature" class UnsafeDmlError(QueryBuildError): ... ``` Raised when compiling or executing an `update(...)` or `delete(...)` without a `.where(...)` clause unless `.allow_full_table(reason=...)` was explicitly declared. See [Patch & Returning](../story/02_patch_and_returning.md). ### `NoResultError` {#NoResultError} ```python title="signature" class NoResultError(PgdormError, LookupError): ... ``` Raised by `Pool.one(...)`, `Transaction.one(...)`, and `Pool.json_one(...)` when the query returns zero rows. ### `MultipleResultsError` {#MultipleResultsError} ```python title="signature" class MultipleResultsError(PgdormError, LookupError): ... ``` Raised by `.one(...)`, `.one_or_none(...)`, and `.json_one(...)` when the query returns more than one row. ### `OptimisticLockError` {#OptimisticLockError} ```python title="signature" class OptimisticLockError(PgdormError, RuntimeError): ... ``` Raised by `Pool.update_versioned(...)` (or `Transaction.update_versioned(...)`) when the row's `xmin` or version column no longer matches, indicating a concurrent modification. See [Transactions, Locks & Queues](../story/08_transactions_locks_queue.md). --- ## PostgreSQL Wire & SQLSTATE Errors ### `PostgresError` {#PostgresError} ```python title="signature" class PostgresError(RuntimeError): ... ``` Base exception for all errors returned by PostgreSQL over the v3 wire protocol. Exposes structured diagnostic fields (`sqlstate`, `message`, `detail`, `hint`, `constraint`, `table`, `column`) parsed from the `ErrorResponse` message. ### `IntegrityError` {#IntegrityError} ```python title="signature" class IntegrityError(PostgresError): ... ``` Base class for PostgreSQL class `23` integrity constraint violations. ### `UniqueViolationError` {#UniqueViolationError} ```python title="signature" class UniqueViolationError(IntegrityError): ... ``` PostgreSQL SQLSTATE `23505` (`unique_violation`). Raised when an `INSERT`, `UPDATE`, or `MERGE` violates a unique index or primary key constraint. ### `ForeignKeyViolationError` {#ForeignKeyViolationError} ```python title="signature" class ForeignKeyViolationError(IntegrityError): ... ``` PostgreSQL SQLSTATE `23503` (`foreign_key_violation`). Raised when a referenced parent key does not exist or a referenced row cannot be deleted/updated. ### `NotNullViolationError` {#NotNullViolationError} ```python title="signature" class NotNullViolationError(IntegrityError): ... ``` PostgreSQL SQLSTATE `23502` (`not_null_violation`). Raised when a `NOT NULL` column receives `NULL`. ### `CheckViolationError` {#CheckViolationError} ```python title="signature" class CheckViolationError(IntegrityError): ... ``` PostgreSQL SQLSTATE `23514` (`check_violation`). Raised when a row fails a `CHECK` constraint. ### `ExclusionViolationError` {#ExclusionViolationError} ```python title="signature" class ExclusionViolationError(IntegrityError): ... ``` PostgreSQL SQLSTATE `23P01` (`exclusion_violation`). Raised when a row conflicts with an `EXCLUDE` constraint (such as `TemporalPrimaryKey` or `TemporalUnique` overlapping ranges). See [Temporal Bookings](../story/06_temporal_bookings.md). ### `RestrictViolationError` {#RestrictViolationError} ```python title="signature" class RestrictViolationError(IntegrityError): ... ``` PostgreSQL SQLSTATE `23001` (`restrict_violation`). Raised when a `RESTRICT` referential action prevents a delete or update. ### `RetryablePgError` {#RetryablePgError} ```python title="signature" class RetryablePgError(PostgresError): ... ``` PostgreSQL SQLSTATE `40001` (`serialization_failure`) or `40P01` (`deadlock_detected`). Automatically caught and retried with exponential backoff by `Pool.retry_transaction(...)`. See [Transactions, Locks & Queues](../story/08_transactions_locks_queue.md). ### `LockNotAvailableError` {#LockNotAvailableError} ```python title="signature" class LockNotAvailableError(PostgresError): ... ``` PostgreSQL SQLSTATE `55P03` (`lock_not_available`). Raised when a `FOR UPDATE NOWAIT` or `lock_timeout` expires before acquiring a lock. ### `QueryCanceledError` {#QueryCanceledError} ```python title="signature" class QueryCanceledError(PostgresError): ... ``` PostgreSQL SQLSTATE `57014` (`query_canceled`). Raised when a statement is canceled by `statement_timeout`, `.timeout_ms(...)`, or `pg_cancel_backend`. ### `ReadOnlyTransactionError` {#ReadOnlyTransactionError} ```python title="signature" class ReadOnlyTransactionError(PostgresError): ... ``` PostgreSQL SQLSTATE `25006` (`read_only_sql_transaction`). Raised when a write statement executes inside a `READ ONLY` transaction or against a read-only replica. ### `InsufficientPrivilegeError` {#InsufficientPrivilegeError} ```python title="signature" class InsufficientPrivilegeError(PostgresError): ... ``` PostgreSQL SQLSTATE `42501` (`insufficient_privilege`). Raised when the connected role lacks privileges or fails an RLS policy check. See [Multitenancy & RLS](../story/14_multitenancy_rls.md). ### `AdminShutdownError` {#AdminShutdownError} ```python title="signature" class AdminShutdownError(PostgresError): ... ``` PostgreSQL SQLSTATE `57P01` (`admin_shutdown`), `57P02` (`crash_shutdown`), or `57P03` (`cannot_connect_now`). Indicates server shutdown or restart. ### `TooManyRequestsError` {#TooManyRequestsError} ```python title="signature" class TooManyRequestsError(RuntimeError): ... ``` PostgreSQL SQLSTATE `53300` (`too_many_connections`) or pool admission limit exhaustion (`max_waiting`). ### `SubtransactionLimitError` {#SubtransactionLimitError} ```python title="signature" class SubtransactionLimitError(RuntimeError): ... ``` Raised when a transaction exceeds `max_savepoints` (default `64`), protecting PostgreSQL from subtransaction overflow (`SubtransControlLock` contention). --- # Migrations & Assimilation Reference Complete API reference for all 172 public exports of `pgdorm.migrate` -- online PostgreSQL schema migrations, catalog introspection, AST diffing, lock-timeout guards, and legacy schema assimilation. For conceptual walkthroughs and operational playbooks, see **[The Renovations -- Migrations Story](../migrations/index.md)** (8 live-verified chapters), [Online Migrations (Launch Day)](../story/19_online_migrations.md), [Schema Assimilation](../assimilation/index.md), and [Library Authors](../guide/library-authors.md). ## Execution & Lifecycle ### `apply_ddl` {#apply_ddl} ```python title="signature" async def apply_ddl( conn: Pool | Transaction, *ops: MigrationOp, schema: str | None = None, online: bool = True, ) -> MigrationPlan: ... ``` Compile and execute typed `MigrationOp`s directly without writing to the ledger. ### `baseline_schema` {#baseline_schema} ```python title="signature" async def baseline_schema( pool: Pool, tables: Sequence[type[Table]] = (), *, schema: str | None = None, version: str = "0000_baseline", name: str = "baseline", ignore_tables: frozenset[str] = frozenset(), ) -> MigrationRecord: ... ``` Adopt an existing schema (e.g. from `create_all()`) into `_pgdorm.migration`. ### `check_drift` {#check_drift} ```python title="signature" async def check_drift( pool: Pool, *, schema: str | None = None, tables: Sequence[type[Table]] = (), ignore_tables: frozenset[str] = frozenset(), ) -> DriftReport: ... ``` Compare last `_pgdorm.migration` snapshot against live `pg_catalog` state. ### `cli_main` {#cli_main} ```python title="signature" def main(argv: Sequence[str] | None = None) -> int: ... ``` Public `cli_main` export from `pgdorm.migrate`. ### `ensure_pgdorm_schema` {#ensure_pgdorm_schema} ```python title="signature" async def ensure_pgdorm_schema(pool: Pool) -> None: ... ``` Self-hosted bootstrap & self-migration of the internal `_pgdorm` schema. ### `execute_step` {#execute_step} ```python title="signature" async def execute_step(conn: Pool | Transaction, step: MigrationStep) -> None: ... ``` Execute one compiler-produced `MigrationStep` (sealed Rust DDL, binary query, or Python). ### `migration_events` {#migration_events} ```python title="signature" async def migration_events( pool: Pool, *, schema: str | None = None, migration_id: int | None = None, ) -> list[MigrationEventRecord]: ... ``` Return `_pgdorm.migration_event` rows as hydrated `MigrationEventRecord`s. ### `migration_history` {#migration_history} ```python title="signature" async def migration_history(pool: Pool, *, schema: str | None = None) -> list[MigrationRecord]: ... ``` Return all `_pgdorm.migration` rows for `schema` as hydrated `MigrationRecord`s. ### `migration_steps` {#migration_steps} ```python title="signature" async def migration_steps( pool: Pool, *, schema: str | None = None, migration_id: int | None = None, ) -> list[MigrationStepRecord]: ... ``` Return `_pgdorm.migration_step` rows as hydrated `MigrationStepRecord`s. ### `plan_migration` {#plan_migration} ```python title="signature" async def plan_migration( pool: Pool, tables: Sequence[type[Table]], *, schema: str | None = None, name: str = "sync", version: str | None = None, online: bool = True, ignore_tables: frozenset[str] = frozenset(), ) -> MigrationPlan: ... ``` Dry-run diff of `tables` against live `pg_catalog` and compile online steps. ### `run_cli` {#run_cli} ```python title="signature" async def run_cli(argv: Sequence[str]) -> int: ... ``` Public `run_cli` export from `pgdorm.migrate`. ### `sync_schema` {#sync_schema} ```python title="signature" async def sync_schema( pool: Pool, tables: Sequence[type[Table]], *, schema: str | None = None, name: str = "sync", version: str | None = None, online: bool = True, lock_timeout: str = "2s", statement_timeout: str = "30s", lock_retries: int = 3, lock_retry_delay: float = 0.2, allow_destructive: bool = False, allow_breaking: bool = False, allow_drift: bool = False, lease_seconds: int = 300, ignore_tables: frozenset[str] = frozenset(), ) -> MigrationRecord | None: ... ``` Mode A: zero-file declarative sync returning the persisted `_pgdorm.migration` record. ### `upgrade_schema` {#upgrade_schema} ```python title="signature" async def upgrade_schema( pool: Pool, migrations: Sequence[Migration], *, schema: str | None = None, tables: Sequence[type[Table]] = (), online: bool = True, lock_timeout: str = "2s", statement_timeout: str = "30s", lock_retries: int = 3, lock_retry_delay: float = 0.2, allow_destructive: bool = False, allow_breaking: bool = False, verify_checksums: bool = True, lease_seconds: int = 300, ignore_tables: frozenset[str] = frozenset(), ) -> list[MigrationRecord]: ... ``` Mode B: apply ordered `pg.Migration` values with checksum & baseline verification. ## Planning, Drift & Snapshots ### `LEGACY_MIGRATION_TABLES` {#LEGACY_MIGRATION_TABLES} ```python title="signature" LEGACY_MIGRATION_TABLES: frozenset[str] = frozenset( { "alembic_version", "ar_internal_metadata", "django_migrations", "flyway_schema_history", "knex_migrations", "knex_migrations_lock", "_prisma_migrations", "schema_migrations", "spatial_ref_sys", } ) ``` Build an immutable unordered collection of unique elements. ### `ONBOARDING_RULES` {#ONBOARDING_RULES} ```python title="signature" ONBOARDING_RULES: tuple[OnboardingRule, ...] = ( OnboardingRule( code="TABLE_NAME_NON_SNAKE", category=RuleCategory.NAMING, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.MIGRATABLE, title="Non-snake_case or mixed-case table name", summary="Table name is not snake_case (`mode='bind'` requires singular snake_case).", action="Use `mode='assimilate'` so AdoptionMap renames it, or exclude via `ignore_tables`.", auto_fixable=True, doc_anchor="table-naming", ), OnboardingRule( code="TABLE_NAME_BUILTIN_COLLISION", category=RuleCategory.NAMING, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.MIGRATABLE, title="Table class name collides with a Python builtin", summary="PascalCase model name shadows a Python builtin (e.g. `ImportError`).", action="Use `mode='assimilate'` to map to `_record`, or exclude via `ignore_tables`.", auto_fixable=True, doc_anchor="table-naming", ), OnboardingRule( code="TABLE_NAME_PLURAL", category=RuleCategory.NAMING, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Plural table name", summary="Table name appears plural (`users`, `order_items`); pgdorm models are singular.", action="Rename table to singular snake_case via AdoptionMap.", auto_fixable=True, doc_anchor="table-naming", ), OnboardingRule( code="TABLE_NAME_RESERVED", category=RuleCategory.NAMING, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Python keyword or reserved identifier", summary="Table or column name collides with a Python keyword (`class`, `from`, `type`).", action="Rename table or column to a valid Python identifier via AdoptionMap.", auto_fixable=True, doc_anchor="table-naming", ), OnboardingRule( code="NON_TYPE_TABLE_ENDS_WITH_TYPE", category=RuleCategory.NAMING, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Regular entity table ending in `_type`", summary="The `_type` suffix is strictly reserved for `pg.TypeTable` enum lookup tables.", action="Either promote to `pg.TypeTable` or rename the entity table (e.g. `*_kind`).", auto_fixable=True, doc_anchor="type-table-namespace", ), OnboardingRule( code="PK_NAME_MISMATCH", category=RuleCategory.PRIMARY_KEY, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Primary key not named `_id`", summary="Permanent tables declare `_id` so joins auto-emit `JOIN ... USING`.", action="Rename single int/UUID PK to `_id`, or add surrogate PK.", auto_fixable=True, doc_anchor="primary-keys-and-serials", ), OnboardingRule( code="PK_COMPOSITE", category=RuleCategory.PRIMARY_KEY, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Composite primary key on permanent table", summary="Junction/entity tables use a surrogate `_id` PK + `pg.Unique(...)`.", action="Add surrogate `_id` PK and demote composite PK to `pg.Unique(...)`.", auto_fixable=True, doc_anchor="primary-keys-and-serials", ), OnboardingRule( code="PK_MISSING", category=RuleCategory.PRIMARY_KEY, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Table has no primary key", summary="Permanent tables require a `_id` primary key.", action="Add `_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`.", auto_fixable=True, doc_anchor="primary-keys-and-serials", ), OnboardingRule( code="SERIAL_COLUMN", category=RuleCategory.PRIMARY_KEY, severity=AuditSeverity.INFO, support_status=SupportStatus.SUPPORTED, title="Legacy SERIAL / sequence `nextval(...)` default", summary="SERIAL PKs auto-upgrade to `pg.identity()` (or `server_managed=True` in bind).", action="Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.", auto_fixable=True, doc_anchor="primary-keys-and-serials", ), OnboardingRule( code="TYPE_TABLE_CANDIDATE", category=RuleCategory.TYPE_TABLE, severity=AuditSeverity.INFO, support_status=SupportStatus.MIGRATABLE, title="Lookup table candidate for `pg.TypeTable`", summary="Referenced table has an int/UUID PK and unique short text column.", action="Review candidate; pass `--type-table
` or `as_type_table=True` to promote.", auto_fixable=True, doc_anchor="type-table-namespace", ), OnboardingRule( code="PG_NATIVE_ENUM", category=RuleCategory.TYPES, severity=AuditSeverity.INFO, support_status=SupportStatus.MIGRATABLE, title="PostgreSQL native `CREATE TYPE ... AS ENUM`", summary="Zero-DDL Bind binds PG enums via `CustomType` (no `CREATE TYPE` DDL).", action="Use `mode='assimilate'` to migrate PG enums into seeded `IntEnum` `pg.TypeTable`s.", auto_fixable=True, doc_anchor="column-types", ), OnboardingRule( code="CUSTOM_OR_EXTENSION_TYPE", category=RuleCategory.TYPES, severity=AuditSeverity.INFO, support_status=SupportStatus.SUPPORTED, title="Extension, domain, or custom column type", summary="Types like `citext`, `ltree`, `vector`, or PG domains bind via `pg.CustomType`.", action="Scaffold emits `Annotated[str, pg.CustomType(pg_type=...)]` for review.", auto_fixable=False, doc_anchor="column-types", ), OnboardingRule( code="TIMESTAMP_WITHOUT_TZ", category=RuleCategory.TYPES, severity=AuditSeverity.INFO, support_status=SupportStatus.SUPPORTED, title="`TIMESTAMP WITHOUT TIME ZONE` column", summary="Supported natively via `pg.Timestamp` (plain `datetime` maps to `TIMESTAMPTZ`).", action="Scaffold emits `pg.Col[pg.Timestamp]` automatically.", auto_fixable=False, doc_anchor="column-types", ), OnboardingRule( code="UNINDEXED_FK", category=RuleCategory.INDEXES, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Foreign key missing a leftmost-prefix B-tree index", summary="pgdorm enforces indexed FKs (`auto_index=True`) to avoid parent-delete seq scans.", action="Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.", auto_fixable=True, doc_anchor="constraints-and-indexes", ), OnboardingRule( code="UNVALIDATED_CONSTRAINT", category=RuleCategory.CONSTRAINTS, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Unvalidated `NOT VALID` constraint", summary="An existing CHECK, FK, or NOT NULL constraint is marked `NOT VALID` in PG.", action="Assimilation schedules online `VALIDATE CONSTRAINT` under SHARE UPDATE EXCLUSIVE.", auto_fixable=True, doc_anchor="constraints-and-indexes", ), OnboardingRule( code="INVALID_INDEX", category=RuleCategory.INDEXES, severity=AuditSeverity.MIGRATION_REQUIRED, support_status=SupportStatus.MIGRATABLE, title="Invalid leftover index (`indisvalid = false`)", summary="Likely left behind by an interrupted `CREATE INDEX CONCURRENTLY`.", action="Assimilation drops the invalid index concurrently before rebuilding.", auto_fixable=True, doc_anchor="constraints-and-indexes", ), OnboardingRule( code="FK_ON_UPDATE_ACTION", category=RuleCategory.CONSTRAINTS, severity=AuditSeverity.INFO, support_status=SupportStatus.UNMANAGED, title="Foreign key with non-default `ON UPDATE` action", summary="pgdorm models `ON DELETE` actions; `ON UPDATE` clauses are not currently modeled.", action="Matched by signature; review if PK updates rely on `ON UPDATE CASCADE`.", auto_fixable=False, doc_anchor="constraints-and-indexes", ), OnboardingRule( code="DEFERRABLE_CONSTRAINT", category=RuleCategory.CONSTRAINTS, severity=AuditSeverity.INFO, support_status=SupportStatus.UNMANAGED, title="Deferrable constraint (`DEFERRABLE`)", summary="Constraint deferrability attributes are not modeled on `pg.Table`.", action="Existing constraint is preserved when untouched; recreate manually if altered.", auto_fixable=False, doc_anchor="constraints-and-indexes", ), OnboardingRule( code="FUNCTION_OR_PROC_PRESENT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Functions and stored procedures (`pg_proc`)", summary="Stored routines are intentionally excluded from `pgdorm.migrate` versioning.", action="Preserved untouched; review any routine referencing renamed tables or columns.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="TRIGGER_PRESENT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="User triggers (`pg_trigger`)", summary="Triggers are intentionally left unmanaged by `pgdorm.migrate`.", action="Preserved untouched; verify trigger function bodies after table/column renames.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="VIEW_PRESENT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Views and materialized views", summary="Views are left unmanaged; column renames or type changes may require recreating.", action="Use the external-TX bridge (`psycopg3`) to recreate impacted views atomically.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="UNMANAGED_INDEX_PRESENT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Non-B-tree (GIN/GiST/BRIN/Hash), expression, or `INCLUDE` index", summary="Recorded in `TableSnapshot.unmanaged_indexes` and never dropped by diffing.", action="Preserved automatically; verify expression predicates if columns are renamed.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="RLS_POLICY_PRESENT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Existing Row-Level Security policies", summary="Existing RLS policies are preserved untouched during schema diffing.", action="Review policy expressions if referenced columns are renamed.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="EXTENSION_PRESENT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Installed PostgreSQL extension", summary="Extension installed inside the app schema; DROP SCHEMA ... CASCADE removes it.", action="pgdorm creates the extensions its models need (btree_gist) in `public`.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="LEGACY_MIGRATION_TABLE", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Third-party migration ledger table", summary="Detected legacy tool ledger (`alembic_version`, `django_migrations`, etc.).", action="Auto-added to `ignore_tables` so `pgdorm.migrate` leaves it untouched.", auto_fixable=True, doc_anchor="unmanaged-objects", ), OnboardingRule( code="PG_TABLE_INHERITANCE", category=RuleCategory.UNSUPPORTED, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.UNSUPPORTED, title="PostgreSQL classical `INHERITS` table inheritance", summary="Classical `INHERITS` is unsupported; pgdorm uses STI/CTI or partitioning.", action="Flatten or convert to declarative partitioning / CTI before assimilating.", auto_fixable=False, doc_anchor="unsupported-blockers", ), OnboardingRule( code="FOREIGN_TABLE_PRESENT", category=RuleCategory.UNSUPPORTED, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.UNSUPPORTED, title="Foreign table (`FDW` / `relkind = 'f'`)", summary="Foreign Data Wrapper tables cannot be migrated by `pgdorm.migrate`.", action="Exclude via `--ignore-table` or access via a separate `read_only=True` model.", auto_fixable=False, doc_anchor="unsupported-blockers", ), OnboardingRule( code="EXCLUSION_CONSTRAINT", category=RuleCategory.UNMANAGED, severity=AuditSeverity.UNMANAGED, support_status=SupportStatus.UNMANAGED, title="Exclusion constraint (`EXCLUDE USING ...`)", summary="Arbitrary `EXCLUDE USING` constraints are preserved untouched during diffing.", action="Preserved automatically; replace overlaps with `WITHOUT OVERLAPS` if desired.", auto_fixable=False, doc_anchor="unmanaged-objects", ), OnboardingRule( code="COMPOSITE_COLUMN_TYPE", category=RuleCategory.UNSUPPORTED, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.UNSUPPORTED, title="User-defined composite column type", summary="Columns using custom `CREATE TYPE ... AS (...)` row types are not supported.", action="Normalize into columns or `JSONB` before assimilating.", auto_fixable=False, doc_anchor="unsupported-blockers", ), OnboardingRule( code="MULTIDIM_ARRAY_TYPE", category=RuleCategory.UNSUPPORTED, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.UNSUPPORTED, title="Multi-dimensional PostgreSQL array column", summary="pgdorm binary array codecs support 1-D arrays (`T[]`), not `T[][]`.", action="Store nested arrays as `JSONB` or normalize into a child table.", auto_fixable=False, doc_anchor="unsupported-blockers", ), OnboardingRule( code="RESERVED_SCHEMA_PGDORM", category=RuleCategory.UNSUPPORTED, severity=AuditSeverity.BLOCKER, support_status=SupportStatus.UNSUPPORTED, title="Reserved `_pgdorm` schema", summary="The `_pgdorm` schema is reserved exclusively for pgdorm's internal ledger.", action="Move user tables into another schema (e.g. `public` or `app`).", auto_fixable=False, doc_anchor="unsupported-blockers", ), ) ``` Built-in immutable sequence. ### `OperationDependency` {#OperationDependency} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class OperationDependency: kind: str schema: str table: str name: str state: DependencyState ``` Typed resource state produced or required by a `MigrationOp`. ### `PGDORM_LEDGER_TABLES` {#PGDORM_LEDGER_TABLES} ```python title="signature" PGDORM_LEDGER_TABLES: tuple[type[Table], ...] = ( MigrationModeType, MigrationStatusType, MigrationEventType, HazardLevelType, LockModeType, Migration, MigrationStep, MigrationEvent, ) ``` Built-in immutable sequence. ### `PGDORM_SCHEMA` {#PGDORM_SCHEMA} ```python title="signature" PGDORM_SCHEMA = "_pgdorm" ``` str(object='') -> str ### `RULE_BY_CODE` {#RULE_BY_CODE} ```python title="signature" RULE_BY_CODE: frozendict[str, OnboardingRule] = frozendict({r.code: r for r in ONBOARDING_RULES}) ``` frozendict() -> new empty immutable dictionary ### `apply_op` {#apply_op} ```python title="signature" def apply_op(snapshot: SchemaSnapshot, op: MigrationOp) -> SchemaSnapshot: ... ``` Pure in-memory schema replay applying one `MigrationOp` with strict preconditions (`JQ2`). ### `apply_ops` {#apply_ops} ```python title="signature" def apply_ops(snapshot: SchemaSnapshot, ops: Sequence[MigrationOp]) -> SchemaSnapshot: ... ``` Apply an ordered sequence of `MigrationOp`s to `snapshot` in memory. ### `compile_plan` {#compile_plan} ```python title="signature" def compile_plan( ops: Sequence[MigrationOp], *, schema: str, version: str = "plan", name: str = "adhoc", online: bool = True, target_snapshot: SchemaSnapshot | None = None, current_snapshot: SchemaSnapshot | None = None, ) -> MigrationPlan: ... ``` Compile typed `MigrationOp`s into online lock-safe `MigrationStep`s + hazards. ### `detect_drift` {#detect_drift} ```python title="signature" def detect_drift(recorded: SchemaSnapshot, live: SchemaSnapshot) -> DriftReport: ... ``` Public `detect_drift` export from `pgdorm.migrate`. ### `detect_potential_renames` {#detect_potential_renames} ```python title="signature" def detect_potential_renames( current: SchemaSnapshot, desired: SchemaSnapshot ) -> tuple[tuple[str, str, str], ...]: ... ``` Return `(table, old_col, new_col)` hints where a dropped & added column share PG type. ### `diff_snapshots` {#diff_snapshots} ```python title="signature" def diff_snapshots( current: SchemaSnapshot, desired: SchemaSnapshot, *, canonical_desired: SchemaSnapshot | None = None, ) -> tuple[MigrationOp, ...]: ... ``` Compute ordered declarative `MigrationOp`s transforming `current` into `desired`. ### `order_ops_by_dependencies` {#order_ops_by_dependencies} ```python title="signature" def order_ops_by_dependencies( ops: Sequence[MigrationOp], *, schema: str, current: SchemaSnapshot | None = None, ) -> list[MigrationOp]: ... ``` Deterministically order migration ops via `graphlib.TopologicalSorter` (`DJ1`). ### `render_python_migration` {#render_python_migration} ```python title="signature" def render_python_migration(plan: MigrationPlan, *, var_name: str | None = None) -> str: ... ``` Render a self-contained, type-check-clean `pgm.Migration` data value from `plan`. ## Migration Operations (`MigrationOp`) ### `AddCheck` {#AddCheck} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddCheck(_TableOp): op_kind: ClassVar[str] = "add_check" table: str check: CheckSnapshot ``` AddCheck(*, table: str, check: pgdorm.migrate._catalog._models.CheckSnapshot) ### `AddColumn` {#AddColumn} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddColumn(_TableOp): op_kind: ClassVar[str] = "add_column" table: str column: ColumnSnapshot ``` AddColumn(*, table: str, column: pgdorm.migrate._catalog._models.ColumnSnapshot) ### `AddColumnIdentity` {#AddColumnIdentity} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddColumnIdentity(_TableOp): op_kind: ClassVar[str] = "add_column_identity" table: str column: str ``` AddColumnIdentity(*, table: str, column: str) ### `AddForeignKey` {#AddForeignKey} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddForeignKey(_TableOp): op_kind: ClassVar[str] = "add_foreign_key" table: str fk: FkSnapshot ``` AddForeignKey(*, table: str, fk: pgdorm.migrate._catalog._models.FkSnapshot) ### `AddPrimaryKey` {#AddPrimaryKey} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddPrimaryKey(_TableOp): op_kind: ClassVar[str] = "add_primary_key" table: str name: str columns: tuple[str, ...] ``` AddPrimaryKey(*, table: str, name: str, columns: tuple[str, ...]) ### `AddTemporalConstraint` {#AddTemporalConstraint} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddTemporalConstraint(_TableOp): op_kind: ClassVar[str] = "add_temporal_constraint" table: str temporal: TemporalSnapshot ``` AddTemporalConstraint(*, table: str, temporal: pgdorm.migrate._catalog._models.TemporalSnapshot) ### `AddUnique` {#AddUnique} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AddUnique(_TableOp): op_kind: ClassVar[str] = "add_unique" table: str unique: UniqueSnapshot transactional_only: bool = False ``` AddUnique(*, table: str, unique: pgdorm.migrate._catalog._models.UniqueSnapshot, transactional_only: bool = False) ### `AlterColumnExpression` {#AlterColumnExpression} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AlterColumnExpression(_TableOp): op_kind: ClassVar[str] = "alter_column_expression" table: str column: str old_expr: str | None = None new_expr: str stored: bool = False ``` AlterColumnExpression(*, table: str, column: str, old_expr: str | None = None, new_expr: str, stored: bool = False) ### `AlterColumnType` {#AlterColumnType} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AlterColumnType(_TableOp): op_kind: ClassVar[str] = "alter_column_type" table: str column: str old_type: str | None = None new_type: str using_sql: str | None = None ``` AlterColumnType(*, table: str, column: str, old_type: str | None = None, new_type: str, using_sql: str | None = None) ### `AnalyzeTable` {#AnalyzeTable} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AnalyzeTable(_TableOp): op_kind: ClassVar[str] = "analyze_table" table: str ``` AnalyzeTable(*, table: str) ### `CreateIndex` {#CreateIndex} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CreateIndex(_TableOp): op_kind: ClassVar[str] = "create_index" table: str index: IndexSnapshot partitioned: bool = False ``` CreateIndex(*, table: str, index: pgdorm.migrate._catalog._models.IndexSnapshot, partitioned: bool = False) ### `CreatePolicy` {#CreatePolicy} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CreatePolicy(_TableOp): op_kind: ClassVar[str] = "create_policy" table: str name: str using_sql: str with_check_sql: str | None = None ``` CreatePolicy(*, table: str, name: str, using_sql: str, with_check_sql: str | None = None) ### `CreateExtension` {#CreateExtension} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CreateExtension(_BaseOp): op_kind: ClassVar[str] = "create_extension" name: str schema: str = EXTENSION_SCHEMA ``` Installs a database-wide extension the schema needs, with `CREATE EXTENSION IF NOT EXISTS ... WITH SCHEMA "public"`. You rarely write it yourself: `snapshot_from_tables()` records the extensions your models need (today `btree_gist`, for `WITHOUT OVERLAPS` keys that include a scalar column), and `diff_snapshots()` plans this op ahead of the tables that depend on it. `pool.create_all()` installs the same extensions. pgdorm never drops an extension, because other schemas in the database may rely on it; `check_drift()` reports a required extension that has gone missing. ### `CreateSchema` {#CreateSchema} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CreateSchema(_BaseOp): op_kind: ClassVar[str] = "create_schema" schema: str if_not_exists: bool = True ``` CreateSchema(*, schema: str, if_not_exists: bool = True) ### `CreateTable` {#CreateTable} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CreateTable(_BaseOp): op_kind: ClassVar[str] = "create_table" table: TableSnapshot defer_fks: tuple[str, ...] = () ``` CreateTable(*, table: pgdorm.migrate._catalog._models.TableSnapshot, defer_fks: tuple[str, ...] = ()) ### `DropColumn` {#DropColumn} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropColumn(_TableOp): op_kind: ClassVar[str] = "drop_column" table: str column: str ``` DropColumn(*, table: str, column: str) ### `DropColumnDefault` {#DropColumnDefault} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropColumnDefault(_TableOp): op_kind: ClassVar[str] = "drop_column_default" table: str column: str ``` DropColumnDefault(*, table: str, column: str) ### `DropColumnIdentity` {#DropColumnIdentity} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropColumnIdentity(_TableOp): op_kind: ClassVar[str] = "drop_column_identity" table: str column: str ``` DropColumnIdentity(*, table: str, column: str) ### `DropConstraint` {#DropConstraint} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropConstraint(_TableOp): op_kind: ClassVar[str] = "drop_constraint" table: str name: str constraint_kind: ConstraintKind = ConstraintKind.UNKNOWN ``` DropConstraint(*, table: str, name: str, constraint_kind: Literal['fk', 'pk', 'unique', 'check', 'temporal', 'unknown'] = 'unknown') ### `DropIndex` {#DropIndex} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropIndex(_TableOp): op_kind: ClassVar[str] = "drop_index" table: str name: str partitioned: bool = False ``` DropIndex(*, table: str, name: str, partitioned: bool = False) ### `DropNotNull` {#DropNotNull} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropNotNull(_TableOp): op_kind: ClassVar[str] = "drop_not_null" table: str column: str ``` DropNotNull(*, table: str, column: str) ### `DropSchema` {#DropSchema} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropSchema(_BaseOp): op_kind: ClassVar[str] = "drop_schema" schema: str if_exists: bool = True cascade: bool = False ``` DropSchema(*, schema: str, if_exists: bool = True, cascade: bool = False) ### `DropTable` {#DropTable} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DropTable(_TableOp): op_kind: ClassVar[str] = "drop_table" table: str cascade: bool = False ``` DropTable(*, table: str, cascade: bool = False) ### `EnableRls` {#EnableRls} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class EnableRls(_TableOp): op_kind: ClassVar[str] = "enable_rls" table: str force: bool = True ``` EnableRls(*, table: str, force: bool = True) ### `GrantSchema` {#GrantSchema} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class GrantSchema(_BaseOp): op_kind: ClassVar[str] = "grant_schema" schema: str role: str scope: GrantScope = GrantScope.SCHEMA_USAGE ``` GrantSchema(*, schema: str, role: str, scope: GrantScopeName = 'schema_usage') ### `GrantScope` {#GrantScope} ```python title="signature" class GrantScope(StrEnum): SCHEMA_USAGE = "schema_usage" ALL_TABLES = "all_tables" ALL_SEQUENCES = "all_sequences" ``` Schema grant scope accepted by `grant_schema(...)` (`pgm.enums.GrantScope`). ### `Migration` {#Migration} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Migration: version: str name: str ops: tuple[MigrationOp, ...] ``` Pure immutable migration value (no subclassing ceremony required). ### `MigrationApp` {#MigrationApp} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class MigrationApp: tables: tuple[type[Table], ...] migrations: tuple[Migration, ...] = () schema: str = "public" ignore_tables: frozenset[str] = frozenset() online: bool = True lock_timeout: str = "2s" statement_timeout: str = "30s" lock_retries: int = 3 lock_retry_delay: float = 0.2 ``` Typed application manifest pointed to by `[tool.pgdorm] app = "module:attr"`. ### `MigrationOp` {#MigrationOp} ```python title="signature" type MigrationOp = ( CreateExtension | CreateSchema | DropSchema | CreateTable | DropTable | RenameTable | AddColumn | DropColumn | RenameColumn | AlterColumnType | AlterColumnExpression | AddColumnIdentity | DropColumnIdentity | AddTemporalConstraint | SetColumnDefault | DropColumnDefault | SetNotNull | DropNotNull | AddForeignKey | AddCheck | AddUnique | AddPrimaryKey | RestartIdentity | DropConstraint | ValidateConstraint | CreateIndex | DropIndex | SyncTypeTable | AnalyzeTable | EnableRls | CreatePolicy | GrantSchema | RunPython ) ``` Type alias. ### `MigrationPlan` {#MigrationPlan} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class MigrationPlan: version: str name: str ops: tuple[MigrationOp, ...] steps: tuple[MigrationStep, ...] hazards: tuple[MigrationHazard, ...] checksum: str target_snapshot: SchemaSnapshot | None = None ``` MigrationPlan(*, version: str, name: str, ops: tuple[pgdorm.migrate._plan._ops.MigrationOp, ...], steps: tuple[pgdorm.migrate._catalog._models.MigrationStep, ...], hazards: tuple[pgdorm.migrate._catalog._models.MigrationHazard, ...], checksum: str, target_snapshot: pgdorm.migrate._catalog._models.SchemaSnapshot | None = None) ### `RenameColumn` {#RenameColumn} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class RenameColumn(_TableOp): op_kind: ClassVar[str] = "rename_column" table: str old_name: str new_name: str ``` RenameColumn(*, table: str, old_name: str, new_name: str) ### `RenameTable` {#RenameTable} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class RenameTable(_BaseOp): op_kind: ClassVar[str] = "rename_table" old_name: str new_name: str ``` RenameTable(*, old_name: str, new_name: str) ### `RestartIdentity` {#RestartIdentity} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class RestartIdentity(_TableOp): op_kind: ClassVar[str] = "restart_identity" table: str column: str start_with: int ``` RestartIdentity(*, table: str, column: str, start_with: int) ### `RunPython` {#RunPython} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class RunPython(_BaseOp): op_kind: ClassVar[str] = "run_python" name: str fn: Callable[[Transaction], Awaitable[None]] target_table: str | None = None ``` RunPython(*, name: str, fn: collections.abc.Callable[[pgdorm.runtime._executors.Transaction], collections.abc.Awaitable[None]], target_table: str | None = None) ### `SetColumnDefault` {#SetColumnDefault} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SetColumnDefault(_TableOp): op_kind: ClassVar[str] = "set_column_default" table: str column: str default_sql: str ``` SetColumnDefault(*, table: str, column: str, default_sql: str) ### `SetNotNull` {#SetNotNull} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SetNotNull(_TableOp): op_kind: ClassVar[str] = "set_not_null" table: str column: str constraint_name: str | None = None ``` SetNotNull(*, table: str, column: str, constraint_name: str | None = None) ### `SyncTypeTable` {#SyncTypeTable} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SyncTypeTable(_TableOp): op_kind: ClassVar[str] = "sync_type_table" table: str pk_column: str pk_pg_type: str seeds: tuple[tuple[str, str], ...] ``` SyncTypeTable(*, table: str, pk_column: str, pk_pg_type: str, seeds: tuple[tuple[str, str], ...]) ### `ValidateConstraint` {#ValidateConstraint} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ValidateConstraint(_TableOp): op_kind: ClassVar[str] = "validate_constraint" table: str name: str ``` ValidateConstraint(*, table: str, name: str) ### `add_check` {#add_check} ```python title="signature" def add_check( table: type[Table] | str, predicate: Expr[bool], *, name: str | None = None ) -> AddCheck: ... ``` Public `add_check` export from `pgdorm.migrate`. ### `add_column` {#add_column} ```python title="signature" def add_column(col: ColBase) -> AddColumn: ... ``` Build an `AddColumn` op directly from a typed `Table.col` descriptor. ### `add_primary_key` {#add_primary_key} ```python title="signature" def add_primary_key( table: type[Table] | str, *columns: ColBase | str, name: str | None = None ) -> AddPrimaryKey: ... ``` Public `add_primary_key` export from `pgdorm.migrate`. ### `add_unique` {#add_unique} ```python title="signature" def add_unique( table: type[Table] | str, *columns: ColBase | str, name: str | None = None ) -> AddUnique: ... ``` Public `add_unique` export from `pgdorm.migrate`. ### `analyze_table` {#analyze_table} ```python title="signature" def analyze_table(table: type[Table] | str) -> AnalyzeTable: ... ``` Public `analyze_table` export from `pgdorm.migrate`. ### `create_index` {#create_index} ```python title="signature" def create_index( table: type[Table] | str, *columns: ColBase | str, name: str | None = None, unique: bool = False, where: Expr[bool] | None = None, ) -> CreateIndex: ... ``` Public `create_index` export from `pgdorm.migrate`. ### `create_policy` {#create_policy} ```python title="signature" def create_policy( table: type[Table] | str, *, name: str, using: Expr[bool], with_check: Expr[bool] | None = None, ) -> CreatePolicy: ... ``` Public `create_policy` export from `pgdorm.migrate`. ### `create_schema` {#create_schema} ```python title="signature" def create_schema(schema: str, *, if_not_exists: bool = True) -> CreateSchema: ... ``` Public `create_schema` export from `pgdorm.migrate`. ### `drop_column` {#drop_column} ```python title="signature" def drop_column(table: type[Table] | str, column: ColBase | str) -> DropColumn: ... ``` Public `drop_column` export from `pgdorm.migrate`. ### `drop_not_null` {#drop_not_null} ```python title="signature" def drop_not_null(col: ColBase) -> DropNotNull: ... ``` Public `drop_not_null` export from `pgdorm.migrate`. ### `drop_schema` {#drop_schema} ```python title="signature" def drop_schema(schema: str, *, if_exists: bool = True, cascade: bool = False) -> DropSchema: ... ``` Public `drop_schema` export from `pgdorm.migrate`. ### `enable_rls` {#enable_rls} ```python title="signature" def enable_rls(table: type[Table] | str, *, force: bool = True) -> EnableRls: ... ``` Public `enable_rls` export from `pgdorm.migrate`. ### `grant_schema` {#grant_schema} ```python title="signature" def grant_schema( schema: str, *, role: str, scope: GrantScope = GrantScope.SCHEMA_USAGE ) -> GrantSchema: ... ``` Public `grant_schema` export from `pgdorm.migrate`. ### `rename_column` {#rename_column} ```python title="signature" def rename_column( table: type[Table] | str, *, old: ColBase | str, new: ColBase | str ) -> RenameColumn: ... ``` Public `rename_column` export from `pgdorm.migrate`. ### `rename_table` {#rename_table} ```python title="signature" def rename_table(*, old: type[Table] | str, new: type[Table] | str) -> RenameTable: ... ``` Public `rename_table` export from `pgdorm.migrate`. ### `restart_identity` {#restart_identity} ```python title="signature" def restart_identity( table: type[Table] | str, column: ColBase | str, *, start_with: int ) -> RestartIdentity: ... ``` Public `restart_identity` export from `pgdorm.migrate`. ### `set_not_null` {#set_not_null} ```python title="signature" def set_not_null(col: ColBase, *, constraint_name: str | None = None) -> SetNotNull: ... ``` Public `set_not_null` export from `pgdorm.migrate`. ### `sync_type_table` {#sync_type_table} ```python title="signature" def sync_type_table(table: type[Table]) -> SyncTypeTable: ... ``` Public `sync_type_table` export from `pgdorm.migrate`. ## Schema Onboarding & Assimilation ### `AdoptionImpactWarning` {#AdoptionImpactWarning} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AdoptionImpactWarning: object_kind: str object_name: str table: str | None referenced_old: str detail: str definition: str | None = None ``` Warning when a planned rename/PK change impacts an unmanaged or dependent DB object. ### `AdoptionMap` {#AdoptionMap} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AdoptionMap: tables: Mapping[str, TableMapping] = frozendict() ignore_tables: frozenset[str] = frozenset() drop_tables: frozenset[str] = frozenset() enum_types: Mapping[str, tuple[str, ...]] = frozendict() ``` Bijective source->target mapping guaranteeing exact table/column targeting. ### `AdoptionPlan` {#AdoptionPlan} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class AdoptionPlan: plan: MigrationPlan adoption: AdoptionMap impact_warnings: tuple[AdoptionImpactWarning, ...] = () ignored_tables: frozenset[str] = frozenset() preserved_unmanaged_count: int = 0 ``` Complete verified assimilation plan with compiled PostgreSQL steps and impact warnings. ### `AuditSeverity` {#AuditSeverity} ```python title="signature" class AuditSeverity(IntEnum): INFO = 1 UNMANAGED = 2 MIGRATION_REQUIRED = 3 BLOCKER = 4 ``` Enum where members are also (and must be) ints ### `CatalogExtras` {#CatalogExtras} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CatalogExtras: views: tuple[ViewInfo, ...] = () routines: tuple[RoutineInfo, ...] = () triggers: tuple[TriggerInfo, ...] = () pg_enums: Mapping[str, tuple[str, ...]] = frozendict() pg_domains: frozenset[str] = frozenset() pg_composites: frozenset[str] = frozenset() inherited_tables: tuple[tuple[str, str], ...] = () foreign_tables: tuple[str, ...] = () exclusion_constraints: tuple[ExclusionConstraintInfo, ...] = () rls_policies: tuple[tuple[str, str], ...] = () extensions: tuple[str, ...] = () fk_metas: tuple[FkMetaInfo, ...] = () serial_owned_columns: frozenset[tuple[str, str]] = frozenset() multidim_array_columns: frozenset[tuple[str, str]] = frozenset() ``` Read-only inventory of PG objects outside `SchemaSnapshot` tables. ### `ExclusionConstraintInfo` {#ExclusionConstraintInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ExclusionConstraintInfo: table: str name: str definition: str ``` ExclusionConstraintInfo(*, table: str, name: str, definition: str) ### `ExternalPlanPhases` {#ExternalPlanPhases} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ExternalPlanPhases: transactional_steps: tuple[MigrationStep, ...] post_commit_steps: tuple[MigrationStep, ...] ``` Split a `MigrationPlan` into atomic transactional steps and post-commit online steps. ### `ExternalSqlExecutor` {#ExternalSqlExecutor} ```python title="signature" type ExternalSqlExecutor = Callable[[str], Awaitable[object]] ``` Type alias. ### `FkMetaInfo` {#FkMetaInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class FkMetaInfo: table: str name: str on_update: str | None = None deferrable: bool = False ``` FkMetaInfo(*, table: str, name: str, on_update: str | None = None, deferrable: bool = False) ### `OnboardingFinding` {#OnboardingFinding} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class OnboardingFinding: code: str severity: AuditSeverity category: RuleCategory object_kind: str object_name: str table: str | None message: str suggestion: str auto_fixable: bool doc_anchor: str ``` OnboardingFinding(*, code: str, severity: pgdorm.migrate._assimilate._rules.AuditSeverity, category: RuleCategory, object_kind: str, object_name: str, table: str | None, message: str, suggestion: str, auto_fixable: bool, doc_anchor: str) ### `OnboardingReport` {#OnboardingReport} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class OnboardingReport: schema: str snapshot: SchemaSnapshot extras: CatalogExtras findings: tuple[OnboardingFinding, ...] type_table_candidates: tuple[TypeTableCandidate, ...] workflow_steps: tuple[OnboardingWorkflowStep, ...] ignored_tables: frozenset[str] = frozenset() ``` Structured readiness checklist and agentic gap report for an existing PG schema. ### `OnboardingRule` {#OnboardingRule} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class OnboardingRule: code: str category: RuleCategory severity: AuditSeverity support_status: SupportStatus title: str summary: str action: str auto_fixable: bool doc_anchor: str ``` Single-source-of-truth compatibility rule shared by `audit_schema()` and docsgen. ### `OnboardingWorkflowStep` {#OnboardingWorkflowStep} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class OnboardingWorkflowStep: phase: OnboardingPhase order: int summary: str detail: str ``` OnboardingWorkflowStep(*, phase: Literal['pre_ddl', 'ddl', 'post_ddl', 'post_commit'], order: int, summary: str, detail: str) ### `PkStrategy` {#PkStrategy} ```python title="signature" class PkStrategy(StrEnum): RENAME = "rename" ADD_SURROGATE = "add_surrogate" KEEP = "keep" ``` Primary-key assimilation strategy (`pgm.enums.PkStrategy`). ### `RoutineInfo` {#RoutineInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class RoutineInfo: name: str kind: RoutineKind source: str = "" definition: str | None = None ``` Stored function, procedure, aggregate, or window routine discovered during schema auditing. ### `RuleCategory` {#RuleCategory} ```python title="signature" class RuleCategory(StrEnum): NAMING = "naming" PRIMARY_KEY = "primary_key" TYPE_TABLE = "type_table" TYPES = "types" CONSTRAINTS = "constraints" INDEXES = "indexes" UNMANAGED = "unmanaged" UNSUPPORTED = "unsupported" ``` Onboarding audit rule category (`pgm.enums.RuleCategory`). ### `ScaffoldMode` {#ScaffoldMode} ```python title="signature" class ScaffoldMode(StrEnum): ASSIMILATE = "assimilate" BIND = "bind" ``` Model scaffolding mode (`pgm.enums.ScaffoldMode`). ### `ScaffoldResult` {#ScaffoldResult} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ScaffoldResult: code: str adoption_map: AdoptionMap table_names: tuple[str, ...] warnings: tuple[str, ...] = () ``` Generated compliant `pgdorm` models and paired `AdoptionMap`. ### `SupportStatus` {#SupportStatus} ```python title="signature" class SupportStatus(StrEnum): SUPPORTED = "supported" MIGRATABLE = "migratable" UNMANAGED = "unmanaged" UNSUPPORTED = "unsupported" ``` Onboarding rule support classification (`pgm.enums.SupportStatus`). ### `SurrogatePkType` {#SurrogatePkType} ```python title="signature" class SurrogatePkType(StrEnum): BIGINT = "bigint" UUIDV7 = "uuidv7" ``` Surrogate primary-key column type (`pgm.enums.SurrogatePkType`). ### `TableMapping` {#TableMapping} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TableMapping: target: str columns: Mapping[str, str] = frozendict() as_type_table: bool = False pk_strategy: PkStrategy = PkStrategy.RENAME migrate_serial_to_identity: bool = False migrate_uuid_to_uuidv7: bool = False surrogate_pk: SurrogatePkType = SurrogatePkType.BIGINT ``` Explicit assimilation rule mapping one existing table to its `pgdorm` target shape. ### `TriggerInfo` {#TriggerInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TriggerInfo: name: str table: str function_name: str definition: str | None = None ``` TriggerInfo(*, name: str, table: str, function_name: str, definition: str | None = None) ### `TypeTableCandidate` {#TypeTableCandidate} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TypeTableCandidate: table: str pk_column: str pk_pg_type: str code_column: str code_pg_type: str referencing_tables: tuple[str, ...] confidence: Confidence reason: str ``` TypeTableCandidate(*, table: str, pk_column: str, pk_pg_type: str, code_column: str, code_pg_type: str, referencing_tables: tuple[str, ...], confidence: Literal['high', 'medium'], reason: str) ### `ViewInfo` {#ViewInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ViewInfo: name: str materialized: bool = False depends_on_tables: tuple[str, ...] = () definition: str | None = None ``` ViewInfo(*, name: str, materialized: bool = False, depends_on_tables: tuple[str, ...] = (), definition: str | None = None) ### `analyze_onboarding` {#analyze_onboarding} ```python title="signature" def analyze_onboarding( snapshot: SchemaSnapshot, extras: CatalogExtras | None = None, *, ignore_tables: frozenset[str] = frozenset(), ) -> OnboardingReport: ... ``` Pure analyzer producing a deterministic readiness checklist & agentic gap report. ### `assimilate_column_name` {#assimilate_column_name} ```python title="signature" def assimilate_column_name(raw: str) -> str: ... ``` Compute a compliant `snake_case` Python identifier for a column. ### `assimilate_table_name` {#assimilate_table_name} ```python title="signature" def assimilate_table_name(raw: str, *, as_type_table: bool = False) -> str: ... ``` Compute a compliant singular `snake_case` target table name for full assimilation. ### `audit_schema` {#audit_schema} ```python title="signature" async def audit_schema( conn: Pool | Transaction, *, schema: str | None = None, ignore_tables: frozenset[str] = frozenset(), include_definitions: bool = True, ) -> OnboardingReport: ... ``` Inspect a live PostgreSQL schema and return a full assimilation readiness report. ### `build_adoption_ops` {#build_adoption_ops} ```python title="signature" def build_adoption_ops( live: SchemaSnapshot, desired: SchemaSnapshot, adoption: AdoptionMap, *, canonical_desired: SchemaSnapshot | None = None, allow_unmapped_drops: bool = False, ) -> tuple[MigrationOp, ...]: ... ``` Validate `adoption`, emit cycle-safe renames + PK assimilation, and diff remaining gaps. ### `detect_rename_impacts` {#detect_rename_impacts} ```python title="signature" def detect_rename_impacts( adoption: AdoptionMap, live: SchemaSnapshot, extras: CatalogExtras, ) -> tuple[AdoptionImpactWarning, ...]: ... ``` Identify views, triggers, routines, CHECKs, and FKs affected by planned renames. ### `execute_plan_tx` {#execute_plan_tx} ```python title="signature" async def execute_plan_tx(plan: MigrationPlan, execute_sql: ExternalSqlExecutor) -> int: ... ``` Feed compiled transactional DDL steps into a caller's external TX (e.g. `psycopg3`). ### `finalize_external` {#finalize_external} ```python title="signature" async def finalize_external( pool: Pool, plan: MigrationPlan, *, tables: Sequence[type[Table]], schema: str | None = None, ignore_tables: frozenset[str] = frozenset(), lease_seconds: int = 300, ) -> MigrationRecord: ... ``` Run post-commit online steps (`CONCURRENTLY`/`VALIDATE`) and record ledger state. ### `introspect_catalog_extras` {#introspect_catalog_extras} ```python title="signature" async def introspect_catalog_extras( conn: Pool | Transaction, schema: str, *, include_definitions: bool = True ) -> CatalogExtras: ... ``` Read-only pipelined inspection of views, routines, triggers, enums, and blockers. ### `plan_adoption` {#plan_adoption} ```python title="signature" async def plan_adoption( pool: Pool, tables: Sequence[type[Table]], *, adoption: AdoptionMap, schema: str | None = None, version: str | None = None, name: str = "adopt", online: bool = True, allow_unmapped_drops: bool = False, ) -> AdoptionPlan: ... ``` Introspect live catalog, validate `adoption`, and compile an assimilation plan. ### `render_phased_sql` {#render_phased_sql} ```python title="signature" def render_phased_sql(adoption_plan: AdoptionPlan) -> str: ... ``` Render a reviewable 4-phase SQL blueprint for DBAs and AI agents. ### `scaffold_from_db` {#scaffold_from_db} ```python title="signature" async def scaffold_from_db( pool: Pool, *, schema: str | None = None, adoption: AdoptionMap | None = None, type_tables: frozenset[str] = frozenset(), ignore_tables: frozenset[str] = frozenset(), mode: ScaffoldMode = ScaffoldMode.ASSIMILATE, assimilate_enums: bool = False, modernize: bool = False, surrogate_pk: SurrogatePkType = SurrogatePkType.BIGINT, emit_app: bool = True, ) -> ScaffoldResult: ... ``` Introspect live PostgreSQL and scaffold `pgdorm` models (`assimilate` or `bind`). ### `scaffold_models` {#scaffold_models} ```python title="signature" def scaffold_models( snapshot: SchemaSnapshot, *, adoption: AdoptionMap | None = None, type_table_rows: Mapping[str, Sequence[tuple[str, str]]] = {}, enum_types: Mapping[str, Sequence[str]] = frozendict(), mode: ScaffoldMode = ScaffoldMode.ASSIMILATE, emit_app: bool = True, ) -> ScaffoldResult: ... ``` Generate `pg.Table` / `pg.TypeTable` code from a schema snapshot. ### `singularize_ident` {#singularize_ident} ```python title="signature" def singularize_ident(snake: str) -> str: ... ``` Deterministically singularize the trailing token of a snake_case identifier. ### `snake_to_pascal` {#snake_to_pascal} ```python title="signature" def snake_to_pascal(name: str) -> str: ... ``` Convert a `snake_case` table identifier to a PascalCase Python class name. ### `split_plan_phases` {#split_plan_phases} ```python title="signature" def split_plan_phases(plan: MigrationPlan) -> ExternalPlanPhases: ... ``` Partition `plan.steps` into atomic TX DDL and autocommit/online post-commit steps. ### `suggest_adoption_map` {#suggest_adoption_map} ```python title="signature" def suggest_adoption_map( snapshot: SchemaSnapshot, *, candidates: Sequence[TypeTableCandidate] = (), type_tables: frozenset[str] = frozenset(), ignore_tables: frozenset[str] = frozenset(), enum_types: Mapping[str, Sequence[str]] = frozendict(), modernize: bool = False, surrogate_pk: SurrogatePkType = SurrogatePkType.BIGINT, mode: ScaffoldMode = ScaffoldMode.ASSIMILATE, ) -> AdoptionMap: ... ``` Propose an `AdoptionMap` (`assimilate` normalizes names/PKs; `bind` keeps live schema). ### `sync_identity_from_max` {#sync_identity_from_max} ```python title="signature" async def sync_identity_from_max( conn: Pool | Transaction, table: type[Table], column: str, *, schema: str | None = None, ) -> int: ... ``` Compute `MAX(column) + 1` via typed ORM and emit `ALTER COLUMN ... RESTART WITH`. ### `validate_adoption_map` {#validate_adoption_map} ```python title="signature" def validate_adoption_map( live: SchemaSnapshot, desired: SchemaSnapshot, adoption: AdoptionMap, *, allow_unmapped_drops: bool = False, ) -> None: ... ``` Strictly verify bijection, live existence, and zero-implicit-drop invariants. ## Catalog Introspection Models ### `CheckSnapshot` {#CheckSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class CheckSnapshot: name: str expr_sql: str validated: bool = True ``` CheckSnapshot(*, name: str, expr_sql: str, validated: bool = True) ### `ColumnSnapshot` {#ColumnSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ColumnSnapshot: name: str pg_type: str nullable: bool = False not_null_constraint: str | None = None not_null_validated: bool = True primary_key: bool = False identity: bool = False default_sql: str | None = None generated_expr: str | None = None generated_stored: bool = False server_managed: bool = False ``` ColumnSnapshot(*, name: str, pg_type: str, nullable: bool = False, not_null_constraint: str | None = None, not_null_validated: bool = True, primary_key: bool = False, identity: bool = False, default_sql: str | None = None, generated_expr: str | None = None, generated_stored: bool = False) ### `DriftItem` {#DriftItem} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DriftItem: kind: str table: str detail: str ``` DriftItem(*, kind: str, table: str, detail: str) ### `DriftReport` {#DriftReport} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class DriftReport: schema: str items: tuple[DriftItem, ...] invalid_indexes: tuple[tuple[str, str], ...] = () unvalidated_constraints: tuple[tuple[str, str], ...] = () ``` DriftReport(*, schema: str, items: tuple[pgdorm.migrate._catalog._models.DriftItem, ...], invalid_indexes: tuple[tuple[str, str], ...] = (), unvalidated_constraints: tuple[tuple[str, str], ...] = ()) ### `FkSnapshot` {#FkSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class FkSnapshot: name: str columns: tuple[str, ...] ref_schema: str | None = None ref_table: str ref_columns: tuple[str, ...] on_delete: str | None = None validated: bool = True deferrable: bool = False initially_deferred: bool = False ``` FkSnapshot(*, name: str, columns: tuple[str, ...], ref_schema: str | None = None, ref_table: str, ref_columns: tuple[str, ...], on_delete: str | None = None, validated: bool = True, deferrable: bool = False, initially_deferred: bool = False) ### `HazardLevel` {#HazardLevel} ```python title="signature" class HazardLevel(IntEnum): SAFE = 1 LOCK_SENSITIVE = 2 BREAKING = 3 DESTRUCTIVE = 4 ``` Enum where members are also (and must be) ints ### `IndexSnapshot` {#IndexSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class IndexSnapshot: name: str columns: tuple[str, ...] column_orders: tuple[str, ...] = () unique: bool = False where_sql: str | None = None valid: bool = True ``` IndexSnapshot(*, name: str, columns: tuple[str, ...], column_orders: tuple[str, ...] = (), unique: bool = False, where_sql: str | None = None, valid: bool = True) ### `LockMode` {#LockMode} ```python title="signature" class LockMode(IntEnum): NONE = 1 SHARE_UPDATE_EXCLUSIVE = 2 SHARE = 3 SHARE_ROW_EXCLUSIVE = 4 ACCESS_EXCLUSIVE = 5 ``` Enum where members are also (and must be) ints ### `MigrationEventTypeEnum` {#MigrationEventTypeEnum} ```python title="signature" class MigrationEventTypeEnum(IntEnum): START = 1 STEP_OK = 2 STEP_FAIL = 3 COMPLETE = 4 ROLLBACK = 5 BASELINE = 6 DRIFT = 7 ``` Enum where members are also (and must be) ints ### `MigrationHazard` {#MigrationHazard} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class MigrationHazard: level: HazardLevel code: str table: str | None = None message: str suggestion: str | None = None ``` MigrationHazard(*, level: pgdorm.migrate._catalog._models.HazardLevel, code: str, table: str | None = None, message: str, suggestion: str | None = None) ### `MigrationModeEnum` {#MigrationModeEnum} ```python title="signature" class MigrationModeEnum(IntEnum): SYNC = 1 VERSIONED = 2 BASELINE = 3 ``` Enum where members are also (and must be) ints ### `MigrationStatusEnum` {#MigrationStatusEnum} ```python title="signature" class MigrationStatusEnum(IntEnum): RUNNING = 1 APPLIED = 2 FAILED = 3 ROLLED_BACK = 4 ``` Enum where members are also (and must be) ints ### `MigrationStep` {#MigrationStep} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class MigrationStep: action: StepAction description: str op_kind: str target_table: str | None = None transactional: bool = True separate_tx: bool = False lock_mode: LockMode = LockMode.NONE hazard_level: HazardLevel = HazardLevel.SAFE retry_on_lock_timeout: bool = False ``` MigrationStep(*, action: StepAction, description: str, op_kind: str, target_table: str | None = None, transactional: bool = True, separate_tx: bool = False, lock_mode: pgdorm.migrate._catalog._models.LockMode = , hazard_level: pgdorm.migrate._catalog._models.HazardLevel = , retry_on_lock_timeout: bool = False) ### `PartitionSnapshot` {#PartitionSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class PartitionSnapshot: strategy: str columns: tuple[str, ...] ``` PartitionSnapshot(*, strategy: str, columns: tuple[str, ...]) ### `PgAttrdef` {#PgAttrdef} ```python title="signature" class PgAttrdef(Table, schema="pg_catalog", read_only=True): oid: Col[int] = pk() adrelid: Col[int] = fk(PgClass.oid) adnum: Col[Int2] = col() adbin: Col[str] = col() ``` Read-only ORM model for `pg_catalog.pg_attrdef`. ### `PgAttribute` {#PgAttribute} ```python title="signature" class PgAttribute(Table, schema="pg_catalog", read_only=True): attrelid: Col[int] = fk(PgClass.oid) attname: Col[str] = col() atttypid: Col[int] = col() atttypmod: Col[Int4] = col() attnum: Col[Int2] = col() attndims: Col[Int2] = col() attnotnull: Col[bool] = col() attisdropped: Col[bool] = col() attidentity: Col[str] = col() attgenerated: Col[str] = col() ``` Read-only ORM model for `pg_catalog.pg_attribute`. ### `PgClass` {#PgClass} ```python title="signature" class PgClass(Table, schema="pg_catalog", read_only=True): oid: Col[int] = pk() relname: Col[str] = col() relnamespace: Col[int] = fk(PgNamespace.oid) relkind: Col[str] = col() relispartition: Col[bool] = col() relam: Col[int] = fk(PgAm.oid) relrowsecurity: Col[bool] = col() ``` Read-only ORM model for `pg_catalog.pg_class`. ### `PgConstraint` {#PgConstraint} ```python title="signature" class PgConstraint(Table, schema="pg_catalog", read_only=True): oid: Col[int] = pk() conname: Col[str] = col() conrelid: Col[int] = fk(PgClass.oid) confrelid: Col[int] = col() conparentid: Col[int] = col() contype: Col[str] = col() convalidated: Col[bool] = col() conindid: Col[int] = col() conkey: Col[list[Int2] | None] = col(default=None) confkey: Col[list[Int2] | None] = col(default=None) confdeltype: Col[str] = col() confupdtype: Col[str] = col() condeferrable: Col[bool] = col() condeferred: Col[bool] = col() confdelsetcols: Col[list[Int2] | None] = col(default=None) ``` Read-only ORM model for `pg_catalog.pg_constraint`. ### `PgExtension` {#PgExtension} ```python title="signature" class PgExtension(Table, schema="pg_catalog", read_only=True): oid: Col[int] = pk() extname: Col[str] = col() extnamespace: Col[int] = fk(PgNamespace.oid) ``` Read-only ORM model for `pg_catalog.pg_extension`. ### `PgIndex` {#PgIndex} ```python title="signature" class PgIndex(Table, schema="pg_catalog", read_only=True): indexrelid: Col[int] = fk(PgClass.oid) indrelid: Col[int] = fk(PgClass.oid) indnatts: Col[Int2] = col() indnkeyatts: Col[Int2] = col() indisunique: Col[bool] = col() indisprimary: Col[bool] = col() indisvalid: Col[bool] = col() indkey: Col[list[Int2]] = col() indoption: Col[list[Int2]] = col() indpred: Col[str | None] = col(default=None) ``` Read-only ORM model for `pg_catalog.pg_index`. ### `PgIndexes` {#PgIndexes} ```python title="signature" class PgIndexes(Table, schema="pg_catalog", read_only=True): schemaname: Col[str] = col() tablename: Col[str] = col() indexname: Col[str] = col() indexdef: Col[str] = col() ``` Read-only ORM model for `pg_catalog.pg_indexes`. ### `PgNamespace` {#PgNamespace} ```python title="signature" class PgNamespace(Table, schema="pg_catalog", read_only=True): oid: Col[int] = pk() nspname: Col[str] = col() ``` Read-only ORM model for `pg_catalog.pg_namespace`. ### `PgTables` {#PgTables} ```python title="signature" class PgTables(Table, schema="pg_catalog", read_only=True): schemaname: Col[str] = col() tablename: Col[str] = col() tableowner: Col[str] = col() ``` Read-only ORM model for `pg_catalog.pg_tables`. ### `PgType` {#PgType} ```python title="signature" class PgType(Table, schema="pg_catalog", read_only=True): oid: Col[int] = pk() typname: Col[str] = col() typnamespace: Col[int] = fk(PgNamespace.oid) typtype: Col[str] = col() typbasetype: Col[int] = col() ``` Read-only ORM model for `pg_catalog.pg_type`. ### `SchemaSnapshot` {#SchemaSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class SchemaSnapshot: schema: str tables: Mapping[str, TableSnapshot] view_dependencies: tuple[ViewDependencySnapshot, ...] = () extensions: tuple[str, ...] = () ``` SchemaSnapshot(*, schema: str, tables: collections.abc.Mapping[str, pgdorm.migrate._catalog._models.TableSnapshot], view_dependencies: tuple[pgdorm.migrate._catalog._view_deps.ViewDependencySnapshot, ...] = ()) ### `TableSnapshot` {#TableSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TableSnapshot: name: str schema: str | None = None columns: tuple[ColumnSnapshot, ...] primary_key_columns: tuple[str, ...] = () primary_key_name: str | None = None foreign_keys: tuple[FkSnapshot, ...] = () unique_constraints: tuple[UniqueSnapshot, ...] = () checks: tuple[CheckSnapshot, ...] = () temporal_constraints: tuple[TemporalSnapshot, ...] = () indexes: tuple[IndexSnapshot, ...] = () unmanaged_indexes: tuple[UnmanagedIndexSnapshot, ...] = () preserved_constraints: tuple[str, ...] = () partition_by: PartitionSnapshot | None = None type_seeds: tuple[tuple[str, str], ...] = () ``` TableSnapshot(*, name: str, schema: str | None = None, columns: tuple[pgdorm.migrate._catalog._models.ColumnSnapshot, ...], primary_key_columns: tuple[str, ...] = (), primary_key_name: str | None = None, foreign_keys: tuple[pgdorm.migrate._catalog._models.FkSnapshot, ...] = (), unique_constraints: tuple[pgdorm.migrate._catalog._models.UniqueSnapshot, ...] = (), checks: tuple[pgdorm.migrate._catalog._models.CheckSnapshot, ...] = (), temporal_constraints: tuple[pgdorm.migrate._catalog._models.TemporalSnapshot, ...] = (), indexes: tuple[pgdorm.migrate._catalog._models.IndexSnapshot, ...] = (), unmanaged_indexes: tuple[pgdorm.migrate._catalog._models.UnmanagedIndexSnapshot, ...] = (), preserved_constraints: tuple[str, ...] = (), partition_by: pgdorm.migrate._catalog._models.PartitionSnapshot | None = None, type_seeds: tuple[tuple[str, str], ...] = ()) ### `TemporalSnapshot` {#TemporalSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class TemporalSnapshot: name: str columns: tuple[str, ...] range_column: str is_primary_key: bool ``` TemporalSnapshot(*, name: str, columns: tuple[str, ...], range_column: str, is_primary_key: bool) ### `UniqueSnapshot` {#UniqueSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class UniqueSnapshot: name: str columns: tuple[str, ...] ``` UniqueSnapshot(*, name: str, columns: tuple[str, ...]) ### `UnmanagedIndexSnapshot` {#UnmanagedIndexSnapshot} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class UnmanagedIndexSnapshot: name: str access_method: str indexdef: str reason: str ``` Index preserved untouched by `pgdorm.migrate` (non-B-tree, expression, or INCLUDE). ### `canonicalize_snapshot_with_pg` {#canonicalize_snapshot_with_pg} ```python title="signature" async def canonicalize_snapshot_with_pg(pool: Pool, desired: SchemaSnapshot) -> SchemaSnapshot: ... ``` Canonicalize CHECK/DEFAULT/generated expressions via PostgreSQL inside a rolled-back temp tx. ### `introspect_schema` {#introspect_schema} ```python title="signature" async def introspect_schema( conn: Pool | Transaction, schema: str, *, ignore_tables: frozenset[str] = frozenset(), type_tables: Sequence[type[Table]] = (), ) -> SchemaSnapshot: ... ``` Introspect live `pg_catalog` via 100% pure pipelined `pgdorm` ORM queries. ### `snapshot_from_tables` {#snapshot_from_tables} ```python title="signature" def snapshot_from_tables(*tables: type[Table], schema: str) -> SchemaSnapshot: ... ``` Convert `pg.Table` classes into a canonical `SchemaSnapshot` matching live introspection. ## Migration Ledger & Constants ### `HazardLevelType` {#HazardLevelType} ```python title="signature" class HazardLevelType(TypeTable, schema=PGDORM_SCHEMA, enum=HazardLevel): hazard_level_type_id: Col[HazardLevel] = pk() ``` Lookup table base class backed by a Python Enum (enforces unique `code` column). ### `LockModeType` {#LockModeType} ```python title="signature" class LockModeType(TypeTable, schema=PGDORM_SCHEMA, enum=LockMode): lock_mode_type_id: Col[LockMode] = pk() ``` Lookup table base class backed by a Python Enum (enforces unique `code` column). ### `MigrationEventRecord` {#MigrationEventRecord} ```python title="signature" MigrationEventRecord = MigrationEvent ``` Immutable append-only migration audit event in `_pgdorm.migration_event`. ### `MigrationEventType` {#MigrationEventType} ```python title="signature" class MigrationEventType(TypeTable, schema=PGDORM_SCHEMA, enum=MigrationEventTypeEnum): migration_event_type_id: Col[MigrationEventTypeEnum] = pk() ``` Lookup table base class backed by a Python Enum (enforces unique `code` column). ### `MigrationMode` {#MigrationMode} ```python title="signature" MigrationMode = MigrationModeType ``` Lookup table base class backed by a Python Enum (enforces unique `code` column). ### `MigrationRecord` {#MigrationRecord} ```python title="signature" MigrationRecord = Migration ``` Persisted migration execution record in `_pgdorm.migration`. ### `MigrationStatus` {#MigrationStatus} ```python title="signature" MigrationStatus = MigrationStatusType ``` Lookup table base class backed by a Python Enum (enforces unique `code` column). ### `MigrationStepRecord` {#MigrationStepRecord} ```python title="signature" MigrationStepRecord = MigrationStep ``` Persisted per-step DDL/Python execution row in `_pgdorm.migration_step`. ## Migration Exceptions ### `AdoptionTargetError` {#AdoptionTargetError} ```python title="signature" class AdoptionTargetError(MigrationError): ... ``` Base exception for all Python-side pgdorm errors. ### `ChecksumMismatchError` {#ChecksumMismatchError} ```python title="signature" class ChecksumMismatchError(MigrationError): ... ``` Base exception for all Python-side pgdorm errors. ### `DriftError` {#DriftError} ```python title="signature" class DriftError(MigrationError): ... ``` Base exception for all Python-side pgdorm errors. ### `HistoryDivergenceError` {#HistoryDivergenceError} ```python title="signature" class HistoryDivergenceError(MigrationError): ... ``` Base exception for all Python-side pgdorm errors. ### `MigrationError` {#MigrationError} ```python title="signature" class MigrationError(PgdormError, RuntimeError): ... ``` Base exception for all Python-side pgdorm errors. ### `MigrationLockError` {#MigrationLockError} ```python title="signature" class MigrationLockError(MigrationError): ... ``` Base exception for all Python-side pgdorm errors. ### `UnsafeMigrationError` {#UnsafeMigrationError} ```python title="signature" class UnsafeMigrationError(MigrationError): ... ``` Base exception for all Python-side pgdorm errors. --- ## Migration Enums (`pgdorm.migrate.enums`) Strict `StrEnum` option namespaces exposed as `pgm.enums.*` and re-exported as types from `pgdorm.typing`. ### `enums` {#enums} ```python title="signature" import pgdorm.migrate.enums as enums ``` Submodule namespace holding all migration `StrEnum` option types (`pgm.enums.*`). ### `AdoptOutputFormat` {#AdoptOutputFormat} ```python title="signature" class AdoptOutputFormat(StrEnum): TEXT = "text" JSON = "json" SQL = "sql" ``` CLI output format for `adopt-plan` (`TEXT`, `JSON`, `SQL`). ### `Confidence` {#Confidence} ```python title="signature" class Confidence(StrEnum): HIGH = "high" MEDIUM = "medium" ``` Heuristic confidence level for detected `TypeTable` candidates (`HIGH`, `MEDIUM`). ### `ConstraintKind` {#ConstraintKind} ```python title="signature" class ConstraintKind(StrEnum): FK = "fk" PK = "pk" UNIQUE = "unique" CHECK = "check" TEMPORAL = "temporal" UNKNOWN = "unknown" ``` Constraint classification accepted by `DropConstraint` (`FK`, `PK`, `UNIQUE`, `CHECK`, `TEMPORAL`, `UNKNOWN`). ### `DependencyState` {#DependencyState} ```python title="signature" class DependencyState(StrEnum): PRESENT = "present" ABSENT = "absent" ``` Dependency graph edge target state (`PRESENT`, `ABSENT`). ### `OnboardingPhase` {#OnboardingPhase} ```python title="signature" class OnboardingPhase(StrEnum): PRE_DDL = "pre_ddl" DDL = "ddl" POST_DDL = "post_ddl" POST_COMMIT = "post_commit" ``` Assimilation workflow phase (`PRE_DDL`, `DDL`, `POST_DDL`, `POST_COMMIT`). ### `RoutineKind` {#RoutineKind} ```python title="signature" class RoutineKind(StrEnum): FUNCTION = "function" PROCEDURE = "procedure" AGGREGATE = "aggregate" WINDOW = "window" ``` PostgreSQL routine kind from `pg_proc.prokind` (`FUNCTION`, `PROCEDURE`, `AGGREGATE`, `WINDOW`). ## Legacy Brownfield Expression Escape Hatches Emitted by `scaffold_models()` only when an existing database `CHECK`, partial index `WHERE`, or `GENERATED ALWAYS AS (...)` expression cannot be represented as a typed `pg.Expr`. ### `legacy_check` {#legacy_check} ```python title="signature" def legacy_check(expr_sql: str) -> Check: ... ``` Wraps a pre-existing brownfield PostgreSQL `CHECK` expression inside `@classmethod def __constraints__(cls)`. ### `legacy_where` {#legacy_where} ```python title="signature" def legacy_where(expr_sql: str) -> LegacyWhere: ... ``` Wraps a pre-existing brownfield PostgreSQL partial-index `WHERE` predicate for `pg.Index(..., where=pgm.legacy_where(...))`. ### `legacy_generated` {#legacy_generated} ```python title="signature" def legacy_generated[T: PgValue](col: Col[T], expr_sql: str) -> Generated: ... ``` Wraps a pre-existing brownfield PostgreSQL `GENERATED ALWAYS AS (...)` expression inside `@classmethod def __generated__(cls)`. --- # CLI Reference Command-line interface for `pgdorm` migrations, drift detection, schema assimilation, and live PostgreSQL compatibility checks (`python -m pgdorm` or `pgdorm`). For guided workflows, see **[The Foreman's Toolkit (CLI & CI)](../migrations/07_cli_and_ci_gates.md)**, [First Shift](../guide/first-shift.md), and [Schema Assimilation](../assimilation/index.md). ## Global Options & Configuration Global options precede the subcommand: ```bash pgdorm [--app MODULE:ATTR] [--config PATH] [--dsn DSN] [--schema SCHEMA] [--ignore-table TABLE ...] [--pool-mode {direct,transaction}] [--json] [subcommand-options] ``` | Flag | Type / Values | Default | Description | | :--- | :--- | :--- | :--- | | `--app` | `module.path:attr` | `[tool.pgdorm].app` | Dotted Python target pointing to a `pg.MigrationApp` (not required for `doctor`, `audit-schema`, `scaffold`). | | `--config` | `PATH` | `./pyproject.toml` | Path to `pyproject.toml` containing `[tool.pgdorm]`. | | `--dsn` | `str` | `$DATABASE_URL` or `[tool.pgdorm].dsn` | PostgreSQL connection DSN. | | `--schema` | `str` | App schema / `public` | Override the target PostgreSQL schema. | | `--ignore-table` | `str` (repeatable) | `[]` | Table name to leave untouched during introspection and diffing. Merged with `app.ignore_tables` and `[tool.pgdorm].ignore_tables`. | | `--pool-mode` | `direct` \| `transaction` | `direct` | Connection pool mode. Use `transaction` behind PgBouncer transaction pooling. | | `--json` | flag | `false` | Emit machine-readable JSON output. | ### Environment Variables & `pyproject.toml` - **`DATABASE_URL`**: Default PostgreSQL DSN when `--dsn` is omitted. Takes precedence over `[tool.pgdorm].dsn`. - **`[tool.pgdorm]`** in `pyproject.toml`: ```toml [tool.pgdorm] app = "myapp.db:migrations" dsn = "postgresql://postgres@localhost:5432/myapp" ignore_tables = ["legacy_audit"] ``` ### Exit Codes | Code | Meaning | | :---: | :--- | | `0` | Success (or clean check with no drift / migratable schema). | | `1` | Configuration error, missing DSN/app, failed `doctor` probe, or `MigrationError`. | | `2` | `drift` detected live `pg_catalog` divergence from the last recorded `_pgdorm` snapshot. | | `3` | `audit-schema` found blocking issues (`migratable == False`). | --- ## Subcommands ### `doctor` Probe live PostgreSQL compatibility without requiring `--app`. Checks server version (`>= 180000`), wire protocol capabilities, and optional write-path features. - `--write-probe`: Also exercise `pg_temp`, `UNNEST`, and `RETURNING OLD/NEW` inside a rolled-back transaction. - `--no-prepared-statements`: Run probes using unnamed statements (for proxies with `max_prepared_statements = 0`). ### `status` Show the latest applied migration in `_pgdorm`, whether live `pg_catalog` has drifted, and the count of pending schema operations. ### `plan` Dry-run the schema diff between live `pg_catalog` and the `MigrationApp` target tables, printing the compiled PostgreSQL DDL steps and lock levels. - `--name` (default `"sync"`): Human-readable name for the planned migration. ### `sync` Zero-file declarative sync: compute the diff, execute online DDL with lock-timeout guards, and record the new snapshot directly in `_pgdorm`. - `--name` (default `"sync"`): Migration name recorded in `_pgdorm`. - `--allow-destructive`: Permit destructive operations (`DROP TABLE`, `DROP COLUMN`, etc.). - `--allow-breaking`: Permit breaking operations (type narrowing, unsafe rewrites). - `--allow-drift`: Proceed even if live `pg_catalog` drifted from the last recorded snapshot. ### `upgrade` Apply code-defined `pg.Migration` values registered on the `MigrationApp` in version order, verifying checksums against `_pgdorm`. - `--allow-destructive`: Permit destructive operations in pending migrations. - `--allow-breaking`: Permit breaking operations in pending migrations. ### `baseline` Adopt an existing live schema into the `_pgdorm` ledger without executing DDL, recording the current catalog snapshot as the initial revision. - `--version` (default `"0000_baseline"`): Baseline version identifier. - `--name` (default `"baseline"`): Baseline migration name. ### `drift` Compare live `pg_catalog` against the last recorded `_pgdorm` snapshot. Exits with code `0` when clean or `2` when drift is detected. ### `history` Print the migration history stored in the `_pgdorm` ledger table. ### `render` Render a code-defined `pg.Migration` Python value from the current schema diff to stdout. - `--version` (default `"0001"`): Migration version string. - `--name` (default `"auto"`): Migration name. - `--var-name` (default `None`): Optional Python variable name for the rendered `Migration` constant. ### `audit-schema` Audit a live PostgreSQL schema for assimilation readiness (works without `--app`). Reports unmanaged views, triggers, routines, enum types, and `TypeTable` candidates. Exits `0` if migratable or `3` if blockers exist. - `--no-definitions`: Omit live SQL definitions for unmanaged views, triggers, and routines from JSON output. ### `scaffold` Introspect a live PostgreSQL schema and generate `pgdorm` `Table` models plus an `AdoptionMap` (works without `--app`). - `--mode` (`assimilate` | `bind`, default `assimilate`): Generate idiomatic `pgdorm` models with rename/modernize mappings (`assimilate`) or bind to existing physical names (`bind`). - `--type-table` (repeatable): Mark specific lookup tables to scaffold as `pg.TypeTable` subclasses. - `--modernize`: Upgrade legacy column types (e.g. `serial` -> `IDENTITY`, `varchar` -> `text`) in the generated models. - `--surrogate-pk` (`bigint` | `uuidv7`, default `bigint`): Surrogate primary key type for tables lacking a compliant `_id` key. - `--out` (`PATH`, default stdout): Write generated Python module to a file instead of stdout. ### `adopt-plan` Validate an `AdoptionMap` against live `pg_catalog` and dry-run the phased assimilation plan with downstream object impact warnings. - `--adoption` (required): Dotted Python target `module.path:attr` pointing to a `pgm.AdoptionMap`. - `--version` (default `"0001_assimilate"`): Version string for the planned adoption migration. - `--name` (default `"assimilate"`): Name for the planned adoption migration. - `--format` (`text` | `json` | `sql`, default `text`): Output format for the plan and impact report. --- # Typing & Testing Reference Public typing primitives in `pgdorm.typing` (strictly types, protocols, and aliases -- zero runtime helper functions) and zero-mock PostgreSQL test helpers in `pgdorm.testing`. For usage guides, see [Testing Your App](../story/20_testing_your_app.md) and [Library Authors](../guide/library-authors.md). --- ## `pgdorm.typing` -- Typing-Only Protocols & Aliases These symbols are exported exclusively from `pgdorm.typing` for static type checking and generic library code. ### `ArrowStreamExportable` {#ArrowStreamExportable} ```python title="signature" class ArrowStreamExportable(Protocol): def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: ... ``` PyCapsule Arrow C Stream Interface protocol implemented by `ArrowStream` and accepted by `Pool.copy_arrow()` / `Transaction.copy_arrow()`. ### `ColBase` {#ColBase} ```python title="signature" class ColBase: @property def qualifier(self) -> str: ... @overload def cast[R: PgValue](self, pg_type: str, *, returns: type[R]) -> Expr[R]: ... @overload def cast(self, pg_type: str, *, returns: None = None) -> Expr[PgValue]: ... def asc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ... def desc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ... ``` Non-generic runtime base class of `Col[T]`, used in generic helper signatures that accept any column descriptor regardless of its Python value type. ### `CopyOnError` {#CopyOnError} ```python title="signature" class CopyOnError(StrEnum): ... ``` `COPY ... (ON_ERROR ...)` error-handling mode. ### `DdlLockMode` {#DdlLockMode} ```python title="signature" class LockMode(IntEnum): NONE = 1 SHARE_UPDATE_EXCLUSIVE = 2 SHARE = 3 SHARE_ROW_EXCLUSIVE = 4 ACCESS_EXCLUSIVE = 5 ``` Lock severity level (`ACCESS_SHARE`, `SHARE_UPDATE_EXCLUSIVE`, `SHARE`, `SHARE_ROW_EXCLUSIVE`, `ACCESS_EXCLUSIVE`) attached to compiled `MigrationStep` entries. ### `DmlStatement` {#DmlStatement} ```python title="signature" type DmlStatement[T: Table = Table, S: Table = Table] = ( Insert[T] | InsertFromSelect[T] | InsertMany[T] | InsertSubtype[T] | Update[T] | Delete[T] | Merge[T, S] ) ``` ### `Generated` {#Generated} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class Generated: col: ColBase expr_sql: str ``` Typed binding returned from `@classmethod def __generated__(cls) -> tuple[Generated, ...]`. ### `TableConstraint` {#TableConstraint} ```python title="signature" type TableConstraint = ( PrimaryKey | Unique | Index | Check | ForeignKey | TemporalPrimaryKey | TemporalUnique | PartitionBy ) ``` Union of all table-level constraint and partitioning descriptors returned from `@classmethod def __constraints__(cls) -> tuple[TableConstraint, ...]`. Union of all write DML statement builders. ### `ExprArg` {#ExprArg} ```python title="signature" type ExprArg = ExprBase | _ToRustValue | ParamRefBase | PgValue ``` Accepted operand type for `pg.func(...)`, `pg.case(...)`, and expression operators. ### `ExprBase` {#ExprBase} ```python title="signature" class ExprBase: def asc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ... def desc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ... @overload def cast[R: PgValue](self, pg_type: str, *, returns: type[R]) -> Expr[R]: ... @overload def cast(self, pg_type: str, *, returns: None = None) -> Expr[PgValue]: ... ``` Non-generic base class of `Expr[T]` and `ValueExpr[T]`. ### `HydrationTarget` {#HydrationTarget} ```python title="signature" type HydrationTarget = type[object] | None ``` Target class accepted by `.into(...)` hydration helpers (slot-backed `Table`, Pydantic `BaseModel`, or dataclass). ### `JsonScalar` {#JsonScalar} ```python title="signature" type JsonScalar = bool | int | float | str | None ``` JSON scalar leaf type used in `JsonValue` and `JsonObject`. ### `ParamRefBase` {#ParamRefBase} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class ParamRefBase: name: str pg_type: str | None = None ``` Base dataclass for named query parameters (`ParamRef[T]` and `UntypedParamRef`). ### `PgScalar` {#PgScalar} ```python title="signature" type PgScalar = ( bool | int | float | str | bytes | bytearray | UUID | date | time | datetime | timedelta | Decimal | IPv4Address | IPv6Address | IPv4Interface | IPv6Interface | Enum | _RangeLike | _ModelDumpable | _DataclassLike | None ) ``` Union of scalar Python types natively encoded/decoded by `pgdorm-wire`. ### `QueryRow` {#QueryRow} ```python title="signature" type QueryRow = Table | ResultRow ``` Row shape returned by `Select[T]` and `RETURNING` projections. ### `RowLockMode` {#RowLockMode} ```python title="signature" class RowLockMode(StrEnum): UPDATE = "update" NO_KEY_UPDATE = "no_key_update" SHARE = "share" KEY_SHARE = "key_share" ``` Row-level locking mode accepted by `Select.for_update(...)` / `.for_share(...)` (alias for `LockMode`). ### `Statement` {#Statement} ```python title="signature" type Statement[T: Table = Table, S: Table = Table, RetT = T] = Select[RetT] | DmlStatement[T, S] ``` Union of all compilable SQL statement builders. ### `TableMeta` {#TableMeta} ```python title="signature" class TableMeta(type): ... ``` Metaclass for `pg.Table` and `pg.TypeTable` that validates schema lint rules, generates `__slots__`, and builds `Col` descriptors. ### `TableRef` {#TableRef} ```python title="signature" class TableRef(Protocol): @property @property def __name__(self) -> str: ... @property def __pg_table__(self) -> str: ... @property def __pg_schema__(self) -> str | None: ... ``` Structural protocol satisfied by `Table` subclasses and `TableAlias` references. ### `UntypedParamRef` {#UntypedParamRef} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class UntypedParamRef(ParamRefBase): ... ``` Parameter reference created by `pg.param("name")` without an explicit Python type argument. ### `ValueExpr` {#ValueExpr} ```python title="signature" class ValueExpr[T]: ... ``` Typed value expression protocol/base shared by `Col[T]` and `Expr[T]`. ### Re-exported Symbols in `pgdorm.typing` All remaining symbols in `pgdorm.typing.__all__` are direct re-exports of public types from `pgdorm` (documented in [Models & Types](models-and-types.md), [Queries & DML](queries-and-dml.md), [Expressions & Functions](expressions-and-functions.md), and [Runtime & Pool](runtime-and-pool.md)) and `pgdorm.migrate` (documented in [Migrations & Assimilation](migrations-and-assimilation.md)). --- ## `pgdorm.testing` -- Zero-Mock Test Helpers `pgdorm` enforces a zero-mock testing pyramid against live PostgreSQL. Import these helpers from `pgdorm.testing` (`testcontainers` is lazily imported via PEP 810). ### `PG18_IMAGE` {#PG18_IMAGE} ```python title="signature" PG18_IMAGE = "postgres:18-alpine" ``` Default Docker image tag used by `postgres_container(...)`. ### `PgContainerInfo` {#PgContainerInfo} ```python title="signature" @dataclass(frozen=True, kw_only=True, slots=True) class PgContainerInfo: major_version: int host: str port: int user: str password: str database: str pgbouncer: bool = False container_id: str | None = None dsn_override: str | None = None pool_mode_override: pgdorm.enums.PoolMode | None = None ``` Immutable connection metadata for a running PostgreSQL test container or external `--dsn` override. ### `SnapshotValue` {#SnapshotValue} ```python title="signature" type SnapshotValue = _SnapshotAtom | Sequence[SnapshotValue] ``` Recursive type of values formatted by the `pgdorm` Syrupy snapshot serializer. ### `TestDB` {#TestDB} ```python title="signature" class TestDB(Pool): ... ``` Test-scoped `Pool` subclass pinned to an isolated PostgreSQL schema (`search_path=schema`). ### `assert_compiles` {#assert_compiles} ```python title="signature" def assert_compiles( stmt: Executable[object], expected_sql: str, *, param_types: Sequence[str] | None = None, search_path: str | None = None, cacheable: bool | None = None, requires_pg19: bool | None = None, ) -> CompiledQuery: ... ``` Compile `stmt` without a database connection and assert exact canonical SQL plus optional `param_types`, `cacheable`, and `requires_pg19` metadata. ### `compile_query` {#compile_query} ```python title="signature" def compile( stmt: Executable[object], *, search_path: str | None = None, ) -> CompiledQuery: ... ``` Re-export of `pgdorm.compile` for pure-unit compilation tests. ### `make_syrupy_extension` {#make_syrupy_extension} ```python title="signature" def make_syrupy_extension() -> type[_SnapshotExtensionProto]: ... ``` Build a `syrupy` `AmberSnapshotExtension` subclass that deterministically serializes `Table`, `Range`, `Enum`, `UUID`, `datetime`, `ExplainPlan`, and `Trace` values and strips ephemeral schema prefixes. ### `normalize_sql_for_docs` {#normalize_sql_for_docs} ```python title="signature" def normalize_sql_for_docs(sql: str) -> str: ... ``` Strip ephemeral per-test schema prefixes (`"t_".` and `"dorm_ro_...".`) from compiled SQL for stable snapshots and documentation. ### `postgres_container` {#postgres_container} ```python title="signature" def postgres_container( *, image: str = PG18_IMAGE, username: str = "postgres", password: str = "pgdorm_test_password", dbname: str = "pgdorm", command: str | None = None, ) -> PostgresContainer: ... ``` Construct a configured `testcontainers` PostgreSQL container (`driver=None`, defaulting to `PG18_IMAGE`). ### `write_or_check_readme` {#write_or_check_readme} ```python title="signature" def write_or_check_readme(readme_path: Path, content: str, *, update: bool, check: bool) -> None: ... ``` Write a generated README when `update=True` (`--update-readmes`) or assert zero drift when `check=True` (`--check-readmes`). --- ## `pgdorm.enums` -- Strict `StrEnum` Option Namespace All discrete ORM choices live under `pg.enums` (`pgdorm.enums`) and are re-exported from `pgdorm.typing`. Bare string literals are rejected both statically and at runtime. ### `enums` {#enums} ```python title="signature" import pgdorm.enums as enums ``` Submodule namespace exposing all strict ORM `StrEnum` option types (`pg.enums.OnDelete.CASCADE`, `pg.enums.PoolMode.TRANSACTION`, `pg.enums.IsolationLevel.SERIALIZABLE`, etc.). ### `ExtractField` {#ExtractField} ```python title="signature" class ExtractField(StrEnum): CENTURY = "CENTURY" DAY = "DAY" DECADE = "DECADE" DOW = "DOW" DOY = "DOY" EPOCH = "EPOCH" HOUR = "HOUR" ISODOW = "ISODOW" ISOYEAR = "ISOYEAR" JULIAN = "JULIAN" MICROSECONDS = "MICROSECONDS" MILLENNIUM = "MILLENNIUM" MILLISECONDS = "MILLISECONDS" MINUTE = "MINUTE" MONTH = "MONTH" QUARTER = "QUARTER" SECOND = "SECOND" TIMEZONE = "TIMEZONE" TIMEZONE_HOUR = "TIMEZONE_HOUR" TIMEZONE_MINUTE = "TIMEZONE_MINUTE" WEEK = "WEEK" YEAR = "YEAR" ``` Closed set of PostgreSQL `EXTRACT(field FROM ...)` field names accepted by `pg.extract(...)`. ### `FrameBoundKind` {#FrameBoundKind} ```python title="signature" class FrameBoundKind(StrEnum): UNBOUNDED_PRECEDING = "unbounded_preceding" CURRENT_ROW = "current_row" UNBOUNDED_FOLLOWING = "unbounded_following" ``` Unbounded/current-row window frame boundary markers (`UNBOUNDED_PRECEDING`, `CURRENT_ROW`, `UNBOUNDED_FOLLOWING`). ### `FrameOffsetDir` {#FrameOffsetDir} ```python title="signature" class FrameOffsetDir(StrEnum): PRECEDING = "preceding" FOLLOWING = "following" ``` Offset direction (`PRECEDING`, `FOLLOWING`) used in `(offset, direction)` window frame bounds. ### `GeneratedMode` {#GeneratedMode} ```python title="signature" class GeneratedMode(StrEnum): VIRTUAL = "virtual" STORED = "stored" ``` Generated column storage mode (`VIRTUAL` or `STORED`) accepted by `pg.generated(...)`. ### `GroupByKind` {#GroupByKind} ```python title="signature" class GroupByKind(StrEnum): EXPR = "expr" ROLLUP = "rollup" CUBE = "cube" GROUPING_SETS = "grouping_sets" ``` `GROUP BY` clause variant (`EXPR`, `ROLLUP`, `CUBE`, `GROUPING_SETS`). ### `IndexOrder` {#IndexOrder} ```python title="signature" class IndexOrder(StrEnum): ASC = "" DESC = "DESC" ASC_NULLS_FIRST = "ASC NULLS FIRST" DESC_NULLS_LAST = "DESC NULLS LAST" ``` Canonical B-tree index column sort direction and `NULLS` ordering. ### `OnCommit` {#OnCommit} ```python title="signature" class OnCommit(StrEnum): DELETE_ROWS = "delete_rows" DROP = "drop" ``` Temporary staging table `ON COMMIT` behavior (`DELETE_ROWS`, `DROP`). ### `OnDelete` {#OnDelete} ```python title="signature" class OnDelete(StrEnum): NO_ACTION = "no_action" RESTRICT = "restrict" CASCADE = "cascade" SET_NULL = "set_null" SET_DEFAULT = "set_default" ``` Foreign-key `ON DELETE` referential action (`NO_ACTION`, `RESTRICT`, `CASCADE`, `SET_NULL`, `SET_DEFAULT`). ### `PartitionStrategy` {#PartitionStrategy} ```python title="signature" class PartitionStrategy(StrEnum): RANGE = "range" LIST = "list" HASH = "hash" ``` Declarative table partitioning strategy (`RANGE`, `LIST`, `HASH`). ### `SearchOrder` {#SearchOrder} ```python title="signature" class SearchOrder(StrEnum): DEPTH = "depth" BREADTH = "breadth" ``` Recursive CTE `SEARCH DEPTH/BREADTH FIRST` traversal order. ### `SetOpKind` {#SetOpKind} ```python title="signature" class SetOpKind(StrEnum): UNION = "union" UNION_ALL = "union_all" INTERSECT = "intersect" INTERSECT_ALL = "intersect_all" EXCEPT = "except" EXCEPT_ALL = "except_all" ``` SQL set-operation combinator kind (`UNION`, `UNION_ALL`, `INTERSECT`, `INTERSECT_ALL`, `EXCEPT`, `EXCEPT_ALL`). --- # Glossary Every PostgreSQL and `pgdorm` term used across **The Elephant Dormitory**, grouped by layer for quick lookup. ## Schema & Modeling CTI (Class-Table Inheritance) : Polymorphic modeling where a shared base table (`task`) holds common columns and each subtype (`cleaning_task`, `maintenance_task`) lives in its own joined table sharing the same primary key. Enabled via `joined=True`. See [Chapter 7](../story/07_inheritance_payments_tasks.md). Discriminator : A column identifying which subtype a polymorphic row belongs to. `pgdorm` forbids string discriminators: `pg.discriminator(...)` must reference a `TypeTable` primary key, and variants must be `IntEnum` members. See [Chapter 7](../story/07_inheritance_payments_tasks.md). Exclusion constraint / `WITHOUT OVERLAPS` (GiST) : A native PostgreSQL temporal constraint (`PRIMARY KEY (room_id, stay WITHOUT OVERLAPS)` or `UNIQUE (... WITHOUT OVERLAPS)`) backed by a GiST index (scalar key columns use the `btree_gist` extension, which pgdorm installs for you) that forbids overlapping ranges for the same key. Violations raise `ExclusionViolationError` (`23P01`). See [Chapter 6](../story/06_temporal_bookings.md). Partial index : An index with a `WHERE` predicate (for example `WHERE out_of_service IS FALSE`) that indexes only the active subset of rows, staying smaller and faster. See [Chapter 4](../story/04_column_types_and_ddl.md). RLS (Row-Level Security) : Database-enforced per-row access policies (`USING` for reads, `WITH CHECK` for writes) evaluated inside PostgreSQL on every query. Paired with `local_settings=` in `pgdorm` for 1-RTT, PgBouncer-safe multi-tenancy. See [Chapter 14](../story/14_multitenancy_rls.md). STI (Single-Table Inheritance) : Polymorphic modeling where all variants (`CardPayment`, `BankTransfer`, `VoucherPayment`) live in one table guarded by a `TypeTable` discriminator and auto-generated disjoint `CHECK` constraints. See [Chapter 7](../story/07_inheritance_payments_tasks.md). `TypeDecorator` : A reusable column codec subclassing `pg.TypeDecorator[PyT, DbT]` that transforms values automatically on bind (`process_bind_param`) and hydration (`process_result_value`), such as `LowerEmail`. See [Chapter 4](../story/04_column_types_and_ddl.md). `TypeTable` : A small lookup table auto-generated and seeded from a Python `IntEnum`, using an `INTEGER` PK and a unique `code` column. Enforced by real foreign keys instead of raw strings. See [Chapter 4](../story/04_column_types_and_ddl.md). `UNSET` (`pg.UNSET`) : Sentinel distinguishing "field omitted in PATCH" from `None` (deliberate SQL `NULL`). Prevents partial updates from wiping existing columns. See [Chapter 2](../story/02_patch_and_returning.md). `UUIDv7` (`pg.uuidv7()`) : Time-ordered UUID built natively into PostgreSQL, combining unguessable public identifiers with B-tree index locality. See [Chapter 4](../story/04_column_types_and_ddl.md). Virtual generated column : Default mode for `GENERATED ALWAYS AS (...) VIRTUAL` in PostgreSQL, computed on read with zero disk storage (`Guest.full_name`). Contrast with `mode=pg.enums.GeneratedMode.STORED` (`Charge.amount`). See [Chapter 4](../story/04_column_types_and_ddl.md). ## Queries, Joins & Analytics CTE (Common Table Expression) : A named temporary result set inside a single SQL statement (`WITH ... AS (...)`). `pgdorm` supports both standard CTEs, writable CTEs (used automatically for 1-RTT CTI inserts), and typed `WITH RECURSIVE` CTEs with `SEARCH` and `CYCLE`. See [Chapter 12](../story/12_hierarchy_regions_cte.md). Data-Modifying CTE (`WriteCte`) : A PostgreSQL writable `WITH` clause (`WITH claimed AS (UPDATE ... RETURNING ...)`) built via `pg.write_cte(...)` that executes a mutation and feeds its `RETURNING` rows directly into a downstream `SELECT`, `INSERT`, `UPDATE`, or `DELETE` in a single statement. See [Field Note 6](../story/field_notes_search_json_and_dml.md). Keyset pagination : Cursor-based pagination using row-value comparisons such as `(last_name, guest_id) > ($1, $2)` so page 10,000 hits a B-tree index in O(log N) time instead of scanning and discarding rows like `OFFSET`. See [Chapter 9](../story/09_keyset_pagination_plans.md). Lateral Subquery (`Select.join_lateral`) : A correlated `JOIN LATERAL (...) ON TRUE` subquery that can reference columns from preceding `FROM` items, enabling O(W|K) index-backed Top-K per group without scanning the full detail table. See [Field Note 6](../story/field_notes_search_json_and_dml.md). `MERGE ... RETURNING` : PostgreSQL statement that atomically updates matching target rows and inserts non-matching rows from a source table (such as a `pg_temp` staging table), returning `merge_action()` (`INSERT`/`UPDATE`) plus `OLD` and `NEW` values in one statement. See [Chapter 13](../story/13_staging_and_merge_import.md). Prepared-statement shape stability (`= ANY($1)` / `UNNEST`) : Keeping one canonical SQL text regardless of list or batch length so PostgreSQL parses, plans, and caches **one** prepared statement and produces stable log and `pg_stat_statements` entries (including for bulk inserts, which `IN`-list squashing does not cover). See [Chapter 3](../story/03_bulk_insert_and_upsert.md). `RETURNING OLD/NEW` : Native PostgreSQL clause allowing `UPDATE`, `DELETE`, and `MERGE` to return both the previous (`pg.old(...)`) and updated (`pg.new(...)`) values of a row in a single round trip. See [Chapter 2](../story/02_patch_and_returning.md). `SKIP LOCKED` : Row-locking modifier (`FOR UPDATE SKIP LOCKED`) that skips rows currently locked by another transaction instead of blocking, turning an ordinary PostgreSQL table into a concurrent work queue. See [Chapter 8](../story/08_transactions_locks_queue.md). `split_load()` : `pgdorm`'s eager-loading helper that loads parent rows in RTT 1 and pipelines all child relation queries (`= ANY($1)`) in RTT 2 under a single `REPEATABLE READ` snapshot -- zero N+1 and zero Cartesian bloat. See [Chapter 5](../story/05_joins_and_folios.md). ## Wire Protocol, Hydration & Pooling Arrow C Stream (`__arrow_c_stream__`) : A standard zero-copy C interface for streaming columnar Apache Arrow `RecordBatch`es between Python libraries (`pgdorm`, Polars, DuckDB, PyArrow) without converting rows into Python objects or CSVs. See [Chapter 16](../story/16_arrow_polars_analytics.md) and [Chapter 17](../story/17_arrow_duckdb_lakehouse.md). Direct Slot Hydration : Decoding PostgreSQL v3 binary wire cells straight into CPython `tp_alloc` + `Py_tp_descr_set` slot descriptors in a single pass without intermediate Rust `Value` trees, Python attribute dictionaries, or tuple call frames. See [Field Note 5](../story/field_notes_wire_and_json.md). ETL / ELT / EtLT : Three patterns for moving data into a database or warehouse: **ETL** transforms data before loading (e.g., Polars -> `copy_from_arrow()`), **ELT** loads raw data first and transforms inside PostgreSQL SQL (`pipe.stage()` + `pg.merge()`), and **EtLT** runs lightweight pre-load cleanup/typing (`on_error="ignore"` or Polars) before heavy SQL transforms. See [Chapter 13](../story/13_staging_and_merge_import.md) and [Chapter 17](../story/17_arrow_duckdb_lakehouse.md). PgBouncer (`pool_mode=pg.enums.PoolMode.TRANSACTION`) : A lightweight PostgreSQL connection pooler that assigns a server connection only for the duration of one transaction. Requires transaction-scoped settings (`set_config(..., true)`) and `ON COMMIT DROP` temp tables. See [Chapter 13](../story/13_staging_and_merge_import.md) and [Chapter 14](../story/14_multitenancy_rls.md). Pipeline (`pool.pipeline()` / `tx.pipeline()`) : Sending multiple PostgreSQL extended-query messages (`Parse`/`Bind`/`Execute`) in one TCP write before a single `Sync`, completing all statements -- including lazy `BEGIN` and `COMMIT` -- in **1 RTT**. See [Chapter 10](../story/10_pipelining_prepared_stream.md). Reverse ETL : Moving curated analytical outputs (audit records, scores, customer segments, pricing tiers) from an analytical engine or lakehouse (DuckDB, Parquet, Polars) *back* into an operational PostgreSQL OLTP database -- done zero-CSV in `pgdorm` via `copy_from_arrow()` (append) or `pg_temp` staging + `pg.merge()` (upsert). See [Chapter 17](../story/17_arrow_duckdb_lakehouse.md). RTT (Round Trip Time) : One full network exchange between your application and PostgreSQL. Counted explicitly in tests with `pool.trace()` (`assert tr.rtts == 1`). See [Prologue](../story/00_prologue.md) and [Chapter 10](../story/10_pipelining_prepared_stream.md). Server JSON Aggregation (`pool.json(..., mode="server")`) : Wrapping a compiled query in PostgreSQL `row_to_json` / `json_agg` (OID `114` binary `json`) so the database emits a ready-to-forward UTF-8 JSON payload in 1 RTT, minimizing client CPU instructions. See [Field Note 5](../story/field_notes_wire_and_json.md) and [Chapter 18](../story/18_web_api_and_telemetry.md). ## Migrations & Assimilation Online migration : Schema evolution broken into lock-friendly steps (`CREATE INDEX CONCURRENTLY`, `ADD CONSTRAINT ... NOT VALID`, `VALIDATE CONSTRAINT`) guarded by `lock_timeout` / `statement_timeout` so production reads and writes stay unblocked. Provided by `pgdorm.migrate`. See [Chapter 19](../story/19_online_migrations.md).