Lanzar un error en un disparador MySQL


Si tengo un trigger before the update en una tabla, ¿cómo puedo lanzar un error que impide la actualización en esa tabla?

Author: sujith karivelil, 2008-08-01

6 answers

Aquí hay un hack que puede funcionar. No está limpio, pero parece que podría funcionar:

Esencialmente, solo intenta actualizar una columna que no existe.

 55
Author: Justin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-24 21:24:41

A partir de MySQL 5.5, puede utilizar el SIGNAL sintaxis para lanzar una excepción :

signal sqlstate '45000' set message_text = 'My Error Message';

El Estado 45000 es un estado genérico que representa "excepción definida por el usuario no controlada".


Aquí hay un ejemplo más completo del enfoque:

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;
 121
Author: RuiDC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-19 21:05:59

Desafortunadamente, la respuesta proporcionada por @RuiDC no funciona en versiones de MySQL anteriores a la 5.5 porque no hay implementación de SIGNAL para procedimientos almacenados.

La solución que he encontrado es simular una señal lanzando un error table_name doesn't exist, empujando un mensaje de error personalizado en el table_name.

El hackeo podría implementarse utilizando disparadores o utilizando un procedimiento almacenado. Describo ambas opciones a continuación siguiendo el ejemplo utilizado por @RuiDC.

Utilizando desencadenantes

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 ;

Usando un procedimiento almacenado

Procedimientos almacenados le permite utilizar sql dinámico, lo que hace posible la encapsulación de la funcionalidad de generación de errores en un procedimiento. El contrapunto es que deberíamos controlar los métodos insert/update de las aplicaciones, para que utilicen solo nuestro procedimiento almacenado (no otorgando privilegios directos 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 ;
 29
Author: el.atomo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-28 15:46:57

El siguiente procedimiento es (en mysql5) una forma de lanzar errores personalizados y registrarlos al mismo tiempo:

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.");
 10
Author: Marinos An,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-09 06:53:40
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;
 6
Author: BHUVANESH MOHANKUMAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-12 18:08:14

Otro método (hack) (si no está en 5.5+ por alguna razón) que puede usar:

Si tiene un campo obligatorio, dentro de un disparador establezca el campo obligatorio en un valor no válido como NULL. Esto funcionará tanto para INSERTAR como para ACTUALIZAR. Tenga en cuenta que si NULL es un valor válido para el campo requerido (por alguna razón loca), entonces este enfoque no funcionará.

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

Si está en 5.5+, puede usar el estado de la señal como se describe en otras respuestas:

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
 4
Author: baflink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-09 23:16:28