CREATE TABLE AGGREGATE (
       UUID VARCHAR(36) NOT NULL
     , TYPE VARCHAR NOT NULL
     , VERSION_NUMBER BIGINT NOT NULL
     , PRIMARY KEY (UUID)
);

CREATE TABLE EVENT_STORE (
       EVENT_UUID VARCHAR(36) NOT NULL
     , CREATION_ORDER SERIAL8 NOT NULL
     , EVENT_DATA TEXT NOT NULL
     , VERSION_NUMBER BIGINT DEFAULT -1
     , AGGREGATE_UUID VARCHAR(36)
     , PRIMARY KEY (EVENT_UUID)
);

ALTER TABLE EVENT_STORE
  ADD CONSTRAINT UQ_EVENT_STORE_TUPLE_AGGREGATE_UUID_AND_VERSION_NUMBER
      UNIQUE (AGGREGATE_UUID, VERSION_NUMBER);

ALTER TABLE EVENT_STORE
  ADD CONSTRAINT FK_EVENT_STORE_1
      FOREIGN KEY (AGGREGATE_UUID)
      REFERENCES AGGREGATE (UUID);
