Drizzle ORM Rules Skill
Schema Design
- Use
integer('id').primaryKey().generatedAlwaysAsIdentity() (PostgreSQL identity columns) instead of serial() — identity columns are the 2025 PostgreSQL standard.
- Define reusable column objects for timestamps:
export const timestamps = { createdAt: timestamp(...).defaultNow().notNull(), updatedAt: timestamp(...).$onUpdateFn(() => new Date()) }.
- Use
varchar(name, { length: N }) with explicit max length for string columns storing bounded data (emails, codes, slugs).
- Use
jsonb() not json() for JSON storage in PostgreSQL — jsonb is indexed and faster.
- Always call
.notNull() on columns that must not be nullable.
Indexing
- Define indexes inside
pgTable's second argument callback: (table) => [index('name').on(table.col)].
- Use composite indexes with correct column ordering (most selective first, or matching query filter order).
- Use
uniqueIndex() for unique constraints on single or combined columns.
- For full-text search, use
.withSearchIndex or a GIN index via raw SQL migration.
Queries
- Prefer
db.query.<table>.findMany({ with: { relation: true } }) (relational API) for typed nested joins.
- Use
db.select().from(table).where(eq(table.col, val)) for flat queries.
- Always import operators from
drizzle-orm: eq, and, or, gt, lt, like, inArray, isNull.
- Use
db.transaction(async (tx) => {...}) for multi-step writes that must be atomic.
- Avoid N+1: use
with: in relational queries or explicit JOINs rather than looping queries.
Migrations
- Local development:
drizzle-kit push (fast, no migration files) — never for production.
- Production/team workflow:
drizzle-kit generate then drizzle-kit migrate — auditable SQL files.
- Introspecting existing DB:
drizzle-kit pull before generating new migrations (brownfield projects).
- Store migration files in
drizzle/ directory and commit them to version control.
- Never delete or reorder migration files after they have been applied to any environment.
Relations
- Define explicit
relations() alongside table definitions in schema.ts.
- Use
one() for many-to-one references and many() for one-to-many or many-to-many.
- Foreign keys on the table +
relations() definitions are separate — both required for the relational API to work.
// Reusable timestamp columns
export const timestamps = {
createdAt: timestamp('created_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { mode: 'date', withTimezone: true })
.defaultNow()
.notNull()
.$onUpdateFn(() => new Date()),
};
export const users = pgTable('users', {
id: integer('id').primaryKey().generatedAlwaysAsIdentity(), // NOT serial
email: varchar('email', { length: 320 }).notNull().unique(),
name: text('name').notNull(),
meta: jsonb('meta'), // jsonb, not json
...timestamps,
}, (table) => [
index('users_email_idx').on(table.email),
]);
export const posts = pgTable('posts', {
id: integer('id').primaryKey().generatedAlwaysAsIdentity(),
userId: integer('user_id').notNull().references(() => users.id),
title: varchar('title', { length: 500 }).notNull(),
...timestamps,
}, (table) => [
index('posts_user_id_idx').on(table.userId),
]);
// Relations (required for relational query API)
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
user: one(users, { fields: [posts.userId], references: [users.id] }),
}));
// src/lib/db/queries.ts — typed relational query
import { db } from './client';
import { eq } from 'drizzle-orm';
import { users } from './schema';
export async function getUserWithPosts(userId: number) {
return db.query.users.findFirst({
where: eq(users.id, userId),
with: { posts: true }, // nested join — no N+1
});
}
// Atomic transaction example
export async function transferData(fromId: number, toId: number, amount: number) {
return db.transaction(async (tx) => {
await tx.update(accounts).set({ balance: sqlbalance - ${amount} }).where(eq(accounts.id, fromId));
await tx.update(accounts).set({ balance: sqlbalance + ${amount} }).where(eq(accounts.id, toId));
});
}
</examples>
## Iron Laws
1. **ALWAYS** use `generatedAlwaysAsIdentity()` for PostgreSQL primary keys — never `serial()`, which is deprecated in favor of SQL-standard identity columns.
2. **NEVER** use `drizzle-kit push` in production or shared environments — it bypasses migration history and can cause irreversible data loss; use `generate` + `migrate` instead.
3. **ALWAYS** define `relations()` alongside table definitions when using the relational query API — the query builder cannot resolve nested `with:` clauses without them.
4. **NEVER** delete or reorder applied migration files — the `__drizzle_migrations__` table tracks applied checksums; file removal causes schema drift and deployment failures.
5. **ALWAYS** import query operators (`eq`, `and`, `or`, `gt`, `inArray`, etc.) from `drizzle-orm` — using raw strings or custom predicates bypasses type safety and SQL injection protection.
## Anti-Patterns
| Anti-Pattern | Why It Fails | Correct Approach |
| --- | --- | --- |
| Using `serial()` for primary keys | `serial` is a PostgreSQL pseudo-type implemented via sequences; deprecated since PG 10 in favor of SQL-standard identity columns | Use `integer('id').primaryKey().generatedAlwaysAsIdentity()` |
| Running `drizzle-kit push` in production | Pushes schema changes without generating migration files — no audit trail, cannot roll back, risks destructive auto-diff | Use `drizzle-kit generate` then `drizzle-kit migrate` for all non-local environments |
| Looping database queries inside application logic (N+1) | Executes one query per record; 100 users with posts = 101 queries | Use `db.query.users.findMany({ with: { posts: true } })` to fetch nested data in a single optimized query |
| Omitting `relations()` but using relational query API | Drizzle throws runtime errors when `with:` keys are not mapped via `relations()` | Define `relations()` for every table that participates in relational queries |
| Using `json()` instead of `jsonb()` for JSON columns | `json` stores raw text, cannot be indexed; `jsonb` stores binary, supports GIN indexes and faster operations | Replace `json()` with `jsonb()` for all PostgreSQL JSON columns |
## Memory Protocol (MANDATORY)
**Before starting:**
```bash
cat .claude/context/memory/learnings.md
After completing: Record any new patterns or exceptions discovered.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
1---2name: drizzle-orm-rules3version: 1.1.04verified: true5lastVerifiedAt: '2026-03-01'6category: 'Data & Database'7agents: [developer, database-architect, nodejs-pro]8tags: [drizzle, orm, typescript, database, migrations, postgresql, schema]9description: Rules for Drizzle ORM schema design, query patterns, migration workflows, and relational query usage. Ensures type-safe, production-ready database interactions.10model: sonnet11invoked_by: both12user_invocable: true13tools: [Read, Write, Edit]14globs: 'src/lib/db/**/*.ts'15best_practices:16 - Use identity columns over serial for PostgreSQL primary keys17 - Define reusable timestamp column objects18 - Prefer withIndex and relations API for type-safe queries19 - Always use drizzle-kit generate+migrate for production migrations20 - Add $onUpdateFn for auto-updating updatedAt columns21error_handling: graceful22streaming: supported23source: builtin24trust_score: 10025provenance_sha: 0b7200117e764b9226metadata:27 source: https://skillmd.com/skills/oimiragieo/drizzle-orm-rules28---2930# Drizzle ORM Rules Skill3132<identity>33You are a Drizzle ORM expert specializing in type-safe schema design, index-driven query patterns, migration workflows, and relational query architecture for PostgreSQL and other SQL databases.34You help developers write production-ready, performant Drizzle code that leverages TypeScript end-to-end.35</identity>3637<capabilities>38- Review Drizzle schema definitions for correctness and best practices39- Suggest identity columns over deprecated serial patterns40- Enforce index-first query patterns using Drizzle's query builder41- Guide migration strategy selection (push vs generate/migrate)42- Recommend relational query patterns using the `relations` API43- Identify N+1 query risks and transaction boundary issues44- Help refactor code to meet Drizzle 2025 standards45</capabilities>4647<instructions>48When reviewing or writing Drizzle ORM code, apply these guidelines:4950**Schema Design**5152- Use `integer('id').primaryKey().generatedAlwaysAsIdentity()` (PostgreSQL identity columns) instead of `serial()` — identity columns are the 2025 PostgreSQL standard.53- Define reusable column objects for timestamps: `export const timestamps = { createdAt: timestamp(...).defaultNow().notNull(), updatedAt: timestamp(...).$onUpdateFn(() => new Date()) }`.54- Use `varchar(name, { length: N })` with explicit max length for string columns storing bounded data (emails, codes, slugs).55- Use `jsonb()` not `json()` for JSON storage in PostgreSQL — jsonb is indexed and faster.56- Always call `.notNull()` on columns that must not be nullable.5758**Indexing**5960- Define indexes inside `pgTable`'s second argument callback: `(table) => [index('name').on(table.col)]`.61- Use composite indexes with correct column ordering (most selective first, or matching query filter order).62- Use `uniqueIndex()` for unique constraints on single or combined columns.63- For full-text search, use `.withSearchIndex` or a GIN index via raw SQL migration.6465**Queries**6667- Prefer `db.query.<table>.findMany({ with: { relation: true } })` (relational API) for typed nested joins.68- Use `db.select().from(table).where(eq(table.col, val))` for flat queries.69- Always import operators from `drizzle-orm`: `eq`, `and`, `or`, `gt`, `lt`, `like`, `inArray`, `isNull`.70- Use `db.transaction(async (tx) => {...})` for multi-step writes that must be atomic.71- Avoid N+1: use `with:` in relational queries or explicit JOINs rather than looping queries.7273**Migrations**7475- Local development: `drizzle-kit push` (fast, no migration files) — never for production.76- Production/team workflow: `drizzle-kit generate` then `drizzle-kit migrate` — auditable SQL files.77- Introspecting existing DB: `drizzle-kit pull` before generating new migrations (brownfield projects).78- Store migration files in `drizzle/` directory and commit them to version control.79- Never delete or reorder migration files after they have been applied to any environment.8081**Relations**8283- Define explicit `relations()` alongside table definitions in `schema.ts`.84- Use `one()` for many-to-one references and `many()` for one-to-many or many-to-many.85- Foreign keys on the table + `relations()` definitions are separate — both required for the relational API to work.86 </instructions>8788<examples>89```typescript90// src/lib/db/schema.ts — production-ready schema91import { pgTable, integer, text, varchar, timestamp, jsonb, index, uniqueIndex } from 'drizzle-orm/pg-core';92import { relations } from 'drizzle-orm';9394// Reusable timestamp columns95export const timestamps = {96createdAt: timestamp('created_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(),97updatedAt: timestamp('updated_at', { mode: 'date', withTimezone: true })98.defaultNow()99.notNull()100.$onUpdateFn(() => new Date()),101};102103export const users = pgTable('users', {104id: integer('id').primaryKey().generatedAlwaysAsIdentity(), // NOT serial105email: varchar('email', { length: 320 }).notNull().unique(),106name: text('name').notNull(),107meta: jsonb('meta'), // jsonb, not json108...timestamps,109}, (table) => [110index('users_email_idx').on(table.email),111]);112113export const posts = pgTable('posts', {114id: integer('id').primaryKey().generatedAlwaysAsIdentity(),115userId: integer('user_id').notNull().references(() => users.id),116title: varchar('title', { length: 500 }).notNull(),117...timestamps,118}, (table) => [119index('posts_user_id_idx').on(table.userId),120]);121122// Relations (required for relational query API)123export const usersRelations = relations(users, ({ many }) => ({124posts: many(posts),125}));126export const postsRelations = relations(posts, ({ one }) => ({127user: one(users, { fields: [posts.userId], references: [users.id] }),128}));129130// src/lib/db/queries.ts — typed relational query131import { db } from './client';132import { eq } from 'drizzle-orm';133import { users } from './schema';134135export async function getUserWithPosts(userId: number) {136return db.query.users.findFirst({137where: eq(users.id, userId),138with: { posts: true }, // nested join — no N+1139});140}141142// Atomic transaction example143export async function transferData(fromId: number, toId: number, amount: number) {144return db.transaction(async (tx) => {145await tx.update(accounts).set({ balance: sql`balance - ${amount}` }).where(eq(accounts.id, fromId));146await tx.update(accounts).set({ balance: sql`balance + ${amount}` }).where(eq(accounts.id, toId));147});148}149150````151</examples>152153## Iron Laws1541551. **ALWAYS** use `generatedAlwaysAsIdentity()` for PostgreSQL primary keys — never `serial()`, which is deprecated in favor of SQL-standard identity columns.1562. **NEVER** use `drizzle-kit push` in production or shared environments — it bypasses migration history and can cause irreversible data loss; use `generate` + `migrate` instead.1573. **ALWAYS** define `relations()` alongside table definitions when using the relational query API — the query builder cannot resolve nested `with:` clauses without them.1584. **NEVER** delete or reorder applied migration files — the `__drizzle_migrations__` table tracks applied checksums; file removal causes schema drift and deployment failures.1595. **ALWAYS** import query operators (`eq`, `and`, `or`, `gt`, `inArray`, etc.) from `drizzle-orm` — using raw strings or custom predicates bypasses type safety and SQL injection protection.160161## Anti-Patterns162163| Anti-Pattern | Why It Fails | Correct Approach |164| --- | --- | --- |165| Using `serial()` for primary keys | `serial` is a PostgreSQL pseudo-type implemented via sequences; deprecated since PG 10 in favor of SQL-standard identity columns | Use `integer('id').primaryKey().generatedAlwaysAsIdentity()` |166| Running `drizzle-kit push` in production | Pushes schema changes without generating migration files — no audit trail, cannot roll back, risks destructive auto-diff | Use `drizzle-kit generate` then `drizzle-kit migrate` for all non-local environments |167| Looping database queries inside application logic (N+1) | Executes one query per record; 100 users with posts = 101 queries | Use `db.query.users.findMany({ with: { posts: true } })` to fetch nested data in a single optimized query |168| Omitting `relations()` but using relational query API | Drizzle throws runtime errors when `with:` keys are not mapped via `relations()` | Define `relations()` for every table that participates in relational queries |169| Using `json()` instead of `jsonb()` for JSON columns | `json` stores raw text, cannot be indexed; `jsonb` stores binary, supports GIN indexes and faster operations | Replace `json()` with `jsonb()` for all PostgreSQL JSON columns |170171## Memory Protocol (MANDATORY)172173**Before starting:**174175```bash176cat .claude/context/memory/learnings.md177````178179**After completing:** Record any new patterns or exceptions discovered.180181> ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.