Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect row from deletion in MySQL

I want to protect some rows from deletion and I prefer to do it using triggers rather than logic of my application. I am using MySQL database.

What I came up with is this:

DELIMITER $$

DROP TRIGGER `preserve_permissions`$$

USE `systemzarzadzaniareporterami`$$

CREATE TRIGGER `preserve_permissions`
AFTER DELETE ON `permissions`
FOR EACH ROW
BEGIN
IF old.`userLevel` = 0 AND old.`permissionCode` = 164 THEN
    INSERT INTO `permissions` SET `userLevel`=0, `permissionCode`=164;
END IF;
END$$

DELIMITER ;

But it gives me an error when I use delete:

DELETE FROM `systemzarzadzaniareporterami`.`permissions`
WHERE `userLevel` = 0 AND `permissionCode` = 164;

Error Code: 1442. Can't update table 'permissions' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

Is there another way to do such a thing?

like image 357
BartoszCichecki Avatar asked Dec 30 '11 23:12

BartoszCichecki


2 Answers

One solution would be to create a child table with a foreign key to your permissions table, and add dependent rows referencing the individual rows for which you want to block deletion.

CREATE TABLE preserve_permissions (
  permission_id INT PRIMARY KEY,
  FOREIGN KEY (permission_id) REFERENCES permissions (permission_id)
);

INSERT INTO perserve_permissions (permission_id) VALUES (1234);

Now you can't delete the row from permissions with id 1234, because it would violate the foreign key dependency.

If you really want to do it with a trigger, instead of re-inserting a row when someone tries to delete it, just abort the delete. MySQL 5.5 has the SIGNAL feature to raise an SQLEXCEPTION in a stored proc or trigger.

If you use MySQL 5.0 or 5.1, you can't use SIGNAL but you can use a trick which is to declare a local INT variable in your trigger and try to assign a string value to it. This is a data type conflict so it throws an error and aborts the operation that spawned the trigger. The extra clever trick is to specify an appropriate error message in the string you try to stuff into the INT, because that string will be reported in the error! :-)

like image 109
Bill Karwin Avatar answered Oct 18 '22 15:10

Bill Karwin


Create one new table and create a foreign key. Set the foreign key on delete - restrict.

CONSTRAINT FOREIGN KEY fk_restriction (restriction_col)
table_to_restrict (restricted_id) ON DELETE RESTRICT ON UPDATE CASCADE

Note: This is not possible to be done with MyISAM, BlackHole, etc. engine. Use with InnoDB and descendant engines.

like image 35
Rolice Avatar answered Oct 18 '22 16:10

Rolice