Skip to main content
skill CX Codex

drizzle-orm-patterns — Claude Code skill

Guides Drizzle ORM schema design, typed queries, relations, transactions and migrations. Use it while building database code with a supported dialect.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill drizzle-orm-patterns -a claude-code
Open on GitHub

What drizzle-orm-patterns does

This skill provides Drizzle ORM patterns for schema definitions, CRUD work, relations, joins, aggregations, transactions and Drizzle Kit migrations. It covers PostgreSQL, MySQL, SQLite, MSSQL and CockroachDB.

It selects a dialect-specific table function such as pgTable(), mysqlTable(), sqliteTable() or mssqlTable(). Query examples use db.insert(), db.select(), db.update() and db.delete(), while relations use relations() or defineRelations().

The guidance puts linked writes inside db.transaction() and calls for migration testing before production. tx.rollback() throws an exception, so this is a reason to check try/catch handling. Support for .returning() also varies by database dialect.

What it helps with

  • define tables, columns and schema constraints
  • write typed CRUD queries
  • model one-to-many table relations
  • wrap linked writes in a transaction
  • configure migrations with Drizzle Kit

Example prompts for the agent

  • Create a PostgreSQL user schema with pgTable() and a foreign key.
  • Write a Drizzle ORM query that loads a user with related records.
  • Set up Drizzle Kit migrations for the current schema.

How to install drizzle-orm-patterns

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill drizzle-orm-patterns -a claude-code

2Manually: put the files in place

~/.claude/skills/drizzle-orm-patterns/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/drizzle-orm-patterns/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about drizzle-orm-patterns

How do I install drizzle-orm-patterns in Claude Code?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill drizzle-orm-patterns -a claude-code, then run npx skills add giuseppe-trisciuoglio/developer-kit --skill drizzle-orm-patterns -a claude-code again. The skill file is ~/.claude/skills/drizzle-orm-patterns/SKILL.md.

What does drizzle-orm-patterns do?

It supplies patterns for Drizzle ORM schemas, relations, CRUD operations, joins, transactions and migrations. It also covers indexes, soft deletes, batch operations and pagination.

What should I know about transaction rollback?

tx.rollback() throws an exception. Handle it with try/catch when rollback is part of the expected control flow.

Source text

SKILL.md · MIT
---
name: drizzle-orm-patterns
description: Provides comprehensive Drizzle ORM patterns for schema definition, CRUD operations, relations, queries, transactions, and migrations. Proactively use for any Drizzle ORM development including defining database schemas, writing type-safe queries, implementing relations, managing transactions, and setting up migrations with Drizzle Kit. Supports PostgreSQL, MySQL, SQLite, MSSQL, and CockroachDB.
allowed-tools: Read, Write, Edit, Bash, Grep, Glob
---

# Drizzle ORM Patterns

## Overview

Expert guide for building type-safe database applications with Drizzle ORM. Covers schema definition, relations, queries, transactions, and migrations for all supported databases.

## When to Use

- Defining database schemas with tables, columns, and constraints
- Creating relations between tables (one-to-one, one-to-many, many-to-many)
- Writing type-safe CRUD queries
- Implementing complex joins and aggregations
- Managing database transactions with rollback
- Setting up migrations with Drizzle Kit
- Working with PostgreSQL, MySQL, SQLite, MSSQL, or CockroachDB

## Quick Reference

| Database | Table Function | Import |
|----------|---------------|--------|
| PostgreSQL | `pgTable()` | `drizzle-orm/pg-core` |
| MySQL | `mysqlTable()` | `drizzle-orm/mysql-core` |
| SQLite | `sqliteTable()` | `drizzle-orm/sqlite-core` |
| MSSQL | `mssqlTable()` | `drizzle-orm/mssql-core` |

| Operation | Method | Example |
|-----------|--------|---------|
| Insert | `db.insert()` | `db.insert(users).values({...})` |
| Select | `db.select()` | `db.select().from(users).where(eq(...))` |
| Update | `db.update()` | `db.update(users).set({...}).where(...)` |
| Delete | `db.delete()` | `db.delete(users).where(...)` |
| Transaction | `db.transaction()` | `db.transaction(async (tx) => {...})` |

## Instructions

1. **Identify your database dialect** - Choose PostgreSQL, MySQL, SQLite, MSSQL, or CockroachDB
2. **Define your schema** - Use the appropriate table function (pgTable, mysqlTable, etc.)
3. **Set up relations** - Define relations using `relations()` or `defineRelations()`
4. **Initialize the database client** - Create your Drizzle client with proper credentials
5. **Write queries** - Use the query builder for type-safe CRUD operations
6. **Handle transactions** - Wrap multi-step operations in transactions when needed
7. **Set up migrations** - Configure Drizzle Kit for schema management

## Examples

