CREATE OR ALTER TRIGGER LINKS_BU FOR LINKS
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
	NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.PARENT_ID INTO NEW.PARENT_TYPE_ID;
	SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.OBJ_ID INTO NEW.OBJ_TYPE_ID;
	SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.EXT_OBJ_ID INTO NEW.EXT_OBJ_TYPE_ID;
END;

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'RT' AND RDB$RELATION_NAME = 'LOG'}
  ALTER TABLE "LOG" DROP RT;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'AUTH_TOKENS'}

  CREATE GENERATOR GEN_RT_ID;

  CREATE TABLE AUTH_TOKENS (
    OBJ_ID    BIGINT NOT NULL,
    DATE_ADD  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    USER_ID   BIGINT NOT NULL,
    ADDR      VARCHAR(100),
    RT        VARCHAR(100),
    IS_VALID  SMALLINT DEFAULT 1 NOT NULL,
    IS_LOGIN  SMALLINT
  );

  ALTER TABLE AUTH_TOKENS ADD CONSTRAINT PK_AUTH_TOKENS PRIMARY KEY (OBJ_ID);
  ALTER TABLE AUTH_TOKENS ADD CONSTRAINT FK_AUTH_TOKENS_1 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER AUTH_TOKENS_BI0 FOR AUTH_TOKENS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_RT_ID, 1);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON AUTH_TOKENS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_LOGIN' AND RDB$RELATION_NAME = 'AUTH_TOKENS'}

  ALTER TABLE AUTH_TOKENS ADD IS_LOGIN SMALLINT DEFAULT 0;
  COMMIT WORK;
  CREATE INDEX AUTH_TOKENS_IDX2 ON AUTH_TOKENS (DATE_ADD, IS_LOGIN);
  COMMIT WORK;

{$ENDIF}
   
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'SHOW_ALL_FIELDS'
	AND RDB$RELATION_NAME = 'PARENTS'}
	ALTER TABLE PARENTS
	ADD SHOW_ALL_FIELDS SMALLINT
	DEFAULT 0 
	NOT NULL;
{$ENDIF}
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'RUN_FUNCTION'
	AND RDB$RELATION_NAME = 'PARENTS'}
	ALTER TABLE PARENTS
	ADD RUN_FUNCTION SMALLINT
	DEFAULT 0 
	NOT NULL;
{$ENDIF}
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'CURRICULUM_ID'
	AND RDB$RELATION_NAME = 'CURRICULUM_HOURS'}

	CREATE GLOBAL TEMPORARY TABLE CURRICULUM_HOURS (
	    CURRICULUM_ID      BIGINT,
	    COMPONENT_TYPE_ID  BIGINT,
	    SUBJECT_ID         BIGINT,
	    STAGE_ID           BIGINT,
	    HOURS              INTEGER
	) ON COMMIT DELETE ROWS;
	CREATE INDEX CURRICULUM_HOURS_IDX1 ON CURRICULUM_HOURS (CURRICULUM_ID, SUBJECT_ID);
	CREATE INDEX CURRICULUM_HOURS_IDX2 ON CURRICULUM_HOURS (CURRICULUM_ID, STAGE_ID);
	GRANT ALL ON CURRICULUM_HOURS TO INISSOFT_ROLE;
{$ENDIF}
/* REPORT_OSH1  2016-05-02 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'STAGE_LISTVAL_ID'
	AND RDB$RELATION_NAME = 'REPORT_OSH1'}

	CREATE GLOBAL TEMPORARY TABLE REPORT_OSH1 (
	    STAGE_ID          BIGINT,
	    STAGE_LISTVAL_ID  BIGINT,
	    CLASS_ID          BIGINT,
	    CLASS             VARCHAR(100),
	    SCHOLAR_ID        BIGINT
	) ON COMMIT PRESERVE ROWS;
	GRANT ALL ON REPORT_OSH1 TO INISSOFT_ROLE;
{$ENDIF}
/* REPORT_OSH1  2016-05-17 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'STREAM_ID'
	AND RDB$RELATION_NAME = 'REPORT_OSH1'}

	ALTER TABLE REPORT_OSH1 ALTER STAGE_ID TO STREAM_ID;
	
	COMMIT WORK;
{$ENDIF}
/* IS_EXT_OBJ  2016-03-29 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'EXT_TYPE_ID'
	AND RDB$RELATION_NAME = 'PARENTS'}

	ALTER TABLE PARENTS ADD EXT_TYPE_ID BIGINT;
	
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_BLOCKED_PWD' AND RDB$RELATION_NAME = 'USERS'}
  ALTER TABLE USERS ADD IS_BLOCKED_PWD SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ADDED_BY' AND RDB$RELATION_NAME = 'USERS'}
  ALTER TABLE USERS ADD ADDED_BY BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DATE_MODIFY' AND RDB$RELATION_NAME = 'USERS'}

  ALTER TABLE USERS ADD DATE_MODIFY TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;

  SET TERM ^ ;

  CREATE TRIGGER USERS_BU0 FOR USERS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^

  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'PWD' AND F.RDB$RELATION_NAME = 'USERS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 100}
  ALTER TABLE USERS ALTER COLUMN PWD TYPE VARCHAR(200);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SNILS' AND RDB$RELATION_NAME = 'USERS'}

  ALTER TABLE USERS ADD SNILS VARCHAR(40) CHARACTER SET UTF8 COLLATE UTF8;
  ALTER TABLE USERS ADD REG_ID VARCHAR(60) CHARACTER SET UTF8 COLLATE UTF8;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LAST_ACCESS' AND RDB$RELATION_NAME = 'USERS'}

  ALTER TABLE USERS ADD LAST_ACCESS TIMESTAMP;
  ALTER TABLE USERS ADD PWD_TIMEMARK TIMESTAMP;
  COMMIT WORK;
  UPDATE USERS SET LAST_ACCESS = CURRENT_TIMESTAMP, PWD_TIMEMARK = CURRENT_TIMESTAMP;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SECTION_ID' AND RDB$RELATION_NAME = 'USERS'}

  ALTER TABLE USERS ADD SECTION_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

/* Исключено удаление SNILS_INDEX в старом формате */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PUPIL_ID' AND RDB$RELATION_NAME = 'AGREGATE_PUPIL'}
	CREATE GLOBAL TEMPORARY TABLE AGREGATE_PUPIL (
		PUPIL_ID        BIGINT NOT NULL,
		SCHOOL_ID       BIGINT,
		PARENT_TYPE_ID  BIGINT,
		F1              SMALLINT DEFAULT 0,
		F2              SMALLINT DEFAULT 0,
		F3              SMALLINT DEFAULT 0,
		F4              SMALLINT DEFAULT 0,
		F5              SMALLINT DEFAULT 0
	) ON COMMIT DELETE ROWS;
	ALTER TABLE AGREGATE_PUPIL ADD CONSTRAINT PK_AGREGATE_PUPIL PRIMARY KEY (PUPIL_ID);
	CREATE INDEX AGREGATE_PUPIL_IDX1 ON AGREGATE_PUPIL (SCHOOL_ID, PARENT_TYPE_ID, PUPIL_ID);
	CREATE INDEX AGREGATE_PUPIL_IDX2 ON AGREGATE_PUPIL (SCHOOL_ID, PUPIL_ID);
	GRANT SELECT, INSERT, UPDATE, DELETE ON AGREGATE_PUPIL TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'PUPIL_ID'
	AND RDB$RELATION_NAME = 'SNILS_INDEX'}
	CREATE TABLE SNILS_INDEX (
		SNILS       VARCHAR(20),
		FIRSTNAME   VARCHAR(50),
		SECONDNAME  VARCHAR(50),
		LASTNAME    VARCHAR(50),
		PUPIL_ID    BIGINT NOT NULL,
		DROPOUT     SMALLINT
	);
	ALTER TABLE SNILS_INDEX ADD CONSTRAINT PK_SNILS_INDEX PRIMARY KEY (PUPIL_ID);
	CREATE INDEX SNILS_INDEX_LASTNAME ON SNILS_INDEX (LASTNAME);
	CREATE INDEX SNILS_INDEX_SNILS ON SNILS_INDEX (SNILS);
	GRANT ALL ON SNILS_INDEX TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'DOC_ID'
	AND RDB$RELATION_NAME = 'DOC_INDEX'}
	CREATE TABLE DOC_INDEX (
		DOC_ID     BIGINT NOT NULL,
		PUPIL_ID   BIGINT NOT NULL,
		DOCTYPE    BIGINT,
		DOCSERIE   VARCHAR(20),
		DOCNUMBER  VARCHAR(20)
	);
	ALTER TABLE DOC_INDEX ADD PRIMARY KEY (DOC_ID);
	ALTER TABLE DOC_INDEX ADD CONSTRAINT FK_DOC_INDEX_1 FOREIGN KEY (PUPIL_ID) REFERENCES SNILS_INDEX (PUPIL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
	GRANT ALL ON DOC_INDEX TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SCHOOL_ID' AND RDB$RELATION_NAME = 'REPORT_D12'}
	CREATE GLOBAL TEMPORARY TABLE REPORT_D12 (
		SCHOOL_ID   BIGINT NOT NULL,
		SCHOLAR_ID  BIGINT NOT NULL,
		ROW_NUM     INTEGER NOT NULL,
		C1          INTEGER NOT NULL,
		C2          INTEGER NOT NULL,
		C3          INTEGER NOT NULL
	) ON COMMIT PRESERVE ROWS;
	ALTER TABLE REPORT_D12 ADD CONSTRAINT PK_REPORT_D12 PRIMARY KEY (SCHOOL_ID, SCHOLAR_ID, ROW_NUM);
	GRANT ALL ON REPORT_D12 TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SCHOOL_ID' AND RDB$RELATION_NAME = 'REPORT_D12'}
	CREATE GLOBAL TEMPORARY TABLE REPORT_D12 (
		SCHOOL_ID   BIGINT NOT NULL,
		SCHOLAR_ID  BIGINT NOT NULL,
		ROW_NUM     INTEGER NOT NULL,
		C1          INTEGER NOT NULL,
		C2          INTEGER NOT NULL,
		C3          INTEGER NOT NULL
	) ON COMMIT PRESERVE ROWS;
	ALTER TABLE REPORT_D12 ADD CONSTRAINT PK_REPORT_D12 PRIMARY KEY (SCHOOL_ID, SCHOLAR_ID, ROW_NUM);
	GRANT ALL ON REPORT_D12 TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CLASS_ID' AND RDB$RELATION_NAME = 'REPORT_D12'}

	ALTER TABLE REPORT_D12
	ADD CLASS_ID BIGINT;
	
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'CLASS_TYPE_ID'
	AND RDB$RELATION_NAME = 'REPORT_D12'}

	ALTER TABLE REPORT_D12
	ADD CLASS_TYPE_ID BIGINT;
	
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SCHOOL_ID' AND RDB$RELATION_NAME = 'REPORT_D12_ADD'}

  CREATE TABLE REPORT_D12_ADD (
    SCHOOL_ID     BIGINT NOT NULL,
    SCHOLAR_ID    BIGINT NOT NULL,
    DATE_MODIFY   TIMESTAMP NOT NULL,
    CLASS_TYPE    BIGINT,
    STAGE_ID      BIGINT,
    CLASS_ID      BIGINT,
    REASON_IN     BIGINT,
    DATE_IN       DATE,
    REASON_OUT    DATE,
    DATE_OUT      DATE
  );

  CREATE INDEX REPORT_D12_ADD_IDX2 ON REPORT_D12_ADD (SCHOOL_ID, SCHOLAR_ID, DATE_IN);
  GRANT ALL ON REPORT_D12_ADD TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CLASS_ID' AND RDB$RELATION_NAME = 'REPORT_D12_ADD'}

  ALTER TABLE REPORT_D12_ADD ADD CLASS_ID BIGINT;	
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REASON_IN' AND RDB$RELATION_NAME = 'REPORT_D12_ADD'}

  ALTER TABLE REPORT_D12_ADD ADD REASON_IN BIGINT;	
  ALTER TABLE REPORT_D12_ADD ADD DATE_IN DATE;	
  ALTER TABLE REPORT_D12_ADD ADD REASON_OUT BIGINT;	
  ALTER TABLE REPORT_D12_ADD ADD DATE_OUT DATE;	
  COMMIT WORK;

  DROP INDEX REPORT_D12_ADD_IDX1;
  COMMIT WORK;
  CREATE INDEX REPORT_D12_ADD_IDX2 ON REPORT_D12_ADD (SCHOOL_ID, SCHOLAR_ID, DATE_IN);
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS
	SELECT FIRST 1 I.RDB$INDEX_NAME
	FROM RDB$INDICES I
	LEFT JOIN RDB$INDEX_SEGMENTS S
	ON I.RDB$INDEX_NAME = S.RDB$INDEX_NAME
	LEFT JOIN RDB$RELATION_CONSTRAINTS RC
	ON RC.RDB$INDEX_NAME = I.RDB$INDEX_NAME
	WHERE RC.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
	AND I.RDB$INDEX_NAME = 'PK_REPORT_D12'}

	ALTER TABLE REPORT_D12 DROP CONSTRAINT PK_REPORT_D12;
	CREATE INDEX REPORT_D12_IDX1 ON REPORT_D12 (SCHOOL_ID,SCHOLAR_ID,ROW_NUM);
	CREATE INDEX REPORT_D12_IDX2 ON REPORT_D12 (ROW_NUM);

	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'USER_ID'
	AND RDB$RELATION_NAME = 'USER_SETTINGS'}
	CREATE TABLE USER_SETTINGS (
		USER_ID    BIGINT NOT NULL,
		MODULE_ID  BIGINT NOT NULL,
		SETTINGS   VARCHAR(4000)
	);
	ALTER TABLE USER_SETTINGS ADD CONSTRAINT PK_USER_SETTINGS PRIMARY KEY (USER_ID, MODULE_ID);
	ALTER TABLE USER_SETTINGS ADD CONSTRAINT FK_USER_SETTINGS_1 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID);
	ALTER TABLE USER_SETTINGS ADD CONSTRAINT FK_USER_SETTINGS_2 FOREIGN KEY (MODULE_ID) REFERENCES MODULES (MODULE_ID);
	GRANT ALL ON USER_SETTINGS TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'OBJ_ID'
	AND RDB$RELATION_NAME = 'TREE_TMP'}
	CREATE GLOBAL TEMPORARY TABLE TREE_TMP (
	    "LEVEL"  SMALLINT,
	    OBJ_ID   BIGINT,
	    TYPE_ID  BIGINT
	) ON COMMIT DELETE ROWS;

	CREATE INDEX TREE_TMP_LEVEL_IDX ON TREE_TMP ("LEVEL");
	GRANT ALL ON TREE_TMP TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SEARCH_ID' AND RDB$RELATION_NAME = 'SEARCH'}

	CREATE GENERATOR GEN_SEARCH_ID;
	CREATE TABLE SEARCH (
		SEARCH_ID      BIGINT NOT NULL,
		USER_ID        BIGINT NOT NULL,
		TYPE_ID        BIGINT NOT NULL,
		LEVEL_ID       BIGINT NOT NULL,
		IS_ACTIVE      SMALLINT DEFAULT 1 NOT NULL,
		SEARCH_NAME    VARCHAR(100) DEFAULT '' NOT NULL,
		MAX_ROW_COUNT  INTEGER
	);
	CREATE TABLE SEARCHFIELDS (
		SEARCH_ID        BIGINT NOT NULL,
		TYPE_ID          BIGINT NOT NULL,
		PARAM_ID         BIGINT NOT NULL,
		GRID_ORDER       SMALLINT DEFAULT 0 NOT NULL,
		SEARCH_AGREGATE  VARCHAR(3) DEFAULT '' NOT NULL
	);
	CREATE GLOBAL TEMPORARY TABLE SEARCHING (
		SEARCH_ID       BIGINT NOT NULL,
		SEARCH_ORDER    BIGINT NOT NULL,
		PARENT_ID       BIGINT,
		PARENT_TYPE_ID  BIGINT,
		LINK_ID         BIGINT,
		OBJECT_ID       BIGINT NOT NULL,
		OBJECT_TYPE_ID  BIGINT NOT NULL,
		IS_OK           SMALLINT NOT NULL
	)
	ON COMMIT DELETE ROWS;
	CREATE TABLE SEARCHPARAMS (
		SEARCH_ID    BIGINT NOT NULL,
		TYPE_ID      BIGINT NOT NULL,
		PARAM_ID     BIGINT NOT NULL,
		SORT_ORDER   SMALLINT DEFAULT 0 NOT NULL,
		SEARCH_TERM  VARCHAR(10) DEFAULT '=' NOT NULL,
		VAL_S        VARCHAR(4000),
		VAL_I        BIGINT,
		VAL_F        DOUBLE PRECISION,
		VAL_D        DATE
	);
	CREATE TABLE SEARCHTYPES (
		SEARCH_ID      BIGINT NOT NULL,
		TYPE_ID        BIGINT NOT NULL,
		SEARCH_ORDER   SMALLINT DEFAULT 0 NOT NULL,
		SEARCH_TERM    VARCHAR(10) DEFAULT '=' NOT NULL,
		SEARCH_VIEW    VARCHAR(10) DEFAULT 'list' NOT NULL,
		OWNER_TYPE_ID  BIGINT
	);
	ALTER TABLE SEARCH ADD CONSTRAINT UNQ1_SEARCH UNIQUE (USER_ID, TYPE_ID, LEVEL_ID, SEARCH_NAME);
	ALTER TABLE SEARCH ADD CONSTRAINT PK_SEARCH PRIMARY KEY (SEARCH_ID);
	ALTER TABLE SEARCHFIELDS ADD CONSTRAINT PK_SEARCHFIELDS PRIMARY KEY (SEARCH_ID, TYPE_ID, PARAM_ID);
	ALTER TABLE SEARCHPARAMS ADD CONSTRAINT PK_SEARCHPARAMS PRIMARY KEY (SEARCH_ID, TYPE_ID, PARAM_ID, SORT_ORDER);
	ALTER TABLE SEARCHTYPES ADD CONSTRAINT PK_SEARCHTYPES PRIMARY KEY (SEARCH_ID, TYPE_ID);

	ALTER TABLE SEARCH ADD CONSTRAINT FK_SEARCH_1 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCH ADD CONSTRAINT FK_SEARCH_2 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCH ADD CONSTRAINT FK_SEARCH_3 FOREIGN KEY (LEVEL_ID) REFERENCES LEVELS (LEVEL_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHFIELDS ADD CONSTRAINT FK_SEARCHFIELDS_1 FOREIGN KEY (SEARCH_ID) REFERENCES SEARCH (SEARCH_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHFIELDS ADD CONSTRAINT FK_SEARCHFIELDS_2 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHFIELDS ADD CONSTRAINT FK_SEARCHFIELDS_3 FOREIGN KEY (PARAM_ID) REFERENCES PARAMS (PARAM_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHPARAMS ADD CONSTRAINT FK_SEARCHPARAMS_1 FOREIGN KEY (SEARCH_ID) REFERENCES SEARCH (SEARCH_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHPARAMS ADD CONSTRAINT FK_SEARCHPARAMS_2 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHPARAMS ADD CONSTRAINT FK_SEARCHPARAMS_3 FOREIGN KEY (PARAM_ID) REFERENCES PARAMS (PARAM_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHTYPES ADD CONSTRAINT FK_SEARCHTYPES_1 FOREIGN KEY (SEARCH_ID) REFERENCES SEARCH (SEARCH_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHTYPES ADD CONSTRAINT FK_SEARCHTYPES_2 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;
	ALTER TABLE SEARCHTYPES ADD CONSTRAINT FK_SEARCHTYPES_3 FOREIGN KEY (OWNER_TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;

	CREATE INDEX SEARCHING_IDX1 ON SEARCHING (SEARCH_ID, SEARCH_ORDER, OBJECT_ID);

	CREATE OR ALTER TRIGGER SEARCH_BI FOR SEARCH
	ACTIVE BEFORE INSERT POSITION 0
	AS
	DECLARE VARIABLE G BIGINT;
	BEGIN
		SELECT GEN * MULTIPLIER FROM GEN INTO :G;
		IF (NEW.SEARCH_ID IS NULL) THEN NEW.SEARCH_ID = GEN_ID(GEN_SEARCH_ID, 1) + :G;
	END;

	COMMIT WORK;
{$ENDIF}

/* Коррекция нового списка */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'DATA_PATH' AND RDB$RELATION_NAME = 'SEARCHING'}

    ALTER TABLE SEARCHING ADD DATA_PATH VARCHAR(200) CHARACTER SET ASCII NOT NULL;
    CREATE INDEX SEARCHING_IDX2 ON SEARCHING (SEARCH_ID, SEARCH_ORDER, OBJECT_ID, DATA_PATH);    
    COMMIT WORK;

{$ENDIF}

/* Table VALM 2012-03-05 */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'MARK_ID' AND RDB$RELATION_NAME = 'VALM'}
	CREATE GENERATOR GEN_MARK_ID;

	CREATE TABLE VALM (
		MARK_ID      BIGINT NOT NULL,
		PUPIL_ID     BIGINT NOT NULL,
		SUBJECT_ID   BIGINT NOT NULL,
		TEACHER_ID   BIGINT,
		YEAR_ID      BIGINT NOT NULL,
		MARKTYPE_ID  BIGINT NOT NULL,
		MARKVAL_ID   BIGINT NOT NULL,
		IS_DEL       SMALLINT DEFAULT 0 NOT NULL,
		DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
	);
	ALTER TABLE VALM ADD CONSTRAINT PK_VALM PRIMARY KEY (MARK_ID);
	ALTER TABLE VALM ADD CONSTRAINT FK_VALM_1 FOREIGN KEY (PUPIL_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE;
	ALTER TABLE VALM ADD CONSTRAINT FK_VALM_2 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE;
	ALTER TABLE VALM ADD CONSTRAINT FK_VALM_3 FOREIGN KEY (TEACHER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE;
	ALTER TABLE VALM ADD CONSTRAINT FK_VALM_4 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE;
	ALTER TABLE VALM ADD CONSTRAINT FK_VALM_5 FOREIGN KEY (MARKTYPE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE;
	ALTER TABLE VALM ADD CONSTRAINT FK_VALM_6 FOREIGN KEY (MARKVAL_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE;

	CREATE OR ALTER TRIGGER VALM_BI FOR VALM
	ACTIVE BEFORE INSERT POSITION 0
	AS
	DECLARE VARIABLE G BIGINT;
	BEGIN
		SELECT GEN * MULTIPLIER FROM GEN INTO :G;
		IF (NEW.MARK_ID IS NULL) THEN NEW.MARK_ID = GEN_ID(GEN_MARK_ID,1) + :G;
	END;

	CREATE OR ALTER TRIGGER VALM_BU FOR VALM
	ACTIVE BEFORE UPDATE POSITION 0
	AS
	BEGIN
		NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	END;
	
	GRANT ALL ON VALM TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

/* NEW ROLES 2012-04-09 */
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'INTOKC_ROLE'}
	CREATE ROLE INTOKC_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'ZNAK_ROLE'}
	CREATE ROLE ZNAK_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'USER1_ROLE'}
	CREATE ROLE USER1_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'USER2_ROLE'}
	CREATE ROLE USER2_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'USER3_ROLE'}
	CREATE ROLE USER3_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'USER4_ROLE'}
	CREATE ROLE USER4_ROLE;
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT RDB$ROLE_NAME
	FROM RDB$ROLES
	WHERE RDB$ROLE_NAME = 'USER5_ROLE'}
	CREATE ROLE USER5_ROLE;
	COMMIT WORK;
{$ENDIF}

/* Table SEARCHING_TYPES 2012-04-24 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'TYPE_ID'
	AND RDB$RELATION_NAME = 'SEARCHING_TYPES'}
	CREATE GLOBAL TEMPORARY TABLE SEARCHING_TYPES (
		TYPE_ID   BIGINT NOT NULL,
		CHILD_ID  BIGINT NOT NULL
	) ON COMMIT DELETE ROWS;
	GRANT ALL ON SEARCHING_TYPES TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

/* Table PARAMS column DO_CHECK 2012-05-02 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'DO_CHECK'
	AND RDB$RELATION_NAME = 'PARAMS'}

	ALTER TABLE PARAMS
	ADD DO_CHECK SMALLINT DEFAULT 0 NOT NULL,
	ADD DO_CHECK_EVENT SMALLINT DEFAULT 0 NOT NULL;

	COMMIT WORK;
{$ENDIF}

/* Исключено удаление SEARCH_OBJECT_FIND */

/* 2012-06-05 DB optimization */
{$IFEXISTS
	SELECT RDB$CONSTRAINT_NAME
	FROM RDB$REF_CONSTRAINTS
	WHERE RDB$CONSTRAINT_NAME = 'LINKS_LISTVAL_ID'}

	ALTER TABLE LINKS DROP CONSTRAINT LINKS_LISTVAL_ID;

	COMMIT WORK;
{$ENDIF}

{$IFEXISTS
	SELECT RDB$CONSTRAINT_NAME
	FROM RDB$REF_CONSTRAINTS
	WHERE RDB$CONSTRAINT_NAME = 'LINKS_REASON_ID'}

	ALTER TABLE LINKS DROP CONSTRAINT LINKS_REASON_ID;

	COMMIT WORK;
{$ENDIF}

{$IFEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'COST'
	AND RDB$RELATION_NAME = 'LINKS'}

	UPDATE LINKS SET REASON_ID = COST
	WHERE OBJ_TYPE_ID IN (52, 106, 107)
	AND COST > 0;

	COMMIT WORK;
{$ENDIF}


{$IFNOTEXISTS SELECT RDB$GENERATOR_NAME	FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'GEN_GIA_ON_NUM'}
  CREATE SEQUENCE GEN_GIA_ON_NUM;
  COMMIT WORK;
{$ENDIF}

/* READ ONLY  2012-08-23 */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'READ_ONLY' AND RDB$RELATION_NAME = 'LUSERS'}
  ALTER TABLE LUSERS ADD READ_ONLY SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;
{$ENDIF}

/* Table SNILS_INDEX add column DOB 2012-12-04 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'DOB'
	AND RDB$RELATION_NAME = 'SNILS_INDEX'}

	ALTER TABLE SNILS_INDEX ADD DOB DATE;

	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALR_VAL'}

  CREATE INDEX VALR_VAL ON VALR (VAL);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALR_OBJ_PARAM_VAL'}

  CREATE INDEX VALR_OBJ_PARAM_VAL ON VALR (OBJ_ID,PARAM_ID,VAL);
  COMMIT WORK;

{$ENDIF}

/* Table LINKS add new ext object info*/
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'EXT_OBJ_ID'
	AND RDB$RELATION_NAME = 'LINKS'}

	ALTER TABLE LINKS ADD EXT_OBJ_ID BIGINT;
	ALTER TABLE LINKS ADD EXT_OBJ_TYPE_ID BIGINT;
	ALTER TABLE LINKS ADD CONSTRAINT LINKS_EXT_OBJ_ID FOREIGN KEY (EXT_OBJ_ID) REFERENCES OBJECTS(OBJ_ID) USING INDEX LINKS_EXT_OBJ_ID;
	ALTER TABLE LINKS ADD CONSTRAINT LINKS_EXT_OBJ_TYPE_ID FOREIGN KEY (EXT_OBJ_TYPE_ID) REFERENCES TYPES(TYPE_ID) USING INDEX LINKS_EXT_OBJ_TYPE_ID;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'EXT_TYPE_ID'
	AND RDB$RELATION_NAME = 'SEARCHPARAMS'}

	ALTER TABLE SEARCHPARAMS
	ADD EXT_TYPE_ID BIGINT;

	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'SCHOOL_ID'
	AND RDB$RELATION_NAME = 'REPORT_RIK83'}
	CREATE GLOBAL TEMPORARY TABLE REPORT_RIK83 (
		G           SMALLINT NOT NULL,
		N1          SMALLINT,
		N           SMALLINT,
		SCHOOL_ID   BIGINT NOT NULL,
		TEACHER_ID  BIGINT,
		V03         INTEGER,
		V04         NUMERIC(11,2),
		V05         INTEGER,
		V06         INTEGER,
		V07         INTEGER,
		V08         INTEGER,
		V09         INTEGER,
		V10         INTEGER,
		V11         INTEGER,
		V12         INTEGER,
		V13         INTEGER,
		V14         INTEGER,
		V15         INTEGER,
		V16         INTEGER,
		V17         INTEGER,
		V18         INTEGER,
		V19         INTEGER,
		V20         INTEGER,
		V21         INTEGER,
		V22         INTEGER,
		V23         INTEGER,
		V24         INTEGER,
		V25         INTEGER,
		V26         INTEGER,
		V27         INTEGER,
		V28         INTEGER,
		V29         INTEGER,
		V30         INTEGER
	) ON COMMIT PRESERVE ROWS;
	/* Fields descriptions */
	COMMENT ON COLUMN REPORT_RIK83.G IS 
	'Grid #';
	COMMENT ON COLUMN REPORT_RIK83.N1 IS 
	'Row # in Grid 1';
	COMMENT ON COLUMN REPORT_RIK83.N IS
	'Row # in other Grids';
	/* Privileges of roles */
	GRANT ALL ON REPORT_RIK83 TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OCATD' AND RDB$RELATION_NAME = 'VALA'}
  ALTER TABLE VALA ADD OCATD VARCHAR(11);	
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'BEGIN_GROUP'
	AND RDB$RELATION_NAME = 'PARAMS'}

	ALTER TABLE PARAMS
	ADD BEGIN_GROUP SMALLINT
	DEFAULT 0
	NOT NULL;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'IS_REQUIRED' AND RDB$RELATION_NAME = 'RPARAMS'}

	ALTER TABLE RPARAMS
	ADD IS_REQUIRED SMALLINT
	DEFAULT 1;

	ALTER TABLE RPARAMS ALTER IS_REQUIRED POSITION 7;
	COMMIT WORK;
{$ENDIF}

CREATE OR ALTER trigger links_bi for links
active before insert position 0
AS
DECLARE VARIABLE G BIGINT;
BEGIN
	SELECT GEN * MULTIPLIER FROM GEN INTO :G;
	IF (NEW.LINK_ID IS NULL) THEN NEW.LINK_ID = GEN_ID(GEN_LINK_ID,1) + :G;

	SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.PARENT_ID INTO NEW.PARENT_TYPE_ID;
	SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.OBJ_ID INTO NEW.OBJ_TYPE_ID;
	SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.EXT_OBJ_ID INTO NEW.EXT_OBJ_TYPE_ID;
END;

COMMIT WORK;

/* ADD INDEX FOR SEARCH INCREASE 2014-02-26 */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SVAL' AND RDB$RELATION_NAME = 'VALS'}

  ALTER TABLE VALS ADD SVAL VARCHAR(500);
  COMMIT WORK;

  UPDATE VALS SET SVAL = SUBSTRING(VAL FROM 1 FOR 500);
  COMMIT WORK;

  CREATE INDEX VALS_PARAM_SVAL_IDX ON VALS (PARAM_ID, SVAL);
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'VALS_BI0'}

  DROP TRIGGER VALS_BI0;
  COMMIT WORK;  

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'VALS_BU'}

  DROP TRIGGER VALS_BU;
  COMMIT WORK;  

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'XVAL' AND RDB$RELATION_NAME = 'VALS'}

  ALTER TABLE VALS ADD XVAL VARCHAR(40);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER VALS_BI2 FOR VALS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    NEW.SVAL = SUBSTRING(NEW.VAL FROM 1 FOR 500);

    IF(NEW.PARAM_ID IN (55, 56, 57, 59, 60, 61, 128, 129, 130, 827, 828, 829, 1409, 2455, 2365, 3277)) THEN
    NEW.XVAL = REPLACE(REPLACE(REPLACE(UPPER(SUBSTRING(NEW.VAL FROM 1 FOR 40)), 'Ё', 'Е'), '-', ''), ' ', '');
  end
  ^

  CREATE OR ALTER TRIGGER VALS_BU2 FOR VALS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    NEW.SVAL = SUBSTRING(NEW.VAL FROM 1 FOR 500);

    IF(NEW.PARAM_ID IN (55, 56, 57, 59, 60, 61, 128, 129, 130, 827, 828, 829, 1409, 2455, 2365, 3277)) THEN
    NEW.XVAL = REPLACE(REPLACE(REPLACE(UPPER(SUBSTRING(NEW.VAL FROM 1 FOR 40)), 'Ё', 'Е'), '-', ''), ' ', '');
  END
  ^

  SET TERM ; ^

  COMMIT WORK;

  UPDATE VALS SET VAL = VAL WHERE 1 = 1;
  COMMIT WORK;

  CREATE INDEX VALS_PARAM_XVAL_IDX ON VALS (PARAM_ID, XVAL);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME=S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALL_PARAM_VAL_IDX'}

  CREATE INDEX VALL_PARAM_VAL_IDX ON VALL (PARAM_ID,LISTVAL_ID);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME=S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALI_PARAM_VAL_IDX'}

  CREATE INDEX VALI_PARAM_VAL_IDX ON VALI (PARAM_ID,VAL);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME=S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALF_PARAM_VAL_IDX'}

  CREATE INDEX VALF_PARAM_VAL_IDX ON VALF (PARAM_ID,VAL);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS
	SELECT I.RDB$INDEX_NAME
	FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S
	WHERE I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
	AND I.RDB$INDEX_NAME = 'VALDT_PARAM_VAL_IDX'}

	CREATE INDEX VALDT_PARAM_VAL_IDX
	ON VALDT (PARAM_ID,VAL);

	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT I.RDB$INDEX_NAME
	FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S
	WHERE I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
	AND I.RDB$INDEX_NAME = 'VALD_PARAM_VAL_IDX'}

	CREATE INDEX VALD_PARAM_VAL_IDX
	ON VALD (PARAM_ID,VAL);

	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT I.RDB$INDEX_NAME
	FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S
	WHERE I.RDB$INDEX_NAME=S.RDB$INDEX_NAME
	AND I.RDB$INDEX_NAME = 'VALT_PARAM_VAL_IDX'}

	CREATE INDEX VALT_PARAM_VAL_IDX
	ON VALT (PARAM_ID,VAL);

	COMMIT WORK;
{$ENDIF}

/* Table RES column VAL_LONG 2014-03-24 */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'VAL_LONG'
	AND RDB$RELATION_NAME = 'RES'}

	ALTER TABLE RES
	ADD VAL_LONG VARCHAR(4000);
	ALTER TABLE RES ALTER VAL_LONG POSITION 4;

	ALTER TABLE LISTVALS
	ADD RES_ID BIGINT;
	ALTER TABLE LISTVALS ALTER RES_ID POSITION 3;

	COMMIT WORK;
{$ENDIF}

CREATE OR ALTER trigger listvals_bi for listvals
active before insert position 0
AS
DECLARE VARIABLE G BIGINT;
BEGIN
	SELECT GEN * MULTIPLIER FROM GEN INTO :G;
	IF (NEW.LISTVAL_ID IS NULL) THEN NEW.LISTVAL_ID = GEN_ID(GEN_LISTVAL_ID, 1) + :G;
	IF (NEW.RES_ID IS NULL) THEN NEW.RES_ID = GEN_ID(GEN_RES_ID, 1) + :G;
END;

COMMIT WORK;

/*2014-07-10*/
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'GROUP_NAME'
	AND RDB$RELATION_NAME = 'LREPORTS'}

	ALTER TABLE LREPORTS
	ADD GROUP_NAME VARCHAR(100) CHARACTER SET UTF8 
	COLLATE UTF8;
	ALTER TABLE LREPORTS ALTER GROUP_NAME POSITION 3;

	COMMIT WORK;
{$ENDIF}

