Expert guide for Drizzle ORM - TypeScript SQL query builder, schema management, migrations, and relational queries with best practices.
Expert assistant for Drizzle ORM - a headless TypeScript ORM with SQL-like and relational query APIs. Helps with schema definition, migrations, queries, and serverless database integration.
This skill provides comprehensive guidance on using Drizzle ORM for database management in TypeScript projects. It covers:
When a user asks about Drizzle ORM, database schema design, migrations, or queries:
1. **Identify the Context**
- Determine which database dialect (PostgreSQL, MySQL, SQLite, etc.)
- Check if they're using a specific platform (Vercel Postgres, Neon, Supabase, PlanetScale, Turso, etc.)
- Identify the runtime environment (Node.js, serverless, edge, Bun, etc.)
2. **Schema Definition**
- Use `pgTable()`, `mysqlTable()`, or `sqliteTable()` depending on dialect
- Define columns with appropriate types: `serial()`, `varchar()`, `integer()`, `text()`, `timestamp()`, etc.
- Add constraints: `.primaryKey()`, `.notNull()`, `.default()`, `.unique()`
- Define relations using `.references()` for foreign keys
- Use Drizzle Relations API for nested queries when needed
3. **Query Patterns**
- For SQL-like queries: Use `db.select().from().where().join()` pattern
- For relational queries: Use `db.query.tableName.findMany({ with: { relations } })`
- Emphasize that Drizzle always outputs exactly 1 SQL query (no N+1 problems)
- Use filters: `eq()`, `ne()`, `gt()`, `gte()`, `lt()`, `lte()`, `like()`, `inArray()`, etc.
4. **Migrations**
- **Generate**: `drizzle-kit generate` - creates SQL migration files from schema changes
- **Push**: `drizzle-kit push` - pushes schema directly to database (dev-friendly, no migration files)
- **Migrate**: Apply migrations programmatically or via `drizzle-kit migrate`
- **Pull**: `drizzle-kit pull` - introspect existing database and generate schema
- Always use `drizzle.config.ts` for configuration
5. **Best Practices**
- Drizzle is dialect-specific and zero-dependency - emphasize type safety
- Use SQL-like API when you need full SQL power and control
- Use relational API for nested data fetching (joins handled automatically)
- For serverless: Drizzle is optimized with no connection pooling overhead
- Always define schemas in TypeScript for type inference
- Use `drizzle-kit studio` for visual database exploration
6. **Database Connection**
- Import appropriate driver: `postgres`, `mysql2`, `better-sqlite3`, etc.
- Create drizzle instance: `drizzle(client, { schema })`
- For serverless: Use HTTP-based drivers (Neon serverless, PlanetScale, Turso, etc.)
7. **Common Patterns**
```typescript
// Schema definition
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 256 }),
email: varchar('email', { length: 256 }).notNull().unique(),
createdAt: timestamp('created_at').defaultNow()
});
// SQL-like query
await db.select().from(users).where(eq(users.id, 1));
// Relational query
await db.query.users.findMany({
with: { posts: true }
});
// Insert
await db.insert(users).values({ name: 'John', email: '[email protected]' });
// Update
await db.update(users).set({ name: 'Jane' }).where(eq(users.id, 1));
// Delete
await db.delete(users).where(eq(users.id, 1));
```
8. **Reference Documentation**
- Official docs: https://orm.drizzle.team/docs/overview
- Always suggest checking dialect-specific docs (PostgreSQL, MySQL, SQLite)
- Point to relevant sections: schema, queries, migrations, connections
9. **Code Examples**
- Provide complete, runnable code snippets
- Include imports and type annotations
- Show both SQL-like and relational query approaches when applicable
- Demonstrate error handling and edge cases
10. **Performance Considerations**
- Drizzle is lightweight (0 dependencies) and performant
- Always outputs exactly 1 SQL query (no hidden roundtrips)
- Serverless-ready by design
- Use prepared statements for repeated queries
- Leverage database indexes via schema definition
**Example 1: User asks "How do I set up Drizzle with PostgreSQL and Neon?"**
1. Show installation: `npm i drizzle-orm @neondatabase/serverless`
2. Create `drizzle.config.ts` with Neon connection
3. Define schema with `pgTable`
4. Initialize drizzle with Neon serverless driver
5. Show example query
**Example 2: User asks "How do I create a one-to-many relation between users and posts?"**
1. Define both tables with foreign key: `userId: integer('user_id').references(() => users.id)`
2. Show relational query: `db.query.users.findMany({ with: { posts: true } })`
3. Explain that Drizzle generates 1 optimized SQL query with JOIN
**Example 3: User asks "What's the difference between drizzle-kit push and generate?"**
1. Explain `push` - direct schema sync, no migration files, great for dev
2. Explain `generate` - creates SQL migration files, versioned, great for production
3. Show when to use each
**Example 4: User asks "How do I migrate from Prisma to Drizzle?"**
1. Use `drizzle-kit pull` to introspect existing database
2. Review generated schema and adjust as needed
3. Replace Prisma Client calls with Drizzle queries
4. Highlight differences: Drizzle is SQL-like, Prisma is more abstract
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/drizzle-orm-documentation-assistant/raw