mcpField
P
postgresql-best-practices

postgresql-best-practices

github.com/wimolivier数据与数据库5172 次安装27 周前更新
代码仓库

关于 postgresql-best-practices

面向 PostgreSQL 18+ 开发者的实践指南集合,涵盖数据库架构、SQL 编码、迁移、测试、性能与运维。内容以 schema 分层、API 函数和安全规范为核心,并提供参考文档与可执行迁移脚本。

主要功能

  1. 01提供 data、private、api schema 分层模式
  2. 02涵盖函数、过程、触发器与命名规范
  3. 03包含迁移系统文档和可执行脚本
  4. 04覆盖测试、性能、安全和数据处理模式
  5. 05列出 PostgreSQL 18+ 功能及反模式

适用场景

  1. 01设计应用访问数据库的 API 层
  2. 02建立版本化数据库迁移流程
  3. 03检查查询性能与索引策略
  4. 04实现多租户隔离、审计或向量搜索

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wimolivier/postgresql-best-practices --skill postgresql-best-practices

安装后在 Claude Code 中输入/postgresql-best-practices确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
CLAUDE.md
references/
checklists-troubleshooting.md
anti-patterns.md
audit-logging.md
bulk-operations.md
backup-recovery.md
cicd-integration.md
analytical-queries.md
coding-standards-trivadis.md
data-types.md
indexes-constraints.md
full-text-search.md
encryption.md
event-sourcing.md
data-warehousing-medallion.md
migrations.md
oracle-migration-guide.md
jsonb-patterns.md
monitoring-observability.md
plpgsql-table-api.md
partitioning.md
performance-tuning.md
queue-patterns.md
postgis-patterns.md
replication-ha.md
quick-reference.md
schema-naming.md
row-level-security.md
schema-architecture.md

详细介绍

PostgreSQL 高级最佳实践(PostgreSQL 18+)

架构一览

                        ┌─── PostgreSQL Database ──────────────────────────────┐
                        │                                                      │
                        │  ┌──────────────────┐    ┌───────────────────────┐   │
                        │  │   api schema      │    │   private schema      │   │
  ┌─────────────┐       │  │──────────────────│    │───────────────────────│   │
  │ Application │─EXECUTE─▶│ get_customer()   │───▶│ set_updated_at()     │   │
  └─────────────┘       │  │ insert_order()   │    │ hash_password()      │   │
        │               │  └────────┬─────────┘    └──────────┬────────────┘   │
        │               │           │                         │                │
        │               │           │ SECURITY DEFINER        │ triggers       │
        │               │           ▼                         ▼                │
        │               │  ┌──────────────────────────────────────────────┐    │
        │               │  │              data schema                     │    │
     BLOCKED            │  │──────────────────────────────────────────────│    │
        │               │  │  customers    orders    ...                  │    │
        └ ─ ─ ─ ✕       │  └──────────────────────────────────────────────┘    │
                        │                                                      │
                        └──────────────────────────────────────────────────────┘

技能内容

🚀 入门(请先阅读)
文档用途
quick-reference.md快速查阅 - 单页速查表(请打印!)
schema-architecture.md从这里开始 - Schema 分离模式(data/private/api)
coding-standards-trivadis.md编码标准与命名约定(l_、g_、co_)
📚 核心参考(每日使用)
文档用途
plpgsql-table-api.md表 API 函数、过程、触发器
schema-naming.md所有对象的命名约定
data-types.md数据类型选择(UUIDv7、text、timestamptz)
indexes-constraints.md索引类型、策略、约束
migrations.md原生迁移系统文档
anti-patterns.md需要避免的常见错误
checklists-troubleshooting.md项目检查清单与问题解决方案
🔧 高级主题(按需查阅)
文档用途
testing-patterns.mdpgTAP 单元测试、测试工厂
performance-tuning.mdEXPLAIN ANALYZE、查询优化、JIT
row-level-security.mdRLS 模式、多租户隔离
jsonb-patterns.mdJSONB 索引、查询、验证
audit-logging.md通用审计触发器、变更跟踪
bulk-operations.mdCOPY、批量插入、Upsert
session-management.md会话变量、连接池
transaction-patterns.md隔离级别、锁定、死锁预防
full-text-search.mdtsvector、tsquery、排名、多语言
partitioning.md范围、列表、哈希分区策略
window-functions.md窗口帧、排名、累计计算
time-series.md时间序列数据模式、BRIN 索引
event-sourcing.md事件存储、投影、CQRS
queue-patterns.md作业队列、SKIP LOCKED、LISTEN/NOTIFY
encryption.mdpgcrypto、列加密、TLS
vector-search.mdpgvector、嵌入向量、相似性搜索
postgis-patterns.md空间数据、地理查询
🚀 DevOps 与迁移
文档用途
oracle-migration-guide.mdPL/SQL 到 PL/pgSQL 的转换
cicd-integration.mdGitHub Actions、GitLab CI、Docker
monitoring-observability.mdpg_stat_statements、指标、告警
backup-recovery.mdpg_dump、pg_basebackup、PITR
replication-ha.md流复制/逻辑复制、故障转移
📊 数据仓库
文档用途
data-warehousing-medallion.mdMedallion 架构 - Bronze/Silver/Gold、数据沿袭、ETL
analytical-queries.md分析型查询模式、OLAP 优化、GROUPING SETS
可执行脚本
脚本用途
001_install_migration_system.sql安装迁移系统(核心函数)
002_migration_runner_helpers.sql辅助过程(run_versioned、run_repeatable)
003_example_migrations.sql迁移模式示例
999_uninstall_migration_system.sql完全移除迁移系统

