0

I have a table called tags and tags_audit.

I have created a trigger such that if there is an update on one of the fields, I would insert rows equal to the number of fields updated in the row of tags table, into the tags_audit table.

Table: tags Structure:

id         int(11)
name       varchar(100)
slug       varchar(100)
type       enum('PUBLIC','PRIVATE')
filterable tinyint(1)
created_at timestamp
updated_at timestamp
tag_line   varchar(500)

Table: tags_audit Structure:

id          int(11)
tag_id      int(11)
column_name varchar(50)
old_value   varchar(50)
new_value   varchar(50)
updated_at  timestamp

Trigger

DELIMITER $$

CREATE TRIGGER after_tags_audit_update
    AFTER UPDATE
    ON tags FOR EACH ROW
BEGIN
    DECLARE oldValue CHAR(50);
    DECLARE newValue CHAR(50);
    DECLARE columnName CHAR(50);
    IF OLD.name <> new.name THEN
        SELECT old.name, new.name INTO oldValue, newValue;
        SET columnName = 'name';
        INSERT INTO tags_audit(tag_id, column_name, old_value, new_value, updated_at)
        VALUES(old.id, columnName, oldValue, newValue, new.updated_at);
    END IF;
    IF OLD.slug <> new.slug THEN
        SELECT old.slug, new.slug INTO oldValue, newValue;
        SET columnName = 'slug';
        INSERT INTO tags_audit(tag_id, column_name, old_value, new_value, updated_at)
        VALUES(old.id, columnName, oldValue, newValue, new.updated_at);
    END IF;
    IF OLD.type <> new.type THEN
        SELECT CAST(old.type AS CHAR(10)), CAST(new.type AS CHAR(10)) INTO oldValue, newValue;
        SET columnName = 'type';
        INSERT INTO tags_audit(tag_id, column_name, old_value, new_value, updated_at)
        VALUES(old.id, columnName, oldValue, newValue, new.updated_at);
    END IF;
    IF OLD.filterable <> new.filterable THEN
        SELECT CAST(old.filterable AS CHAR(10)), CAST(new.filterable AS CHAR(10)) INTO oldValue, newValue;
        SET columnName = 'filterable';
        INSERT INTO tags_audit(tag_id, column_name, old_value, new_value, updated_at)
        VALUES(old.id, columnName, oldValue, newValue, new.updated_at);
    END IF;
    IF OLD.tag_line <> new.tag_line THEN
        SELECT old.tag_line, new.tag_line INTO oldValue, newValue;
        SET columnName = 'tag_line';
        INSERT INTO tags_audit(tag_id, column_name, old_value, new_value, updated_at)
        VALUES(old.id, columnName, oldValue, newValue, new.updated_at);
    END IF;

END$$

DELIMITER ;

I feel that the above above trigger that I have written is clumsy and there should be a better way to do this.

Eg.

if there are 4 fields updated in a row of tags table, then I'm doing 4 inserts into the tags_audit table. Is there a better approach/way to do this?

4

0 回答 0