Вашата тригерна функция не може да работи добре, тя създава грешка при вмъкване на ред:
Трябва да третирате трите случая на INSERT
, UPDATE
и DELETE
отделно:
create or replace function changelog_procedure()
returns trigger as $$
declare
json_new jsonb;
json_old jsonb;
begin
if tg_op = 'INSERT' then
json_new:= to_jsonb(new);
elsif tg_op = 'DELETE' then
json_old:= to_jsonb(old);
else
select jsonb_object_agg(new_key, new_value), jsonb_object_agg(old_key, old_value)
into json_new, json_old
from jsonb_each(to_jsonb(new)) as n(new_key, new_value)
join jsonb_each(to_jsonb(old)) as o(old_key, old_value)
on new_key = old_key and new_value <> old_value;
end if;
insert into tbl_changelog(tbl, op, new, old)
values (tg_table_name, tg_op, json_new, json_old);
return null;
end;
$$ language plpgsql;