CREATE SEQUENCE ORDERING__SEQ START WITH 1 INCREMENT BY 1 NOMAXVALUE
/

CREATE TABLE JOURNAL (
   ORDERING NUMERIC UNIQUE,
   DELETED CHAR(1) DEFAULT 0 NOT NULL check (DELETED in (0, 1)),
   PERSISTENCE_ID VARCHAR(255) NOT NULL,
   SEQUENCE_NUMBER NUMERIC NOT NULL,
  TAGS VARCHAR(255) DEFAULT NULL,
  MESSAGE BLOB NOT NULL,
  PRIMARY KEY(PERSISTENCE_ID, SEQUENCE_NUMBER)
)
/

CREATE TABLE LEGACY_SNAPSHOT (
    PERSISTENCE_ID VARCHAR(255) NOT NULL,
    SEQUENCE_NUMBER NUMERIC NOT NULL,
    CREATED NUMERIC NOT NULL,
    SNAPSHOT BLOB NOT NULL,
    PRIMARY KEY(PERSISTENCE_ID,SEQUENCE_NUMBER)
)
/

CREATE OR REPLACE TRIGGER JOURNAL__ORDERING_TRG
BEFORE INSERT ON JOURNAL
FOR EACH ROW
BEGIN
  SELECT ORDERING__SEQ.NEXTVAL INTO :NEW.ORDERING FROM DUAL;
END;
/

CREATE OR REPLACE PROCEDURE "reset_legacy_sequence"
IS
  l_value NUMBER;
BEGIN
  EXECUTE IMMEDIATE 'SELECT ORDERING__SEQ.nextval FROM dual' INTO l_value;
  EXECUTE IMMEDIATE 'ALTER SEQUENCE ORDERING__SEQ INCREMENT BY -' || l_value || ' MINVALUE 0';
  EXECUTE IMMEDIATE 'SELECT ORDERING__SEQ.nextval FROM dual' INTO l_value;
  EXECUTE IMMEDIATE 'ALTER SEQUENCE ORDERING__SEQ INCREMENT BY 1 MINVALUE 0';
END;
/
