Genera un errore in un trigger MySQL
Domanda
Se ho un trigger
before the update
su una tabella, come posso generare un errore che impedisce l'aggiornamento su quella tabella?
Soluzione
Ecco un trucco potrebbe funzionare.Non è pulito, ma sembra che potrebbe funzionare:
In sostanza, provi semplicemente ad aggiornare una colonna che non esiste.
Altri suggerimenti
A partire da MySQL 5.5, è possibile utilizzare il file SIGNAL
sintassi per generare un'eccezione:
signal sqlstate '45000' set message_text = 'My Error Message';
Lo stato 45000 è uno stato generico che rappresenta "un'eccezione definita dall'utente non gestita".
Ecco un esempio più completo dell’approccio:
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;
Sfortunatamente, la risposta fornita da @RuiDC non funziona nelle versioni MySQL precedenti alla 5.5 perché non esiste un'implementazione di SEGNALE per le procedure memorizzate.
La soluzione che ho trovato è simulare un segnale che lancia a table_name doesn't exist
errore, inserendo un messaggio di errore personalizzato nel file table_name
.
L'hacking potrebbe essere implementato utilizzando trigger o utilizzando una procedura memorizzata.Descrivo entrambe le opzioni di seguito seguendo l'esempio utilizzato da @RuiDC.
Utilizzo dei trigger
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 ;
Utilizzando una procedura memorizzata
Le procedure memorizzate consentono di utilizzare SQL dinamico, che rende possibile l'incapsulamento della funzionalità di generazione degli errori in un'unica procedura.Il contrappunto è che dovremmo controllare i metodi di inserimento/aggiornamento delle applicazioni, in modo che utilizzino solo la nostra procedura memorizzata (non concedendo privilegi diretti a 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 ;
La seguente procedura è (su mysql5) un modo per generare errori personalizzati e registrarli allo stesso tempo:
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;
Un altro metodo (hack) (se per qualche motivo non utilizzi la versione 5.5+) che puoi utilizzare:
Se disponi di un campo obbligatorio, all'interno di un trigger imposta il campo obbligatorio su un valore non valido come NULL.Funzionerà sia per INSERT che per UPDATE.Tieni presente che se NULL è un valore valido per il campo obbligatorio (per qualche strano motivo), questo approccio non funzionerà.
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
Se utilizzi 5.5+, puoi utilizzare lo stato del segnale come descritto in altre risposte:
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