核心架构

模式隔离模式
Application → api schema → data schema
                ↓
            private schema (triggers, helpers)
模式包含内容访问权限用途
data表、索引无数据存储
private触发器、辅助函数无内部逻辑
api函数、过程应用程序外部接口
app_audit审计表管理员更改跟踪
app_migration迁移跟踪管理员模式版本管理
安全模型

所有 api 函数都必须具备:

SECURITY DEFINER
SET search_path = data, private, pg_temp

快速参考

创建表模式
CREATE TABLE data.{table_name} (
    id              uuid PRIMARY KEY DEFAULT uuidv7(),
    -- columns...
    created_at      timestamptz NOT NULL DEFAULT now(),
    updated_at      timestamptz NOT NULL DEFAULT now()
);

CREATE TRIGGER {table}_bu_updated_trg
    BEFORE UPDATE ON data.{table_name}
    FOR EACH ROW EXECUTE FUNCTION private.set_updated_at();
API 函数模式
CREATE FUNCTION api.{action}_{entity}(in_param type)
RETURNS TABLE (col1 type, col2 type)
LANGUAGE sql STABLE
SECURITY DEFINER
SET search_path = data, private, pg_temp
AS $$
    SELECT col1, col2 FROM data.{table} WHERE ...;
$$;
API 过程模式
CREATE PROCEDURE api.{action}_{entity}(
    in_param type,
    INOUT io_id uuid DEFAULT NULL
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = data, private, pg_temp
AS $$
BEGIN
    INSERT INTO data.{table} (...) VALUES (...) RETURNING id INTO io_id;
END;
$$;
迁移模式
SELECT app_migration.acquire_lock();

CALL app_migration.run_versioned(
    in_version := '001',
    in_description := 'Description',
    in_sql := $mig$ ... $mig$,
    in_rollback_sql := '...'
);

SELECT app_migration.release_lock();

命名约定

Trivadis 风格的变量前缀
前缀类型示例
l_局部变量l_customer_count
g_会话/全局变量g_current_user_id
co_常量co_max_retries
in_IN 参数in_customer_id
out_OUT 参数(仅函数)out_total
io_INOUT 参数(过程)io_id
c_游标c_active_orders
r_记录r_customer
t_数组/表t_order_ids
e_异常e_not_found

注意:PostgreSQL 过程仅支持 INOUT 参数,不支持 OUT。所有过程输出参数都使用 io_ 前缀。

数据库对象
对象模式示例
表snake_case,复数orders、order_items
列snake_casecustomer_id、created_at
主键idid
外键{table_singular}_idcustomer_id
索引{table}_{cols}_idxorders_customer_id_idx
唯一约束{table}_{cols}_keyusers_email_key
函数{action}_{entity}get_customer、select_orders
过程{action}_{entity}insert_order、update_status
触发器{table}_{timing}{event}_trgorders_bu_trg

数据类型建议

使用替代
textchar(n)、varchar(n)
numeric(p,s)money、float
timestamptztimestamp
booleaninteger 标志
uuidv7()serial、uuid_generate_v4()
GENERATED ALWAYS AS IDENTITYserial、bigserial
jsonbjson、EAV 模式

关键反模式

  1. ❌ 应用程序直接访问表
  2. ❌ RETURNS SETOF table(会暴露所有列)
  3. ❌ 使用 SECURITY DEFINER 却未设置 SET search_path
  4. ❌ 使用不带时区的 timestamp
  5. ❌ 在子查询中使用 NOT IN(应使用 NOT EXISTS)
  6. ❌ 对时间戳使用 BETWEEN(应使用 >= AND <)
  7. ❌ 外键缺少索引
  8. ❌ 使用 serial/bigserial(应使用 IDENTITY)
  9. ❌ 使用 varchar(n) 设置任意长度限制(应使用 text)
  10. ❌ 使用 SELECT FOR UPDATE 却未指定 NOWAIT/SKIP LOCKED

PostgreSQL 18+ 功能

功能用法
uuidv7()id uuid DEFAULT uuidv7() - 按时间排序的 UUID
虚拟生成列col type GENERATED ALWAYS AS (expr) - 在查询时计算
RETURNING 中的 OLD/NEWUPDATE ... RETURNING OLD.col, NEW.col
时态约束PRIMARY KEY (id) WITHOUT OVERLAPS
NOT VALID 约束添加约束时无需完整扫描表

文件组织

db/
├── migrations/
│   ├── V001__create_schemas.sql
│   ├── V002__create_tables.sql
│   └── repeatable/
│       ├── R__private_triggers.sql
│       └── R__api_functions.sql
├── schemas/
│   ├── data/           # Table definitions
│   ├── private/        # Internal functions
│   └── api/            # External interface
└── seeds/              # Reference data

评论

支持 Markdown