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, if you use it as an
AFTER
trigger, an ERROR
trigger is raised and the current (sub)transaction is rolled back.
It will also be easy to add a log of the deleted attempts into a table in this same trigger function in order to help enforce the company policy—just add INSERT
to a log table that is similar to the table in the previous example.
Of course, you can make one or both the messages more menacing if you want, by adding something such as ''Authorities will be notified!'' or ''You will be terminated!''.
Let's take a look at how this works in the following code:
postgres=# CREATE TABLE delete_test1(i int); CREATE TABLE postgres=# INSERT INTO delete_test1 VALUES(1); INSERT 0 1 postgres=# CREATE TRIGGER disallow_delete AFTER DELETE ON delete_test1 FOR EACH ROW EXECUTE PROCEDURE cancel_op(); CREATE TRIGGER postgres=# DELETE FROM delete_test1 WHERE i = 1; ERROR: YOU ARE NOT ALLOWED TO DELETE ROWS IN public.delete_test1
Notice that the AFTER
trigger raised an error:
postgres=# CREATE TRIGGER skip_delete BEFORE DELETE ON delete_test1 FOR EACH ROW EXECUTE PROCEDURE cancel_op(); CREATE TRIGGER postgres=# DELETE FROM delete_test1 WHERE i = 1; NOTICE: DELETE ON ROWS IN public.delete_test1 WON'T HAPPEN DELETE 0
This time, the
BEFORE
trigger canceled the delete and the AFTER
trigger, although still there, was not reached.
3.149.214.32