How to commit transaction before raise in mysql trigger? - mysql

CREATE TRIGGER maindb.before_acc_update
BEFORE UPDATE
ON maindb.acc FOR EACH ROW
BEGIN
DECLARE errorMessage VARCHAR(255);
DECLARE clientName VARCHAR(100);
SET clientName = (select USER());
SET errorMessage = CONCAT('DB Error=> new acc_name value (',
NEW.acc_name,
') cannot be null or empty. Old Value is:',
OLD.acc_name);
IF new.acc_name is null or TRIM(COALESCE(new.acc_name , '')) = '' THEN
BEGIN
INSERT INTO maindb.acc_log_error (old_tz, new_tz, username) values (old.acc_name , new.acc_name, clientName);
END ;
SIGNAL SQLSTATE '23000' SET MESSAGE_TEXT = errorMessage;
END IF;
END;
Mysql cancels my transaction. I'd like to log to maindb.acc_log_error and raise my custom error.

Sorry, if you raise a signal in a trigger, it aborts the action of that trigger, including all changes made by that trigge, e.g. your INSERT into the log table.
The only way you could keep the insert to the log table after the trigger aborts is to do that INSERT as a separate statement before or after your UPDATE to acc that spawned the trigger.

Related

SIGNAL SQLSTATE '45000' Doesn't stop Insert

I am having problems implementing a trigger into my table. I am using MySQL, Phpmyadmin
Scenario: Table User(user_id, name, surname, date_of_joining), record(record_id, date_of_record, weight, height, id_user)
a user can have multiple records which show his weight and height at a certain date. id_user is a foreign key referencing to user_id.
I am trying to implement a trigger for insert and update which checks if date_of_record is greater than date_of_joining, if not, the insert should be stopped.
This is a trigger I tried and the insert still goes through
CREATE TRIGGER date_check_insert BEFORE INSERT ON record
FOR EACH ROW
BEGIN
DECLARE date_of_registering DATE;
SET date_of_registering = (SELECT date_of_registering FROM user WHERE user_id = new.id_user);
IF (new.date_of_record NOT BETWEEN date_of_registering AND CURDATE()) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Can not insert that value";
END IF;
END
Any help is appreciated
I'd slightly change the trigger:
Use session variable (so no DECLARE needed)
Put comparison logic in a single place in the WHERE clause (easier to read & understand)
Shows reason in error message
Use SELECT INTO variable instead of SET variable = query (not necessary, I just prefer this way)
So:
CREATE TRIGGER date_check_insert BEFORE INSERT ON record
FOR EACH ROW
BEGIN
SET #found = NULL;
SELECT
user_id INTO #found
FROM
user
WHERE
user_id = NEW.id_user
AND NEW.date_of_record BETWEEN date_of_registering AND NOW() -- or CURDATE() depend on your datetype
;
IF #found IS NULL THEN
SET #msg = CONCAT('Can not insert. Out of range value ', NEW.date_of_record);
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = #msg;
END IF;
END

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 executes two if statements although one is true the other is false

I have this stored procedure
delimiter $$
CREATE TRIGGER le_trigger
AFTER INSERT ON inbox
FOR EACH ROW
BEGIN
declare last_inserted_number VARCHAR(100) DEFAULT '0800100200';
declare last_inserted_message VARCHAR(100) DEFAULT 'Lorem Ipsum';
set last_inserted_number = NEW.in_number;
set last_inserted_message = NEW.in_message;
if(select exists(select id from transactions where tel =last_inserted_number) = 0) then
insert into transactions (message,tel)values(last_inserted_message,last_inserted_number);
if(select exists(select id from transactions where tel =last_inserted_number) > 0) then
insert into outbox (out_message,out_number) values("there was an error",last_inserted_number);
end if;end if;
END$$
delimiter ;
This is how it is supposed to work.If i insert something into the inbox table,the trigger picks the message and telephone number and inserts it into transactions table if that number is not already in transactions.If the trigger finds that that number exists in transactions,it inserts into outbox that there was an error.
In my code,the stored procedure inserts into the error table every time i insert into inbox.What's wrong with my procedure?.
You have a logical fallacy. After you execute the insert, the value exists in the table. That causes the second condition to find the row. I think you want an else statement:
if (not exists(select id from transactions where tel = last_inserted_number)) then
insert into transactions(message, tel)
values(last_inserted_message, last_inserted_number);
else
insert into outbox(out_message, out_number)
values("there was an error", last_inserted_number);
end if;
Note that I changed the logic by removing = 0 and using not exists. Also, it is good practice to prepend all variables with something like v_ so they are not confused with columns in tables.

mySQL Triggers PRINT & ROLLBACK

DELIMITER $$
CREATE TRIGGER insertTrigger BEFORE INSERT ON `agents`
FOR EACH ROW
BEGIN
DECLARE groupID int;
SET groupID = 0;
SET groupID = (SELECT id FROM `groups` WHERE `id` = NEW.group_id);
IF (groupID != 0) THEN
PRINT 'ID is ' + groupID;
ROLLBACK;
END IF;
END$$
DELIMITER ;
The above trigger is created for checking if the foreign key ID exists in the group table.
1) How do I print error messages in mySQL?
2) ROLLBACK Function doesn't work. It gave me the following error message.
"#1422 - Explicit or implicit commit is not allowed in stored function or trigger."
You can use SIGNAL statement to raise an error with custom message from the trigger.
...
IF (groupID != 0) THEN
SET #msg = CONCAT('ID is ', groupID);
SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = #msg;
END IF;
...
If you want just warning message, then use SQLSTATE code starting with '01...'.

Throw an error preventing a table update in a MySQL trigger

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 ;