CREATE TABLE func_import_end_change(
    action_format VARCHAR NOT NULL,
    action_topic_uuid_1 VARCHAR(40),
    action_topic_uuid_2 VARCHAR(40),
    identity_uuid VARCHAR(40),
    message VARCHAR,
    uuid VARCHAR(40)
);


CREATE TRIGGER
    func_import_end_change_bi_1
BEFORE INSERT ON
    func_import_end_change
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.action_topic_uuid_1,
        NEW.action_topic_uuid_2,
        NEW.identity_uuid,
        NEW.message,
        NEW.uuid
    );

    INSERT INTO
        func_end_change(
            id,
            action_format,
            action_topic_id_1,
            action_topic_id_2,
            identity_id,
            message,
            uuid
        )
    SELECT
        currval('changes'),
        NEW.action_format,
        t1.id,
        t2.id,
        i.id,
        NEW.message,
        NEW.uuid
    FROM
        topics i
    LEFT JOIN
        topics t1
    ON
        t1.uuid = NEW.action_topic_uuid_1
    LEFT JOIN
        topics t2
    ON
        t2.uuid = NEW.action_topic_uuid_2
    WHERE
        i.uuid = NEW.identity_uuid
    ;

    SELECT RAISE(IGNORE);
END;
