实战

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 Skills 实战:15 个可直接使用的 SKILL.md 模板(Git/审查/测试/文档/部署/调试)15 个精心设计的开箱即用 SKILL.md 模板:Git 工作流类(Smart Commit/PR Creator/Branch Cleanup);代码审查类(Security Review 含 OWASP 清单/Performance Review N+1 检测);测试类(Test Generator/Coverage Check);文档类(API Doc Generator OpenAPI 格式/Changelog Generator);部署运维类(Pre-deploy Checklist);调试类(Error Analyzer);效率工具类(Code Explainer/Refactor Advisor/Dependency Auditor/Daily Standup Helper)。2026/5/10实战Claude Code 成本优化完整指南:Token 节省策略、模型选择和 Prompt Cache 配置Claude Code 成本优化完整指南:Token 消耗来源分析(对话历史/大文件读取/工具输出/MCP 服务器/长 CLAUDE.md);8 个优化策略(/compact 主动压缩/精确 @ 引用/控制 MCP 数量/模型选择 Haiku vs Sonnet vs Opus 价格对比/努力等级按需调整/Prompt Cache 1 小时 TTL/CLAUDE.md 精简/usage 监控);不同场景的成本估算(个人/小团队/企业);以及订阅 vs API 的临界点分析。2026/5/8实战Claude Code 企业规模化最佳实践:AI 网关、成本控制和可观测性完全指南Claude Code 企业级部署完整指南:原生局限(订阅模式无实时仪表盘/API 密钥散落风险);AI 网关层解决方案(7 个最佳实践:凭证三级层级/预算速率限制/完整请求可观测性/请求元数据标签/多提供商故障转移/输入输出护栏/灵活提供商切换);Portkey 2 分钟配置示例;Enterprise 专属功能(managed-settings/allowManagedDomainsOnly/OpenTelemetry);以及团队 CLAUDE.md 安全策略模板。2026/5/7实战Claude Code 45 个进阶技巧:8.1k Star 的 GitHub 精华整理ykdojo GitHub 仓库(8100+ Stars)45 个 Claude Code 实战技巧精华整理:自定义状态栏显示 Token 消耗;Git CLI 配合自动创建 PR;Gemini CLI 作为助手处理被限制的搜索;/compact 带焦点提示词保留关键信息;Fork 会话和半克隆技术;容器安全运行高风险任务;CLAUDE.md vs Skills vs Slash Commands vs Plugins 的区别;/loop 定期轮询;以及 dx 插件安装。2026/5/6实战Claude Code 全软件开发生命周期实战:从需求到运维的端到端工作流指南Claude Code 覆盖完整 SDLC 的端到端工作流:需求拆解和 ADR 生成、TDD 验证循环配置(质量 2-3×)、分层实现+Git Worktree 并行、多角度并行 PR 审查、GitHub Actions CI/CD 配置、OpenAPI 文档自动生成、生产日志分析和性能分析,各阶段效率提升数据对比。2026/4/24