name: pitfalls-drizzle-orm description: “Drizzle ORM 模式与迁移安全规则。在定义模式、运行迁移或调试数据库问题时使用。触发条件:Drizzle、schema、migration、db:push、$inferSelect、array column。”
Drizzle ORM 常见陷阱
Drizzle ORM 的常见陷阱与正确模式。
使用时机
- 定义数据库模式
- 运行迁移(db:push)
- 创建插入/选择类型
- 处理数组列
- 审查 Drizzle ORM 代码
工作流程
步骤 1:验证模式类型
检查类型是否正确导出。
步骤 2:检查数组语法
验证数组列使用了正确的语法。
步骤 3:安全测试迁移
切勿在生产环境中更改主键类型。
关键规则
// ❌ 切勿更改主键类型
// serial → varchar 或 varchar → uuid 会破坏迁移
// ✅ 数组列 - 正确语法
allowedTokens: text('allowed_tokens').array() // 正确
// ❌ 错误:array(text('allowed_tokens'))
// ✅ 始终创建插入/选择类型
export type Strategy = typeof strategies.$inferSelect;
export type NewStrategy = typeof strategies.$inferInsert;
// ✅ 使用 drizzle-zod 进行验证
import { createInsertSchema } from 'drizzle-zod';
export const insertStrategySchema = createInsertSchema(strategies);
迁移安全
# 安全模式同步
npm run db:push
# 如果出现数据丢失警告且你确认无误
npm run db:push --force
# 切勿在生产环境中无备份操作
类型推断模式
// ✅ 从模式推断类型
import { strategies } from './schema';
type Strategy = typeof strategies.$inferSelect;
type NewStrategy = typeof strategies.$inferInsert;
// ✅ 结合 Zod 验证
import { createInsertSchema, createSelectSchema } from 'drizzle-zod';
import { z } from 'zod';
const insertSchema = createInsertSchema(strategies);
type StrategyInput = z.infer<typeof insertSchema>;
快速检查清单
- [ ] 未更改主键类型
- [ ] 数组列使用
text().array()语法 - [ ] 为模型导出了插入/选择类型
- [ ] 使用 drizzle-zod 进行验证
- [ ] 迁移在开发环境测试后才部署到生产环境