Din triggerfunktion kan inte fungera bra, den skapar felet när du infogar en rad:
Du bör behandla de tre fallen av INSERT
, UPDATE
och DELETE
separat:
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;