CREATE TABLE work_deltas(
    id INTEGER NOT NULL PRIMARY KEY,
    change_id INTEGER NOT NULL,
    node_id INTEGER NOT NULL,
    offset INTEGER NOT NULL,
    start INTEGER NOT NULL,
    stop INTEGER NOT NULL,
    gtime_start INTEGER,
    gtime_stop INTEGER,
    start_comment TEXT,
    stop_comment TEXT,
    FOREIGN KEY(id) REFERENCES deltas(id) ON DELETE CASCADE,
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE CASCADE,
    FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE,
    CONSTRAINT start_stop_order CHECK(stop >= start),
    CONSTRAINT offset_check CHECK(offset BETWEEN -64800 AND 64800)
);


CREATE INDEX
    work_deltas_gtime_start_gtime_stop
ON
    work_deltas(gtime_start,gtime_stop)
;


CREATE TRIGGER
    work_deltas_ai_1
AFTER INSERT ON
    work_deltas
FOR EACH ROW
BEGIN

    UPDATE
        work_deltas
    SET
        gtime_start = NEW.start + NEW.offset,
        gtime_stop  = NEW.stop  + NEW.offset
    WHERE
        id = NEW.id
    ;

END;
