标签
PostgreSQL , 自动创建分区 , 触发器 , 写入 , 动态创建分区
背景
数据写入时,自动创建分区。
目前pg_pathman这个分区插件,有这个功能,如果你不是用的这个插件,可以考虑一下用触发器写入,并在触发器中实现自动创建分区。
例子
1、创建主表,索引
create table test(id int, info text, crt_time timestamp not null );
create index idx_test_1 on test(id);
create index idx_test_2 on test(crt_time);
2、创建写入触发器,在触发器内,根据错误判断是否需要建表
长连接,使用绑定变量来写入,性能比动态SQL更好。
create or replace function ins_tg() returns trigger as $$
declare
-- 分区后缀
suffix text := to_char(NEW.crt_time,'yyyymmdd');
begin
-- 乐观实现,执行绑定变量
execute format('execute p%s(%s, %L, %L)', suffix, NEW.id, NEW.info, NEW.crt_time);
return null;
exception
when others then
-- 自动建分区, 有必要的话,你可以把分区表的分区键约束也在这个QUERY中添加一下。