CREATE TABLE hub_repo_deltas (
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    hub_id INTEGER,
    hub_repo_id INTEGER NOT NULL,
    new INTEGER,
    location VARCHAR,
    FOREIGN KEY(id) REFERENCES deltas(id) ON DELETE CASCADE,
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(hub_id) REFERENCES hubs(id) ON DELETE CASCADE,
    FOREIGN KEY(hub_repo_id) REFERENCES hub_repos(id) ON DELETE CASCADE
);

CREATE TRIGGER
    hub_repo_deltas_ai_1
AFTER INSERT ON
    hub_repo_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.id,
        NEW.change_id,
        NEW.hub_id,
        NEW.hub_repo_id,
        NEW.new,
        NEW.location
    );

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


    UPDATE
        hub_repos_tomerge
    SET
        location = location + (NEW.location IS NOT NULL)
    WHERE
        hub_repo_id = NEW.hub_repo_id
    ;
END;


CREATE TRIGGER
    hub_repo_deltas_ad_1
AFTER DELETE ON
    hub_repo_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.change_id,
        OLD.hub_id,
        OLD.hub_repo_id,
        OLD.location
    );

    INSERT OR IGNORE INTO
        hub_repos_tomerge(hub_repo_id)
    VALUES
        (OLD.hub_repo_id)
    ;

    UPDATE
        hub_repos_tomerge
    SET
        location = location + (OLD.location IS NOT NULL)
    WHERE
        hub_repo_id = OLD.hub_repo_id
    ;

END;

