Drizzle ORM 是「schema 用 TypeScript 寫、查詢長得像 SQL、遷移檔是可直接讀的純 SQL」的 ORM。它沒有 runtime 程式碼產生器、不需要 prisma generate,型別直接從 schema 推導;代價是你要願意理解 SQL。這篇從零建一個 SQLite 商店資料庫,把每一步的實際輸出貼出來。
一、先講定位:它解決什麼問題
多數 ORM 的取捨長這樣:要嘛型別安全但 SQL 被藏起來(查效能時很痛苦),要嘛貼近 SQL 但查詢結果是 any。Drizzle 走第三條路——查詢 API 幾乎是 SQL 的語法樹,select().from().where().orderBy() 編譯出來就是你能預期的 SQL,而且型別一路傳到結果。
| 面向 | Drizzle 的做法 | 常見痛點 |
|---|---|---|
| Schema 定義 | TypeScript 檔案(sqliteTable(...)) | 不需要額外 DSL 或 .prisma 檔 |
| 型別來源 | 直接從 schema 推導 | 沒有「產生 client」這一步,也就沒有忘了產生而型別過期的問題 |
| 遷移 | drizzle-kit generate 產出 .sql + meta | 遷移檔進 git、可以 code review,也可以手改 |
| 查詢 | 鏈式 API,與 SQL 一一對應 | 需要基本 SQL 知識(巢狀子查詢要用 sql 片段) |
| 執行方式 | 驅動決定同步或非同步 | better-sqlite3 是同步、Postgres 是非同步,寫法要分清楚 |
這篇用的版本(2026-12-01 於 Node 22.22.0 實測):drizzle-orm 0.45.4、drizzle-kit 0.31.11、better-sqlite3 13.2.0。
二、安裝與專案結構
mkdir shop && cd shop && npm init -y
npm install drizzle-orm better-sqlite3
npm install -D drizzle-kit tsx typescript
shop/
├── drizzle.config.ts
├── drizzle/ # 產生的遷移檔(進 git)
│ ├── 0000_xxx.sql
│ └── meta/
├── src/
│ ├── schema.ts # schema 唯一真相來源
│ └── demo.ts
└── shop.db # SQLite 檔(不進 git)
drizzle.config.ts 只有四個關鍵欄位:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'sqlite',
schema: './src/schema.ts',
out: './drizzle',
dbCredentials: { url: './shop.db' },
});
dialect 換成 postgresql 或 mysql 就是另一個資料庫,schema 檔案幾乎不用改寫法(欄位型別要換)。
三、Schema:四個表+關聯
import { sqliteTable, text, integer, real, index, uniqueIndex } from 'drizzle-orm/sqlite-core';
import { relations, sql } from 'drizzle-orm';
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
email: text('email').notNull().unique(),
name: text('name').notNull(),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
});
export const products = sqliteTable(
'products',
{
id: integer('id').primaryKey({ autoIncrement: true }),
sku: text('sku').notNull(),
name: text('name').notNull(),
priceCents: integer('price_cents').notNull(),
stock: integer('stock').notNull().default(0),
tags: text('tags', { mode: 'json' }).$type<string[]>().default([]),
rating: real('rating'),
},
(t) => ({
skuIdx: uniqueIndex('products_sku_idx').on(t.sku),
priceIdx: index('products_price_idx').on(t.priceCents),
})
);
export const orders = sqliteTable('orders', {
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
status: text('status', { enum: ['pending', 'paid', 'shipped', 'cancelled'] }).notNull().default('pending'),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
});
export const orderItems = sqliteTable('order_items', {
id: integer('id').primaryKey({ autoIncrement: true }),
orderId: integer('order_id').notNull().references(() => orders.id, { onDelete: 'cascade' }),
productId: integer('product_id').notNull().references(() => products.id),
qty: integer('qty').notNull().default(1),
unitPriceCents: integer('unit_price_cents').notNull(),
});
三個實務重點:
mode: 'timestamp':SQLite 沒有原生時間型別,這個設定讓Date物件自動轉成 Unix 秒數儲存,讀出來再轉回Date。實測寫入後讀到的是2026-12-01T18:03:41.000Z,不是數字。mode: 'json'+$type<string[]>():欄位實際存 TEXT,但 TypeScript 端是string[],寫入讀出都自動 JSON 序列化。- 關聯要另外宣告(
relations()),它只影響「關聯查詢 API」,不影響資料庫的 FOREIGN KEY:
export const usersRelations = relations(users, ({ many }) => ({ orders: many(orders) }));
export const ordersRelations = relations(orders, ({ one, many }) => ({
user: one(users, { fields: [orders.userId], references: [users.id] }),
items: many(orderItems),
}));
export const orderItemsRelations = relations(orderItems, ({ one }) => ({
order: one(orders, { fields: [orderItems.orderId], references: [orders.id] }),
product: one(products, { fields: [orderItems.productId], references: [products.id] }),
}));
四、產生遷移:先看它寫了什麼
npx drizzle-kit generate
輸出(實測):
4 tables
order_items 5 columns 0 indexes 2 fks
orders 4 columns 0 indexes 1 fks
products 7 columns 2 indexes 0 fks
users 4 columns 1 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0000_boring_felicia_hardy.sql 🚀
檔名是隨機取的(0000_boring_felicia_hardy),想可讀一點可以用 npx drizzle-kit generate --name init_shop。產生的 SQL 就是純 SQL,沒有魔法:
CREATE TABLE `products` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`sku` text NOT NULL,
`name` text NOT NULL,
`price_cents` integer NOT NULL,
`stock` integer DEFAULT 0 NOT NULL,
`tags` text DEFAULT '[]',
`rating` real
);
CREATE UNIQUE INDEX `products_sku_idx` ON `products` (`sku`);
CREATE INDEX `products_price_idx` ON `products` (`price_cents`);
orders 的外鍵也照著寫出來:
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
這裡有個容易漏的設定:SQLite 預設不強制外鍵。要真的生效必須在連線時執行
PRAGMA foreign_keys = ON;,否則onDelete: 'cascade'只是寫好玩的。
五、套用遷移
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import { migrate } from 'drizzle-orm/better-sqlite3/migrator';
import * as schema from './schema';
const sqlite = new Database('./shop.db');
sqlite.pragma('journal_mode = WAL');
sqlite.pragma('foreign_keys = ON');
const db = drizzle(sqlite, { schema }); // 要傳 schema,關聯查詢才認得 relations
migrate(db, { migrationsFolder: './drizzle' });
跑完之後資料庫會多一張 __drizzle_migrations 表記錄已套用的版本。實測查詢結果:
cols: id,sku,name,price_cents,stock,tags,rating
migrations: { c: 1 }
開發階段也可以用 npx drizzle-kit push 直接把 schema 同步到資料庫(不產遷移檔),適合本機反覆實驗;正式環境請用 generate + migrate,因為 push 沒有版本紀錄、無法 rollback、也無法 code review。
六、查詢:先看編譯出來的 SQL
Drizzle 的除錯友善之處是 .toSQL(),任何查詢都能先看它要送什麼:
const q1 = db.select().from(products)
.where(gt(products.priceCents, 1000))
.orderBy(desc(products.priceCents));
console.log(q1.toSQL().sql);
console.log(q1.toSQL().params);
實際輸出:
select "id", "sku", "name", "price_cents", "stock", "tags", "rating" from "products" where "products"."price_cents" > ? order by "products"."price_cents" desc
params: [ 1000 ]
rows: [ '27 吋螢幕 8990', '機械鍵盤 3290', '無線滑鼠 1290' ]
參數是預處理佔位符(?),不是字串拼接——SQL injection 的防線在這一層,不需要自己 escape。
七、關聯查詢(RQB):一個實際踩到的陷阱
Drizzle 的關聯查詢 API(Relational Query Builder)可以直接把巢狀結構拉出來:
const orderList = await db.query.orders.findMany({
with: { user: true, items: { with: { product: true } } },
orderBy: (o, { desc }) => [desc(o.id)],
});
for (const o of orderList) {
const total = o.items.reduce((s, it) => s + it.qty * it.unitPriceCents, 0);
console.log(`order#${o.id} ${o.user.name} ${o.status} items=${o.items.length} total=${total}`);
}
實測輸出:
order#3 Dennis pending items=0 total=0
order#2 Amy shipped items=1 total=8990
order#1 Dennis paid items=2 total=4070
陷阱一:better-sqlite3 驅動下,findMany() 不是回傳陣列。 直接寫 for (const o of db.query.orders.findMany({...})) 會得到:
TypeError: orderList is not iterable
原因:它回傳的是 SQLiteSyncRelationalQuery 物件,原型上只有 sync 一個方法。修法有兩種——加 await(本文寫法),或明確呼叫 .sync():
const rows = db.query.orders.findMany({ with: { user: true } }).sync();
同步驅動卻要 await,看起來很怪,但這是 Drizzle 為了讓同一套 API 能跨同步/非同步驅動的設計。實測 await 之後拿到的是正常的陣列(長度 3)。
八、聚合:count() 被 JOIN 放大
這是 SQL 的老問題,Drizzle 不會幫你擋。先看錯誤示範:
const wrong = db.select({
name: users.name,
orderCount: count(orders.id),
})
.from(users)
.leftJoin(orders, eq(orders.userId, users.id))
.leftJoin(orderItems, eq(orderItems.orderId, orders.id))
.groupBy(users.id)
.all();
實測結果:
[ { name: 'Dennis', orderCount: 3 }, // 錯:Dennis 只有 2 張訂單
{ name: 'Amy', orderCount: 1 },
{ name: 'Bob', orderCount: 0 } ]
Dennis 只有 2 張訂單,卻算出 3。原因是 JOIN order_items 之後,訂單 #1(2 個品項)被展開成 2 列,count(orders.id) 數的是結果列數不是訂單數。修法:
import { countDistinct } from 'drizzle-orm';
const agg = db.select({
name: users.name,
orderCount: countDistinct(orders.id),
revenue: sum(sql`${orderItems.qty} * ${orderItems.unitPriceCents}`).mapWith(Number),
})
.from(users)
.leftJoin(orders, eq(orders.userId, users.id))
.leftJoin(orderItems, eq(orderItems.orderId, orders.id))
.groupBy(users.id)
.all();
實測輸出:
[ { name: 'Dennis', orderCount: 2, revenue: 4070 },
{ name: 'Amy', orderCount: 1, revenue: 8990 },
{ name: 'Bob', orderCount: 0, revenue: null } ]
revenue 那段有兩個細節:sum() 在 SQLite 回傳字串型別,要 .mapWith(Number) 才是數字;而沒有訂單的 Bob 是 null 不是 0,畫面顯示時要自己 ?? 0。
九、交易:第二個實際踩到的陷阱
下單扣庫存這種事一定要包交易。直覺寫法(把參數直接傳給 transaction callback)會壞掉:
// ✗ 錯誤:Drizzle 只把 tx 傳進 callback,額外參數不會轉發
db.transaction((userId, productId, qty) => {
const p = tx.select().from(products).where(eq(products.id, productId)).get();
// ↑ tx 未定義;而且 productId 其實是 undefined
});
實測錯誤訊息是 Error: product not found——看起來像資料不存在,其實是 productId 收到 undefined(callback 的第一個參數被 tx 佔走,第二、三個參數根本沒傳進來)。better-sqlite3 原生 API 會轉發額外參數,Drizzle 的包裝不會,這個差異很容易讓人卡住。
正確寫法是外層包一個箭頭函式:
const placeOrder = (userId: number, productId: number, qty: number) =>
db.transaction((tx) => {
const p = tx.select().from(products).where(eq(products.id, productId)).get();
if (!p) throw new Error('product not found');
if (p.stock < qty) throw new Error(`庫存不足:只剩 ${p.stock}`);
const [order] = tx.insert(orders).values({ userId, status: 'paid' }).returning().all();
tx.insert(orderItems).values({ orderId: order.id, productId, qty, unitPriceCents: p.priceCents }).run();
tx.update(products).set({ stock: p.stock - qty }).where(eq(products.id, productId)).run();
return order;
});
實測行為:
成功下單 id: 4
回滾訊息: 庫存不足:只剩 5
螢幕庫存未被扣: 5
Bob 的訂單數(失敗那筆未寫入): 1
第二筆故意下 999 台螢幕,拋錯後整筆交易回滾——訂單沒有寫入、庫存也沒被扣。這就是包交易的意義:把「檢查庫存 → 建訂單 → 扣庫存」變成一個原子操作。
十、JSON 欄位、預處理語句與索引實測
JSON 欄位查詢可以直接用 SQLite 的 json_extract:
const jsonRows = db.select({
name: products.name,
firstTag: sql<string>`json_extract(${products.tags}, '$[0]')`,
})
.from(products)
.where(sql`json_extract(${products.tags}, '$[0]') = '周邊'`)
.all();
// [ { name: '機械鍵盤', firstTag: '周邊' }, { name: '無線滑鼠', firstTag: '周邊' } ]
但要注意:
json_extract用不到一般索引。標籤這種「多值」查詢在 SQLite 的正解是 FTS5 或正規化成一張product_tags表。
預處理語句適合放進迴圈或高頻路徑:
const stmt = db.select({ sku: products.sku, price: products.priceCents })
.from(products)
.where(inArray(products.sku, ['KB-001', 'CB-004']))
.prepare();
stmt.all(); // [ { sku: 'CB-004', price: 390 }, { sku: 'KB-001', price: 3290 } ]
索引有沒有生效,Drizzle 在 better-sqlite3 驅動沒有 .explain()(那是 Postgres/MySQL 才有的方法),實務做法是把 toSQL() 的結果丟給 SQLite 自己解釋:
const built = db.select().from(products).where(eq(products.priceCents, 8990)).toSQL();
sqlite.prepare(`EXPLAIN QUERY PLAN ${built.sql}`).all(built.params);
實測輸出:
SEARCH products USING INDEX products_price_idx (price_cents=?)
換成模糊搜尋就原形畢露:
EXPLAIN QUERY PLAN SELECT * FROM products WHERE name LIKE '%滑鼠%'
→ SCAN products
LIKE '%…%' 開頭帶萬用字元一定全表掃描——這跟有沒有用 ORM 無關,是 SQLite 的限制。要做中文站內搜尋請走 FTS5 或外掛搜尋引擎,不要硬凹 LIKE。
十一、改 schema:加欄位只要一行
把 description 加進 products 後重跑 generate:
npx drizzle-kit generate
# [✓] Your SQL migration file ➜ drizzle/0001_amusing_bishop.sql 🚀
ALTER TABLE `products` ADD `description` text;
套用後實測 PRAGMA table_info(products):
cols: id,sku,name,price_cents,stock,tags,rating,description
migrations: { c: 2 }
這就是 Drizzle 遷移工作流的價值:schema 改動 → 產生差異 SQL → 進 code review → 套用。每一步都能被人讀懂,而不是一個黑盒 diff。
十二、常見錯誤對照表
| 症狀 | 原因 | 修法 |
|---|---|---|
TypeError: xxx is not iterable | 把 db.query.*.findMany() 當陣列用 | 加 await 或 .sync() |
product not found(參數明明有傳) | db.transaction((tx) => ...) 不轉發額外參數 | 外層包箭頭函式,參數走閉包 |
關聯查詢回空、db.query 不存在 | 建立 drizzle() 時沒傳 { schema } | drizzle(sqlite, { schema }) |
onDelete: cascade 沒作用 | SQLite 預設關閉外鍵 | 連線時 PRAGMA foreign_keys = ON |
| 統計數字比預期大 | JOIN 後 count() 數到展開的列 | 改 countDistinct() |
sum() 拿到字串 / 型別不對 | 驅動回傳字串 | .mapWith(Number) |
| 遷移檔名很醜看不懂 | 隨機命名 | generate --name <描述> |
| 正式環境資料表結構和程式碼不同步 | 用了 push 沒留遷移檔 | 正式環境只走 generate + migrate |
十三、誰適合、誰不適合
適合:已經懂 SQL、想要型別安全但不想被 ORM 綁住查詢能力的人;需要把遷移檔進 git 做 review 的團隊;同時要接 SQLite/Postgres/MySQL 的專案(換方言的成本主要在欄位型別)。
不適合:完全不想碰 SQL 的人(Drizzle 的子查詢、sql 片段、.toSQL() 除錯都需要基本 SQL 底子);需要「用圖形介面看資料模型」的團隊(Drizzle Studio 有,但生態比 Prisma 小);想用大量現成 adapter 的專案。
一句話總結:Drizzle 不是「幫你寫 SQL 的框架」,而是「讓你用 TypeScript 寫 SQL 的框架」。這個定位決定了它的學習曲線,也決定了它適不適合你。
站內延伸閱讀
- SQLite 完整教學 2026:JSONB、FTS5 與 Python 實戰,本文用到的底層特性都在這篇
- DuckDB 教學:分析型查詢的另一條路線,跟 SQLite 的分工怎麼切
- Bun 完整教學 2026:用 Bun 內建 SQLite 驅動接 Drizzle 的另一種組合
本文所有程式碼與輸出於 2026-12-01 在 Node 22.22.0 + drizzle-orm 0.45.4 + drizzle-kit 0.31.11 + better-sqlite3 13.2.0 環境實測,SQLite 檔為本機建立、資料為自建測試資料。正式環境請以官方文件為準。
