Drizzle ORM: Type-safe Database Access
Tại sao chọn Drizzle ORM?
Drizzle ORM là một thư viện TypeScript ORM tập trung vào sự đơn giản, hiệu năng và Type-safety tuyệt đối. Khác với Prisma, Drizzle không cần một engine chạy ngầm (binary), giúp giảm kích thước bundle và thời gian khởi động (Cold start) trên Serverless.
Thiết lập Schema
Bạn định nghĩa Database Schema hoàn toàn bằng code TypeScript:
import { pgTable, serial, text, varchar, timestamp } from "drizzle-orm/pg-core";
export const users = pgTable('users', {
id: serial('id').primaryKey(),
fullName: text('full_name'),
phone: varchar('phone', { length: 256 }),
createdAt: timestamp('created_at').defaultNow(),
});Truy vấn dữ liệu (Querying)
Drizzle cung cấp hai cách truy vấn: SQL-like (cho người thích SQL) và Relational API (giống Prisma).
SQL-like API:
const allUsers = await db.select().from(users).where(eq(users.id, 1));Relational API:
const userWithPosts = await db.query.users.findFirst({
with: {
posts: true,
},
});Ưu điểm so với Prisma
| Tính năng | Drizzle ORM | Prisma |
|---|---|---|
| Runtime | TypeScript thuần | Rust-based Engine |
| Cold Start | Cực nhanh | Chậm hơn (Serverless) |
| Migrations | SQL files | Prisma Migrate |
| Type-safety | Tự động từ Schema | Code-generation |
Drizzle Kit
Để quản lý migration, hãy sử dụng Drizzle Kit. Nó sẽ so sánh Schema của bạn và tạo ra các file .sql tương ứng.
npx drizzle-kit generate:pg
npx drizzle-kit push:pgMẹo: Kết hợp Drizzle với Turso (SQLite) hoặc Neon (PostgreSQL) là lựa chọn hoàn hảo cho các ứng dụng Edge Computing hiện nay.