1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
# Drizzle ORM Claude Code Configuration ๐๏ธ
A comprehensive Claude Code configuration for building type-safe, performant database applications with Drizzle ORM, schema management, migrations, and modern database patterns.
## โจ Features
This configuration provides:
- **Type-safe database operations** with full TypeScript inference
- **Schema management patterns** for scalable database design
- **Migration strategies** with versioning and rollback support
- **Query optimization** with prepared statements and indexing
- **Multi-database support** for PostgreSQL, MySQL, and SQLite
- **Testing approaches** with in-memory databases
- **Performance patterns** for production applications
- **Repository and service patterns** for clean architecture
## ๐ฆ Installation
1. Copy the `.claude` directory to your project root:
```bash
cp -r drizzle/.claude your-project/
cp drizzle/CLAUDE.md your-project/
```
2. Install Drizzle ORM in your project:
```bash
# For PostgreSQL
npm install drizzle-orm @neondatabase/serverless
npm install -D drizzle-kit
# For MySQL
npm install drizzle-orm mysql2
npm install -D drizzle-kit @types/mysql
# For SQLite
npm install drizzle-orm better-sqlite3
npm install -D drizzle-kit @types/better-sqlite3
```
3. The configuration will be automatically loaded when you start Claude Code in your project.
## ๐ฏ What You Get
### Database Expertise
- **Schema Design** - Proper table definitions, relationships, and constraints
- **Migration Management** - Automatic generation, versioning, and deployment
- **Query Optimization** - Efficient queries with proper indexing strategies
- **Type Safety** - Full TypeScript inference from schema to queries
- **Multi-Database Support** - PostgreSQL, MySQL, SQLite configurations
- **Performance Patterns** - Prepared statements, connection pooling, caching
### Key Development Areas
| Area | Coverage |
|------|----------|
| **Schema Design** | Table definitions, relationships, constraints, indexes |
| **Migrations** | Generation, versioning, rollback, seeding |
| **Queries** | CRUD operations, joins, aggregations, pagination |
| **Type Safety** | Full TypeScript inference, compile-time validation |
| **Performance** | Prepared statements, indexes, connection pooling |
| **Testing** | In-memory testing, query mocking, integration tests |
| **Patterns** | Repository pattern, service layer, transaction handling |
| **Deployment** | Environment configuration, production optimizations |
## ๐ Quick Start Examples
### Schema Definition
```typescript
// schema/users.ts
import { pgTable, serial, text, timestamp, boolean } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: text('email').notNull().unique(),
name: text('name').notNull(),
emailVerified: boolean('email_verified').default(false),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
```
### Database Connection
```typescript
// lib/db.ts
import { drizzle } from 'drizzle-orm/neon-http';
import { neon } from '@neondatabase/serverless';
const sql = neon(process.env.DATABASE_URL!);
export const db = drizzle(sql);
```
### Basic Queries
```typescript
// lib/queries/users.ts
import { db } from '@/lib/db';
import { users } from '@/schema/users';
import { eq } from 'drizzle-orm';
export async function createUser(userData: NewUser) {
const [user] = await db.insert(users).values(userData).returning();
return user;
}
export async function getUserById(id: number) {
const user = await db.select().from(users).where(eq(users.id, id));
return user[0];
}
```
### Relations and Joins
```typescript
// schema/posts.ts
import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content').notNull(),
authorId: integer('author_id').references(() => users.id),
});
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
}));
```
## ๐ง Configuration Setup
### Drizzle Config
```typescript
// drizzle.config.ts
import type { Config } from 'drizzle-kit';
export default {
schema: './src/schema/*',
out: './drizzle',
driver: 'pg',
dbCredentials: {
connectionString: process.env.DATABASE_URL!,
},
verbose: true,
strict: true,
} satisfies Config;
```
### Environment Variables
```env
# PostgreSQL (Neon, Railway, Supabase)
DATABASE_URL=postgresql://username:password@host:5432/database
# MySQL (PlanetScale, Railway)
DATABASE_URL=mysql://username:password@host:3306/database
# SQLite (Local development)
DATABASE_URL=file:./dev.db
```
## ๐ ๏ธ Migration Commands
```bash
# Generate migration from schema changes
npx drizzle-kit generate:pg
# Push schema changes to database
npx drizzle-kit push:pg
# Introspect existing database
npx drizzle-kit introspect:pg
# Open Drizzle Studio (database browser)
npx drizzle-kit studio
```
## ๐๏ธ Schema Patterns
### E-commerce Schema
```typescript
// Complete e-commerce database schema
export const products = pgTable('products', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
price: decimal('price', { precision: 10, scale: 2 }).notNull(),
stock: integer('stock').default(0),
categoryId: integer('category_id').references(() => categories.id),
});
export const orders = pgTable('orders', {
id: serial('id').primaryKey(),
userId: integer('user_id').references(() => users.id),
total: decimal('total', { precision: 10, scale: 2 }).notNull(),
status: text('status', {
enum: ['pending', 'processing', 'shipped', 'delivered']
}).default('pending'),
});
```
### Content Management
```typescript
// Blog/CMS schema with full-text search
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content').notNull(),
slug: text('slug').notNull().unique(),
published: boolean('published').default(false),
tags: text('tags').array(),
searchVector: vector('search_vector'), // For full-text search
}, (table) => ({
slugIdx: uniqueIndex('posts_slug_idx').on(table.slug),
searchIdx: index('posts_search_idx').using('gin', table.searchVector),
}));
```
## ๐ Performance Features
### Prepared Statements
```typescript
// High-performance prepared queries
export const getUserByIdPrepared = db
.select()
.from(users)
.where(eq(users.id, placeholder('id')))
.prepare();
// Usage with full type safety
const user = await getUserByIdPrepared.execute({ id: 123 });
```
### Query Optimization
```typescript
// Optimized pagination with count
export async function getPaginatedPosts(page = 1, limit = 10) {
const offset = (page - 1) * limit;
const [posts, totalCount] = await Promise.all([
db.select().from(posts).limit(limit).offset(offset),
db.select({ count: count() }).from(posts),
]);
return { posts, total: totalCount[0].count };
}
```
### Connection Pooling
```typescript
// Production-ready connection pooling
const poolConnection = mysql.createPool({
connectionLimit: 10,
queueLimit: 0,
acquireTimeout: 60000,
timeout: 60000,
});
export const db = drizzle(poolConnection);
```
## ๐งช Testing Support
### Test Database Setup
```typescript
// In-memory testing database
import { drizzle } from 'drizzle-orm/better-sqlite3';
import Database from 'better-sqlite3';
export function createTestDb() {
const sqlite = new Database(':memory:');
const db = drizzle(sqlite);
migrate(db, { migrationsFolder: 'drizzle' });
return db;
}
```
### Query Testing
```typescript
// Comprehensive query testing
describe('User Queries', () => {
let testDb: ReturnType<typeof createTestDb>;
beforeEach(() => {
testDb = createTestDb();
});
it('should create and retrieve user', async () => {
const user = await createUser({ email: 'test@example.com' });
const retrieved = await getUserById(user.id);
expect(retrieved).toEqual(user);
});
});
```
## ๐ Multi-Database Support
### PostgreSQL with Neon
```typescript
import { drizzle } from 'drizzle-orm/neon-http';
import { neon, neonConfig } from '@neondatabase/serverless';
neonConfig.fetchConnectionCache = true;
export const db = drizzle(neon(process.env.DATABASE_URL!));
```
### MySQL with PlanetScale
```typescript
import { drizzle } from 'drizzle-orm/mysql2';
import { connect } from '@planetscale/database';
const connection = connect({
url: process.env.DATABASE_URL
});
export const db = drizzle(connection);
```
### SQLite for Local Development
```typescript
import { drizzle } from 'drizzle-orm/better-sqlite3';
import Database from 'better-sqlite3';
const sqlite = new Database('./dev.db');
export const db = drizzle(sqlite);
```
## ๐ Advanced Features
### Transaction Handling
```typescript
// Safe transaction management
export async function transferFunds(fromId: number, toId: number, amount: number) {
return await db.transaction(async (tx) => {
await tx.update(accounts)
.set({ balance: sql`${accounts.balance} - ${amount}` })
.where(eq(accounts.id, fromId));
await tx.update(accounts)
.set({ balance: sql`${accounts.balance} + ${amount}` })
.where(eq(accounts.id, toId));
});
}
```
### Analytics Queries
```typescript
// Complex analytical queries
export async function getSalesAnalytics() {
return await db
.select({
month: sql`DATE_TRUNC('month', ${orders.createdAt})`,
revenue: sum(orders.total),
orderCount: count(orders.id),
})
.from(orders)
.groupBy(sql`DATE_TRUNC('month', ${orders.createdAt})`)
.orderBy(sql`DATE_TRUNC('month', ${orders.createdAt})`);
}
```
## ๐ Integration
This configuration works excellently with:
- **Next.js 15** - API routes and Server Components
- **Vercel AI SDK** - Chat history and user management
- **shadcn/ui** - Data tables and forms
- **Neon/PlanetScale** - Serverless database platforms
- **Prisma Studio alternative** - Drizzle Studio for database browsing
## ๐ Resources
- [Drizzle ORM Documentation](https://orm.drizzle.team)
- [Drizzle Kit CLI Reference](https://orm.drizzle.team/kit-docs/overview)
- [Schema Declaration Guide](https://orm.drizzle.team/docs/sql-schema-declaration)
- [Query Builder Reference](https://orm.drizzle.team/docs/rqb)
- [Migration Documentation](https://orm.drizzle.team/docs/migrations)
- [Community Discord](https://discord.gg/yfjTbVXMW4)
---
**Ready to build type-safe, performant database applications with Claude Code and Drizzle ORM!**
๐ **Star this configuration** if it accelerates your database development workflow!
|