START TRANSACTION;

ALTER TABLE quota DROP CONSTRAINT IF EXISTS quota_quota_spec_id_project_id_key;

CREATE TABLE IF NOT EXISTS segmentation (
  id              bigserial PRIMARY KEY,
  key             short_text NOT NULL,
  name            short_text NOT NULL,
  description     text NOT NULL,
  UNIQUE (key)
);

CREATE TABLE IF NOT EXISTS segment (
  id              bigserial PRIMARY KEY,
  key             short_text NOT NULL,
  name            short_text NOT NULL,
  description     text NOT NULL,
  segmentation_id bigint NOT NULL REFERENCES segmentation(id) ON UPDATE CASCADE ON DELETE CASCADE,
  UNIQUE (key)
);

CREATE TABLE IF NOT EXISTS resource_segmentation (
  id              bigserial PRIMARY KEY,
  resource_id     bigint NOT NULL REFERENCES resource(id) ON UPDATE CASCADE ON DELETE CASCADE,
  segmentation_id bigint NOT NULL REFERENCES segmentation(id) ON UPDATE CASCADE ON DELETE CASCADE,
  UNIQUE (resource_id, segmentation_id)
);

CREATE TABLE IF NOT EXISTS quota_segment (
  id              bigserial PRIMARY KEY,
  quota_id        bigint NOT NULL REFERENCES quota(id) ON UPDATE CASCADE ON DELETE CASCADE,
  segment_id      bigint,
  segmentation_id bigint REFERENCES segmentation(id) ON UPDATE CASCADE ON DELETE CASCADE,
  UNIQUE (quota_id, segmentation_id, segment_id)
);

CREATE INDEX IF NOT EXISTS quota_segment_quota_id_ix ON quota_segment (quota_id);
CREATE INDEX IF NOT EXISTS quota_segment_segment_id_ix ON quota_segment (segment_id);

COMMIT;
