O'Reilly logo

PostgreSQL Server Programming by Jim Mlodgenski, Kirk Roybal, Hannu Krosing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Disallowing DELETE

What if our business requirements are such that data can only be added and modified in some tables, but not deleted?

One way to handle this would be to just revoke the DELETE right on these tables from all users (remember to also revoke DELETE from PUBLIC), but this can also be achieved using triggers.

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_NAME; 
    END IF; 
    RAISE NOTICE '% ON ROWS IN %.% WON''T HAPPEN', 
                          TG_OP, TG_TABLE_SCHEMA, TG_TABLE_NAME; 
    RETURN NULL; 
END; 
$$ LANGUAGE plpgsql; 

The same trigger function can be used for both BEFORE and

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required