/* Table LISTVALS column FILTER 2014-04-09 */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'FILTER' AND RDB$RELATION_NAME = 'LISTVALS'}
  ALTER TABLE LISTVALS ADD "FILTER" VARCHAR(255);
  ALTER TABLE LISTVALS ALTER "FILTER" POSITION 6;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'FIN_LISTS'}

	CREATE TABLE FIN_LISTS (
	    ID           BIGINT NOT NULL,
	    PARENT_ID    BIGINT NOT NULL,
	    OBJ_TYPE     SMALLINT NOT NULL,
	    NAME         VARCHAR(1000),
	    IS_ACTIVE    SMALLINT NOT NULL,
	    DATE_MODIFY  TIMESTAMP,
	    DATE_DEL     TIMESTAMP
	);

	ALTER TABLE FIN_LISTS ADD CONSTRAINT PK_FIN_LISTS PRIMARY KEY (ID, PARENT_ID);


	SET TERM ^ ;

	/* Trigger: FIN_LISTS_BI0 */
	CREATE OR ALTER TRIGGER FIN_LISTS_BI0 FOR FIN_LISTS
	ACTIVE BEFORE INSERT POSITION 0
	AS
	DECLARE VARIABLE G BIGINT;
	BEGIN
	  SELECT GEN * MULTIPLIER FROM GEN INTO :G;
	  IF (NEW.ID IS NULL) THEN NEW.ID = GEN_ID(GEN_OBJ_ID,1) + :G;
	  IF(NEW.DATE_MODIFY IS NULL) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	END
	^

	/* Trigger: FIN_LISTS_BU0 */
	CREATE OR ALTER TRIGGER FIN_LISTS_BU0 FOR FIN_LISTS
	ACTIVE BEFORE UPDATE POSITION 0
	AS
	begin
	  IF(NEW.DATE_MODIFY IS NULL OR NEW.DATE_MODIFY = OLD.DATE_MODIFY) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	end

	^

	SET TERM ; ^

	GRANT ALL ON FIN_LISTS TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'FIN_PARAM_GROUPS'}

	CREATE TABLE FIN_PARAM_GROUPS (
	    ID             BIGINT NOT NULL,
	    NAME           VARCHAR(1000) NOT NULL,
	    DATE_MODIFY    TIMESTAMP,
	    DATE_DEL       TIMESTAMP,
	    DISPLAY_ORDER  INTEGER DEFAULT 0 NOT NULL
	);

	ALTER TABLE FIN_PARAM_GROUPS ADD CONSTRAINT PK_FIN_PARAM_GROUPS PRIMARY KEY (ID);


	SET TERM ^ ;

	/* Trigger: FIN_PARAM_GROUPS_BI0 */
	CREATE OR ALTER TRIGGER FIN_PARAM_GROUPS_BI0 FOR FIN_PARAM_GROUPS
	ACTIVE BEFORE INSERT POSITION 0
	AS
	DECLARE VARIABLE G BIGINT;
	BEGIN
	  SELECT GEN * MULTIPLIER FROM GEN INTO :G;
	  IF (NEW.ID IS NULL) THEN NEW.ID = GEN_ID(GEN_OBJ_ID,1) + :G;
	  IF(NEW.DATE_MODIFY IS NULL) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	END
	^


	/* Trigger: FIN_PARAM_GROUPS_BU0 */
	CREATE OR ALTER TRIGGER FIN_PARAM_GROUPS_BU0 FOR FIN_PARAM_GROUPS
	ACTIVE BEFORE UPDATE POSITION 0
	AS
	begin
	  IF(NEW.DATE_MODIFY IS NULL OR NEW.DATE_MODIFY = OLD.DATE_MODIFY) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	end

	^

	SET TERM ; ^

	GRANT ALL ON FIN_PARAM_GROUPS TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'PARAM_ID' AND RDB$RELATION_NAME = 'FIN_PARAMS'}

	CREATE TABLE FIN_PARAMS (
	    GROUP_ID       BIGINT NOT NULL,
	    PARAM_ID       BIGINT NOT NULL,
	    NAME           VARCHAR(1000) NOT NULL,
	    PARAM_SOURCE   VARCHAR(1000),
	    PARAM_PATH     VARCHAR(100),
	    DIRECTION      SMALLINT NOT NULL,
	    K_WEIGHT       DOUBLE PRECISION NOT NULL,
	    DISPLAY_ORDER  INTEGER DEFAULT 0 NOT NULL,
	    DATE_MODIFY    TIMESTAMP,
	    DATE_DEL       TIMESTAMP
	);

	ALTER TABLE FIN_PARAMS ADD CONSTRAINT PK_FIN_PARAMS PRIMARY KEY (PARAM_ID);


	SET TERM ^ ;

	/* Trigger: FIN_PARAMS_BI0 */
	CREATE OR ALTER TRIGGER FIN_PARAMS_BI0 FOR FIN_PARAMS
	ACTIVE BEFORE INSERT POSITION 0
	AS
	DECLARE VARIABLE G BIGINT;
	BEGIN
	  SELECT GEN * MULTIPLIER FROM GEN INTO :G;
	  IF (NEW.PARAM_ID IS NULL) THEN NEW.PARAM_ID = GEN_ID(GEN_OBJ_ID,1) + :G;
	  IF(NEW.DATE_MODIFY IS NULL) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	END
	^


	/* Trigger: FIN_PARAMS_BU0 */
	CREATE OR ALTER TRIGGER FIN_PARAMS_BU0 FOR FIN_PARAMS
	ACTIVE BEFORE UPDATE POSITION 0
	AS
	begin
	  IF(NEW.DATE_MODIFY IS NULL OR NEW.DATE_MODIFY = OLD.DATE_MODIFY) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	end

	^

	SET TERM ; ^

	GRANT ALL ON FIN_PARAMS TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'FIN_PARAM_GROUPS'}

	CREATE TABLE FIN_PARAM_GROUPS (
	    ID             BIGINT NOT NULL,
	    NAME           VARCHAR(1000) CHARACTER SET UTF8 NOT NULL,
	    DATE_MODIFY    TIMESTAMP,
	    DATE_DEL       TIMESTAMP,
	    DISPLAY_ORDER  INTEGER DEFAULT 0 NOT NULL
	);

	ALTER TABLE FIN_PARAM_GROUPS ADD CONSTRAINT PK_FIN_PARAM_GROUPS PRIMARY KEY (ID);


	SET TERM ^ ;

	/* Trigger: FIN_PARAM_GROUPS_BI0 */
	CREATE OR ALTER TRIGGER FIN_PARAM_GROUPS_BI0 FOR FIN_PARAM_GROUPS
	ACTIVE BEFORE INSERT POSITION 0
	AS
	DECLARE VARIABLE G BIGINT;
	BEGIN
	  SELECT GEN * MULTIPLIER FROM GEN INTO :G;
	  IF (NEW.ID IS NULL) THEN NEW.ID = GEN_ID(GEN_OBJ_ID,1) + :G;
	  IF(NEW.DATE_MODIFY IS NULL) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	END
	^


	/* Trigger: FIN_PARAM_GROUPS_BU0 */
	CREATE OR ALTER TRIGGER FIN_PARAM_GROUPS_BU0 FOR FIN_PARAM_GROUPS
	ACTIVE BEFORE UPDATE POSITION 0
	AS
	begin
	  IF(NEW.DATE_MODIFY IS NULL OR NEW.DATE_MODIFY = OLD.DATE_MODIFY) THEN NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
	end

	^

	SET TERM ; ^

	GRANT ALL ON FIN_PARAM_GROUPS TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SCHOOL_ID' AND RDB$RELATION_NAME = 'FIN_VALUES'}

	CREATE TABLE FIN_VALUES (
	    SCHOOL_ID  BIGINT NOT NULL,
	    PARAM_ID   BIGINT NOT NULL,
	    RANGE_ID   BIGINT NOT NULL,
	    VAL        DOUBLE PRECISION
	);

	ALTER TABLE FIN_VALUES ADD CONSTRAINT PK_FIN_VALUES PRIMARY KEY (SCHOOL_ID, PARAM_ID, RANGE_ID);


	GRANT ALL ON FIN_VALUES TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FIAS_UID' AND RDB$RELATION_NAME = 'VALA'}
  ALTER TABLE VALA ADD FIAS_UID VARCHAR(36);	
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STREET_UID' AND RDB$RELATION_NAME = 'VALA'}
  ALTER TABLE VALA ADD STREET_UID VARCHAR(36);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'RAW_TEXT' AND RDB$RELATION_NAME = 'VALA'}
  ALTER TABLE VALA ADD RAW_TEXT VARCHAR(1000);
  COMMIT WORK;
{$ENDIF}

CREATE OR ALTER EXCEPTION DATA_ERROR '';
COMMIT WORK;

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'OBJECT_FRAMES'}

	CREATE TABLE OBJECT_FRAMES (
    		OBJ_ID          BIGINT NOT NULL,
	    	PARENT_TYPE_ID  BIGINT,
		TYPE_ID         BIGINT NOT NULL,
		CAPTION         VARCHAR(200) CHARACTER SET UTF8,
    		FRAME_CLASS     VARCHAR(100) CHARACTER SET UTF8 NOT NULL,
    		IS_DEL          SMALLINT DEFAULT 0 NOT NULL,
    		TAB_ID          BIGINT
	);

	ALTER TABLE OBJECT_FRAMES ADD CONSTRAINT PK_OBJECT_FRAMES PRIMARY KEY (OBJ_ID);

	ALTER TABLE OBJECT_FRAMES ADD CONSTRAINT FK_OBJECT_FRAMES_1 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
	ALTER TABLE OBJECT_FRAMES ADD CONSTRAINT FK_OBJECT_FRAMES_2 FOREIGN KEY (TAB_ID) REFERENCES TABS (TAB_ID) ON DELETE CASCADE ON UPDATE CASCADE;
	ALTER TABLE OBJECT_FRAMES ADD CONSTRAINT FK_OBJECT_FRAMES_3 FOREIGN KEY (PARENT_TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;

	SET TERM ^ ;

	CREATE OR ALTER TRIGGER OBJECT_FRAMES_BI0 FOR OBJECT_FRAMES
	ACTIVE BEFORE INSERT POSITION 0
	AS
	declare variable G BIGINT;
	begin
	  IF(NEW.OBJ_ID is null) THEN
	  BEGIN
	    SELECT MAX(OBJ_ID)
	    FROM OBJECT_FRAMES
	    INTO :G;
	    IF(G is null) THEN G = 0;
	    NEW.OBJ_ID = G + 1;
	  END
	end
	^        

	SET TERM ; ^

	GRANT ALL ON OBJECT_FRAMES TO INISSOFT_ROLE;
	GRANT SELECT, UPDATE, REFERENCES ON OBJECT_FRAMES TO TRIGGER OBJECT_FRAMES_BI0;

	COMMIT WORK;
{$ENDIF}

/* Заплатка для промежуточной сборки 03.2017 */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'PARENT_TYPE_ID' AND RDB$RELATION_NAME = 'OBJECT_FRAMES'}
  ALTER TABLE OBJECT_FRAMES ADD PARENT_TYPE_ID bigint;
  ALTER TABLE OBJECT_FRAMES ALTER TYPE_ID bigint not null;	
  COMMIT WORK;
{$ENDIF}

/* 20.04.2017 Добавление поля в CURRICULUM_HOURS */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'IS_ELECTIVE'
	AND RDB$RELATION_NAME = 'CURRICULUM_HOURS'}

	ALTER TABLE CURRICULUM_HOURS ADD IS_ELECTIVE smallint;
	
	COMMIT WORK;
{$ENDIF}
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'TEMPLATE_SUBJECT_ID'
	AND RDB$RELATION_NAME = 'CURRICULUM_HOURS'}

	ALTER TABLE CURRICULUM_HOURS ADD TEMPLATE_SUBJECT_ID bigint;
	
	COMMIT WORK;
{$ENDIF}

/* 07.07.2017 Таблица и связи хранения данных СМИР */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'OBJ_ID'
	AND RDB$RELATION_NAME = 'VALN'}

	CREATE TABLE VALN (
	    OBJ_ID  BIGINT NOT NULL,
	    OBJ_DATA  BLOB SUB_TYPE 1 SEGMENT SIZE 16384
	);

	ALTER TABLE VALN ADD CONSTRAINT PK_VALN PRIMARY KEY (OBJ_ID);
        ALTER TABLE VALN ADD CONSTRAINT FK_VALN_1 FOREIGN KEY (OBJ_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

	GRANT ALL ON VALN TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

/* 03.08.2017 Таблицы для хранения данных СКУД и СОП */
{$IFEXISTS
  SELECT 1
  FROM RDB$RELATION_FIELDS
  WHERE RDB$FIELD_NAME = 'PUPIL_ID'
  AND RDB$RELATION_NAME = 'SCUD_RAW'}

  SET TERM ^ ;

  create or alter procedure DC_SCUD_UPDATE (
    SUID varchar(100),
    DIRECTION varchar(100),
    EVENT_DATE varchar(100))
  as
  begin
  end ^

  SET TERM ; ^

  DROP TABLE SCUD_RAW;

{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'PERSON_ID'
	AND RDB$RELATION_NAME = 'SCUD_RAW'}

	CREATE TABLE SCUD_RAW (
	    PERSON_ID   BIGINT NOT NULL,
	    EVENT_DATE  TIMESTAMP NOT NULL,
	    EVENT_VAL   SMALLINT NOT NULL
	);

	ALTER TABLE SCUD_RAW ADD CONSTRAINT PK_SCUD_RAW PRIMARY KEY (PERSON_ID, EVENT_DATE);
	ALTER TABLE SCUD_RAW ADD CONSTRAINT FK_SCUD_RAW_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

	CREATE INDEX SCUD_RAW_IDX1 ON SCUD_RAW (EVENT_DATE);
	CREATE INDEX SCUD_RAW_IDX2 ON SCUD_RAW (PERSON_ID, EVENT_VAL);
	CREATE INDEX SCUD_RAW_IDX3 ON SCUD_RAW (EVENT_DATE, EVENT_VAL);

	GRANT ALL ON SCUD_RAW TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'PERSON_ID'
	AND RDB$RELATION_NAME = 'SOP_RAW'}

	CREATE TABLE SOP_RAW (
	    PERSON_ID   BIGINT NOT NULL,
	    EVENT_DATE  TIMESTAMP NOT NULL,
	    EVENT_VAL   SMALLINT NOT NULL
	);

	ALTER TABLE SOP_RAW ADD CONSTRAINT PK_SOP_RAW PRIMARY KEY (PERSON_ID, EVENT_DATE);
	ALTER TABLE SOP_RAW ADD CONSTRAINT FK_SOP_RAW_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

	CREATE INDEX SOP_RAW_IDX1 ON SOP_RAW (EVENT_DATE);
	CREATE INDEX SOP_RAW_IDX2 ON SOP_RAW (PERSON_ID, EVENT_VAL);
	CREATE INDEX SOP_RAW_IDX3 ON SOP_RAW (EVENT_DATE, EVENT_VAL);

	GRANT ALL ON SOP_RAW TO INISSOFT_ROLE;
	COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'EVENT_ID'
	AND RDB$RELATION_NAME = 'SOP_RAW'}

	ALTER TABLE SOP_RAW ADD EVENT_ID BIGINT NOT NULL;
        ALTER TABLE SOP_RAW ADD FOOD_NAME VARCHAR(200) NOT NULL;
	ALTER TABLE SOP_RAW ADD FOOD_QTY FLOAT NOT NULL;
	
	CREATE INDEX SOP_RAW_IDX4 ON SOP_RAW (EVENT_ID);
	

	COMMIT WORK;
{$ENDIF}

/* Новый столбец для фреймов 14.08.2017 */
{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LEVEL_ID' AND RDB$RELATION_NAME = 'OBJECT_FRAMES'}

	ALTER TABLE OBJECT_FRAMES ADD LEVEL_ID bigint;
	COMMIT WORK;

	ALTER TABLE OBJECT_FRAMES ADD CONSTRAINT FK_OBJECT_FRAMES_4 FOREIGN KEY (LEVEL_ID) REFERENCES LEVELS (LEVEL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
	COMMIT WORK;

{$ENDIF}

/* Таблица для сохранения данных СКУД */
{$IFNOTEXISTS
	SELECT 1
	FROM RDB$RELATION_FIELDS
	WHERE RDB$FIELD_NAME = 'PUPIL_ID'
	AND RDB$RELATION_NAME = 'SCUD_PUPILS'}

	CREATE TABLE SCUD_PUPILS (PUPIL_ID BIGINT PRIMARY KEY, UPDATED TIMESTAMP NOT NULL);
	ALTER TABLE SCUD_PUPILS ADD CONSTRAINT FK_SCUD_PUPILS_1 FOREIGN KEY (PUPIL_ID) REFERENCES OBJECTS (OBJ_ID);

	GRANT ALL ON SCUD_PUPILS TO INISSOFT_ROLE;
	COMMIT WORK;

{$ENDIF}


{$IFNOTEXISTS SELECT 1 
              FROM RDB$RELATION_FIELDS
              WHERE RDB$FIELD_NAME = 'DATE_ID' 
              AND RDB$RELATION_NAME = 'CJ_REPORT4_TEMP'}

	CREATE GLOBAL TEMPORARY TABLE CJ_REPORT4_TEMP (
	    DATE_ID      DATE NOT NULL,
	    CLASS_ID     BIGINT NOT NULL,
	    REASON_1     INTEGER,
	    REASON_2     INTEGER,
	    REASON_3     INTEGER,
	    REASON_4     INTEGER,
	    REASON_MISS  INTEGER
	) ON COMMIT DELETE ROWS;

	COMMIT WORK;

{$ENDIF}
{$IFNOTEXISTS SELECT RDB$INDEX_NAME FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'PK_CJ_REPORT4_TEMP' AND RDB$RELATION_NAME = 'CJ_REPORT4_TEMP'}
  ALTER TABLE CJ_REPORT4_TEMP ADD CONSTRAINT PK_CJ_REPORT4_TEMP PRIMARY KEY (DATE_ID, CLASS_ID);
  GRANT ALL ON CJ_REPORT4_TEMP TO INISSOFT_ROLE;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 
              FROM RDB$RELATION_FIELDS
              WHERE RDB$FIELD_NAME = 'OOOD_ID'
              AND RDB$RELATION_NAME = 'PARAGRAF_REPORT_VCN_TEMP'}

  CREATE GLOBAL TEMPORARY TABLE PARAGRAF_REPORT_VCN_TEMP (
      OOOD_ID      BIGINT,
      VAK_TAG      VARCHAR(20),
      VAC_ID       BIGINT,
      DATE_EVENTS  DATE,
      FIO_ID       BIGINT,
      LISTVAL_ID   INTEGER,
      STAVOK       DOUBLE PRECISION,
      TYPE_RECORD  INTEGER,
      VAC_POS_ID   INTEGER
  ) ON COMMIT DELETE ROWS;

  GRANT ALL ON PARAGRAF_REPORT_VCN_TEMP TO INISSOFT_ROLE;

  COMMIT WORK;

{$ENDIF}

/* 01.03.2018 Добавление таблицы для хранения сырых метаданных */
{$IFNOTEXISTS SELECT 1 
              FROM RDB$RELATION_FIELDS
              WHERE RDB$FIELD_NAME = 'OBJ_ID'
              AND RDB$RELATION_NAME = 'CS_METADATA'}

  CREATE TABLE CS_METADATA (
    OBJ_ID     BIGINT NOT NULL,
    ATTRNAME   VARCHAR(100) NOT NULL,
    ATTRVALUE  VARCHAR(4000)
  );

  ALTER TABLE CS_METADATA ADD CONSTRAINT PK_CS_METADATA PRIMARY KEY (OBJ_ID, ATTRNAME);
  GRANT ALL ON CS_METADATA TO INISSOFT_ROLE;

  COMMIT WORK;

{$ENDIF}

/* 14.03.2018 Создание таблиц для DataGate */
{$IFNOTEXISTS SELECT 1 FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'GEN_DC'}

  CREATE GENERATOR GEN_DC;

{$ENDIF}


{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'DC_TASKS'}

  CREATE TABLE DC_TASKS (
    ID              BIGINT NOT NULL,
    TASK_NAME       VARCHAR(100) NOT NULL,
    TASK_REF        VARCHAR(100),
    LAST_EXPORT     TIMESTAMP,
    LAST_TIMEMARK   TIMESTAMP,
    TASK_TIMING     VARCHAR(250) NOT NULL,
    TASK_ENABLED    SMALLINT DEFAULT 0 NOT NULL,
    RESTORE_MISSED  SMALLINT DEFAULT 0 NOT NULL,
    MISS_METHOD     SMALLINT DEFAULT 0 NOT NULL,
    TASK_METHOD     VARCHAR(100) NOT NULL,
    FMT_DATA        BLOB SUB_TYPE 1 SEGMENT SIZE 80,
    FMT_FILENAME    VARCHAR(200),
    IS_PRIVATE SMALLINT DEFAULT 0 NOT NULL,
    TASKPARAMS VARCHAR(4000)
  );

  ALTER TABLE DC_TASKS ADD PRIMARY KEY (ID);

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER DC_TASKS_BI0 FOR DC_TASKS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  DECLARE VARIABLE G BIGINT;
  BEGIN
    SELECT GEN * MULTIPLIER FROM GEN INTO :G;
    IF(G IS NULL) THEN G = 0;

    IF (NEW.ID IS NULL) THEN NEW.ID = GEN_ID(GEN_DC, 1) + :G;
  END
  ^

  SET TERM ; ^

  GRANT ALL ON DC_TASKS TO INISSOFT_ROLE;

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_PRIVATE' AND RDB$RELATION_NAME = 'DC_TASKS'}

  ALTER TABLE DC_TASKS ADD IS_PRIVATE SMALLINT DEFAULT 0 NOT NULL;

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'TASKPARAMS' AND RDB$RELATION_NAME = 'DC_TASKS'}

  ALTER TABLE DC_TASKS ADD TASKPARAMS VARCHAR(4000);

  COMMIT WORK;

{$ENDIF}

/* Поурочно-тематические планы Gen.2 */

{$IFNOTEXISTS SELECT 1 FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'GEN_PTP'}

    CREATE SEQUENCE GEN_PTP;

    CREATE TABLE PTP (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        OBJ_NAME     VARCHAR(1000) NOT NULL,
        PARENT_ID    BIGINT,
        OWNER_ID     BIGINT,
        LEVEL_ID     BIGINT,
        SUBJECT_ID   BIGINT,
        LEVEL_NUM    INTEGER NOT NULL,
        PTP_HOURS    INTEGER NOT NULL,
        STAGE_MASK    BIGINT,
        EDU_LEVEL_ID  BIGINT
    );

    ALTER TABLE PTP ADD CONSTRAINT PK_PTP PRIMARY KEY (OBJ_ID);
    ALTER TABLE PTP ADD CONSTRAINT FK_PTP_1 FOREIGN KEY (PARENT_ID) REFERENCES PTP (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE PTP ADD CONSTRAINT FK_PTP_2 FOREIGN KEY (OWNER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE PTP ADD CONSTRAINT FK_PTP_3 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE PTP ADD CONSTRAINT FK_PTP_4 FOREIGN KEY (LEVEL_ID) REFERENCES LISTVALS (LISTVAL_ID) ON UPDATE CASCADE;
    ALTER TABLE PTP ADD CONSTRAINT FK_PTP_5 FOREIGN KEY (EDU_LEVEL_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER PTP_BI0 FOR PTP
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      IF(NEW.OBJ_ID IS NULL) THEN
      BEGIN
          SELECT GEN * MULTIPLIER FROM GEN INTO :G;
          NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_PTP);
      END
    end 
    ^

    CREATE OR ALTER TRIGGER PTP_BU0 FOR PTP
    ACTIVE BEFORE INSERT OR UPDATE POSITION 0
    AS
    declare variable L integer;
    declare variable PID bigint;
    declare variable P_DT timestamp;
    declare variable CURR_ID bigint;
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;

      -- Нельзя ссылаться на несуществующий ПТП. Проверка только для актуальных планов
      IF(NEW.PARENT_ID IS NULL) THEN NEW.LEVEL_NUM = 0;
      ELSE
      BEGIN

          IF(NEW.DATE_DEL IS NULL) THEN
          BEGIN
              -- Подсчитываем наш номер уровня
              L = 0;
              CURR_ID = NEW.PARENT_ID;

              WHILE (CURR_ID IS NOT NULL) DO
              BEGIN

                  PID = NULL;
                  P_DT = NULL;
                  SELECT P.PARENT_ID, P.DATE_DEL
                  FROM PTP P
                  WHERE P.OBJ_ID = :CURR_ID
                  INTO :PID, :P_DT;

                  IF(PID IS NOT NULL AND P_DT IS NOT NULL) THEN EXCEPTION DATA_ERROR 'Родительский ПТП для плана ' || PID || ' не существует или удален';

                  L = L + 1;
                  CURR_ID = PID;

                  IF(L > 1000) THEN EXCEPTION DATA_ERROR 'Системная ошибка: в иерархии ПТП имеется кольцевая связь';

              END

              NEW.LEVEL_NUM = L;

          END
      
      END

      -- При удалении требуем, чтобы дочерние планы были уже удалены
      IF(NEW.DATE_DEL IS NOT NULL) THEN
      BEGIN
          L = 0;
          SELECT FIRST 1 1
          FROM PTP P
          WHERE P.PARENT_ID = NEW.OBJ_ID AND P.DATE_DEL IS NULL
          INTO :L;

          IF(L > 0) THEN EXCEPTION DATA_ERROR 'Сначала необходимо удалить дочерние планы';
      END

      IF(NEW.PTP_HOURS < 0) THEN EXCEPTION DATA_ERROR 'Отрицательное количество часов недопустимо';

    end
    ^

    SET TERM ; ^

{$ENDIF}

GRANT ALL ON PTP TO INISSOFT_ROLE;

/* Дополнение для ПТП ГПД, ДО и колледжей */

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SUBJECT_ID' AND RDB$RELATION_NAME = 'PTP' AND RDB$NULL_FLAG = 1}

  ALTER TABLE PTP ALTER SUBJECT_ID DROP NOT NULL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STAGE_MASK' AND RDB$RELATION_NAME = 'PTP'}

  ALTER TABLE PTP ADD STAGE_MASK BIGINT;
  ALTER TABLE PTP ADD EDU_LEVEL_ID BIGINT;
  ALTER TABLE PTP ADD CONSTRAINT FK_PTP_5 FOREIGN KEY (EDU_LEVEL_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PTP_LESSONS'}

    CREATE TABLE PTP_LESSONS (
        OBJ_ID            BIGINT NOT NULL,
        DATE_ADD          TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY       TIMESTAMP NOT NULL,
        DATE_DEL          TIMESTAMP,
        PTP_ID            BIGINT NOT NULL,
        LESSON_NUM        INTEGER NOT NULL,
        THEME_TEXT        VARCHAR(1000) NOT NULL,
        HOMETASK_TEXT     VARCHAR(1000),
        DURATION          FLOAT DEFAULT 1 NOT NULL,
        PARENT_LESSON_ID  BIGINT,
        TYPE_ID           BIGINT,
        EXTRA_TEXT        VARCHAR(1000),
        H_TEXT            BLOB SUB_TYPE 1 SEGMENT SIZE 4096 CHARACTER SET UTF8,
        H_TEXT2           BLOB SUB_TYPE 1 SEGMENT SIZE 4096 CHARACTER SET UTF8,
        VIRT_NUM          VARCHAR(40),
        STAGE_ID          BIGINT   
    );

    ALTER TABLE PTP_LESSONS ADD CONSTRAINT PK_PTP_LESSONS PRIMARY KEY (OBJ_ID);
    ALTER TABLE PTP_LESSONS ADD CONSTRAINT FK_PTP_LESSONS_1 FOREIGN KEY (PTP_ID) REFERENCES PTP (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER PTP_LESSONS_BI0 FOR PTP_LESSONS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      IF(NEW.OBJ_ID IS NULL) THEN
      BEGIN
          SELECT GEN * MULTIPLIER FROM GEN INTO :G;
          NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_PTP);
        END
    end
    ^

    CREATE OR ALTER TRIGGER PTP_LESSONS_BIU0 FOR PTP_LESSONS
    ACTIVE BEFORE INSERT OR UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'TYPE_ID' AND RDB$RELATION_NAME = 'PTP_LESSONS'}

  ALTER TABLE PTP_LESSONS ADD TYPE_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'EXTRA_TEXT' AND RDB$RELATION_NAME = 'PTP_LESSONS'}

  ALTER TABLE PTP_LESSONS ADD EXTRA_TEXT VARCHAR(1000);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'H_TEXT' AND RDB$RELATION_NAME = 'PTP_LESSONS'}

  ALTER TABLE PTP_LESSONS ADD H_TEXT BLOB SUB_TYPE 1 SEGMENT SIZE 4096 CHARACTER SET UTF8;
  ALTER TABLE PTP_LESSONS ADD H_TEXT2 BLOB SUB_TYPE 1 SEGMENT SIZE 4096 CHARACTER SET UTF8; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'VIRT_NUM' AND RDB$RELATION_NAME = 'PTP_LESSONS'}

  ALTER TABLE PTP_LESSONS ADD VIRT_NUM VARCHAR(40);
  ALTER TABLE PTP_LESSONS ADD STAGE_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

