Saving the USER_ID of a user that deleted a record with a trigger in MySQL

故事扮演 提交于 2019-12-24 07:09:41

问题


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.


回答1:


Set a session variable to the user_id and have the trigger abort the delete if the user_id session variable does not have a value user_id in it.

Query to set user_id in MySQL session:

SET @user_id = <value of user_id>

New delete:

CREATE TRIGGER `db`.`delete_history_trigger` BEFORE DELETE ON `db`.`payments`
   FOR EACH ROW BEGIN
      INSERT INTO `payments_history` select *, 'delete', NOW(), USER(), @user_id from `payments` where `PAYMENT_ID` = OLD.`PAYMENT_ID`;
   END
//


来源:https://stackoverflow.com/questions/1374383/saving-the-user-id-of-a-user-that-deleted-a-record-with-a-trigger-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!