Drizzle ORM
规则
- 架构定义:在
src/db/schema.ts 中使用 pgTable() / mysqlTable() / sqliteTable()
- 开发阶段:使用
drizzle-kit push 进行快速迭代 — 无需生成迁移文件
- 生产环境:使用
drizzle-kit generate + drizzle-kit migrate 获得可追踪的迁移历史
- 类型安全查询:
db.select().from(users).where(eq(users.email, email)) — 完整的 TypeScript 类型推断
- 关联:使用
relations() 辅助函数定义 — one() 和 many() 用于通过 db.query 进行关联查询
- 预编译语句:
db.select().from(users).where(eq(users.id, sql.placeholder("id"))).prepare() — 在热点路径中复用
- 事务:
db.transaction(async (tx) => { ... }) — 在回调内部使用 tx 而不是 db
- 索引:使用
.index() 内联定义或在表配置中定义 — 在 where 和 orderBy 使用的列上添加
- Drizzle Studio:
npx drizzle-kit studio — 开发期间可视化数据库浏览器
模式
import { pgTable, text, timestamp, uuid, integer } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
export const posts = pgTable("posts", {
id: uuid("id").primaryKey().defaultRandom(),
title: text("title").notNull(),
authorId: uuid("author_id").references(() => users.id).notNull(),
});
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));
const result = await db.query.users.findFirst({
where: eq(users.id, userId),
with: { posts: true },
});
避免
- 在生产环境中使用
drizzle-kit push — 应使用 generate + migrate 进行受追踪的迁移
- 当 Drizzle API 已涵盖时使用原始 SQL — 仅在复杂表达式中使用
sql 模板标签
- 忘记定义
relations() — 没有它们,db.query 关联查询将无法工作
- N+1 查询问题 — 在
db.query 中使用 with 在单个查询中连接关联
- 在外键和筛选列上缺少索引 — Drizzle 不会自动创建它们