postgres-drizzle by ccheney/robust-skills
npx skills add https://github.com/ccheney/robust-skills --skill postgres-drizzle使用 PostgreSQL 18 和 Drizzle ORM 构建类型安全的数据库应用。
npx drizzle-kit generate # 根据模式变更生成迁移文件
npx drizzle-kit migrate # 应用待处理的迁移
npx drizzle-kit push # 直接推送模式(仅限开发环境!)
npx drizzle-kit studio # 打开数据库浏览器
关系类型?
├─ 一对多(用户拥有帖子) → 在“多”侧设置外键 + relations()
├─ 多对多(帖子拥有标签) → 连接表 + relations()
├─ 一对一(用户拥有个人资料) → 带唯一约束的外键
└─ 自引用(评论) → 指向同一表的外键
查询慢?
├─ WHERE/JOIN 列上缺少索引 → 添加索引
├─ 循环中存在 N+1 查询 → 使用关系查询 API
├─ 全表扫描 → 使用 EXPLAIN ANALYZE,添加索引
├─ 结果集过大 → 添加分页(limit/offset)
└─ 连接开销 → 启用连接池
我需要什么?
├─ 模式已更改,需要 SQL 迁移 → drizzle-kit generate
├─ 将迁移应用到数据库 → drizzle-kit migrate
├─ 快速开发迭代(无需迁移) → drizzle-kit push
└─ 可视化浏览/编辑数据 → drizzle-kit studio
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
src/db/
├── schema/
│ ├── index.ts # 重新导出所有表
│ ├── users.ts # 表 + 关系
│ └── posts.ts # 表 + 关系
├── db.ts # 带连接池的连接
└── migrate.ts # 迁移运行器
drizzle/
└── migrations/ # 生成的 SQL 文件
drizzle.config.ts # drizzle-kit 配置
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), // 始终为外键建立索引
]);
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.userId], references: [users.id] }),
}));
// ✓ 包含嵌套数据的单次查询
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 });
});
| 优先级 | 检查项 | 影响 |
|---|---|---|
| 关键 | 为所有外键建立索引 | 防止 JOIN 操作时的全表扫描 |
| 关键 | 对嵌套数据使用关系查询 | 避免 N+1 问题 |
| 高 | 在生产环境中使用连接池 | 减少连接开销 |
| 高 | 对慢查询使用 EXPLAIN ANALYZE | 识别缺失的索引 |
| 中 | 为过滤子集使用部分索引 | 更小、更快的索引 |
| 中 | 主键使用 UUIDv7(PG18+) | 更好的索引局部性 |
| 反模式 | 问题 | 修复方法 |
|---|---|---|
| 外键无索引 | JOIN 慢,全表扫描 | 为每个外键列添加索引 |
| 循环中的 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 | 快速参考 |
每周安装量
365
仓库
GitHub 星标数
22
首次出现
2026年1月21日
安全审计
安装于
opencode321
codex310
gemini-cli301
github-copilot295
kimi-cli247
cursor247
Type-safe database applications with PostgreSQL 18 and 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
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
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] }),
}));
// ✓ 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 });
});
| Priority | Check | Impact |
|---|---|---|
| CRITICAL | Index all foreign keys | Prevents full table scans on JOINs |
| CRITICAL | Use relational queries for nested data | Avoids N+1 |
| HIGH | Connection pooling in production | Reduces connection overhead |
| HIGH | EXPLAIN ANALYZE slow queries | Identifies missing indexes |
| MEDIUM | Partial indexes for filtered subsets | Smaller, faster indexes |
| MEDIUM | UUIDv7 for PKs (PG18+) | Better index locality |
| Anti-Pattern | Problem | Fix |
|---|---|---|
| No FK index | Slow JOINs, full scans | Add index on every FK column |
| N+1 in loops | Query per row | Use with: relational queries |
| No pooling | Connection per request | Use @neondatabase/serverless or similar |
push in prod | Data loss risk | Always use generate + migrate |
| File | Purpose |
|---|---|
| references/SCHEMA.md | Column types, constraints |
| references/QUERIES.md | Operators, joins, aggregations |
| references/RELATIONS.md | One-to-many, many-to-many |
| references/MIGRATIONS.md | drizzle-kit workflows |
| references/POSTGRES.md | PG18 features, RLS, partitioning |
| references/PERFORMANCE.md | Indexing, optimization |
| references/CHEATSHEET.md | Quick reference |
Weekly Installs
365
Repository
GitHub Stars
22
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode321
codex310
gemini-cli301
github-copilot295
kimi-cli247
cursor247
Firestore 基础入门指南 - 配置、安全规则、SDK 使用与索引优化
1,300 周安装
Gemini CLI 更新日志自动化流程指南 | 技术文档版本管理最佳实践
430 周安装
tsdown - 基于Rolldown的极速TypeScript/JavaScript库打包工具,支持ESM/CJS/IIFE/UMD
430 周安装
PDF OCR技能:双引擎文字提取,支持影印PDF和图片识别
430 周安装
MUI v7 使用指南:组件样式、主题定制与响应式设计模式详解
431 周安装
HubSpot CRM 集成指南:使用 Membrane CLI 自动化销售、营销与客户服务
431 周安装
index-knowledge:自动生成层级化AGENTS.md文档工具,Turso数据库出品
431 周安装
| Storing JSON as text | No validation, bad queries | Use jsonb() column type |