Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSTEAD OF DELETE trigger (Postgresql)

I would like to disable the DELETE statement on a table. What I need to do is a SET a field value instead of removing the respective record.

So far I have tried the following:

CREATE TRIGGER delete_trg
INSTEAD OF DELETE
ON schema.tbl
FOR EACH ROW
EXECUTE PROCEDURE schema.tbl_delete_fn();

My schema.tbl_delete_fn() function is as follows:

CREATE OR REPLACE FUNCTION schema.tbl_delete_fn()
  RETURNS trigger AS
BEGIN
  NEW.deleted := true;

  RETURN NEW;
END;

So far this doesn't seem to work... any ideas?

like image 946
Emanuele Mazzoni Avatar asked Aug 13 '13 16:08

Emanuele Mazzoni


People also ask

What is instead of delete trigger?

INSTEAD OF DELETE TRIGGERS are used, to delete records from a view. Introduction. INSTEAD OF DELETE triggers are used to delete records from a View that is based on multiple tables. Description. An INSTEAD OF DELETE trigger gets executed in place of the DELETE event on a table or a View.

What is instead of trigger in PostgreSQL?

INSTEAD OF triggers do not support WHEN conditions. Typically, row-level BEFORE triggers are used for checking or modifying the data that will be inserted or updated. For example, a BEFORE trigger might be used to insert the current time into a timestamp column, or to check that two elements of the row are consistent.

What is Tg_op in PostgreSQL?

TG_OP. Data type text ; a string of INSERT , UPDATE , DELETE , or TRUNCATE telling for which operation the trigger was fired. TG_RELID. Data type oid ; the object ID of the table that caused the trigger invocation. TG_RELNAME.


1 Answers

You want a BEFORE DELETE trigger whose function returns NULL and the row variable is OLD, not NEW.

CREATE TRIGGER delete_trg
BEFORE DELETE
ON schema.tbl
FOR EACH ROW
EXECUTE PROCEDURE schema.tbl_delete_fn();

CREATE OR REPLACE FUNCTION schema.tbl_delete_fn()
  RETURNS trigger AS '
BEGIN
  UPDATE schema.tbl SET deleted=true WHERE ctid=OLD.ctid;
  RETURN NULL;
END; ' language plpgsql;
like image 84
Daniel Vérité Avatar answered Oct 29 '22 14:10

Daniel Vérité