DBAtlas · 数据库运维图谱

使用 pg_partman 自动化分区创建和保留

PostgreSQL分区

命令

CREATE SCHEMA partman;
CREATE EXTENSION pg_partman SCHEMA partman;

CREATE TABLE public.measurements (
  id    bigint GENERATED ALWAYS AS IDENTITY,
  ts    timestamptz NOT NULL,
  value numeric,
  PRIMARY KEY (id, ts)
) PARTITION BY RANGE (ts);

-- Daily partitions, pre-create 7 days ahead (pg_partman 5.x syntax)
SELECT partman.create_parent(
  p_parent_table := 'public.measurements',
  p_control      := 'ts',
  p_interval     := '1 day',
  p_premake      := 7
);

-- Drop partitions older than 30 days
UPDATE partman.part_config
   SET retention = '30 days',
       retention_keep_table = false
 WHERE parent_table = 'public.measurements';

-- Maintenance: run periodically (schedule with pg_cron or pg_partman_bgw)
CALL partman.run_maintenance_proc();

-- Any rows in the default partition?
SELECT * FROM partman.check_default(p_exact_count := true);

作用

将父表注册到 pg_partman;预先创建未来分区,删除超过保留期的分区,并报告落入默认分区的行。

适用场景

当需要标准化、可观测的自动化,而不是手工或用自定义脚本管理按日/按月分区时(日志、指标、事件表)。

注意

pg_partman 4.x 与 5.x 之间 API 有变化:在 5.x 中 p_type 只接受 'range'/'list'(默认 'range'),4.x 的 p_type := 'native' 无效;请用 SELECT extversion FROM pg_extension WHERE extname = 'pg_partman'; 检查已安装版本。create_parent 默认还会创建一个默认分区。retention_keep_table = false 会永久 DROP 分区;如需归档,请保持为 true 并使用 retention_schema。如果没有调度 run_maintenance_proc(),则不会创建新分区,数据会落入默认分区。pg_partman_bgw 需要 shared_preload_libraries 加重启。

在 DBAtlas 中打开 →

相关内容