CREATE TABLE func_new_topic2(
    change_id INTEGER,
    id INTEGER NOT NULL DEFAULT (nextval('topics')),
    kind VARCHAR,
    uuid VARCHAR(40)
);


CREATE TRIGGER
    func_new_topic2_bi_1
BEFORE INSERT ON
    func_new_topic2
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.change_id,
        NEW.id,
        NEW.kind,
        NEW.uuid
    );

    INSERT INTO
        topics(
            id,
            first_change_id,
            last_change_id,
            kind,
            ctime,
            ctimetz,
            mtime,
            mtimetz,
            lang,
            uuid
        )
    SELECT
        NEW.id,
        NEW.change_id,
        NEW.change_id,
        NEW.kind,
        c.mtime,
        c.mtimetz,
        c.mtime,
        c.mtimetz,
        c.lang,
        sha1_hex(c.yaml)
    FROM
        changes c
    WHERE
        c.id = NEW.change_id
    ;


    SELECT
        CASE WHEN
            NEW.uuid IS NULL OR
            (NEW.uuid IS NOT NULL AND t.uuid = NEW.uuid)
        THEN
            RAISE(IGNORE)
        ELSE
            RAISE(ABORT, 'Bif::Err::TopicUUIDMismatch')
        END
    FROM
        topics t
    WHERE
        t.id = NEW.id
    ;

END;
