CREATE TABLE work_buffers(
    id INTEGER NOT NULL PRIMARY KEY,
    topic_id INTEGER NOT NULL,
    start INTEGER NOT NULL,
    start_comment TEXT,
    stop INTEGER,
    stop_comment TEXT,
    billable BOOLEAN NOT NULL,
    change_id INTEGER,
    FOREIGN KEY(topic_id) REFERENCES topics(id) ON DELETE CASCADE,
    FOREIGN KEY(change_id) REFERENCES changes(id) ON DELETE SET NULL,
    CONSTRAINT start_stop_order CHECK(stop >= start)
);


CREATE INDEX
    work_buffers_start_stop
ON
    work_buffers(start,stop)
;

CREATE TRIGGER
    work_buffers_bi_2
BEFORE INSERT ON
    work_buffers
FOR EACH ROW WHEN
    NEW.stop IS NULL AND EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
        WHERE
            wb.stop IS NULL
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot have two open work buffers');
END;


CREATE TRIGGER
    work_buffers_bi_1
BEFORE INSERT ON
    work_buffers
FOR EACH ROW WHEN
    -- intersects with existing buffer
    EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
        WHERE
            -- just checking the start time at insert
            NEW.start > wb.start AND NEW.start < wb.stop
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot overlap work_buffers (insert)');
END;


CREATE TRIGGER
    work_buffers_bu_1
BEFORE UPDATE OF
    start,stop
ON
    work_buffers
FOR EACH ROW WHEN
    EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
        WHERE
        NOT (NEW.start >= wb.stop OR NEW.stop <= wb.start)
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot overlap work_buffers (update)');
END;
