Created
March 19, 2020 16:07
-
-
Save dorkness-io/f043d63b3e1889edda2d588b4f1cb0b5 to your computer and use it in GitHub Desktop.
SQL to create a logging schema and table, create a stored procedure for logging CUD events and implement that stored procedure on a table.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Create a special schema to store our logging data | |
create schema logging; | |
-- Create a new table within the schema to log our events | |
create table logging.events | |
( | |
id serial | |
,timestamp timestamptz default current_timestamp | |
,schema_name text | |
,table_name text | |
,operation text | |
,new_row json | |
,old_row json | |
); | |
-- Create the stored procedure to log create, update, & delete events | |
create or replace function logging.log_trigger() | |
returns trigger AS $$ | |
begin | |
if (lower(tg_op) = 'insert') then | |
insert into logging.events (schema_name, table_name, operation, new_row) | |
values (tg_table_schema, tg_relname, tg_op, row_to_json(new)); | |
return new; | |
elsif (lower(tg_op) = 'update') then | |
insert into logging.events (schema_name, table_name, operation, old_row, new_row) | |
values (tg_table_schema, tg_relname, tg_op, row_to_json(old), row_to_json(new)); | |
return new; | |
elsif (lower(tg_op) = 'delete') then | |
insert into logging.events (schema_name, table_name, operation, old_row) | |
values (tg_table_schema, tg_relname, tg_op, row_to_json(old)); | |
return old; | |
end if; | |
return null; | |
end; | |
$$ language 'plpgsql' security definer; | |
-- Drop any existing trigger with this name (shouldn't be any, but let's be safe) on jiraissue | |
drop trigger if exists log_events on jiraissue; | |
-- Create new trigger to capture events after creating, deleting or insert a row into jiraissue | |
create trigger log_events | |
after insert or update or delete on jiraissue | |
for each row execute procedure logging.log_trigger(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment