Throw an error preventing a table update in a MySQL trigger - mysql

If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?

As of MySQL 5.5, you can use the SIGNAL syntax to throw an exception:
signal sqlstate '45000' set message_text = 'My Error Message';
State 45000 is a generic state representing "unhandled user-defined exception".
Here is a more complete example of the approach:
delimiter //
use test//
create table trigger_test
(
id int not null
)//
drop trigger if exists trg_trigger_test_ins //
create trigger trg_trigger_test_ins before insert on trigger_test
for each row
begin
declare msg varchar(128);
if new.id < 0 then
set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));
signal sqlstate '45000' set message_text = msg;
end if;
end
//
delimiter ;
-- run the following as seperate statements:
insert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad
select * from trigger_test;
insert into trigger_test values (1); -- succeeds as expected
insert into trigger_test values (-1); -- fails as expected
select * from trigger_test;

Here is one hack that may work. It isn't clean, but it looks like it might work:
Essentially, you just try to update a column that doesn't exist.

Unfortunately, the answer provided by #RuiDC does not work in MySQL versions prior to 5.5 because there is no implementation of SIGNAL for stored procedures.
The solution I've found is to simulate a signal throwing a table_name doesn't exist error, pushing a customized error message into the table_name.
The hack could be implemented using triggers or using a stored procedure. I describe both options below following the example used by #RuiDC.
Using triggers
DELIMITER $$
-- before inserting new id
DROP TRIGGER IF EXISTS before_insert_id$$
CREATE TRIGGER before_insert_id
BEFORE INSERT ON test FOR EACH ROW
BEGIN
-- condition to check
IF NEW.id < 0 THEN
-- hack to solve absence of SIGNAL/prepared statements in triggers
UPDATE `Error: invalid_id_test` SET x=1;
END IF;
END$$
DELIMITER ;
Using a stored procedure
Stored procedures allows you to use dynamic sql, which makes possible the encapsulation of the error generation functionality in one procedure. The counterpoint is that we should control the applications insert/update methods, so they use only our stored procedure (not granting direct privileges to INSERT/UPDATE).
DELIMITER $$
-- my_signal procedure
CREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))
BEGIN
SET #sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');
PREPARE my_signal_stmt FROM #sql;
EXECUTE my_signal_stmt;
DEALLOCATE PREPARE my_signal_stmt;
END$$
CREATE PROCEDURE insert_test(p_id INT)
BEGIN
IF NEW.id < 0 THEN
CALL my_signal('Error: invalid_id_test; Id must be a positive integer');
ELSE
INSERT INTO test (id) VALUES (p_id);
END IF;
END$$
DELIMITER ;

The following procedure is (on mysql5) a way to throw custom errors , and log them at the same time:
create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;
DELIMITER $$
CREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))
BEGIN
DECLARE errorWithDate varchar(64);
select concat("[",DATE_FORMAT(now(),"%Y%m%d %T"),"] ", errorText) into errorWithDate;
INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);
INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);
END;
$$
DELIMITER ;
call throwCustomError("Custom error message with log support.");

CREATE TRIGGER sample_trigger_msg
BEFORE INSERT
FOR EACH ROW
BEGIN
IF(NEW.important_value) < (1*2) THEN
DECLARE dummy INT;
SELECT
Enter your Message Here!!!
INTO dummy
FROM mytable
WHERE mytable.id=new.id
END IF;
END;

Another (hack) method (if you are not on 5.5+ for some reason) that you can use:
If you have a required field, then within a trigger set the required field to an invalid value such as NULL. This will work for both INSERT and UPDATE. Do note that if NULL is a valid value for the required field (for some crazy reason) then this approach will not work.
BEGIN
-- Force one of the following to be assigned otherwise set required field to null which will throw an error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SET NEW.`required_id_field`=NULL;
END IF;
END
If you are on 5.5+ then you can use the signal state as described in other answers:
BEGIN
-- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';
END IF;
END

DELIMITER ##
DROP TRIGGER IF EXISTS trigger_name ##
CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
--the condition of error is:
--if NEW update value of the attribute age = 1 and OLD value was 0
--key word OLD and NEW let you distinguish between the old and new value of an attribute
IF (NEW.state = 1 AND OLD.state = 0) THEN
signal sqlstate '-20000' set message_text = 'hey it's an error!';
END IF;
END ##
DELIMITER ;

Related

can't update data using trigger [duplicate]

I have created a before insert trigger when new value insert as it's item_sku already exits then delete already exit line and then insert new line. but it shows error:
Error Code: 1442
Can't update table 'order_item_temp' in stored function/trigger because it is already used by statement which invoked this stored function/trigger
Trigger Code is
TRIGGER LINE_DEL AFTER INSERT ON order_item_temp
FOR EACH ROW
BEGIN
DECLARE ITEM_D VARCHAR(50);
SELECT item_sku INTO #ITEM_D
FROM order_item_temp
GROUP BY item_sku,shopify_order_id
HAVING COUNT(item_sku) > 1;
DELETE FROM order_item_temp WHERE item_sku=#item_d;
END;
$$
DELIMITER ;
and by manual entry entering new duplicate line syntax is:
INSERT INTO ehad_db.order_item_temp (
id,
item_sku,
item_uid,
item_sid,
item_qty,
document_item_sid,
document_item_row_version,
ref_order_item_sid,
ref_order_item_row_version,
item_discount_amt,
item_discount_code,
item_discount_type,
item_discount_target,
shopify_order_id,
order_document_sid,
ref_order_sid
)
VALUES
(
'89',
'1000000009574',
'517662213000115019',
'32000000306430',
'1',
'582945547000174220',
'1',
' ',
' ',
'0',
' ',
' ',
' ',
'1903931129956',
'582945544000151211',
' ');
now it shows above error.
It seems you can't delete rows from order_item_temp in your trigger. According to the documentation:
A stored function or trigger cannot modify a table that is already
being used (for reading or writing) by the statement that invoked the
function or trigger.
Instead, you should handle it in your code using transaction like this
start_transaction();
delete_existed_rows();
insert_new_row();
commit();
or you could create a stored procedure that deletes already exited rows and inserts the new one, all in a transaction.
Here is an example code for creating a stored procedure
CREATE PROCEDURE insert_new_row(...)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SIGNAL SQLSTATE 'ERROR'
SET MESSAGE_TEXT = 'INSERT FAILED';
END;
START TRANSACTION;
DECLARE ITEM_D VARCHAR(50);
SELECT item_sku INTO #ITEM_D
FROM order_item_temp
GROUP BY item_sku,shopify_order_id
HAVING COUNT(item_sku) > 1
FOR UPDATE;
DELETE FROM order_item_temp WHERE item_sku=#item_d;
INSERT INTO order_item_temp (...) VALUE (...);
COMMIT;
END;
You cannot put a trigger on order_item_temp that will SELECT/DELETE from the same table order_item_temp. Triggers cannot be used to update/delete the table that triggers them. Triggers should only be used to update other tables, not the one which is triggering the action.
What you are trying to do needs to be written in your coding language, so after you get a positive result for insert, you run the delete SQL.

Can't Working my Before insert trigger in mysql

