Drizzle ORM Overview
Introduction
Drizzle is a lightweight TypeScript ORM (Object-Relational Mapper) for SQL databases. Designed for type safety and developer experience, it provides:
- Type-safe SQL query builder
- Schema declaration in TypeScript
- Automatic migrations
- Minimal runtime overhead
- Support for PostgreSQL, MySQL, SQLite, and Cloudflare D1
Key Features
1. Type-Safe SQL
// Example query
const users = await db.select().from(usersTable).where(eq(usersTable.age, 25));
// users is typed as User[]
2. Schema Declaration
// schema.ts
import { pgTable, serial, text } from 'drizzle-orm/pg-core';
const usersTable = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: text('email').unique()
});
3. Migrations
# Generate migrations
npx drizzle-kit generate:pg
4. Raw SQL Support
await db.execute(sql`SELECT * FROM users WHERE age > ${18}`);
Comparison with Prisma
Feature | Drizzle | Prisma |
---|---|---|
Type Safety | Query-level types | Model-level types |
Schema Definition | TypeScript-first | Prisma Schema Language |
Runtime Size | 15-20KB | 2-3MB |
Query Builder | SQL-like syntax | Object-based syntax |
Transactions | Explicit | Interactive/Implicit |
Basic Usage
- Installation
npm install drizzle-orm postgres
npm install -D drizzle-kit
- Define Schema
// schema.ts
export const postsTable = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content')
});
- Query Data
const results = await db
.select({
postTitle: postsTable.title,
author: usersTable.name
})
.from(postsTable)
.leftJoin(usersTable, eq(postsTable.authorId, usersTable.id));
When to Use Drizzle
- Need direct SQL control with type safety
- Building lightweight applications
- Prefer TypeScript-first approach
- Require minimal abstraction layer