From db6d29c208d9723b319bf76ea049731443232403 Mon Sep 17 00:00:00 2001 From: Danel Kungla Date: Tue, 26 Aug 2025 16:13:17 +0300 Subject: [PATCH] feat: update audit logging function for tracking changes in database --- .../20250826160800_improve_logging.sql | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 supabase/migrations/20250826160800_improve_logging.sql diff --git a/supabase/migrations/20250826160800_improve_logging.sql b/supabase/migrations/20250826160800_improve_logging.sql new file mode 100644 index 0000000..fc0d6d8 --- /dev/null +++ b/supabase/migrations/20250826160800_improve_logging.sql @@ -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; +$$; +