postgresql-core-schema

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PostgreSQL Core & Schema

PostgreSQL 核心与Schema设计

When to use this skill

何时使用该技能

  • Creating or modifying PostgreSQL tables (DDL).
  • Working with JSONB, Arrays, or specialized Postgres types.
  • Creating triggers or functions (PL/pgSQL).
  • 创建或修改PostgreSQL表(DDL操作)。
  • 处理JSONB、数组或PostgreSQL专属数据类型。
  • 创建触发器或函数(PL/pgSQL)。

1. Data Types

1. 数据类型

  • Timestamps: Always use
    timestamptz
    (Timestamp with Time Zone), rarely
    timestamp
    (without TZ).
  • Text: Use
    text
    instead of
    varchar(n)
    unless a strict limit is architecturally required.
  • JSON: Use
    jsonb
    (binary) for storage and indexing, not
    json
    .
  • Primary Keys:
    bigint GENERATED ALWAYS AS IDENTITY
    or
    uuid
    (v4/v7).
  • 时间戳:始终使用
    timestamptz
    (带时区的时间戳),尽量避免使用
    timestamp
    (无时区)。
  • 文本类型:使用
    text
    而非
    varchar(n)
    ,除非架构上明确要求严格的长度限制。
  • JSON类型:存储和索引时使用
    jsonb
    (二进制格式),而非
    json
  • 主键:使用
    bigint GENERATED ALWAYS AS IDENTITY
    uuid
    (v4/v7版本)。

2. Constraints & Integrity

2. 约束与完整性

  • Check Constraints: Use
    CHECK
    constraints generously (e.g.,
    CHECK (price > 0)
    ).
  • Foreign Keys: Index all FK columns manually (Postgres does not auto-index them).
  • Exclusion Constraints: Use where
    UNIQUE
    is not enough (e.g., non-overlapping time ranges).
  • 检查约束:大量使用
    CHECK
    约束(例如:
    CHECK (price > 0)
    )。
  • 外键:手动为所有外键列创建索引(PostgreSQL不会自动为其创建索引)。
  • 排他约束:当
    UNIQUE
    约束不足以满足需求时使用(例如:非重叠时间范围)。

3. Advanced Features

3. 高级特性

  • Triggers: Use for audit logs or complex data consistency that cannot be enforced by constraints.
  • Partitions: Consider declarative partitioning for massive time-series tables.
  • Enumerations: Use Native Enums for strict, infrequently changing sets; otherwise use a reference table.
  • 触发器:用于审计日志或无法通过约束实现的复杂数据一致性保障。
  • 分区表:对于大规模时间序列表,考虑使用声明式分区。
  • 枚举类型:对于严格且不常变更的集合,使用原生枚举类型;否则使用参考表。