Community程式設計與開發github.com

mianhtsys/landingMod3

設計穩固、可擴展的 SQL 與 NoSQL 資料庫綱要。提供正規化指引、索引策略、遷移模式、約束設計與效能最佳化,確保資料完整性、查詢效能與可維護的資料模型。

landingMod3 是什麼?

此技能為資料庫綱要設計師,能幫助開發者從需求描述快速產生生產就緒的資料庫綱要。它支援 SQL 與 NoSQL 資料庫,涵蓋從分析、設計、最佳化到遷移的完整流程。技能內建大量最佳實踐,包括正規化、索引策略、資料類型選擇、關係模式(一對多、多對多、自我參照、多型)以及 NoSQL 的嵌入與參考設計。此外,它也提供反模式清單與驗證檢查清單,以確保綱要的品質與可維護性。此技能適合在使用 Cursor、Codex 或 Claude Code 等 AI 編碼代理時,快速設計或審查資料庫架構。

相容平台~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

觸發詞

觸發詞範例
設計綱要"設計一個使用者認證的綱要"
資料庫設計"多租戶 SaaS 的資料庫設計"
建立資料表"為一個部落格系統建立資料表"
綱要 for"庫存管理系統的綱要"
模型資料"為即時分析建立資料模型"
我需要一個資料庫"我需要一個追蹤訂單的資料庫"
設計 NoSQL"為產品目錄設計 NoSQL 綱要"

關鍵術語

術語定義
正規化組織資料以減少冗餘(1NF → 2NF → 3NF)
3NF第三正規化形式 - 欄位之間無遞移相依性
OLTP線上交易處理 - 寫入密集,需要正規化
OLAP線上分析處理 - 讀取密集,受益於反正規化
外鍵 (FK)參照另一個資料表主鍵的欄位
索引加速查詢的資料結構(但會減慢寫入速度)
存取模式應用程式如何讀取/寫入資料(查詢、連接、過濾)
反正規化為了加速讀取而刻意複製資料

快速參考

任務方法關鍵考量
新綱要先正規化到 3NF領域建模優先於 UI
SQL vs NoSQL由存取模式決定讀取/寫入比率很重要
主鍵INT 或 UUID分散式系統使用 UUID
外鍵永遠加上約束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
生產就緒綱要

指令

指令使用時機動作
設計綱要 for {領域}從頭開始完整綱要產生
正規化 {資料表}修復現有資料表套用正規化規則
為 {資料表} 加上索引效能問題產生索引策略
遷移 for {變更}綱要演進建立可逆遷移
審查綱要程式碼審查審計現有綱要

工作流程: 從 設計綱要 開始 → 用 正規化 迭代 → 用 加上索引 最佳化 → 用 遷移 演進


核心原則

原則為什麼實作方式
對領域建模UI 會變,領域不會實體名稱反映商業概念
資料完整性優先損壞難以修復在資料庫層級加上約束
為存取模式最佳化無法同時最佳化兩者OLTP:正規化,OLAP:反正規化
為規模規劃事後補救很痛苦索引策略 + 分割計畫

反模式

避免原因替代方案
到處都用 VARCHAR(255)浪費儲存空間、隱藏意圖根據欄位適當設定大小
用 FLOAT 存錢四捨五入誤差DECIMAL(10,2)
缺少 FK 約束孤兒資料永遠定義外鍵
FK 上沒有索引慢速 JOIN為每個外鍵建立索引
將日期存為字串無法比較/排序DATE、TIMESTAMP 類型
查詢中使用 SELECT *擷取不必要的資料明確列出欄位
不可逆的遷移無法回滾永遠撰寫 DOWN 遷移
未給預設值就加 NOT NULL破壞現有資料行先設為可空、補填、再加約束

驗證檢查清單

設計綱要後:

  • 每個資料表都有主鍵
  • 所有關係都有外鍵約束
  • 每個 FK 都定義 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]'
全文文字搜尋MATCH AGAINST
部分索引資料行的子集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';

規則: 選擇性最高的欄位在前,或最常單獨查詢的欄位在前。

索引陷阱

陷阱問題解決方案
過度索引慢速寫入只索引查詢用到的欄位
錯誤的欄位順序未使用的索引符合查詢模式
缺少 FK 索引慢速 JOIN永遠為 FK 建立索引

主鍵

-- 自動遞增(簡單)
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:獨立 FK(完整性更強)
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": "Alice"
  },
  "items": [
    { "product_id": "prod_789", "quantity": 2, "price": 29.99 }
  ],
  "total": 59.98
}

使用參考

// orders 集合
{ "_id": "order_123", "customer_id": "cust_456" }

// customers 集合
{ "_id": "cust_456", "name": "Alice" }

選擇指南

關係建議原因
文章 + 評論嵌入一起讀取,限制數量
使用者 + 訂單參考訂單可能會很多
產品 + 類別參考類別會重複使用
訂單 + 品項嵌入一起讀取,數量有限
標籤參考可重複使用,標準化

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.

相關技能