Since MySQL ignores check constraints, how does one go about using a trigger to stop an insert or update from happening?
For example:
Table foo has an attribute called agency, and the agency attribute can only be 1, 2, 3, 4, or 5.
delimiter $$
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency > 5) then
#Do nothing?
end if;
end
$$
delimiter ;
Or is there a better way to go about doing check constraints in MySQL?
Try the SIGNAL syntax - https://dev.mysql.com/doc/refman/5.5/en/signal.html
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency >5) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'your error message';
end if
end
EDIT
Updated based on popular comment below by Bill Karwin.
If your version of MySQL is older than 5.5, try setting a non-null field of the table to NULL. It is a hack, but it does prevent the update or insert from completing.
The SIGNAL command which Naveen suggests looks great, and I'm looking forward to using it after we upgrade.
Related
I have a trigger in MySQL
DELIMITER $$
CREATE TRIGGER trigger2
BEFORE INSERT ON participated FOR EACH ROW
BEGIN
IF((SELECT COUNT(*) FROM participated WHERE driver_id = NEW.driver_id) > 3) THEN
DELETE FROM accident WHERE report_no = NEW.report_no;
SIGNAL SQLSTATE '45000' SET message_text = "Driver is already involved in 3 accciddents";
END IF;
END;$$
DELIMITER ;
First an accident report is inserted into accident table. Before inserting in to participated table if it involves a driver who has participated in more than 3 accident a waring has to be given and driver's data in accident table should be deleted.
'accident' and 'participated' are the two tables.
accident(report_no,date,location);
participated(driver_id,reg_no,report_no,amount);
ex:
insert into accident values(34,"2022-04-05","bangalore");
insert into participated values("D1","KA-09-MM-5644",34,20000);
ERROR 1644 (45000): Driver is already involved in 3 accciddents
Warning is working but it is not deleting the row in accident table. accident table still has the row with report_no 34
The body part in Mysql trigger is like a single ALL-OR-NOTHING transaction. This means every query inside has to be successful, or the entire process is undone. By using SIGNAL SQLSTATE '45000' SET message_text , an error is intentionally raised, which rolls back every thing that has happend so far, and a message is returned. Note, the INSERT statement itself is cancelled due to error induced. Of course, it's possible to ignore the error by declaring a continue handler in the very begining of the trigger.
BEGIN
declare continue handler for SQLSTATE '45000' begin end;
IF((SELECT COUNT(*) FROM participated WHERE driver_id = NEW.driver_id) > 3) THEN
DELETE FROM accident WHERE report_no = NEW.report_no;
SIGNAL SQLSTATE '45000' SET message_text = "Driver is already involved in 3 accciddents";
END IF;
END
This will make sure things keep going after SQLSTATE '45000' is encountered. However, the message_text is IGNORED, as it's only intended to show up to address a warning/error, not for a continue handler. And regrettably, we can not return a result set using a trigger. So if we add a SELECT statement or something alike after the SIGNAL statement , an error will pop up:
select "Driver is already involved in 3 accciddents" as a warning;
-- OR
show warnings;
-- Error Code: 1415. Not allowed to return a result set from a trigger
If we really need a message to show up,we can considering using a procedure to bypass the restriction enforced by trigger:
DELIMITER $$
CREATE TRIGGER trigger2
BEFORE INSERT ON participated FOR EACH ROW
BEGIN
IF((SELECT COUNT(*) FROM participated WHERE driver_id = NEW.driver_id) > 3) THEN
DELETE FROM accident WHERE report_no = NEW.report_no;
SET #warning = "Driver is already involved in 3 accciddents"; -- here we don't really need a SIGNAL statement. Just creating a user variable is adequate.
else set #warning=null;
END IF;
END$$
create procedure insert_participated (d_id varchar(20),rg_no varchar(20),rp_no int,amt int)
begin
insert into participated values(d_id,rg_no,rp_no,amt);
if #warning is not null then
select #warning as warning;
end if;
end $$
DELIMITER ;
By using a procedure ,we can display a message. And if we directly use an insert statement(when we forget to use the procedure), the trigger's operation still applies. Therefore, we might think about adding an INSERT statement to populate an auditing table for future reference.
I'm in the process of converting some SQL Server triggers to MySQL, and am running into some syntax issues. The rest of the database schema and objects were converted using the AWS Schema Conversion Tool, as I'm migrating a SQL Server database to Aurora RDS MySQL. Here's an example of a trigger I'm having trouble converting:
-- Create the UpdateAUD trigger on the new table.
CREATE TRIGGER [dbo].[UpdateAUD] ON [dbo].[AUD]
INSTEAD OF UPDATE
AS
BEGIN
IF ##ROWCOUNT > 0
BEGIN
RAISERROR( 'Audit rows for AUD cannot be updated!', -1, 0 );
ROLLBACK;
END
END;
The code that I've tried looks like:
DELIMITER $$
-- Create the UpdateAUD trigger on the new table.
CREATE TRIGGER dbo.UpdateAUD
AFTER UPDATE
ON dbo.AUD FOR EACH ROW
BEGIN
set msg = ('Audit rows for AUD cannot be updated!');
signal sqlstate '45000' set message_text = msg;
ROLLBACK;
END$$
First, does AFTER work to replace INSTEAD OF? Secondly, MySQL workbench is having an issue with the RAISERROR, which I've looked up workarounds for. However the error I'm getting is around theh msg variable where it's saying Unknown system variable 'msg'
Any ideas?
It has to be a BEFORE UPDATE TRIGGER, so that the UPDATE is interupted
You could also
REVOKE UPDATE ON AUD FROM '*'#'localhost';
and so nobody could UPDATE the table anymore
CREATE TABLE AUD (id int)
INSERT INTO AUD VALUES(1)
CREATE TRIGGER UpdateAUD
BEFORE UPDATE
ON AUD FOR EACH ROW
BEGIN
set #msg := 'Audit rows for AUD cannot be updated!';
signal sqlstate '45000' set message_text = #msg;
END
✓
UPDATE AUD SET id = 1 WHERE id = 1
Audit rows for AUD cannot be updated!
db<>fiddle here
I ended up revising to
DELIMITER $$
-- Create the UpdateAUD trigger on the new table.
CREATE TRIGGER dbo.UpdateAUD
BEFORE UPDATE
ON dbo.AUD FOR EACH ROW
BEGIN
signal sqlstate '45000' set message_text = 'Audit rows for AUD cannot be updated!';
END$$
Per documentation, there's no need for ROWCOUNT since FOR EACH ROW should handle that. As far as the ROLLBACK goes, I checked https://dev.mysql.com/doc/refman/5.6/en/trigger-syntax.html and saw that it should be handled as well.
Does this look like a good conversion from the original MS-SQL posted at the top?
After this trigger i dont get a warning if i inserted 5 in foo.x
\d $
CREATE TRIGGER `tri` BEFORE INSERT ON `foo` FOR EACH ROW
BEGIN
IF NEW.bar = 5 THEN
SIGNAL SQLSTATE '01002' SET MESSAGE_TEXT = 'MSG';
END IF;
END$\d ;
INSERT INTO `foo` values (5);
1 row affected
As documented under Changes in MySQL 5.5.8 (2010-12-03, General Availability):
Bugs Fixed
[ deletia ]
Warnings raised by a trigger were not cleared upon successful completion. Now warnings are cleared if the trigger completes successfully, per the SQL standard. (Bug #55850)
Are you sure that trigger was created? I have got two errors.
Try to use this statement instead -
SIGNAL SQLSTATE '01002' SET MESSAGE_TEXT = 'MSG';
'010002' -> '01002'
TEXT_MESSAGE -> MESSAGE_TEXT
SIGNAL Syntax.
Since MySQL ignores check constraints, how does one go about using a trigger to stop an insert or update from happening?
For example:
Table foo has an attribute called agency, and the agency attribute can only be 1, 2, 3, 4, or 5.
delimiter $$
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency > 5) then
#Do nothing?
end if;
end
$$
delimiter ;
Or is there a better way to go about doing check constraints in MySQL?
Try the SIGNAL syntax - https://dev.mysql.com/doc/refman/5.5/en/signal.html
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency >5) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'your error message';
end if
end
EDIT
Updated based on popular comment below by Bill Karwin.
If your version of MySQL is older than 5.5, try setting a non-null field of the table to NULL. It is a hack, but it does prevent the update or insert from completing.
The SIGNAL command which Naveen suggests looks great, and I'm looking forward to using it after we upgrade.
I read this article but it seems not work for delete. I got this error when tried to create a trigger:
Executing SQL script in server
ERROR: Error 1363: There is no NEW row in on DELETE trigger
CREATE TRIGGER DeviceCatalog_PreventDeletion
BEFORE DELETE on DeviceCatalog
FOR EACH ROW
BEGIN
DECLARE dummy INT;
IF old.id = 1 or old.id =2 THEN
SELECT * FROM DeviceCatalog WHERE DeviceCatalog.id=NEW.id;
END IF;
END;
SQL script execution finished: statements: 4 succeeded, 1 failed
Improving #Devart's (accepted) answer with #MathewFoscarini's comment about MySQL SIGNAL Command, instead of raising an error by calling an inexistent procedure you could signal your custom error message.
DELIMITER $$
CREATE TRIGGER DeviceCatalog_PreventDeletion
BEFORE DELETE ON DeviceCatalog
FOR EACH ROW
BEGIN
IF old.id IN (1,2) THEN -- Will only abort deletion for specified IDs
SIGNAL SQLSTATE '45000' -- "unhandled user-defined exception"
-- Here comes your custom error message that will be returned by MySQL
SET MESSAGE_TEXT = 'This record is sacred! You are not allowed to remove it!!';
END IF;
END
$$
DELIMITER ;
The SQLSTATE 45000 was chosen as MySQL's Reference Manual suggests:
To signal a generic SQLSTATE value, use '45000', which means “unhandled user-defined exception.”
This way your custom message will be shown to the user whenever it tries to delete records ID 1 or 2. Also, if no records should be deleted from the table, you could just remove the IF .. THEN and END IF; lines. This would prevent ANY records from being deleted on the table.
Try something like this -
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE DELETE
ON table1
FOR EACH ROW
BEGIN
IF OLD.id = 1 THEN -- Abort when trying to remove this record
CALL cannot_delete_error; -- raise an error to prevent deleting from the table
END IF;
END
$$
DELIMITER ;
Well, the error messages tells you quite clearly: in a DELETE trigger there is no NEW.
In an INSERT trigger you can access the new values with NEW..
In an UPDATE trigger you can access the new values with NEW., the old ones with - you guessed it - OLD.
In a DELETE trigger you can acces the old values with OLD..
It simply makes no sense to have NEW in a DELETE, just as OLD in an INSERT makes no sense.
As the error says: There is no NEW variable on delete.
you can use new.id only on insert and update. Use old.id instead.
SELECT * FROM DeviceCatalog WHERE DeviceCatalog.id=old.id;