CREATE TABLE func_update_topic(
    change_id INTEGER NOT NULL,
    id INTEGER NOT NULL,
    topic_status_id INTEGER,
    title VARCHAR
);

CREATE TRIGGER
    func_update_topic_bi_1
BEFORE INSERT ON
    func_update_topic
FOR EACH ROW BEGIN

    SELECT debug(
        NEW.id,
        NEW.change_id,
        NEW.topic_status_id,
        NEW.title
    );

    UPDATE
        changes
    SET
        yaml = yaml || (
            SELECT
                '-' || x'0A'
                || '  _delta: update_topic' || x'0A'
                ||
                    CASE WHEN
                        NEW.title IS NULL
                    THEN
                        '  title: ~' || x'0A'
                    WHEN
                        NEW.title = '-'
                    THEN
                        '  title: ''-''' || x'0A'
                    WHEN
                        instr(NEW.title, x'0A') OR
                        instr(NEW.title, '\\')
                    THEN
                        '  title: "' 
                        || REPLACE(
                              REPLACE(
                                REPLACE(NEW.title, '\\', '\\\\'),
                                x'0A', '\n'), '"', '\"')
                        || '"' || x'0A'
                    WHEN
                        instr(NEW.title, ' ') OR
                        NEW.title = '' -- not at all sufficient
                    THEN
                        '  title: ''' || NEW.title || '''' || x'0A'
                    ELSE
                        '  title: ' || NEW.title || x'0A'
                    END
                || '  topic_status_uuid: ' || COALESCE(s.uuid,'~') || x'0A'
                || '  uuid: ' || n.uuid || x'0A'
            FROM
                nodes n
            LEFT JOIN
                nodes s
            ON
                s.id = NEW.topic_status_id
            WHERE
                n.id = NEW.id
        )
    WHERE
        id = NEW.change_id
    ;


    INSERT INTO deltas(
        id,
        change_id,
        action
    )
    VALUES(
        nextval('deltas'),
        NEW.change_id,
        'update_topic'
    );


    -- TODO remove this?
    INSERT INTO
        node_deltas(
            id,
            change_id,
            node_id
        )
    VALUES(
        currval('deltas'),
        NEW.change_id,
        NEW.id
    );


    INSERT INTO
        link_topic_deltas(
            id,
            change_id,
            link_topic_id,
            topic_id,
            topic_status_id,
            title
        )
    SELECT
        currval('deltas'),
        NEW.change_id,
        t.link_topic_id,
        NEW.id,
        NEW.topic_status_id,
        NEW.title
    FROM
        topics t
    WHERE
        t.id = NEW.id
    ;


    SELECT RAISE(IGNORE);
END;
