实战

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 跨会话协作实战:用 SendMessage 和 ListAgents 串联你的多台设备解析 Claude Code v2.1.224 新增的跨会话消息能力,探讨 SendMessage/ListAgents 的实战用法、crossSessionInbound 安全边界与多设备协作的应用潜力。2026/8/7实战Claude Code 长会话优化实战:让 CLAUDE.md 规则在 Compaction 后依然存活实战教学:基于官方 Compaction 存活规则表,指导你如何重新组织 CLAUDE.md 规则、调整 SKILL.md 写作顺序、合理使用 /compact focus 和 /clear,确保关键约定在长会话压缩后仍然存活,附完整检查清单。2026/7/12实战Claude Code Agent Teams 实战:三视角协作设计一个 CLI 工具基于官方文档实例,实战演示如何启用 Claude Code Agent Teams 并用三个视角(UX、技术架构、唱反调)协作探索一个 CLI 工具的设计方案,详解空闲行显示逻辑、折叠交互、In-process 与 Split panes 两种显示模式的适用场景。2026/7/12实战Claude Code 实战:Desktop 内置浏览器 + Auto Mode 组合,从查文档到自动提交 PR通过一个真实集成第三方 API 的完整场景,演示 Claude Code Desktop 内置浏览器与 Auto Mode 组合使用如何实现从查阅官方文档、编写集成代码、本地预览验证到提交推送创建 PR 的端到端自动化,并梳理背后的多层安全边界设计。2026/7/11实战Claude Code 生产力工具箱:MCP + GitHub Actions + Prompt Caching 三件套实战组合实战讲解如何组合 MCP 数据连接、GitHub Actions 自动化和 Prompt Caching 优化,搭建从 Issue 到 PR 的完整自动化工作流,并给出权限最小化配置和团队级实战检查清单。2026/7/6