Ejemplo LOG eventos sobre BBDD
Tabla de LOG’s:
CREATE TABLE logs (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
usuario VARCHAR(50) NULL DEFAULT user() ,
operacion VARCHAR(50) NULL DEFAULT ,
tabla VARCHAR(50) NULL DEFAULT,
descripcion TEXT NULL DEFAULT,
PRIMARY KEY (`id`) );
CREATE TABLE tabla1 (
id INT(11) NOT NULL AUTO_INCREMENT,
nombre VARCHAR(50) NOT NULL DEFAULT 'Sin nombre',
PRIMARY KEY (id)
);
Creación de triggers después de actualización, borrado o insercción en algunas de las tablas de la base de datos.
After insert:
BEGIN
INSERT INTO log VALUES
(NULL,SYSDATE(),"insert.after",
CONCAT("usuarios ->","id:",new.id),
USER(), null,
CONCAT_WS(" ","usuario:",NEW.nombre,
"password:",NEW.password));
END
Before insert:
BEGIN
DECLARE ult INT;
/* aquí podemos tener problemas
con nombre de variables y campos */
SELECT MAX(id)+1 into ult
FROM usuarios;
/* aquí se evitan esos problemas */
SET ult = (SELECT MAX(id)+1
FROM usuarios);
INSERT INTO log VALUES
(NULL,SYSDATE(),"insert.before",
CONCAT("usuarios ->","id:",ult),
USER(), null,
null);
END
After update:
BEGIN
if (NEW.nombre<>OLD.nombre) then
INSERT INTO log
VALUES
(NULL,SYSDATE(),"update.after",
"usuarios.nombre",USER(),OLD.nombre,NEW.nombre);
END if;
if (NEW.password<>OLD.password) then
INSERT INTO LOG
VALUES
(NULL,SYSDATE(),"update.after",
"usuarios.password", USER(), OLD.password,NEW.password);
END if;
END
Before update:
BEGIN
if (NEW.nombre<>OLD.nombre) then
INSERT INTO log
VALUES
(NULL,SYSDATE(),"update.before",
"usuarios.nombre",USER(),OLD.nombre,NEW.nombre);
END if;
if (NEW.password<>OLD.password) then
INSERT INTO LOG
VALUES
(NULL,SYSDATE(),"update.before",
"usuarios.password", USER(), OLD.password,NEW.password);
END if;
END
Before delete:
BEGIN
INSERT INTO log VALUES
(NULL,SYSDATE(),"before.delete",
CONCAT("usuarios ->","id:",old.id),
USER(), OLD.nombre,
null);
END
After delete
BEGIN
INSERT INTO log VALUES
(NULL,SYSDATE(),"after.delete",
CONCAT("usuarios ->","id:",old.id),
USER(), OLD.nombre,
null);
END