Overview
Drizzle ORM is a lightweight TypeScript ORM that feels like writing SQL. It provides type-safe schema definitions, automatic migrations, and a query builder that maps 1:1 to SQL.
Capabilities
- Type-safe schema definitions with Drizzle schema language
- Automatic migration generation with Drizzle Kit
- Select, insert, update, delete with full type inference
- Relations API for one-to-one, one-to-many, many-to-many
- Transactions and batch operations
- Support for PostgreSQL, MySQL, SQLite, Turso, D1
When to Use
Trigger phrases:
"drizzle orm"
"Drizzle ORM — type-safe SQL, schema definitions, migrations, queries, relations "
Building TypeScript/Node.js backends with SQL databases
Need type safety without heavy ORM overhead
Want SQL-like syntax instead of Active Record patterns
Working with edge databases (D1, Turso, Neon)
When NOT to Use
- Task is about deployment, not development (use deploy skills)
- Task is about code review, not writing (use review skills)
- You need to understand existing code first (use research skills)
- Task is about testing only (use test skills)
- Requirements are unclear (clarify first)
- Task is trivially simple (single line fix)
Pseudo Code
The drizzle-orm workflow follows a standard pipeline pattern.
Core flow:
# drizzle-orm primary flow
input = prepare(raw_data)
result = process(input, config={definitions, drizzle, migrations, node, orm})
validate(result)
deliver(result)
Error handling:
on error:
log(error_details)
retry_with_backoff(max=3)
if still_failing: alert_and_escalate()
Schema Definition
import { pgTable, serial, text, integer, timestamp } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').notNull().unique(),
createdAt: timestamp('created_at').defaultNow(),
});
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
authorId: integer('author_id').references(() => users.id),
});
Queries
import { eq, and, desc } from 'drizzle-orm';
import { db } from './db';
import { users, posts } from './schema';
// Select
const allUsers = await db.select().from(users);
const user = await db.select().from(users).where(eq(users.id, 1));
// Insert
await db.insert(users).values({ name: 'Alice', email: 'alice@example.com' });
// Update
await db.update(users).set({ name: 'Bob' }).where(eq(users.id, 1));
// Delete
await db.delete(users).where(eq(users.id, 1));
// Join
const result = await db
.select({ userName: users.name, postTitle: posts.title })
.from(users)
.leftJoin(posts, eq(users.id, posts.authorId))
.orderBy(desc(users.createdAt))
.limit(10);
Relations
import { relations } from 'drizzle-orm';
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));
// Query with relations
const usersWithPosts = await db.query.users.findMany({
with: { posts: true },
});
Migrations
# Generate migration
npx drizzle-kit generate
# Apply migration
npx drizzle-kit migrate
# Push schema directly (dev only)
npx drizzle-kit push
# Open studio
npx drizzle-kit studio
Transactions
await db.transaction(async (tx) => {
const user = await tx.insert(users).values({ name: 'Alice' }).returning();
await tx.insert(posts).values({ title: 'Hello', authorId: user[0].id });
});
Common Patterns
- drizzle.config.ts: Configure schema path, output dir, DB driver
- Connection pooling: Use with Neon serverless, PgBouncer, or Hyperdrive
- Edge deployment: Works with Cloudflare D1, Turso, Neon serverless driver
- Seeding: Create seed scripts using the same schema types
How to Use
- Understand the requirement and existing codebase patterns
- Design the solution with error handling and testability in mind
- Implement incrementally with tests for each change
- Verify against expected outcomes (manual and automated)
- Document usage, edge cases, and integration points
- Review with team before merging to shared branches
Red Flags
- Skipping tests to ship faster: Untested code breaks in production when you least expect it
- No error handling in production code: Unhandled errors crash services and lose user data
- Hardcoded configuration values: Hardcoded values prevent environment switching and leak secrets
- Ignoring security implications: Missing input validation, auth bypasses, and injection vulnerabilities
- Over-engineering simple solutions: Premature abstraction adds complexity without proportional benefit
Verification
Process
- Analyze the task requirements
- Apply domain expertise
- Verify output quality
Anti-Rationalization Table
| Rationalization |
Reality |
| "Tests slow me down" |
Bugs slow you down 10x more. Tests are speed, not overhead. |
| "I will refactor later" |
Technical debt compounds. Refactor as you go. |
| "It works on my machine" |
If it is not in CI, it does not work. Ship proof, not claims. |
1---2name: drizzle-orm3description: Use when drizzle ORM — type-safe SQL, schema definitions, migrations, queries, relations for TypeScript/Node.js. Use when working with drizzle orm.4license: Apache-2.05---6789## Overview1011Drizzle ORM is a lightweight TypeScript ORM that feels like writing SQL. It provides type-safe schema definitions, automatic migrations, and a query builder that maps 1:1 to SQL.1213## Capabilities1415- Type-safe schema definitions with Drizzle schema language16- Automatic migration generation with Drizzle Kit17- Select, insert, update, delete with full type inference18- Relations API for one-to-one, one-to-many, many-to-many19- Transactions and batch operations20- Support for PostgreSQL, MySQL, SQLite, Turso, D12122## When to Use23**Trigger phrases:**24- "drizzle orm"25- "Drizzle ORM — type-safe SQL, schema definitions, migrations, queries, relations "262728- Building TypeScript/Node.js backends with SQL databases29- Need type safety without heavy ORM overhead30- Want SQL-like syntax instead of Active Record patterns31- Working with edge databases (D1, Turso, Neon)3233## When NOT to Use3435- Task is about deployment, not development (use deploy skills)36- Task is about code review, not writing (use review skills)37- You need to understand existing code first (use research skills)38- Task is about testing only (use test skills)39- Requirements are unclear (clarify first)40- Task is trivially simple (single line fix)414243## Pseudo Code4445The drizzle-orm workflow follows a standard pipeline pattern.4647Core flow:48```49# drizzle-orm primary flow50input = prepare(raw_data)51result = process(input, config={definitions, drizzle, migrations, node, orm})52validate(result)53deliver(result)54```5556Error handling:57```58on error:59 log(error_details)60 retry_with_backoff(max=3)61 if still_failing: alert_and_escalate()62```636465### Schema Definition66```typescript67import { pgTable, serial, text, integer, timestamp } from 'drizzle-orm/pg-core';6869export const users = pgTable('users', {70 id: serial('id').primaryKey(),71 name: text('name').notNull(),72 email: text('email').notNull().unique(),73 createdAt: timestamp('created_at').defaultNow(),74});7576export const posts = pgTable('posts', {77 id: serial('id').primaryKey(),78 title: text('title').notNull(),79 authorId: integer('author_id').references(() => users.id),80});81```8283### Queries84```typescript85import { eq, and, desc } from 'drizzle-orm';86import { db } from './db';87import { users, posts } from './schema';8889// Select90const allUsers = await db.select().from(users);91const user = await db.select().from(users).where(eq(users.id, 1));9293// Insert94await db.insert(users).values({ name: 'Alice', email: 'alice@example.com' });9596// Update97await db.update(users).set({ name: 'Bob' }).where(eq(users.id, 1));9899// Delete100await db.delete(users).where(eq(users.id, 1));101102// Join103const result = await db104 .select({ userName: users.name, postTitle: posts.title })105 .from(users)106 .leftJoin(posts, eq(users.id, posts.authorId))107 .orderBy(desc(users.createdAt))108 .limit(10);109```110111### Relations112```typescript113import { relations } from 'drizzle-orm';114115export const usersRelations = relations(users, ({ many }) => ({116 posts: many(posts),117}));118119export const postsRelations = relations(posts, ({ one }) => ({120 author: one(users, { fields: [posts.authorId], references: [users.id] }),121}));122123// Query with relations124const usersWithPosts = await db.query.users.findMany({125 with: { posts: true },126});127```128129### Migrations130```bash131# Generate migration132npx drizzle-kit generate133134# Apply migration135npx drizzle-kit migrate136137# Push schema directly (dev only)138npx drizzle-kit push139140# Open studio141npx drizzle-kit studio142```143144### Transactions145```typescript146await db.transaction(async (tx) => {147 const user = await tx.insert(users).values({ name: 'Alice' }).returning();148 await tx.insert(posts).values({ title: 'Hello', authorId: user[0].id });149});150```151152## Common Patterns153154- **drizzle.config.ts**: Configure schema path, output dir, DB driver155- **Connection pooling**: Use with Neon serverless, PgBouncer, or Hyperdrive156- **Edge deployment**: Works with Cloudflare D1, Turso, Neon serverless driver157- **Seeding**: Create seed scripts using the same schema types158159## How to Use1601611. Understand the requirement and existing codebase patterns1622. Design the solution with error handling and testability in mind1633. Implement incrementally with tests for each change1644. Verify against expected outcomes (manual and automated)1655. Document usage, edge cases, and integration points1666. Review with team before merging to shared branches167168## Red Flags169170- **Skipping tests to ship faster**: Untested code breaks in production when you least expect it171- **No error handling in production code**: Unhandled errors crash services and lose user data172- **Hardcoded configuration values**: Hardcoded values prevent environment switching and leak secrets173- **Ignoring security implications**: Missing input validation, auth bypasses, and injection vulnerabilities174- **Over-engineering simple solutions**: Premature abstraction adds complexity without proportional benefit175176## Verification177178- [ ] Skill output matches expected behavior179180## Process1811821. Analyze the task requirements1832. Apply domain expertise1843. Verify output quality185186## Anti-Rationalization Table187188| Rationalization | Reality |189|---|---|190| "Tests slow me down" | Bugs slow you down 10x more. Tests are speed, not overhead. |191| "I will refactor later" | Technical debt compounds. Refactor as you go. |192| "It works on my machine" | If it is not in CI, it does not work. Ship proof, not claims. |