Community编程与开发github.com

mianhtsys/landingMod3

设计健壮、可扩展的SQL和NoSQL数据库模式。提供规范化指南、索引策略、迁移模式、约束设计和性能优化。确保数据完整性、查询性能和可维护的数据模型。

landingMod3 是什么?

此技能是一个全面的数据库模式设计助手,适用于生产环境。它支持SQL和NoSQL数据库,通过提供从需求分析到模式生成的完整工作流程,帮助开发者设计高质量的数据模型。该技能强调核心原则,如领域建模、数据完整性优先和访问模式优化,并提供详细的规范化和索引策略指南。它覆盖了从基础表创建到复杂关系、约束设计、迁移脚本和反模式预防的各个方面。适用于需要快速设计、审查或迭代数据库模式的AI代理(如Claude Code、Coder、Cursor),通过分析用户输入的自然语言需求来生成相应的SQL语句或NoSQL文档模式。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/database-schema-designer

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

数据库模式设计器

设计生产就绪的数据库模式,内置最佳实践。


快速开始

只需描述您的数据模型:

为一个包含用户、产品和订单的电商平台设计模式

您将获得一个完整的 SQL 模式,如下:

CREATE TABLE users (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE orders (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(id),
  total DECIMAL(10,2) NOT NULL,
  INDEX idx_orders_user (user_id)
);

应在请求中包含的内容:

  • 实体(用户、产品、订单)
  • 关键关系(用户拥有订单,订单包含项)
  • 规模提示(高流量、百万条记录)
  • 数据库偏好(SQL/NoSQL)—— 如果未指定,默认为 SQL

触发词

触发词示例
design schema"为用户认证设计模式"
database design"多租户SaaS的数据库设计"
create tables"为博客系统创建表"
schema for"库存管理模式"
model data"为实时分析建模数据"
I need a database"我需要一个用于追踪订单的数据库"
design NoSQL"为产品目录设计NoSQL模式"

关键术语

术语定义
规范化组织数据以减少冗余(1NF → 2NF → 3NF)
3NF第三范式——列之间没有传递依赖
OLTP在线事务处理——写密集型,需要规范化
OLAP在线分析处理——读密集型,受益于反规范化
外键 (FK)引用另一个表主键的列
索引加速查询的数据结构(以较慢的写操作为代价)
访问模式应用程序读写数据的方式(查询、连接、过滤)
反规范化有意复制数据以加速读取

快速参考

任务方法关键考量
新模式先规范化到 3NF领域建模优于 UI
SQL vs NoSQL访问模式决定读写比例很重要
主键INT 或 UUIDUUID 用于分布式系统
外键始终约束ON DELETE 策略至关重要
索引外键 + WHERE 列列顺序很重要
迁移始终可逆首先向后兼容

流程概述

您的数据需求
    |
    v
+-----------------------------------------------------+
| 阶段 1:分析                                        |
| * 识别实体和关系                                    |
| * 确定访问模式(读密集型 vs 写密集型)               |
| * 根据需求选择 SQL 或 NoSQL                         |
+-----------------------------------------------------+
    |
    v
+-----------------------------------------------------+
| 阶段 2:设计                                        |
| * 规范化到 3NF(SQL)或嵌入/引用(NoSQL)           |
| * 定义主键和外键                                    |
| * 选择适当的数据类型                                |
| * 添加约束(UNIQUE、CHECK、NOT NULL)              |
+-----------------------------------------------------+
    |
    v
+-----------------------------------------------------+
| 阶段 3:优化                                        |
| * 规划索引策略                                      |
| * 考虑针对读密集型查询进行反规范化                  |
| * 添加时间戳(created_at、updated_at)              |
+-----------------------------------------------------+
    |
    v
+-----------------------------------------------------+
| 阶段 4:迁移                                        |
| * 生成迁移脚本(向上 + 向下)                       |
| * 确保向后兼容性                                    |
| * 规划零停机部署                                    |
+-----------------------------------------------------+
    |
    v
生产就绪模式

命令

命令使用时机操作
design schema for {领域}从头开始生成完整模式
normalize {表}修复现有表应用规范化规则
add indexes for {表}性能问题生成索引策略
migration for {变更}模式演进创建可逆迁移
review schema代码审查审计现有模式

工作流程: 从 design schema 开始 → 使用 normalize 迭代 → 使用 add indexes 优化 → 使用 migration 演进


核心原则

原则为什么实现
对领域建模UI 会变,领域不会实体名称反映业务概念
数据完整性优先损坏修复成本高数据库级别的约束
优化访问模式无法两者兼得OLTP:规范化,OLAP:反规范化
规划可扩展性追溯性改造成本高索引策略 + 分区计划

反模式

避免原因取而代之
到处使用 VARCHAR(255)浪费存储,隐藏意图根据字段适当调整大小
使用 FLOAT 表示金钱四舍五入错误DECIMAL(10,2)
缺少外键约束孤数据始终定义外键
外键上没有索引慢速 JOIN索引每个外键
将日期存储为字符串无法比较/排序DATE、TIMESTAMP 类型
查询中使用 SELECT *提取不必要的数据显式指定列列表
不可逆的迁移无法回滚始终编写 DOWN 迁移
添加 NOT NULL 没有默认值破坏现有行添加可空、回填、然后约束

验证清单

设计完模式后:

  • 每个表都有一个主键
  • 所有关系都有外键约束
  • 为每个外键定义了 ON DELETE 策略
  • 所有外键上都有索引
  • 经常查询的列上都有索引
  • 适当的数据类型(金钱用 DECIMAL 等)
  • 必填字段设为 NOT NULL
  • 需要时添加了 UNIQUE 约束
  • 使用 CHECK 约束进行验证
  • 包含了 created_at 和 updated_at 时间戳
  • 迁移脚本可逆
  • 在使用生产数据的暂存环境中进行了测试

范式

范式规则违反示例
1NF原子值,无重复组product_ids = '1,2,3'
2NF1NF + 无部分依赖order_items 中的 customer_name
3NF2NF + 无传递依赖从 postal_code 派生的 country

第一范式 (1NF)

-- 错误:列中包含多个值
CREATE TABLE orders (
  id INT PRIMARY KEY,
  product_ids VARCHAR(255)  -- '101,102,103'
);

-- 正确:单独的表存放项
CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT
);

