CREATE TABLE task_deltas (
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    task_id INTEGER NOT NULL,
    new INTEGER,
    task_status_id INTEGER,
    title VARCHAR(1024),
    UNIQUE(change_id,task_id), -- one change per change
    FOREIGN KEY(id) REFERENCES deltas(id),
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(task_id) REFERENCES tasks(id) ON DELETE CASCADE,
    FOREIGN KEY(task_status_id) REFERENCES task_status(id) ON DELETE CASCADE
);


CREATE TRIGGER
    task_deltas_ai_1
AFTER INSERT ON
    task_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        NEW.change_id,
        NEW.task_id,
        NEW.task_status_id,
        NEW.title
    );

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


    INSERT OR IGNORE INTO
        tasks_tomerge(task_id)
    VALUES
        (NEW.task_id)
    ;


    UPDATE
        tasks_tomerge
    SET
        task_status_id = task_status_id + (NEW.task_status_id IS NOT NULL),
        title    = title + (NEW.title IS NOT NULL)
    WHERE
        task_id = NEW.task_id
    ;


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


CREATE TRIGGER
    task_deltas_ad_1
AFTER DELETE ON
    task_deltas
FOR EACH ROW
BEGIN

    SELECT debug(
        OLD.change_id,
        OLD.task_id,
        OLD.task_status_id,
        OLD.title
    );


    INSERT OR IGNORE INTO
        tasks_tomerge(task_id)
    VALUES
        (OLD.task_id)
    ;


    UPDATE
        tasks_tomerge
    SET
        task_status_id = task_status_id + (OLD.task_status_id IS NOT NULL),
        title    = title + (OLD.title IS NOT NULL)
    WHERE
        task_id = OLD.task_id
    ;

END;
