What if our business requirements are such that the data can only be added and modified in some tables, but not deleted?
One way to handle this will be to just revoke the DELETE
rights on these tables from all the users (remember to also revoke DELETE
from PUBLIC
), but this can also be achieved using triggers because of reasons such as auditing or returning custom exception messages.
A generic
cancel
trigger can be written as follows:
CREATE OR REPLACE FUNCTION cancel_op() RETURNS TRIGGER AS $$ BEGIN IF TG_WHEN = 'AFTER' THEN RAISE EXCEPTION 'YOU ARE NOT ALLOWED TO % ROWS IN %.%', TG_OP, TG_TABLE_SCHEMA, TG_TABLE_NAMENAME; END IF; RAISE NOTICE '% ON ROWS IN %.% WON'T HAPPEN', TG_OP, TG_TABLE_SCHEMA, TG_TABLE_NAMENAME; RETURN NULL; END; $$ LANGUAGE plpgsql;
The same trigger function can be used for both the BEFORE
and
AFTER
triggers. If you use it as a BEFORE
trigger, the operation is skipped with a message. However...