Complete the code to create a trigger function that logs inserts.
CREATE FUNCTION log_insert() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(action, changed_data) VALUES ('INSERT', row_to_json(NEW)); RETURN NEW; END; $$ LANGUAGE [1];
The trigger function must be written in plpgsql for row-level triggers in Supabase/PostgreSQL.
Complete the code to create a trigger that calls the function after an update.
CREATE TRIGGER audit_update AFTER [1] ON users FOR EACH ROW EXECUTE FUNCTION log_update();The trigger should fire after an UPDATE on the table to log changes.
Fix the error in the trigger function to correctly log deleted rows.
CREATE FUNCTION log_delete() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(action, changed_data) VALUES ('DELETE', row_to_json([1])); RETURN OLD; END; $$ LANGUAGE plpgsql;
For DELETE triggers, the OLD record holds the deleted row's data.
Fill both blanks to create a trigger that logs both inserts and updates.
CREATE TRIGGER audit_changes AFTER [1] OR [2] ON orders FOR EACH ROW EXECUTE FUNCTION log_change();
The trigger should fire after both INSERT and UPDATE events to log changes.
Fill all three blanks to create a trigger function that logs action, user, and timestamp.
CREATE FUNCTION log_action() RETURNS trigger AS $$ BEGIN INSERT INTO audit_log(action, changed_by, changed_at) VALUES ([1], [2], [3]); RETURN NEW; END; $$ LANGUAGE plpgsql;
The function logs the action as a string, the current user, and the current timestamp.
