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.txtinto your agent's context so it follows these rules automatically. For full exception signatures and inheritance, see the Errors & Linters Reference.
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 |
JoinLintError |
Query build (select().join(...)) |
Multiple FKs between two tables, unindexed FK, violated require_using=True |
JoinLintError |
UnsafeDmlError |
Query build (update() / delete()) |
UPDATE or DELETE without .where(...) |
UnsafeDmlError |
QueryBuildError |
Query build | Writable CTE missing .returning(...), invalid GROUP BY / window / expression |
QueryBuildError |
NoResultError / MultipleResultsError |
Wire execution (.one(), .one_or_none()) |
Expected 1 row, got 0 or >1 | Result Cardinality Errors |
RetryablePgError |
Wire execution (40001 / 40P01) |
Serialization failure or deadlock | 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:
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"):
class User(pg.Table):
user_id: pg.Col[int] = pg.pk()
2. Generic id primary key instead of <table_name>_id#
What your AI agent wrote:
class _Guest(pg.Table):
id: pg.Col[int] = pg.pk() # SchemaLintError: expected guest_id
Idiomatic pgdorm fix: Declare <table_name>_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):
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:
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:
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:
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):
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).
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:
# 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):
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:
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 <table_name>_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:
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="..."):
# 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:
# 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:
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.
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:
# 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:
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.