Community程式設計與開發github.com

mianhtsys/landingMod3

在設計或審查 PostgreSQL 專用資料表綱要時使用。涵蓋最佳實踐、資料型別、索引、限制條件、效能模式及進階功能。

landingMod3 是什麼?

這項技能提供了一個全面的 PostgreSQL 資料表設計指南,適用於設計新綱要、審查即將上線的綱要、處理大型資料表分區,或規劃線上綱要變更等情境。它強調正規化到第三正規化(3NF)以消除資料冗餘,並僅在經測量且高回報率的讀取情境下進行反正規化。技能涵蓋了 PostgreSQL 特有的「陷阱」,如識別碼大小寫處理、唯一索引對 NULL 值的寬容、外部鍵需手動建立索引、無自動型別轉換等行為。詳細的型別選擇建議(例如使用 `BIGINT GENERATED ALWAYS AS IDENTITY` 作為主鍵、`TEXT` 取代 `varchar`、`TIMESTAMPTZ` 儲存時間)以及索引、限制條件、分區的豐富實例均包含在內。進階主題則導向 `references/details.md` 的更深層內容。

相容平台~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/postgresql-table-design

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

PostgreSQL 資料表設計

使用時機

  • 正在設計新的 PostgreSQL 綱要,或在資料表上線前進行審查。
  • 為 PostgreSQL 選擇欄位型別、主鍵、限制條件或索引。
  • 決定是否要以及如何對大型資料表進行分區,或如何儲存半結構化資料。
  • 規劃在不中斷服務的情況下對現有資料庫進行綱要變更。

這份文件涵蓋了 PostgreSQL 綱要的規則與決策要點。完整的資料型別目錄、工作負載模式(更新頻繁、插入頻繁、更新插入、綱要演進)、擴充套件、JSONB 索引以及完整的 DDL 範例,皆收錄於 references/details.md;當下方某個小節指向它時,請開啟該文件。

核心規則

  • 為參考資料表(使用者、訂單等)定義 主鍵。時間序列/事件/日誌資料不一定需要。使用主鍵時,偏好 BIGINT GENERATED ALWAYS AS IDENTITY;僅在需要全域唯一性或遮蔽性時才使用 UUID。
  • 先正規化(至 3NF) 以消除資料冗餘與更新異常;僅在證實因關聯查詢導致效能問題且具有高投資報酬率的讀取情境下,才進行反正規化。
  • 在語意上需要的地方都加上 NOT NULL;對常見值使用 DEFAULT。
  • 為你實際會查詢的存取路徑建立索引:主鍵/唯一(自動)、外部鍵欄位(手動!)、常見的篩選/排序條件與關聯鍵。
  • 偏好 TIMESTAMPTZ 儲存事件時間;NUMERIC 儲存金錢;TEXT 儲存字串;BIGINT 儲存整數;DOUBLE PRECISION 儲存浮點數(或使用 NUMERIC 進行精確十進位運算)。

PostgreSQL 陷阱

  • 識別碼:未加引號 → 全小寫。避免使用帶引號或大小寫混合的名稱;請使用 snake_case。
  • 唯一 + NULL:UNIQUE 允許多個 NULL 值。使用 UNIQUE NULLS NOT DISTINCT (...)(PG15+)將唯一限制套用至只允許一個 NULL 值。
  • 外部鍵索引:PostgreSQL 不會自動為外部鍵欄位建立索引。請手動新增。
  • 無自動型別轉換:長度/精確度溢位會直接報錯(不會截斷)。將 999 插入 NUMERIC(2,0) 會失敗,不同於某些會默默截斷或進位的資料庫。
  • 序列/識別欄位會有間隙(正常現象,無需「修復」)。回滾、崩潰與並行事務會留下間隙(例如 1, 2, 5, 6...)。
  • 堆積儲存:預設無叢集主鍵;CLUSTER 是一次性的重組,後續插入不會維持排序。
  • MVCC:更新/刪除會留下死元組;autovacuum 會處理它們——設計時應避免造成熱點資料區塊的寬行頻繁變動。

資料型別

  • ID:BIGINT GENERATED ALWAYS AS IDENTITY;UUID 用於分散式或遮蔽性 ID,可使用 uuidv7()(PG18+)或 gen_random_uuid() 產生。
  • 數值:BIGINT,除非儲存空間非常關鍵;DOUBLE PRECISION 優於 REAL;NUMERIC(p,s) 用於金錢與精確小數。
  • 字串:TEXT,當需要長度限制時搭配 CHECK (LENGTH(col) <= n);BYTEA 用於二進位資料。大小寫不敏感的查詢:對 LOWER(col) 建立表達式索引,或當限制條件也需要大小寫不敏感時使用 CITEXT。
  • 時間:TIMESTAMPTZ、DATE、INTERVAL。now() 是交易開始時間;clock_timestamp() 是真實時間。
  • 布林值:BOOLEAN NOT NULL,除非需要三態。
  • 列舉:僅對小且穩定的集合使用 CREATE TYPE ... AS ENUM;會演變的業務值請使用 TEXT + CHECK 或查詢表。
  • JSONB(優於 JSON)搭配 GIN 索引,僅用於可選或半結構化的屬性。
  • 陣列、範圍、網路、幾何、全文檢索、領域 (domain)、複合型別與向量型別,以及 TOAST 儲存與語系排序控制:請參閱 references/details.md。

