CREATE TABLE issue_deltas (
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    new INTEGER,
    issue_id INTEGER NOT NULL,
    issue_status_id INTEGER,
    title VARCHAR(1024),
    FOREIGN KEY(id) REFERENCES deltas(id),
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(issue_id) REFERENCES issues(id) ON DELETE CASCADE
);

CREATE INDEX
    issue_deltas_issue_id_issue_status_id
ON
    issue_deltas(issue_id,issue_status_id)
;


CREATE TRIGGER
    issue_deltas_ai_1
AFTER INSERT ON
    issue_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.change_id,
        NEW.issue_id,
        NEW.issue_status_id,
        NEW.title
    );

    UPDATE
        changes
    SET
        ucount = ucount + 1
    WHERE
        id = NEW.change_id
    ;


    INSERT OR IGNORE INTO
        issues_tomerge(issue_id)
    VALUES
        (NEW.issue_id)
    ;


    UPDATE
        issues_tomerge
    SET
        title = title + (NEW.title IS NOT NULL),
        issue_status_id = issue_status_id + (NEW.issue_status_id IS NOT NULL)
    WHERE
        issue_id = NEW.issue_id
    ;


    UPDATE
        change_nodes
    SET
        project_change = project_change + 1
    WHERE
        change_id = NEW.change_id AND node_id = NEW.issue_id
    ;
END;


CREATE TRIGGER
    issue_deltas_ad_1
AFTER DELETE ON
    issue_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.change_id,
        OLD.issue_id,
        OLD.issue_status_id,
        OLD.title
    );

    INSERT OR IGNORE INTO
        issues_tomerge(issue_id)
    VALUES
        (OLD.issue_id)
    ;

    UPDATE
        issues_tomerge
    SET
        title    = title + (OLD.title IS NOT NULL),
        issue_status_id = issue_status_id + (OLD.issue_status_id IS NOT NULL)
    WHERE
        issue_id = OLD.issue_id
    ;

END;
