CREATE TABLE issues (
    id INTEGER NOT NULL PRIMARY KEY,
    src_id INTEGER,
    project_id INTEGER NOT NULL,
    issue_status_id INTEGER NOT NULL,
    title VARCHAR(1024) NOT NULL DEFAULT '',
    UNIQUE (src_id,project_id),
    FOREIGN KEY(id) REFERENCES topics(id) ON DELETE CASCADE,
    FOREIGN KEY(src_id) REFERENCES issues(id) ON DELETE CASCADE,
    FOREIGN KEY(project_id,issue_status_id)
        REFERENCES issue_status(project_id,id)
        ON DELETE CASCADE
);


/*
    An issue just got added to a project. Add all of the changes
    for this issue's parents to the project_related_changes table.

    TODO: this only works for the first src_id - need to recurse to the
    rest in the event issue has been pushed multiple times.
*/

CREATE TRIGGER
    issues_ai_1
AFTER INSERT ON
    issues
FOR EACH ROW WHEN
    NEW.src_id IS NOT NULL
BEGIN
    SELECT debug(
        NEW.id,
        NEW.src_id,
        NEW.project_id,
        NEW.issue_status_id,
        NEW.title
    );

    INSERT INTO
        project_related_changes(
            project_id,
            real_project_id,
            change_id,
            merkled
        )
    SELECT DISTINCT
        NEW.project_id,
        i.project_id,
        id.change_id,
        c.valid
    FROM
        issues i
    INNER JOIN
        issue_deltas id
    ON
        id.issue_id = i.id
    INNER JOIN
        changes c
    ON
        c.id = id.change_id
    WHERE
        i.id = NEW.src_id
    ;

END;


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

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

    DELETE FROM
        issue_deltas
    WHERE
        issue_id = OLD.id
    ;

END;


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

    DELETE FROM
        topics
    WHERE
        id = OLD.id
    ;

END;

