当前位置: 移动技术网 > IT编程>数据库>其他数据库 > postgresql 按小时分表(含触发器)的实现方式

postgresql 按小时分表(含触发器)的实现方式

2020年03月09日  | 移动技术网IT编程  | 我要评论

本人后端开发,因为业务需求需要使用分表方式进行数据存储。结合网上的资料最后使用的以下方式:

create or replace function auto_insert_into_tbl_partition()
 returns trigger as
$body$
declare
  time_column_name   text ;      -- 父表中用于分区的时间字段的名称[必须首先初始化!!]
  curmm     varchar(16);    -- 'yyyymm'字串,用做分区子表的后缀
  isexist     boolean;    -- 分区子表,是否已存在
  strsql     text;
  
begin
  -- 调用前,必须首先初始化(时间字段名):time_column_name [直接从调用参数中获取!!]
  time_column_name := tg_argv[0];
  
  -- 判断对应分区表 是否已经存在?
  execute 'select $1.'||time_column_name into strsql using new;
  curmm := to_char( strsql::timestamp , 'yyyymmddhh' );
  select count(1) into isexist from pg_class where relname = ('t_audit_'||curmm);
 
  -- 若不存在, 则插入前需 先创建子分区
  if ( isexist = false ) then 
    -- 创建子分区表
    strsql := 'create table if not exists t_audit_'||curmm||'() inherits (t_audit);' ; 
    execute strsql;
    -- 创建索引
    strsql := 'create index t_audit_'||curmm||'_index_'||time_column_name||' on t_audit_'||curmm||' ('||time_column_name||');' ;
    execute strsql;
  end if;
 
  -- 插入数据到子分区!
  strsql := 'insert into t_audit_'||curmm||' select $1.*' ;
  execute strsql using new;
  return null; 
end
$body$
 language plpgsql;

我是按照小时对固定的一张表进行分表的,其实可以写活就是加个变量,拼sql的时候拼接进去。这个就是写个函数作为触发器的回调函数。就先判断一下这个表有没有,有就直接插,没有就建表再插。

create trigger insert_tbl_partition_trigger
 before insert
 on t_audit
 for each row
 execute procedure auto_insert_into_tbl_partition('time');

建一个触发器,在父表的插入数据的时候执行前面的那个回调函数。

ps:下面看下postgresql 表触发器

1、先建一个函数,用来执行触发器启动后要执行的脚本

create or replace function "public"."trigger_day_aqi"()
 returns "pg_catalog"."trigger" as $body$
begin
  --日均值表,没有o3,小时值表,没有o3_8h
   new.so2iaqi=day_so2_aqi(new.so2);
     new.no2iaqi=day_no2_aqi(new.no2);
     new.coiaqi=day_co_aqi(new.co);
     new.o3_8hiaqi=o3_8_aqi(new.o3_8h);
     new.pm10iaqi=pm10_aqi(new.pm10);
     new.pm25iaqi=pm25_aqi(new.pm25);
     new.aqi=new.coiaqi;
     new.primarypol='co';
    if new.aqi<new.no2iaqi  then  new.aqi=new.no2iaqi;  new.primarypol='no2';  end if;
    if new.aqi<new.so2iaqi  then  new.aqi=new.so2iaqi;  new.primarypol='so2';  end if;
    if new.aqi<new.o3_8hiaqi then  new.aqi=new.o3_8hiaqi;  new.primarypol='o3_8h'; end if;
    if new.aqi<new.pm10iaqi then  new.aqi=new.pm10iaqi;  new.primarypol='pm10';  end if;
    if new.aqi<new.pm25iaqi then  new.aqi=new.pm25iaqi;  new.primarypol='pm2.5'; end if; 
    if new.aqi<=50      then  new.primarypol='-';   end if;
     new.aqilevel=getrank(new.aqi);
  return new;
end;
$body$
 language plpgsql volatile
 cost 100

2、建表的触发器,

create trigger gk_site_day_insert before insert on gk_site_day
  for each row execute procedure trigger_day_aqi();

总结

以上所述是小编给大家介绍的postgresql 按小时分表(含触发器)的实现方式,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网