Complete the code to create a trigger function that logs inserts.
CREATE OR REPLACE FUNCTION audit_insert() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(table_name, operation) VALUES ([1], 'INSERT'); RETURN NEW; END; $$ LANGUAGE plpgsql;
The special variable TG_TABLE_NAME holds the name of the table that fired the trigger.
Complete the code to create a trigger that calls the audit function after insert.
CREATE TRIGGER audit_trigger AFTER INSERT ON [1] FOR EACH ROW EXECUTE FUNCTION audit_insert();The trigger must be created on the table you want to audit, here my_table.
Fix the error in the trigger function to correctly log the old row data on DELETE.
CREATE OR REPLACE FUNCTION audit_delete() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(table_name, operation, row_data) VALUES (TG_TABLE_NAME, 'DELETE', [1]); RETURN OLD; END; $$ LANGUAGE plpgsql;
On DELETE triggers, OLD holds the row being deleted.
Fill both blanks to create a trigger function that logs UPDATE operations with old and new row data.
CREATE OR REPLACE FUNCTION audit_update() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(table_name, operation, old_data, new_data) VALUES ([1], 'UPDATE', [2], NEW); RETURN NEW; END; $$ LANGUAGE plpgsql;
TG_TABLE_NAME gives the table name, and OLD holds the old row data before update.
Fill all three blanks to create a trigger that logs all operations with operation type and row data.
CREATE OR REPLACE FUNCTION audit_all_ops() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(table_name, operation, row_data) VALUES ([1], [2], CASE WHEN TG_OP = 'DELETE' THEN [3] ELSE NEW END); RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END; END; $$ LANGUAGE plpgsql;
TG_TABLE_NAME is the table name, TG_OP is the operation type, and OLD is used for row data on DELETE operations.