應避免的型別

避免使用改用
timestamp(不帶時區)timestamptz
char(n), varchar(n)text(必要時加上 CHECK 長度限制)
moneynumeric
timetztimestamptz
timestamptz(0) 或任何精確度timestamptz
serialgenerated always as identity

限制條件

  • 主鍵:隱含 UNIQUE + NOT NULL;建立一個 B-tree 索引。
  • 外部鍵:指定 ON DELETE/UPDATE(CASCADE, RESTRICT, SET NULL, SET DEFAULT)。為參考欄位建立索引。使用 DEFERRABLE INITIALLY DEFERRED 處理會在交易提交時才檢查的循環依賴。
  • 唯一:建立一個 B-tree 索引;允許多個 NULL 值,除非使用 NULLS NOT DISTINCT(PG15+)。偏好 NULLS NOT DISTINCT,除非你希望允許重複的 NULL 值。
  • 檢查:僅限於資料列層級;NULL 值會通過檢查(三值邏輯)。可與 NOT NULL 結合使用:price NUMERIC NOT NULL CHECK (price > 0)。
  • 排除:使用運算子避免重疊,例如 EXCLUDE USING gist (room_id WITH =, booking_period WITH &&) 可防止重複預訂。需要 GiST 相容的型別。

索引

  • B-tree:預設用於等值/範圍查詢(=, <, >, BETWEEN, ORDER BY)。
  • 複合索引:最左前綴規則(WHERE a = ? AND b > ? 可使用 (a,b);WHERE b = ? 則不行)。將選擇性最高的欄位放在最前面。
  • 涵蓋索引:CREATE INDEX ON tbl (id) INCLUDE (name, email) 用於僅索引掃描。
  • 部分索引:熱點子集,CREATE INDEX ON tbl (user_id) WHERE status = 'active'。
  • 表達式索引:CREATE INDEX ON tbl (LOWER(email));查詢必須使用相同的表達式。
  • GIN:JSONB 的包含/存在查詢、陣列、全文檢索。GiST:範圍、幾何、排除限制條件。
  • BRIN:大型、自然有序的資料(時間序列),儲存成本極低;當磁碟順序與索引欄位相關時效果顯著。

分區

  • 用於大型資料表(超過 1 億行),其查詢會一致地依分區鍵進行篩選,或需要依分區鍵進行維護(清除、批次取代)。
  • RANGE 用於時間序列(PARTITION BY RANGE (created_at);TimescaleDB 可自動化處理保留與壓縮)、LIST 用於離散值、HASH 用於在沒有自然鍵的情況下均勻分布。
  • 限制排除:最佳化器透過分區的 CHECK 限制條件來修剪分區;宣告式分區(PG10+)會自動為你建立這些條件。
  • 偏好使用宣告式分區或 hypertable。不要使用資料表繼承。
  • 限制:無全域 UNIQUE 限制條件——必須將分區鍵納入主鍵/唯一索引中。從分區表建立外部鍵需 PG11+,外部鍵參考分區表需 PG12+;在較舊版本上,請使用觸發器。

範例

CREATE TABLE users (
  user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX ON users (LOWER(email));
CREATE INDEX ON users (created_at);
CREATE TABLE orders (
  order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id BIGINT NOT NULL REFERENCES users(user_id),
  status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','PAID','CANCELED')),
  total NUMERIC(10,2) NOT NULL CHECK (total > 0),
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON orders (user_id);
CREATE INDEX ON orders (created_at);
-- JSONB 屬性搭配一個可產生且可索引的純量欄位
CREATE TABLE profiles (
  user_id BIGINT PRIMARY KEY REFERENCES users(user_id),
  attrs JSONB NOT NULL DEFAULT '{}',
  theme TEXT GENERATED ALWAYS AS (attrs->>'theme') STORED
);
CREATE INDEX profiles_attrs_gin ON profiles USING GIN (attrs);

深入探討

references/details.md 包含了本文件僅提及的進階資料:

  • 完整的資料型別目錄:TOAST 儲存、語系排序、陣列、範圍、網路、幾何、文字搜尋、領域、複合型別、向量。
  • 資料表型別(TEMPORARY, UNLOGGED)與資料列層級安全。
  • 限制條件與索引注意事項,以及 RANGE、LIST 和 HASH 分區的 DDL。
  • 工作負載模式:更新頻繁、插入頻繁、更新插入設計、安全的綱要演進。
  • 產生欄位與擴充套件(pg_trgm, citext, timescaledb, postgis, pgvector 等)。
  • JSONB 索引策略,包含 jsonb_path_ops 與提取出的 B-tree 欄位。

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

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

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

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.

相關技能