实战

Claude Code 数据库开发实战:Schema 设计、迁移脚本与查询优化完整指南

Claude Code 辅助数据库开发完整指南:从 ERD 需求到 SQL Schema 设计、Prisma/SQLAlchemy ORM 集成、数据库迁移脚本生成、N+1 查询优化、索引分析、慢查询排查,以及 PostgreSQL/MySQL/SQLite 各场景最佳实践。

2026/3/154分钟 阅读ClaudeEagle

数据库设计和优化是开发中技术门槛最高的部分之一。Claude Code 能从业务需求直接推导出合理的 Schema 设计,生成迁移脚本,并分析性能瓶颈。本文展示完整工作流。

工作流 1:从业务需求设计 Schema

Design a PostgreSQL schema for an e-commerce platform: Entities: - Users: can be buyers or sellers - Products: belong to sellers, have multiple images and variants - Orders: placed by buyers, contain multiple order items - Reviews: buyers review purchased products - Categories: hierarchical (electronics > phones > iPhone) Requirements: - Support product variants (size, color, etc.) - Track inventory per variant - Order status history (created->paid->shipped->delivered) - Soft delete for products Output: 1. CREATE TABLE statements with proper constraints 2. Indexes for common query patterns 3. Brief explanation of design decisions

工作流 2:生成 Prisma Schema

Convert this SQL schema to Prisma schema format: [粘贴 SQL] Also add: - Proper relations (one-to-many, many-to-many) - @default values - @updatedAt for timestamp fields - @@index for performance-critical fields - Cascade delete rules

生成结果示例

prisma
model Product {
  id          String    @id @default(cuid())
  title       String
  slug        String    @unique
  price       Decimal   @db.Decimal(10, 2)
  sellerId    String
  seller      User      @relation(fields: [sellerId], references: [id])
  variants    Variant[]
  images      Image[]
  reviews     Review[]
  categoryId  String
  category    Category  @relation(fields: [categoryId], references: [id])
  deletedAt   DateTime?
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt

  @@index([sellerId])
  @@index([categoryId])
  @@index([slug])
}

工作流 3:生成数据库迁移

Generate a safe database migration for these changes: Current schema: [粘贴当前 schema] Target schema: [粘贴新 schema] Requirements: - Zero-downtime migration (no table locks) - Add new nullable columns before making them required - Backfill existing rows before adding NOT NULL constraints - Create indexes CONCURRENTLY Output: 1. migration.sql 2. rollback.sql (undo script) 3. Estimated migration time for 10M rows

工作流 4:N+1 查询检测与修复

Review this code for N+1 query problems: [粘贴 ORM 代码] For each N+1 pattern found: 1. Explain why it causes N+1 2. Show the fixed version using proper joins/includes 3. Estimate queries before vs after the fix Use Prisma syntax for the fixes.

常见 N+1 修复

typescript
// 问题:N+1
const orders = await prisma.order.findMany()
for (const order of orders) {
  const user = await prisma.user.findUnique({where: {id: order.userId}})
  // 每个 order 一次查询 = N+1 次
}

// 修复:一次查询
const orders = await prisma.order.findMany({
  include: { user: true }  // JOIN 一次搞定
})

工作流 5:分析查询性能

Analyze the performance of this PostgreSQL query: Query: SELECT p.*, u.name, COUNT(r.id) as review_count FROM products p JOIN users u ON p.seller_id = u.id LEFT JOIN reviews r ON p.id = r.product_id WHERE p.category_id = $1 AND p.deleted_at IS NULL GROUP BY p.id, u.name ORDER BY review_count DESC LIMIT 20; EXPLAIN ANALYZE output: [粘贴 EXPLAIN 输出] Please: 1. Identify bottlenecks (seq scans, high cost steps) 2. Suggest missing indexes 3. Rewrite if the query can be restructured for better performance

工作流 6:SQLAlchemy 模型生成(Python)

Generate SQLAlchemy 2.0 models for this schema: [粘贴 SQL] Requirements: - Use DeclarativeBase (new SQLAlchemy 2.0 style) - Type annotations for all columns - relationship() with lazy='select' for small sets, lazy='dynamic' for large - __repr__ for debugging - save to src/models/

