I'm trying to set up a series of history triggers to automatically collect history for a given table via triggers. I want to use triggers as this guarantees I capture all changes regardless if someone forgets about saving it in the app. My problem is that I have this trigger.
CREATE TRIGGER `db`.`delete_history_trigger` BEFORE DELETE ON `db`.`payments`
FOR EACH ROW BEGIN
INSERT INTO `payments_history` select *, 'delete', NOW(), USER() from `payments` where `PAYMENT_ID` = OLD.`PAYMENT_ID`;
END
//
This stuff everything in payments
into payments_history
and fills out the action that was performed, the date/time the action occurred, the MySQL user that caused the action to be performed. Each user in my app has a USER_ID
(which is from the users
table) that I want to save. For updates this is no problem as USER_ID
is one fields used in the update
query. However, in delete there is no data passed in and therefore NEW is not accessible as there is nothing there. I can't think of a good way to get the USER_ID
to save into the history table on deletes short of doing a second query to update the record. I'd rather not use this solution as it is possible that someone else may forget to call the method to update the record after a delete and that data would be lost.