CREATE TABLE topics (
    id INTEGER NOT NULL PRIMARY KEY,
    link_topic_id INTEGER NOT NULL,
    project_id INTEGER NOT NULL,
    tkind VARCHAR NOT NULL,
    topic_status_id INTEGER NOT NULL,
    title VARCHAR(1024) NOT NULL DEFAULT '',
    UNIQUE(link_topic_id,project_id),
    FOREIGN KEY(id) REFERENCES nodes(id) ON DELETE CASCADE,
    FOREIGN KEY(link_topic_id) REFERENCES link_topics(id) ON DELETE CASCADE,
    FOREIGN KEY(project_id) REFERENCES projects(id) ON DELETE CASCADE,
    FOREIGN KEY(project_id,tkind,topic_status_id)
        REFERENCES topic_status(project_id,tkind,id)
        ON DELETE CASCADE
);


CREATE TRIGGER
    topics_ai_1
AFTER INSERT ON
    topics
FOR EACH ROW
BEGIN
    SELECT debug(
        NEW.id
    );

    UPDATE
        link_topics
    SET
        count = count + 1
    WHERE
        id = NEW.link_topic_id
    ;

END;


/*
    When rows are deleted from link_topic_deltas, triggers attempt to
    update the link_topics_tomerge and link/topics tables, which will
    cause foreign key failures if we have already deleted the relevant
    row from the topics table. So here we get rid of them early.
*/

CREATE TRIGGER
    topics_bd_1
BEFORE DELETE ON
    topics
FOR EACH ROW
BEGIN
    SELECT debug(
        OLD.id,
        OLD.title
    );

    DELETE FROM
        link_topic_deltas
    WHERE
        topic_id = OLD.id
    ;


END;


CREATE TRIGGER
    topics_ad_1
AFTER DELETE ON
    topics
FOR EACH ROW
BEGIN
    SELECT debug(
        OLD.id,
        OLD.title
    );

    DELETE FROM
        nodes
    WHERE
        id = OLD.id
    ;


    UPDATE
        link_topics
    SET
        count = count - 1
    WHERE
        id = OLD.link_topic_id
    ;

END;