I have created a before insert trigger when new value insert as it's item_sku already exits then delete already exit line and then insert new line. but it shows error:
Error Code: 1442
Can't update table 'order_item_temp' in stored function/trigger because it is already used by statement which invoked this stored function/trigger
Trigger Code is
TRIGGER LINE_DEL AFTER INSERT ON order_item_temp
FOR EACH ROW
BEGIN
DECLARE ITEM_D VARCHAR(50);
SELECT item_sku INTO #ITEM_D
FROM order_item_temp
GROUP BY item_sku,shopify_order_id
HAVING COUNT(item_sku) > 1;
DELETE FROM order_item_temp WHERE item_sku=#item_d;
END;
$$
DELIMITER ;
and by manual entry entering new duplicate line syntax is:
INSERT INTO ehad_db.order_item_temp (
id,
item_sku,
item_uid,
item_sid,
item_qty,
document_item_sid,
document_item_row_version,
ref_order_item_sid,
ref_order_item_row_version,
item_discount_amt,
item_discount_code,
item_discount_type,
item_discount_target,
shopify_order_id,
order_document_sid,
ref_order_sid
)
VALUES
(
'89',
'1000000009574',
'517662213000115019',
'32000000306430',
'1',
'582945547000174220',
'1',
' ',
' ',
'0',
' ',
' ',
' ',
'1903931129956',
'582945544000151211',
' ');
now it shows above error.
It seems you can't delete rows from order_item_temp in your trigger. According to the documentation:
A stored function or trigger cannot modify a table that is already
being used (for reading or writing) by the statement that invoked the
function or trigger.
Instead, you should handle it in your code using transaction like this
start_transaction();
delete_existed_rows();
insert_new_row();
commit();
or you could create a stored procedure that deletes already exited rows and inserts the new one, all in a transaction.
Here is an example code for creating a stored procedure
CREATE PROCEDURE insert_new_row(...)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
SIGNAL SQLSTATE 'ERROR'
SET MESSAGE_TEXT = 'INSERT FAILED';
END;
START TRANSACTION;
DECLARE ITEM_D VARCHAR(50);
SELECT item_sku INTO #ITEM_D
FROM order_item_temp
GROUP BY item_sku,shopify_order_id
HAVING COUNT(item_sku) > 1
FOR UPDATE;
DELETE FROM order_item_temp WHERE item_sku=#item_d;
INSERT INTO order_item_temp (...) VALUE (...);
COMMIT;
END;
You cannot put a trigger on order_item_temp that will SELECT/DELETE from the same table order_item_temp. Triggers cannot be used to update/delete the table that triggers them. Triggers should only be used to update other tables, not the one which is triggering the action.
What you are trying to do needs to be written in your coding language, so after you get a positive result for insert, you run the delete SQL.

Writing a before delete trigger to delete only based on count of attribute [duplicate]

If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?
As of MySQL 5.5, you can use the SIGNAL syntax to throw an exception:
signal sqlstate '45000' set message_text = 'My Error Message';
State 45000 is a generic state representing "unhandled user-defined exception".
Here is a more complete example of the approach:
delimiter //
use test//
create table trigger_test
(
id int not null
)//
drop trigger if exists trg_trigger_test_ins //
create trigger trg_trigger_test_ins before insert on trigger_test
for each row
begin
declare msg varchar(128);
if new.id < 0 then
set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));
signal sqlstate '45000' set message_text = msg;
end if;
end
//
delimiter ;
-- run the following as seperate statements:
insert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad
select * from trigger_test;
insert into trigger_test values (1); -- succeeds as expected
insert into trigger_test values (-1); -- fails as expected
select * from trigger_test;
Here is one hack that may work. It isn't clean, but it looks like it might work:
Essentially, you just try to update a column that doesn't exist.
Unfortunately, the answer provided by #RuiDC does not work in MySQL versions prior to 5.5 because there is no implementation of SIGNAL for stored procedures.
The solution I've found is to simulate a signal throwing a table_name doesn't exist error, pushing a customized error message into the table_name.
The hack could be implemented using triggers or using a stored procedure. I describe both options below following the example used by #RuiDC.
Using triggers
DELIMITER $$
-- before inserting new id
DROP TRIGGER IF EXISTS before_insert_id$$
CREATE TRIGGER before_insert_id
BEFORE INSERT ON test FOR EACH ROW
BEGIN
-- condition to check
IF NEW.id < 0 THEN
-- hack to solve absence of SIGNAL/prepared statements in triggers
UPDATE `Error: invalid_id_test` SET x=1;
END IF;
END$$
DELIMITER ;
Using a stored procedure
Stored procedures allows you to use dynamic sql, which makes possible the encapsulation of the error generation functionality in one procedure. The counterpoint is that we should control the applications insert/update methods, so they use only our stored procedure (not granting direct privileges to INSERT/UPDATE).
DELIMITER $$
-- my_signal procedure
CREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))
BEGIN
SET #sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');
PREPARE my_signal_stmt FROM #sql;
EXECUTE my_signal_stmt;
DEALLOCATE PREPARE my_signal_stmt;
END$$
CREATE PROCEDURE insert_test(p_id INT)
BEGIN
IF NEW.id < 0 THEN
CALL my_signal('Error: invalid_id_test; Id must be a positive integer');
ELSE
INSERT INTO test (id) VALUES (p_id);
END IF;
END$$
DELIMITER ;
The following procedure is (on mysql5) a way to throw custom errors , and log them at the same time:
create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;
DELIMITER $$
CREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))
BEGIN
DECLARE errorWithDate varchar(64);
select concat("[",DATE_FORMAT(now(),"%Y%m%d %T"),"] ", errorText) into errorWithDate;
INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);
INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);
END;
$$
DELIMITER ;
call throwCustomError("Custom error message with log support.");
CREATE TRIGGER sample_trigger_msg
BEFORE INSERT
FOR EACH ROW
BEGIN
IF(NEW.important_value) < (1*2) THEN
DECLARE dummy INT;
SELECT
Enter your Message Here!!!
INTO dummy
FROM mytable
WHERE mytable.id=new.id
END IF;
END;
Another (hack) method (if you are not on 5.5+ for some reason) that you can use:
If you have a required field, then within a trigger set the required field to an invalid value such as NULL. This will work for both INSERT and UPDATE. Do note that if NULL is a valid value for the required field (for some crazy reason) then this approach will not work.
BEGIN
-- Force one of the following to be assigned otherwise set required field to null which will throw an error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SET NEW.`required_id_field`=NULL;
END IF;
END
If you are on 5.5+ then you can use the signal state as described in other answers:
BEGIN
-- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error
IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN
SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';
END IF;
END
DELIMITER ##
DROP TRIGGER IF EXISTS trigger_name ##
CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
--the condition of error is:
--if NEW update value of the attribute age = 1 and OLD value was 0
--key word OLD and NEW let you distinguish between the old and new value of an attribute
IF (NEW.state = 1 AND OLD.state = 0) THEN
signal sqlstate '-20000' set message_text = 'hey it's an error!';
END IF;
END ##
DELIMITER ;

