postgresql触发器应用-INSERT-UPDATE-数据表版本表应用

1.实现功能

        主要是给数据库表的数据做数据备份使用,

2.设计实现

        给数据表加上两张表,后缀名his,log,为plt_cus_studenthis,plt_cus_studentlog,his表(历史表)主要记录该表原数据,log表(日志表)主要记录数据操作日志

        案例表

        历史表 :plt_versionid,历史表主键id,确定唯一数据唯一id,plt_dataversion,某条数据版本号,记录数据多次变更记录,属性名得取dataversion而不是version,怕原表已经有version属性,引起冲突。

        日志表:plt_oid是记录原表数据id,plt_dataversion是操作数据版本,这两个字段可以确定历史表中哪条数据的操作记录,plt_operationlog记录修改了那些字段信息,plt_updatetime修改时间

3.具体实现

3.1创建触发器函数

create or replace function plt_cus_student_update()
returns trigger
AS $$
declare
  version_max integer; 
  operation_log text;
begin
  if tg_op = 'UPDATE' then 
  	operation_log = '';
    SELECT MAX(plt_dataversion) into version_max FROM plt_cus_studenthis where id = old.id;
	if version_max is NULL then version_max=0;
	else
	version_max = version_max+1;
	end if;
	if version_max = 0 then INSERT INTO public.plt_cus_studenthis(id, name, age, plt_dataversion)VALUES (old.id, old.name, old.age, 0);
    else
	INSERT INTO public.plt_cus_studenthis(id, name, age, plt_dataversion)VALUES (old.id, old.name, old.age, version_max);
  	end if;
	if old.name!=new.name then operation_log = operation_log || '修改了name字段,';
	end if;
	if old.age!=new.age then operation_log = operation_log || '修改了age字段,';
	end if;	
	
	INSERT INTO public.plt_cus_studentlog(plt_oid, plt_operationlog, plt_updatetime,plt_dataversion)VALUES ( old.id, operation_log, current_timestamp,version_max);
  end if;	
  return new;
end $$
language plpgsql;

备注:version_max,是查看该条数据是否有版本,没有就设当前版本为0,|| 运算符是字符串拼接

3.2给表的update的事件触发器绑定函数

create trigger plt_cus_student_change
before UPDATE
on plt_cus_student
for each row
execute function plt_cus_student_update();

3.3查看表的触发器

SELECT tgname, tgisinternal, tgtype, tgrelid::regclass, tgfoid::regproc, tgattr, tgqual, tgdeferrable, tginitdeferred, tgnargs, tgargs
FROM pg_trigger
WHERE tgrelid = 'plt_cus_student'::regclass;

4.实现效果

4.1修改学生表数据

4.2可以查看到his表记录的数据

4.3可以查看到log表记录的数据

备注:在原表plt_cus_student表中修改了两次数据,在his表记录两次表修改前数据,同样log表中记录修改记录

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值