Su función de activación no puede funcionar bien, produce el error al insertar una fila:
Debes tratar los tres casos de INSERT
, UPDATE
y DELETE
por separado:
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;