Mysql syntax error with trigger

I have this trigger
CREATE TRIGGER checkcollision AFTER UPDATE ON players BEGIN
SELECT RAISE(ABORT, 'collision') FROM walls WHERE NEW.x=x AND NEW.y=y;
END;
mysql 5.1.72-0ubuntu0.10.04.1 (Ubuntu)
But I am getting a syntax error, and I don't see where...
EDIT:
DELIMITER //
CREATE TRIGGER checkcollision AFTER UPDATE ON players BEGIN SELECT RAISE(ABORT, 'collision') FROM walls WHERE NEW.x=x AND NEW.y=y; END//
DELIMITER ;
This is still getting a syntax error...
This is getting a syntax error:
DELIMITER //
CREATE TRIGGER checkcollision AFTER UPDATE ON players
FOR EACH ROW
BEGIN
IF (SELECT count(*) FROM walls WHERE NEW.x=x AND NEW.y=y)>0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Collision detected';
END IF;
END;//
DELIMITER ;
You probably didn't change DELIMITER
How do I do that?
With the DELIMITER command, described here
http://dev.mysql.com/doc/refman/5.6/en/mysql-commands.html
http://dev.mysql.com/doc/refman/5.6/en/stored-programs-defining.html
It's important to change the delimiter when you're creating triggers or procedures, because otherwise using the semicolon statement delimiter inside the body of your trigger (e.g. at the end of the SELECT statement) is ambiguous with respect to the semicolon at the end of the CREATE TRIGGER statement.
This is a very common source of confusion for MySQL developers.
Edit 1:
How do I get it to roll back the change if there is a collision then
Rollback, commit are not allowed in triggers.
Instead, you can raise a signal by setting specific sqlstate on a condition failure.
IF ( condition_for_collision_true ) THEN
SET error_message = 'Invalid XYZ'; -- set proper message
-- set proper error state number
SIGNAL SQLSTATE <ERROR_STATE_NUMBER> SET message_text = error_message;
END IF;
This causes the transaction be aborted.
Original answer:
Triggers get fired for each row affected.
And you are missing the same in your trigger definition.
DELIMITER //
CREATE TRIGGER checkcollision
AFTER UPDATE ON players
FOR EACH ROW
BEGIN
SELECT RAISE(ABORT, 'collision') FROM walls WHERE NEW.x=x AND NEW.y=y;
END;
//
DELIMITER ;
And, it is obvious. Triggers are not regular routines. They are for background action. You can't expect them to return a cursor or any other result. But perform an action like setting or resetting a value in a row or any DML operation on other related table, etc.
Change the body accordingly.

How to write a trigger to abort delete in MYSQL?

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;