CREATE TABLE order_items (
  id INT PRIMARY KEY,
  order_id INT REFERENCES orders(id),
  product_id INT
);

第二范式 (2NF)

-- 错误:customer_name 仅依赖于 customer_id
CREATE TABLE order_items (
  order_id INT,
  product_id INT,
  customer_name VARCHAR(100),  -- 部分依赖!
  PRIMARY KEY (order_id, product_id)
);

-- 正确:客户数据放在单独的表中
CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(100)
);

第三范式 (3NF)

-- 错误:country 依赖于 postal_code
CREATE TABLE customers (
  id INT PRIMARY KEY,
  postal_code VARCHAR(10),
  country VARCHAR(50)  -- 传递依赖!
);

-- 正确:单独的 postal_codes 表
CREATE TABLE postal_codes (
  code VARCHAR(10) PRIMARY KEY,
  country VARCHAR(50)
);

何时反规范化

场景反规范化策略
读密集型报表预计算聚合
昂贵的 JOIN缓存派生列
分析仪表板物化视图
-- 为了性能而反规范化
CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  total_amount DECIMAL(10,2),  -- 计算所得
  item_count INT               -- 计算所得
);

字符串类型

类型使用场景示例
CHAR(n)固定长度州代码,ISO 日期
VARCHAR(n)可变长度姓名,电子邮件
TEXT长内容文章,描述
-- 良好的大小设定
email VARCHAR(255)
phone VARCHAR(20)
country_code CHAR(2)

数值类型

类型范围使用场景
TINYINT-128 到 127年龄,状态码
SMALLINT-32K 到 32K数量
INT-2.1B 到 2.1BID,计数
BIGINT非常大大 ID,时间戳
DECIMAL(p,s)精确精度金钱
FLOAT/DOUBLE近似值科学数据
-- 金钱始终使用 DECIMAL
price DECIMAL(10, 2)  -- $99,999,999.99

-- 绝不要用 FLOAT 表示金钱
price FLOAT  -- 四舍五入错误!

日期/时间类型

DATE        -- 2025-10-31
TIME        -- 14:30:00
DATETIME    -- 2025-10-31 14:30:00
TIMESTAMP   -- 自动时区转换

-- 始终以 UTC 存储
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

布尔类型

-- PostgreSQL
is_active BOOLEAN DEFAULT TRUE

-- MySQL
is_active TINYINT(1) DEFAULT 1

何时创建索引

始终索引原因
外键加速 JOIN
WHERE 子句列加速过滤
ORDER BY 列加速排序
唯一约束强制唯一性
-- 外键索引
CREATE INDEX idx_orders_customer ON orders(customer_id);