工作流 7:种子数据生成

Generate seed data for development/testing: Schema: [Prisma schema or SQL] Generate: - 10 users (mix of buyers and sellers) - 50 products (across 5 categories) - 100 orders with order items - 200 reviews Use realistic fake data (Faker.js). Save to prisma/seed.ts

CLAUDE.md 推荐配置(数据库项目)

markdown
## 数据库规范
- ORM: Prisma
- DB: PostgreSQL 15
- 迁移:prisma migrate dev

## 查询规范
- 禁止裸 SQL(除性能关键路径)
- 所有关联查询用 include/select 而非循环查询
- 新增字段先加 nullable,backfill 后再加约束

## 命令
- 迁移:npx prisma migrate dev
- 查看:npx prisma studio
- 重置:npx prisma migrate reset

来源:Anthropic 官方文档 + Prisma 官方文档

相关文章推荐

实战Claude Code Prisma ORM 实战完全指南:AI 辅助现代 TypeScript 数据库开发(2026)Claude Code 辅助 Prisma ORM 开发的完整实战指南:从需求直接生成 Prisma Schema(多表关系/@relation/@@index/枚举)、复杂查询生成(include/select/cursor分页)、Prisma 事务处理(原子操作/库存扣减)、安全的数据库 Migration 策略(生产环境不停机迁移)、N+1 查询问题排查与优化,覆盖 PostgreSQL/MySQL/SQLite 三种数据库。2026/3/27实战Claude Code Plugins 开发指南:封装 Skills、Agents、Hooks 和 MCP ServersClaude Code Plugins 适合把团队工作流从 .claude 本地配置升级为可共享扩展。插件通过 .claude-plugin/plugin.json 描述元数据,skills 使用命名空间避免冲突,可用 --plugin-dir 本地测试。2026/6/8实战Claude Code GitLab CI/CD 完整指南:@claude 创建 MR、Bedrock/Vertex 企业部署Claude Code GitLab CI/CD 官方文档中文整理:beta 状态、工作原理、最小 .gitlab-ci.yml、masked CI/CD variables、issue/MR 评论触发、AI_FLOW_INPUT/AI_FLOW_CONTEXT、GitLab MCP server、Bedrock/Vertex AI 企业认证和安全建议。2026/5/20实战Claude Code GitHub Actions v1 完整指南:@claude 自动开发、PR 审查和 CI 集成Claude Code GitHub Actions 官方文档中文整理:它能做什么、快速安装 /install-github-app、手动配置 GitHub App 和 ANTHROPIC_API_KEY、v1 相比 beta 的破坏性变更、@claude 评论触发、自动 PR 审查、Skills 调用、Daily Report 自动化、权限安全、成本控制和可直接复制的 workflow 模板。2026/5/15实战Claude Code 并行 Worktree 实战:同时跑 4 个 AI 任务的工作流设计Claude Code Worktree 4 种并行工作流模式:功能开发+Bug修复同时进行(3个终端并行、时间节省分析);并行代码审查(PR Worktree审查+继续开发);大规模重构+主线开发(破坏性变更的隔离策略);Subagent 隔离自动并行(4个维度同时分析节省 75% 时间)。不应该并行的场景(有依赖/需共享上下文/单一简单任务)。5 个实用技巧(命名规范、.worktreeinclude、状态监控脚本、PR Worktree 直接推送)。2026/5/13实战Claude Code Routines 实战:6 个可直接使用的 Routine 配置模板6 个开箱即用的 Claude Code Routines 模板:PR 代码审查(GitHub 触发,含 OWASP 安全清单和内联评论格式);依赖安全扫描(每日 Schedule,自动修复低风险漏洞并创建 PR);文档漂移检测(每周 Schedule,比对代码变更与文档的一致性);生产告警响应(API 触发,含 curl 请求示例和 Slack 通知格式);每日 PR 摘要(含超时 PR 的 @mention 提醒);发布后烟雾测试(CD 流水线调用,健康检查 + 错误率验证)。含写好 Routine Prompt 的 5 个核心原则。2026/5/12