CREATE TABLE work_buffers(
    id INTEGER NOT NULL PRIMARY KEY,
    node_id INTEGER,
    start INTEGER NOT NULL,
    offset INTEGER NOT NULL
        DEFAULT (strftime('%s','now','localtime') - strftime('%s','now')),
    comment TEXT,
    bill BOOLEAN NOT NULL,
    FOREIGN KEY(node_id) REFERENCES nodes(id) ON DELETE CASCADE,
    CONSTRAINT offset_check CHECK (offset BETWEEN -64800 AND 64800)
);


CREATE TRIGGER
    work_buffers_bi_2
BEFORE INSERT ON
    work_buffers
FOR EACH ROW WHEN
    EXISTS (
        SELECT
            1
        FROM
            work_buffers wb
    )
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_deltas wd
        WHERE
            -- just checking the start time at insert
            NEW.start + NEW.offset > wd.gtime_start AND
            NEW.start + NEW.offset < wd.gtime_stop
    )
BEGIN
    SELECT RAISE(ABORT, 'cannot overlap work_buffer with work_deltas');
END;