-- 查询模式索引
CREATE INDEX idx_orders_status_date ON orders(status, created_at);

索引类型

类型最佳适用示例
B-Tree范围、等值price > 100
Hash仅精确匹配email = '[email protected]'
Full-text文本搜索MATCH AGAINST
Partial行子集WHERE is_active = true

复合索引顺序

CREATE INDEX idx_customer_status ON orders(customer_id, status);

-- 使用索引(customer_id 在前)
SELECT * FROM orders WHERE customer_id = 123;
SELECT * FROM orders WHERE customer_id = 123 AND status = 'pending';

-- 不使用索引(仅 status)
SELECT * FROM orders WHERE status = 'pending';

规则: 选择性最高的列在前,或最常单独查询的列在前。

索引陷阱

陷阱问题解决方案
过度索引写操作变慢仅索引被查询的列
列顺序错误索引未使用匹配查询模式
缺少外键索引慢速 JOIN始终索引外键

主键

-- 自增(简单)
id INT AUTO_INCREMENT PRIMARY KEY

-- UUID(分布式系统)
id CHAR(36) PRIMARY KEY DEFAULT (UUID())

-- 复合(连接表)
PRIMARY KEY (student_id, course_id)

外键

FOREIGN KEY (customer_id) REFERENCES customers(id)
  ON DELETE CASCADE     -- 删除父记录时级联删除子记录
  ON DELETE RESTRICT    -- 如果有引用则阻止删除
  ON DELETE SET NULL    -- 父记录删除时将外键设为 NULL
  ON UPDATE CASCADE     -- 父记录更改时更新子记录
策略使用场景
CASCADE依赖数据(order_items)
RESTRICT重要引用(防止意外)
SET NULL可选关系

其他约束

-- 唯一
email VARCHAR(255) UNIQUE NOT NULL

-- 复合唯一
UNIQUE (student_id, course_id)

-- 检查
price DECIMAL(10,2) CHECK (price >= 0)
discount INT CHECK (discount BETWEEN 0 AND 100)

-- 非空
name VARCHAR(100) NOT NULL

一对多

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT NOT NULL REFERENCES customers(id)
);

CREATE TABLE order_items (
  id INT PRIMARY KEY,
  order_id INT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
  product_id INT NOT NULL,
  quantity INT NOT NULL
);

多对多

-- 连接表
CREATE TABLE enrollments (
  student_id INT REFERENCES students(id) ON DELETE CASCADE,
  course_id INT REFERENCES courses(id) ON DELETE CASCADE,
  enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (student_id, course_id)
);

自引用

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  manager_id INT REFERENCES employees(id)
);

多态

-- 方法 1:单独的外键(更强的完整性)
CREATE TABLE comments (
  id INT PRIMARY KEY,
  content TEXT NOT NULL,
  post_id INT REFERENCES posts(id),
  photo_id INT REFERENCES photos(id),
  CHECK (
    (post_id IS NOT NULL AND photo_id IS NULL) OR
    (post_id IS NULL AND photo_id IS NOT NULL)
  )
);

-- 方法 2:类型 + ID(灵活,完整性较弱)
CREATE TABLE comments (
  id INT PRIMARY KEY,
  content TEXT NOT NULL,
  commentable_type VARCHAR(50) NOT NULL,
  commentable_id INT NOT NULL
);

嵌入 vs 引用

因素嵌入引用
访问模式一起读取分开读取
关系1:很少1:很多
文档大小小接近 16MB
更新频率很少频繁

嵌入文档

{
  "_id": "order_123",
  "customer": {
    "id": "cust_456",
    "name": "John Doe",
    "email": "[email protected]"
  },
  "items": [
    { "product_id": "prod_789", "name": "Widget", "price": 29.99 }
  ],
  "total": 29.99
}

引用文档

// Orders collection
{
  "_id": "order_123",
  "customer_id": "cust_456",
  "status": "pending"
}

// Customers collection
{
  "_id": "cust_456",
  "name": "John Doe",
  "addresses": [
    {
      "type": "billing",
      "street": "123 Main St"
    }
  ]
}

经验法则: 如果数据始终一起读取 → 嵌入;如果数据独立增长或单独读取 → 引用。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

PHP 8.0+ development — XAMPP, RESTful APIs, PDO/MySQL/MariaDB, and authentication. Use when building PHP backends, creating API endpoints, configuring XAMPP, or integrating PHP with databases.

mianhtsys/landingMod3

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

相关技能