Community编程与开发github.com

mianhtsys/landingMod3

用于设计或审查 PostgreSQL 专属模式的技能。涵盖最佳实践、数据类型、索引、约束、性能模式以及高级特性。

landingMod3 是什么?

该技能专注于 PostgreSQL 表设计,提供从模式设计到审查的完整指导。它涵盖了核心规则,例如使用 BIGINT 自增主键(而非 UUID,除非需要全局唯一性)、优先将数据规范化到第三范式(3NF)、仅在性能瓶颈时进行反规范化,以及建议为所有语义必需的列添加 NOT NULL 约束。技能还详细介绍了 PostgreSQL 特有的陷阱,如标识符大小写处理、唯一约束与 NULL 的行为、外键列不会自动创建索引,以及无提示类型转换异常。在数据类型方面,它推荐使用 TIMESTAMPTZ 处理时间、NUMERIC 处理货币、TEXT 处理字符串,并提供了一个“应避免的类型”对照表。此外,它还深入介绍了索引策略(B-tree、GIN、GiST、BRIN 等)、表分区(RANGE、LIST、HASH)以及 DDL 示例(包括 JSONB 和生成列的使用)。最终,技能将更深入的细节指向一个独立的 `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 模式的规则和决策点。完整的数据类型目录、工作负载模式(更新密集型、插入密集型、upsert、模式演变)、扩展、JSONB 索引以及带有示例的 DDL 都包含在 references/details.md 中;当下面某个部分指向它时,请打开该文件。

核心规则

  • 为引用表(用户、订单等)定义 PRIMARY KEY。对于时序/事件/日志数据,并非总是需要。当使用时,优先使用 BIGINT GENERATED ALWAYS AS IDENTITY;仅在需要全局唯一性/不透明性时使用 UUID。
  • 首先规范化(到 3NF) 以消除数据冗余和更新异常;仅 在可衡量的、高 ROI 的读取场景中,且连接性能被证明确实有问题时,才进行反规范化。
  • 在所有语义上需要的地方添加 NOT NULL;对常见值使用 DEFAULT。
  • 为你实际查询的访问路径创建索引:PK/唯一(自动创建),外键列(手动!),频繁使用的过滤器/排序,以及连接键。
  • 事件时间优先使用 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:更新/删除会留下死元组;VACUUM 负责处理它们——设计时应避免对宽行进行频繁的热更新。

数据类型

  • ID:BIGINT GENERATED ALWAYS AS IDENTITY;对于分布式或不透明 ID 使用 UUID,使用 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 索引,仅用于可选的/半结构化属性。
  • 数组、范围、网络、几何、全文搜索、域、复合类型和向量类型,以及 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 索引;除非使用 NULLS NOT DISTINCT(PG15+),否则允许多个 NULL。除非希望允许重复的 NULL,否则优先使用 NULLS NOT DISTINCT。
  • 检查约束:行级约束;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) 用于索引-only 扫描。
  • 部分索引:针对热点子集,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。不要 使用表继承。
  • 限制:不支持全局唯一约束——必须在主键/唯一约束中包含分区键。从分区表引用的外键需要 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。
  • 工作负载模式:更新密集型、插入密集型、upsert 设计、安全的模式演变。
  • 生成列和扩展(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.

相关技能