GRANT ALL ON PTP_LESSONS TO INISSOFT_ROLE;

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CONTROL_TYPE_ID' AND RDB$RELATION_NAME = 'CJ2_CONTROL_TYPE'}

    CREATE TABLE CJ2_CONTROL_TYPE (
        CONTROL_TYPE_ID    BIGINT NOT NULL,
        CONTROL_NAME       VARCHAR(100) NOT NULL,
        CONTROL_SHORTNAME  VARCHAR(20) NOT NULL,
        CONTROL_DESC       VARCHAR(400),
        DEFAULT_COST       FLOAT NOT NULL,
        MASTER_ID          BIGINT,
        TYPE_MASK          VARCHAR(100),
        "FILTER"           VARCHAR(200) CHARACTER SET UTF8 COLLATE UTF8,
        IS_DEL             SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE CJ2_CONTROL_TYPE ADD CONSTRAINT PK_CJ2_CONTROL_TYPE PRIMARY KEY (CONTROL_TYPE_ID);
    GRANT ALL ON CJ2_CONTROL_TYPE TO INISSOFT_ROLE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'TYPE_MASK' AND RDB$RELATION_NAME = 'CJ2_CONTROL_TYPE'}
    ALTER TABLE CJ2_CONTROL_TYPE ADD TYPE_MASK VARCHAR(100);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_DEL' AND RDB$RELATION_NAME = 'CJ2_CONTROL_TYPE'}
    ALTER TABLE CJ2_CONTROL_TYPE ADD IS_DEL SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'FILTER' AND RDB$RELATION_NAME = 'CJ2_CONTROL_TYPE'}

    ALTER TABLE CJ2_CONTROL_TYPE ADD "FILTER" VARCHAR(200) CHARACTER SET UTF8 COLLATE UTF8;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PTP_LESSON_CONTROLS'}

    CREATE TABLE PTP_LESSON_CONTROLS (
        OBJ_ID           BIGINT NOT NULL,
        DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY      TIMESTAMP NOT NULL,
        DATE_DEL         TIMESTAMP,
        LESSON_ID        BIGINT NOT NULL,
        CONTROL_TYPE_ID  BIGINT,
        USA_ID           BIGINT
    );

    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT PK_PTP_LESSON_CONTROLS PRIMARY KEY (OBJ_ID);
    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT FK_PTP_LESSON_CONTROLS_2 FOREIGN KEY (LESSON_ID) REFERENCES PTP_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT FK_PTP_LESSON_CONTROLS_3 FOREIGN KEY (CONTROL_TYPE_ID) REFERENCES CJ2_CONTROL_TYPE (CONTROL_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT FK_PTP_LESSON_CONTROLS_4 FOREIGN KEY (USA_ID) REFERENCES LISTVALS(LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER PTP_LESSON_CONTROLS_BI0 FOR PTP_LESSON_CONTROLS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      IF(NEW.OBJ_ID IS NULL) THEN
      BEGIN
          SELECT GEN * MULTIPLIER FROM GEN INTO :G;
          NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_PTP);
      END
    end
    ^

    CREATE OR ALTER TRIGGER PTP_LESSON_CONTROLS_BIU0 FOR PTP_LESSON_CONTROLS
    ACTIVE BEFORE INSERT OR UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'FK_PTP_LESSON_CONTROLS_1'}

    ALTER TABLE PTP_LESSON_CONTROLS DROP CONSTRAINT FK_PTP_LESSON_CONTROLS_1;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'FK_PTP_LESSON_CONTROLS_2'}

    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT FK_PTP_LESSON_CONTROLS_2 FOREIGN KEY (LESSON_ID) REFERENCES PTP_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'FK_PTP_LESSON_CONTROLS_3'}

    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT FK_PTP_LESSON_CONTROLS_3 FOREIGN KEY (CONTROL_TYPE_ID) REFERENCES CJ2_CONTROL_TYPE (CONTROL_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USA_ID' AND RDB$RELATION_NAME = 'PTP_LESSON_CONTROLS'}

    ALTER TABLE PTP_LESSON_CONTROLS ADD USA_ID BIGINT;
    COMMIT WORK;
    ALTER TABLE PTP_LESSON_CONTROLS ADD CONSTRAINT FK_PTP_LESSON_CONTROLS_4 FOREIGN KEY (USA_ID) REFERENCES LISTVALS(LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    COMMIT WORK;

{$ENDIF}

/* Классный журнал Gen.2 */

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    CREATE TABLE CJ2_JOURNAL (
        OBJ_ID         BIGINT NOT NULL,
        DATE_ADD       TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY    TIMESTAMP NOT NULL,
        DATE_DEL       TIMESTAMP,
        GRADE_ID       BIGINT NOT NULL,
        SUBJECT_ID     BIGINT,
        TEACHER_ID     BIGINT,
        JOURNAL_TYPE   SMALLINT NOT NULL,
        GRADE_TYPE_ID  BIGINT NOT NULL,
        STAGE_INDEX    BIGINT,
        STAGE_MASK     BIGINT DEFAULT 0,
        JOURNAL_NAME   VARCHAR(400) CHARACTER SET UTF8,
        REF_ID         BIGINT,
        YEAR_ID        BIGINT,
        WEEKS          INTEGER,
        HOURS          FLOAT,
        IS_ENABLED     SMALLINT DEFAULT 1 NOT NULL,
        RCM_MODE       SMALLINT DEFAULT 0 NOT NULL,
        DURATION       SMALLINT,
        DAYMASK        SMALLINT DEFAULT 0 NOT NULL,
        PERIOD_ID      BIGINT,
        EXT_INFO       VARCHAR(1000),
        VK_ENABLED     SMALLINT DEFAULT 0 NOT NULL,
        CHAT_ID        VARCHAR(400),
        ROOM_ID        BIGINT
    );

    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT PK_CJ2_JOURNAL PRIMARY KEY (OBJ_ID);
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_1 FOREIGN KEY (GRADE_ID) REFERENCES OBJECTS (OBJ_ID) ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_2 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_3 FOREIGN KEY (TEACHER_ID) REFERENCES OBJECTS (OBJ_ID) ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_4 FOREIGN KEY (STAGE_INDEX) REFERENCES LISTVALS (LISTVAL_ID) ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_5 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_6 FOREIGN KEY (PERIOD_ID) REFERENCES OBJECTS(OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_JOURNAL_BI0 FOR CJ2_JOURNAL
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      IF(NEW.OBJ_ID IS NULL) THEN
      BEGIN
          SELECT GEN * MULTIPLIER FROM GEN INTO :G;
          NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_MAIN_ID);
      END
    end
    ^

    CREATE OR ALTER TRIGGER CJ2_JOURNAL_BIU0 FOR CJ2_JOURNAL
    ACTIVE BEFORE INSERT OR UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    GRANT ALL ON CJ2_JOURNAL TO INISSOFT_ROLE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'JOURNAL_NAME' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD JOURNAL_NAME VARCHAR(1000) CHARACTER SET UTF8;  
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STAGE_MASK' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD STAGE_MASK BIGINT DEFAULT 0;  
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REF_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD REF_ID BIGINT;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STAGE_INDEX' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD STAGE_INDEX BIGINT; 
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_4 FOREIGN KEY (STAGE_INDEX) REFERENCES LISTVALS (LISTVAL_ID) ON UPDATE CASCADE;
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SUBJECT_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL' AND RDB$NULL_FLAG = 1}

  ALTER TABLE CJ2_JOURNAL ALTER SUBJECT_ID DROP NOT NULL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'YEAR_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD YEAR_ID BIGINT; 
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_5 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'WEEKS' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD WEEKS INTEGER; 
    ALTER TABLE CJ2_JOURNAL ADD HOURS INTEGER; 
    ALTER TABLE CJ2_JOURNAL ADD IS_ENABLED SMALLINT DEFAULT 1 NOT NULL; 

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'RCM_MODE' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD RCM_MODE SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'DURATION' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD DURATION SMALLINT;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'DAYMASK' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD DAYMASK SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'PERIOD_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD PERIOD_ID BIGINT;
    ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_6 FOREIGN KEY (PERIOD_ID) REFERENCES OBJECTS(OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'EXT_INFO' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD EXT_INFO VARCHAR(1000);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'VK_ENABLED' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD VK_ENABLED SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE CJ2_JOURNAL ADD CHAT_ID VARCHAR(400) CHARACTER SET UTF8;  
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'CHAT_ID' AND F.RDB$RELATION_NAME = 'CJ2_JOURNAL' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 40}

    ALTER TABLE CJ2_JOURNAL ALTER COLUMN CHAT_ID TYPE VARCHAR(400);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ROOM_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}

    ALTER TABLE CJ2_JOURNAL ADD ROOM_ID BIGINT; 
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_IDX1'}
    CREATE INDEX CJ2_JOURNAL_IDX1 ON CJ2_JOURNAL (JOURNAL_TYPE, STAGE_INDEX);
    COMMIT WORK;
{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS RF JOIN RDB$FIELDS F ON F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE WHERE RF.RDB$RELATION_NAME = 'CJ2_JOURNAL' AND RF.RDB$FIELD_NAME = 'JOURNAL_NAME' AND F.RDB$CHARACTER_LENGTH = 1000}
  ALTER TABLE CJ2_JOURNAL ADD JOURNAL_NAME1 VARCHAR(400);
  COMMIT WORK;
  UPDATE CJ2_JOURNAL SET JOURNAL_NAME1 = JOURNAL_NAME;
  COMMIT WORK;
  ALTER TABLE CJ2_JOURNAL DROP JOURNAL_NAME;
  COMMIT WORK;
  ALTER TABLE CJ2_JOURNAL ALTER JOURNAL_NAME1 TO JOURNAL_NAME;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_IDX2'}
  CREATE INDEX CJ2_JOURNAL_IDX2 ON CJ2_JOURNAL (STAGE_INDEX, JOURNAL_NAME);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_IDX3'}
  CREATE INDEX CJ2_JOURNAL_IDX3 ON CJ2_JOURNAL (REF_ID);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CHAT_TIMEMARK' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}
  ALTER TABLE CJ2_JOURNAL ADD CHAT_TIMEMARK TIMESTAMP;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_PTP'}

    CREATE TABLE CJ2_JOURNAL_PTP (
        OBJ_ID          BIGINT NOT NULL,
        DATE_ADD        TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY     TIMESTAMP NOT NULL,
        DATE_DEL        TIMESTAMP,
        CJ_ID           BIGINT NOT NULL,
        PTP_ID          BIGINT NOT NULL,
        APPROVAL_STATE  SMALLINT DEFAULT 0 NOT NULL,
        APP_ORDER_DATE  DATE,
        APP_ORDER_NUM   VARCHAR(100)
    );

    ALTER TABLE CJ2_JOURNAL_PTP ADD CONSTRAINT PK_CJ2_JOURNAL_PTP PRIMARY KEY (OBJ_ID);
    ALTER TABLE CJ2_JOURNAL_PTP ADD CONSTRAINT FK_CJ2_JOURNAL_PTP_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL_PTP ADD CONSTRAINT FK_CJ2_JOURNAL_PTP_2 FOREIGN KEY (PTP_ID) REFERENCES PTP (OBJ_ID) ON UPDATE CASCADE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_JOURNAL_PTP_BI0 FOR CJ2_JOURNAL_PTP
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      IF(NEW.OBJ_ID IS NULL) THEN
      BEGIN
          SELECT GEN * MULTIPLIER FROM GEN INTO :G;
          NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_MAIN_ID);
      END
    end
    ^

    CREATE OR ALTER TRIGGER CJ2_JOURNAL_PTP_BIU0 FOR CJ2_JOURNAL_PTP
    ACTIVE BEFORE INSERT OR UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

  GRANT ALL ON CJ2_JOURNAL_PTP TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_MS_LESSONS'}

  CREATE SEQUENCE GEN_CJ2_MS_ID;
  COMMIT WORK;

  CREATE TABLE CJ2_MS_LESSONS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    CJ_ID        BIGINT NOT NULL,
    SEQ_INDEX    SMALLINT NOT NULL,
    LESSON_DATE  DATE NOT NULL,
    LESSON_NUM   INTEGER NOT NULL,
    LESSON_TIME  TIME
  );

  ALTER TABLE CJ2_MS_LESSONS ADD CONSTRAINT PK_CJ2_MS_LESSONS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_MS_LESSONS ADD CONSTRAINT FK_CJ2_MS_LESSONS_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE; 
  CREATE INDEX CJ2_MS_LESSONS_IDX1 ON CJ2_MS_LESSONS (DATE_MODIFY);
  CREATE INDEX CJ2_MS_LESSONS_IDX2 ON CJ2_MS_LESSONS (CJ_ID,LESSON_DATE,LESSON_NUM);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_MS_LESSONS_BI0 FOR CJ2_MS_LESSONS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_CJ2_MS_ID);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_MS_LESSONS_BU0 FOR CJ2_MS_LESSONS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_MS_LESSONS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DATE_ADD' AND RDB$RELATION_NAME = 'CJ2_MS_LESSONS'}
  ALTER TABLE CJ2_MS_LESSONS ADD DATE_ADD TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LESSON_TIME' AND RDB$RELATION_NAME = 'CJ2_MS_LESSONS'}
  ALTER TABLE CJ2_MS_LESSONS ADD LESSON_TIME TIME;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'FK_CJ2_MS_LESSONS_1'}
  ALTER TABLE CJ2_MS_LESSONS ADD CONSTRAINT FK_CJ2_MS_LESSONS_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE; 
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'CJ2_MS_LESSONS_IDX2'}
  CREATE INDEX CJ2_MS_LESSONS_IDX2 ON CJ2_MS_LESSONS (CJ_ID,LESSON_DATE,LESSON_NUM);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}

    CREATE TABLE CJ2_JOURNAL_LESSONS (
        OBJ_ID        BIGINT NOT NULL,
        DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY   TIMESTAMP NOT NULL,
        DATE_DEL      TIMESTAMP,
        CJ_ID         BIGINT NOT NULL,
        LESSON_DATE   DATE NOT NULL,
        LESSON_NUM    INTEGER NOT NULL,
        TEACHER_ID    BIGINT,
        LESSON_THEME  VARCHAR(1000),
        IS_COMPLETED  SMALLINT DEFAULT 0 NOT NULL,
        LESSON_PTP_ID  BIGINT,
        LESSON_HOURS   FLOAT DEFAULT 1 NOT NULL,
        LESSON_TYPE_ID BIGINT,
        LESSON_HOMEWORK  VARCHAR(1000),
        LESSON_EXTRA     VARCHAR(2000),
        IS_PUBLISHED     SMALLINT DEFAULT 0 NOT NULL,
        REPL_QUALITY     SMALLINT,
        INST_ID          VARCHAR(40),
        INST_MODIFIED    SMALLINT DEFAULT 0 NOT NULL,
        DE_ID            VARCHAR(400),
        IS_ONLINE        SMALLINT DEFAULT 0 NOT NULL,
        INST_LINK        VARCHAR(400),
        INST_STATUS      SMALLINT DEFAULT 0 NOT NULL,  
        MS_ID            BIGINT,
        LESSON_TIME      TIME
    );
                                                                                
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD CONSTRAINT PK_CJ2_JOURNAL_LESSONS PRIMARY KEY (OBJ_ID);

    ALTER TABLE CJ2_JOURNAL_LESSONS ADD CONSTRAINT FK_CJ2_JOURNAL_LESSONS_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD CONSTRAINT FK_CJ2_JOURNAL_LESSONS_2 FOREIGN KEY (TEACHER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD CONSTRAINT FK_CJ2_JOURNAL_LESSONS_3 FOREIGN KEY (MS_ID) REFERENCES CJ2_MS_LESSONS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX1 ON CJ2_JOURNAL_LESSONS (CJ_ID,LESSON_DATE);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX2 ON CJ2_JOURNAL_LESSONS (OBJ_ID,LESSON_DATE);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX3 ON CJ2_JOURNAL_LESSONS (CJ_ID, TEACHER_ID, LESSON_DATE);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX4 ON CJ2_JOURNAL_LESSONS (DATE_MODIFY);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX5 ON CJ2_JOURNAL_LESSONS (CJ_ID, DATE_MODIFY);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX6 ON CJ2_JOURNAL_LESSONS (CJ_ID, DATE_DEL);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX7 ON CJ2_JOURNAL_LESSONS (INST_MODIFIED);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX8 ON CJ2_JOURNAL_LESSONS (INST_ID,INST_MODIFIED);

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_JOURNAL_LESSONS_BI0 FOR CJ2_JOURNAL_LESSONS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      IF(NEW.OBJ_ID IS NULL) THEN
      BEGIN
          SELECT GEN * MULTIPLIER FROM GEN INTO :G;
          NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_MAIN_ID);
      END
    end
    ^

    CREATE OR ALTER TRIGGER CJ2_JOURNAL_LESSONS_BIU0 FOR CJ2_JOURNAL_LESSONS
    ACTIVE BEFORE INSERT OR UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

  GRANT ALL ON CJ2_JOURNAL_LESSONS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LESSON_PTP_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD LESSON_PTP_ID BIGINT;
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD LESSON_HOURS FLOAT DEFAULT 1 NOT NULL;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LESSON_TYPE_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD LESSON_TYPE_ID BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LESSON_HOMEWORK' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD LESSON_HOMEWORK VARCHAR(1000);
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD LESSON_EXTRA VARCHAR(2000);
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD IS_PUBLISHED SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REPL_QUALITY' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD REPL_QUALITY SMALLINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'INST_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD INST_ID VARCHAR(40);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'INST_MODIFIED' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
    ALTER TABLE CJ2_JOURNAL_LESSONS ADD INST_MODIFIED SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX7 ON CJ2_JOURNAL_LESSONS (INST_MODIFIED);
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX8 ON CJ2_JOURNAL_LESSONS (INST_ID,INST_MODIFIED);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LESSON_TIME' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
  ALTER TABLE CJ2_JOURNAL_LESSONS ADD LESSON_TIME TIME;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_LESSONS_IDX1'}
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX1 ON CJ2_JOURNAL_LESSONS (CJ_ID,LESSON_DATE);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_LESSONS_IDX2'}
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX2 ON CJ2_JOURNAL_LESSONS (OBJ_ID,LESSON_DATE);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_LESSONS_IDX3'}
    CREATE INDEX CJ2_JOURNAL_LESSONS_IDX3 ON CJ2_JOURNAL_LESSONS (CJ_ID, TEACHER_ID, LESSON_DATE);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_LESSONS_IDX4'}
  CREATE INDEX CJ2_JOURNAL_LESSONS_IDX4 ON CJ2_JOURNAL_LESSONS (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_LESSONS_IDX5'}
  CREATE INDEX CJ2_JOURNAL_LESSONS_IDX5 ON CJ2_JOURNAL_LESSONS (CJ_ID, DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_LESSONS_IDX6'}
  CREATE INDEX CJ2_JOURNAL_LESSONS_IDX6 ON CJ2_JOURNAL_LESSONS (CJ_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'MS_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}
  ALTER TABLE CJ2_JOURNAL_LESSONS ADD MS_ID BIGINT;
  COMMIT WORK;
  ALTER TABLE CJ2_JOURNAL_LESSONS ADD CONSTRAINT FK_CJ2_JOURNAL_LESSONS_3 FOREIGN KEY (MS_ID) REFERENCES CJ2_MS_LESSONS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_BLOB'}

  CREATE TABLE CJ2_BLOB (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LESSON_ID    BIGINT NOT NULL,
    FILE_TYPE    SMALLINT DEFAULT 0 NOT NULL,
    FILE_NAME    VARCHAR(4000) NOT NULL
  );

  ALTER TABLE CJ2_BLOB ADD CONSTRAINT PK_CJ2_BLOB PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_BLOB ADD CONSTRAINT FK_CJ2_BLOB_1 FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX CJ2_BLOB_IDX1 ON CJ2_BLOB (DATE_MODIFY);

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_BLOB_BI FOR CJ2_BLOB
  ACTIVE BEFORE INSERT POSITION 0
  AS
  DECLARE VARIABLE G BIGINT;
  BEGIN
    SELECT GEN * MULTIPLIER FROM GEN INTO :G;
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_BLOB_ID,1) + :G;
  END
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_BLOB TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_BLOB_IDX1'}
  CREATE INDEX CJ2_BLOB_IDX1 ON CJ2_BLOB (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'MARK_TYPE_ID' AND RDB$RELATION_NAME = 'CJ2_MARK_TYPE'}

    CREATE TABLE CJ2_MARK_TYPE (
        MARK_TYPE_ID    BIGINT NOT NULL,
        PARENT_ID       BIGINT,
        MARK_NAME       VARCHAR(100) NOT NULL,
        MARK_SHORTNAME  VARCHAR(10) NOT NULL,
        MARK_COST       FLOAT NOT NULL,
        MARK_SHORTCUT   CHAR(1),
        TYPE_MASK       VARCHAR(100),
        IS_DEL          SMALLINT DEFAULT 0 NOT NULL,
        FINAL_ID        BIGINT,
        MARK_SCALE      FLOAT DEFAULT 1
    );                                                                                

    ALTER TABLE CJ2_MARK_TYPE ADD CONSTRAINT PK_CJ2_MARK_TYPE_1 PRIMARY KEY (MARK_TYPE_ID);
    GRANT ALL ON CJ2_MARK_TYPE TO INISSOFT_ROLE;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'TYPE_MASK' AND RDB$RELATION_NAME = 'CJ2_MARK_TYPE'}
    ALTER TABLE CJ2_MARK_TYPE ADD TYPE_MASK VARCHAR(100);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_DEL' AND RDB$RELATION_NAME = 'CJ2_MARK_TYPE'}
    ALTER TABLE CJ2_MARK_TYPE ADD IS_DEL SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'FINAL_ID' AND RDB$RELATION_NAME = 'CJ2_MARK_TYPE'}
    ALTER TABLE CJ2_MARK_TYPE ADD FINAL_ID BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'MARK_SCALE' AND RDB$RELATION_NAME = 'CJ2_MARK_TYPE'}
    ALTER TABLE CJ2_MARK_TYPE ADD MARK_SCALE FLOAT DEFAULT 1;
    COMMIT WORK;
{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS RF
  JOIN RDB$FIELDS F ON F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE AND F.RDB$FIELD_TYPE = 8
  WHERE RF.RDB$FIELD_NAME = 'MARK_COST' AND RF.RDB$RELATION_NAME = 'CJ2_MARK_TYPE'}

    ALTER TABLE CJ2_MARK_TYPE ADD MARK_COST1 FLOAT;
    COMMIT WORK;
    UPDATE CJ2_MARK_TYPE SET MARK_COST1 = MARK_COST;
    COMMIT WORK;

    ALTER TABLE CJ2_MARK_TYPE DROP MARK_COST;
    COMMIT WORK;
    ALTER TABLE CJ2_MARK_TYPE ALTER MARK_COST1 TO MARK_COST;
    ALTER TABLE CJ2_MARK_TYPE ALTER MARK_COST SET NOT NULL;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ASST_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL'}
  ALTER TABLE CJ2_JOURNAL ADD ASST_ID BIGINT;
  ALTER TABLE CJ2_JOURNAL ADD CONSTRAINT FK_CJ2_JOURNAL_7 FOREIGN KEY (ASST_ID) REFERENCES CJ2_MARK_TYPE (MARK_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_ASSESSMENT'}

  CREATE GENERATOR CJ2_ASST_GEN;

  CREATE TABLE CJ2_ASSESSMENT (
    OBJ_ID       BIGINT NOT NULL,
    YEAR_ID      BIGINT NOT NULL,
    STAGE_ID     BIGINT,
    GRADE_ID     BIGINT,
    SUBJECT_ID   BIGINT,
    ASST_ID      BIGINT NOT NULL,
    USER_ID      BIGINT,
    USER_DEL_ID  BIGINT,
    DATE_ADD     TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP
  );

  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT CJ2_ASSESSMENT_PK PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_1 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_2 FOREIGN KEY (STAGE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_3 FOREIGN KEY (GRADE_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_4 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_5 FOREIGN KEY (ASST_ID) REFERENCES CJ2_MARK_TYPE (MARK_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_6 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE CJ2_ASSESSMENT ADD CONSTRAINT FK_CJ2_ASSESSMENT_7 FOREIGN KEY (USER_DEL_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER CJ2_ASSESSMENT_BI0 FOR CJ2_ASSESSMENT
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR CJ2_ASST_GEN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_ASSESSMENT_BU0 FOR CJ2_ASSESSMENT
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_ASSESSMENT TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CONTROL_ID' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}

    CREATE TABLE CJ2_CONTROL (
        CONTROL_ID       BIGINT NOT NULL,
        DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL         TIMESTAMP,
        LESSON_ID        BIGINT NOT NULL,
        CONTROL_TYPE_ID  BIGINT NOT NULL,
        CONTROL_COST     FLOAT DEFAULT 0 NOT NULL,
        HINT_TEXT        VARCHAR(1000),
        EXT_ID           VARCHAR(100),
        EXT_ASSIGNED     VARCHAR(40)    
    );

    /* TEST_ID можно добавлять только после UT_EXAM_DATES */

    ALTER TABLE CJ2_CONTROL ADD CONSTRAINT PK_CJ2_CONTROL PRIMARY KEY (CONTROL_ID);
    ALTER TABLE CJ2_CONTROL ADD CONSTRAINT CJ2_CONTROL_CONTROL_TYPE FOREIGN KEY (CONTROL_TYPE_ID) REFERENCES CJ2_CONTROL_TYPE (CONTROL_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_CONTROL ADD CONSTRAINT CJ2_CONTROL_LESSON_ID FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    CREATE INDEX CJ2_CONTROL_IDX1 ON CJ2_CONTROL (DATE_MODIFY);
    CREATE INDEX CJ2_CONTROL_IDX2 ON CJ2_CONTROL (LESSON_ID, DATE_MODIFY);
    CREATE INDEX CJ2_CONTROL_IDX3 ON CJ2_CONTROL (LESSON_ID, DATE_DEL);
    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_CONTROL_BI FOR CJ2_CONTROL
    ACTIVE BEFORE INSERT POSITION 0
    AS
    DECLARE VARIABLE G BIGINT;
    BEGIN
      SELECT GEN * MULTIPLIER FROM GEN INTO :G;
      IF (NEW.CONTROL_ID IS NULL) THEN NEW.CONTROL_ID = GEN_ID(GEN_CJ_MAIN_ID,1) + :G;
    END
    ^

    CREATE OR ALTER TRIGGER CJ2_CONTROL_BU FOR CJ2_CONTROL
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    BEGIN
        NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    END
    ^

    SET TERM ; ^

    GRANT ALL ON CJ2_CONTROL TO INISSOFT_ROLE;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'HINT_TEXT' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}

    ALTER TABLE CJ2_CONTROL ADD HINT_TEXT VARCHAR(1000);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'EXT_ID' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}

    ALTER TABLE CJ2_CONTROL ADD EXT_ID VARCHAR(100);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'EXT_ASSIGNED' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}

    ALTER TABLE CJ2_CONTROL ADD EXT_ASSIGNED VARCHAR(40);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_CONTROL_IDX1'}
  CREATE INDEX CJ2_CONTROL_IDX1 ON CJ2_CONTROL (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_CONTROL_IDX2'}
  CREATE INDEX CJ2_CONTROL_IDX2 ON CJ2_CONTROL (LESSON_ID, DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_CONTROL_IDX3'}
  CREATE INDEX CJ2_CONTROL_IDX3 ON CJ2_CONTROL (LESSON_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'MARK_ID' AND RDB$RELATION_NAME = 'CJ2_MARK'}

    CREATE TABLE CJ2_MARK (
        MARK_ID        BIGINT NOT NULL,
        DATE_ADD       TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL       TIMESTAMP,
        CONTROL_ID     BIGINT,
        FINAL_ID       BIGINT,
        STUDENT_ID     BIGINT NOT NULL,
        MARK_TYPE_ID   BIGINT NOT NULL,
        MARK_DATE      DATE NOT NULL,
        IS_USED        SMALLINT DEFAULT 0 NOT NULL,
        USER_ID        BIGINT,
        COMMENTS_TEXT  VARCHAR(1000),
        USER_DEL       BIGINT,
        REASON_ID      BIGINT
    );

    ALTER TABLE CJ2_MARK ADD CONSTRAINT PK_CJ2_MARK PRIMARY KEY (MARK_ID);
    ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_CONTROL_ID FOREIGN KEY (CONTROL_ID) REFERENCES CJ2_CONTROL (CONTROL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_MARK_TYPE_ID FOREIGN KEY (MARK_TYPE_ID) REFERENCES CJ2_MARK_TYPE (MARK_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_STUDENT_ID FOREIGN KEY (STUDENT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_USER_ID FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_USER_DEL FOREIGN KEY (USER_DEL) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    CREATE INDEX CJ2_MARK_IDX1 ON CJ2_MARK (DATE_MODIFY);
    CREATE INDEX CJ2_MARK_IDX2 ON CJ2_MARK (CONTROL_ID, DATE_MODIFY);
    CREATE INDEX CJ2_MARK_IDX3 ON CJ2_MARK (CONTROL_ID, DATE_DEL);
    CREATE INDEX CJ2_MARK_IDX4 ON CJ2_MARK (CONTROL_ID, STUDENT_ID);

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_MARK_BI FOR CJ2_MARK
    ACTIVE BEFORE INSERT POSITION 0
    AS
    DECLARE VARIABLE G BIGINT;
    BEGIN
      SELECT GEN * MULTIPLIER FROM GEN INTO :G;
      IF (NEW.MARK_ID IS NULL) THEN NEW.MARK_ID = GEN_ID(GEN_CJ_MAIN_ID,1) + :G;
    END
    ^

    CREATE OR ALTER TRIGGER CJ2_MARK_BU FOR CJ2_MARK
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    BEGIN
        NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    END
    ^

    SET TERM ; ^

    GRANT ALL ON CJ2_MARK TO INISSOFT_ROLE;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USER_DEL' AND RDB$RELATION_NAME = 'CJ2_MARK'}

    ALTER TABLE CJ2_MARK ADD USER_DEL BIGINT;  
    COMMIT WORK;
    ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_USER_DEL FOREIGN KEY (USER_DEL) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REASON_ID' AND RDB$RELATION_NAME = 'CJ2_MARK'}

    ALTER TABLE CJ2_MARK ADD REASON_ID BIGINT;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_MARK_IDX1'}
  CREATE INDEX CJ2_MARK_IDX1 ON CJ2_MARK (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_MARK_IDX2'}
  CREATE INDEX CJ2_MARK_IDX2 ON CJ2_MARK (CONTROL_ID, DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_MARK_IDX3'}
  CREATE INDEX CJ2_MARK_IDX3 ON CJ2_MARK (CONTROL_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_MARK_IDX4'}
  CREATE INDEX CJ2_MARK_IDX4 ON CJ2_MARK (CONTROL_ID, STUDENT_ID);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CONTROL_COST' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}
  ALTER TABLE CJ2_CONTROL ADD CONTROL_COST FLOAT DEFAULT 0 NOT NULL;  
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'MARK_SYSTEM_ID' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}
  ALTER TABLE CJ2_CONTROL ADD MARK_SYSTEM_ID BIGINT NOT NULL;
  ALTER TABLE CJ2_CONTROL ADD CONSTRAINT FK_CJ2_CONTROL_MARK_SYSTEM FOREIGN KEY (MARK_SYSTEM_ID) REFERENCES CJ2_MARK_TYPE (MARK_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK; 
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_COMPLETED' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}
  ALTER TABLE CJ2_CONTROL ADD IS_COMPLETED SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_REPL_PLAN'}

    CREATE TABLE CJ2_REPL_PLAN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        PERSON_ID    BIGINT NOT NULL,
        REASON_ID    BIGINT,
        DATE_FROM    DATE NOT NULL,
        DATE_TO      DATE
    );

    ALTER TABLE CJ2_REPL_PLAN ADD CONSTRAINT PK_CJ2_REPL_PLAN PRIMARY KEY (OBJ_ID);
    ALTER TABLE CJ2_REPL_PLAN ADD CONSTRAINT FK_CJ2_REPL_PLAN_PERSON_ID FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_REPL_PLAN ADD CONSTRAINT FK_CJ2_REPL_PLAN_REASON_ID FOREIGN KEY (REASON_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_REPL_PLAN_BI0 FOR CJ2_REPL_PLAN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    declare variable G bigint;
    begin
      SELECT GEN * MULTIPLIER FROM GEN INTO :G;
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_CJ_MAIN_ID, 1) + :G;
    end
    ^

    CREATE OR ALTER TRIGGER CJ2_REPL_PLAN_BU0 FOR CJ2_REPL_PLAN
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    GRANT ALL ON CJ2_REPL_PLAN TO INISSOFT_ROLE;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}

    CREATE TABLE CJ2_REPL_PROCESS (
        OBJ_ID          BIGINT NOT NULL,
        DATE_ADD        TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL        TIMESTAMP,
        REPL_DATE       DATE NOT NULL,
        PLAN_ID         BIGINT,
        PERSON_ID       BIGINT,
        REPL_PERSON_ID  BIGINT,
        CJ_ID           BIGINT,
        REPL_CJ_ID      BIGINT,
        LESSON_NUM      SMALLINT,
        IS_APPROVED     SMALLINT DEFAULT 0 NOT NULL,
        ORDER_DATE      DATE,
        ORDER_NUM       VARCHAR(100),
        ROOM_ID         BIGINT,
        LESSON_TIME     TIME
    );

    ALTER TABLE CJ2_REPL_PROCESS ADD CONSTRAINT PK_CJ2_REPL_PROCESS PRIMARY KEY (OBJ_ID);
    ALTER TABLE CJ2_REPL_PROCESS ADD CONSTRAINT FK_CJ2_REPL_PROCESS_1 FOREIGN KEY (PLAN_ID) REFERENCES CJ2_REPL_PLAN (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    ALTER TABLE CJ2_REPL_PROCESS ADD CONSTRAINT FK_CJ2_REPL_PROCESS_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE CJ2_REPL_PROCESS ADD CONSTRAINT FK_CJ2_REPL_PROCESS_3 FOREIGN KEY (REPL_PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    CREATE INDEX CJ2_REPL_PROCESS_IDX1 ON CJ2_REPL_PROCESS (DATE_MODIFY);

    GRANT ALL ON CJ2_REPL_PROCESS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CJ2_REPL_PROCESS_BI0 FOR CJ2_REPL_PROCESS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_CJ_MAIN_ID, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER CJ2_REPL_PROCESS_BU0 FOR CJ2_REPL_PROCESS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

{$ENDIF}

{$IFEXISTS SELECT RDB$NULL_FLAG	FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'PERSON_ID' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS' AND RDB$NULL_FLAG = 1}
  ALTER TABLE CJ2_REPL_PROCESS ALTER PERSON_ID DROP NOT NULL;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REPL_CJ_ID' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}
  ALTER TABLE CJ2_REPL_PROCESS ADD REPL_CJ_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LESSON_NUM' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}
  ALTER TABLE CJ2_REPL_PROCESS ADD LESSON_NUM SMALLINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_APPROVED' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}
  ALTER TABLE CJ2_REPL_PROCESS ADD IS_APPROVED SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ORDER_DATE' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}
  ALTER TABLE CJ2_REPL_PROCESS ADD ORDER_DATE DATE;
  ALTER TABLE CJ2_REPL_PROCESS ADD ORDER_NUM VARCHAR(100);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ROOM_ID' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}
  ALTER TABLE CJ2_REPL_PROCESS ADD ROOM_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LESSON_TIME' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS'}
  ALTER TABLE CJ2_REPL_PROCESS ADD LESSON_TIME TIME;
  COMMIT WORK;
{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REPL_PERSON_ID' AND RDB$RELATION_NAME = 'CJ2_REPL_PROCESS' AND RDB$NULL_FLAG IS NOT NULL}
  UPDATE RDB$RELATION_FIELDS SET RDB$NULL_FLAG = NULL WHERE (RDB$FIELD_NAME = 'REPL_PERSON_ID') AND (RDB$RELATION_NAME = 'CJ2_REPL_PROCESS');
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_REPL_PROCESS_IDX1'}
  CREATE INDEX CJ2_REPL_PROCESS_IDX1 ON CJ2_REPL_PROCESS (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'GEN_CJ_ACCESS'}

  CREATE GENERATOR GEN_CJ_ACCESS;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_USERS'}

  CREATE TABLE CJ2_JOURNAL_USERS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    CJ_ID        BIGINT NOT NULL,
    USER_ID      BIGINT,
    ACCESS       SMALLINT DEFAULT 0 NOT NULL,
    ADDED_BY     BIGINT,
    DELETED_BY   BIGINT
  );

  ALTER TABLE CJ2_JOURNAL_USERS ADD CONSTRAINT PK_CJ2_JOURNAL_USERS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_JOURNAL_USERS ADD CONSTRAINT FK_CJ2_JOURNAL_USERS_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_JOURNAL_USERS ADD CONSTRAINT FK_CJ2_JOURNAL_USERS_2 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_USERS_BI1 FOR CJ2_JOURNAL_USERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  declare variable G bigint;
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
        SELECT GEN * MULTIPLIER FROM GEN INTO :G;
        NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_ACCESS);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_USERS_BIU0 FOR CJ2_JOURNAL_USERS
  ACTIVE BEFORE INSERT OR UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_JOURNAL_USERS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_AUTOUSERS'}

  CREATE TABLE CJ2_JOURNAL_AUTOUSERS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    CJ_ID        BIGINT NOT NULL,
    USER_ID      BIGINT,
    ACCESS       SMALLINT DEFAULT 0 NOT NULL
  );

  ALTER TABLE CJ2_JOURNAL_AUTOUSERS ADD CONSTRAINT PK_CJ2_JOURNAL_AUTOUSERS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_JOURNAL_AUTOUSERS ADD CONSTRAINT FK_CJ2_JOURNAL_AUTOUSERS_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_JOURNAL_AUTOUSERS ADD CONSTRAINT FK_CJ2_JOURNAL_AUTOUSERS_2 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_AUTOUSERS_BI1 FOR CJ2_JOURNAL_AUTOUSERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  declare variable G bigint;
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      SELECT GEN * MULTIPLIER FROM GEN INTO :G;
      NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_ACCESS);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_AUTOUSERS_BIU0 FOR CJ2_JOURNAL_AUTOUSERS
  ACTIVE BEFORE INSERT OR UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_JOURNAL_AUTOUSERS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'CJ2_JOURNAL_USERS_BI0'}

  DROP TRIGGER CJ2_JOURNAL_USERS_BI0;
  COMMIT WORK;  

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_USERS_BI1 FOR CJ2_JOURNAL_USERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  declare variable G bigint;
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
        SELECT GEN * MULTIPLIER FROM GEN INTO :G;
        NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_ACCESS);
    END
  end
  ^

  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'CJ2_JOURNAL_AUTOUSERS_BI0'}

  DROP TRIGGER CJ2_JOURNAL_AUTOUSERS_BI0;
  COMMIT WORK;  

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_AUTOUSERS_BI1 FOR CJ2_JOURNAL_AUTOUSERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  declare variable G bigint;
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      SELECT GEN * MULTIPLIER FROM GEN INTO :G;
      NEW.OBJ_ID = :G + (NEXT VALUE FOR GEN_CJ_ACCESS);
    END
  end
  ^

  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

/* Тестирование на базе DG */
{$IFNOTEXISTS SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'UT_BASEGEN'}

    CREATE SEQUENCE UT_BASEGEN;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'EXPERT_ID' AND RDB$RELATION_NAME = 'UT_EXPERTS'}

    CREATE TABLE UT_EXPERTS (
        EXPERT_ID     BIGINT NOT NULL,
        DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL      TIMESTAMP,
        TEACHER_ID    BIGINT,
        LAST_NAME     VARCHAR(400) NOT NULL,
        FIRST_NAME    VARCHAR(400) NOT NULL,
        MIDDLE_NAME   VARCHAR(400),
        BIRTHDATE     DATE,
        JOB_TITLE     VARCHAR(400),
        ORGANIZATION  VARCHAR(400),
        AREA_ID   BIGINT,
        IS_ACTIVE INTEGER DEFAULT 1 NOT NULL,
        USER_NAME VARCHAR(100),
        PWD VARCHAR(200),
        ORG_ID BIGINT
    );

    ALTER TABLE UT_EXPERTS ADD CONSTRAINT PK_UT_EXPERTS PRIMARY KEY (EXPERT_ID);
    ALTER TABLE UT_EXPERTS ADD CONSTRAINT FK_UT_EXPERTS_2 FOREIGN KEY (AREA_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXPERTS_BI0 FOR UT_EXPERTS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.EXPERT_ID IS NULL) THEN
        NEW.EXPERT_ID = GEN_ID(UT_BASEGEN,1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    CREATE OR ALTER TRIGGER UT_EXPERTS_BU0 FOR UT_EXPERTS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    GRANT ALL ON UT_EXPERTS TO INISSOFT_ROLE;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'FIRST_NAME' AND F.RDB$RELATION_NAME = 'UT_EXPERTS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 40}

    ALTER TABLE UT_EXPERTS ALTER COLUMN FIRST_NAME TYPE VARCHAR(400);
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'PWD' AND F.RDB$RELATION_NAME = 'UT_EXPERTS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 100}
  ALTER TABLE UT_EXPERTS ALTER COLUMN PWD TYPE VARCHAR(200);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_DAY_TYPES'}

    CREATE TABLE UT_EXAM_DAY_TYPES (
        OBJ_ID    INTEGER NOT NULL,
        OBJ_NAME  VARCHAR(1000),
        IS_DEL    SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_DAY_TYPES ADD CONSTRAINT PK_UT_EXAM_DAY_TYPES PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXAM_DAY_TYPES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (0, 'Вне ГИА', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (100, 'Олимпиада', 0) MATCHING (OBJ_ID);    
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (10, 'Пробный экзамен', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (20, 'Досрочный этап основной день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (30, 'Досрочный этап резервный день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (40, 'Основной этап основной день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (50, 'Основной этап резервный день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (60, 'Дополнительный этап основной день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (70, 'Дополнительный этап резервный день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (90, 'Демонстрационный экзамен', 0) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_DEL' AND RDB$RELATION_NAME = 'UT_EXAM_DAY_TYPES'}	

    ALTER TABLE UT_EXAM_DAY_TYPES ADD IS_DEL SMALLINT DEFAULT 0 NOT NULL;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM UT_EXAM_DAY_TYPES WHERE OBJ_ID = 0}

    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (0, 'Вне ГИА', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (100, 'Олимпиада', 0) MATCHING (OBJ_ID);    
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (10, 'Пробный экзамен', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (20, 'Досрочный этап основной день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (30, 'Досрочный этап резервный день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (40, 'Основной этап основной день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (50, 'Основной этап резервный день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (60, 'Дополнительный этап основной день', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (70, 'Дополнительный этап резервный день', 0) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM UT_EXAM_DAY_TYPES WHERE OBJ_ID = 90}

    UPDATE OR INSERT INTO UT_EXAM_DAY_TYPES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (90, 'Демонстрационный экзамен', 0) MATCHING (OBJ_ID);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_STATES'}	

    CREATE TABLE UT_EXAM_STATES (
        OBJ_ID    INTEGER NOT NULL,
        OBJ_NAME  VARCHAR(1000),
        IS_DEL    SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_STATES ADD CONSTRAINT PK_UT_EXAM_STATES PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXAM_STATES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (0, 'Черновик', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (100, 'Планирование участников', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (200, 'Планирование размещения', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (300, 'Планирование персонала', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (500, 'Подготовка материалов', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (600, 'Проведение', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (700, 'Сбор результатов', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (800, 'Обработка результатов', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (1000, 'Завершен', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (1001, 'Отменен', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (900, 'Экспертная проверка', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (550, 'Готовность к проведению', 0) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_DEL' AND RDB$RELATION_NAME = 'UT_EXAM_STATES'}	

    ALTER TABLE UT_EXAM_STATES ADD IS_DEL SMALLINT DEFAULT 0 NOT NULL;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (900, 'Экспертная проверка', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (550, 'Готовность к проведению', 0) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_METHODS'}	

    CREATE TABLE UT_EXAM_METHODS (
        OBJ_ID    INTEGER NOT NULL,
        OBJ_NAME  VARCHAR(1000)
    );

    ALTER TABLE UT_EXAM_METHODS ADD CONSTRAINT PK_UT_EXAM_METHODS PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXAM_METHODS TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (0, 'Электронное тестирование') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (1, 'Электронное аудио-тестирование') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (2, 'Бумажное тестирование') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (3, 'Очное тестирование') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (4, 'Олимпиада') MATCHING (OBJ_ID);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM UT_EXAM_METHODS WHERE OBJ_ID = 4}

    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (4, 'Олимпиада') MATCHING (OBJ_ID);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM UT_EXAM_METHODS WHERE OBJ_ID = 3}

    UPDATE OR INSERT INTO UT_EXAM_METHODS (OBJ_ID, OBJ_NAME) VALUES (3, 'Очное тестирование') MATCHING (OBJ_ID);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXPERT_CALC_MODES'}	

    CREATE TABLE UT_EXPERT_CALC_MODES (
        OBJ_ID    INTEGER NOT NULL,
        OBJ_NAME  VARCHAR(1000)
    );

    ALTER TABLE UT_EXPERT_CALC_MODES ADD CONSTRAINT PK_UT_EXPERT_CALC_MODES PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXPERT_CALC_MODES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXPERT_CALC_MODES (OBJ_ID, OBJ_NAME) VALUES (0, 'Средняя оценка') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXPERT_CALC_MODES (OBJ_ID, OBJ_NAME) VALUES (1, 'Наименьшая из оценок') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXPERT_CALC_MODES (OBJ_ID, OBJ_NAME) VALUES (2, 'Наибольшая из оценок') MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_PLAN_METHODS'}

    CREATE TABLE UT_EXAM_PLAN_METHODS (
        OBJ_ID    INTEGER NOT NULL,
        OBJ_NAME  VARCHAR(1000)
    );

    ALTER TABLE UT_EXAM_PLAN_METHODS ADD CONSTRAINT PK_UT_EXAM_PLAN_METHODS PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXAM_PLAN_METHODS TO INISSOFT_ROLE;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM UT_EXAM_PLAN_METHODS WHERE OBJ_ID = 4}

    UPDATE OR INSERT INTO UT_EXAM_PLAN_METHODS (OBJ_ID, OBJ_NAME) VALUES (0, 'С распределением участников по ППЭ и индивидуальной рассадкой') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_PLAN_METHODS (OBJ_ID, OBJ_NAME) VALUES (1, 'С распределением участников по ППЭ без планирования рассадки') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_PLAN_METHODS (OBJ_ID, OBJ_NAME) VALUES (2, 'С планированием участников без распределения по ППЭ') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_PLAN_METHODS (OBJ_ID, OBJ_NAME) VALUES (3, 'Без планирования участников, тестирование всех желающих') MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_PLAN_METHODS (OBJ_ID, OBJ_NAME) VALUES (4, 'Участники в соответствии со списком учебного коллектива') MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_STAGES'}

    CREATE TABLE UT_EXAM_STAGES (
        OBJ_ID      INTEGER NOT NULL,
        OBJ_NAME    VARCHAR(1000),
        SORT_INDEX  INTEGER DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_STAGES ADD CONSTRAINT PK_UT_EXAM_STAGES PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXAM_STAGES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (21, 'Преподаватели', 1) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (100, 'Любые участники', 2) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (20, 'Любые учащиеся', 3) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (11, '11 классы', 100) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (1, '1 классы', 110) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (2, '2 классы', 120) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (3, '3 классы', 130) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (4, '4 классы', 140) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (5, '5 классы', 150) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (6, '6 классы', 160) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (7, '7 классы', 170) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (8, '8 классы', 180) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (9, '9 классы', 190) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (10, '10 классы', 200) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM UT_EXAM_STAGES WHERE OBJ_ID = 41}

    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (41, '1 курс', 110) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (42, '2 курс', 120) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (43, '3 курс', 130) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (44, '4 курс', 140) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (45, '5 курс', 150) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXAM_STAGES (OBJ_ID, OBJ_NAME, SORT_INDEX) VALUES (46, '6 курс', 160) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_DATES'}

    CREATE TABLE UT_EXAM_DATES (
        OBJ_ID           BIGINT NOT NULL,
        DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL         TIMESTAMP,
        OBJ_NAME         VARCHAR(200),
        SUBJECT_ID       BIGINT,
        STAGE_ID         INTEGER NOT NULL,
        EXAM_DATE_START  DATE,
        EXAM_DATE_END    DATE,
        DURATION         INTEGER,
        EXAM_DAY_TYPE    INTEGER NOT NULL,
        EXAM_STATE       INTEGER DEFAULT 0 NOT NULL,
        C_CALC_MODE      INTEGER DEFAULT 0 NOT NULL,
        C_EXPERT_NUM     INTEGER DEFAULT 1 NOT NULL,
        C_DIFF_QUESTION  INTEGER DEFAULT 1 NOT NULL,
        C_DIFF_TOTAL     INTEGER DEFAULT 1 NOT NULL,
        METHOD_ID        INTEGER DEFAULT 0 NOT NULL,
        PLAN_METHOD_ID   INTEGER DEFAULT 0 NOT NULL,
        ATTEMPTS         INTEGER DEFAULT 1 NOT NULL,
        OWNER_ID         BIGINT,
        H_LEVEL          INTEGER,
        ORG_REF          BIGINT,
        FLOW_MODE         SMALLINT DEFAULT 0 NOT NULL,
        PAUSE_ENABLED     SMALLINT DEFAULT 0 NOT NULL,
        SCALE_N0          SMALLINT,
        SCALE_NMIN        SMALLINT,
        SCALE_N4          SMALLINT,
        SCALE_N5          SMALLINT,
        SCALE_NMAX        SMALLINT,
        BLANK_AB_ID       BIGINT DEFAULT 0,
        BLANK_C_ID        BIGINT DEFAULT 0,
        BLANK_EXT_ID      BIGINT DEFAULT 0,
        BLANK_GEN_ID      BIGINT DEFAULT 0,
        EXPERT_ASSN_MODE  SMALLINT DEFAULT 0 NOT NULL,
        PERIOD_ID         BIGINT,
        LINK_HASH         VARCHAR(200),
        LINK_MASK         INTEGER DEFAULT 0 NOT NULL,
        PPE_ID            BIGINT,
        RESULTS_ALW       SMALLINT DEFAULT 0 NOT NULL,
        HINT_MODE         SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT PK_UT_EXAM_DATES PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_1 FOREIGN KEY (EXAM_DAY_TYPE) REFERENCES UT_EXAM_DAY_TYPES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_2 FOREIGN KEY (EXAM_STATE) REFERENCES UT_EXAM_STATES (OBJ_ID) ON DELETE SET DEFAULT ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_3 FOREIGN KEY (METHOD_ID) REFERENCES UT_EXAM_METHODS (OBJ_ID) ON DELETE SET DEFAULT ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_4 FOREIGN KEY (C_CALC_MODE) REFERENCES UT_EXPERT_CALC_MODES (OBJ_ID) ON DELETE SET DEFAULT ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_5 FOREIGN KEY (PLAN_METHOD_ID) REFERENCES UT_EXAM_PLAN_METHODS (OBJ_ID) ON DELETE SET DEFAULT ON UPDATE CASCADE;    
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_6 FOREIGN KEY (STAGE_ID) REFERENCES UT_EXAM_STAGES (OBJ_ID) ON DELETE SET DEFAULT ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_DATES ADD CONSTRAINT FK_UT_EXAM_DATES_SUBJECT_ID FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;

    GRANT ALL ON UT_EXAM_DATES TO INISSOFT_ROLE;

    COMMIT WORK;
    
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'PPE_ID' AND RDB$RELATION_NAME = 'UT_EXAM_DATES'}
    ALTER TABLE UT_EXAM_DATES ADD PPE_ID BIGINT;   
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_EXAM_DATES_BI0'}

    SET TERM ^ ;
   
    CREATE OR ALTER TRIGGER UT_EXAM_DATES_BI0 FOR UT_EXAM_DATES
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^
                                
    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_EXAM_DATES_BU0'}
    DROP TRIGGER UT_EXAM_DATES_BU0;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'DURATION' AND RDB$RELATION_NAME = 'UT_EXAM_DATES'}

    /* DURATION вместо EXAM_TIME */
    ALTER TABLE UT_EXAM_DATES ADD DURATION INTEGER;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'FLOW_MODE' AND RDB$RELATION_NAME = 'UT_EXAM_DATES'}

    ALTER TABLE UT_EXAM_DATES ADD FLOW_MODE         SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE UT_EXAM_DATES ADD PAUSE_ENABLED     SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE UT_EXAM_DATES ADD SCALE_N0          SMALLINT;
    ALTER TABLE UT_EXAM_DATES ADD SCALE_NMIN        SMALLINT;
    ALTER TABLE UT_EXAM_DATES ADD SCALE_N4          SMALLINT;
    ALTER TABLE UT_EXAM_DATES ADD SCALE_N5          SMALLINT;
    ALTER TABLE UT_EXAM_DATES ADD SCALE_NMAX        SMALLINT;
    ALTER TABLE UT_EXAM_DATES ADD BLANK_AB_ID       BIGINT DEFAULT 0;
    ALTER TABLE UT_EXAM_DATES ADD BLANK_C_ID        BIGINT DEFAULT 0;
    ALTER TABLE UT_EXAM_DATES ADD BLANK_EXT_ID      BIGINT DEFAULT 0;
    ALTER TABLE UT_EXAM_DATES ADD BLANK_GEN_ID      BIGINT DEFAULT 0;
    ALTER TABLE UT_EXAM_DATES ADD EXPERT_ASSN_MODE  SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE UT_EXAM_DATES ADD PERIOD_ID         BIGINT;
    ALTER TABLE UT_EXAM_DATES ADD LINK_HASH         VARCHAR(200);
    ALTER TABLE UT_EXAM_DATES ADD LINK_MASK         INTEGER DEFAULT 0 NOT NULL;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_NAME' AND RDB$RELATION_NAME = 'UT_EXAM_DATES'}
    ALTER TABLE UT_EXAM_DATES ADD OBJ_NAME VARCHAR(200);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'RESULTS_ALW' AND RDB$RELATION_NAME = 'UT_EXAM_DATES'}
    ALTER TABLE UT_EXAM_DATES ADD RESULTS_ALW SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE UT_EXAM_DATES ADD HINT_MODE SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'TEST_ID' AND RDB$RELATION_NAME = 'CJ2_CONTROL'}

  /* TEST_ID можно добавлять только тут */
  ALTER TABLE CJ2_CONTROL ADD TEST_ID BIGINT;
  COMMIT WORK;
  ALTER TABLE CJ2_CONTROL ADD CONSTRAINT FK_CJ2_CONTROL_1 FOREIGN KEY (TEST_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OWNER_ID' AND RDB$RELATION_NAME = 'UT_EXAM_DATES_VIEW'}

  CREATE OR ALTER VIEW UT_EXAM_DATES_VIEW(
    OBJ_ID,
    DATE_ADD,
    DATE_MODIFY,
    DATE_DEL,
    OBJ_NAME,
    SUBJECT_ID,
    STAGE_ID,
    EXAM_DATE_START,
    EXAM_DATE_END,
    DURATION,
    EXAM_DAY_TYPE,
    EXAM_STATE,
    SUBJECT_NAME,
    STAGE_NAME,
    STATE_NAME,
    DAY_TYPE_NAME,
    METHOD_ID,
    METHOD_NAME,
    C_EXPERT_NUM,
    C_CALC_MODE,
    C_DIFF_QUESTION,
    C_DIFF_TOTAL,
    C_CALC_MODE_NAME,
    PLAN_METHOD_ID,
    PLAN_METHOD_NAME,
    ATTEMPTS_TEXT,
    OWNER_NAME,
    OWNER_ID)
  AS
  SELECT
        D.obj_id,
        D.date_add,
        D.date_modify,
        D.date_del,
        D.obj_name,
        D.subject_id,
        D.stage_id,
        D.exam_date_start,
        D.exam_date_end,
        D.duration,
        D.exam_day_type,
        D.exam_state,
        V376.val,
        ES.obj_name,
        S.obj_name,
        DT.obj_name,
        D.method_id,
        M.obj_name,
        D.c_expert_num,
        D.c_calc_mode,
        D.c_diff_question,
        D.c_diff_total,
        CM.obj_name,
        D.plan_method_id,
        PM.OBJ_NAME,
        IIF(D.attempts > 0, D.attempts, 'не огр'),
        COALESCE(UC.SCAPTION, U.USER_NAME),
        D.OWNER_ID
    FROM UT_EXAM_DATES D
    LEFT JOIN VALS V376 ON V376.obj_id = D.subject_id and V376.PARAM_ID IN (376, 1751) AND V376.IS_DEL = 0
    JOIN UT_EXAM_STAGES ES ON ES.obj_id = D.stage_id
    JOIN UT_EXAM_STATES S ON S.obj_id = D.exam_state
    JOIN UT_EXAM_DAY_TYPES DT ON DT.obj_id = D.exam_day_type
    JOIN UT_EXAM_METHODS M ON M.obj_id = D.method_id
    JOIN UT_EXAM_PLAN_METHODS PM ON PM.obj_id = D.plan_method_id
    JOIN UT_EXPERT_CALC_MODES CM ON CM.obj_id = D.c_calc_mode
    LEFT JOIN USERS U on U.USER_ID = D.OWNER_ID AND D.OWNER_ID IS NOT NULL
    LEFT JOIN object_caption_get(U.OBJ_ID) UC ON U.OBJ_ID IS NOT NULL;

    COMMIT WORK;

    GRANT ALL ON UT_EXAM_DATES_VIEW TO INISSOFT_ROLE;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_PERSON_ASSN'}

    CREATE GENERATOR UT_ASSN_GEN;

    CREATE TABLE UT_EXAM_PERSON_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        PERSON_ID    BIGINT NOT NULL,
        LOCAL_ID        VARCHAR(40) CHARACTER SET ASCII,
        BLANKS_PRINTED  SMALLINT DEFAULT 0 NOT NULL,
        LEVEL_ID        SMALLINT,
        OU_ID           BIGINT,
        AREA_ID         BIGINT
    );
                                                                                
    ALTER TABLE UT_EXAM_PERSON_ASSN ADD CONSTRAINT PK_UT_EXAM_PERSON_ASSN PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_PERSON_ASSN ADD CONSTRAINT FK_UT_EXAM_PERSON_ASSN_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_EXAM_PERSON_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_PERSON_ASSN_BI0 FOR UT_EXAM_PERSON_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    DECLARE CYCLE SMALLINT;
    BEGIN
        IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);

        IF(NEW.LOCAL_ID IS NULL) THEN
        BEGIN

            -- Генерируем локальный уникальный ID из 7 символов
            NEW.LOCAL_ID = RIGHT(NEW.OBJ_ID, 7);
            CYCLE = 0;

            WHILE(1 = 1) DO
            BEGIN

                IF(NOT EXISTS(
                    SELECT FIRST 1 1
                    FROM UT_EXAM_PERSON_ASSN P
                    WHERE P.EXAM_ID = NEW.EXAM_ID AND P.DATE_DEL IS NULL AND P.LOCAL_ID = NEW.LOCAL_ID
                )) THEN LEAVE;

                NEW.LOCAL_ID = RIGHT(CAST(NEW.LOCAL_ID AS BIGINT) + 1, 7);
                IF(NEW.LOCAL_ID = '00000000') THEN
                BEGIN
                    CYCLE = CYCLE + 1;
                    IF(CYCLE > 1) THEN EXCEPTION DATA_ERROR 'Не удалось сгенерировать сигнатуру участника, переполнение';
                END

            END
        END
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OU_ID' AND RDB$RELATION_NAME = 'UT_EXAM_PERSON_ASSN'}

    ALTER TABLE UT_EXAM_PERSON_ASSN ADD OU_ID BIGINT;
    ALTER TABLE UT_EXAM_PERSON_ASSN ADD AREA_ID BIGINT;
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'FK_UT_EXAM_PERSON_ASSN_2'}
   
    ALTER TABLE UT_EXAM_PERSON_ASSN DROP CONSTRAINT FK_UT_EXAM_PERSON_ASSN_2;
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_EXAM_PERSON_ASSN_BU0' AND RDB$RELATION_NAME = 'UT_EXAM_PERSON_ASSN'}

    DROP TRIGGER UT_EXAM_PERSON_ASSN_BU0;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LOCAL_ID' AND RDB$RELATION_NAME = 'UT_EXAM_PERSON_ASSN'}

    ALTER TABLE UT_EXAM_PERSON_ASSN ADD LOCAL_ID VARCHAR(40) CHARACTER SET ASCII;
    ALTER TABLE UT_EXAM_PERSON_ASSN ADD BLANKS_PRINTED SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE UT_EXAM_PERSON_ASSN ADD LEVEL_ID SMALLINT;

    CREATE GENERATOR UT_ASSN_GEN;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_PERSON_ASSN_BI0 FOR UT_EXAM_PERSON_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    DECLARE CYCLE SMALLINT;
    BEGIN
        IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);

        IF(NEW.LOCAL_ID IS NULL) THEN
        BEGIN

            -- Генерируем локальный уникальный ID из 7 символов
            NEW.LOCAL_ID = RIGHT(NEW.OBJ_ID, 7);
            CYCLE = 0;

            WHILE(1 = 1) DO
            BEGIN

                IF(NOT EXISTS(
                    SELECT FIRST 1 1
                    FROM UT_EXAM_PERSON_ASSN P
                    WHERE P.EXAM_ID = NEW.EXAM_ID AND P.DATE_DEL IS NULL AND P.LOCAL_ID = NEW.LOCAL_ID
                )) THEN LEAVE;

                NEW.LOCAL_ID = RIGHT(CAST(NEW.LOCAL_ID AS BIGINT) + 1, 7);
                IF(NEW.LOCAL_ID = '00000000') THEN
                BEGIN
                    CYCLE = CYCLE + 1;
                    IF(CYCLE > 1) THEN EXCEPTION DATA_ERROR 'Не удалось сгенерировать сигнатуру участника, переполнение';
                END

            END
        END
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_RES_ASSN'}

  CREATE TABLE UT_EXAM_RES_ASSN (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    EXAM_ID      BIGINT NOT NULL,
    RES_ID       BIGINT NOT NULL,
    QTY          INTEGER NOT NULL
  );

  ALTER TABLE UT_EXAM_RES_ASSN ADD CONSTRAINT PK_UT_EXAM_RES_ASSN PRIMARY KEY (OBJ_ID);
  ALTER TABLE UT_EXAM_RES_ASSN ADD CONSTRAINT FK_UT_EXAM_RES_ASSN_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE UT_EXAM_RES_ASSN ADD CONSTRAINT FK_UT_EXAM_RES_ASSN_2 FOREIGN KEY (RES_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER UT_EXAM_RES_ASSN_BI0 FOR UT_EXAM_RES_ASSN
  ACTIVE BEFORE INSERT POSITION 0
  AS
  BEGIN
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  END
  ^
  SET TERM ; ^

  GRANT ALL ON UT_EXAM_RES_ASSN TO INISSOFT_ROLE;

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_EXPERT_ASSN'}

    CREATE TABLE UT_EXAM_EXPERT_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        EXPERT_ID    BIGINT NOT NULL,
        ROLE_ID      INTEGER DEFAULT 0 NOT NULL,
        SECOND_CHECK  SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_EXPERT_ASSN ADD CONSTRAINT PK_UT_EXAM_EXPERT_ASSN PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_EXPERT_ASSN ADD CONSTRAINT FK_UT_EXAM_EXPERT_ASSN_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_EXPERT_ASSN ADD CONSTRAINT FK_UT_EXAM_EXPERT_ASSN_2 FOREIGN KEY (EXPERT_ID) REFERENCES UT_EXPERTS (EXPERT_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_EXAM_EXPERT_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_EXPERT_ASSN_BI0 FOR UT_EXAM_EXPERT_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN
        NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    SET TERM ; ^

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_EXAM_EXPERT_ASSN_BU0' AND RDB$RELATION_NAME = 'UT_EXAM_EXPERT_ASSN'}

    DROP TRIGGER UT_EXAM_EXPERT_ASSN_BU0;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SECOND_CHECK' AND RDB$RELATION_NAME = 'UT_EXAM_EXPERT_ASSN'}

    ALTER TABLE UT_EXAM_EXPERT_ASSN ADD SECOND_CHECK SMALLINT DEFAULT 0 NOT NULL;

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ORG_ID' AND RDB$RELATION_NAME = 'UT_EXPERTS'}	

    ALTER TABLE UT_EXPERTS ADD USER_NAME VARCHAR(100);
    ALTER TABLE UT_EXPERTS ADD PWD VARCHAR(100);
    ALTER TABLE UT_EXPERTS ADD ORG_ID BIGINT;

    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT RDB$CONSTRAINT_NAME FROM RDB$REF_CONSTRAINTS WHERE RDB$CONSTRAINT_NAME = 'FK_UT_EXPERTS_1'}

    ALTER TABLE UT_EXPERTS DROP CONSTRAINT FK_UT_EXPERTS_1;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USER_NAME' AND RDB$RELATION_NAME = 'UT_EXPERTS'}

    ALTER TABLE UT_EXPERTS ADD USER_NAME VARCHAR(100);
    ALTER TABLE UT_EXPERTS ADD PWD VARCHAR(100);
    ALTER TABLE UT_EXPERTS ADD ORG_ID BIGINT;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_CHARSETS'}

    CREATE TABLE UT_CHARSETS (
        OBJ_ID     SMALLINT NOT NULL,
        OBJ_NAME   VARCHAR(100) NOT NULL,
        LANG_CODE  VARCHAR(100) NOT NULL,
        IS_DEL     SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_CHARSETS ADD CONSTRAINT PK_UT_CHARSETS PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_CHARSETS TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_CHARSETS (OBJ_ID, OBJ_NAME, LANG_CODE, IS_DEL) VALUES (0, 'Цифры 0-9', 'digits', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_CHARSETS (OBJ_ID, OBJ_NAME, LANG_CODE, IS_DEL) VALUES (1, 'Цифры, минус, запятая, точка', 'digits2', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_CHARSETS (OBJ_ID, OBJ_NAME, LANG_CODE, IS_DEL) VALUES (2, 'Кириллица', 'rus2', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_CHARSETS (OBJ_ID, OBJ_NAME, LANG_CODE, IS_DEL) VALUES (10, 'Латиница', 'eng2', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_CHARSETS (OBJ_ID, OBJ_NAME, LANG_CODE, IS_DEL) VALUES (3, 'Кириллица, цифры и знаки', 'rus2e', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_CHARSETS (OBJ_ID, OBJ_NAME, LANG_CODE, IS_DEL) VALUES (11, 'Латиница, цифры и знаки', 'eng', 0) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}


{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_QUESTION_TYPE'}

    CREATE GENERATOR GEN_UT2_QUESTION_TYPE_ID;

    CREATE TABLE UT_QUESTION_TYPE (
        OBJ_ID          SMALLINT NOT NULL,
        OBJ_NAME        VARCHAR(100) NOT NULL,
        OBJ_VALUE       CHAR(1) NOT NULL,
        IS_DEL          SMALLINT DEFAULT 0 NOT NULL,
        IS_HANDCHECKED  SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_QUESTION_TYPE ADD CONSTRAINT PK_UT_QUESTION_TYPE_1 PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_QUESTION_TYPE TO INISSOFT_ROLE;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_QUESTION_TYPE_BI FOR UT_QUESTION_TYPE
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_UT2_QUESTION_TYPE_ID, 1);
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_QUESTION_TYPE (OBJ_ID, OBJ_NAME, OBJ_VALUE, IS_DEL, IS_HANDCHECKED) VALUES (1, 'задание на выбор', 'A', 0, 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_QUESTION_TYPE (OBJ_ID, OBJ_NAME, OBJ_VALUE, IS_DEL, IS_HANDCHECKED) VALUES (2, 'задание на ввод', 'B', 0, 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_QUESTION_TYPE (OBJ_ID, OBJ_NAME, OBJ_VALUE, IS_DEL, IS_HANDCHECKED) VALUES (3, 'задание с развернутым ответом', 'C', 0, 1) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_QUESTION_TYPE (OBJ_ID, OBJ_NAME, OBJ_VALUE, IS_DEL, IS_HANDCHECKED) VALUES (4, 'задание на ввод соответствия', 'E', 0, 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_QUESTION_TYPE (OBJ_ID, OBJ_NAME, OBJ_VALUE, IS_DEL, IS_HANDCHECKED) VALUES (5, 'задание на ввод фрагментов', 'F', 0, 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_QUESTION_TYPE (OBJ_ID, OBJ_NAME, OBJ_VALUE, IS_DEL, IS_HANDCHECKED) VALUES (8, 'задание с записью звука', 'V', 0, 1) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING'}

    CREATE TABLE UT_KIM_CODING (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        OBJ_NAME     VARCHAR(1000) NOT NULL,
        N_LEVELS     SMALLINT DEFAULT 2 NOT NULL,
        OWNER_LEVEL  SMALLINT DEFAULT 0 NOT NULL,
        OWNER_ID     BIGINT,
        USER_ID      BIGINT
    );

    ALTER TABLE UT_KIM_CODING ADD CONSTRAINT PK_UT_KIM_CODING_1 PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_KIM_CODING TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_KIM_CODING_BI0 FOR UT_KIM_CODING
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_KIM_CODING_BU0 FOR UT_KIM_CODING
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USER_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING'}

    ALTER TABLE UT_KIM_CODING ADD USER_ID BIGINT;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REF_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING'}

    ALTER TABLE UT_KIM_CODING ADD REF_ID BIGINT;
    COMMIT WORK;
    ALTER TABLE UT_KIM_CODING ADD CONSTRAINT FK_UT_KIM_CODING_1 FOREIGN KEY (USER_ID) REFERENCES USERS(USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    COMMIT WORK;
    CREATE INDEX UT_KIM_CODING_IDX1 ON UT_KIM_CODING (REF_ID);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING_LEVELS'}

    CREATE TABLE UT_KIM_CODING_LEVELS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        CODING_ID    BIGINT NOT NULL,
        PARENT_ID    BIGINT,
        OBJ_NAME     VARCHAR(300) NOT NULL,
        N_LEVEL      SMALLINT DEFAULT 0 NOT NULL,
        SORT_ORDER   SMALLINT DEFAULT 0 NOT NULL,
        REF_ID       BIGINT
    );

    ALTER TABLE UT_KIM_CODING_LEVELS ADD CONSTRAINT PK_UT_KIM_CODING_LEVELS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_KIM_CODING_LEVELS ADD CONSTRAINT FK_UT_KIM_CODING_LEVELS_1 FOREIGN KEY (CODING_ID) REFERENCES UT_KIM_CODING (OBJ_ID);
    ALTER TABLE UT_KIM_CODING_LEVELS ADD CONSTRAINT FK_UT_KIM_CODING_LEVELS_2 FOREIGN KEY (PARENT_ID) REFERENCES UT_KIM_CODING_LEVELS (OBJ_ID);

    GRANT ALL ON UT_KIM_CODING_LEVELS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_KIM_CODING_LEVELS_BI0 FOR UT_KIM_CODING_LEVELS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_KIM_CODING_LEVELS_BU0 FOR UT_KIM_CODING_LEVELS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REF_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING_LEVELS'}

    ALTER TABLE UT_KIM_CODING_LEVELS ADD REF_ID BIGINT;
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'OBJ_NAME' AND F.RDB$RELATION_NAME = 'UT_KIM_CODING_LEVELS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 200}

    ALTER TABLE UT_KIM_CODING_LEVELS ALTER COLUMN OBJ_NAME TYPE VARCHAR(300);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING_STAGES'}

    CREATE TABLE UT_KIM_CODING_STAGES (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        CODING_ID    BIGINT NOT NULL,
        STAGE_ID     INTEGER NOT NULL
    );

    ALTER TABLE UT_KIM_CODING_STAGES ADD CONSTRAINT PK_UT_KIM_CODING_STAGES PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_KIM_CODING_STAGES ADD CONSTRAINT FK_UT_KIM_CODING_STAGES_1 FOREIGN KEY (CODING_ID) REFERENCES UT_KIM_CODING (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_KIM_CODING_STAGES ADD CONSTRAINT FK_UT_KIM_CODING_STAGES_2 FOREIGN KEY (STAGE_ID) REFERENCES UT_EXAM_STAGES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_KIM_CODING_STAGES TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_KIM_CODING_STAGES_BI0 FOR UT_KIM_CODING_STAGES
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN
        NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_KIM_CODING_STAGES_BU0 FOR UT_KIM_CODING_STAGES
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_KIM_CODING_SUBJECTS'}

    CREATE TABLE UT_KIM_CODING_SUBJECTS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        CODING_ID    BIGINT NOT NULL,
        SUBJECT_ID   BIGINT
    );
                                         
    ALTER TABLE UT_KIM_CODING_SUBJECTS ADD CONSTRAINT PK_UT_KIM_CODING_SUBJECTS PRIMARY KEY (OBJ_ID);                                       
    ALTER TABLE UT_KIM_CODING_SUBJECTS ADD CONSTRAINT FK_UT_KIM_CODING_SUBJECTS_1 FOREIGN KEY (CODING_ID) REFERENCES UT_KIM_CODING (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_KIM_CODING_SUBJECTS ADD CONSTRAINT FK_UT_KIM_CODING_SUBJECTS_2 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_KIM_CODING_STAGES TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_KIM_CODING_SUBJECTS_BI0 FOR UT_KIM_CODING_SUBJECTS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN
        NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^
                                         
    CREATE OR ALTER TRIGGER UT_KIM_CODING_SUBJECTS_BU0 FOR UT_KIM_CODING_SUBJECTS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXPERT_ROLES'}

    CREATE TABLE UT_EXPERT_ROLES (
        OBJ_ID       INTEGER NOT NULL,
        OBJ_NAME     VARCHAR(1000),
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT current_timestamp NOT NULL,
        DATE_DEL     TIMESTAMP
    );                                                                               

    ALTER TABLE UT_EXPERT_ROLES ADD CONSTRAINT PK_UT_EXPERT_ROLES PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXPERT_ROLES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_EXPERT_ROLES (OBJ_ID, OBJ_NAME, DATE_ADD, DATE_MODIFY, DATE_DEL) VALUES (1, 'Основной эксперт', '2019-02-20 11:08:17', '2019-02-20 11:08:17', NULL) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXPERT_ROLES (OBJ_ID, OBJ_NAME, DATE_ADD, DATE_MODIFY, DATE_DEL) VALUES (2, 'Старший эксперт', '2019-02-20 11:08:27', '2019-02-20 11:08:27', NULL) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_EXPERT_ROLES (OBJ_ID, OBJ_NAME, DATE_ADD, DATE_MODIFY, DATE_DEL) VALUES (3, 'Ведущий эксперт', '2019-02-20 11:08:34', '2019-02-20 11:08:34', NULL) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PAGE_TEMPLATES'}

    CREATE TABLE UT_PAGE_TEMPLATES (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        OBJ_NAME     VARCHAR(400) NOT NULL,
        IS_DS        SMALLINT DEFAULT 0 NOT NULL,
        BLANK_TYPE   SMALLINT DEFAULT 0 NOT NULL,
        IS_ACTIVE    SMALLINT DEFAULT 1 NOT NULL,
        DATA_FRONT   BLOB SUB_TYPE 1 SEGMENT SIZE 80,
        DATA_BACK    BLOB SUB_TYPE 1 SEGMENT SIZE 80
    );

    ALTER TABLE UT_PAGE_TEMPLATES ADD CONSTRAINT UT_PAGE_TEMPLATES_PK PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_PAGE_TEMPLATES TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PAGE_TEMPLATES_BI0 FOR UT_PAGE_TEMPLATES
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN,1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_PAGE_TEMPLATES_BU0 FOR UT_PAGE_TEMPLATES
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    UPDATE OR INSERT INTO UT_PAGE_TEMPLATES (OBJ_ID, DATE_ADD, DATE_MODIFY, DATE_DEL, OBJ_NAME, IS_DS, BLANK_TYPE, IS_ACTIVE) VALUES (0, '2019-04-22 13:07:53', '2019-04-22 13:07:53', NULL, 'Пустой бланк', 0, 0, 1) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PPE'}

    CREATE TABLE UT_PPE (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        ORG_ID       BIGINT,
        NAME_SHORT   VARCHAR(1000),
        NAME_FULL    VARCHAR(1000),
        PPE_CODE     VARCHAR(40),
        FLAGS        INTEGER DEFAULT 0 NOT NULL,
        N_PLACES     INTEGER DEFAULT 0,
        AREA_ID      BIGINT,
        SPEC_COUNT   SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_PPE ADD CONSTRAINT PK_UT_PPE PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_PPE ADD CONSTRAINT FK_UT_PPE_1 FOREIGN KEY (AREA_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;

    GRANT ALL ON UT_PPE TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PPE_BI0 FOR UT_PPE
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN  NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_PPE_BU0 FOR UT_PPE
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PPE_ROOMS'}

    CREATE TABLE UT_PPE_ROOMS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        PPE_ID       BIGINT,
        OBJ_NAME     VARCHAR(100) NOT NULL,
        LOCATION     VARCHAR(400),
        N_FLOOR      SMALLINT,
        ROOM_NUM     VARCHAR(20),
        PPE_CODE     VARCHAR(40),
        FLAGS        INTEGER DEFAULT 0 NOT NULL,
        N_PLACES     INTEGER DEFAULT 0 NOT NULL,
        N_ROWS       SMALLINT,
        N_COLS       SMALLINT,
        IS_ACTIVE    SMALLINT DEFAULT 1 NOT NULL,
        PLACES_MAP   VARCHAR(4000)
    );

    ALTER TABLE UT_PPE_ROOMS ADD CONSTRAINT PK_UT_PPE_ROOMS PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_PPE_ROOMS ADD CONSTRAINT FK_UT_PPE_ROOMS_1 FOREIGN KEY (PPE_ID) REFERENCES UT_PPE (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_PPE_ROOMS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PPE_ROOM_BI0 FOR UT_PPE_ROOMS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_PPE_ROOMS_BU0 FOR UT_PPE_ROOMS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PPE_PLACES'}

    CREATE TABLE UT_PPE_PLACES (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        ROOM_ID      BIGINT,
        OBJ_NAME     VARCHAR(100) NOT NULL,
        FLAGS        INTEGER DEFAULT 0 NOT NULL,
        IS_DELETED   SMALLINT DEFAULT 0 NOT NULL,
        COORD_X      FLOAT,
        COORD_Y      FLOAT,
        COORD_R      FLOAT,
        PLACE_NUM    SMALLINT NOT NULL,
        N_ROW        SMALLINT NOT NULL,
        N_COL        SMALLINT NOT NULL
    );

    ALTER TABLE UT_PPE_PLACES ADD CONSTRAINT PK_UT_PPE_PLACES PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_PPE_PLACES ADD CONSTRAINT FK_UT_PPE_PLACES_1 FOREIGN KEY (ROOM_ID) REFERENCES UT_PPE_ROOMS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_PPE_PLACES TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PPE_PLACES_BI0 FOR UT_PPE_PLACES
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_PPE_PLACES_BU0 FOR UT_PPE_PLACES
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_ROOM_ASSN'}

    CREATE TABLE UT_EXAM_ROOM_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        ROOM_ID      BIGINT NOT NULL,
        ROLE_ID      INTEGER DEFAULT 1 NOT NULL
    );

    ALTER TABLE UT_EXAM_ROOM_ASSN ADD CONSTRAINT PK_UT_EXAM_ROOM_ASSN PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_ROOM_ASSN ADD CONSTRAINT FK_UT_EXAM_ROOM_ASSN_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_ROOM_ASSN ADD CONSTRAINT FK_UT_EXAM_ROOM_ASSN_2 FOREIGN KEY (ROOM_ID) REFERENCES UT_PPE_ROOMS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;


    GRANT ALL ON UT_EXAM_ROOM_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_ROOM_ASSN_BI0 FOR UT_EXAM_ROOM_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    CREATE OR ALTER TRIGGER UT_EXAM_ROOM_ASSN_BU0 FOR UT_EXAM_ROOM_ASSN
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    BEGIN
        NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PERSON_PPE_ASSN'}

    CREATE TABLE UT_PERSON_PPE_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        PPE_ID       BIGINT NOT NULL,
        PERSON_ID    BIGINT NOT NULL,
        EXAM_ID      BIGINT NOT NULL
    );

    ALTER TABLE UT_PERSON_PPE_ASSN ADD CONSTRAINT PK_UT_PERSON_PPE_ASSN PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_PERSON_PPE_ASSN ADD CONSTRAINT FK_UT_PERSON_PPE_ASSN_1 FOREIGN KEY (PPE_ID) REFERENCES UT_PPE (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_PERSON_PPE_ASSN ADD CONSTRAINT FK_UT_PERSON_PPE_ASSN_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_PERSON_PPE_ASSN ADD CONSTRAINT FK_UT_PERSON_PPE_ASSN_3 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_PERSON_PPE_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PERSON_PPE_ASSN_BI0 FOR UT_PERSON_PPE_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    CREATE OR ALTER TRIGGER UT_PERSON_PPE_ASSN_BU0 FOR UT_PERSON_PPE_ASSN
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    BEGIN
        NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PERSON_PLACE_ASSN'}

    CREATE TABLE UT_PERSON_PLACE_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        PLACE_ID     BIGINT NOT NULL,
        PERSON_ID    BIGINT NOT NULL,
        EXAM_ID      BIGINT NOT NULL
    );

    ALTER TABLE UT_PERSON_PLACE_ASSN ADD CONSTRAINT PK_UT_PERSON_PLACE_ASSN PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_PERSON_PLACE_ASSN ADD CONSTRAINT FK_UT_PERSON_PLACE_ASSN_1 FOREIGN KEY (PLACE_ID) REFERENCES UT_PPE_PLACES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_PERSON_PLACE_ASSN ADD CONSTRAINT FK_UT_PERSON_PLACE_ASSN_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_PERSON_PLACE_ASSN ADD CONSTRAINT FK_UT_PERSON_PLACE_ASSN_3 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_PERSON_PLACE_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PERSON_PLACE_ASSN_BI0 FOR UT_PERSON_PLACE_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    CREATE OR ALTER TRIGGER UT_PERSON_PLACE_ASSN_BU0 FOR UT_PERSON_PLACE_ASSN
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    BEGIN
        NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXT_BLANKS'}

    CREATE GENERATOR UT_BLANK_GEN;

    CREATE TABLE UT_EXT_BLANKS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT,
        REF_ID       BIGINT,
        USER_ID      BIGINT,
        LOCAL_ID     VARCHAR(40) CHARACTER SET ASCII NOT NULL,
        BLANK_STATE  SMALLINT default 0 NOT NULL
    );

    ALTER TABLE UT_EXT_BLANKS ADD CONSTRAINT PK_UT_EXT_BLANKS PRIMARY KEY (OBJ_ID);
    CREATE INDEX UT_EXT_BLANKS_IDX1 ON UT_EXT_BLANKS (EXAM_ID, REF_ID, LOCAL_ID);

    GRANT ALL ON UT_EXT_BLANKS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXT_BLANKS_BI0 FOR UT_EXT_BLANKS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BLANK_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_EXT_BLANKS_BU0 FOR UT_EXT_BLANKS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_PACKAGES'}

    CREATE TABLE UT_PACKAGES (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        ED_ID        BIGINT NOT NULL,
        PPE_ID       BIGINT NOT NULL,
        ROOM_ID      BIGINT,
        USER_ID      BIGINT,
        N_PAGES      INTEGER NOT NULL,
        STATE_ID     SMALLINT DEFAULT 0 NOT NULL,
        IP_INFO      VARCHAR(200)
    );

    ALTER TABLE UT_PACKAGES ADD CONSTRAINT PK_UT_PACKAGES PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_PACKAGES ADD CONSTRAINT FK_UT_PACKAGES_1 FOREIGN KEY (ED_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_PACKAGES TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_PACKAGES_BI0 FOR UT_PACKAGES
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BLANK_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_PACKAGES_BU0' AND RDB$RELATION_NAME = 'UT_PACKAGES'}

    DROP TRIGGER UT_PACKAGES_BU0;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_OU_ASSN'}

    CREATE TABLE UT_EXAM_OU_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        OU_ID        BIGINT NOT NULL,
        DATE_START   DATE,
        DATE_END     DATE
    );
                                                                                
    ALTER TABLE UT_EXAM_OU_ASSN ADD CONSTRAINT PK_UT_EXAM_OU_ASSN PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_EXAM_OU_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_OU_ASSN_BI0 FOR UT_EXAM_OU_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_EXAM_OU_ASSN_BU0' AND RDB$RELATION_NAME = 'UT_EXAM_OU_ASSN'}

    DROP TRIGGER UT_EXAM_OU_ASSN_BU0;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_PPE_ASSN'}

    CREATE TABLE UT_EXAM_PPE_ASSN (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        PPE_ID       BIGINT NOT NULL,
        N_PLACES     INTEGER DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_PPE_ASSN ADD CONSTRAINT PK_UT_EXAM_PPE_ASSN PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_PPE_ASSN ADD CONSTRAINT FK_UT_EXAM_PPE_ASSN_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_PPE_ASSN ADD CONSTRAINT FK_UT_EXAM_PPE_ASSN_2 FOREIGN KEY (PPE_ID) REFERENCES UT_PPE (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_EXAM_PPE_ASSN TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_PPE_ASSN_BI0 FOR UT_EXAM_PPE_ASSN
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ASSN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    CREATE OR ALTER TRIGGER UT_EXAM_PPE_ASSN0 FOR UT_EXAM_PPE_ASSN
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    BEGIN
        NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_PRINT_LOG'}

    CREATE GENERATOR UT_LOG_GEN;

    CREATE TABLE UT_EXAM_PRINT_LOG (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        REF_ID       BIGINT NOT NULL,
        USER_ID      BIGINT NOT NULL,
        EVENT_TYPE   SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_EXAM_PRINT_LOG ADD CONSTRAINT PK_UT_EXAM_PRINT_LOG PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_PRINT_LOG ADD CONSTRAINT FK_UT_EXAM_PRINT_LOG_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_EXAM_PRINT_LOG TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_PRINT_LOG_BI0 FOR UT_EXAM_PRINT_LOG
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_LOG_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_EXAM_PRINT_LOG_BU0 FOR UT_EXAM_PRINT_LOG
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_TEST_STRUCTS'}

    CREATE TABLE UT_TEST_STRUCTS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        SUBJECT_ID   BIGINT,
        STAGE_ID     INTEGER NOT NULL,
        METHOD_ID    INTEGER NOT NULL,
        OBJ_NAME     VARCHAR(1000) NOT NULL,
        IS_AUTO      SMALLINT DEFAULT 0 NOT NULL,
        STR_HASH     VARCHAR(100),
        TEXT_NOTES   BLOB SUB_TYPE 1 SEGMENT SIZE 80
    );

    ALTER TABLE UT_TEST_STRUCTS ADD CONSTRAINT PK_UT_TEST_STRUCTS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_TEST_STRUCTS ADD CONSTRAINT FK_UT_TEST_STRUCTS_1 FOREIGN KEY (METHOD_ID) REFERENCES UT_EXAM_METHODS (OBJ_ID) ON UPDATE CASCADE;
    ALTER TABLE UT_TEST_STRUCTS ADD CONSTRAINT FK_UT_TEST_STRUCTS_2 FOREIGN KEY (STAGE_ID) REFERENCES UT_EXAM_STAGES (OBJ_ID) ON UPDATE CASCADE;

    GRANT ALL ON UT_TEST_STRUCTS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_TEST_STRUCTS_BI0 FOR UT_TEST_STRUCTS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_TEST_STRUCTS_BU0 FOR UT_TEST_STRUCTS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_TEST_STRUCT_POINTS'}

    CREATE TABLE UT_TEST_STRUCT_POINTS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        STRUCT_ID    BIGINT NOT NULL,
        Q_TYPE_ID    SMALLINT NOT NULL,
        Q_ORDER      INTEGER NOT NULL,
        Q_LEVEL      SMALLINT DEFAULT 0 NOT NULL,
        Q_MAX_SCORE  SMALLINT NOT NULL,
        CHARSET_ID   SMALLINT,
        TEXT_NOTES   VARCHAR(8000),
        WND_MIN      FLOAT,
        WND_MAX      FLOAT
    );

    ALTER TABLE UT_TEST_STRUCT_POINTS ADD CONSTRAINT PK_UT_TEST_STRUCT_POINTS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_TEST_STRUCT_POINTS ADD CONSTRAINT FK_UT_TEST_STRUCT_POINTS_1 FOREIGN KEY (STRUCT_ID) REFERENCES UT_TEST_STRUCTS (OBJ_ID) ON DELETE CASCADE;
    ALTER TABLE UT_TEST_STRUCT_POINTS ADD CONSTRAINT FK_UT_TEST_STRUCT_POINTS_2 FOREIGN KEY (Q_TYPE_ID) REFERENCES UT_QUESTION_TYPE (OBJ_ID);
    ALTER TABLE UT_TEST_STRUCT_POINTS ADD CONSTRAINT FK_UT_TEST_STRUCT_POINTS_3 FOREIGN KEY (CHARSET_ID) REFERENCES UT_CHARSETS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    CREATE INDEX UT_TEST_STRUCT_POINTS_IDX1 ON UT_TEST_STRUCT_POINTS (STRUCT_ID, DATE_DEL);
    CREATE INDEX UT_TEST_STRUCT_POINTS_IDX2 ON UT_TEST_STRUCT_POINTS (STRUCT_ID, DATE_DEL, Q_ORDER);

    GRANT ALL ON UT_TEST_STRUCT_POINTS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_TEST_STRUCT_POINTS_BI0 FOR UT_TEST_STRUCT_POINTS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_TEST_STRUCT_POINTS_BU0 FOR UT_TEST_STRUCT_POINTS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'WND_MIN' AND RDB$RELATION_NAME = 'UT_TEST_STRUCT_POINTS'}
  ALTER TABLE UT_TEST_STRUCT_POINTS ADD WND_MIN FLOAT;
  ALTER TABLE UT_TEST_STRUCT_POINTS ADD WND_MAX FLOAT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_TESTS'}

    CREATE TABLE UT_TESTS (
        OBJ_ID        BIGINT NOT NULL,
        DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL      TIMESTAMP,
        STRUCT_ID     BIGINT NOT NULL,
        OBJ_NAME      VARCHAR(1000) NOT NULL,
        MASTER_ED_ID  BIGINT,
        CODING_ID     BIGINT
    );

    ALTER TABLE UT_TESTS ADD CONSTRAINT PK_UT_TESTS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_TESTS ADD CONSTRAINT FK_UT_TESTS_2 FOREIGN KEY (STRUCT_ID) REFERENCES UT_TEST_STRUCTS (OBJ_ID);

    GRANT ALL ON UT_TESTS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_TESTS_BI0 FOR UT_TESTS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_TESTS_BU0 FOR UT_TESTS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_TEST_VARS'}

    CREATE TABLE UT_TEST_VARS (
        OBJ_ID        BIGINT NOT NULL,
        DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL      TIMESTAMP,
        TEST_ID       BIGINT NOT NULL,
        NUM           SMALLINT NOT NULL,
        OBJ_NAME      VARCHAR(1000),
        MASTER_ED_ID  BIGINT
    );

    ALTER TABLE UT_TEST_VARS ADD CONSTRAINT PK_UT_TEST_VARS PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_TEST_VARS ADD CONSTRAINT FK_UT_TEST_VARS_2 FOREIGN KEY (TEST_ID) REFERENCES UT_TESTS (OBJ_ID);

    GRANT ALL ON UT_TEST_VARS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_TEST_VARS_BI0 FOR UT_TEST_VARS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_TEST_VARS_BU0 FOR UT_TEST_VARS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_QUESTIONS'}

    CREATE TABLE UT_QUESTIONS (
        OBJ_ID         BIGINT NOT NULL,
        DATE_ADD       TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL       TIMESTAMP,
        SECTION_ID     BIGINT,
        PARENT_ID      BIGINT,
        OBJ_NAME       VARCHAR(400) NOT NULL,
        SORT_ORDER     SMALLINT NOT NULL,
        QUESTION_TYPE  SMALLINT NOT NULL,
        QUESTION       BLOB SUB_TYPE 1 SEGMENT SIZE 80,
        MAX_SCORE      SMALLINT,
        HINT           BLOB SUB_TYPE 1 SEGMENT SIZE 80,
        TIME_LIMIT     SMALLINT,
        METADATA_ID    VARCHAR(40),
        FLAGS          INTEGER DEFAULT 0 NOT NULL,
        CHARSET_ID     SMALLINT,
        Q_LEVEL        SMALLINT DEFAULT 0 NOT NULL,
        FILE_SIZE      INTEGER,
        K              VARCHAR(64),
        USER_ID        BIGINT,
        REF_ID         VARCHAR(64),
        STAGE_ID1      BIGINT,
        STAGE_ID2      BIGINT,
        STAGE_ID3      BIGINT
    );

    ALTER TABLE UT_QUESTIONS ADD CONSTRAINT PK_UT_QUESTIONS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_QUESTIONS ADD CONSTRAINT FK_UT_QUESTIONS_1 FOREIGN KEY (SECTION_ID) REFERENCES UT_KIM_CODING_LEVELS (OBJ_ID);
    ALTER TABLE UT_QUESTIONS ADD CONSTRAINT FK_UT_QUESTIONS_2 FOREIGN KEY (PARENT_ID) REFERENCES UT_QUESTIONS (OBJ_ID);
    ALTER TABLE UT_QUESTIONS ADD CONSTRAINT FK_UT_QUESTIONS_3 FOREIGN KEY (QUESTION_TYPE) REFERENCES UT_QUESTION_TYPE (OBJ_ID);
    ALTER TABLE UT_QUESTIONS ADD CONSTRAINT FK_UT_QUESTIONS_4 FOREIGN KEY (CHARSET_ID) REFERENCES UT_CHARSETS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
    COMMIT WORK;
    CREATE INDEX UT_QUESTIONS_IDX1 ON UT_QUESTIONS (STAGE_ID1);
    CREATE INDEX UT_QUESTIONS_IDX2 ON UT_QUESTIONS (STAGE_ID2);
    CREATE INDEX UT_QUESTIONS_IDX3 ON UT_QUESTIONS (STAGE_ID3);

    GRANT ALL ON UT_QUESTIONS TO INISSOFT_ROLE;
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SECTION_ID' AND RDB$RELATION_NAME = 'UT_QUESTIONS' AND RDB$NULL_FLAG = 1}

    ALTER TABLE UT_QUESTIONS ALTER SECTION_ID DROP NOT NULL;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REF_ID' AND RDB$RELATION_NAME = 'UT_QUESTIONS'}

    ALTER TABLE UT_QUESTIONS ADD REF_ID VARCHAR(64);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STAGE_ID1' AND RDB$RELATION_NAME = 'UT_QUESTIONS'}

    ALTER TABLE UT_QUESTIONS ADD STAGE_ID1 BIGINT;
    ALTER TABLE UT_QUESTIONS ADD STAGE_ID2 BIGINT;
    ALTER TABLE UT_QUESTIONS ADD STAGE_ID3 BIGINT;
    COMMIT WORK;
    CREATE INDEX UT_QUESTIONS_IDX1 ON UT_QUESTIONS (STAGE_ID1);
    CREATE INDEX UT_QUESTIONS_IDX2 ON UT_QUESTIONS (STAGE_ID2);
    CREATE INDEX UT_QUESTIONS_IDX3 ON UT_QUESTIONS (STAGE_ID3);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'QUESTION_ID' AND RDB$RELATION_NAME = 'UT_QUESTION_RELS'}

  CREATE TABLE UT_QUESTION_RELS (
    QUESTION_ID  BIGINT NOT NULL,
    SECTION_ID   BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP
  );
                                                                                
  ALTER TABLE UT_QUESTION_RELS ADD CONSTRAINT PK_UT_QUESTION_RELS PRIMARY KEY (QUESTION_ID, SECTION_ID);
  ALTER TABLE UT_QUESTION_RELS ADD CONSTRAINT FK_UT_QUESTION_RELS_1 FOREIGN KEY (QUESTION_ID) REFERENCES UT_QUESTIONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE UT_QUESTION_RELS ADD CONSTRAINT FK_UT_QUESTION_RELS_2 FOREIGN KEY (SECTION_ID) REFERENCES UT_KIM_CODING_LEVELS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  GRANT ALL ON UT_QUESTION_RELS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'FILE_SIZE' AND RDB$RELATION_NAME = 'UT_QUESTIONS'}

  ALTER TABLE UT_QUESTIONS ADD FILE_SIZE INTEGER;
  ALTER TABLE UT_QUESTIONS ADD K VARCHAR(64);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USER_ID' AND RDB$RELATION_NAME = 'UT_QUESTIONS'}

  ALTER TABLE UT_QUESTIONS ADD USER_ID BIGINT;
  COMMIT WORK;
  ALTER TABLE UT_QUESTIONS ADD CONSTRAINT FK_UT_QUESTIONS_5 FOREIGN KEY (USER_ID) REFERENCES USERS(USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;  
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_QUESTIONS_BI0' AND RDB$RELATION_NAME = 'UT_TEST_VARS'}

  DROP TRIGGER UT_QUESTIONS_BI0;
  DROP TRIGGER UT_QUESTIONS_BU0;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_QUESTIONS_BI0'}

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_QUESTIONS_BI0 FOR UT_QUESTIONS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_QUESTIONS_BU0 FOR UT_QUESTIONS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_ANSWERS'}

    CREATE TABLE UT_ANSWERS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        QUESTION_ID  BIGINT NOT NULL,
        SORT_ORDER   SMALLINT NOT NULL,
        VARIANT      BLOB SUB_TYPE 1 SEGMENT SIZE 80,
        A_LEVEL      SMALLINT,
        OBJ_NAME     VARCHAR(400),
        FAKE_ORDER   SMALLINT DEFAULT 0 NOT NULL,
        SIGNATURE    SMALLINT DEFAULT 0 NOT NULL,
        HSIGNATURE   BIGINT
    );

    ALTER TABLE UT_ANSWERS ADD CONSTRAINT PK_UT_ANSWERS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_ANSWERS ADD CONSTRAINT FK_UT_ANSWERS_1 FOREIGN KEY (QUESTION_ID) REFERENCES UT_QUESTIONS (OBJ_ID) ON DELETE CASCADE;

    GRANT ALL ON UT_ANSWERS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_ANSWERS_BI0 FOR UT_ANSWERS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN,1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_ANSWERS_BU0 FOR UT_ANSWERS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'HSIGNATURE' AND RDB$RELATION_NAME = 'UT_ANSWERS'}

  ALTER TABLE UT_ANSWERS ADD HSIGNATURE BIGINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_TEST_VAR_QUESTIONS'}

    CREATE TABLE UT_TEST_VAR_QUESTIONS (
        OBJ_ID           BIGINT NOT NULL,
        DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL         TIMESTAMP,
        VAR_ID           BIGINT NOT NULL,
        STRUCT_POINT_ID  BIGINT NOT NULL,
        QUESTION_ID      BIGINT NOT NULL,
        ORDER_INDEX      INTEGER NOT NULL
    );                                                                              

    ALTER TABLE UT_TEST_VAR_QUESTIONS ADD CONSTRAINT PK_UT_TEST_VAR_QUESTIONS_1 PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_TEST_VAR_QUESTIONS ADD CONSTRAINT FK_UT_TEST_VAR_QUESTIONS_1 FOREIGN KEY (QUESTION_ID) REFERENCES UT_QUESTIONS (OBJ_ID);
    ALTER TABLE UT_TEST_VAR_QUESTIONS ADD CONSTRAINT FK_UT_TEST_VAR_QUESTIONS_2 FOREIGN KEY (STRUCT_POINT_ID) REFERENCES UT_TEST_STRUCT_POINTS (OBJ_ID);
    ALTER TABLE UT_TEST_VAR_QUESTIONS ADD CONSTRAINT FK_UT_TEST_VAR_QUESTIONS_3 FOREIGN KEY (VAR_ID) REFERENCES UT_TEST_VARS (OBJ_ID) ON DELETE CASCADE;

    GRANT ALL ON UT_TEST_VAR_QUESTIONS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_TEST_VAR_QUESTIONS_BI0 FOR UT_TEST_VAR_QUESTIONS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_TEST_VAR_QUESTIONS_BU0 FOR UT_TEST_VAR_QUESTIONS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_ANSWER_STATES'}

    CREATE TABLE UT_ANSWER_STATES (
        OBJ_ID    INTEGER NOT NULL,
        OBJ_NAME  VARCHAR(100) NOT NULL,
        IS_DEL    SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_ANSWER_STATES ADD CONSTRAINT PK_UT_ANSWER_STATES PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_ANSWER_STATES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (0, 'Зарезервирован', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (10, 'Сформирован', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (30, 'Валидирован', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (21, 'Результат загружен', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (20, 'Отвечен', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (40, 'Запланирован на проверку', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (50, 'Передан на проверку', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (60, 'Результаты проверки получены', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (70, 'Результаты проверки загружены', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (1000, 'Обработан', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (1001, 'Аннулирован', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (80, 'Передан на перепроверку', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (90, 'Результаты перепроверки получены', 0) MATCHING (OBJ_ID);
    UPDATE OR INSERT INTO UT_ANSWER_STATES (OBJ_ID, OBJ_NAME, IS_DEL) VALUES (100, 'Результаты перепроверки загружены', 0) MATCHING (OBJ_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STATE_ID' AND RDB$RELATION_NAME = 'UT_SESSION_STATES'}

    CREATE TABLE UT_SESSION_STATES (
        STATE_ID    INTEGER NOT NULL,
        STATE_NAME  VARCHAR(100) NOT NULL,
        IS_DEL      SMALLINT DEFAULT 0 NOT NULL
    );

    ALTER TABLE UT_SESSION_STATES ADD CONSTRAINT PK_UT_SESSION_STATES PRIMARY KEY (STATE_ID);

    GRANT ALL ON UT_SESSION_STATES TO INISSOFT_ROLE;

    COMMIT WORK;

    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (0, 'Тестирование не проводилось', 0) MATCHING (STATE_ID);
    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (2, 'Тестирование начато', 0) MATCHING (STATE_ID);
    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (1, 'Тестирование зарезервировано', 0) MATCHING (STATE_ID);
    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (100, 'Тестирование завершено', 0) MATCHING (STATE_ID);
    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (101, 'Тестирование отменено', 0) MATCHING (STATE_ID);
    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (102, 'Удален с тестирования', 0) MATCHING (STATE_ID);
    UPDATE OR INSERT INTO UT_SESSION_STATES (STATE_ID, STATE_NAME, IS_DEL) VALUES (10, 'Тестирование пройдено', 0) MATCHING (STATE_ID);

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_TEST_VARS'}

    CREATE TABLE UT_EXAM_TEST_VARS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        EXAM_ID      BIGINT NOT NULL,
        TEST_VAR_ID  BIGINT NOT NULL
    );

    ALTER TABLE UT_EXAM_TEST_VARS ADD CONSTRAINT PK_UT_EXAM_TEST_VARS PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_EXAM_TEST_VARS ADD CONSTRAINT FK_UT_EXAM_TEST_VARS_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_EXAM_TEST_VARS ADD CONSTRAINT FK_UT_EXAM_TEST_VARS_2 FOREIGN KEY (TEST_VAR_ID) REFERENCES UT_TEST_VARS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_EXAM_TEST_VARS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_EXAM_TEST_VARS_BI0 FOR UT_EXAM_TEST_VARS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BASEGEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_EXAM_TEST_VARS_BU0 FOR UT_EXAM_TEST_VARS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_SESSIONS'}

    CREATE GENERATOR UT_SESSION_GEN;

    CREATE TABLE UT_SESSIONS (
        OBJ_ID           BIGINT NOT NULL,
        DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL         TIMESTAMP,
        ED_ID            BIGINT NOT NULL,
        PERSON_ID        BIGINT,
        VARIANT_ID       BIGINT,
        VARIANT_INDEX    SMALLINT,
        STARTED_AT       TIMESTAMP,
        COMPLETED_AT     TIMESTAMP,
        STATE_ID         INTEGER,
        DURATION         INTEGER DEFAULT 0,
        RAW_RESULT       INTEGER,
        FINAL_RESULT_ID  BIGINT,
        TEST_PROGRESS    SMALLINT DEFAULT 0 NOT NULL,
        NETWORK_DATA     VARCHAR(100)
    );

    ALTER TABLE UT_SESSIONS ADD CONSTRAINT PK_UT_SESSIONS PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_SESSIONS ADD CONSTRAINT FK_UT_SESSIONS_1 FOREIGN KEY (FINAL_RESULT_ID) REFERENCES CJ2_MARK_TYPE (MARK_TYPE_ID) ON UPDATE CASCADE;
    ALTER TABLE UT_SESSIONS ADD CONSTRAINT FK_UT_SESSIONS_2 FOREIGN KEY (ED_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_SESSIONS ADD CONSTRAINT FK_UT_SESSIONS_3 FOREIGN KEY (VARIANT_ID) REFERENCES UT_EXAM_TEST_VARS (OBJ_ID) ON UPDATE CASCADE;
    ALTER TABLE UT_SESSIONS ADD CONSTRAINT FK_UT_SESSIONS_4 FOREIGN KEY (STATE_ID) REFERENCES UT_SESSION_STATES (STATE_ID) ON UPDATE CASCADE;
    ALTER TABLE UT_SESSIONS ADD CONSTRAINT FK_UT_SESSIONS_5 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

    GRANT ALL ON UT_SESSIONS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_SESSIONS_BI0 FOR UT_SESSIONS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_SESSION_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_SESSIONS_BU0 FOR UT_SESSIONS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'VARIANT_INDEX' AND RDB$RELATION_NAME = 'UT_SESSIONS'}

    ALTER TABLE UT_SESSIONS ADD VARIANT_INDEX SMALLINT;
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_EXAM_QUESTIONS'}

  CREATE GENERATOR UT_QUESTIONS_GEN;
  GRANT USAGE ON SEQUENCE UT_QUESTIONS_GEN TO INISSOFT_ROLE;

  CREATE TABLE UT_EXAM_QUESTIONS (
    OBJ_ID         BIGINT NOT NULL,
    DATE_ADD       TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL       TIMESTAMP,
    EXAM_ID        BIGINT,
    QUESTION_ID    BIGINT,
    VARIANT_INDEX  SMALLINT,
    SORT_INDEX     SMALLINT
  );

  ALTER TABLE UT_EXAM_QUESTIONS ADD CONSTRAINT PK_UT_EXAM_QUESTIONS PRIMARY KEY (OBJ_ID);
  ALTER TABLE UT_EXAM_QUESTIONS ADD CONSTRAINT FK_UT_EXAM_QUESTIONS_1 FOREIGN KEY (EXAM_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE UT_EXAM_QUESTIONS ADD CONSTRAINT FK_UT_EXAM_QUESTIONS_2 FOREIGN KEY (QUESTION_ID) REFERENCES UT_QUESTIONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX UT_EXAM_QUESTIONS_IDX1 ON UT_EXAM_QUESTIONS (EXAM_ID, VARIANT_INDEX, SORT_INDEX);
  CREATE INDEX UT_EXAM_QUESTIONS_IDX2 ON UT_EXAM_QUESTIONS (EXAM_ID, QUESTION_ID);
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER UT_EXAM_QUESTIONS_BI0 FOR UT_EXAM_QUESTIONS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_QUESTIONS_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON UT_EXAM_QUESTIONS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_SESSION_QUESTIONS'}

    CREATE GENERATOR UT_ANSWERS_GEN;

    CREATE TABLE UT_SESSION_QUESTIONS (
        OBJ_ID        BIGINT NOT NULL,
        DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL      TIMESTAMP,
        SESSION_ID    BIGINT,
        QUESTION_ID   BIGINT,
        QUESTION_RAW  BIGINT,
        ANSWER_DATA   VARCHAR(4000),
        RAW_RESULT    INTEGER,
        METADATA_ID   VARCHAR(40),
        STATE_ID      INTEGER DEFAULT 0 NOT NULL,
        NETWORK_DATA  VARCHAR(100)
    );

    ALTER TABLE UT_SESSION_QUESTIONS ADD CONSTRAINT PK_UT_SESSION_QUESTIONS PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_SESSION_QUESTIONS ADD CONSTRAINT FK_UT_SESSION_QUESTIONS_1 FOREIGN KEY (SESSION_ID) REFERENCES UT_SESSIONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_SESSION_QUESTIONS ADD CONSTRAINT FK_UT_SESSION_QUESTIONS_2 FOREIGN KEY (QUESTION_ID) REFERENCES UT_TEST_VAR_QUESTIONS (OBJ_ID) ON UPDATE CASCADE;
    ALTER TABLE UT_SESSION_QUESTIONS ADD CONSTRAINT FK_UT_SESSION_QUESTIONS_3 FOREIGN KEY (STATE_ID) REFERENCES UT_ANSWER_STATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE UT_SESSION_QUESTIONS ADD CONSTRAINT FK_UT_SESSION_QUESTIONS_4 FOREIGN KEY (QUESTION_RAW) REFERENCES UT_EXAM_QUESTIONS (OBJ_ID) ON UPDATE CASCADE;

    GRANT ALL ON UT_SESSION_QUESTIONS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_SESSION_QUESTIONS_BI0 FOR UT_SESSION_QUESTIONS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ANSWERS_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_SESSION_QUESTIONS_BU0 FOR UT_SESSION_QUESTIONS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'QUESTION_RAW' AND RDB$RELATION_NAME = 'UT_SESSION_QUESTIONS'}

  ALTER TABLE UT_SESSION_QUESTIONS ADD QUESTION_RAW BIGINT;
  ALTER TABLE UT_SESSION_QUESTIONS ADD CONSTRAINT FK_UT_SESSION_QUESTIONS_4 FOREIGN KEY (QUESTION_RAW) REFERENCES UT_EXAM_QUESTIONS (OBJ_ID) ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_SESSION_MARKUPS'}

    CREATE TABLE UT_SESSION_MARKUPS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        RESULT_ID    BIGINT NOT NULL,
        MARK_TYPE    SMALLINT NOT NULL,
        INDEX_X1     INTEGER,
        INDEX_Y1     INTEGER,
        INDEX_X2     INTEGER,
        INDEX_Y2     INTEGER,
        TEXT_VALUE   VARCHAR(200)
    );

    ALTER TABLE UT_SESSION_MARKUPS ADD CONSTRAINT PK_UT_SESSION_MARKUPS PRIMARY KEY (OBJ_ID);

    GRANT ALL ON UT_SESSION_MARKUPS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_SESSION_MARKUPS_BI0 FOR UT_SESSION_MARKUPS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ANSWERS_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_SESSION_MARKUPS_BU0 FOR UT_SESSION_MARKUPS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_BLANKS'}

    CREATE TABLE UT_BLANKS (
        OBJ_ID          BIGINT NOT NULL,
        DATE_ADD        TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL        TIMESTAMP,
        PACKAGE_ID      BIGINT NOT NULL,
        BLANK_TYPE      BIGINT,
        BLANK_SIDE      SMALLINT,
        PARENT_ID       BIGINT,
        NEXT_BLANK_ID   BIGINT,
        SESSION_ID      BIGINT,
        FILE_ID         VARCHAR(40),
        FILE_HASH       VARCHAR(40) CHARACTER SET ASCII,
        BARCODE_DATA    VARCHAR(128) CHARACTER SET ASCII,
        BARCODE2_DATA   VARCHAR(128) CHARACTER SET ASCII,
        BARCODE3_DATA   VARCHAR(128) CHARACTER SET ASCII,
        STATE_ID        SMALLINT DEFAULT 0 NOT NULL,
        RCV_STATION_ID  VARCHAR(40) CHARACTER SET ASCII,
        VER_USER_ID     BIGINT
    );

    ALTER TABLE UT_BLANKS ADD CONSTRAINT PK_UT_BLANKS PRIMARY KEY (OBJ_ID);
    CREATE INDEX UT_BLANKS_IDX1 ON UT_BLANKS (FILE_ID);
    CREATE INDEX UT_BLANKS_IDX2 ON UT_BLANKS (FILE_HASH);

    GRANT ALL ON UT_BLANKS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_BLANKS_BI0 FOR UT_BLANKS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_BLANK_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'UT_BLANKS_BU0' AND RDB$RELATION_NAME = 'UT_BLANKS'}

    DROP TRIGGER UT_BLANKS_BU0;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_BLANK_ATTRS'}

    CREATE GENERATOR UT_ATTR_GEN;

    CREATE TABLE UT_BLANK_ATTRS (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        BLANK_ID     BIGINT NOT NULL,
        ATTR_NAME    VARCHAR(40) NOT NULL,
        ATTR_VALUE   VARCHAR(100),
        SRC_VALUE    VARCHAR(100),
        STATE_ID     SMALLINT DEFAULT 0 NOT NULL,
        USER_ID      BIGINT
    );

    ALTER TABLE UT_BLANK_ATTRS ADD CONSTRAINT UT_BLANK_ATTRS_PK PRIMARY KEY (OBJ_ID);
    ALTER TABLE UT_BLANK_ATTRS ADD CONSTRAINT UT_BLANK_ATTRS_FK1 FOREIGN KEY (BLANK_ID) REFERENCES UT_BLANKS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    CREATE INDEX UT_BLANK_ATTRS_IDX1 ON UT_BLANK_ATTRS (OBJ_ID, ATTR_NAME, DATE_DEL);

    GRANT ALL ON UT_BLANK_ATTRS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER UT_BLANK_ATTRS_BI0 FOR UT_BLANK_ATTRS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    begin
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ATTR_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    end
    ^

    CREATE OR ALTER TRIGGER UT_BLANK_ATTRS_BU0 FOR UT_BLANK_ATTRS
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'SRC_VALUE' AND RDB$RELATION_NAME = 'UT_BLANK_ATTRS'}

    ALTER TABLE UT_BLANK_ATTRS ADD SRC_VALUE VARCHAR(100);
    COMMIT WORK;

{$ENDIF}

/* Книга регистрации документов об образовании */

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CERT_DATA'}

    CREATE GENERATOR GEN_CERT_ID;

    CREATE TABLE CERT_DATA (
        OBJ_ID       BIGINT NOT NULL,
        DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
        DATE_DEL     TIMESTAMP,
        PUPIL_ID     BIGINT,
        NAME_FIRST   VARCHAR(400),
        NAME_MID     VARCHAR(400),
        NAME_LAST    VARCHAR(400),
        BIRTH_DATE   DATE,
        YEAR_ACCEPT  SMALLINT,
        YEAR_LEAVE   SMALLINT,
        SEX          BIGINT,
        BLANK_STATE  BIGINT,
        CERT_TYPE    BIGINT,
        CERT_KIND    BIGINT,
        STAGE_ID     BIGINT,
        ISSUE_DATE   DATE,
        CERT_SERIE   VARCHAR(40),
        CERT_NUMBER  VARCHAR(40),
        IS_OWN       SMALLINT DEFAULT 0 NOT NULL,
        ISSUED_BY    VARCHAR(1000),
        PARENT_ID    BIGINT,
        USER_ADD     BIGINT,
        USER_DEL     BIGINT,
        SNILS        VARCHAR(40),
        CITIZENSHIP  BIGINT,
        BIRTH_PLACE  VARCHAR(200)
    );

    ALTER TABLE CERT_DATA ADD CONSTRAINT PK_CERT_DATA PRIMARY KEY (OBJ_ID);
    ALTER TABLE CERT_DATA ADD CONSTRAINT FK_CERT_DATA_1 FOREIGN KEY (SEX) REFERENCES LISTVALS (LISTVAL_ID);
    ALTER TABLE CERT_DATA ADD CONSTRAINT FK_CERT_DATA_2 FOREIGN KEY (BLANK_STATE) REFERENCES LISTVALS (LISTVAL_ID);
    ALTER TABLE CERT_DATA ADD CONSTRAINT FK_CERT_DATA_3 FOREIGN KEY (CERT_TYPE) REFERENCES LISTVALS (LISTVAL_ID);
    ALTER TABLE CERT_DATA ADD CONSTRAINT FK_CERT_DATA_4 FOREIGN KEY (CERT_KIND) REFERENCES LISTVALS (LISTVAL_ID);
    ALTER TABLE CERT_DATA ADD CONSTRAINT FK_CERT_DATA_5 FOREIGN KEY (STAGE_ID) REFERENCES LISTVALS (LISTVAL_ID);

    GRANT ALL ON CERT_DATA TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER CERT_DATA_BI0 FOR CERT_DATA
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_CERT_ID, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    CREATE OR ALTER TRIGGER CERT_DATA_BU0 FOR CERT_DATA
    ACTIVE BEFORE UPDATE POSITION 0
    AS
    begin
      NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
    end
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}

    CREATE GENERATOR GEN_MOVEMENTS_ID;

    CREATE TABLE PERSON_MOVEMENTS (
      OBJ_ID          BIGINT NOT NULL,
      DATE_ADD        TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
      DATE_MODIFY     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
      DATE_DEL        TIMESTAMP,
      PERSON_ID       BIGINT NOT NULL,
      GROUP_ID        BIGINT NOT NULL,
      REASON_IN       BIGINT,
      DATE_IN         DATE NOT NULL,
      DATE_OUT        DATE,
      STAGE_ID        BIGINT,
      ORDER_DATE_IN   DATE,
      ORDER_NUM_IN    VARCHAR(40),
      ORDER_DATE_OUT  DATE,
      ORDER_NUM_OUT   VARCHAR(40),
      ORDER_ID_IN     BIGINT,
      ORDER_ID_OUT    BIGINT,
      NAME_IN         VARCHAR(400),
      REASON_OUT      BIGINT,
      USER_IN         BIGINT,
      USER_OUT        BIGINT,
      TYPE_IN         BIGINT,
      IS_VD           SMALLINT DEFAULT 0 NOT NULL,
      SOURCE_IN       BIGINT DEFAULT 903 NOT NULL,
      SOURCE_OUT      BIGINT,
      PLAN_STAGES     SMALLINT,
      STAGE_YEAR      SMALLINT,
      GROUP_TYPE_ID   BIGINT,
      LEVEL_ID        BIGINT,
      OU_ID           BIGINT
    );

    ALTER TABLE PERSON_MOVEMENTS ADD CONSTRAINT PK_PERSON_MOVEMENTS PRIMARY KEY (OBJ_ID);
    ALTER TABLE PERSON_MOVEMENTS ADD CONSTRAINT FK_PERSON_MOVEMENTS_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    ALTER TABLE PERSON_MOVEMENTS ADD CONSTRAINT FK_PERSON_MOVEMENTS_2 FOREIGN KEY (GROUP_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
    CREATE INDEX PERSON_MOVEMENTS_IDX1 ON PERSON_MOVEMENTS (PERSON_ID, DATE_OUT);
    CREATE INDEX PERSON_MOVEMENTS_IDX2 ON PERSON_MOVEMENTS (DATE_OUT);
    CREATE INDEX PERSON_MOVEMENTS_IDX3 ON PERSON_MOVEMENTS (DATE_MODIFY);
    CREATE INDEX PERSON_MOVEMENTS_IDX4 ON PERSON_MOVEMENTS (PERSON_ID, GROUP_ID, DATE_IN, DATE_OUT);
    CREATE INDEX PERSON_MOVEMENTS_IDX5 ON PERSON_MOVEMENTS (OBJ_ID, REASON_IN);
    CREATE INDEX PERSON_MOVEMENTS_IDX6 ON PERSON_MOVEMENTS (OBJ_ID, REASON_OUT);
    CREATE INDEX PERSON_MOVEMENTS_IDX7 ON PERSON_MOVEMENTS (OBJ_ID, STAGE_ID, DATE_IN, DATE_OUT);
    CREATE INDEX PERSON_MOVEMENTS_IDX8 ON PERSON_MOVEMENTS (GROUP_TYPE_ID,DATE_IN,DATE_OUT);
    CREATE INDEX PERSON_MOVEMENTS_IDX9 ON PERSON_MOVEMENTS (OBJ_ID, LEVEL_ID, DATE_IN, DATE_OUT);

    GRANT ALL ON PERSON_MOVEMENTS TO INISSOFT_ROLE;

    COMMIT WORK;

    SET TERM ^ ;

    CREATE OR ALTER TRIGGER PERSON_MOVEMENTS_BI0 FOR PERSON_MOVEMENTS
    ACTIVE BEFORE INSERT POSITION 0
    AS
    BEGIN
      IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_MOVEMENTS_ID, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ^

    SET TERM ; ^

    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STAGE_ID' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD STAGE_ID BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'REASON_OUT' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD REASON_OUT BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USER_IN' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD USER_IN BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'USER_OUT' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD USER_OUT BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'TYPE_IN' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD TYPE_IN BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'IS_VD' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD IS_VD SMALLINT DEFAULT 0 NOT NULL;
    ALTER TABLE PERSON_MOVEMENTS ADD SOURCE_IN BIGINT DEFAULT 903 NOT NULL;
    ALTER TABLE PERSON_MOVEMENTS ADD SOURCE_OUT BIGINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'PLAN_STAGES' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD PLAN_STAGES SMALLINT;
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'STAGE_YEAR' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
    ALTER TABLE PERSON_MOVEMENTS ADD STAGE_YEAR SMALLINT;
    ALTER TABLE PERSON_MOVEMENTS ADD GROUP_TYPE_ID BIGINT;
    COMMIT WORK;
    CREATE INDEX PERSON_MOVEMENTS_IDX8 ON PERSON_MOVEMENTS (GROUP_TYPE_ID,DATE_IN,DATE_OUT);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LEVEL_ID' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
  ALTER TABLE PERSON_MOVEMENTS ADD LEVEL_ID BIGINT;
  COMMIT WORK;
  CREATE INDEX PERSON_MOVEMENTS_IDX9 ON PERSON_MOVEMENTS (OBJ_ID, LEVEL_ID, DATE_IN, DATE_OUT);
  COMMIT WORK;
{$ENDIF}


{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OU_ID' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
  ALTER TABLE PERSON_MOVEMENTS ADD OU_ID BIGINT;
  COMMIT WORK;
{$ENDIF}


{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX1'}
    CREATE INDEX PERSON_MOVEMENTS_IDX1 ON PERSON_MOVEMENTS (PERSON_ID, DATE_OUT);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX2'}
    CREATE INDEX PERSON_MOVEMENTS_IDX2 ON PERSON_MOVEMENTS (DATE_OUT);
    COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX3'}
  CREATE INDEX PERSON_MOVEMENTS_IDX3 ON PERSON_MOVEMENTS (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX4'}
  CREATE INDEX PERSON_MOVEMENTS_IDX4 ON PERSON_MOVEMENTS (PERSON_ID, GROUP_ID, DATE_IN, DATE_OUT);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX5'}
  CREATE INDEX PERSON_MOVEMENTS_IDX5 ON PERSON_MOVEMENTS (OBJ_ID, REASON_IN);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX6'}
  CREATE INDEX PERSON_MOVEMENTS_IDX6 ON PERSON_MOVEMENTS (OBJ_ID, REASON_OUT);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'PERSON_MOVEMENTS_IDX7'}
  CREATE INDEX PERSON_MOVEMENTS_IDX7 ON PERSON_MOVEMENTS (OBJ_ID, STAGE_ID, DATE_IN, DATE_OUT);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ADAPT_ID' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}
  ALTER TABLE PERSON_MOVEMENTS ADD ADAPT_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_SESSION_CHECKS'}

  CREATE TABLE UT_SESSION_CHECKS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    QUESTION_ID  BIGINT NOT NULL,
    EXPERT_ID    BIGINT,
    LEVEL_ID     SMALLINT DEFAULT 1 NOT NULL,
    STATE_ID     INTEGER DEFAULT 0 NOT NULL,
    RAW_RESULT   INTEGER,
    QUEUE_TIME   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
  );

  ALTER TABLE UT_SESSION_CHECKS ADD CONSTRAINT PK_UT_SESSION_CHECKS PRIMARY KEY (OBJ_ID);
  ALTER TABLE UT_SESSION_CHECKS ADD CONSTRAINT FK_UT_SESSION_CHECKS_1 FOREIGN KEY (QUESTION_ID) REFERENCES UT_SESSION_QUESTIONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE UT_SESSION_CHECKS ADD CONSTRAINT FK_UT_SESSION_CHECKS_2 FOREIGN KEY (EXPERT_ID) REFERENCES UT_EXPERTS (EXPERT_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE UT_SESSION_CHECKS ADD CONSTRAINT FK_UT_SESSION_CHECKS_3 FOREIGN KEY (STATE_ID) REFERENCES UT_ANSWER_STATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  GRANT ALL ON UT_SESSION_CHECKS TO INISSOFT_ROLE;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER UT_SESSION_CHECKS_BI0 FOR UT_SESSION_CHECKS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  BEGIN
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ANSWERS_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  END
  ^

  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_SESSION_CHECK_RES'}

  CREATE TABLE UT_SESSION_CHECK_RES (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    CHECK_ID     BIGINT NOT NULL,
    CRITERIA_ID  SMALLINT NOT NULL,
    RAW_RESULT   INTEGER
  );

  ALTER TABLE UT_SESSION_CHECK_RES ADD CONSTRAINT PK_UT_SESSION_CHECK_RES PRIMARY KEY (OBJ_ID);
  ALTER TABLE UT_SESSION_CHECK_RES ADD CONSTRAINT FK_UT_SESSION_CHECK_RES_1 FOREIGN KEY (CHECK_ID) REFERENCES UT_SESSION_CHECKS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  GRANT ALL ON UT_SESSION_CHECK_RES TO INISSOFT_ROLE;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER UT_SESSION_CHECK_RES_BI0 FOR UT_SESSION_CHECK_RES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  BEGIN
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_ANSWERS_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  END
  ^

  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'UT_TEST_VAR_FILES'}

  CREATE GENERATOR UT_FILE_GEN;

  CREATE TABLE UT_TEST_VAR_FILES (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    VAR_ID        BIGINT NOT NULL,
    OBJ_NAME      VARCHAR(1000) NOT NULL,
    FILE_HASH     VARCHAR(64) NOT NULL,
    CONTENT_TYPE  VARCHAR(255) NOT NULL,
    CONTENT_DATA  BLOB SUB_TYPE 0 SEGMENT SIZE 4096,
    ATTR_MASK     INTEGER DEFAULT 0 NOT NULL
  );

  ALTER TABLE UT_TEST_VAR_FILES ADD CONSTRAINT PK_UT_TEST_VAR_FILES_1 PRIMARY KEY (OBJ_ID);
  ALTER TABLE UT_TEST_VAR_FILES ADD CONSTRAINT FK_UT_TEST_VAR_FILES_1 FOREIGN KEY (VAR_ID) REFERENCES UT_TEST_VARS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  GRANT ALL ON UT_TEST_VAR_FILES TO INISSOFT_ROLE;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER UT_TEST_VAR_FILES_BI0 FOR UT_TEST_VAR_FILES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(UT_FILE_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'FILE_HASH' AND F.RDB$RELATION_NAME = 'UT_TEST_VAR_FILES' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 40}

    ALTER TABLE UT_TEST_VAR_FILES ALTER COLUMN FILE_HASH TYPE VARCHAR(64);
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'CONTENT_TYPE' AND F.RDB$RELATION_NAME = 'UT_TEST_VAR_FILES' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH IN (10, 40)}

    ALTER TABLE UT_TEST_VAR_FILES ALTER COLUMN CONTENT_TYPE TYPE VARCHAR(255);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'GEN_SYNC_LOG'}

  CREATE GENERATOR GEN_SYNC_LOG;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'SYNC_LOG'}

  CREATE TABLE SYNC_LOG (
      OBJ_ID       BIGINT NOT NULL,
      DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
      PERSON_ID    BIGINT NOT NULL,
      STATE_ID     SMALLINT NOT NULL,
      MSG          VARCHAR(1000),
      VER_MSG      VARCHAR(1000)
  );

  COMMIT WORK;

  ALTER TABLE SYNC_LOG ADD CONSTRAINT PK_SYNC_LOG PRIMARY KEY (OBJ_ID);
  ALTER TABLE SYNC_LOG ADD CONSTRAINT FK_SYNC_LOG_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER SYNC_LOG_BI0 FOR SYNC_LOG
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_SYNC_LOG, 1);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON SYNC_LOG TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'VER_MSG' AND RDB$RELATION_NAME = 'SYNC_LOG'}

  ALTER TABLE SYNC_LOG ADD VER_MSG VARCHAR(1000) CHARACTER SET UTF8 COLLATE UTF8;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PLAN_SUBJECTS'}

  CREATE GENERATOR PLAN_GEN;

  CREATE TABLE PLAN_SUBJECTS (
    OBJ_ID        BIGINT NOT NULL,
    PLAN_ID       BIGINT NOT NULL,
    SUBJECT_ID    BIGINT,
    FIELD_ID      BIGINT,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    SORT_INDEX    SMALLINT DEFAULT 0 NOT NULL,
    PARENT_ID     BIGINT,
    LEVEL_INDEX   SMALLINT DEFAULT 0 NOT NULL,
    GLOBAL_INDEX  INTEGER,
    IS_ADV        SMALLINT DEFAULT 0 NOT NULL,
    ROW_TYPE      SMALLINT DEFAULT 0 NOT NULL,
    SRC_SUBJECT_ID  BIGINT,
    IS_STM        SMALLINT DEFAULT 0 NOT NULL ,
    ROW_CODE      VARCHAR(40)
  );

  CREATE TABLE PLAN_LOADS (
    OBJ_ID          BIGINT NOT NULL,
    SUBJECT_ID      BIGINT NOT NULL,
    STAGE_ID        BIGINT,
    DATE_ADD        TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL        TIMESTAMP,
    WEEKS           SMALLINT,
    LOAD_HOURS      FLOAT,
    LOAD_HOURS_S1   FLOAT,
    LOAD_HOURS_S2   FLOAT,
    CONTROL_Q1      BIGINT,
    CONTROL_Q2      BIGINT,
    HOURS_THEORY1   FLOAT,
    HOURS_PR1       FLOAT,
    HOURS_DX1       FLOAT,
    HOURS_IND1      FLOAT,
    HOURS_MAX       FLOAT,
    HOURS_CR1       FLOAT,
    HOURS_ATT1      FLOAT,
    HOURS_GIA       FLOAT,
    HOURS_REST      FLOAT
  );

  COMMIT WORK;

  ALTER TABLE PLAN_SUBJECTS ADD CONSTRAINT PK_PLAN_SUBJECTS PRIMARY KEY (OBJ_ID);
  ALTER TABLE PLAN_SUBJECTS ADD CONSTRAINT FK_PLAN_SUBJECTS_1 FOREIGN KEY (FIELD_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PLAN_SUBJECTS ADD CONSTRAINT FK_PLAN_SUBJECTS_2 FOREIGN KEY (PLAN_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PLAN_SUBJECTS ADD CONSTRAINT FK_PLAN_SUBJECTS_3 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  ALTER TABLE PLAN_LOADS ADD CONSTRAINT PK_PLAN_LOADS PRIMARY KEY (OBJ_ID);
  ALTER TABLE PLAN_LOADS ADD CONSTRAINT FK_PLAN_LOADS_1 FOREIGN KEY (SUBJECT_ID) REFERENCES PLAN_SUBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PLAN_LOADS ADD CONSTRAINT FK_PLAN_LOADS_2 FOREIGN KEY (STAGE_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PLAN_LOADS ADD CONSTRAINT FK_PLAN_LOADS_3 FOREIGN KEY (CONTROL_Q1) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PLAN_LOADS ADD CONSTRAINT FK_PLAN_LOADS_4 FOREIGN KEY (CONTROL_Q2) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER PLAN_SUBJECTS_BI0 FOR PLAN_SUBJECTS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(PLAN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  CREATE OR ALTER TRIGGER PLAN_LOADS_BI0 FOR PLAN_LOADS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(PLAN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  COMMIT WORK;

  GRANT ALL ON PLAN_SUBJECTS TO INISSOFT_ROLE;
  GRANT ALL ON PLAN_LOADS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'ROW_CODE' AND RDB$RELATION_NAME = 'PLAN_SUBJECTS'}

  ALTER TABLE PLAN_SUBJECTS ADD ROW_CODE VARCHAR(40);
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'LOAD_HOURS_OBL' AND RDB$RELATION_NAME = 'PLAN_LOADS'}

  ALTER TABLE PLAN_LOADS DROP LOAD_HOURS_OBL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'HOURS_THEORY1' AND RDB$RELATION_NAME = 'PLAN_LOADS'}

  ALTER TABLE PLAN_LOADS ADD HOURS_THEORY1 FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_PR1 FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_DX1 FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_IND1 FLOAT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'HOURS_MAX' AND RDB$RELATION_NAME = 'PLAN_LOADS'}

  ALTER TABLE PLAN_LOADS ADD HOURS_MAX FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_CR1 FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_ATT1 FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_GIA FLOAT;
  ALTER TABLE PLAN_LOADS ADD HOURS_REST FLOAT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_STM' AND RDB$RELATION_NAME = 'PLAN_SUBJECTS'}

  ALTER TABLE PLAN_SUBJECTS ADD IS_STM SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PLAN_RESOURCES'}

  CREATE TABLE PLAN_RESOURCES (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LOAD_ID      BIGINT NOT NULL,
    RES_TYPE_ID  SMALLINT NOT NULL,
    RES_ID       BIGINT NOT NULL,
    QTY          DOUBLE PRECISION DEFAULT 0 NOT NULL
  );

  ALTER TABLE PLAN_RESOURCES ADD CONSTRAINT PK_PLAN_RESOURCES PRIMARY KEY (OBJ_ID);
  ALTER TABLE PLAN_RESOURCES ADD CONSTRAINT FK_PLAN_RESOURCES_1 FOREIGN KEY (LOAD_ID) REFERENCES PLAN_LOADS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PLAN_RESOURCES ADD CONSTRAINT FK_PLAN_RESOURCES_2 FOREIGN KEY (RES_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER PLAN_RESOURCES_BI0 FOR PLAN_RESOURCES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(PLAN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON PLAN_RESOURCES TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_AUDIT'}

  CREATE GENERATOR CJ2_AUDIT_GEN;

  CREATE TABLE CJ2_AUDIT (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    CJ_ID         BIGINT NOT NULL,
    OWNER_ID      BIGINT NOT NULL,
    TEACHER_ID    BIGINT NOT NULL,
    MSG_TEXT      VARCHAR(1000),
    STATE_ID      SMALLINT,
    RESOLVED_AT   TIMESTAMP,
    CONFIRMED_AT  TIMESTAMP,
    PARENT_ID     BIGINT,
    USER_DEL      BIGINT,
    BOT_STATUS SMALLINT DEFAULT 0 NOT NULL  
  );

  ALTER TABLE CJ2_AUDIT ADD CONSTRAINT PK_CJ2_AUDIT PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_AUDIT ADD CONSTRAINT FK_CJ2_AUDIT_1 FOREIGN KEY (OWNER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_AUDIT ADD CONSTRAINT FK_CJ2_AUDIT_2 FOREIGN KEY (TEACHER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_AUDIT ADD CONSTRAINT FK_CJ2_AUDIT_3 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_AUDIT_BI0 FOR CJ2_AUDIT
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(CJ2_AUDIT_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_AUDIT_BU0 FOR CJ2_AUDIT
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
   ^

  SET TERM ; ^

  GRANT ALL ON CJ2_AUDIT TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'BOT_STATUS' AND RDB$RELATION_NAME = 'CJ2_AUDIT'}

  ALTER TABLE CJ2_AUDIT ADD BOT_STATUS SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CEC_TYPES'}

  CREATE TABLE CEC_TYPES (
    OBJ_ID   SMALLINT NOT NULL,
    IS_DEL   SMALLINT DEFAULT 0 NOT NULL,
    CAPTION  VARCHAR(400)
  );

  ALTER TABLE CEC_TYPES ADD CONSTRAINT PK_CEC_TYPES PRIMARY KEY (OBJ_ID);  
  GRANT ALL ON CEC_TYPES TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

UPDATE OR INSERT INTO CEC_TYPES (OBJ_ID, IS_DEL, CAPTION) VALUES (0, 0, 'ЕГЭ') MATCHING (OBJ_ID);
UPDATE OR INSERT INTO CEC_TYPES (OBJ_ID, IS_DEL, CAPTION) VALUES (1, 0, 'ОГЭ') MATCHING (OBJ_ID);
UPDATE OR INSERT INTO CEC_TYPES (OBJ_ID, IS_DEL, CAPTION) VALUES (9999, 0, 'Региональный') MATCHING (OBJ_ID);
UPDATE OR INSERT INTO CEC_TYPES (OBJ_ID, IS_DEL, CAPTION) VALUES (10000, 0, 'ПЭС') MATCHING (OBJ_ID);
UPDATE OR INSERT INTO CEC_TYPES (OBJ_ID, IS_DEL, CAPTION) VALUES (10100, 0, 'Дидактические единицы') MATCHING (OBJ_ID);
COMMIT WORK;

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CEC'}

  CREATE GENERATOR CEC_GEN;

  CREATE TABLE CEC (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    CAPTION      VARCHAR(400) NOT NULL,
    SUBJECT_ID   BIGINT NOT NULL,
    TYPE_ID      SMALLINT NOT NULL,
    USER_ID      BIGINT
  );

  ALTER TABLE CEC ADD CONSTRAINT PK_CEC PRIMARY KEY (OBJ_ID);
  ALTER TABLE CEC ADD CONSTRAINT FK_CEC_1 FOREIGN KEY (TYPE_ID) REFERENCES CEC_TYPES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CEC_BI0 FOR CEC
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(CEC_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON CEC TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CEC_ITEMS'}

  CREATE TABLE CEC_ITEMS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    CEC_ID       BIGINT NOT NULL,
    SORT_INDEX   SMALLINT,
    CODE         VARCHAR(40) NOT NULL,
    CAPTION      VARCHAR(400),
    "DESC"       VARCHAR(1000),
    MASTER_ID    VARCHAR(200),
    PARENT_ID    BIGINT,
    LEVEL_INDEX  SMALLINT DEFAULT 0 NOT NULL,
    STAGE_ID     BIGINT,
    SUBJECT_ID   BIGINT,
    UMK_NAME     VARCHAR(400),
    DE_TYPE_ID   BIGINT,
    SOURCE_NAME  VARCHAR(200),
    AUTHOR_NAME  VARCHAR(200)
  );

  ALTER TABLE CEC_ITEMS ADD CONSTRAINT PK_CEC_ITEMS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CEC_ITEMS ADD CONSTRAINT FK_CEC_ITEMS_1 FOREIGN KEY (CEC_ID) REFERENCES CEC (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CEC_ITEMS_BI0 FOR CEC_ITEMS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(CEC_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON CEC_ITEMS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'STAGE_ID' AND RDB$RELATION_NAME = 'CEC_ITEMS'}

  ALTER TABLE CEC_ITEMS ADD STAGE_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS RF
  JOIN RDB$FIELDS F ON F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE AND F.RDB$FIELD_TYPE = 16
  WHERE RF.RDB$FIELD_NAME = 'MASTER_ID' AND RF.RDB$RELATION_NAME = 'CEC_ITEMS'}

  ALTER TABLE CEC_ITEMS ALTER COLUMN MASTER_ID TYPE VARCHAR(200) CHARACTER SET ASCII;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SUBJECT_ID' AND RDB$RELATION_NAME = 'CEC_ITEMS'}

  ALTER TABLE CEC_ITEMS ADD SUBJECT_ID BIGINT;
  ALTER TABLE CEC_ITEMS ADD UMK_NAME VARCHAR(400);
  ALTER TABLE CEC_ITEMS ADD DE_TYPE_ID BIGINT;
  ALTER TABLE CEC_ITEMS ADD SOURCE_NAME VARCHAR(200);
  ALTER TABLE CEC_ITEMS ADD AUTHOR_NAME VARCHAR(200);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PTP_LESSON_CEC'}

  CREATE TABLE PTP_LESSON_CEC (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LESSON_ID    BIGINT NOT NULL,
    CEC_ITEM_ID  BIGINT NOT NULL
  );

  ALTER TABLE PTP_LESSON_CEC ADD CONSTRAINT PK_PTP_LESSON_CEC PRIMARY KEY (OBJ_ID);
  ALTER TABLE PTP_LESSON_CEC ADD CONSTRAINT FK_PTP_LESSON_CEC_1 FOREIGN KEY (LESSON_ID) REFERENCES PTP_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PTP_LESSON_CEC ADD CONSTRAINT FK_PTP_LESSON_CEC_2 FOREIGN KEY (CEC_ITEM_ID) REFERENCES CEC_ITEMS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER PTP_LESSON_CEC_BI0 FOR PTP_LESSON_CEC
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_PTP, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON PTP_LESSON_CEC TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DE_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}

  ALTER TABLE CJ2_JOURNAL_LESSONS ADD DE_ID VARCHAR(400);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_ONLINE' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}

  ALTER TABLE CJ2_JOURNAL_LESSONS ADD IS_ONLINE SMALLINT DEFAULT 0 NOT NULL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'INST_LINK' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}

  ALTER TABLE CJ2_JOURNAL_LESSONS ADD INST_LINK VARCHAR(400) CHARACTER SET UTF8;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'INST_STATUS' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}

    ALTER TABLE CJ2_JOURNAL_LESSONS ADD INST_STATUS SMALLINT DEFAULT 0 NOT NULL;
    COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$INDICES WHERE RDB$INDEX_NAME = 'FK_CJ2_JOURNAL_LESSONS_3'}

  ALTER TABLE CJ2_JOURNAL_LESSONS DROP CONSTRAINT FK_CJ2_JOURNAL_LESSONS_3;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS RF
  JOIN RDB$FIELDS F ON F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE AND F.RDB$FIELD_TYPE = 16
  WHERE RF.RDB$FIELD_NAME = 'DE_ID' AND RF.RDB$RELATION_NAME = 'CJ2_JOURNAL_LESSONS'}

  ALTER TABLE CJ2_JOURNAL_LESSONS ALTER COLUMN DE_ID TYPE VARCHAR(400) CHARACTER SET ASCII;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'SCHEDULE_ITEMS'}

  CREATE GENERATOR GEN_SCHEDULE;

  CREATE TABLE SCHEDULE_ITEMS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    SCHEDULE_ID  BIGINT NOT NULL,
    WEEKDAY_NUM  SMALLINT NOT NULL,
    LESSON_NUM   SMALLINT NOT NULL,
    CJ_ID        BIGINT NOT NULL,
    ROOM_ID      BIGINT,
    DURATION     SMALLINT,
    PARENT_ID    BIGINT,
    EXT_INFO     VARCHAR(1000),
    LESSON_TIME  TIME
  );

  ALTER TABLE SCHEDULE_ITEMS ADD CONSTRAINT PK_SCHEDULE_ITEMS PRIMARY KEY (OBJ_ID);
  ALTER TABLE SCHEDULE_ITEMS ADD CONSTRAINT FK_SCHEDULE_ITEMS_1 FOREIGN KEY (SCHEDULE_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX SCHEDULE_ITEMS_IDX1 ON SCHEDULE_ITEMS (PARENT_ID);
  CREATE INDEX SCHEDULE_ITEMS_IDX2 ON SCHEDULE_ITEMS (SCHEDULE_ID,DATE_MODIFY);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER SCHEDULE_ITEMS_BI0 FOR SCHEDULE_ITEMS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_SCHEDULE, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON SCHEDULE_ITEMS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DURATION' AND RDB$RELATION_NAME = 'SCHEDULE_ITEMS'}

  ALTER TABLE SCHEDULE_ITEMS ADD DURATION SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PARENT_ID' AND RDB$RELATION_NAME = 'SCHEDULE_ITEMS'}

  ALTER TABLE SCHEDULE_ITEMS ADD PARENT_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'EXT_INFO' AND RDB$RELATION_NAME = 'SCHEDULE_ITEMS'}

  ALTER TABLE SCHEDULE_ITEMS ADD EXT_INFO VARCHAR(1000);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'SCHEDULE_ITEMS_IDX1'}
  CREATE INDEX SCHEDULE_ITEMS_IDX1 ON SCHEDULE_ITEMS (PARENT_ID);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'SCHEDULE_ITEMS_IDX2'}
  CREATE INDEX SCHEDULE_ITEMS_IDX2 ON SCHEDULE_ITEMS (SCHEDULE_ID,DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LESSON_TIME' AND RDB$RELATION_NAME = 'SCHEDULE_ITEMS'}
  ALTER TABLE SCHEDULE_ITEMS ADD LESSON_TIME TIME;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'RGN_REPORTS'}

  CREATE GENERATOR RGN_GEN;

  CREATE TABLE RGN_REPORTS (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    OBJ_NAME      VARCHAR(400) NOT NULL,
    ICON_NAME     VARCHAR(100),
    COLOR         VARCHAR(40),
    LAST_TYPE_ID  BIGINT,
    IS_LIVE       SMALLINT DEFAULT 0 NOT NULL,
    USER_ID       BIGINT,
    SORT_INDEX    INTEGER,
    LIVE_VALUE    FLOAT,
    TILE_SIZE     SMALLINT DEFAULT 0 NOT NULL,
    IS_ARCHIVE    SMALLINT DEFAULT 0 NOT NULL,
    LIVE_VALUES VARCHAR(4000) CHARACTER SET ASCII COLLATE ASCII 
  );

  ALTER TABLE RGN_REPORTS ADD CONSTRAINT PK_RGN_REPORTS PRIMARY KEY (OBJ_ID);
  ALTER TABLE RGN_REPORTS ADD CONSTRAINT FK_RGN_REPORTS_1 FOREIGN KEY (LAST_TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER RGN_REPORTS_BI0 FOR RGN_REPORTS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(RGN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON RGN_REPORTS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'RGN_REPORT_LEVELS'}

  CREATE TABLE RGN_REPORT_LEVELS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    REPORT_ID    BIGINT NOT NULL,
    PARENT_ID    BIGINT,
    TYPE_ID      BIGINT NOT NULL,
    LIST_MODE    SMALLINT DEFAULT 0 NOT NULL,
    SORT_INDEX   SMALLINT NOT NULL
  );

  ALTER TABLE RGN_REPORT_LEVELS ADD CONSTRAINT PK_RGN_REPORT_LEVELS PRIMARY KEY (OBJ_ID);
  ALTER TABLE RGN_REPORT_LEVELS ADD CONSTRAINT FK_RGN_REPORT_LEVELS_1 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE RGN_REPORT_LEVELS ADD CONSTRAINT FK_RGN_REPORT_LEVELS_2 FOREIGN KEY (REPORT_ID) REFERENCES RGN_REPORTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE RGN_REPORT_LEVELS ADD CONSTRAINT FK_RGN_REPORT_LEVELS_3 FOREIGN KEY (PARENT_ID) REFERENCES RGN_REPORT_LEVELS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER RGN_REPORT_LEVELS_BI0 FOR RGN_REPORT_LEVELS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(RGN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON RGN_REPORT_LEVELS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'RGN_REPORT_LPARAMS'}

  CREATE TABLE RGN_REPORT_LPARAMS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LEVEL_ID     BIGINT NOT NULL,
    PARAM_ID     BIGINT NOT NULL,
    SORT_INDEX   INTEGER NOT NULL,
    PARAM_ALIAS  VARCHAR(100)
  );

  ALTER TABLE RGN_REPORT_LPARAMS ADD CONSTRAINT PK_RGN_REPORT_LPARAMS PRIMARY KEY (OBJ_ID);
  ALTER TABLE RGN_REPORT_LPARAMS ADD CONSTRAINT FK_RGN_REPORT_LPARAMS_1 FOREIGN KEY (PARAM_ID) REFERENCES PARAMS (PARAM_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE RGN_REPORT_LPARAMS ADD CONSTRAINT FK_RGN_REPORT_LPARAMS_2 FOREIGN KEY (LEVEL_ID) REFERENCES RGN_REPORT_LEVELS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER RGN_REPORT_LPARAMS_BI0 FOR RGN_REPORT_LPARAMS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(RGN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON RGN_REPORT_LPARAMS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PARAM_ALIAS' AND RDB$RELATION_NAME = 'RGN_REPORT_LPARAMS'}

  ALTER TABLE RGN_REPORT_LPARAMS ADD PARAM_ALIAS VARCHAR(100);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'RGN_REPORT_LFILTERS'}

  CREATE TABLE RGN_REPORT_LFILTERS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LEVEL_ID     BIGINT NOT NULL,
    SORT_INDEX   INTEGER NOT NULL,
    PARAM_ID     BIGINT NOT NULL,
    EQU_INDEX    SMALLINT,
    EQU_VALUE    VARCHAR(200),
    EQU_VALUE2   VARCHAR(200)
  );

  ALTER TABLE RGN_REPORT_LFILTERS ADD CONSTRAINT PK_RGN_REPORT_LFILTERS PRIMARY KEY (OBJ_ID);
  ALTER TABLE RGN_REPORT_LFILTERS ADD CONSTRAINT FK_RGN_REPORT_LFILTERS_1 FOREIGN KEY (LEVEL_ID) REFERENCES RGN_REPORT_LEVELS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE RGN_REPORT_LFILTERS ADD CONSTRAINT FK_RGN_REPORT_LFILTERS_2 FOREIGN KEY (PARAM_ID) REFERENCES PARAMS (PARAM_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER RGN_REPORT_LFILTERS_BI0 FOR RGN_REPORT_LFILTERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(RGN_GEN, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON RGN_REPORT_LFILTERS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'ORDERS'}

  CREATE GENERATOR GEN_ORDERS;

  CREATE TABLE ORDERS (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    PARENT_ID     BIGINT,
    TYPE_ID       BIGINT NOT NULL,
    SIGNED_BY     BIGINT,
    ORDER_DATE    DATE,
    ORDER_NUM     VARCHAR(100),
    DETAILS_TEXT  VARCHAR(1000),
    STATE_ID      BIGINT NOT NULL,
    CANCEL_DATE   DATE,
    USER_ID       BIGINT,
    ACTION_DATE   DATE,
    PROJECT_NUM   VARCHAR(40),
    COMMENTS      VARCHAR(1000),
    SUBTYPE_ID    BIGINT,
    OWNER_ID      BIGINT,
    REF_ID        BIGINT
  );

  ALTER TABLE ORDERS ADD CONSTRAINT PK_ORDERS PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_1 FOREIGN KEY (PARENT_ID) REFERENCES ORDERS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_2 FOREIGN KEY (TYPE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_3 FOREIGN KEY (SIGNED_BY) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_4 FOREIGN KEY (STATE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_5 FOREIGN KEY (SUBTYPE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_6 FOREIGN KEY (OWNER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX ORDERS_IDX1 ON ORDERS (REF_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER ORDERS_BI0 FOR ORDERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  declare variable TMP bigint;
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      TMP = GEN_ID(GEN_ORDERS, 1);
      NEW.OBJ_ID = TMP + (SELECT GEN * MULTIPLIER FROM GEN);
    END
    ELSE
    BEGIN
      TMP = NEW.OBJ_ID / (SELECT GEN * MULTIPLIER FROM GEN);
    END
    NEW.PROJECT_NUM = TMP;
  end
  ^

  SET TERM ; ^

  GRANT ALL ON ORDERS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'COMMENTS' AND RDB$RELATION_NAME = 'ORDERS'}

  ALTER TABLE ORDERS ADD COMMENTS VARCHAR(1000) CHARACTER SET UTF8  COLLATE UTF8 ;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SUBTYPE_ID' AND RDB$RELATION_NAME = 'ORDERS'}

  ALTER TABLE ORDERS ADD SUBTYPE_ID BIGINT;
  COMMIT WORK;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_5 FOREIGN KEY (SUBTYPE_ID) REFERENCES LISTVALS(LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'REF_ID' AND RDB$RELATION_NAME = 'ORDERS'}

  ALTER TABLE ORDERS ADD REF_ID BIGINT;
  COMMIT WORK;
  CREATE INDEX ORDERS_IDX1 ON ORDERS (REF_ID);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'ORDER_DATA'}

  CREATE TABLE ORDER_DATA (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    ORDER_ID     BIGINT NOT NULL,
    ACTION_ID    BIGINT,
    ACTION_TYPE  SMALLINT NOT NULL,
    REF_ID       BIGINT NOT NULL,
    IS_PRESENT   SMALLINT DEFAULT 1 NOT NULL,
    GRADE_NAME   VARCHAR(400),
    DST_GROUPS   VARCHAR(400) CHARACTER SET ASCII COLLATE ASCII,
    DST_DATA     VARCHAR(1000),
    JOB_ID       BIGINT
  );

  ALTER TABLE ORDER_DATA ADD CONSTRAINT PK_ORDER_DATA PRIMARY KEY (OBJ_ID);
  ALTER TABLE ORDER_DATA ADD CONSTRAINT FK_ORDER_DATA_1 FOREIGN KEY (ORDER_ID) REFERENCES ORDERS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDER_DATA ADD CONSTRAINT FK_ORDER_DATA_2 FOREIGN KEY (REF_ID) REFERENCES OBJECTS(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ORDER_DATA ADD CONSTRAINT FK_ORDER_DATA_3 FOREIGN KEY (JOB_ID) REFERENCES OBJECTS(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE; 
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER ORDER_DATA_BI0 FOR ORDER_DATA
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_ORDERS, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON ORDER_DATA TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_PRESENT' AND RDB$RELATION_NAME = 'ORDER_DATA'}

  ALTER TABLE ORDER_DATA ADD IS_PRESENT SMALLINT DEFAULT 1 NOT NULL;
  ALTER TABLE ORDER_DATA ADD GRADE_NAME VARCHAR(400);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DST_GROUPS' AND RDB$RELATION_NAME = 'ORDER_DATA'}

  ALTER TABLE ORDER_DATA ADD DST_GROUPS VARCHAR(400) CHARACTER SET ASCII COLLATE ASCII;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DST_DATA' AND RDB$RELATION_NAME = 'ORDER_DATA'}

  ALTER TABLE ORDER_DATA ADD DST_DATA VARCHAR(1000);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ORDER_ID_IN' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}

  ALTER TABLE PERSON_MOVEMENTS ADD ORDER_ID_IN BIGINT;
  ALTER TABLE PERSON_MOVEMENTS ADD ORDER_ID_OUT BIGINT;
  COMMIT WORK;
  ALTER TABLE PERSON_MOVEMENTS ADD CONSTRAINT FK_PERSON_MOVEMENTS_3 FOREIGN KEY (ORDER_ID_IN) REFERENCES ORDERS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PERSON_MOVEMENTS ADD CONSTRAINT FK_PERSON_MOVEMENTS_4 FOREIGN KEY (ORDER_ID_OUT) REFERENCES ORDERS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'NAME_IN' AND RDB$RELATION_NAME = 'PERSON_MOVEMENTS'}

  ALTER TABLE PERSON_MOVEMENTS ADD NAME_IN VARCHAR(400);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PERSON_ID' AND RDB$RELATION_NAME = 'CJ2_PERSON_MISS'}

  CREATE TABLE CJ2_PERSON_MISS (
    PERSON_ID  BIGINT NOT NULL,
    UPDATED_AT TIMESTAMP NOT NULL,
    N_MISS     INTEGER DEFAULT 0 NOT NULL,
    RATE_MISS  FLOAT DEFAULT 0 NOT NULL
  );

  ALTER TABLE CJ2_PERSON_MISS ADD CONSTRAINT PK_CJ2_PERSON_MISS PRIMARY KEY (PERSON_ID);
  ALTER TABLE CJ2_PERSON_MISS ADD CONSTRAINT FK_CJ2_PERSON_MISS_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  GRANT ALL ON CJ2_PERSON_MISS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'STAGE_ID' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD STAGE_ID BIGINT; 
  COMMIT WORK;
  ALTER TABLE VALM ADD CONSTRAINT FK_VALM_7 FOREIGN KEY (STAGE_ID) REFERENCES LISTVALS(LISTVAL_ID) ON DELETE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PERIOD_FROM' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD PERIOD_FROM DATE; 
  ALTER TABLE VALM ADD PERIOD_TO DATE; 
  ALTER TABLE VALM ADD GRADE_ID BIGINT; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'MARK_DATE' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD MARK_DATE DATE; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_NATIVE' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD IS_NATIVE SMALLINT; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'USER_DEL' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD USER_DEL BIGINT; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'USER_ADD' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD USER_ADD BIGINT; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_EXT' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD IS_EXT SMALLINT DEFAULT 0 NOT NULL; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'IS_IND' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD IS_IND SMALLINT DEFAULT 0 NOT NULL; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALM_IDX1'}

  CREATE INDEX VALM_IDX1 ON VALM (PUPIL_ID, MARKTYPE_ID, YEAR_ID);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALM_IDX2'}

  CREATE INDEX VALM_IDX2 ON VALM (PUPIL_ID, SUBJECT_ID, YEAR_ID, MARKTYPE_ID);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SRC_ID' AND RDB$RELATION_NAME = 'UT_TRANSCODE'}

  CREATE TABLE UT_TRANSCODE (
    SRC_ID    BIGINT,
    DST_ID    BIGINT,
    SRC_NAME  VARCHAR(150)
  );

  CREATE INDEX UT_TRANSCODE_IDX1 ON UT_TRANSCODE (SRC_ID);
  GRANT ALL ON UT_TRANSCODE TO INISSOFT_ROLE;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CS_REPORTS'}

  CREATE GENERATOR GEN_CS_REPORTS;

  CREATE TABLE CS_REPORTS (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    OU_ID         BIGINT NOT NULL,
    APPROVE_DATE  TIMESTAMP,
    VAL           VARCHAR(8000),
    STATE_ID      SMALLINT DEFAULT 0 NOT NULL
  );

  ALTER TABLE CS_REPORTS ADD CONSTRAINT PK_CS_REPORTS PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CS_REPORTS_BI0 FOR CS_REPORTS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_CS_REPORTS, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  SET TERM ; ^

  GRANT ALL ON CS_REPORTS TO INISSOFT_ROLE;
  COMMIT WORK; 

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'VAL' AND F.RDB$RELATION_NAME = 'CS_REPORTS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 4000}

    ALTER TABLE CS_REPORTS ALTER COLUMN VAL TYPE VARCHAR(8000);
    COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_FINALS'}

  CREATE TABLE CJ2_JOURNAL_FINALS (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    CJ_ID         BIGINT NOT NULL,
    FINAL_DATE    DATE NOT NULL,
    TEACHER_ID    BIGINT,
    FINAL_TYPE    BIGINT NOT NULL,
    IS_PUBLISHED  SMALLINT DEFAULT 0 NOT NULL,
    MARK_SYSTEM_ID BIGINT DEFAULT 400 NOT NULL
  );

  ALTER TABLE CJ2_JOURNAL_FINALS ADD CONSTRAINT PK_CJ2_JOURNAL_FINALS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_JOURNAL_FINALS ADD CONSTRAINT FK_CJ2_JOURNAL_FINALS_1 FOREIGN KEY (CJ_ID) REFERENCES CJ2_JOURNAL (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_JOURNAL_FINALS ADD CONSTRAINT FK_CJ2_JOURNAL_FINALS_2 FOREIGN KEY (TEACHER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE CJ2_JOURNAL_FINALS ADD CONSTRAINT FK_CJ2_JOURNAL_FINALS_3 FOREIGN KEY (FINAL_TYPE) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_JOURNAL_FINALS ADD CONSTRAINT FK_CJ2_JOURNAL_FINALS_4 FOREIGN KEY (MARK_SYSTEM_ID) REFERENCES CJ2_MARK_TYPE(MARK_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX CJ2_JOURNAL_FINALS_IDX1 ON CJ2_JOURNAL_FINALS (DATE_MODIFY);
  CREATE INDEX CJ2_JOURNAL_FINALS_IDX2 ON CJ2_JOURNAL_FINALS (CJ_ID, DATE_MODIFY);
  CREATE INDEX CJ2_JOURNAL_FINALS_IDX3 ON CJ2_JOURNAL_FINALS (CJ_ID, DATE_DEL);

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_FINALS_BI0 FOR CJ2_JOURNAL_FINALS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
        NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_CJ_MAIN_ID);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_JOURNAL_FINALS_BU0 FOR CJ2_JOURNAL_FINALS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^

  SET TERM ; ^

  GRANT ALL ON CJ2_JOURNAL_FINALS TO INISSOFT_ROLE;
  COMMIT WORK; 

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'MARK_SYSTEM_ID' AND RDB$RELATION_NAME = 'CJ2_JOURNAL_FINALS'}
  
  ALTER TABLE CJ2_JOURNAL_FINALS ADD MARK_SYSTEM_ID BIGINT DEFAULT 400 NOT NULL;
  COMMIT WORK; 

  ALTER TABLE CJ2_JOURNAL_FINALS ADD CONSTRAINT FK_CJ2_JOURNAL_FINALS_4 FOREIGN KEY (MARK_SYSTEM_ID) REFERENCES CJ2_MARK_TYPE(MARK_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK; 

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_FINALS_IDX1'}
  CREATE INDEX CJ2_JOURNAL_FINALS_IDX1 ON CJ2_JOURNAL_FINALS (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_FINALS_IDX2'}
  CREATE INDEX CJ2_JOURNAL_FINALS_IDX2 ON CJ2_JOURNAL_FINALS (CJ_ID, DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_JOURNAL_FINALS_IDX3'}
  CREATE INDEX CJ2_JOURNAL_FINALS_IDX3 ON CJ2_JOURNAL_FINALS (CJ_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FINAL_ID' AND RDB$RELATION_NAME = 'CJ2_MARK'}

  ALTER TABLE CJ2_MARK ADD FINAL_ID BIGINT;
  COMMIT WORK; 

  ALTER TABLE CJ2_MARK ADD CONSTRAINT FK_CJ2_MARK_1 FOREIGN KEY (FINAL_ID) REFERENCES CJ2_JOURNAL_FINALS(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK; 

{$ENDIF}

/* Внимание ! Это не работает на FB3, необходимо поле исправить вручную и снять флаг NULL */
{$IFEXISTS SELECT RDB$NULL_FLAG	FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'CONTROL_ID' AND RDB$RELATION_NAME = 'CJ2_MARK' AND RDB$NULL_FLAG = 1}

  UPDATE RDB$RELATION_FIELDS SET RDB$NULL_FLAG = NULL WHERE RDB$FIELD_NAME = 'CONTROL_ID' AND RDB$RELATION_NAME = 'CJ2_MARK';
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DATEVAL' AND RDB$RELATION_NAME = 'SPECIAL_DATES'}

  CREATE TABLE SPECIAL_DATES (
    DATEVAL   DATE NOT NULL,
    DATETYPE  SMALLINT DEFAULT 0 NOT NULL
  );

  COMMIT WORK;

  ALTER TABLE SPECIAL_DATES ADD CONSTRAINT PK_SPECIAL_DATES PRIMARY KEY (DATEVAL);
  GRANT ALL ON SPECIAL_DATES TO INISSOFT_ROLE;

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'OBJECTS_DATE_MODIFY'}

  CREATE INDEX OBJECTS_DATE_MODIFY ON OBJECTS (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'LINKS_DATE_MODIFY'}

  CREATE INDEX LINKS_DATE_MODIFY ON LINKS (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALA_DATE_MODIFY'}

  CREATE INDEX VALA_DATE_MODIFY ON VALA (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALB_DATE_MODIFY'}

  CREATE INDEX VALB_DATE_MODIFY ON VALB (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALD_DATE_MODIFY'}

  CREATE INDEX VALD_DATE_MODIFY ON VALD (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALDT_DATE_MODIFY'}

  CREATE INDEX VALDT_DATE_MODIFY ON VALDT (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALF_DATE_MODIFY'}

  CREATE INDEX VALF_DATE_MODIFY ON VALF (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALI_DATE_MODIFY'}

  CREATE INDEX VALI_DATE_MODIFY ON VALI (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALL_DATE_MODIFY'}

  CREATE INDEX VALL_DATE_MODIFY ON VALL (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALM_DATE_MODIFY'}

  CREATE INDEX VALM_DATE_MODIFY ON VALM (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALR_DATE_MODIFY'}

  CREATE INDEX VALR_DATE_MODIFY ON VALR (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALR_IDX1'}

  CREATE INDEX VALR_IDX1 ON VALR (PARAM_ID, VAL);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALS_DATE_MODIFY'}

  CREATE INDEX VALS_DATE_MODIFY ON VALS (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT I.RDB$INDEX_NAME FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'VALT_DATE_MODIFY'}

  CREATE INDEX VALT_DATE_MODIFY ON VALT (DATE_MODIFY);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'BOT_REQUESTS'}

  CREATE GENERATOR GEN_BOT;

  CREATE TABLE BOT_REQUESTS (
    ID         BIGINT NOT NULL,
    DATE_ADD   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    ACC_ID     VARCHAR(40),
    ACC_NAME   VARCHAR(100),
    MSG_TEXT   VARCHAR(1000),
    PHONE_NUM  VARCHAR(100),
    PERSON_ID  BIGINT,
    STATE_ID   SMALLINT DEFAULT 0 NOT NULL
  );
  COMMIT WORK;

  ALTER TABLE BOT_REQUESTS ADD CONSTRAINT PK_BOT_REQUESTS PRIMARY KEY (ID);
  ALTER TABLE BOT_REQUESTS ADD CONSTRAINT FK_BOT_REQUESTS_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER BOT_REQUESTS_BI0 FOR BOT_REQUESTS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.ID IS NULL) THEN NEW.ID = GEN_ID(GEN_BOT, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON BOT_REQUESTS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'GRADE_ID' AND RDB$RELATION_NAME = 'YCHANGE_GRADES_TMP'}

  CREATE GLOBAL TEMPORARY TABLE YCHANGE_GRADES_TMP (
    GRADE_ID          BIGINT,
    TYPE_ID           BIGINT,
    STAGE_ID          BIGINT,
    OVZ               BIGINT,
    OVZ_YEAR          BIGINT,
    GRADE_SUFFIX_OLD  VARCHAR(400) CHARACTER SET UTF8,
    GRADE_SUFFIX_NEW  VARCHAR(400) CHARACTER SET UTF8,
    GRADE_NAME_OLD    VARCHAR(400) CHARACTER SET UTF8,
    GRADE_NAME_NEW    VARCHAR(400) CHARACTER SET UTF8
  ) ON COMMIT DELETE ROWS;

  GRANT ALL ON YCHANGE_GRADES_TMP TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'GRADE_NAME_OLD' AND RDB$RELATION_NAME = 'YCHANGE_GRADES_TMP'}

  ALTER TABLE YCHANGE_GRADES_TMP ADD GRADE_NAME_OLD VARCHAR(400) CHARACTER SET UTF8;

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_HISTORY'}

  CREATE GENERATOR GEN_CJ2_HISTORY;

  CREATE TABLE CJ2_LESSON_HISTORY (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LESSON_ID    BIGINT NOT NULL,
    USER_ID      BIGINT NOT NULL,
    STATE_ID     SMALLINT NOT NULL
  );                                                                              

  ALTER TABLE CJ2_LESSON_HISTORY ADD CONSTRAINT PK_CJ2_LESSON_HISTORY PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_LESSON_HISTORY ADD CONSTRAINT FK_CJ2_LESSON_HISTORY_1 FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_LESSON_HISTORY ADD CONSTRAINT FK_CJ2_LESSON_HISTORY_2 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_LESSON_HISTORY_BI1 FOR CJ2_LESSON_HISTORY
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (NEXT VALUE FOR GEN_CJ2_HISTORY) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_LESSON_HISTORY_BIU0 FOR CJ2_LESSON_HISTORY
  ACTIVE BEFORE INSERT OR UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_LESSON_HISTORY TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_LOG'}

  CREATE TABLE CJ2_LESSON_LOG (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LESSON_ID    BIGINT NOT NULL,
    FIELD_ID     VARCHAR(40) NOT NULL,
    VAL          VARCHAR(1000),
    USER_ID      BIGINT,
    ATTR_ID      BIGINT
  );

  ALTER TABLE CJ2_LESSON_LOG ADD CONSTRAINT PK_CJ2_LESSON_LOG PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_LESSON_LOG_BI0 FOR CJ2_LESSON_LOG
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (NEXT VALUE FOR GEN_CJ2_HISTORY) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_LESSON_LOG TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ATTR_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_LOG'}
  ALTER TABLE CJ2_LESSON_LOG ADD ATTR_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_STUDENT_RATING'}

  CREATE TABLE CJ2_STUDENT_RATING (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    STUDENT_ID   BIGINT NOT NULL,
    SUBJECT_ID   BIGINT,
    FIELD_ID     BIGINT,
    PERIOD_ID    BIGINT,
    RATE_DATE    DATE,
    RATE_VALUE   FLOAT,
    RATE_INDEX   SMALLINT,
    VAL_TOP      FLOAT,
    VAL_BOTTOM   FLOAT
  );  

  ALTER TABLE CJ2_STUDENT_RATING ADD CONSTRAINT PK_CJ2_STUDENT_RATING PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_STUDENT_RATING ADD CONSTRAINT FK_CJ2_STUDENT_RATING_1 FOREIGN KEY (STUDENT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX CJ2_STUDENT_RATING_IDX1 ON CJ2_STUDENT_RATING (STUDENT_ID, SUBJECT_ID, RATE_DATE);
  CREATE INDEX CJ2_STUDENT_RATING_IDX2 ON CJ2_STUDENT_RATING (DATE_MODIFY);
  CREATE INDEX CJ2_STUDENT_RATING_IDX3 ON CJ2_STUDENT_RATING (STUDENT_ID, SUBJECT_ID, FIELD_ID, RATE_DATE);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_STUDENT_RATING_BI0 FOR CJ2_STUDENT_RATING
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (NEXT VALUE FOR GEN_CJ2_HISTORY) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_STUDENT_RATING_BU0 FOR CJ2_STUDENT_RATING
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^

  SET TERM ; ^

  GRANT ALL ON CJ2_STUDENT_RATING TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

GRANT ALL ON CJ2_STUDENT_RATING TO INISSOFT_ROLE;

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_STUDENT_RATING_IDX2'}
  CREATE INDEX CJ2_STUDENT_RATING_IDX2 ON CJ2_STUDENT_RATING (DATE_MODIFY);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FIELD_ID' AND RDB$RELATION_NAME = 'CJ2_STUDENT_RATING'}
  ALTER TABLE CJ2_STUDENT_RATING ADD FIELD_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'CJ2_STUDENT_RATING_IDX3'}
  CREATE INDEX CJ2_STUDENT_RATING_IDX3 ON CJ2_STUDENT_RATING (STUDENT_ID, SUBJECT_ID, FIELD_ID, RATE_DATE);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PERIOD_ID' AND RDB$RELATION_NAME = 'CJ2_STUDENT_RATING'}
  ALTER TABLE CJ2_STUDENT_RATING ADD PERIOD_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PERIOD_TYPE_ID' AND RDB$RELATION_NAME = 'CJ2_STUDENT_RATING'}
  ALTER TABLE CJ2_STUDENT_RATING ADD PERIOD_TYPE_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'VAL_TOP' AND RDB$RELATION_NAME = 'CJ2_STUDENT_RATING'}
  ALTER TABLE CJ2_STUDENT_RATING ADD VAL_TOP FLOAT;
  ALTER TABLE CJ2_STUDENT_RATING ADD VAL_BOTTOM FLOAT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'STAT_QUERIES'}

  CREATE GENERATOR GEN_STAT_ID;

  CREATE TABLE STAT_QUERIES (
    ID             BIGINT NOT NULL,
    DATE_ADD       TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY    TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL       TIMESTAMP,
    QUERY_TYPE     SMALLINT DEFAULT 0 NOT NULL,
    QUERY_PATH     VARCHAR(2000),
    QUERY_FILTER   VARCHAR(2000),
    QUERY_DETAILS  VARCHAR(200),
    UPDATE_PERIOD  SMALLINT DEFAULT 0 NOT NULL,
    QUERY_NAME     VARCHAR(100),
    POST_FILTER VARCHAR(1000)
  );

  ALTER TABLE STAT_QUERIES ADD CONSTRAINT PK_STAT_QUERIES PRIMARY KEY (ID);

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER STAT_QUERIES_BI0 FOR STAT_QUERIES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.ID IS NULL) THEN
    BEGIN
        NEW.ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_STAT_ID);
    END
  end
  ^
  SET TERM ; ^

  GRANT ALL ON STAT_QUERIES TO INISSOFT_ROLE;

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ID' AND RDB$RELATION_NAME = 'STAT_FIELDS'}

  CREATE TABLE STAT_FIELDS (
    ID           BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    QUERY_ID     BIGINT NOT NULL,
    FIELD_NAME   VARCHAR(200),
    FUNC_ID      SMALLINT DEFAULT 0 NOT NULL,
    SUBFUNC_ID   VARCHAR(100),
    FIELD_FILTER VARCHAR(1000),
    FIELD_TITLE  VARCHAR(400),
    FIELD_DIR    SMALLINT,
    LIMIT_W      FLOAT,
    LIMIT_A      FLOAT,
    IS_REGMON    SMALLINT,
    MASTER_SCALE FLOAT,
    MASTER_PARAM_ID BIGINT,
    BOTTOM_PARAM_ID BIGINT
  );

  ALTER TABLE STAT_FIELDS ADD CONSTRAINT PK_STAT_FIELDS PRIMARY KEY (ID);
  ALTER TABLE STAT_FIELDS ADD CONSTRAINT FK_STAT_FIELDS_1 FOREIGN KEY (QUERY_ID) REFERENCES STAT_QUERIES (ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER STAT_FIELDS_BI0 FOR STAT_FIELDS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.ID IS NULL) THEN
    BEGIN
        NEW.ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_STAT_ID);
    END
  end
  ^
  SET TERM ; ^

  GRANT ALL ON STAT_FIELDS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'QUERY_DETAILS' AND RDB$RELATION_NAME = 'STAT_QUERIES'}
  ALTER TABLE STAT_QUERIES ADD QUERY_DETAILS VARCHAR(200) CHARACTER SET UTF8 COLLATE UTF8;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FIELD_TITLE' AND RDB$RELATION_NAME = 'STAT_FIELDS'}
  ALTER TABLE STAT_FIELDS ADD FIELD_TITLE VARCHAR(400) CHARACTER SET UTF8 COLLATE UTF8;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FIELD_DIR' AND RDB$RELATION_NAME = 'STAT_FIELDS'}
  ALTER TABLE STAT_FIELDS ADD FIELD_DIR SMALLINT;
  ALTER TABLE STAT_FIELDS ADD LIMIT_W FLOAT;
  ALTER TABLE STAT_FIELDS ADD LIMIT_A FLOAT;
  ALTER TABLE STAT_FIELDS ADD IS_REGMON SMALLINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'MASTER_SCALE' AND RDB$RELATION_NAME = 'STAT_FIELDS'}
  ALTER TABLE STAT_FIELDS ADD MASTER_SCALE FLOAT;
  ALTER TABLE STAT_FIELDS ADD MASTER_PARAM_ID BIGINT;
  ALTER TABLE STAT_FIELDS ADD BOTTOM_PARAM_ID BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'POST_FILTER' AND RDB$RELATION_NAME = 'STAT_QUERIES'}
  ALTER TABLE STAT_QUERIES ADD POST_FILTER VARCHAR(1000) CHARACTER SET UTF8 COLLATE UTF8;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FIELD_FILTER' AND RDB$RELATION_NAME = 'STAT_FIELDS'}
  ALTER TABLE STAT_FIELDS ADD FIELD_FILTER VARCHAR(1000) CHARACTER SET UTF8 COLLATE UTF8;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'FK_CJ2_STUDENT_RATING_2'}
  ALTER TABLE CJ2_STUDENT_RATING ADD CONSTRAINT FK_CJ2_STUDENT_RATING_2 FOREIGN KEY (FIELD_ID) REFERENCES STAT_FIELDS(ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_RES'}

  CREATE GENERATOR GEN_CJ_RES_ID;

  CREATE TABLE CJ2_LESSON_RES (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LESSON_ID    BIGINT NOT NULL,
    RES_ID       BIGINT NOT NULL,
    RES_TYPE     BIGINT
  );

  ALTER TABLE CJ2_LESSON_RES ADD CONSTRAINT PK_CJ2_LESSON_RES PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_LESSON_RES ADD CONSTRAINT FK_CJ2_LESSON_RES_1 FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_LESSON_RES ADD CONSTRAINT FK_CJ2_LESSON_RES_2 FOREIGN KEY (RES_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_LESSON_RES_BI0 FOR CJ2_LESSON_RES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
        NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_CJ_RES_ID);
    END
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_LESSON_RES TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'RES_TYPE' AND RDB$RELATION_NAME = 'CJ2_LESSON_RES'}
  ALTER TABLE CJ2_LESSON_RES ADD RES_TYPE BIGINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PUPIL_ID' AND RDB$RELATION_NAME = 'VALX'}

  CREATE TABLE VALX (
    PUPIL_ID     BIGINT NOT NULL,
    USA_ID       BIGINT NOT NULL,
    CEC_ID       BIGINT NOT NULL,
    YEAR_ID      BIGINT NOT NULL,
    NVALS        INTEGER,
    YTOTAL       FLOAT,
    NTOTAL       FLOAT,
    YVAL         FLOAT,
    VTOTAL       FLOAT,
    LVAL         FLOAT,
    VAL          FLOAT,
    USA_GROUP     BIGINT,
    USA_SUBGROUP  BIGINT,
    USA_ITEM      BIGINT,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
  );

  ALTER TABLE VALX ADD CONSTRAINT PK_VALX PRIMARY KEY (PUPIL_ID, USA_ID, CEC_ID, YEAR_ID);
  ALTER TABLE VALX ADD CONSTRAINT FK_VALX_1 FOREIGN KEY (PUPIL_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE VALX ADD CONSTRAINT FK_VALX_2 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX VALX_IDX1 ON VALX (PUPIL_ID, YEAR_ID);
  CREATE INDEX VALX_IDX2 ON VALX (PUPIL_ID, USA_GROUP);
  CREATE INDEX VALX_IDX3 ON VALX (PUPIL_ID, USA_SUBGROUP);
  CREATE INDEX VALX_IDX4 ON VALX (PUPIL_ID, USA_ITEM);

  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER VALX_BU0 FOR VALX
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON VALX TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'CONTROL_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_UUD'}

  CREATE TABLE CJ2_LESSON_UUD (
    CONTROL_ID   BIGINT NOT NULL,
    USA_ID       BIGINT NOT NULL,
    GROUP_ID     BIGINT,
    SUBGROUP_ID  BIGINT,
    ITEM_ID      BIGINT,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    IS_DEL       SMALLINT DEFAULT 0 NOT NULL
  );

  ALTER TABLE CJ2_LESSON_UUD ADD CONSTRAINT PK_CJ2_LESSON_UUD PRIMARY KEY (CONTROL_ID, USA_ID);
  ALTER TABLE CJ2_LESSON_UUD ADD CONSTRAINT FK_CJ2_LESSON_UUD_1 FOREIGN KEY (CONTROL_ID) REFERENCES CJ2_CONTROL (CONTROL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_LESSON_UUD ADD CONSTRAINT FK_CJ2_LESSON_UUD_2 FOREIGN KEY (USA_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX CJ2_LESSON_UUD_IDX1 ON CJ2_LESSON_UUD (CONTROL_ID, GROUP_ID);
  CREATE INDEX CJ2_LESSON_UUD_IDX2 ON CJ2_LESSON_UUD (CONTROL_ID, SUBGROUP_ID);
  CREATE INDEX CJ2_LESSON_UUD_IDX3 ON CJ2_LESSON_UUD (CONTROL_ID, ITEM_ID);
  COMMIT WORK;

  GRANT ALL ON CJ2_LESSON_UUD TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LESSON_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_CEC'}

  CREATE TABLE CJ2_LESSON_CEC (
    LESSON_ID    BIGINT NOT NULL,
    CEC_ID       BIGINT NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    IS_DEL       SMALLINT DEFAULT 0 NOT NULL
  );

  ALTER TABLE CJ2_LESSON_CEC ADD CONSTRAINT PK_CJ2_LESSON_CEC PRIMARY KEY (LESSON_ID, CEC_ID);
  ALTER TABLE CJ2_LESSON_CEC ADD CONSTRAINT FK_CJ2_LESSON_CEC_1 FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_LESSON_CEC ADD CONSTRAINT FK_CJ2_LESSON_CEC_2 FOREIGN KEY (CEC_ID) REFERENCES CEC_ITEMS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  GRANT ALL ON CJ2_LESSON_CEC TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'PERSON_MOVEMENTS_BU0'}

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER PERSON_MOVEMENTS_BU0 FOR PERSON_MOVEMENTS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  END
  ^
  SET TERM ; ^
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'ORDERS_BU0'}

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER ORDERS_BU0 FOR ORDERS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  END
  ^
  SET TERM ; ^
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'ORDER_DATA_BU0'}

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER ORDER_DATA_BU0 FOR ORDER_DATA
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  END
  ^
  SET TERM ; ^
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'PLAN_LOADS_BU0'}

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER PLAN_LOADS_BU0 FOR PLAN_LOADS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  END
  ^
  SET TERM ; ^
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'PLAN_SUBJECTS_BU0'}

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER PLAN_SUBJECTS_BU0 FOR PLAN_SUBJECTS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  END
  ^
  SET TERM ; ^
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'PLAN_RESOURCES_BU0'}

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER PLAN_RESOURCES_BU0 FOR PLAN_RESOURCES
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  BEGIN
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  END
  ^
  SET TERM ; ^
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'LINKS_IDX1'}
  CREATE INDEX LINKS_IDX1 ON LINKS (PARENT_TYPE_ID, OBJ_TYPE_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'LINKS_IDX2'}
  CREATE INDEX LINKS_IDX2 ON LINKS (PARENT_TYPE_ID, OBJ_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'LINKS_IDX3'}
  CREATE INDEX LINKS_IDX3 ON LINKS (OBJ_ID, PARENT_TYPE_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'LINKS_IDX4'}
  CREATE INDEX LINKS_IDX4 ON LINKS (OBJ_TYPE_ID, OBJ_ID, DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$INDICES I, RDB$INDEX_SEGMENTS S WHERE I.RDB$INDEX_NAME = S.RDB$INDEX_NAME AND I.RDB$INDEX_NAME = 'LINKS_IDX5'}
  CREATE INDEX LINKS_IDX5 ON LINKS (PARENT_ID,OBJ_TYPE_ID,DATE_DEL);
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PERSON_ID' AND RDB$RELATION_NAME = 'PMPK_LINKS'}

  CREATE TABLE PMPK_LINKS (
    PERSON_ID    BIGINT NOT NULL,
    TERM_ID      BIGINT NOT NULL,
    UID          VARCHAR(40),
    DATE_UPDATE  TIMESTAMP
  );

  ALTER TABLE PMPK_LINKS ADD CONSTRAINT PK_PMPK_LINKS PRIMARY KEY (PERSON_ID, TERM_ID);
  ALTER TABLE PMPK_LINKS ADD CONSTRAINT FK_PMPK_LINKS_1 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PMPK_LINKS ADD CONSTRAINT FK_PMPK_LINKS_2 FOREIGN KEY (TERM_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  GRANT ALL ON PMPK_LINKS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'BUTTON_ID' AND RDB$RELATION_NAME = 'LBUTTONS'}

  CREATE TABLE LBUTTONS (
    LEVEL_ID        BIGINT NOT NULL,
    BUTTON_ID       BIGINT NOT NULL,
    PARENT_TYPE_ID  BIGINT NOT NULL,
    OBJ_TYPE_ID     BIGINT NOT NULL,
    IS_DEL          SMALLINT DEFAULT 0 NOT NULL
  );

  ALTER TABLE LBUTTONS ADD CONSTRAINT PK_LBUTTONS1 PRIMARY KEY (LEVEL_ID, BUTTON_ID, PARENT_TYPE_ID, OBJ_TYPE_ID);
  ALTER TABLE LBUTTONS ADD CONSTRAINT FK_LBUTTONS_1 FOREIGN KEY (PARENT_TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;
  ALTER TABLE LBUTTONS ADD CONSTRAINT FK_LBUTTONS_2 FOREIGN KEY (OBJ_TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE;
  ALTER TABLE LBUTTONS ADD CONSTRAINT LBUTTONS_BUTTON_ID FOREIGN KEY (BUTTON_ID) REFERENCES BARBUTTONS (BUTTON_ID) ON DELETE CASCADE;
  ALTER TABLE LBUTTONS ADD CONSTRAINT LBUTTONS_LEVEL_ID FOREIGN KEY (LEVEL_ID) REFERENCES LEVELS (LEVEL_ID) ON DELETE CASCADE;
  COMMIT WORK;

  GRANT ALL ON LBUTTONS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT FIRST 1 1 FROM RDB$INDICES I LEFT JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME = S.RDB$INDEX_NAME 
  LEFT JOIN RDB$RELATION_CONSTRAINTS RC ON RC.RDB$INDEX_NAME = I.RDB$INDEX_NAME	WHERE RC.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' AND I.RDB$INDEX_NAME = 'PK_LBUTTONS'}

  ALTER TABLE LBUTTONS DROP CONSTRAINT PK_LBUTTONS;
  COMMIT WORK;

  UPDATE LBUTTONS SET PARENT_TYPE_ID = -1 WHERE PARENT_TYPE_ID IS NULL;
  ALTER TABLE LBUTTONS ALTER COLUMN PARENT_TYPE_ID SET NOT NULL;
  COMMIT WORK;

  ALTER TABLE LBUTTONS ADD CONSTRAINT PK_LBUTTONS1 PRIMARY KEY (LEVEL_ID, BUTTON_ID, PARENT_TYPE_ID, OBJ_TYPE_ID);
  COMMIT WORK;

{$ENDIF}


{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS WHERE RDB$FIELD_NAME = 'FLAT' AND RDB$RELATION_NAME = 'VALA' AND RDB$NULL_FLAG = 1}

  ALTER TABLE VALA ALTER FLAT DROP NOT NULL;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_LESSON_ATTRS'}

  CREATE GENERATOR CJ2_ATTR_GEN;

  CREATE TABLE CJ2_LESSON_ATTRS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LESSON_ID    BIGINT NOT NULL,
    ATTR_NAME    VARCHAR(100) NOT NULL,
    ATTR_VALUE   VARCHAR(400),
    REF_ID       BIGINT,
    LISTVAL_ID   BIGINT
  );

  ALTER TABLE CJ2_LESSON_ATTRS ADD CONSTRAINT PK_CJ2_LESSON_ATTRS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_LESSON_ATTRS ADD CONSTRAINT FK_CJ2_LESSON_ATTRS_1 FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_LESSON_ATTRS ADD CONSTRAINT FK_CJ2_LESSON_ATTRS_2 FOREIGN KEY (REF_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_LESSON_ATTRS ADD CONSTRAINT FK_CJ2_LESSON_ATTRS_3 FOREIGN KEY (LISTVAL_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  CREATE INDEX CJ2_LESSON_ATTRS_IDX1 ON CJ2_LESSON_ATTRS (LESSON_ID, ATTR_NAME);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_LESSON_ATTRS_BI0 FOR CJ2_LESSON_ATTRS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (NEXT VALUE FOR CJ2_ATTR_GEN) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_LESSON_ATTRS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'ATT_REGISTER'}

  CREATE GENERATOR GEN_ATTESTATION;

  CREATE TABLE ATT_REGISTER (
    OBJ_ID           BIGINT NOT NULL,
    DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL         TIMESTAMP,
    ATT_DATE         DATE,
    STATE_ID         SMALLINT default 0 NOT NULL,
    YEAR_ID          BIGINT NOT NULL,
    GROUP_ID         BIGINT, 
    SUBJECT_ID       BIGINT NOT NULL,
    CONTROL_TYPE_ID  BIGINT NOT NULL,
    STAGE_ID         BIGINT NOT NULL,
    SUBSTAGE_ID      SMALLINT NOT NULL,
    USER_ID          BIGINT,
    COMMENTS         VARCHAR(400),
    GROUP_NAME       VARCHAR(400),
    ROOM_ID          BIGINT,
    TIME_VAL         VARCHAR(100)
  );

  ALTER TABLE ATT_REGISTER ADD CONSTRAINT PK_ATT_REGISTER PRIMARY KEY (OBJ_ID);
  ALTER TABLE ATT_REGISTER ADD CONSTRAINT FK_ATT_REGISTER_1 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER ADD CONSTRAINT FK_ATT_REGISTER_2 FOREIGN KEY (SUBJECT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER ADD CONSTRAINT FK_ATT_REGISTER_3 FOREIGN KEY (CONTROL_TYPE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER ADD CONSTRAINT FK_ATT_REGISTER_4 FOREIGN KEY (STAGE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER ADD CONSTRAINT FK_ATT_REGISTER_5 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER ADD CONSTRAINT FK_ATT_REGISTER_6 FOREIGN KEY (GROUP_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER ATT_REGISTER_BI0 FOR ATT_REGISTER
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_ATTESTATION, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON ATT_REGISTER TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'ROOM_ID' AND RDB$RELATION_NAME = 'ATT_REGISTER'}

  ALTER TABLE ATT_REGISTER ADD ROOM_ID BIGINT; 
  ALTER TABLE ATT_REGISTER ADD TIME_VAL VARCHAR(100);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'ATT_REGISTER_STUFF'}

  CREATE TABLE ATT_REGISTER_STUFF (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    ATT_ID       BIGINT NOT NULL,
    PERSON_ID    BIGINT NOT NULL
  );

  ALTER TABLE ATT_REGISTER_STUFF ADD CONSTRAINT PK_ATT_REGISTER_STUFF PRIMARY KEY (OBJ_ID);
  ALTER TABLE ATT_REGISTER_STUFF ADD CONSTRAINT FK_ATT_REGISTER_STUFF_1 FOREIGN KEY (ATT_ID) REFERENCES ATT_REGISTER (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER_STUFF ADD CONSTRAINT FK_ATT_REGISTER_STUFF_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER ATT_REGISTER_STUFF_BI0 FOR ATT_REGISTER_STUFF
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_ATTESTATION, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON ATT_REGISTER_STUFF TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'ATT_REGISTER_STDS'}

  CREATE TABLE ATT_REGISTER_STDS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    ATT_ID       BIGINT NOT NULL,
    PERSON_ID    BIGINT NOT NULL,
    STATE_ID     SMALLINT DEFAULT 0 NOT NULL,
    MARK_ID      BIGINT
  );

  ALTER TABLE ATT_REGISTER_STDS ADD CONSTRAINT PK_ATT_REGISTER_STDS PRIMARY KEY (OBJ_ID);
  ALTER TABLE ATT_REGISTER_STDS ADD CONSTRAINT FK_ATT_REGISTER_STDS_1 FOREIGN KEY (ATT_ID) REFERENCES ATT_REGISTER (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER_STDS ADD CONSTRAINT FK_ATT_REGISTER_STDS_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE ATT_REGISTER_STDS ADD CONSTRAINT FK_ATT_REGISTER_STDS_3 FOREIGN KEY (MARK_ID) REFERENCES VALM (MARK_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER ATT_REGISTER_STDS_BI0 FOR ATT_REGISTER_STDS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_ATTESTATION, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON ATT_REGISTER_STDS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'MARK_TEACHER_ID' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD MARK_TEACHER_ID BIGINT; 
  COMMIT WORK;
  ALTER TABLE VALM ADD CONSTRAINT FK_VALM_8 FOREIGN KEY (MARK_TEACHER_ID) REFERENCES OBJECTS(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SEQ_INDEX' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD SEQ_INDEX SMALLINT DEFAULT 0 NOT NULL; 
  ALTER TABLE VALM ADD PREV_ID BIGINT;
  COMMIT WORK;
  CREATE INDEX VALM_IDX3 ON VALM (PREV_ID);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PLAN_HOURS' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD PLAN_HOURS FLOAT; 
  ALTER TABLE VALM ADD CONTROL_TYPE_ID BIGINT; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PTP_HOURS' AND RDB$RELATION_NAME = 'VALM'}

  ALTER TABLE VALM ADD PTP_HOURS FLOAT; 
  ALTER TABLE VALM ADD FACT_HOURS FLOAT; 
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'JOB_ID' AND RDB$RELATION_NAME = 'ORDER_DATA'}

  ALTER TABLE ORDER_DATA ADD JOB_ID BIGINT;
  ALTER TABLE ORDER_DATA ADD CONSTRAINT FK_ORDER_DATA_3 FOREIGN KEY (JOB_ID) REFERENCES OBJECTS(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'JOB_ID2' AND RDB$RELATION_NAME = 'ORDER_DATA'}

  ALTER TABLE ORDER_DATA ADD JOB_ID2 BIGINT;
  ALTER TABLE ORDER_DATA ADD CONSTRAINT FK_ORDER_DATA_4 FOREIGN KEY (JOB_ID2) REFERENCES OBJECTS(OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OWNER_ID' AND RDB$RELATION_NAME = 'ORDERS'}

  ALTER TABLE ORDERS ADD OWNER_ID BIGINT;
  ALTER TABLE ORDERS ADD CONSTRAINT FK_ORDERS_6 FOREIGN KEY (OWNER_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'HST_ID' AND RDB$RELATION_NAME = 'HISTVALS'}

  CREATE GENERATOR GEN_HISTORY;

  CREATE TABLE HISTVALS (
    HST_ID      BIGINT NOT NULL,
    DATE_ADD    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    TABLE_NAME  VARCHAR(40) CHARACTER SET ASCII,
    OBJ_ID      BIGINT,
    PARAM_ID    BIGINT,
    OPT_ID      BIGINT,
    PARENT_ID   BIGINT,
    VAL         VARCHAR(1000),
    OLD_VAL     VARCHAR(1000),
    USER_ID     BIGINT
  );

  ALTER TABLE HISTVALS ADD CONSTRAINT PK_HISTVALS PRIMARY KEY (HST_ID);
  CREATE INDEX HISTVALS_IDX1 ON HISTVALS (TABLE_NAME, OBJ_ID, PARAM_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER HISTVALS_BI0 FOR HISTVALS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.HST_ID IS NULL) THEN
    BEGIN
      NEW.HST_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_HISTORY);
    END
    IF(NEW.DATE_ADD IS NULL) THEN NEW.DATE_ADD = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON HISTVALS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'VERIFY_VALS'}

  CREATE TABLE VERIFY_VALS (
    OBJ_ID    BIGINT NOT NULL,
    PARAM_ID  BIGINT NOT NULL,
    CNT       INTEGER,
    FCNT      INTEGER
  );

  ALTER TABLE VERIFY_VALS ADD CONSTRAINT PK_VERIFY_VALS PRIMARY KEY (OBJ_ID, PARAM_ID);
  ALTER TABLE VERIFY_VALS ADD CONSTRAINT FK_VERIFY_VALS_1 FOREIGN KEY (OBJ_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE VERIFY_VALS ADD CONSTRAINT FK_VERIFY_VALS_2 FOREIGN KEY (PARAM_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  GRANT ALL ON VERIFY_VALS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'OPLIST_PLANS'}

  CREATE TABLE OPLIST_PLANS (
    OBJ_ID         BIGINT NOT NULL,
    OU_ID          BIGINT,
    OP_ID          BIGINT,
    OU_NAME        VARCHAR(200),
    FULL_NAME      VARCHAR(400),
    OGRN           VARCHAR(20),
    AREA_ID        BIGINT,
    OP_NAME        VARCHAR(200),
    PLAN_NAME      VARCHAR(200),
    OP_LEVEL_ID    BIGINT,
    OP_ADAPT_ID    BIGINT,
    WEEKLEN        SMALLINT,
    ADVSUBJ        VARCHAR(1000),
    GZNAMES        VARCHAR(1000),
    GZCODES        VARCHAR(1000),
    AT_HOME_ID     BIGINT,
    IS_NET_ID      BIGINT,
    IS_DIST_ID     BIGINT,
    HAS_ADV        BIGINT,
    PLAN_TYPE_ID   BIGINT,
    PROFILE_ID     BIGINT,
    OP_FORM_ID     BIGINT,
    FGOS_ID        BIGINT,
    CNT_GZ         INTEGER,
    CNT_20         INTEGER,
    CNT_ALL        INTEGER,
    SUM_HOURS      INTEGER,
    STAGE_LOADS    VARCHAR(400),
    STAGE_COUNTS   VARCHAR(400),
    SUBJECT_NAMES  VARCHAR(4000)
  );

  ALTER TABLE OPLIST_PLANS ADD CONSTRAINT PK_OPLIST_PLANS PRIMARY KEY (OBJ_ID);
  ALTER TABLE OPLIST_PLANS ADD CONSTRAINT FK_OPLIST_PLANS_1 FOREIGN KEY (OBJ_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX OPLIST_PLANS_IDX1 ON OPLIST_PLANS (OU_NAME);
  CREATE INDEX OPLIST_PLANS_IDX10 ON OPLIST_PLANS (CNT_20);
  CREATE INDEX OPLIST_PLANS_IDX11 ON OPLIST_PLANS (CNT_ALL);
  CREATE INDEX OPLIST_PLANS_IDX2 ON OPLIST_PLANS (FULL_NAME);
  CREATE INDEX OPLIST_PLANS_IDX3 ON OPLIST_PLANS (OGRN);
  CREATE INDEX OPLIST_PLANS_IDX4 ON OPLIST_PLANS (AREA_ID);
  CREATE INDEX OPLIST_PLANS_IDX5 ON OPLIST_PLANS (OP_NAME, PLAN_NAME, SUM_HOURS);
  CREATE INDEX OPLIST_PLANS_IDX6 ON OPLIST_PLANS (PLAN_NAME, SUM_HOURS);
  CREATE INDEX OPLIST_PLANS_IDX7 ON OPLIST_PLANS (OP_LEVEL_ID);
  CREATE INDEX OPLIST_PLANS_IDX8 ON OPLIST_PLANS (OP_ADAPT_ID);
  CREATE INDEX OPLIST_PLANS_IDX9 ON OPLIST_PLANS (CNT_GZ);
  COMMIT WORK;

  GRANT ALL ON OPLIST_PLANS TO INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT RDB$GENERATOR_NAME	FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = 'GEN_CJ2_ID'}
  CREATE SEQUENCE GEN_CJ2_ID;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LIST_ID' AND RDB$RELATION_NAME = 'LIB2_LISTS'}

  CREATE GENERATOR GEN_LIB2_LIST;
  GRANT USAGE ON SEQUENCE GEN_LIB2_LIST TO INISSOFT_ROLE;

  CREATE TABLE LIB2_LISTS (
    LIST_ID       BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL      TIMESTAMP,
    LIST_NAME     VARCHAR(1000) NOT NULL,
    MAX_LEVELS    SMALLINT DEFAULT -1 NOT NULL,
    LOCAL_ACCESS  SMALLINT DEFAULT 1 NOT NULL
  );

  ALTER TABLE LIB2_LISTS ADD CONSTRAINT PK_LIB2_LISTS PRIMARY KEY (LIST_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER LIB2_LISTS_BI0 FOR LIB2_LISTS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.LIST_ID IS NULL) THEN
    BEGIN
      NEW.LIST_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_LIST);
    END
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_LISTS_BU0 FOR LIB2_LISTS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON LIB2_LISTS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LISTVAL_ID' AND RDB$RELATION_NAME = 'LIB2_LISTVALS'}

  CREATE GENERATOR GEN_LIB2_LISTVALS;
  GRANT USAGE ON SEQUENCE GEN_LIB2_LISTVALS TO INISSOFT_ROLE;

  CREATE TABLE LIB2_LISTVALS (
    LISTVAL_ID   BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    LIST_ID      BIGINT NOT NULL,
    PARENT_ID    BIGINT,
    VAL          VARCHAR(1000),
    LEVEL_NUM    SMALLINT NOT NULL,
    SVAL         VARCHAR(40)
  );

  ALTER TABLE LIB2_LISTVALS ADD CONSTRAINT PK_LIB2_LISTVALS PRIMARY KEY (LISTVAL_ID);
  COMMIT WORK;

  ALTER TABLE LIB2_LISTVALS ADD CONSTRAINT FK_LIB2_LISTVALS_1 FOREIGN KEY (LIST_ID) REFERENCES LIB2_LISTS (LIST_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_LISTVALS ADD CONSTRAINT FK_LIB2_LISTVALS_2 FOREIGN KEY (PARENT_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  CREATE INDEX LIB2_LISTVALS_IDX1 ON LIB2_LISTVALS (LIST_ID, PARENT_ID);

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER LIB2_LISTVALS_BI1 FOR LIB2_LISTVALS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.LISTVAL_ID IS NULL) THEN
    BEGIN
      NEW.LISTVAL_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_LISTVALS);
    END
    IF(NEW.PARENT_ID IS NULL) THEN
      NEW.LEVEL_NUM = 0;
    ELSE
      NEW.LEVEL_NUM = (SELECT V.LEVEL_NUM FROM LIB2_LISTVALS V WHERE V.LISTVAL_ID = NEW.PARENT_ID) + 1;
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_LISTVALS_BU0 FOR LIB2_LISTVALS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;

    -- По идее нехорошо менять PARENT_ID, но на всякий случай оставим
    IF(NEW.PARENT_ID IS NULL) THEN
      NEW.LEVEL_NUM = 0;
    ELSE
      NEW.LEVEL_NUM = (SELECT V.LEVEL_NUM FROM LIB2_LISTVALS V WHERE V.LISTVAL_ID = NEW.PARENT_ID) + 1;
  end
  ^

  SET TERM ; ^

  GRANT ALL ON LIB2_LISTVALS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'LIB2_LISTVALS_BI0' AND RDB$RELATION_NAME = 'LIB2_LISTVALS'}

  DROP TRIGGER LIB2_LISTVALS_BI0;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER LIB2_LISTVALS_BI1 FOR LIB2_LISTVALS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.LISTVAL_ID IS NULL) THEN
    BEGIN
      NEW.LISTVAL_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_LISTVALS);
    END
    IF(NEW.PARENT_ID IS NULL) THEN
      NEW.LEVEL_NUM = 0;
    ELSE
      NEW.LEVEL_NUM = (SELECT V.LEVEL_NUM FROM LIB2_LISTVALS V WHERE V.LISTVAL_ID = NEW.PARENT_ID) + 1;
  end
  ^
  SET TERM ; ^

  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SVAL' AND RDB$RELATION_NAME = 'LIB2_LISTVALS'}

  ALTER TABLE LIB2_LISTVALS ADD SVAL VARCHAR(40);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'MREPORT_DATA'}

  CREATE GENERATOR GEN_MREPORT_DATA;
  GRANT USAGE ON SEQUENCE GEN_MREPORT_DATA TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE MREPORT_DATA (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    REPORT_ID    BIGINT NOT NULL,
    FIELD_ID     BIGINT NOT NULL,
    DETAIL_ID    BIGINT,
    RATE_DATE    DATE,
    RATE_VALUE   FLOAT,
    RATE_INDEX   SMALLINT
  );


  ALTER TABLE MREPORT_DATA ADD CONSTRAINT PK_MREPORT_DATA PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  ALTER TABLE MREPORT_DATA ADD CONSTRAINT FK_MREPORT_DATA_1 FOREIGN KEY (REPORT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX MREPORT_DATA_IDX1 ON MREPORT_DATA (REPORT_ID, FIELD_ID, DETAIL_ID);

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER MREPORT_DATA_BI0 FOR MREPORT_DATA
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (NEXT VALUE FOR GEN_MREPORT_DATA) + (SELECT GEN * MULTIPLIER FROM GEN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER MREPORT_DATA_BU0 FOR MREPORT_DATA
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON MREPORT_DATA TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'WORKTAB_TYPES'}

  CREATE GENERATOR GEN_WT_TYPES;
  GRANT USAGE ON SEQUENCE GEN_WT_TYPES TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE WORKTAB_TYPES (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    VAL          VARCHAR(1000) NOT NULL,
    SVAL         VARCHAR(10),
    TYPE_ID      SMALLINT DEFAULT 0 NOT NULL,
    WANT_HOURS   SMALLINT DEFAULT 0 NOT NULL
  );

  ALTER TABLE WORKTAB_TYPES ADD CONSTRAINT PK_WORKTAB_TYPES PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER WORKTAB_TYPES_BI0 FOR WORKTAB_TYPES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_WT_TYPES, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  CREATE OR ALTER TRIGGER WORKTAB_TYPES_BU0 FOR WORKTAB_TYPES
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON WORKTAB_TYPES TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'WORKTAB_COLS'}

  CREATE GENERATOR GEN_WT_COLS;
  GRANT USAGE ON SEQUENCE GEN_WT_COLS TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE WORKTAB_COLS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    VAL          VARCHAR(1000) NOT NULL,
    SORT_INDEX   SMALLINT NOT NULL
  );

  ALTER TABLE WORKTAB_COLS ADD CONSTRAINT PK_WORKTAB_COLS PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER WORKTAB_COLS_BI0 FOR WORKTAB_COLS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_WT_COLS, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
    IF(NEW.SORT_INDEX IS NULL) THEN
    BEGIN
      SELECT MAX(C.SORT_INDEX)
      FROM WORKTAB_COLS C
      WHERE C.DATE_DEL IS NULL
      INTO NEW.SORT_INDEX;
      IF(NEW.SORT_INDEX IS NULL) THEN NEW.SORT_INDEX = 1; ELSE NEW.SORT_INDEX = NEW.SORT_INDEX + 1;
    END
  end
  ^

  CREATE OR ALTER TRIGGER WORKTAB_COLS_BU0 FOR WORKTAB_COLS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON WORKTAB_COLS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'WORKTAB_DATA'}

  CREATE GENERATOR GEN_WORKTAB;
  GRANT USAGE ON SEQUENCE GEN_WORKTAB TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE WORKTAB_DATA (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    WORKTAB_ID   BIGINT NOT NULL,
    PERSON_ID    BIGINT NOT NULL,
    JOB_ID       BIGINT NOT NULL,
    COL_INDEX    BIGINT,
    TYPE_ID      BIGINT,
    VAL          FLOAT,
    COMMENTS     VARCHAR(400)
  );

  ALTER TABLE WORKTAB_DATA ADD CONSTRAINT PK_WORKTAB_DATA PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  ALTER TABLE WORKTAB_DATA ADD CONSTRAINT FK_WORKTAB_DATA_1 FOREIGN KEY (WORKTAB_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE WORKTAB_DATA ADD CONSTRAINT FK_WORKTAB_DATA_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE WORKTAB_DATA ADD CONSTRAINT FK_WORKTAB_DATA_3 FOREIGN KEY (JOB_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE WORKTAB_DATA ADD CONSTRAINT FK_WORKTAB_DATA_4 FOREIGN KEY (TYPE_ID) REFERENCES WORKTAB_TYPES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX WORKTAB_DATA_IDX1 ON WORKTAB_DATA (WORKTAB_ID, PERSON_ID, JOB_ID, COL_INDEX);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER WORKTAB_DATA_BI0 FOR WORKTAB_DATA
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_WORKTAB, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  CREATE OR ALTER TRIGGER WORKTAB_DATA_BU0 FOR WORKTAB_DATA
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON WORKTAB_DATA TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'EDULOAD_DATA'}

  CREATE GENERATOR GEN_EDULOAD;
  GRANT USAGE ON SEQUENCE GEN_EDULOAD TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE EDULOAD_DATA (
    OBJ_ID         BIGINT NOT NULL,
    DATE_ADD       TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL       TIMESTAMP,
    PARENT_ID      BIGINT NOT NULL,
    PERSON_ID      BIGINT NOT NULL,
    STAGE_ID       BIGINT,
    GROUP_TYPE_ID  BIGINT,
    GROUP_NAME     VARCHAR(400),
    REF_ID         BIGINT,
    REF_TYPE_ID    BIGINT,
    PLAN_ID        BIGINT,
    LOAD_VAL       FLOAT,
    VAL_DATE       DATE,
    VERIFIED       SMALLINT DEFAULT 0 NOT NULL,
    VAL_FLAG       SMALLINT
  );

  ALTER TABLE EDULOAD_DATA ADD CONSTRAINT PK_EDULOAD_DATA PRIMARY KEY (OBJ_ID);
  COMMIT WORK;

  ALTER TABLE EDULOAD_DATA ADD CONSTRAINT FK_EDULOAD_DATA_1 FOREIGN KEY (PARENT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE EDULOAD_DATA ADD CONSTRAINT FK_EDULOAD_DATA_2 FOREIGN KEY (PERSON_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE EDULOAD_DATA ADD CONSTRAINT FK_EDULOAD_DATA_3 FOREIGN KEY (STAGE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE EDULOAD_DATA ADD CONSTRAINT FK_EDULOAD_DATA_4 FOREIGN KEY (REF_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX EDULOAD_DATA_IDX1 ON EDULOAD_DATA (PARENT_ID, PERSON_ID, STAGE_ID);
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER EDULOAD_DATA_BI0 FOR EDULOAD_DATA
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_EDULOAD, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  CREATE OR ALTER TRIGGER EDULOAD_DATA_BU0 FOR EDULOAD_DATA
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON EDULOAD_DATA TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'VAL_DATE' AND RDB$RELATION_NAME = 'EDULOAD_DATA'}

  ALTER TABLE EDULOAD_DATA ADD VAL_DATE DATE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'VAL_FLAG' AND RDB$RELATION_NAME = 'EDULOAD_DATA'}

  ALTER TABLE EDULOAD_DATA ADD VAL_FLAG SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'TARIFF_DATA'}

  CREATE GENERATOR GEN_TARIFF;
  GRANT USAGE ON SEQUENCE GEN_TARIFF TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE TARIFF_DATA (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    PARENT_ID    BIGINT NOT NULL,
    PERSON_ID    BIGINT,
    JOB_ID       BIGINT NOT NULL,
    ROW_INDEX    SMALLINT,
    VAL          VARCHAR(4000)
  );

  ALTER TABLE TARIFF_DATA ADD CONSTRAINT PK_TARIFF_DATA PRIMARY KEY (OBJ_ID);
  COMMIT WORK;
  ALTER TABLE TARIFF_DATA ADD CONSTRAINT FK_TARIFF_DATA_1 FOREIGN KEY (JOB_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE TARIFF_DATA ADD CONSTRAINT FK_TARIFF_DATA_2 FOREIGN KEY (PARENT_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER TARIFF_DATA_BI0 FOR TARIFF_DATA
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF (NEW.OBJ_ID IS NULL) THEN NEW.OBJ_ID = GEN_ID(GEN_TARIFF, 1) + (SELECT GEN * MULTIPLIER FROM GEN);
  end
  ^

  CREATE OR ALTER TRIGGER TARIFF_DATA_BU0 FOR TARIFF_DATA
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON TARIFF_DATA TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'LIB2_BOOKS'}

  CREATE GENERATOR GEN_LIB2_MAIN;
  GRANT USAGE ON SEQUENCE GEN_LIB2_MAIN TO INISSOFT_ROLE;
  CREATE GENERATOR GEN_LIB2_ABNUM;
  GRANT USAGE ON SEQUENCE GEN_LIB2_ABNUM TO INISSOFT_ROLE;
  COMMIT WORK;

  CREATE TABLE LIB2_BOOKS (
    OBJ_ID        BIGINT NOT NULL,
    DATE_ADD      TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_MODIFY   TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_DEL      TIMESTAMP,
    N_AVAIL       INTEGER DEFAULT 0 NOT NULL,
    N_FREE        INTEGER DEFAULT 0 NOT NULL,
    OBJ_TYPE      BIGINT NOT NULL,
    AUTHOR_ID     BIGINT,
    PUBLISHER_ID  BIGINT NOT NULL,
    CODE_ISBN     VARCHAR(30),
    BOOK_NAME     VARCHAR(400),
    PUB_YEAR      SMALLINT,
    AUTHORS       VARCHAR(400),
    PART_NUM      SMALLINT,
    PART_NAME     VARCHAR(200),
    LANG_ID       BIGINT,
    BOOK_SIZE     VARCHAR(20),
    AGE_GROUP     VARCHAR(20),
    SUBJECT_ID    BIGINT,
    SUBJECT_ID2   BIGINT,
    SUBJECT_ID3   BIGINT,
    PUB_PLACE_ID  BIGINT,
    AUTHOR_SIGN   VARCHAR(10),
    UDK           VARCHAR(100),
    EDITION_TEXT  VARCHAR(200),
    PURPOSE_ID    BIGINT,
    BBK           VARCHAR(100),
    STAGE_NUM     VARCHAR(20),
    STAGE_FROM    SMALLINT,
    STAGE_TO      SMALLINT,
    EDU_LEVEL_ID  BIGINT,
    FPU_ID        BIGINT,
    FPE_ID        BIGINT,
    ADAPT_ID      SMALLINT,
    COMPONENT_ID  BIGINT,
    RELEASE_NUM   VARCHAR(10),
    DIFF_LEVEL_ID  SMALLINT,
    FPU_CODE       VARCHAR(40)
  );

  ALTER TABLE LIB2_BOOKS ADD CONSTRAINT PK_LIB2_BOOKS PRIMARY KEY (OBJ_ID);
  ALTER TABLE LIB2_BOOKS ADD CONSTRAINT FK_LIB2_BOOKS_1 FOREIGN KEY (AUTHOR_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_BOOKS ADD CONSTRAINT FK_LIB2_BOOKS_2 FOREIGN KEY (PUBLISHER_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_BOOKS ADD CONSTRAINT FK_LIB2_BOOKS_3 FOREIGN KEY (LANG_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE LIB2_BOOKS ADD CONSTRAINT FK_LIB2_BOOKS_4 FOREIGN KEY (PUB_PLACE_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE LIB2_BOOKS ADD CONSTRAINT FK_LIB2_BOOKS_5 FOREIGN KEY (PURPOSE_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER LIB2_BOOKS_BI0 FOR LIB2_BOOKS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_MAIN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_BOOKS_BU0 FOR LIB2_BOOKS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON LIB2_BOOKS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FPE_ID' AND RDB$RELATION_NAME = 'LIB2_BOOKS'}

  ALTER TABLE LIB2_BOOKS ADD FPE_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'PART_NUM' AND F.RDB$RELATION_NAME = 'LIB2_BOOKS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 100}

  ALTER TABLE LIB2_BOOKS DROP PART_NUM;
  COMMIT WORK;
  ALTER TABLE LIB2_BOOKS ADD PART_NUM SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$RELATION_FIELDS F, RDB$FIELDS S WHERE F.RDB$FIELD_NAME = 'BOOK_NAME' AND F.RDB$RELATION_NAME = 'LIB2_BOOKS' 
    AND S.RDB$FIELD_NAME = F.RDB$FIELD_SOURCE AND S.RDB$CHARACTER_LENGTH = 200}

  ALTER TABLE LIB2_BOOKS ALTER BOOK_NAME TYPE VARCHAR(400);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'BOOK_ID' AND RDB$RELATION_NAME = 'LIB2_BOOK_ATTRS'}

  CREATE TABLE LIB2_BOOK_ATTRS (
    BOOK_ID      BIGINT NOT NULL,
    LIST_ID      BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_DEL     TIMESTAMP,
    LISTVAL_ID   BIGINT
  );

  ALTER TABLE LIB2_BOOK_ATTRS ADD CONSTRAINT PK_LIB2_BOOK_ATTRS PRIMARY KEY (BOOK_ID, LIST_ID);
  ALTER TABLE LIB2_BOOK_ATTRS ADD CONSTRAINT FK_LIB2_BOOK_ATTRS_1 FOREIGN KEY (BOOK_ID) REFERENCES LIB2_BOOKS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_BOOK_ATTRS ADD CONSTRAINT FK_LIB2_BOOK_ATTRS_2 FOREIGN KEY (LIST_ID) REFERENCES LIB2_LISTS (LIST_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_BOOK_ATTRS ADD CONSTRAINT FK_LIB2_BOOK_ATTRS_3 FOREIGN KEY (LISTVAL_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  GRANT ALL ON LIB2_BOOK_ATTRS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'LIB2_INVOICES'}

  CREATE TABLE LIB2_INVOICES (
    OBJ_ID         BIGINT NOT NULL,
    DATE_ADD       TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_MODIFY    TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_DEL       TIMESTAMP,
    TYPE_ID        SMALLINT NOT NULL,
    ACTION_DATE    DATE NOT NULL,
    ACTION_NUM     VARCHAR(100),
    DOCUMENT_DATE  DATE,
    DOCUMENT_NUM   VARCHAR(100),
    REASON_ID      BIGINT,
    COMMENTS       VARCHAR(1000),
    USER_ID        BIGINT,
    CONTRAGENT_ID  BIGINT,
    LOC_INDEX      SMALLINT,
    DEST_INDEX     SMALLINT,
    USER_ACCEPTED  BIGINT
  );

  ALTER TABLE LIB2_INVOICES ADD CONSTRAINT PK_LIB2_INVOICES PRIMARY KEY (OBJ_ID);
  ALTER TABLE LIB2_INVOICES ADD CONSTRAINT FK_LIB2_INVOICES_1 FOREIGN KEY (REASON_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_INVOICES ADD CONSTRAINT FK_LIB2_INVOICES_2 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE LIB2_INVOICES ADD CONSTRAINT FK_LIB2_INVOICES_3 FOREIGN KEY (CONTRAGENT_ID) REFERENCES LIB2_LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_INVOICES ADD CONSTRAINT FK_LIB2_INVOICES_4 FOREIGN KEY (USER_ACCEPTED) REFERENCES USERS(USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;
  CREATE INDEX LIB2_INVOICES_IDX1 ON LIB2_INVOICES (ACTION_DATE, TYPE_ID);
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER LIB2_INVOICES_BI0 FOR LIB2_INVOICES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_MAIN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_INVOICES_BU0 FOR LIB2_INVOICES
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON LIB2_INVOICES TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LOC_INDEX' AND RDB$RELATION_NAME = 'LIB2_INVOICES'}
  ALTER TABLE LIB2_INVOICES ADD LOC_INDEX SMALLINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DEST_INDEX' AND RDB$RELATION_NAME = 'LIB2_INVOICES'}
  ALTER TABLE LIB2_INVOICES ADD DEST_INDEX SMALLINT;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'USER_ACCEPTED' AND RDB$RELATION_NAME = 'LIB2_INVOICES'}
  ALTER TABLE LIB2_INVOICES ADD USER_ACCEPTED BIGINT;
  ALTER TABLE LIB2_INVOICES ADD CONSTRAINT FK_LIB2_INVOICES_4 FOREIGN KEY (USER_ACCEPTED) REFERENCES USERS(USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;
{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'LIB2_INSTANCES'}

  CREATE TABLE LIB2_INSTANCES (
    OBJ_ID          BIGINT NOT NULL,
    DATE_ADD        TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_MODIFY     TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_DEL        TIMESTAMP,
    BOOK_ID         BIGINT NOT NULL,
    INV_CODE        VARCHAR(40) NOT NULL,
    INV_VALUE       BIGINT NOT NULL,
    INV_DATE        DATE,
    SRC_COST        FLOAT,
    CURRENT_COST    FLOAT,
    SIGLA_ID        BIGINT,
    COMMENTS        VARCHAR(100),
    INVOICE_IN_ID   BIGINT,
    INVOICE_OUT_ID  BIGINT,
    IS_FREE         SMALLINT DEFAULT 1 NOT NULL,
    STATE_ID        BIGINT,
    INVOICE_IN_IDX   SMALLINT,
    INVOICE_OUT_IDX  SMALLINT,
    LOC_INDEX       SMALLINT
  );

  ALTER TABLE LIB2_INSTANCES ADD CONSTRAINT PK_LIB2_INSTANCES PRIMARY KEY (OBJ_ID);
  ALTER TABLE LIB2_INSTANCES ADD CONSTRAINT FK_LIB2_INSTANCES_1 FOREIGN KEY (BOOK_ID) REFERENCES LIB2_BOOKS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_INSTANCES ADD CONSTRAINT FK_LIB2_INSTANCES_2 FOREIGN KEY (INVOICE_IN_ID) REFERENCES LIB2_INVOICES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_INSTANCES ADD CONSTRAINT FK_LIB2_INSTANCES_3 FOREIGN KEY (INVOICE_OUT_ID) REFERENCES LIB2_INVOICES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;
  CREATE INDEX LIB2_INSTANCES_IDX1 ON LIB2_INSTANCES (INV_VALUE);
  CREATE INDEX LIB2_INSTANCES_IDX2 ON LIB2_INSTANCES (INV_CODE);
  CREATE INDEX LIB2_INSTANCES_IDX3 ON LIB2_INSTANCES (BOOK_ID);
  CREATE INDEX LIB2_INSTANCES_IDX4 ON LIB2_INSTANCES (INVOICE_IN_ID, INVOICE_IN_IDX);
  CREATE INDEX LIB2_INSTANCES_IDX5 ON LIB2_INSTANCES (INVOICE_OUT_ID, INVOICE_OUT_IDX);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER LIB2_INSTANCES_BI0 FOR LIB2_INSTANCES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_MAIN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_INSTANCES_BU0 FOR LIB2_INSTANCES
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON LIB2_INSTANCES TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LOC_INDEX' AND RDB$RELATION_NAME = 'LIB2_INSTANCES'}

  ALTER TABLE LIB2_INSTANCES ADD LOC_INDEX SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'LIB2_BATCHES'}

  CREATE TABLE LIB2_BATCHES (
    OBJ_ID           BIGINT NOT NULL,
    DATE_ADD         TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_MODIFY      TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_DEL         TIMESTAMP,
    BOOK_ID          BIGINT NOT NULL,
    QUANTITY         INTEGER NOT NULL,
    CURRENT_PRICE    FLOAT,
    INVOICE_IN_ID    BIGINT,
    INVOICE_OUT_ID   BIGINT,
    STATE_ID         BIGINT,
    INVOICE_IN_IDX   SMALLINT,
    INVOICE_OUT_IDX  SMALLINT,
    LOC_INDEX        SMALLINT
  );

  ALTER TABLE LIB2_BATCHES ADD CONSTRAINT PK_LIB2_BATCHES PRIMARY KEY (OBJ_ID);
  ALTER TABLE LIB2_BATCHES ADD CONSTRAINT FK_LIB2_BATCHES_1 FOREIGN KEY (BOOK_ID) REFERENCES LIB2_BOOKS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_BATCHES ADD CONSTRAINT FK_LIB2_BATCHES_2 FOREIGN KEY (INVOICE_IN_ID) REFERENCES LIB2_INVOICES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_BATCHES ADD CONSTRAINT FK_LIB2_BATCHES_3 FOREIGN KEY (INVOICE_OUT_ID) REFERENCES LIB2_INVOICES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;
  CREATE INDEX LIB2_BATCHES_IDX1 ON LIB2_BATCHES (INVOICE_IN_ID, INVOICE_IN_IDX);
  CREATE INDEX LIB2_BATCHES_IDX2 ON LIB2_BATCHES (INVOICE_OUT_ID, INVOICE_OUT_IDX);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER LIB2_BATCHES_BI0 FOR LIB2_BATCHES
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_MAIN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_BATCHES_BU0 FOR LIB2_BATCHES
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON LIB2_BATCHES TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LOC_INDEX' AND RDB$RELATION_NAME = 'LIB2_BATCHES'}

  ALTER TABLE LIB2_BATCHES ADD LOC_INDEX SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'LIB2_USAGE'}

  CREATE TABLE LIB2_USAGE (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT current_timestamp NOT NULL,
    DATE_DEL     TIMESTAMP,
    BOOK_ID      BIGINT NOT NULL,
    INSTANCE_ID  BIGINT,
    REF_ID       BIGINT NOT NULL,
    REF_TYPE_ID  BIGINT NOT NULL,
    ACTION_DATE  DATE NOT NULL,
    PLAN_DATE    DATE,
    RETURN_DATE  DATE,
    LOSS_DATE    DATE,
    USER_ID      BIGINT,
    RET_USER_ID  BIGINT,
    QUANTITY     INTEGER DEFAULT 1 NOT NULL,
    CLASS_USAGE_ID  BIGINT,
    LOC_INDEX    SMALLINT,
    LOAD_ID      BIGINT
  );

  ALTER TABLE LIB2_USAGE ADD CONSTRAINT PK_LIB2_USAGE PRIMARY KEY (OBJ_ID);
  ALTER TABLE LIB2_USAGE ADD CONSTRAINT FK_LIB2_USAGE_1 FOREIGN KEY (BOOK_ID) REFERENCES LIB2_BOOKS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_USAGE ADD CONSTRAINT FK_LIB2_USAGE_2 FOREIGN KEY (INSTANCE_ID) REFERENCES LIB2_INSTANCES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_USAGE ADD CONSTRAINT FK_LIB2_USAGE_3 FOREIGN KEY (REF_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE LIB2_USAGE ADD CONSTRAINT FK_LIB2_USAGE_4 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  ALTER TABLE LIB2_USAGE ADD CONSTRAINT FK_LIB2_USAGE_5 FOREIGN KEY (RET_USER_ID) REFERENCES USERS (USER_ID) ON DELETE SET NULL ON UPDATE CASCADE;
  COMMIT WORK;
  CREATE INDEX LIB2_USAGE_IDX1 ON LIB2_USAGE (CLASS_USAGE_ID, DATE_DEL);
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER LIB2_USAGE_BI0 FOR LIB2_USAGE
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_LIB2_MAIN);
    END
    NEW.REF_TYPE_ID = (SELECT TYPE_ID FROM OBJECTS WHERE OBJ_ID = NEW.REF_ID);
  end
  ^

  CREATE OR ALTER TRIGGER LIB2_USAGE_BU0 FOR LIB2_USAGE
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON LIB2_USAGE TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LOC_INDEX' AND RDB$RELATION_NAME = 'LIB2_USAGE'}

  ALTER TABLE LIB2_USAGE ADD LOC_INDEX SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'LOAD_ID' AND RDB$RELATION_NAME = 'LIB2_USAGE'}

  ALTER TABLE LIB2_USAGE ADD LOAD_ID BIGINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'OP_CONTENT'}

  CREATE GENERATOR GEN_OP;
  GRANT USAGE ON SEQUENCE GEN_OP TO INISSOFT_ROLE;

  CREATE TABLE OP_CONTENT (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    OP_ID        BIGINT NOT NULL,
    SEQ_INDEX    INTEGER,
    PARENT_ID    BIGINT,
    TYPE_ID      BIGINT NOT NULL,
    TEXT         VARCHAR(1000),
    BLOB_DATA    BLOB SUB_TYPE 1 SEGMENT SIZE 80,
    SC_INDEX     SMALLINT
  );

  ALTER TABLE OP_CONTENT ADD CONSTRAINT PK_OP_CONTENT PRIMARY KEY (OBJ_ID);
  COMMIT WORK;
  ALTER TABLE OP_CONTENT ADD CONSTRAINT FK_OP_CONTENT_1 FOREIGN KEY (OP_ID) REFERENCES OBJECTS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE OP_CONTENT ADD CONSTRAINT FK_OP_CONTENT_2 FOREIGN KEY (TYPE_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE OP_CONTENT ADD CONSTRAINT FK_OP_CONTENT_3 FOREIGN KEY (PARENT_ID) REFERENCES OP_CONTENT (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;
  CREATE OR ALTER TRIGGER OP_CONTENT_BI0 FOR OP_CONTENT
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_OP);
    END
  end
  ^

  CREATE OR ALTER TRIGGER OP_CONTENT_BU0 FOR OP_CONTENT
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON OP_CONTENT TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'SC_INDEX' AND RDB$RELATION_NAME = 'OP_CONTENT'}

  ALTER TABLE OP_CONTENT ADD SC_INDEX SMALLINT;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'USER_ID' AND RDB$RELATION_NAME = 'USER_EVENTS'}

  CREATE TABLE USER_EVENTS (
    USER_ID     BIGINT,
    OBJ_ID      BIGINT,
    DATE_ADD    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    EVENT_TYPE  VARCHAR(20) NOT NULL,
    VAL         VARCHAR(400),
    AUTHOR_ID   BIGINT
  );
                                                                                
  CREATE INDEX USER_EVENTS_IDX1 ON USER_EVENTS (USER_ID, DATE_ADD);
  CREATE INDEX USER_EVENTS_IDX2 ON USER_EVENTS (DATE_ADD, EVENT_TYPE);
  CREATE INDEX USER_EVENTS_IDX3 ON USER_EVENTS (AUTHOR_ID, DATE_ADD);

  GRANT ALL ON USER_EVENTS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'PKG_NAME' AND RDB$RELATION_NAME = 'TYPES'}

  ALTER TABLE TYPES ADD PKG_NAME VARCHAR(40);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'FIELD_NAME' AND RDB$RELATION_NAME = 'PARAMS'}

  ALTER TABLE PARAMS ADD FIELD_NAME VARCHAR(40);
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'PTP_LESSON_TESTS'}

  CREATE TABLE PTP_LESSON_TESTS (
    OBJ_ID           BIGINT NOT NULL,
    DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL         TIMESTAMP,
    LESSON_ID        BIGINT NOT NULL,
    CONTROL_TYPE_ID  BIGINT NOT NULL,
    TEST_ID          BIGINT
  );

  ALTER TABLE PTP_LESSON_TESTS ADD CONSTRAINT PK_PTP_LESSON_TESTS PRIMARY KEY (OBJ_ID);
  ALTER TABLE PTP_LESSON_TESTS ADD CONSTRAINT FK_PTP_LESSON_TESTS_1 FOREIGN KEY (LESSON_ID) REFERENCES PTP_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PTP_LESSON_TESTS ADD CONSTRAINT FK_PTP_LESSON_TESTS_2 FOREIGN KEY (CONTROL_TYPE_ID) REFERENCES CJ2_CONTROL_TYPE (CONTROL_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE PTP_LESSON_TESTS ADD CONSTRAINT FK_PTP_LESSON_TESTS_3 FOREIGN KEY (TEST_ID) REFERENCES UT_EXAM_DATES (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER PTP_LESSON_TESTS_BI0 FOR PTP_LESSON_TESTS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
  IF(NEW.OBJ_ID IS NULL) THEN
    NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_PTP);
  end
  ^
  SET TERM ; ^

  GRANT ALL ON PTP_LESSON_TESTS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'DATE_ADD' AND RDB$RELATION_NAME = 'PDA_LOG'}

  CREATE TABLE PDA_LOG (
    DATE_ADD    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    USER_ID     BIGINT NOT NULL,
    LEVEL_ID    BIGINT,
    OBJ_ID      BIGINT,
    EXTRA_DATA  VARCHAR(1000),
    FROM_IP     VARCHAR(200)
  );

  ALTER TABLE PDA_LOG ADD CONSTRAINT FK_PDA_LOG_1 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX PDA_LOG_IDX1 ON PDA_LOG (DATE_ADD, USER_ID);
  CREATE INDEX PDA_LOG_IDX2 ON PDA_LOG (OBJ_ID, DATE_ADD);
  CREATE INDEX PDA_LOG_IDX3 ON PDA_LOG (FROM_IP, DATE_ADD);
  COMMIT WORK;

  GRANT ALL ON PDA_LOG TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_CONTROL_COST'}

  CREATE GENERATOR CJ2_CC_GEN;

  CREATE TABLE CJ2_CONTROL_COST (
    OBJ_ID           BIGINT NOT NULL,
    DATE_ADD         TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY      TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL         TIMESTAMP,
    CONTROL_TYPE_ID  BIGINT NOT NULL,
    YEAR_ID          BIGINT NOT NULL,
    LEVEL_ID         BIGINT,
    COST             FLOAT
  );

  ALTER TABLE CJ2_CONTROL_COST ADD CONSTRAINT PK_CJ2_CONTROL_COST PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_CONTROL_COST ADD CONSTRAINT FK_CJ2_CONTROL_COST_1 FOREIGN KEY (CONTROL_TYPE_ID) REFERENCES CJ2_CONTROL_TYPE (CONTROL_TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_CONTROL_COST ADD CONSTRAINT FK_CJ2_CONTROL_COST_2 FOREIGN KEY (YEAR_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_CONTROL_COST ADD CONSTRAINT FK_CJ2_CONTROL_COST_3 FOREIGN KEY (LEVEL_ID) REFERENCES LISTVALS (LISTVAL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX CJ2_CONTROL_COST_IDX1 ON CJ2_CONTROL_COST (YEAR_ID, LEVEL_ID, CONTROL_TYPE_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_CONTROL_COST_BI0 FOR CJ2_CONTROL_COST
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR CJ2_CC_GEN);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_CONTROL_COST_BU0 FOR CJ2_CONTROL_COST
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_CONTROL_COST TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'DC_FILTERS'}

  CREATE GENERATOR GEN_FILTERS;

  CREATE TABLE DC_FILTERS (
    OBJ_ID       BIGINT NOT NULL,
    DATE_ADD     TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY  TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL     TIMESTAMP,
    USER_ID      BIGINT NOT NULL,
    LEVEL_ID     BIGINT NOT NULL,
    OBJ_NAME     VARCHAR(200),
    TYPE_ID      BIGINT NOT NULL,
    VAL          VARCHAR(8000) CHARACTER SET WIN1251
  );  

  ALTER TABLE DC_FILTERS ADD CONSTRAINT PK_DC_FILTERS PRIMARY KEY (OBJ_ID);
  ALTER TABLE DC_FILTERS ADD CONSTRAINT FK_DC_FILTERS_1 FOREIGN KEY (USER_ID) REFERENCES USERS (USER_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE DC_FILTERS ADD CONSTRAINT FK_DC_FILTERS_2 FOREIGN KEY (LEVEL_ID) REFERENCES LEVELS (LEVEL_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE DC_FILTERS ADD CONSTRAINT FK_DC_FILTERS_3 FOREIGN KEY (TYPE_ID) REFERENCES TYPES (TYPE_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  CREATE INDEX DC_FILTERS_IDX1 ON DC_FILTERS (USER_ID, LEVEL_ID, TYPE_ID);
  COMMIT WORK;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER DC_FILTERS_BI0 FOR DC_FILTERS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_FILTERS);
    END
  end
  ^

  CREATE OR ALTER TRIGGER DC_FILTERS_BU0 FOR DC_FILTERS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON DC_FILTERS TO ROLE INISSOFT_ROLE;
  COMMIT WORK;

{$ENDIF}

{$IFNOTEXISTS SELECT 1 FROM RDB$RELATION_FIELDS	WHERE RDB$FIELD_NAME = 'OBJ_ID' AND RDB$RELATION_NAME = 'CJ2_HOMEWORKS'}

  CREATE GENERATOR GEN_CJ2_HOMEWORK;

  CREATE TABLE CJ2_HOMEWORKS (
    OBJ_ID         BIGINT NOT NULL,
    DATE_ADD       TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_MODIFY    TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
    DATE_DEL       TIMESTAMP,
    LESSON_ID      BIGINT NOT NULL,
    DST_LESSON_ID  BIGINT,
    DST_DATE       DATE,
    HW_TEXT        VARCHAR(1000) NOT NULL,
    STUDENT_IDS    VARCHAR(2000) CHARACTER SET ASCII
  );

  ALTER TABLE CJ2_HOMEWORKS ADD CONSTRAINT PK_CJ2_HOMEWORKS PRIMARY KEY (OBJ_ID);
  ALTER TABLE CJ2_HOMEWORKS ADD CONSTRAINT FK_CJ2_HOMEWORKS_1 FOREIGN KEY (LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;
  ALTER TABLE CJ2_HOMEWORKS ADD CONSTRAINT FK_CJ2_HOMEWORKS_2 FOREIGN KEY (DST_LESSON_ID) REFERENCES CJ2_JOURNAL_LESSONS (OBJ_ID) ON DELETE CASCADE ON UPDATE CASCADE;

  SET TERM ^ ;

  CREATE OR ALTER TRIGGER CJ2_HOMEWORKS_BI0 FOR CJ2_HOMEWORKS
  ACTIVE BEFORE INSERT POSITION 0
  AS
  begin
    IF(NEW.OBJ_ID IS NULL) THEN
    BEGIN
      NEW.OBJ_ID = (SELECT GEN * MULTIPLIER FROM GEN) + (NEXT VALUE FOR GEN_CJ2_HOMEWORK);
    END
  end
  ^

  CREATE OR ALTER TRIGGER CJ2_HOMEWORKS_BU0 FOR CJ2_HOMEWORKS
  ACTIVE BEFORE UPDATE POSITION 0
  AS
  begin
    NEW.DATE_MODIFY = CURRENT_TIMESTAMP;
  end
  ^
  SET TERM ; ^

  GRANT ALL ON CJ2_HOMEWORKS TO ROLE INISSOFT_ROLE;

{$ENDIF}

{$IFEXISTS SELECT 1 FROM RDB$DATABASE WHERE SUBSTRING(RDB$GET_CONTEXT('SYSTEM', 'ENGINE_VERSION') FROM 1 FOR 1) IN ('3', '4')}

  GRANT USAGE ON EXCEPTION DATA_ERROR TO INISSOFT_ROLE;

  GRANT USAGE ON SEQUENCE GEN_MOVEMENTS_ID TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_RT_ID TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE PLAN_GEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE CJ2_AUDIT_GEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE CEC_GEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_SCHEDULE TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE RGN_GEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_ORDERS TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CS_REPORTS TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CJ_ACCESS TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CJ2_HISTORY TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_STAT_ID TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CJ_RES_ID TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_SYNC_LOG TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE UT_BASEGEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_GIA_ON_NUM TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_PTP TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_BOT TO INISSOFT_ROLE;  
  GRANT USAGE ON SEQUENCE CJ2_ATTR_GEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_ATTESTATION TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_HISTORY TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CJ2_ID TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CJ2_MS_ID TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE CJ2_CC_GEN TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_FILTERS TO INISSOFT_ROLE;
  GRANT USAGE ON SEQUENCE GEN_CJ2_HOMEWORK TO INISSOFT_ROLE;

{$ENDIF}

  SET TERM ^ ;
  EXECUTE BLOCK 
  AS
  DECLARE F VARCHAR(200);
  BEGIN
    FOR
      SELECT RDB$FUNCTION_NAME 
      FROM RDB$FUNCTIONS
      WHERE RDB$MODULE_NAME = 'ib_udf' or RDB$MODULE_NAME = 'fbudf'
      INTO :F
    DO
    BEGIN
      EXECUTE STATEMENT 'DROP EXTERNAL FUNCTION "' || :F || '";';
    END
  END
  ^
  SET TERM ; ^
  COMMIT WORK;
