/*$DELIMITER:/ */
CREATE TABLE JCR_SITEM(
	ID VARCHAR2(96) NOT NULL,
	PARENT_ID VARCHAR2(96) NOT NULL,
	NAME VARCHAR2(512) NOT NULL,
	VERSION INTEGER NOT NULL,
	CONTAINER_NAME VARCHAR2(96) NOT NULL,
	I_CLASS INTEGER NOT NULL,
	I_INDEX INTEGER NOT NULL,
	N_ORDER_NUM INTEGER,
	P_TYPE INTEGER, 
	P_MULTIVALUED INTEGER,	
	CONSTRAINT JCR_PK_SITEM PRIMARY KEY(ID),
	CONSTRAINT JCR_FK_SITEM_PARENT FOREIGN KEY(PARENT_ID) REFERENCES JCR_SITEM(ID)
	)
/
CREATE INDEX JCR_IDX_SITEM_PARENT_FK ON JCR_SITEM(PARENT_ID)
/
CREATE UNIQUE INDEX JCR_IDX_SITEM_PARENT ON JCR_SITEM(CONTAINER_NAME, PARENT_ID, NAME, I_INDEX, I_CLASS, VERSION DESC)
/
CREATE UNIQUE INDEX JCR_IDX_SITEM_PARENT_NAME ON JCR_SITEM(I_CLASS, CONTAINER_NAME, PARENT_ID, NAME, I_INDEX, VERSION DESC)
/
CREATE UNIQUE INDEX JCR_IDX_SITEM_PARENT_ID ON JCR_SITEM(I_CLASS, CONTAINER_NAME, PARENT_ID, ID, VERSION DESC)
/
CREATE INDEX JCR_IDX_SITEM_N_ORDER_NUM ON JCR_SITEM(I_CLASS, CONTAINER_NAME, PARENT_ID, N_ORDER_NUM)
/
CREATE INDEX JCR_IDX_SITEM_NAME ON JCR_SITEM(I_CLASS, CONTAINER_NAME, NAME)
/
CREATE TABLE JCR_SVALUE(
	ID INTEGER NOT NULL, 
	DATA BLOB, 
	ORDER_NUM INTEGER NOT NULL, 
	PROPERTY_ID VARCHAR(96) NOT NULL,
	STORAGE_DESC VARCHAR(512),
	CONSTRAINT JCR_PK_SVALUE PRIMARY KEY(ID),
	CONSTRAINT JCR_FK_SVALUE_PROPERTY FOREIGN KEY(PROPERTY_ID) REFERENCES JCR_SITEM(ID)
	)
/
CREATE UNIQUE INDEX JCR_IDX_SVALUE_PROPERTY ON JCR_SVALUE(PROPERTY_ID, ORDER_NUM)
/
CREATE sequence JCR_SVALUE_SEQ
/
CREATE OR REPLACE trigger BI_JCR_SVALUE
  before insert on JCR_SVALUE
  for each row
begin
  SELECT JCR_SVALUE_SEQ.nextval INTO :NEW.ID FROM dual;
end;
/
CREATE TABLE JCR_SREF(
  NODE_ID VARCHAR(96) NOT NULL,
  PROPERTY_ID VARCHAR(96) NOT NULL,
  ORDER_NUM INTEGER NOT NULL,
  CONSTRAINT JCR_PK_SREF PRIMARY KEY(NODE_ID, PROPERTY_ID, ORDER_NUM)
)
/
CREATE UNIQUE INDEX JCR_IDX_SREF_PROPERTY ON JCR_SREF(PROPERTY_ID, ORDER_NUM)
/

ANALYZE INDEX JCR_PK_SITEM COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SITEM_PARENT_FK COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SITEM_PARENT COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SITEM_PARENT_NAME COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SITEM_N_ORDER_NUM COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SITEM_PARENT_ID COMPUTE STATISTICS
/
ANALYZE INDEX JCR_PK_SVALUE COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SVALUE_PROPERTY COMPUTE STATISTICS
/
ANALYZE INDEX JCR_PK_SREF COMPUTE STATISTICS
/
ANALYZE INDEX JCR_IDX_SREF_PROPERTY COMPUTE STATISTICS
/
ANALYZE INDEX JCR_PK_SCONTAINER COMPUTE STATISTICS
/
CREATE SEQUENCE JCR_SITEM_SEQ  INCREMENT BY 1 MINVALUE -1 NOMAXVALUE NOCACHE NOCYCLE
/
CREATE OR REPLACE FUNCTION JCR_SITEM_NEXT_VAL (nameSeq IN VARCHAR, newVal IN INTEGER, increment IN INTEGER )
RETURN INTEGER
AS
result INTEGER;
query VARCHAR(100);
BEGIN
query := 'select '||nameSeq||'.nextval from dual';
execute immediate query into result;

IF (increment = 0)
THEN
  WHILE (result < newVal)
  LOOP
    execute immediate query into result;
  END LOOP;
END IF;
RETURN result;
end;
/
