-- Create Schema for Brutex
CREATE SCHEMA IF NOT EXISTS brutex;

CREATE MEMORY TABLE IF NOT EXISTS brutex.tbl_events
            (
            btx_event_type VARCHAR(128) NOT NULL,
            btx_id VARCHAR(128) NOT NULL,
            btx_obj_type VARCHAR(32) NOT NULL,
            btx_obj_id VARCHAR(32) NOT NULL,
            btx_timestamp BIGINT NOT NULL,
            btx_event CLOB
            );
CREATE INDEX IF NOT EXISTS brutex.btx_idx_key ON brutex.tbl_events (btx_obj_id, btx_obj_type, btx_event_type);
CREATE INDEX IF NOT EXISTS brutex.btx_idx_ts ON brutex.tbl_events (btx_timestamp ASC);
CREATE INDEX IF NOT EXISTS brutex.btx_idx_id ON brutex.tbl_events (btx_id);


CREATE MEMORY TABLE IF NOT EXISTS brutex.tbl_events_snap
(
    btx_event_type VARCHAR(128) NOT NULL,
    btx_id VARCHAR(128) NOT NULL,
    btx_obj_type VARCHAR(32) NOT NULL,
    btx_obj_id VARCHAR(32) NOT NULL,
    btx_timestamp BIGINT NOT NULL,
    btx_run BIGINT NOT NULL,
    btx_event CLOB
);

CREATE INDEX IF NOT EXISTS brutex.btx_idx_ts ON brutex.tbl_events_snap (btx_timestamp ASC);

CREATE CACHED TABLE IF NOT EXISTS brutex.tbl_events_errors
(
    btx_event_type VARCHAR(128) NOT NULL,
    btx_id VARCHAR(128) NOT NULL,
    btx_obj_type VARCHAR(32) NOT NULL,
    btx_obj_id VARCHAR(32) NOT NULL,
    btx_timestamp BIGINT NOT NULL,
    btx_retry BOOL,
    btx_response CLOB,
    btx_event CLOB
);
CREATE INDEX IF NOT EXISTS brutex.btx_idx_ts ON brutex.tbl_events_errors (btx_timestamp ASC);
CREATE INDEX IF NOT EXISTS brutex.btx_idx_retry ON brutex.tbl_events_errors (btx_retry);

CREATE CACHED TABLE IF NOT EXISTS brutex.tbl_events_all
(
    btx_event_type VARCHAR(128) NOT NULL,
    btx_id VARCHAR(128) NOT NULL,
    btx_obj_type VARCHAR(32) NOT NULL,
    btx_obj_id VARCHAR(32) NOT NULL,
    btx_timestamp BIGINT NOT NULL,
    btx_supersed_id VARCHAR(128),
    btx_event CLOB
);

CREATE INDEX IF NOT EXISTS brutex.btx_idx_ssed ON brutex.tbl_events_all (btx_supersed_id);
CREATE INDEX IF NOT EXISTS brutex.btx_idx_ts ON brutex.tbl_events_all (btx_timestamp ASC);

-- MiscService lock operation
CREATE SEQUENCE IF NOT EXISTS brutex.btx_sequence1;
CREATE TABLE IF NOT EXISTS brutex.tbl_lock (
    btx_seq BIGINT NOT NULL,
    btx_id VARCHAR(100) NOT NULL,
    btx_obj_id VARCHAR(100) NOT NULL,
    btx_timestamp BIGINT NOT NULL,
    btx_validity BIGINT NOT NULL
);

--CREATE INDEX IF NOT EXISTS brutex.btx_idx_seq ON brutex.tbl_lock (btx_seq ASC);
--CREATE INDEX IF NOT EXISTS brutex.btx_idx_key ON brutex.tbl_lock (btx_obj_id, btx_validity DESC);
