Disallowing DELETE

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; ...

Get PostgreSQL Server Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.