Drizzle ORM
Pronounced "Drizzle"
A TypeScript-native ORM that provides complete type safety with SQL-like syntax. Lightweight and optimized for serverless/edge environments, it follows the philosophy "If you know SQL, you know Drizzle."
Pronounced "Drizzle"
A TypeScript-native ORM that provides complete type safety with SQL-like syntax. Lightweight and optimized for serverless/edge environments, it follows the philosophy "If you know SQL, you know Drizzle."
Drizzle ORM is an ORM for TypeScript/JavaScript that appeared in 2022. Unlike Prisma's heavy runtime, it is written in pure TypeScript, so its bundle size is small and its cold start is fast. It provides an API close to SQL syntax, so anyone with SQL knowledge can use it easily, and the generated queries are predictable.
It maps SQL syntax to TypeScript 1:1, preventing the unpredictable query generation caused by ORM abstraction.
| Characteristics | Drizzle | Prisma |
|---|---|---|
| Bundle Size | ~7KB (lightweight) | ~2MB+ (heavy) |
| Cold Start | Fast (suitable for serverless) | Slow (Engine loading) |
| Query Style | SQL-like (predictable) | Prisma Client (abstraction) |
| Schema Definition | TypeScript code | .prisma file |
| Raw SQL | Type Safety Support | $queryRaw (limited) |
| Supported DBs | PostgreSQL, MySQL, SQLite | Supports various DBs |
import { pgTable, serial, text, timestamp, integer, boolean, varchar } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// 사용자 테이블
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', { length: 255 }).notNull().unique(),
name: text('name').notNull(),
role: varchar('role', { length: 20 }).default('user'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
});
// 게시글 테이블
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: varchar('title', { length: 255 }).notNull(),
content: text('content'),
published: boolean('published').default(false),
authorId: integer('author_id').references(() => users.id),
createdAt: timestamp('created_at').defaultNow(),
});
// 댓글 테이블
export const comments = pgTable('comments', {
id: serial('id').primaryKey(),
content: text('content').notNull(),
postId: integer('post_id').references(() => posts.id),
authorId: integer('author_id').references(() => users.id),
createdAt: timestamp('created_at').defaultNow(),
});
// 관계 정의
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
comments: many(comments),
}));
export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
comments: many(comments),
}));import { drizzle } from 'drizzle-orm/node-postgres';
import { eq, and, or, like, desc, asc, sql } from 'drizzle-orm';
import { Pool } from 'pg';
import * as schema from './schema';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool, { schema });
// CREATE - 단일 삽입
async function createUser(email: string, name: string) {
const [user] = await db.insert(schema.users)
.values({ email, name })
.returning();
return user;
}
// CREATE - 다중 삽입
async function createManyPosts(posts: typeof schema.posts.$inferInsert[]) {
return await db.insert(schema.posts)
.values(posts)
.returning();
}
// READ - 조건부 조회
async function getPublishedPosts(authorId?: number) {
return await db.select()
.from(schema.posts)
.where(
and(
eq(schema.posts.published, true),
authorId ? eq(schema.posts.authorId, authorId) : undefined
)
)
.orderBy(desc(schema.posts.createdAt))
.limit(10);
}
// READ - JOIN 쿼리 (SQL-like)
async function getPostsWithAuthor() {
return await db.select({
postId: schema.posts.id,
title: schema.posts.title,
authorName: schema.users.name,
authorEmail: schema.users.email,
})
.from(schema.posts)
.leftJoin(schema.users, eq(schema.posts.authorId, schema.users.id))
.where(eq(schema.posts.published, true));
}
// UPDATE
async function updatePost(postId: number, data: Partial) {
const [updated] = await db.update(schema.posts)
.set({ ...data, updatedAt: new Date() })
.where(eq(schema.posts.id, postId))
.returning();
return updated;
}
// DELETE
async function deletePost(postId: number) {
await db.delete(schema.posts)
.where(eq(schema.posts.id, postId));
} // Drizzle Query API - Prisma-like 문법도 지원
async function getPostWithRelations(postId: number) {
return await db.query.posts.findFirst({
where: eq(schema.posts.id, postId),
with: {
author: true,
comments: {
with: {
author: true,
},
orderBy: [desc(schema.comments.createdAt)],
limit: 10,
},
},
});
}
// 복잡한 필터링
async function searchPosts(query: string, filters: {
published?: boolean;
authorId?: number;
fromDate?: Date;
}) {
return await db.query.posts.findMany({
where: and(
like(schema.posts.title, `%${query}%`),
filters.published !== undefined
? eq(schema.posts.published, filters.published)
: undefined,
filters.authorId
? eq(schema.posts.authorId, filters.authorId)
: undefined,
filters.fromDate
? sql`${schema.posts.createdAt} >= ${filters.fromDate}`
: undefined
),
with: {
author: {
columns: { name: true, email: true },
},
},
orderBy: [desc(schema.posts.createdAt)],
});
}// 트랜잭션
async function transferCredits(fromUserId: number, toUserId: number, amount: number) {
return await db.transaction(async (tx) => {
// 잔액 확인
const [fromUser] = await tx.select()
.from(schema.users)
.where(eq(schema.users.id, fromUserId))
.for('update'); // SELECT FOR UPDATE
if (fromUser.credits < amount) {
throw new Error('Insufficient credits');
}
// 차감
await tx.update(schema.users)
.set({ credits: sql`credits - ${amount}` })
.where(eq(schema.users.id, fromUserId));
// 추가
await tx.update(schema.users)
.set({ credits: sql`credits + ${amount}` })
.where(eq(schema.users.id, toUserId));
return { success: true };
});
}
// 타입 안전한 Raw SQL
async function getPostStats() {
const result = await db.execute<{
author_id: number;
author_name: string;
post_count: number;
avg_comments: number;
}>(sql`
SELECT
u.id as author_id,
u.name as author_name,
COUNT(p.id) as post_count,
AVG(comment_counts.cnt)::numeric as avg_comments
FROM users u
LEFT JOIN posts p ON u.id = p.author_id
LEFT JOIN (
SELECT post_id, COUNT(*) as cnt
FROM comments
GROUP BY post_id
) comment_counts ON p.id = comment_counts.post_id
GROUP BY u.id, u.name
ORDER BY post_count DESC
`);
return result.rows;
}import type { Config } from 'drizzle-kit';
export default {
schema: './src/db/schema.ts',
out: './drizzle',
driver: 'pg',
dbCredentials: {
connectionString: process.env.DATABASE_URL!,
},
} satisfies Config;# Detect schema changes and generate migration files npx drizzle-kit generate:pg # Apply migrations npx drizzle-kit push:pg # Visualize the DB schema (Drizzle Studio) npx drizzle-kit studio # Extract the schema from an existing DB npx drizzle-kit introspect:pgCompared to Prisma, there are fewer plugins, integrations, and tutorials. You may lack reference material for complex cases.
Because the API is close to SQL, there is a learning curve if you don't know SQL. Unlike Prisma, it is hard to get by with the ORM alone, without SQL.
Drizzle Kit supports basic migrations, but, unlike Prisma Migrate, sophisticated downgrade and data migration features are limited.