In order to maintain audit log for the table test_table, I need to create triggers on the base table for INSERT, UPDATE and DELETE events and then insert these records in an audit table.
I can create trigger (and also associated procedure) in the following manner:
Create the procedure as:
CREATE OR REPLACE FUNCTION audit_test_table_function() RETURNS TRIGGER AS $body$
BEGIN
IF (TG_OP = 'DELETE') THEN
INSERT INTO audit_test_table VALUES (OLD.*, now(), user, pg_backend_pid(), 'D', DEFAULT);
RETURN OLD;
ELSIF (TG_OP = 'UPDATE') THEN
INSERT INTO audit_test_table VALUES (NEW.*, now(), user, pg_backend_pid(), 'U', DEFAULT);
RETURN NEW;
ELSIF (TG_OP = 'INSERT') THEN
INSERT INTO audit_test_table VALUES (NEW.*, now(), user, pg_backend_pid(), 'I', DEFAULT);
RETURN NEW;
END IF;
RETURN NULL;
END; $body$ LANGUAGE plpgsql;
And then create the trigger:
CREATE TRIGGER audit_test_table_trigger AFTER INSERT OR UPDATE OR DELETE ON test_table FOR EACH ROW EXECUTE PROCEDURE audit_test_table_function();
Other option would be to create the trigger/function for individual events ie separate one for DELETE event as following:
CREATE OR REPLACE FUNCTION audit_test_table_delete_function() RETURNS TRIGGER AS $body$
BEGIN
INSERT INTO audit_test_table VALUES (OLD.*, now(), user, pg_backend_pid(), 'D', DEFAULT);
RETURN OLD;
END;
$body$ LANGUAGE plpgsql;
CREATE TRIGGER audit_test_table_trigger AFTER DELETE ON test_table FOR EACH ROW EXECUTE PROCEDURE audit_test_table_delete_function();
And similarly for INSERT and UPDATE events.
My question is performance wise which one is recommended. And is there anything else that I should keep in mind?
I have already checked this but it doesn't answer my question.
You'll save a little execution time if you write three simpler functions, but I doubt that it is worth the effort.
If performance is paramount, you might consider writing the trigger functions in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With