### Example 1: Basic Schema and Query

```typescript
import { pgTable, serial, text } from 'drizzle-orm/pg-core';
import { drizzle } from 'drizzle-orm/node-postgres';
import { eq } from 'drizzle-orm';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull().unique(),
});

const db = drizzle(process.env.DATABASE_URL);

const [user] = await db.select().from(users).where(eq(users.id, 1));
```

### Example 2: CRUD Operations

```typescript
import { eq } from 'drizzle-orm';

// Insert
const [newUser] = await db.insert(users).values({
  name: 'John',
  email: '[email protected]',
}).returning();

// Update
await db.update(users)
  .set({ name: 'John Updated' })
  .where(eq(users.id, 1));

// Delete
await db.delete(users).where(eq(users.id, 1));
```

### Example 3: Transaction with Rollback

```typescript
await db.transaction(async (tx) => {
  const [from] = await tx.select().from(accounts)
    .where(eq(accounts.userId, fromId));

  if (from.balance < amount) {
    tx.rollback();
  }

  await tx.update(accounts)
    .set({ balance: sql`${accounts.balance} - ${amount}` })
    .where(eq(accounts.userId, fromId));
});
```

See [references/transactions.md](references/transactions.md) for advanced transaction patterns.

## Best Practices

1. **Type Safety**: Always use TypeScript and leverage `$inferInsert` / `$inferSelect`
2. **Relations**: Define relations using the relations() API for nested queries
3. **Transactions**: Use transactions for multi-step operations that must succeed together
4. **Migrations**: Use `generate` + `migrate` in production, `push` for development
5. **Indexes**: Add indexes on frequently queried columns and foreign keys
6. **Soft Deletes**: Use `deletedAt` timestamp instead of hard deletes when possible
7. **Pagination**: Use cursor-based pagination for large datasets
8. **Query Optimization**: Use `.limit()` and `.where()` to fetch only needed data

## Constraints and Warnings

- **Foreign Key Constraints**: Always define references using arrow functions `() => table.column` to avoid circular dependency issues
- **Transaction Rollback**: Calling `tx.rollback()` throws an exception - use try/catch if needed
- **Returning Clauses**: Not all databases support `.returning()` - check your dialect compatibility
- **Batch Operations**: Large batch inserts may hit database limits - chunk into smaller batches
- **Migrations in Production**: Always test migrations in staging before applying to production

## References

### Core Concepts
- **[references/schema-definition.md](references/schema-definition.md)** - Complete schema definition for all databases (PostgreSQL, MySQL, SQLite), column types, indexes, and constraints
- **[references/relations.md](references/relations.md)** - One-to-one, one-to-many, many-to-many relations with v1 and v2 syntax
- **[references/queries-joins-aggregations.md](references/queries-joins-aggregations.md)** - CRUD operations, query operators, joins, aggregations, and pagination

### Advanced Topics
- **[references/transactions.md](references/transactions.md)** - Transaction patterns, rollback handling, nested transactions
- **[references/migrations.md](references/migrations.md)** - Drizzle Kit configuration, CLI commands, migration workflow
- **[references/common-patterns.md](references/common-patterns.md)** - Soft delete, upsert, batch operations, full-text search, audit trails

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

All skills for Data and databases →

From the same set93

shadcn-ui A skill that tells the agent how to install and configure shadcn/ui components: buttons, dialogs, tables, and forms with React Hook Form and Zod. CX Codex +1 22,400installs tailwind-css-patterns A skill that hands your agent ready Tailwind CSS patterns: responsive grids, cards, forms, dark mode. Useful when it styles React, Vue or Svelte components. CX Codex +1 17,700installs nextjs-performance A Next.js optimization skill: Core Web Vitals, images and fonts, caching, streaming, bundle size. Useful when pages feel slow and you need a starting point. CX Codex +1 4,900installs unit-test-bean-validation Provides patterns for testing Jakarta Bean Validation constraints and custom validators in JUnit 5. Helps verify DTO logic without loading Spring context. CX Codex +1 4,900installs react-patterns Teaches your agent React 19 and Next.js App Router patterns: Server Components, Server Actions, useOptimistic, Suspense boundaries. Useful when the app is already on React 19. CX Codex +1 4,800installs tailwind-design-system Creates and orchestrates a design system using Tailwind CSS v4.1+ and shadcn/ui. It defines oklch design tokens, themes via CSS variables, and wraps UI primitives. CX Codex +1 4,500installs spring-boot-test-patterns A skill that gives your agent ready patterns for Spring Boot tests: Mockito unit tests, @DataJpaTest and @WebMvcTest slices, Testcontainers integration. CX Codex +1 4,300installs react-code-review Reviews React components and hooks before merge: composition, hook dependencies, accessibility, TypeScript types. Findings come sorted by severity. CX Codex +1 4,300installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor