Disparador: mover elimina filas de tabla de archivo
-
16-10-2019 - |
Pregunta
Tengo una tabla pequeña (~ 10 filas) restrictions
llamada en mi base de datos PostgreSQL, donde se eliminan los valores e insertados en una base diaria.
Me gustaría tener una tabla llamada restrictions_deleted
, donde cada fila que se elimina de restrictions
se almacenará automáticamente. Desde restrictions
tiene un ID de serie, no habrá duplicados.
¿Cómo escribo un disparador tal en PostgreSQL?
Solución
You just need to move the old data into the restrictions_deleted
table before it gets deleted. This is done with the OLD
data type. You can use a regulat INSERT
statement and and use the OLD
values as the values-to-be-inserted.
CREATE TRIGGER moveDeleted
BEFORE DELETE ON restrictions
FOR EACH ROW
EXECUTE PROCEDURE moveDeleted();
CREATE FUNCTION moveDeleted() RETURNS trigger AS $$
BEGIN
INSERT INTO restrictions_deleted VALUES(OLD.column1, OLD.column2,...);
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
Otros consejos
If you are open to a different approach, Have you considered adding a 'deleted' Boolean flag to the table, or a 'deleted_at' timestamp instead.
Or better still, deny CRUD access to your database tables and handle the audit trail in your transactional API :)