database-designer
alirezarezvani/claude-skills
利用专家分析和自动化工具,设计数据库模式、规划数据迁移、优化查询以及建模数据关系。
...展开全部数据库设计师——精通多层架构
概述
一项全面的数据库设计技能,为现代数据库系统提供专家级别的分析、优化和迁移能力。该技能将理论原理与实用工具相结合,帮助架构师和开发人员创建可扩展、高性能且易于维护的数据库模式。
核心能力
模式设计与分析
- 规范化分析:自动检测规范化级别(从1NF到BCNF)
- 去规范化策略:针对性能优化的智能建议
- 数据类型优化:识别不恰当的数据类型及大小问题
- 约束分析:缺失的外键、唯一约束及空值检查
- 命名规范验证:确保表和列命名模式的一致性
- ERD生成:根据DDL自动生成Mermaid图
索引优化
- 索引缺口分析:识别外键和查询模式中缺失的索引
- 复合索引策略:多列索引的最佳列排序
- 索引冗余检测:消除重叠和未使用的索引
- 性能影响建模:选择性估算与查询成本分析
- 索引类型选择:B-树索引、哈希索引、部分索引、覆盖索引和专用索引
迁移管理
- 零停机迁移:扩展-收缩模式的实现
- 模式演进:安全地添加、删除列以及更改数据类型
- 数据迁移脚本:自动数据转换与验证
- 回滚策略:具备验证功能的完整回滚能力
- 执行规划:带依赖关系解析的有序迁移步骤
工具工作流(请运行这些脚本——切勿手动分析模式)
所有路径均相对于此技能文件夹;示例输入位于 assets/.
1. 分析模式
python3 schema_analyzer.py --input schema.sql --generate-erd --output-format json -o analysis.json
支持 SQL DDL 或 JSON 模式(assets/sample_schema.sql / sample_schema.json)。输出包括规范化结果、缺失的约束、命名问题以及一张 Mermaid ERD —— 在优化之前,向用户展示 ERD 并修复标记的问题。
2. 根据实际查询模式优化索引
python3 index_optimizer.py --schema assets/sample_schema.json --queries assets/sample_query_patterns.json --analyze-existing --format json -o indexes.json
首先将用户的热门查询写入查询模式 JSON 文件中(复制 assets/sample_query_patterns.json)。输出结果为按优先级排序的 CREATE INDEX 建议列表,以及冗余索引的移除建议。
3. 生成迁移方案
python3 migration_generator.py --current current_schema.json --target target_schema.json --zero-downtime --format sql -o migration.sql
--zero-downtime 生成一个展开-收缩计划; --validate-only 在不生成 SQL 的情况下检查可行性。
4. 验证循环
在目标模式上重新运行步骤 1,并验证首次运行中发现的问题已消除;运行 migration_generator.py --validate-only 后再移交迁移方案。
数据库设计原则
→ 详情请参阅 references/database-design-reference.md
最佳实践
模式设计
- 使用有意义的名称:清晰、一致的命名约定
- 选择合适的数据类型:根据存储效率选择尺寸合适的列
- 定义适当的约束:外键、检查约束、唯一索引
- 考虑未来发展:从一开始就规划可扩展性
- 记录关系:明确的外键关系和业务规则
性能优化
- 策略性地建立索引:覆盖常见查询模式,避免过度索引
- 监控查询性能:定期分析慢查询
- 对大型表进行分区:提高查询性能并简化维护
- 使用适当的隔离级别:在一致性和性能之间取得平衡
- 实现连接池:高效利用资源
安全注意事项
- 最小权限原则:仅授予最低必要的权限
- 加密敏感数据:静态数据和传输中的数据
- 审计访问模式:监控并记录数据库访问
- 验证输入:防止 SQL 注入攻击
- 定期安全更新:保持数据库软件最新
查询生成模式
带 JOIN 的 SELECT 语句
-- INNER JOIN: only matching rows
SELECT o.id, c.name, o.total
FROM orders o
INNER JOIN customers c ON c.id = o.customer_id;
-- LEFT JOIN: all left rows, NULLs for non-matches
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;
-- Self-join: hierarchical data (employees/managers)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
常见表表达式(CTE)
-- Recursive CTE for org chart
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1
FROM employees e INNER JOIN org o ON o.id = e.manager_id
)
SELECT * FROM org ORDER BY depth, name;
窗口函数
-- ROW_NUMBER for pagination / dedup
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;
-- RANK with gaps, DENSE_RANK without gaps
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM leaderboard;
-- LAG/LEAD for comparing adjacent rows
SELECT date, revenue,
revenue - LAG(revenue) OVER (ORDER BY date) AS daily_change
FROM daily_sales;
聚合模式
-- FILTER clause (PostgreSQL) for conditional aggregation
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'active') AS active,
AVG(amount) FILTER (WHERE amount > 0) AS avg_positive
FROM accounts;
-- GROUPING SETS for multi-level rollups
SELECT region, product, SUM(revenue)
FROM sales
GROUP BY GROUPING SETS ((region, product), (region), ());
迁移模式
向上/向下迁移脚本
每次迁移都必须有一个可逆的操作。为便于排序,请在文件名前添加时间戳前缀:
migrations/
├── 20260101_000001_create_users.up.sql
├── 20260101_000001_create_users.down.sql
├── 20260115_000002_add_users_email_index.up.sql
└── 20260115_000002_add_users_email_index.down.sql
零停机迁移(扩展/收缩)
使用扩展-收缩模式以避免锁定或破坏正在运行的代码:
- 扩展 — 添加新列/表(允许为空,并设置默认值)
- 数据迁移 — 分批回填;应用程序进行双重写入
- 过渡 — 应用程序从新列读取数据;停止向旧列写入
- 收缩 — 在后续迁移中删除旧列
数据回填策略
-- Batch update to avoid long-running locks
UPDATE users SET email_normalized = LOWER(email)
WHERE id IN (SELECT id FROM users WHERE email_normalized IS NULL LIMIT 5000);
-- Repeat in a loop until 0 rows affected
回滚流程
- 务必在部署前
down.sql在预发布环境中进行测试up.sql到生产环境前 - 保持回滚窗口时间短——如果合同步骤已执行,则回滚需要进行新的向前迁移
- 对于不可逆的更改(例如删除包含数据的列),请先进行逻辑备份
性能优化
索引策略
| 索引类型 | 用例 | 示例 |
|---|---|---|
| B-树(默认) | 等值、范围、ORDER BY | CREATE INDEX idx_users_email ON users(email); |
| GIN | 全文搜索、JSONB、数组 | CREATE INDEX idx_docs_body ON docs USING gin(to_tsvector('english', body)); |
| GiST | 几何、范围类型、最近邻 | CREATE INDEX idx_locations ON places USING gist(coords); |
| 部分 | 行子集(缩减大小) | CREATE INDEX idx_active ON users(email) WHERE active = true; |
| 覆盖 | 仅索引扫描 | CREATE INDEX idx_cov ON orders(customer_id) INCLUDE (total, created_at); |
EXPLAIN 执行计划阅读
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
需关注的关键信号:
- 对大型表进行顺序扫描 — 缺少索引
- 嵌套循环连接且行数估计值过高 — 考虑使用哈希连接/合并连接或添加索引
- 共享缓冲区的读取次数远高于命中次数 — 工作集超出内存容量
N+1 查询检测
症状:应用程序每行执行一次查询(例如,在循环中检索相关记录)。
解决方案:
- 使用
JOIN或子查询以单次往返完成数据获取 - ORM 预加载(
select_related/includes/with) - GraphQL 解析器的 DataLoader 模式
连接池
| 工具 | 协议 | 最适合 |
|---|---|---|
| PgBouncer | PostgreSQL | 事务/语句池化,低开销 |
| ProxySQL | MySQL | 查询路由,读写分离 |
| 内置池(HikariCP、SQLAlchemy 池) | 任意 | 应用层连接池 |
经验法则:将连接池大小设置为 (2 * CPU cores) + disk spindles。对于云 SSD,建议从 2 * vCPUs ,然后进行调整。
读取副本与查询路由
- 将所有
SELECT查询路由到副本;写入则路由到主节点 - 需考虑复制延迟(异步复制通常<1s,同步复制为0)
- 使用
pg_last_wal_replay_lsn()在读取关键数据前检测延迟
多数据库决策矩阵
| 标准 | PostgreSQL | MySQL | SQLite | SQL Server |
|---|---|---|---|---|
| 最适合 | 复杂查询、JSONB、扩展 | Web 应用、以读取为主的工作负载 | 嵌入式、开发/测试、边缘计算 | 企业级 .NET 技术栈 |
| JSON 支持 | 出色(JSONB + GIN) | 良好(JSON 类型) | 基本 | 良好(OPENJSON) |
| 复制 | 流式、逻辑 | 组复制,InnoDB 集群 | 不适用 | Always On AG |
| 许可 | 开源(PostgreSQL 许可证) | 开源(GPL)/商业 | 公共领域 | 商业 |
| 最大实际容量 | 多 TB | 多TB | 约1 TB(单写入) | 数TB |
何时选择:
- PostgreSQL — 新项目的首选;具备最佳的可扩展性和标准兼容性
- MySQL — 现有的MySQL生态系统;适用于简单的以读取为主的Web应用程序
- SQLite — 移动应用、命令行工具、单元测试数据库、物联网/边缘计算
- SQL Server — 受企业政策强制要求;与 .NET/Azure 深度集成
NoSQL 考量因素
| 数据库 | 模型 | 适用场景 |
|---|---|---|
| MongoDB | 文档 | 模式灵活性、快速原型开发、内容管理 |
| Redis | 键值对 / 缓存 | 会话存储、速率限制、排行榜、发布/订阅 |
| DynamoDB | 宽列 | 无服务器 AWS 应用,无论规模大小,延迟均在个位数毫秒内 |
默认使用 SQL。仅当访问模式能明显受益于 NoSQL 时,才采用 NoSQL。
分片与复制
水平分区与垂直分区
- 纵向分区:将列拆分到不同表中(例如,将 BLOB 列分离)。可减少窄查询的 I/O 负载。
- 水平分区(分片):将行分散到不同的数据库/服务器中。当单个节点无法容纳数据集或处理吞吐量时,必须采用此方法。
分片策略
| 策略 | 工作原理 | 优点 | 缺点 |
|---|---|---|---|
| 哈希 | shard = hash(key) % N |
均匀分布 | 分片重组成本高 |
| 范围 | 按日期或ID范围进行分片 | 简单,适用于时间序列 | 最新分片上出现热点 |
| 地理 | 按用户所在地区进行分片 | 数据本地化、合规性 | 跨区域查询较为困难 |
复制模式
| 模式 | 一致性 | 延迟 | 用例 |
|---|---|---|---|
| 同步 | 强 | 更高的写入延迟 | 金融交易 |
| 异步 | 最终 | 低写入延迟 | 读取密集型 Web 应用 |
| 半同步 | 至少一个副本已确认 | 中等 | 安全性与速度的平衡 |
交叉引用
- sql-database-assistant — 用于日常 SQL 工作的查询编写、优化和调试
- database-schema-designer — 实体关系图(ERD)建模、规范化分析及模式生成
- migration-architect — 跨数据库引擎的大规模迁移规划或主要模式重构
- senior-backend — 应用层模式(连接池、ORM 最佳实践)
- senior-devops — 数据库集群和副本的基础设施部署
---
name: database-designer
description: Design database schemas, plan data migrations, optimize queries, and model data relationships using expert analysis and automated tools.
---
# Database Designer - POWERFUL Tier Skill
## Overview
A comprehensive database design skill that provides expert-level analysis, optimization, and migration capabilities for modern database systems. This skill combines theoretical principles with practical tools to help architects and developers create scalable, performant, and maintainable database schemas.
## Core Competencies
### Schema Design & Analysis
- **Normalization Analysis**: Automated detection of normalization levels (1NF through BCNF)
- **Denormalization Strategy**: Smart recommendations for performance optimization
- **Data Type Optimization**: Identification of inappropriate types and size issues
- **Constraint Analysis**: Missing foreign keys, unique constraints, and null checks
- **Naming Convention Validation**: Consistent table and column naming patterns
- **ERD Generation**: Automatic Mermaid diagram creation from DDL
### Index Optimization
- **Index Gap Analysis**: Identification of missing indexes on foreign keys and query patterns
- **Composite Index Strategy**: Optimal column ordering for multi-column indexes
- **Index Redundancy Detection**: Elimination of overlapping and unused indexes
- **Performance Impact Modeling**: Selectivity estimation and query cost analysis
- **Index Type Selection**: B-tree, hash, partial, covering, and specialized indexes
### Migration Management
- **Zero-Downtime Migrations**: Expand-contract pattern implementation
- **Schema Evolution**: Safe column additions, deletions, and type changes
- **Data Migration Scripts**: Automated data transformation and validation
- **Rollback Strategy**: Complete reversal capabilities with validation
- **Execution Planning**: Ordered migration steps with dependency resolution
## Tool Workflow (run these — do not analyze schemas by hand)
All paths relative to this skill folder; sample inputs in `assets/`.
### 1. Analyze the schema
```bash
python3 schema_analyzer.py --input schema.sql --generate-erd --output-format json -o analysis.json
```
Accepts SQL DDL or JSON schema (`assets/sample_schema.sql` / `sample_schema.json`). Output includes normalization findings, missing constraints, naming issues, and a Mermaid ERD — show the ERD to the user and fix flagged issues before optimizing.
### 2. Optimize indexes against real query patterns
```bash
python3 index_optimizer.py --schema assets/sample_schema.json --queries assets/sample_query_patterns.json --analyze-existing --format json -o indexes.json
```
Write the user's hot queries into a query-patterns JSON first (copy `assets/sample_query_patterns.json`). Output is a priority-ordered list of CREATE INDEX recommendations plus redundant-index removals.
### 3. Generate the migration
```bash
python3 migration_generator.py --current current_schema.json --target target_schema.json --zero-downtime --format sql -o migration.sql
```
`--zero-downtime` emits an expand-contract plan; `--validate-only` checks feasibility without generating SQL.
### 4. Verification loop
Re-run step 1 on the *target* schema and assert the issues found in the first pass are gone; run `migration_generator.py --validate-only` before handing over the migration.
## Database Design Principles
→ See references/database-design-reference.md for details
## Best Practices
### Schema Design
1. **Use meaningful names**: Clear, consistent naming conventions
2. **Choose appropriate data types**: Right-sized columns for storage efficiency
3. **Define proper constraints**: Foreign keys, check constraints, unique indexes
4. **Consider future growth**: Plan for scale from the beginning
5. **Document relationships**: Clear foreign key relationships and business rules
### Performance Optimization
1. **Index strategically**: Cover common query patterns without over-indexing
2. **Monitor query performance**: Regular analysis of slow queries
3. **Partition large tables**: Improve query performance and maintenance
4. **Use appropriate isolation levels**: Balance consistency with performance
5. **Implement connection pooling**: Efficient resource utilization
### Security Considerations
1. **Principle of least privilege**: Grant minimal necessary permissions
2. **Encrypt sensitive data**: At rest and in transit
3. **Audit access patterns**: Monitor and log database access
4. **Validate inputs**: Prevent SQL injection attacks
5. **Regular security updates**: Keep database software current
## Query Generation Patterns
### SELECT with JOINs
```sql
-- INNER JOIN: only matching rows
SELECT o.id, c.name, o.total
FROM orders o
INNER JOIN customers c ON c.id = o.customer_id;
-- LEFT JOIN: all left rows, NULLs for non-matches
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;
-- Self-join: hierarchical data (employees/managers)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
```
### Common Table Expressions (CTEs)
```sql
-- Recursive CTE for org chart
WITH RECURSIVE org AS (
SELECT id, name, manager_id, 1 AS depth
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1
FROM employees e INNER JOIN org o ON o.id = e.manager_id
)
SELECT * FROM org ORDER BY depth, name;
```
### Window Functions
```sql
-- ROW_NUMBER for pagination / dedup
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;
-- RANK with gaps, DENSE_RANK without gaps
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS rank FROM leaderboard;
-- LAG/LEAD for comparing adjacent rows
SELECT date, revenue,
revenue - LAG(revenue) OVER (ORDER BY date) AS daily_change
FROM daily_sales;
```
### Aggregation Patterns
```sql
-- FILTER clause (PostgreSQL) for conditional aggregation
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'active') AS active,
AVG(amount) FILTER (WHERE amount > 0) AS avg_positive
FROM accounts;
-- GROUPING SETS for multi-level rollups
SELECT region, product, SUM(revenue)
FROM sales
GROUP BY GROUPING SETS ((region, product), (region), ());
```
---
## Migration Patterns
### Up/Down Migration Scripts
Every migration must have a reversible counterpart. Name files with a timestamp prefix for ordering:
```
migrations/
├── 20260101_000001_create_users.up.sql
├── 20260101_000001_create_users.down.sql
├── 20260115_000002_add_users_email_index.up.sql
└── 20260115_000002_add_users_email_index.down.sql
```
### Zero-Downtime Migrations (Expand/Contract)
Use the expand-contract pattern to avoid locking or breaking running code:
1. **Expand** — add the new column/table (nullable, with default)
2. **Migrate data** — backfill in batches; dual-write from application
3. **Transition** — application reads from new column; stop writing to old
4. **Contract** — drop old column in a follow-up migration
### Data Backfill Strategies
```sql
-- Batch update to avoid long-running locks
UPDATE users SET email_normalized = LOWER(email)
WHERE id IN (SELECT id FROM users WHERE email_normalized IS NULL LIMIT 5000);
-- Repeat in a loop until 0 rows affected
```
### Rollback Procedures
- Always test the `down.sql` in staging before deploying `up.sql` to production
- Keep rollback window short — if the contract step has run, rollback requires a new forward migration
- For irreversible changes (dropping columns with data), take a logical backup first
---
## Performance Optimization
### Indexing Strategies
| Index Type | Use Case | Example |
|------------|----------|---------|
| **B-tree** (default) | Equality, range, ORDER BY | `CREATE INDEX idx_users_email ON users(email);` |
| **GIN** | Full-text search, JSONB, arrays | `CREATE INDEX idx_docs_body ON docs USING gin(to_tsvector('english', body));` |
| **GiST** | Geometry, range types, nearest-neighbor | `CREATE INDEX idx_locations ON places USING gist(coords);` |
| **Partial** | Subset of rows (reduce size) | `CREATE INDEX idx_active ON users(email) WHERE active = true;` |
| **Covering** | Index-only scans | `CREATE INDEX idx_cov ON orders(customer_id) INCLUDE (total, created_at);` |
### EXPLAIN Plan Reading
```sql
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
```
Key signals to watch:
- **Seq Scan** on large tables — missing index
- **Nested Loop** with high row estimates — consider hash/merge join or add index
- **Buffers shared read** much higher than **hit** — working set exceeds memory
### N+1 Query Detection
Symptoms: application issues one query per row (e.g., fetching related records in a loop).
Fixes:
- Use `JOIN` or subquery to fetch in one round-trip
- ORM eager loading (`select_related` / `includes` / `with`)
- DataLoader pattern for GraphQL resolvers
### Connection Pooling
| Tool | Protocol | Best For |
|------|----------|----------|
| **PgBouncer** | PostgreSQL | Transaction/statement pooling, low overhead |
| **ProxySQL** | MySQL | Query routing, read/write splitting |
| **Built-in pool** (HikariCP, SQLAlchemy pool) | Any | Application-level pooling |
**Rule of thumb:** Set pool size to `(2 * CPU cores) + disk spindles`. For cloud SSDs, start with `2 * vCPUs` and tune.
### Read Replicas and Query Routing
- Route all `SELECT` queries to replicas; writes to primary
- Account for replication lag (typically <1s for async, 0 for sync)
- Use `pg_last_wal_replay_lsn()` to detect lag before reading critical data
---
## Multi-Database Decision Matrix
| Criteria | PostgreSQL | MySQL | SQLite | SQL Server |
|----------|-----------|-------|--------|------------|
| **Best for** | Complex queries, JSONB, extensions | Web apps, read-heavy workloads | Embedded, dev/test, edge | Enterprise .NET stacks |
| **JSON support** | Excellent (JSONB + GIN) | Good (JSON type) | Minimal | Good (OPENJSON) |
| **Replication** | Streaming, logical | Group replication, InnoDB cluster | N/A | Always On AG |
| **Licensing** | Open source (PostgreSQL License) | Open source (GPL) / commercial | Public domain | Commercial |
| **Max practical size** | Multi-TB | Multi-TB | ~1 TB (single-writer) | Multi-TB |
**When to choose:**
- **PostgreSQL** — default choice for new projects; best extensibility and standards compliance
- **MySQL** — existing MySQL ecosystem; simple read-heavy web applications
- **SQLite** — mobile apps, CLI tools, unit test databases, IoT/edge
- **SQL Server** — mandated by enterprise policy; deep .NET/Azure integration
### NoSQL Considerations
| Database | Model | Use When |
|----------|-------|----------|
| **MongoDB** | Document | Schema flexibility, rapid prototyping, content management |
| **Redis** | Key-value / cache | Session store, rate limiting, leaderboards, pub/sub |
| **DynamoDB** | Wide-column | Serverless AWS apps, single-digit-ms latency at any scale |
> Use SQL as default. Reach for NoSQL only when the access pattern clearly benefits from it.
---
## Sharding & Replication
### Horizontal vs Vertical Partitioning
- **Vertical partitioning**: Split columns across tables (e.g., separate BLOB columns). Reduces I/O for narrow queries.
- **Horizontal partitioning (sharding)**: Split rows across databases/servers. Required when a single node cannot hold the dataset or handle the throughput.
### Sharding Strategies
| Strategy | How It Works | Pros | Cons |
|----------|-------------|------|------|
| **Hash** | `shard = hash(key) % N` | Even distribution | Resharding is expensive |
| **Range** | Shard by date or ID range | Simple, good for time-series | Hot spots on latest shard |
| **Geographic** | Shard by user region | Data locality, compliance | Cross-region queries are hard |
### Replication Patterns
| Pattern | Consistency | Latency | Use Case |
|---------|------------|---------|----------|
| **Synchronous** | Strong | Higher write latency | Financial transactions |
| **Asynchronous** | Eventual | Low write latency | Read-heavy web apps |
| **Semi-synchronous** | At-least-one replica confirmed | Moderate | Balance of safety and speed |
---
## Cross-References
- **sql-database-assistant** — query writing, optimization, and debugging for day-to-day SQL work
- **database-schema-designer** — ERD modeling, normalization analysis, and schema generation
- **migration-architect** — large-scale migration planning across database engines or major schema overhauls
- **senior-backend** — application-layer patterns (connection pooling, ORM best practices)
- **senior-devops** — infrastructure provisioning for database clusters and replicas





首页
