-- PW-1515 create orderlog tables

DROP TABLE IF EXISTS orderlogs;

CREATE TABLE orderlogs (
    id SERIAL PRIMARY KEY,
    created TIMESTAMP WITH TIME ZONE NOT NULL
);

DROP TABLE IF EXISTS orderlog_entries;

CREATE TABLE orderlog_entries (
    uuid UUID NOT NULL,
    orderlog_id INTEGER NOT NULL,
    created TIMESTAMP WITH TIME ZONE NOT NULL,
    level INTEGER NOT NULL,
    message VARCHAR NOT NULL,
    context JSONB NOT NULL
) PARTITION BY RANGE (created);

CREATE TABLE orderlog_entries_2016 PARTITION OF orderlog_entries FOR VALUES FROM ('2016-01-01') TO ('2017-01-01');
CREATE TABLE orderlog_entries_2017 PARTITION OF orderlog_entries FOR VALUES FROM ('2017-01-01') TO ('2018-01-01');
CREATE TABLE orderlog_entries_2018 PARTITION OF orderlog_entries FOR VALUES FROM ('2018-01-01') TO ('2019-01-01');
CREATE TABLE orderlog_entries_2019 PARTITION OF orderlog_entries FOR VALUES FROM ('2019-01-01') TO ('2020-01-01');

CREATE INDEX ON orderlog_entries_2016 (orderlog_id, created);
CREATE INDEX ON orderlog_entries_2017 (orderlog_id, created);
CREATE INDEX ON orderlog_entries_2018 (orderlog_id, created);
CREATE INDEX ON orderlog_entries_2019 (orderlog_id, created);

-- New order field for orderlog_id
INSERT INTO "order-fields" (name) VALUES ('orderlog_id');
