feat: update audit logging function for tracking changes in database

This commit is contained in:
Danel Kungla
2025-08-26 16:13:17 +03:00
parent 5d92c34259
commit db6d29c208

View File

@@ -0,0 +1,42 @@
create or replace function audit.log_audit_changes()
returns trigger
language plpgsql
as $$
declare
current_user_id uuid;
current_user_role text;
begin
begin
current_user_id := auth.uid();
current_user_role := auth.jwt() ->> 'role';
end;
insert into audit.log_entries (
schema_name,
table_name,
record_key,
operation,
row_data,
changed_data,
changed_by,
changed_by_role
)
values (
tg_table_schema,
tg_table_name,
case when tg_op in ('DELETE', 'UPDATE') then
COALESCE( to_jsonb(OLD)->>'id',
to_jsonb(OLD)->>'user_id',
to_jsonb(OLD)->>'account_id' )
else null
end,
tg_op,
case when tg_op in ('DELETE', 'UPDATE') then to_jsonb(old) else null end,
case when tg_op in ('INSERT', 'UPDATE') then to_jsonb(new) else null end,
current_user_id,
current_user_role
);
return null;
end;
$$;