CREATE OR REPLACE FUNCTION public.record_change_log_create()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
declare
do_log boolean;
old_json jsonb;
new_json jsonb;
begin
select g.is_record_change_log_enabled() into do_log;
if TG_OP = 'INSERT' then
if not do_log then
return new;
end if;
insert into public.record_change_log (
table_schema,
table_name,
table_id,
user_id,
action_type,
new_values,
query
) values (
TG_TABLE_SCHEMA::text,
TG_TABLE_NAME::text,
new.id,
public.user_session_id(),
'INSERT',
public.hstore_to_jsonb(public.hstore(new.*)),
current_query());
return new;
elsif TG_OP = 'UPDATE' then
if not do_log then
return new;
end if;
old_json := public.hstore_to_jsonb(public.hstore(old.*) - public.hstore(new.*));
if
(old_json - array['updated_date', 'update_ts', 'updated_at', 'updated_on', 'updated_ts', 'update_user_id', 'updated_by', 'updated_by_id', 'updated_user_id']) <> '{}'::jsonb
then
new_json := public.hstore_to_jsonb(public.hstore(new.*) - public.hstore(old.*));
insert into public.record_change_log (
table_schema,
table_name,
table_id,
user_id,
action_type,
old_values,
new_values,
query
) values (
TG_TABLE_SCHEMA::text,
TG_TABLE_NAME::text,
new.id,
public.user_session_id(),
'UPDATE',
old_json,
new_json,
current_query()
);
end if;
return new;
elsif TG_OP = 'DELETE' then
if not do_log then
return old;
end if;
insert into public.record_change_log (
table_schema,
table_name,
table_id,
user_id,
action_type,
old_values,
query
) values (
TG_TABLE_SCHEMA::text,
TG_TABLE_NAME::text,
old.id,
public.user_session_id(),
'DELETE',
public.hstore_to_jsonb(public.hstore(old.*)),
current_query());
return old;
end if;
end $function$