关于 drizzle-postgres
面向使用 Drizzle ORM 构建类型安全 PostgreSQL 应用的实用参考技能,帮助开发者设计表关系、编写查询、管理迁移并排查性能问题。
主要功能
- 01表结构与关系模式
- 02类型化查询示例
- 03迁移命令指引
- 04查询性能检查
- 05PostgreSQL 参考主题
适用场景
- 01设计一对多或多对多数据关系
- 02用关系查询避免 N+1 查询
- 03生成并应用结构迁移
- 04排查慢查询并优化索引
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ pedronauck/ skills --skill drizzle-postgres安装后在 Claude Code 中输入/drizzle-postgres确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/CHEATSHEET.mdMIGRATIONS.mdPERFORMANCE.mdPOSTGRES.mdQUERIES.mdRELATIONS.mdSCHEMA.md详细介绍
PostgreSQL + Drizzle ORM
使用 PostgreSQL 18 和 Drizzle ORM 构建类型安全的数据库应用。
基本命令
npx drizzle-kit generate # Generate migration from schema changes
npx drizzle-kit migrate # Apply pending migrations
npx drizzle-kit push # Push schema directly (dev only!)
npx drizzle-kit studio # Open database browser
快速决策树
“如何建模这种关系?”
Relationship type?
├─ One-to-many (user has posts) → FK on "many" side + relations()
├─ Many-to-many (posts have tags) → Junction table + relations()
├─ One-to-one (user has profile) → FK with unique constraint
└─ Self-referential (comments) → FK to same table
“为什么我的查询很慢?”
Slow query?
├─ Missing index on WHERE/JOIN columns → Add index
├─ N+1 queries in loop → Use relational queries API
├─ Full table scan → EXPLAIN ANALYZE, add index
├─ Large result set → Add pagination (limit/offset)
└─ Connection overhead → Enable connection pooling
“该用哪个 drizzle-kit 命令?”
What do I need?
├─ Schema changed, need SQL migration → drizzle-kit generate
├─ Apply migrations to database → drizzle-kit migrate
├─ Quick dev iteration (no migration) → drizzle-kit push
└─ Browse/edit data visually → drizzle-kit studio
目录结构
src/db/
├── schema/
│ ├── index.ts # Re-export all tables
│ ├── users.ts # Table + relations
│ └── posts.ts # Table + relations
├── db.ts # Connection with pooling
└── migrate.ts # Migration runner
drizzle/
└── migrations/ # Generated SQL files
drizzle.config.ts # drizzle-kit config
Schema 模式
带时间戳的基本表
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
email: varchar("email", { length: 255 }).notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at").defaultNow().notNull(),
});
带索引的外键
export const posts = pgTable(
"posts",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id),
title: varchar("title", { length: 255 }).notNull(),
},
(table) => [
index("posts_user_id_idx").on(table.userId), // ALWAYS index FKs
],
);
关系
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.userId], references: [users.id] }),
}));
查询模式
关系查询(避免 N+1)
// ✓ Single query with nested data
const usersWithPosts = await db.query.users.findMany({
with: { posts: true },
});
筛选查询
const activeUsers = await db
.select()
.from(users)
.where(eq(users.status, "active"));
事务
await db.transaction(async (tx) => {
const [user] = await tx.insert(users).values({ email }).returning();
await tx.insert(profiles).values({ userId: user.id });
});
性能检查清单
| 优先级 | 检查项 | 影响 |
|---|---|---|
| CRITICAL | 为所有外键创建索引 | 避免 JOIN 时进行全表扫描 |
| CRITICAL | 对嵌套数据使用关系查询 | 避免 N+1 |
| HIGH | 在生产环境中使用连接池 | 降低连接开销 |
| HIGH | 对慢查询使用 EXPLAIN ANALYZE | 找出缺失的索引 |
| MEDIUM | 对筛选后的子集使用部分索引 | 索引更小、速度更快 |
| MEDIUM | PK 使用 UUIDv7(PG18+) | 提高索引局部性 |
反模式(CRITICAL)
| 反模式 | 问题 | 修复方法 |
|---|---|---|
| 没有 FK 索引 | JOIN 缓慢、全表扫描 | 为每个 FK 列添加索引 |
| 循环中的 N+1 | 每行执行一次查询 | 使用 with: 关系查询 |
| 没有连接池 | 每个请求都创建连接 | 使用 @neondatabase/serverless 或类似方案 |
在生产环境中使用 push | 存在数据丢失风险 | 始终使用 generate + migrate |
| 将 JSON 存储为文本 | 无校验,查询效果差 | 使用 jsonb() 列类型 |
参考文档
| 文件 | 用途 |
|---|---|
| references/SCHEMA.md | 列类型、约束 |
| references/QUERIES.md | 运算符、连接、聚合 |
| references/RELATIONS.md | 一对多、多对多 |
| references/MIGRATIONS.md | drizzle-kit 工作流 |
| references/POSTGRES.md | PG18 功能、RLS、分区 |
| references/PERFORMANCE.md | 索引、优化 |
| references/CHEATSHEET.md | 快速参考 |
资源
Drizzle ORM
- 官方文档:https://orm.drizzle.team
- GitHub 仓库:https://github.com/drizzle-team/drizzle-orm
- Drizzle Kit(迁移):https://orm.drizzle.team/kit-docs/overview
PostgreSQL
- 官方文档:https://www.postgresql.org/docs/
- SQL 命令参考:https://www.postgresql.org/docs/current/sql-commands.html
- 性能提示:https://www.postgresql.org/docs/current/performance-tips.html
- 索引类型:https://www.postgresql.org/docs/current/indexes-types.html
- JSON 函数:https://www.postgresql.org/docs/current/functions-json.html
- 行级安全:https://www.postgresql.org/docs/current/ddl-rowsecurity.html
评论
支持 Markdown