Drizzle ORM Schema Style Guide
Adding a Model or Repository? Ship a sibling test in the same PR — every new file under
packages/database/src/models/**orsrc/repositories/**needs a matching__tests__/<name>.test.ts. See the testing skill (.agents/skills/testing/references/db-model-test.md) for thegetTestDB()integration pattern, user-isolation tests, the BM25describe.skipIf(!isServerDB)guard, and schema gotchas. CI's coverage patch gate won't reliably catch a brand-new untested file, so this is on you.
Configuration
- Config:
drizzle.config.ts - Schemas:
packages/database/src/schemas/ - Migrations:
packages/database/migrations/ - Dialect:
postgresqlwithstrict: true
Helper Functions
Location: packages/database/src/schemas/_helpers.ts
timestamptz(name): Timestamp with timezonecreatedAt(),updatedAt(),accessedAt(): Standard timestamp columnstimestamps: Object with all three for easy spread
Naming Conventions
- Tables: Plural snake_case (
users,session_groups) - Columns: snake_case (
user_id,created_at) - New tables: Check nearby existing tables before naming a new one. Preserve
the established noun family and suffix. For example, if the user-scoped table
is
user_xxx_logs, the workspace-scoped counterpart should beworkspace_xxx_logs, notworkspace_xxx_recordsor another new synonym.
Column Definitions
Primary Keys
Do not use auto-incrementing primary keys (serial, bigserial, generated
identity columns). They create sequence-state problems during cross-database
migrations, restores, and data copy jobs. Prefer text IDs from application
generators (idGenerator, createNanoId) or uuid for internal tables.
Keep $defaultFn(...) when a table normally owns ID generation. Callers can
still pass an explicit id; the default only runs when the insert omits it. Do
not remove the default just because one flow needs to supply a request-scoped ID.
ID prefixes make entity types distinguishable. For internal tables, use uuid.
Do not use composite primary keys on new tables. Give every table a single-column
surrogate PK and carry business uniqueness in a uniqueIndex instead. PK columns
cannot be nullable, so when the uniqueness scope later grows by a nullable
dimension the composite PK must be torn down and rebuilt — exactly what happened
when ai_providers / ai_models were workspace-scoped (migrations 0110–0111 replaced
their composite PKs with a surrogate _id plus partial unique indexes). A unique
index still works as the arbiter for onConflictDoUpdate upserts.
Existing composite PKs are legacy — leave them alone unless they block a scope change, then migrate them the 0110–0111 way.
Foreign Keys
Timestamps
Optional and Undefined Values
Do not introduce artificial sentinel strings for missing values, such as
unknown, unless the domain already has that explicit state and existing code
uses it consistently. Prefer nullable columns, optional TypeScript fields, or a
separate concrete status enum when the value is genuinely absent.
Database Enums
Default to not using PostgreSQL/Drizzle pgEnum. Database enums are
expensive to evolve safely: adding members needs migrations, removing or
renaming members is awkward, and deployment order becomes more fragile.
For product/business states, use text() or varchar() with a TypeScript value
type via $type<...>(). Keep those TS-only value types in the domain/shared type
module, then import them into the schema. For cloud DB schemas, that usually
means cloudDB/types.ts.
Do not copy existing DB enums as a pattern. Treat them as legacy or explicitly
reviewed exceptions. If a new pgEnum seems necessary, stop and justify why the
value set is effectively immutable and why the migration cost is acceptable.
Field Descriptions
For columns whose meaning is not obvious from the name alone, add JSDoc on the schema field. Include a concrete example when it clarifies the stored value or the lifecycle moment that writes it. This is especially important for external IDs, lifecycle statuses, denormalized snapshots, JSONB signals, and fields whose name could mean either a request ID or a persisted row ID.
JSONB Types
Avoid Record<string, unknown> or similarly loose JSONB types for schema
columns. Define a concrete interface that describes the expected JSON shape, even
when most properties are optional. This keeps callers, migrations, and review
queries aligned on the same data contract.
A loosely-typed JSONB column is often a symptom of a deeper problem: the column
was reserved speculatively ("for future extension") and nothing actually writes
it. Don't add metadata / extra JSONB columns for hypothetical future needs —
a column earns its place only when a concrete writer ships alongside it. When
review finds such a column, the fix is to delete the column, not to invent
an interface for data that doesn't exist; add a properly-typed column once the
real requirement arrives.
Indexes
Type Inference
Example Pattern
Common Patterns
Junction Tables (Many-to-Many)
The surrogate-PK rule above applies to junction tables too — pair uniqueness
goes in a uniqueIndex, not a composite PK (many existing junction tables
still use composite PKs; that is legacy, not the template):
Query Style
Always use db.select() builder API. Never use db.query.* relational API (findMany, findFirst, with:).
The relational API generates complex lateral joins with json_build_array that are fragile and hard to debug.
Select Single Row
Select with JOIN
Select with Aggregation
Raw SQL and Advanced Queries
Prefer Drizzle builders whenever the query reads clearly with select,
insert().select(), update().from(), joins, CTEs, and groupBy — this keeps
table/column references tied to schema, so changes surface as TypeScript errors.
Within a builder, expression-level sql<T> is fine for features lacking a helper
(JSON path, casts, aggregates, CASE, NOW()). Row locks are clauses, not
expressions — use .for('update'), never raw FOR UPDATE.
Use COALESCE only when null-handling is part of required DB semantics (nullable
JSONB append/merge, "keep first non-null"). Don't scatter
COALESCE(excluded.col, current.col) across ordinary upsert scalars just to avoid
an update object — build set from defined values only, and hide any remaining
SQL behind named helpers (appendJsonbArray, mergeJsonbObject, keepFirstValue)
so the method reads as business intent, not SQL plumbing.
When refactoring raw SQL:
- Preserve query shape on latency-sensitive paths. If raw SQL is one roundtrip,
don't split it into multiple depth-based queries just to drop
execute. - Use
$with(...)+insert().select()/update().from()for multi-step single-roundtrip writes Drizzle can express. - Don't rely on
execute<MyRow>(sql...)for safety — it types rows but doesn't keep selected columns in sync with schema changes. - If only a PostgreSQL feature Drizzle can't express works, keep the raw SQL and tighten it: schema refs in interpolations, explicit user scope, a narrow row interface, and regression tests.
Recursive CTEs are the canonical "keep raw" case — there's no clean WITH RECURSIVE
builder, and a rewrite would add depth-based roundtrips:
One-to-Many (Separate Queries)
When you need a parent record with its children, use two queries instead of relational with::
Database Migrations
See the db-migrations skill for the detailed migration guide.


