drizzle-orm-patterns
giuseppe-trisciuoglio/developer-kit
Type-safe database patterns for Drizzle ORM across PostgreSQL, MySQL, SQLite, MSSQL, and CockroachDB.
What is drizzle-orm-patterns?
Comprehensive guide for building type-safe database applications with Drizzle ORM. Covers schema definition, relations, CRUD operations, transactions, and migrations across multiple database dialects. Use this when designing database schemas, writing queries, managing transactions, or setting up migrations with Drizzle Kit.
- Define schemas with tables, columns, and constraints for PostgreSQL, MySQL, SQLite, MSSQL, and CockroachDB
- Create and query one-to-one, one-to-many, and many-to-many relations between tables
- Write type-safe CRUD operations (insert, select, update, delete) with the query builder
- Implement complex joins, aggregations, and pagination patterns
- Manage database transactions with rollback handling for multi-step operations
- Set up and manage migrations using Drizzle Kit with generate, migrate, and push commands
How to install drizzle-orm-patterns
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill drizzle-orm-patterns- Drizzle ORM installed in your project
- Node.js environment configured
- Database credentials and connection string for your chosen dialect
- Drizzle Kit installed for migration management (optional but recommended)
How to use drizzle-orm-patterns
- 1.Identify your database dialect (PostgreSQL, MySQL, SQLite, MSSQL, or CockroachDB)
- 2.Define your schema using the appropriate table function (pgTable, mysqlTable, sqliteTable, etc.)
- 3.Set up relations between tables using the relations() API
- 4.Initialize your Drizzle database client with connection credentials
- 5.Write type-safe queries using the query builder for CRUD operations
- 6.Wrap multi-step operations in transactions using db.transaction() when consistency is required
- 7.Configure Drizzle Kit and run migrations in development or production
Use cases
- Building a multi-tenant SaaS application with complex relational schemas and transaction-based operations
- Implementing soft-delete patterns and audit trails for compliance-heavy applications
- Setting up cursor-based pagination for large datasets in a REST or GraphQL API
- Managing financial transactions with rollback guarantees across multiple account updates
- Migrating an existing database schema while maintaining type safety throughout the codebase
- Backend developers building Node.js applications with Drizzle ORM
- Full-stack developers managing their own database schemas and migrations
- Teams requiring type-safe database operations with TypeScript
- Database architects designing relational schemas for PostgreSQL, MySQL, SQLite, MSSQL, or CockroachDB
drizzle-orm-patterns FAQ
Drizzle ORM supports PostgreSQL, MySQL, SQLite, MSSQL, and CockroachDB. Each has its own table function (pgTable, mysqlTable, sqliteTable, mssqlTable) and core module import.
Use db.transaction(async (tx) => {...}) to wrap operations. Call tx.rollback() to trigger a rollback, which throws an exception. Use try/catch if you need to handle rollback exceptions gracefully.
Not all databases support .returning() equally. PostgreSQL has full support, but MySQL, SQLite, and MSSQL have varying levels of compatibility. Check your dialect's documentation before relying on it.
push applies schema changes directly to your database (development only), generate creates migration files for version control, and migrate applies generated migrations to production databases.
Always define foreign key references using arrow functions: references(() => otherTable.column) instead of direct references to avoid circular dependency problems.
Full instructions (SKILL.md)
Source of truth, from giuseppe-trisciuoglio/developer-kit.
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
- Identify your database dialect - Choose PostgreSQL, MySQL, SQLite, MSSQL, or CockroachDB
- Define your schema - Use the appropriate table function (pgTable, mysqlTable, etc.)
- Set up relations - Define relations using
relations()ordefineRelations() - Initialize the database client - Create your Drizzle client with proper credentials
- Write queries - Use the query builder for type-safe CRUD operations
- Handle transactions - Wrap multi-step operations in transactions when needed
- Set up migrations - Configure Drizzle Kit for schema management
Examples
Example 1: Basic Schema and Query
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
import { eq } from 'drizzle-orm';
// Insert
const [newUser] = await db.insert(users).values({
name: 'John',
email: 'john@example.com',
}).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
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 for advanced transaction patterns.
Best Practices
- Type Safety: Always use TypeScript and leverage
$inferInsert/$inferSelect - Relations: Define relations using the relations() API for nested queries
- Transactions: Use transactions for multi-step operations that must succeed together
- Migrations: Use
generate+migratein production,pushfor development - Indexes: Add indexes on frequently queried columns and foreign keys
- Soft Deletes: Use
deletedAttimestamp instead of hard deletes when possible - Pagination: Use cursor-based pagination for large datasets
- Query Optimization: Use
.limit()and.where()to fetch only needed data
Constraints and Warnings
- Foreign Key Constraints: Always define references using arrow functions
() => table.columnto 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 - Complete schema definition for all databases (PostgreSQL, MySQL, SQLite), column types, indexes, and constraints
- references/relations.md - One-to-one, one-to-many, many-to-many relations with v1 and v2 syntax
- references/queries-joins-aggregations.md - CRUD operations, query operators, joins, aggregations, and pagination
Advanced Topics
- references/transactions.md - Transaction patterns, rollback handling, nested transactions
- references/migrations.md - Drizzle Kit configuration, CLI commands, migration workflow
- references/common-patterns.md - Soft delete, upsert, batch operations, full-text search, audit trails
Related skills
More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

dynamodb-toolbox-patterns
TypeScript patterns for type-safe DynamoDB access with DynamoDB-Toolbox v2 and AWS SDK v3.

gemini
Delegate large-context analysis and complex reasoning tasks to Gemini 3.0 Flash or Pro models via CLI.

github-issue-workflow
Guided 8-phase workflow for resolving GitHub issues from description to pull request in Claude Code.

graalvm-native-image
Expert guidance for building GraalVM Native Image executables from Java applications.

knowledge-graph
Persistent JSON knowledge graph for caching codebase analysis and validating task dependencies.

langchain4j-ai-services-patterns
Build type-safe, declarative AI services in Java with LangChain4j using interface patterns and annotations.