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 nodes(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
);



/*
    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
        nodes
    WHERE
        id = OLD.id
    ;

END;

