 
/*
 | Tables for MS SQL Server
 | SOS GmbH, 2021-11-30
*/

SET ANSI_DEFAULTS ON;

 
/* Table for IAM_BLOCKLIST */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_BLOCKLIST'))
BEGIN
    CREATE TABLE IAM_BLOCKLIST (
        "ID"                    BIGINT        IDENTITY(1,1)  NOT NULL,
        "ACCOUNT_NAME"          NVARCHAR(255) NOT NULL,
        "COMMENT"               NVARCHAR(255) NULL,
        "SINCE"                 DATETIME      NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

/* Table for IAM_HISTORY */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_HISTORY'))
BEGIN
    CREATE TABLE IAM_HISTORY (
        "ID"                    BIGINT        IDENTITY(1,1)  NOT NULL,
        "ACCOUNT_NAME"          NVARCHAR(255) NOT NULL,
        "IDENTITY_SERVICE_ID"   BIGINT        NOT NULL DEFAULT 0,
        "LOGIN_DATE"            DATETIME      NOT NULL,
        "LOGIN_SUCCESS"         TINYINT       NOT NULL DEFAULT 0,       
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_IAMH_ISID  ON IAM_HISTORY("IDENTITY_SERVICE_ID");
    CREATE INDEX IDX_IAMH_LD    ON IAM_HISTORY("LOGIN_DATE");
END;
GO

/* Table for IAM_HISTORY_DETAILS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_HISTORY_DETAILS'))
BEGIN
    CREATE TABLE IAM_HISTORY_DETAILS (
        "ID"                    BIGINT        IDENTITY(1,1)  NOT NULL,
        "IAM_HISTORY_ID"        BIGINT         NOT NULL,
        "IDENTITY_SERVICE_NAME" NVARCHAR(255)  NOT NULL,
        "MESSAGE"               NVARCHAR(2000)  NOT NULL,       
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_IAMHD_HID  ON IAM_HISTORY_DETAILS("IAM_HISTORY_ID");
END;
GO

  
/* Table for IAM_ACCOUNTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_ACCOUNTS'))
BEGIN
    CREATE TABLE IAM_ACCOUNTS (
        "ID"                    BIGINT        IDENTITY(1,1)  NOT NULL,
        "IDENTITY_SERVICE_ID"   BIGINT        NOT NULL,    
        "ACCOUNT_NAME"          NVARCHAR(255) NOT NULL,
        "EMAIL"                 NVARCHAR(255),
        "ACCOUNT_PASSWORD"      NVARCHAR(255) DEFAULT '.'   NOT NULL,
        "FORCE_PASSWORD_CHANGE" TINYINT       NOT NULL DEFAULT 0,
        "DISABLED"              TINYINT       NOT NULL DEFAULT 0,       
        CONSTRAINT UNIQUE_IAM_A_IN UNIQUE ("IDENTITY_SERVICE_ID", "ACCOUNT_NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM IAM_ACCOUNTS;
COMMIT;

/* Table for IAM_FIDO2_DEVICES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_FIDO2_DEVICES'))
BEGIN
    CREATE TABLE IAM_FIDO2_DEVICES (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "IDENTITY_SERVICE_ID"   BIGINT         NOT NULL,
        "ACCOUNT_ID"            BIGINT         NOT NULL,    
        "PUBLIC_KEY"            NVARCHAR(1024) NOT NULL,
        "ALGORITHM"             NVARCHAR(60)   NOT NULL,
        "CREDENTIAL_ID"         NVARCHAR(255),
        "ORIGIN"                NVARCHAR(255)  NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM IAM_FIDO2_DEVICES;
COMMIT;


 
/* Table for IAM_ROLES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_ROLES'))
BEGIN
    CREATE TABLE IAM_ROLES (
        "ID"                   BIGINT        IDENTITY(1,1)  NOT NULL,
        "IDENTITY_SERVICE_ID"  BIGINT        NOT NULL,    
        "ROLE_NAME"            NVARCHAR(255) NOT NULL,
	    "ORDERING"             INT           NULL,
        CONSTRAINT UNIQUE_IAM_R_IR UNIQUE ("IDENTITY_SERVICE_ID", "ROLE_NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM IAM_ROLES;
COMMIT;


/* Table for IAM_ACCOUNT2ROLES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_ACCOUNT2ROLES'))
BEGIN
    CREATE TABLE IAM_ACCOUNT2ROLES(
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "ROLE_ID"               BIGINT  NOT NULL,
        "ACCOUNT_ID"            BIGINT  NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM IAM_ACCOUNT2ROLES;
COMMIT;

 

/* Table for IAM_PERMISSIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_PERMISSIONS'))
BEGIN
    CREATE TABLE IAM_PERMISSIONS(
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "IDENTITY_SERVICE_ID"   BIGINT         NOT NULL,    
        "CONTROLLER_ID"         NVARCHAR(255)  NULL,   
        "ACCOUNT_ID"            BIGINT         NULL,
        "ROLE_ID"               BIGINT         NULL,
        "ACCOUNT_PERMISSION"    NVARCHAR(255)  NULL,   
        "FOLDER_PERMISSION"     NVARCHAR(255)  NULL,   
        "EXCLUDED"              TINYINT        NOT NULL DEFAULT 0,
        "RECURSIVE"             TINYINT        NOT NULL DEFAULT 0,       
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM IAM_PERMISSIONS;
COMMIT;  
 
 

/* Table for IAM_IDENTITY_SERVICES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_IDENTITY_SERVICES'))
BEGIN
    CREATE TABLE IAM_IDENTITY_SERVICES(
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "IDENTITY_SERVICE_TYPE" NVARCHAR(255)  NOT NULL,  
        "IDENTITY_SERVICE_NAME" NVARCHAR(255)  NOT NULL,  
        "SECOND_FACTOR_IS_ID"   BIGINT,  
        "AUTHENTICATION_SCHEME" NVARCHAR(255)  NOT NULL,
        "SECOND_FACTOR"         TINYINT        NOT NULL DEFAULT 0,
	    "ORDERING"              INT            NOT NULL,
        "REQUIRED"              TINYINT        NOT NULL DEFAULT 0,
        "DISABLED"              TINYINT        NOT NULL DEFAULT 0,       
        CONSTRAINT UNIQUE_IAM_S_N UNIQUE ("IDENTITY_SERVICE_NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM IAM_IDENTITY_SERVICES;
COMMIT;  
 
/* Table for IAM_FIDO2_REGISTRATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_FIDO2_REGISTRATIONS'))
BEGIN
    CREATE TABLE IAM_FIDO2_REGISTRATIONS(
        "ID"                  BIGINT         IDENTITY(1,1)  NOT NULL,
        "EMAIL"               NVARCHAR(255)  NOT NULL,
        "IDENTITY_SERVICE_ID" BIGINT         NOT NULL,
        "ACCOUNT_NAME"        NVARCHAR(255)  NOT NULL,
        "TOKEN"               NVARCHAR(255),
        "PUBLIC_KEY"          NVARCHAR(1024),
        "ALGORITHM"           NVARCHAR(1024),
        "CREDENTIAL_ID"       NVARCHAR(255),
        "ORIGIN"              NVARCHAR(255),
        "DEFERRED"            TINYINT        NOT NULL DEFAULT '0',
        "COMPLETED"           TINYINT        NOT NULL DEFAULT '0',
        "CONFIRMED"           TINYINT        NOT NULL DEFAULT '0',
        "CHALLENGE"           NVARCHAR(255),
        "CREATED"             DATETIME       NOT NULL,
        CONSTRAINT UNIQUE_IAM_FIDO2_IID_AN UNIQUE ("IDENTITY_SERVICE_ID","ACCOUNT_NAME","ORIGIN"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
  
SELECT COUNT(*) FROM IAM_FIDO2_REGISTRATIONS;
COMMIT;  
 
/* Table for IAM_FIDO2_REQUESTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_FIDO2_REQUESTS'))
BEGIN
    CREATE TABLE IAM_FIDO2_REQUESTS(
        "ID"                  BIGINT         IDENTITY(1,1)  NOT NULL,
        "IDENTITY_SERVICE_ID" BIGINT         NOT NULL,
        "CHALLENGE"           NVARCHAR(255)  NOT NULL, 
        "REQUEST_ID"          NVARCHAR(255)  NOT NULL, 
        "CREATED"             DATETIME       NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM IAM_FIDO2_REQUESTS;
COMMIT;   
  
/*
 | Tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for DPL_ORDERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    CREATE TABLE DPL_ORDERS (
        "ID"                        BIGINT          IDENTITY(1,1)  NOT NULL,
        "SUBMISSION_HISTORY_ID"     BIGINT          NOT NULL,
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "WORKFLOW_NAME"             NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "WORKFLOW_PATH"             NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "WORKFLOW_FOLDER"           NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "ORDER_ID"                  NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "ORDER_NAME"                NVARCHAR(30)    DEFAULT '.' NOT NULL,
        "SCHEDULE_NAME"             NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "SCHEDULE_PATH"             NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "SCHEDULE_FOLDER"           NVARCHAR(255)   DEFAULT '.' NOT NULL,
        "CALENDAR_ID"               BIGINT          NOT NULL,
        "START_MODE"                TINYINT         DEFAULT 0   NOT NULL,
        "SUBMITTED"                 TINYINT         DEFAULT 0   NOT NULL,
        "SUBMIT_TIME"               DATETIME        NULL,
        "PERIOD_BEGIN"              DATETIME        NULL,
        "PERIOD_END"                DATETIME        NULL,
        "REPEAT_INTERVAL"           INT             NULL,
        "PLANNED_START"             DATETIME        NOT NULL,
        "EXPECTED_END"              DATETIME        NULL,
        "ORDER_PARAMETERISATION"    NVARCHAR(1000)  NULL,
        "CREATED"                   DATETIME        NOT NULL,
        "MODIFIED"                  DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DPL_O_SHID     ON DPL_ORDERS("SUBMISSION_HISTORY_ID");
    CREATE INDEX IDX_DPL_O_ON       ON DPL_ORDERS("ORDER_NAME");
    CREATE INDEX IDX_DPL_O_OID      ON DPL_ORDERS("ORDER_ID");
    CREATE INDEX IDX_DPL_O_PSCID    ON DPL_ORDERS("PLANNED_START","CONTROLLER_ID");
    CREATE INDEX IDX_DPL_O_WN       ON DPL_ORDERS("WORKFLOW_NAME");    
END;
GO

SELECT COUNT(*) FROM DPL_ORDERS;
COMMIT;

/* Table for DPL_SUBMISSIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_SUBMISSIONS'))
BEGIN
    CREATE TABLE DPL_SUBMISSIONS (
        "ID"                    BIGINT        IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100) NOT NULL,
        "SUBMISSION_FOR_DATE"   DATETIME      NOT NULL,
        "USER_ACCOUNT"          NVARCHAR(255) NOT NULL,
        "CREATED"               DATETIME      NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DPL_S_SFDCID ON DPL_SUBMISSIONS("SUBMISSION_FOR_DATE","CONTROLLER_ID");
END;
GO

SELECT COUNT(*) FROM DPL_SUBMISSIONS;
COMMIT;

/* Table for DPL_HISTORY */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_HISTORY'))
BEGIN
    CREATE TABLE DPL_HISTORY(
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NOT NULL,
        "SUBMITTED"             TINYINT        DEFAULT 0 NOT NULL,
        "MESSAGE"               NVARCHAR(2000) NULL,
        "DAILY_PLAN_DATE"       DATETIME       NOT NULL,
        "ORDER_ID"              NVARCHAR(255)  NULL,
        "WORKFLOW_PATH"         NVARCHAR(255)  NULL,
        "WORKFLOW_FOLDER"       NVARCHAR(255)  NULL,
        "SCHEDULED_FOR"         DATETIME       NULL, 
        "USER_ACCOUNT"          NVARCHAR(255)  NOT NULL,
        "SUBMISSION_TIME"       DATETIME       NOT NULL,
        "CREATED"               DATETIME       NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DPL_H_DPDSCID  ON DPL_HISTORY("DAILY_PLAN_DATE","SUBMITTED","CONTROLLER_ID");
    CREATE INDEX IDX_DPL_H_OID      ON DPL_HISTORY("ORDER_ID");
END;
GO

SELECT COUNT(*) FROM DPL_HISTORY;
COMMIT;

/* Table for DPL_ORDER_VARIABLES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDER_VARIABLES'))
BEGIN
    CREATE TABLE DPL_ORDER_VARIABLES(
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NOT NULL,
        "ORDER_ID"              NVARCHAR(255)  NOT NULL,
        "VARIABLE_VALUE"        NVARCHAR(max)  NOT NULL,
        "CREATED"               DATETIME       NOT NULL,
        "MODIFIED"              DATETIME       NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DPL_OV_OIDCID ON DPL_ORDER_VARIABLES("ORDER_ID","CONTROLLER_ID");
END;
GO
    
SELECT COUNT(*) FROM DPL_ORDER_VARIABLES;
COMMIT;

/* Table for DPL_PROJECTIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_PROJECTIONS'))
BEGIN
    CREATE TABLE DPL_PROJECTIONS(
        "ID"            INT             NOT NULL,
        "CONTENT"       VARBINARY(max)  NOT NULL,
        "CREATED"       DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM DPL_PROJECTIONS;
COMMIT;
/*
 | Tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for DEP_HISTORY */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DEP_HISTORY'))
BEGIN
    CREATE TABLE DEP_HISTORY (
        "ID"              BIGINT               IDENTITY(1,1)  NOT NULL,
        "ACCOUNT"         NVARCHAR(100)        NOT NULL,
        "PATH"            NVARCHAR(255)        NOT NULL,
        "FOLDER"          NVARCHAR(255)        NOT NULL,
        "NAME"            NVARCHAR(255)        DEFAULT '' NOT NULL,
        "TITLE"           NVARCHAR(255)        NULL,
        "TYPE"            TINYINT              NOT NULL,
        "INV_CID"         BIGINT               NOT NULL,
        "INV_IID"         BIGINT               NOT NULL,   /* Inventory Instance ID */
        "CONTROLLER_ID"   NVARCHAR(100)        NOT NULL,
        "CONTENT"         NVARCHAR(max)        NOT NULL,
        "INV_CONTENT"     NVARCHAR(max)        DEFAULT '' NOT NULL,
        "SIGNATURE"       NVARCHAR(2000)       NOT NULL,
        "COMMIT_ID"       NVARCHAR(255)        NULL,
        "VERSION"         NVARCHAR(50)         NULL,
        "OPERATION"       TINYINT              NULL,       /* UPDATE, DELETE */
        "STATE"           TINYINT              NOT NULL,   /* DEPLOYED, NOT_DEPLOYED */
        "ERROR_MESSAGE"   NVARCHAR(255)        NULL,       /* ERROR MESSAGE */
        "DEPLOYMENT_DATE" DATETIME             NOT NULL,
        "DELETED_DATE"    DATETIME             NULL,
        "AUDITLOG_ID"     BIGINT               NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DH_P   ON DEP_HISTORY("PATH");
    CREATE INDEX IDX_DH_N   ON DEP_HISTORY("NAME");
    CREATE INDEX IDX_DH_F   ON DEP_HISTORY("FOLDER");
    CREATE INDEX IDX_DH_INVCID ON DEP_HISTORY("INV_CID");
END;
GO
    
SELECT COUNT(*) FROM DEP_HISTORY;
COMMIT;

/* Table for DEP_KEYS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DEP_KEYS'))
BEGIN
    CREATE TABLE DEP_KEYS (
        "ID"              BIGINT            IDENTITY(1,1)  NOT NULL,
        "KEY_TYPE"        TINYINT           NOT NULL, /* PRIVATE, PUBLIC, X.509 */ 
        "KEY_ALG"         TINYINT           NOT NULL, /* PGP, RSA, ECDSA */
        "KEY"             NVARCHAR(4000)    NULL,
        "CERTIFICATE"     NVARCHAR(4000)    NULL,     /* X.509 Certificate*/
        "ACCOUNT"         NVARCHAR(255)     NOT NULL,
        "SECLVL"          TINYINT           DEFAULT 0 NOT NULL,
        CONSTRAINT DEP_K_UNIQUE UNIQUE ("ACCOUNT", "KEY_TYPE", "SECLVL"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DK_A   ON DEP_KEYS("ACCOUNT");
    CREATE INDEX IDX_DK_SL  ON DEP_KEYS("SECLVL");
END;
GO
    
SELECT COUNT(*) FROM DEP_KEYS;
COMMIT;

/* Table for DEP_SIGNATURES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DEP_SIGNATURES'))
BEGIN
    CREATE TABLE DEP_SIGNATURES (
        "ID"              BIGINT            IDENTITY(1,1)  NOT NULL,
        "INV_CID"         BIGINT            NULL, 
        "DEP_HID"         BIGINT            NULL,
        "SIGNATURE"       NVARCHAR(2000)    NOT NULL,
        "ACCOUNT"         NVARCHAR(255)     NOT NULL,
        "MODIFIED"        DATETIME          NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DS_A   ON DEP_SIGNATURES("ACCOUNT");
END;
GO
    
SELECT COUNT(*) FROM DEP_SIGNATURES;
COMMIT;

/* Table for DEP_VERSIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DEP_VERSIONS'))
BEGIN
    CREATE TABLE DEP_VERSIONS (
        "ID"              BIGINT         IDENTITY(1,1)  NOT NULL,
        "INV_CID"         BIGINT         NULL, 
        "DEP_HID"         BIGINT         NULL,
        "VERSION"         NVARCHAR(100)  NOT NULL,
        "MODIFIED"        DATETIME       NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_DV_V   ON DEP_VERSIONS("VERSION");
END;
GO

SELECT COUNT(*) FROM DEP_VERSIONS;
COMMIT;

/* Table for DEP_COMMIT_IDS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DEP_COMMIT_IDS'))
BEGIN
    CREATE TABLE DEP_COMMIT_IDS (
        "ID"              BIGINT         IDENTITY(1,1)  NOT NULL,
        "INV_CID"         BIGINT         NULL, 
        "DEP_HID"         BIGINT         NULL,
        "CFG_PATH"        NVARCHAR(255)  NOT NULL,
        "COMMIT_ID"       NVARCHAR(255)  NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM DEP_COMMIT_IDS;
COMMIT;

/* Table for DEP_SUBMISSIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DEP_SUBMISSIONS'))
BEGIN
    CREATE TABLE DEP_SUBMISSIONS (
        "ID"              BIGINT             IDENTITY(1,1)  NOT NULL,
        "DEP_HID"         BIGINT             NOT NULL,
        "ACCOUNT"         NVARCHAR(100)      NOT NULL,
        "FOLDER"          NVARCHAR(255)      NOT NULL,
        "PATH"            NVARCHAR(255)      NOT NULL,
        "TYPE"            TINYINT            NOT NULL,
        "INV_CID"         BIGINT             NOT NULL,
        "INV_IID"         BIGINT             NOT NULL,   /* Inventory Instance ID */
        "CONTROLLER_ID"   NVARCHAR(100)      NOT NULL,
        "CONTENT"         NVARCHAR(max)      NOT NULL,
        "SIGNATURE"       NVARCHAR(2000)     NOT NULL,
        "COMMIT_ID"       NVARCHAR(255)      NULL,
        "VERSION"         NVARCHAR(50)       NULL,
        "OPERATION"       TINYINT            NULL,       /* UPDATE, DELETE */
        "CREATED"         DATETIME           NOT NULL,
        "DELETED_DATE"    DATETIME           NULL,
        CONSTRAINT DEP_SUB_UNIQUE UNIQUE ("PATH", "CONTROLLER_ID", "COMMIT_ID", "CREATED"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM DEP_SUBMISSIONS;
COMMIT;
/*
 | Tables for MS SQL Server
 | SOS GmbH, 2024-05-22
*/

SET ANSI_DEFAULTS ON;

/* Table for ENC_CERTIFICATES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.ENC_CERTIFICATES'))
BEGIN
    CREATE TABLE ENC_CERTIFICATES (
        "ALIAS"                 NVARCHAR(255)  NOT NULL,
        "CERT"                  NVARCHAR(4000) NOT NULL,
        "PK_PATH"               NVARCHAR(255)  NULL,
        PRIMARY KEY ("ALIAS")
    );
END;
GO
    
SELECT COUNT(*) FROM ENC_CERTIFICATES;
COMMIT;

/* Table for ENC_AGENT_CERTIFICATES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.ENC_AGENT_CERTIFICATES'))
BEGIN
    CREATE TABLE ENC_AGENT_CERTIFICATES (
        "AGENT_ID"              NVARCHAR(255)  NOT NULL,
        "CERT_ALIAS"            NVARCHAR(255)  NOT NULL,  /* PK of ENC_CERTIFICATES */
        PRIMARY KEY ("AGENT_ID", "CERT_ALIAS")
    );
END;
GO
    
SELECT COUNT(*) FROM ENC_AGENT_CERTIFICATES;
COMMIT;

/*
 | tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for HISTORY_CONTROLLERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_CONTROLLERS'))
BEGIN
    CREATE TABLE HISTORY_CONTROLLERS (
        "READY_EVENT_ID"            NUMERIC(16)     NOT NULL,
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "URI"                       NVARCHAR(255)   NOT NULL,
        "TIMEZONE"                  NVARCHAR(100)   NOT NULL,
        "TOTAL_RUNNING_TIME"        NUMERIC(16)     NOT NULL,   /* in milliseconds */
        "READY_TIME"                DATETIME        NOT NULL,
        "SHUTDOWN_TIME"             DATETIME        NULL,
        "LAST_KNOWN_TIME"           DATETIME        NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("READY_EVENT_ID","CONTROLLER_ID")
    );
END;
GO

SELECT COUNT(*) FROM HISTORY_CONTROLLERS;
COMMIT;

/* Table for HISTORY_AGENTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_AGENTS'))
BEGIN
    CREATE TABLE HISTORY_AGENTS (
        "READY_EVENT_ID"            NUMERIC(16)     NOT NULL,
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "AGENT_ID"                  NVARCHAR(255)   NOT NULL,
        "URI"                       NVARCHAR(255)   NOT NULL,
        "TIMEZONE"                  NVARCHAR(100)   NOT NULL,
        "READY_TIME"                DATETIME        NOT NULL,
        "COUPLING_FAILED_TIME"      DATETIME        NULL,
        "COUPLING_FAILED_MESSAGE"   NVARCHAR(500)   NULL,
        "SHUTDOWN_TIME"             DATETIME        NULL,
        "LAST_KNOWN_TIME"           DATETIME        NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("READY_EVENT_ID","CONTROLLER_ID")
    );
    CREATE INDEX IDX_HA_AID ON HISTORY_AGENTS("AGENT_ID");
END;
GO

SELECT COUNT(*) FROM HISTORY_AGENTS;
COMMIT;

/* Table for HISTORY_ORDERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDERS'))
BEGIN
    CREATE TABLE HISTORY_ORDERS (
        "ID"                        BIGINT          IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "ORDER_ID"                  NVARCHAR(255)   NOT NULL,
        "WORKFLOW_PATH"             NVARCHAR(255)   NOT NULL,
        "WORKFLOW_VERSION_ID"       NVARCHAR(255)   NOT NULL,   /* #2019-06-13T08:43:29Z */
        "WORKFLOW_POSITION"         NVARCHAR(255)   NOT NULL,   /* 1#fork_1#0 */
        "WORKFLOW_FOLDER"           NVARCHAR(255)   NOT NULL,
        "WORKFLOW_NAME"             NVARCHAR(255)   NOT NULL,
        "WORKFLOW_TITLE"            NVARCHAR(255)   NULL,       
        "MAIN_PARENT_ID"            BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID of the main order */
        "PARENT_ID"                 BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID of the parent order */
        "PARENT_ORDER_ID"           NVARCHAR(255)   NOT NULL,   /* HISTORY_ORDERS.ORDER_ID */
        "HAS_CHILDREN"              TINYINT         NOT NULL,
        "RETRY_COUNTER"             INT             NOT NULL,
        "NAME"                      NVARCHAR(255)   NOT NULL,   /* orderId or branchId by fork */
        "START_CAUSE"               NVARCHAR(50)    NOT NULL,   /* order, fork, file_trigger, setback, unskip, unstop */
        "START_TIME_SCHEDULED"      DATETIME        NULL,       
        "START_TIME"                DATETIME        NOT NULL,
        "START_WORKFLOW_POSITION"   NVARCHAR(255)   NOT NULL,
        "START_EVENT_ID"            NUMERIC(16)     NOT NULL,   /* OrderStarted eventId */
        "START_VARIABLES"           NVARCHAR(max)   NULL,       
        "CURRENT_HOS_ID"            BIGINT          NOT NULL,   /* HISTORY_ORDER_STEPS.ID */
        "END_TIME"                  DATETIME        NULL,
        "END_WORKFLOW_POSITION"     NVARCHAR(255)   NULL,
        "END_EVENT_ID"              NUMERIC(16)     NULL,       /* OrderFinisched eventId */
        "END_HOS_ID"                BIGINT          NOT NULL,   /* HISTORY_ORDER_STEPS.ID */
        "END_RETURN_CODE"           INT             NULL,
        "END_MESSAGE"               NVARCHAR(500)   NULL,    
        "SEVERITY"                  TINYINT         NOT NULL,   /* 0,1,2 */
        "STATE"                     TINYINT         NOT NULL,   /* */
        "STATE_TIME"                DATETIME        NOT NULL,
        "STATE_TEXT"                NVARCHAR(255)   NULL,       
        "HAS_STATES"                TINYINT         NOT NULL,   /* has entries in HISTORY_ORDER_STATES */
        "ERROR"                     TINYINT         NOT NULL,
        "ERROR_STATE"               NVARCHAR(20)    NULL,       /*  failed, disrupted ... - event outcome*/
        "ERROR_REASON"              NVARCHAR(50)    NULL,       /*  other ... - event outcome*/
        "ERROR_RETURN_CODE"         INT             NULL,
        "ERROR_CODE"                NVARCHAR(50)    NULL,       
        "ERROR_TEXT"                NVARCHAR(500)   NULL,       
        "LOG_ID"                    BIGINT          NOT NULL,   /* HISTORY_LOGS.ID */
        "CONSTRAINT_HASH"           CHAR(64)        NOT NULL,   /* hash from "CONTROLLER_ID", "ORDER_ID"*/
        "CREATED"                   DATETIME        NOT NULL,
        "MODIFIED"                  DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_HO_CH UNIQUE ("CONSTRAINT_HASH"), /* used by history*/
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_HO_OID                 ON HISTORY_ORDERS("ORDER_ID");
    CREATE INDEX IDX_HO_WPATH               ON HISTORY_ORDERS("WORKFLOW_PATH");
    CREATE INDEX IDX_HO_WNAME               ON HISTORY_ORDERS("WORKFLOW_NAME");
    CREATE INDEX IDX_HO_STIME_PID_SY_CID    ON HISTORY_ORDERS("START_TIME","PARENT_ID","SEVERITY","CONTROLLER_ID");
    CREATE INDEX IDX_HO_LID                 ON HISTORY_ORDERS("LOG_ID");
END;
GO
    
SELECT COUNT(*) FROM HISTORY_ORDERS;
COMMIT;

/* Table for HISTORY_ORDER_STATES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDER_STATES'))
BEGIN
    CREATE TABLE HISTORY_ORDER_STATES (
        "ID"                        BIGINT          IDENTITY(1,1)  NOT NULL,
        "HO_MAIN_PARENT_ID"         BIGINT          NOT NULL,   /* HISTORY_ORDERS.MAIN_PARENT_ID */
        "HO_PARENT_ID"              BIGINT          NOT NULL,   /* HISTORY_ORDERS.PARENT_ID */
        "HO_ID"                     BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID */
        "STATE"                     TINYINT         NOT NULL,   
        "STATE_TIME"                DATETIME        NOT NULL,
        "STATE_EVENT_ID"            CHAR(16)        NOT NULL,   
        "STATE_CODE"                NVARCHAR(50)    NULL,
        "STATE_TEXT"                NVARCHAR(255)   NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_HOSTATES_HOID  ON HISTORY_ORDER_STATES("HO_ID");
END;
GO
    
SELECT COUNT(*) FROM HISTORY_ORDER_STATES;
COMMIT;

/* Table for HISTORY_ORDER_STEPS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDER_STEPS'))
BEGIN
    CREATE TABLE HISTORY_ORDER_STEPS (
        "ID"                        BIGINT          IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "ORDER_ID"                  NVARCHAR(255)   NOT NULL,
        "WORKFLOW_PATH"             NVARCHAR(255)   NOT NULL,
        "WORKFLOW_VERSION_ID"       NVARCHAR(255)   NOT NULL,   /* #2019-06-13T08:43:29Z */
        "WORKFLOW_POSITION"         NVARCHAR(255)   NOT NULL,   /* 1#fork_1#3 */
        "WORKFLOW_FOLDER"           NVARCHAR(255)   NOT NULL,
        "WORKFLOW_NAME"             NVARCHAR(255)   NOT NULL,
        "HO_MAIN_PARENT_ID"         BIGINT          NOT NULL,   /* HISTORY_ORDERS.MAIN_PARENT_ID */
        "HO_ID"                     BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID */
        "POSITION"                  INT             NOT NULL,   /* 3 - last position from WORKFLOW_POSITION */
        "RETRY_COUNTER"             INT             NOT NULL,
        "JOB_NAME"                  NVARCHAR(255)   NOT NULL,
        "JOB_LABEL"                 NVARCHAR(255)   NOT NULL,
        "JOB_TITLE"                 NVARCHAR(255)   NULL,       
        "JOB_NOTIFICATION"          NVARCHAR(1000)  NULL,
        "CRITICALITY"               TINYINT         NOT NULL,
        "AGENT_ID"                  NVARCHAR(255)   NOT NULL,
        "AGENT_NAME"                NVARCHAR(255)   NULL,
        "AGENT_URI"                 NVARCHAR(255)   NOT NULL,
        "SUBAGENT_CLUSTER_ID"       NVARCHAR(255)   NULL,
        "START_CAUSE"               NVARCHAR(50)    NOT NULL,   /* order, file_trigger, setback, unskip, unstop */
        "START_TIME"                DATETIME        NOT NULL,
        "START_EVENT_ID"            NUMERIC(16)     NOT NULL,   /* ProcessingStarted eventId */
        "START_VARIABLES"           NVARCHAR(max)   NULL,       
        "END_TIME"                  DATETIME        NULL,
        "END_EVENT_ID"              NUMERIC(16)     NULL,       /* Processed eventId */
        "END_VARIABLES"             NVARCHAR(max)   NULL,                          
        "RETURN_CODE"               INT             NULL,
        "SEVERITY"                  TINYINT         NOT NULL,   /* 0,1,2 */
        "ERROR"                     TINYINT         NOT NULL,   
        "ERROR_STATE"               NVARCHAR(20)    NULL,       /* failed, disrupted ... - event outcome*/
        "ERROR_REASON"              NVARCHAR(50)    NULL,       /* other ... - event outcome*/
        "ERROR_CODE"                NVARCHAR(50)    NULL,       
        "ERROR_TEXT"                NVARCHAR(500)   NULL,       
        "LOG_ID"                    BIGINT          NOT NULL,   /* HISTORY_LOGS.ID */
        "CONSTRAINT_HASH"           CHAR(64)        NOT NULL,   /* hash from "CONTROLLER_ID", "ORDER_ID", "WORKFLOW_POSITION"*/
        "CREATED"                   DATETIME        NOT NULL,
        "MODIFIED"                  DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_HOSTEPS_CH UNIQUE ("CONSTRAINT_HASH"),    /* used by history*/
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_HOSTEPS_STIME_SY_CID   ON HISTORY_ORDER_STEPS("START_TIME","SEVERITY","CONTROLLER_ID");
    CREATE INDEX IDX_HOSTEPS_HOID           ON HISTORY_ORDER_STEPS("HO_ID");
    CREATE INDEX IDX_HOSTEPS_HOMPID_WPOS    ON HISTORY_ORDER_STEPS("HO_MAIN_PARENT_ID","WORKFLOW_POSITION");
    CREATE INDEX IDX_HOSTEPS_WPATH          ON HISTORY_ORDER_STEPS("WORKFLOW_PATH");
    CREATE INDEX IDX_HOSTEPS_WNAME          ON HISTORY_ORDER_STEPS("WORKFLOW_NAME");
    CREATE INDEX IDX_HOSTEPS_CY_JN          ON HISTORY_ORDER_STEPS("CRITICALITY","JOB_NAME");
END;
GO
    
SELECT COUNT(*) FROM HISTORY_ORDER_STEPS;
COMMIT;

/* Table for HISTORY_LOGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_LOGS'))
BEGIN
    CREATE TABLE HISTORY_LOGS (
        "ID"                        BIGINT          IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "HO_MAIN_PARENT_ID"         BIGINT          NOT NULL,  /* HISTORY_ORDERS.MAIN_PARENT_ID */
        "HO_ID"                     BIGINT          NOT NULL,  /* HISTORY_ORDERS.ID */
        "HOS_ID"                    BIGINT          NOT NULL,  /* HISTORY_ORDER_STEPS.ID */
        "COMPRESSED"                TINYINT         NOT NULL,
        "FILE_BASENAME"             NVARCHAR(255)   NOT NULL,
        "FILE_SIZE_UNCOMPRESSED"    INT             NOT NULL,
        "FILE_LINES_UNCOMPRESSED"   INT             NOT NULL,
        "FILE_CONTENT"              VARBINARY(max)  NOT NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_HLOGS_HOID   ON HISTORY_LOGS("HO_ID");
    CREATE INDEX IDX_HLOGS_HOMPID ON HISTORY_LOGS("HO_MAIN_PARENT_ID");
END;
GO

SELECT COUNT(*) FROM HISTORY_LOGS;
COMMIT;

/* Table for HISTORY_ORDER_TAGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDER_TAGS'))
BEGIN
    CREATE TABLE HISTORY_ORDER_TAGS (
        "ID"                        BIGINT          IDENTITY(1,1)  NOT NULL,
        "HO_ID"                     BIGINT          NOT NULL,  /* HISTORY_ORDERS.ID */
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "ORDER_ID"                  NVARCHAR(255)   NOT NULL,
        "TAG_NAME"                  NVARCHAR(255)   NOT NULL,
        "ORDERING"                  INT             NOT NULL,
        "GROUP_ID"                  BIGINT          DEFAULT 0 NOT NULL,
        "START_TIME"                DATETIME        NOT NULL,
        "DAILY_PLAN_DATE"           DATETIME        NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_HOT_OID     ON HISTORY_ORDER_TAGS("ORDER_ID");
END;
GO

SELECT COUNT(*) FROM HISTORY_ORDER_TAGS;
COMMIT;
SET ANSI_DEFAULTS ON;

/* HISTORY_ORDER_STEPS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_STEPS' AND COLUMN_NAME = 'START_VARIABLES'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=-1 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_STEPS ALTER COLUMN "START_VARIABLES" NVARCHAR(max) NULL');
    COMMIT;
END;
GO
/*
 | Tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for INV_OPERATING_SYSTEMS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_OPERATING_SYSTEMS'))
BEGIN
    CREATE TABLE INV_OPERATING_SYSTEMS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "HOSTNAME"              NVARCHAR(100)  NOT NULL,
        "NAME"                  NVARCHAR(50)   NULL,
        "ARCHITECTURE"          NVARCHAR(255)  NULL,
        "DISTRIBUTION"          NVARCHAR(255)  NULL,
        "MODIFIED"              DATETIME       NOT NULL,
        CONSTRAINT UNIQUE_IOS_HOST UNIQUE ("HOSTNAME"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM INV_OPERATING_SYSTEMS;
COMMIT;

/* Table for INV_JS_INSTANCES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_JS_INSTANCES'))
BEGIN
    CREATE TABLE INV_JS_INSTANCES (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)        NOT NULL,
        "SECURITY_LEVEL"        TINYINT              DEFAULT 0 NOT NULL, /* 0=LOW, 1=MEDIUM, 2=HIGH */
        "URI"                   NVARCHAR(255)        NOT NULL,
        "CLUSTER_URI"           NVARCHAR(255)        NULL,
        "OS_ID"                 BIGINT               NOT NULL,
        "VERSION"               NVARCHAR(30)         NULL,
        "JAVA_VERSION"          NVARCHAR(30)         NULL,
        "STARTED_AT"            DATETIME             NULL,
        "TITLE"                 NVARCHAR(30)         NULL,
        "IS_CLUSTER"            TINYINT              DEFAULT 0 NOT NULL, /* 0=standalone, 1=cluster */
        "IS_PRIMARY"            TINYINT              DEFAULT 1 NOT NULL, /* 1=primary, 0=backup */
        "CERTIFICATE"     		NVARCHAR(4000)    	 NULL,     /* X.509 Certificate*/
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_IJI_CCP UNIQUE ("CONTROLLER_ID", "IS_CLUSTER", "IS_PRIMARY"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_IJI_CID    ON INV_JS_INSTANCES("CONTROLLER_ID");
END;
GO

SELECT COUNT(*) FROM INV_JS_INSTANCES;
COMMIT;

/* Table for INV_AGENT_INSTANCES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_AGENT_INSTANCES'))
BEGIN
    CREATE TABLE INV_AGENT_INSTANCES (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "AGENT_ID"              NVARCHAR(255)        NOT NULL, /* (technical) agentName for the Controller in Job configuration. Cannot overwritten */
        "AGENT_NAME"            NVARCHAR(255)        NOT NULL, /* (displayed) agentName for JOC in Job configuration */
        "URI"                   NVARCHAR(255)        NOT NULL,
        "PROCESS_LIMIT"         INT                  NULL,
        "ORDERING"              INT                  DEFAULT 0 NOT NULL,
        "HIDDEN"                TINYINT              DEFAULT 0 NOT NULL, /* boolean */
        "DISABLED"              TINYINT              DEFAULT 0 NOT NULL, /* boolean */
        "DEPLOYED"              TINYINT              DEFAULT 0 NOT NULL, /* boolean */
        "IS_WATCHER"            TINYINT              DEFAULT 0 NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)        NOT NULL,
        "OS_ID"                 BIGINT               NOT NULL,
        "TITLE"                 NVARCHAR(255)        NULL,
        "VERSION"               NVARCHAR(30)         NULL,
        "JAVA_VERSION"          NVARCHAR(30)         NULL,
        "CERTIFICATE"     		NVARCHAR(4000)    	 NULL,     /* X.509 Certificate*/
        "STARTED_AT"            DATETIME             NULL,
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_IAI_A UNIQUE ("AGENT_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_AGENT_INSTANCES;
COMMIT;

/* Table for INV_AGENT_NAME_ALIASES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_AGENT_NAME_ALIASES'))
BEGIN
    CREATE TABLE INV_AGENT_NAME_ALIASES (
        "AGENT_ID"              NVARCHAR(255)  NOT NULL, /* (technical) agentName for the Controller in Jobs configuration. Cannot overwritten*/
        "AGENT_NAME"            NVARCHAR(255)  NOT NULL, /* (displayed) agentName for JOC in Jobs configuration */
        PRIMARY KEY ("AGENT_ID", "AGENT_NAME")
    );
END;
GO

SELECT COUNT(*) FROM INV_AGENT_NAME_ALIASES;
COMMIT;

/* Table INV_SUBAGENT_INSTANCES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_SUBAGENT_INSTANCES'))
BEGIN
    CREATE TABLE INV_SUBAGENT_INSTANCES (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "SUB_AGENT_ID"          NVARCHAR(255)        NOT NULL,
        "AGENT_ID"              NVARCHAR(255)        NOT NULL,
        "URI"                   NVARCHAR(255)        NOT NULL,
        "IS_DIRECTOR"           TINYINT              DEFAULT 0 NOT NULL, /* 0=No director, 1=primary director, 2=standby director */
        "ORDERING"              INT                  DEFAULT 0 NOT NULL,
        "DISABLED"              TINYINT              DEFAULT 0 NOT NULL,
        "DEPLOYED"              TINYINT              DEFAULT 0 NOT NULL, /* boolean */
        "IS_WATCHER"            TINYINT              DEFAULT 0 NOT NULL,
        "OS_ID"                 BIGINT               NOT NULL,
        "TITLE"                 NVARCHAR(255)        NULL,
        "VERSION"               NVARCHAR(30)         NULL,
        "JAVA_VERSION"          NVARCHAR(30)         NULL,
        "CERTIFICATE"     		NVARCHAR(4000)    	 NULL,     /* X.509 Certificate*/
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_ISI_S UNIQUE ("SUB_AGENT_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_SUBAGENT_INSTANCES;
COMMIT;

/* Table INV_SUBAGENT_CLUSTERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_SUBAGENT_CLUSTERS'))
BEGIN
    CREATE TABLE INV_SUBAGENT_CLUSTERS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NOT NULL,
        "AGENT_ID"              NVARCHAR(255)  NOT NULL,
        "SUBAGENT_CLUSTER_ID"   NVARCHAR(255)  NOT NULL,
        "TITLE"                 NVARCHAR(255)      NULL,
        "DEPLOYED"              TINYINT        DEFAULT 0 NOT NULL, /* boolean */
        "ORDERING"              INT            DEFAULT 0 NOT NULL,
        "MODIFIED"              DATETIME       NOT NULL,    
        CONSTRAINT UNIQUE_ISC_CAC UNIQUE ("CONTROLLER_ID", "SUBAGENT_CLUSTER_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_SUBAGENT_CLUSTERS;
COMMIT;


/* Table INV_SUBAGENT_CLUSTER_MEMBERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_SUBAGENT_CLUSTER_MEMBERS'))
BEGIN
    CREATE TABLE INV_SUBAGENT_CLUSTER_MEMBERS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NOT NULL,
        "SUBAGENT_CLUSTER_ID"   NVARCHAR(255)  NOT NULL,
        "SUBAGENT_ID"           NVARCHAR(255)  NOT NULL,
        "PRIORITY"              NVARCHAR(255)  NOT NULL,
        "MODIFIED"              DATETIME       NOT NULL,    
        CONSTRAINT UNIQUE_ISCM_CCS UNIQUE ("CONTROLLER_ID", "SUBAGENT_CLUSTER_ID", "SUBAGENT_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_SUBAGENT_CLUSTER_MEMBERS;
COMMIT;

/* Table for INV_CONFIGURATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CONFIGURATIONS'))
BEGIN
    CREATE TABLE INV_CONFIGURATIONS (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "TYPE"                  TINYINT              NOT NULL,   /* com.sos.joc.model.inventory.ConfigurationType */
        "PATH"                  NVARCHAR(255)        NOT NULL,
        "NAME"                  NVARCHAR(255)        NOT NULL,
        "FOLDER"                NVARCHAR(255)        NOT NULL,
        "TITLE"                 NVARCHAR(255)        NULL,
        "CONTENT"               NVARCHAR(max)        NULL,
        "JSON_CONTENT"          NVARCHAR(max)        NULL,
        "VALID"                 TINYINT              NOT NULL, /* boolean */
        "DELETED"               TINYINT              NOT NULL, /* boolean */
        "DEPLOYED"              TINYINT              NOT NULL, /* boolean */
        "RELEASED"              TINYINT              NOT NULL, /* boolean */
        "REPO_CTRL"             TINYINT              NOT NULL, /* boolean */
        "AUDIT_LOG_ID"          BIGINT               NOT NULL,
        "CREATED"               DATETIME             NOT NULL,
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_IC_TP UNIQUE ("TYPE", "PATH"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_IC_F   ON INV_CONFIGURATIONS("FOLDER");
    CREATE INDEX IDX_IC_NT  ON INV_CONFIGURATIONS("NAME","TYPE");
END;
GO

SELECT COUNT(*) FROM INV_CONFIGURATIONS;
COMMIT;

/* Table for INV_CONFIGURATION_TRASH */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CONFIGURATION_TRASH'))
BEGIN
    CREATE TABLE INV_CONFIGURATION_TRASH (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "TYPE"                  TINYINT              NOT NULL,   /* com.sos.joc.model.inventory.ConfigurationType */
        "PATH"                  NVARCHAR(255)        NOT NULL,
        "NAME"                  NVARCHAR(255)        NOT NULL,
        "FOLDER"                NVARCHAR(255)        NOT NULL,
        "TITLE"                 NVARCHAR(255)        NULL,
        "CONTENT"               NVARCHAR(max)        NULL,
        "VALID"                 TINYINT              NOT NULL, /* boolean */
        "AUDIT_LOG_ID"          BIGINT               NOT NULL,
        "CREATED"               DATETIME             NOT NULL,
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_ICT_TP UNIQUE ("TYPE", "PATH"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_ICT_F  ON INV_CONFIGURATION_TRASH("FOLDER");
    CREATE INDEX IDX_ICT_NT ON INV_CONFIGURATION_TRASH("NAME","TYPE");
END;
GO

SELECT COUNT(*) FROM INV_CONFIGURATION_TRASH;
COMMIT;

/* Table for INV_RELEASED_CONFIGURATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_RELEASED_CONFIGURATIONS'))
BEGIN
    CREATE TABLE INV_RELEASED_CONFIGURATIONS (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "TYPE"                  TINYINT              NOT NULL,   /* com.sos.joc.model.inventory.ConfigurationType */
        "PATH"                  NVARCHAR(255)        NOT NULL,
        "CID"                   BIGINT               NOT NULL, /* 1:1 foreign key INV_CONFIGURATIONS.ID */
        "NAME"                  NVARCHAR(255)        NOT NULL,
        "FOLDER"                NVARCHAR(255)        NOT NULL,
        "TITLE"                 NVARCHAR(255)        NULL,
        "CONTENT"               NVARCHAR(max)        NOT NULL,
        "JSON_CONTENT"          NVARCHAR(max)        NOT NULL,
        "AUDIT_LOG_ID"          BIGINT               NOT NULL,
        "CREATED"               DATETIME             NOT NULL,
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_IRC_TP UNIQUE ("TYPE", "PATH"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_IRC_C  ON INV_RELEASED_CONFIGURATIONS("CID");
    CREATE INDEX IDX_IRC_F  ON INV_RELEASED_CONFIGURATIONS("FOLDER");
    CREATE INDEX IDX_IRC_NT ON INV_RELEASED_CONFIGURATIONS("NAME","TYPE");
END;
GO

SELECT COUNT(*) FROM INV_RELEASED_CONFIGURATIONS;
COMMIT;

/* Table for INV_CERTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CERTS'))
BEGIN
    CREATE TABLE INV_CERTS (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "KEY_TYPE"              TINYINT              NOT NULL, /* PRIVATE, X509 */ 
        "KEY_ALG"               TINYINT              NOT NULL, /* RSA, ECDSA */
        "PEM"                   NVARCHAR(4000)       NOT NULL,
        "CA"                    TINYINT              NOT NULL, /* boolean */
        "ACCOUNT"               NVARCHAR(255)        NOT NULL,
        "SECLVL"                TINYINT              DEFAULT 0 NOT NULL,
        CONSTRAINT UNIQUE_ICS_KTCAS UNIQUE ("KEY_TYPE", "CA", "ACCOUNT", "SECLVL"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_CERTS;
COMMIT;

/* Table for INV_DOCUMENTATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_DOCUMENTATIONS'))
BEGIN
    CREATE TABLE INV_DOCUMENTATIONS (
        "ID"                    BIGINT               IDENTITY(1,1)  NOT NULL,
        "NAME"                  NVARCHAR(255)        NOT NULL,
        "FOLDER"                NVARCHAR(255)        NOT NULL,
        "PATH"                  NVARCHAR(255)        NOT NULL,
        "TYPE"                  NVARCHAR(25)         DEFAULT ''  NOT NULL,
        "CONTENT"               NVARCHAR(max)        NULL,
        "IMAGE_ID"              BIGINT               NULL,
        "IS_REF"                TINYINT              DEFAULT 0 NOT NULL,
        "DOC_REF"               NVARCHAR(255)        NULL,
        "CREATED"               DATETIME             NOT NULL,
        "MODIFIED"              DATETIME             NOT NULL,
        CONSTRAINT UNIQUE_IDOC_PATH UNIQUE ("PATH"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_ID_IR  ON INV_DOCUMENTATIONS("IS_REF");
END;
GO

SELECT COUNT(*) FROM INV_DOCUMENTATIONS;
COMMIT;

/* Table for INV_DOCUMENTATION_IMAGES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_DOCUMENTATION_IMAGES'))
BEGIN
    CREATE TABLE INV_DOCUMENTATION_IMAGES (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "IMAGE"                 VARBINARY(max)  NOT NULL,
        "MD5_HASH"              CHAR(32)        NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_DOCUMENTATION_IMAGES;
COMMIT;

/* Table INV_FAVORITES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_FAVORITES'))
BEGIN
    CREATE TABLE INV_FAVORITES (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "TYPE"                  TINYINT         NOT NULL,   /* e.g. 1=facet, 2=agent */
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "FAVORITE"              NVARCHAR(max)   NULL,
        "ORDERING"              INT             DEFAULT 0 NOT NULL,
        "ACCOUNT"               NVARCHAR(255)   NOT NULL,
        "SHARED"                TINYINT         DEFAULT 0 NOT NULL,
        "CREATED"               DATETIME        NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_IF_TNA UNIQUE ("TYPE","NAME","ACCOUNT"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_FAVORITES;
COMMIT;

/* Table INV_TAGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_TAGS'))
BEGIN
    CREATE TABLE INV_TAGS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "ORDERING"              INT             DEFAULT 0 NOT NULL,
        "GROUP_ID"              BIGINT          DEFAULT 0 NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_IT_N UNIQUE ("NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_TAGS;
COMMIT;

/* Table INV_TAGGINGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_TAGGINGS'))
BEGIN
    CREATE TABLE INV_TAGGINGS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "CID"              	    BIGINT          NOT NULL,
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "TYPE"                  TINYINT         NOT NULL, /* com.sos.joc.model.inventory.ConfigurationType */
        "TAG_ID"              	BIGINT          NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_ITG_CT UNIQUE ("CID","TAG_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_TAGGINGS;
COMMIT;

/* Table INV_JOB_TAGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_JOB_TAGS'))
BEGIN
    CREATE TABLE INV_JOB_TAGS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "ORDERING"              INT             DEFAULT 0 NOT NULL,
        "GROUP_ID"              BIGINT          DEFAULT 0 NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_IJT_N UNIQUE ("NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_JOB_TAGS;
COMMIT;

/* Table INV_JOB_TAGGINGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_JOB_TAGGINGS'))
BEGIN
    CREATE TABLE INV_JOB_TAGGINGS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "CID"              	    BIGINT          NOT NULL,
        "WORKFLOW_NAME"         NVARCHAR(255)   NOT NULL,
        "JOB_NAME"              NVARCHAR(255)   NOT NULL,
        "TAG_ID"              	BIGINT          NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_IJTG_CJT UNIQUE ("CID","JOB_NAME","TAG_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_JOB_TAGGINGS;
COMMIT;

/* Table INV_ADD_ORDER_TAGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_ADD_ORDER_TAGS'))
BEGIN
    CREATE TABLE INV_ADD_ORDER_TAGS (
        "ORDER_ID_PATTERN"      BIGINT          NOT NULL,
        "ORDER_TAGS"            NVARCHAR(max)   NOT NULL,
        PRIMARY KEY ("ORDER_ID_PATTERN")
    );
END;
GO

SELECT COUNT(*) FROM INV_ADD_ORDER_TAGS;
COMMIT;

/* Table INV_TAG_GROUPS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_TAG_GROUPS'))
BEGIN
    CREATE TABLE INV_TAG_GROUPS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "ORDERING"              INT             DEFAULT 0 NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_ITG_N UNIQUE ("NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

/* Table INV_ORDER_TAGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_ORDER_TAGS'))
BEGIN
    CREATE TABLE INV_ORDER_TAGS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "ORDERING"              INT             DEFAULT 0 NOT NULL,
        "GROUP_ID"              BIGINT          DEFAULT 0 NOT NULL,
        "MODIFIED"              DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_IOT_N UNIQUE ("NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_TAG_GROUPS;
COMMIT;


/* Table INV_DEPENDENCIES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_DEPENDENCIES'))
BEGIN
    CREATE TABLE INV_DEPENDENCIES (
        "INV_ID"                BIGINT          NOT NULL,
        "INV_DEP_ID"            BIGINT          NOT NULL,
        "DEP_TYPE"              TINYINT         NOT NULL, /* com.sos.joc.model.inventory.ConfigurationType */
        "PUBLISHED"             TINYINT         DEFAULT 0 NOT NULL,
        "DEP_DEP_ID"            BIGINT          NULL,
        "CONTROLLER_ID"         NVARCHAR(100)   NULL,
        "INV_ENFORCE"           TINYINT         DEFAULT 0 NOT NULL,
        "DEP_ENFORCE"           TINYINT         DEFAULT 0 NOT NULL,
        PRIMARY KEY  ("INV_ID", "INV_DEP_ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_DEPENDENCIES;
COMMIT;


/* Table INV_CHANGES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CHANGES'))
BEGIN
    CREATE TABLE INV_CHANGES (
        "ID"                    BIGINT        IDENTITY(1,1) NOT NULL,
        "NAME"                  NVARCHAR(100) NOT NULL,
        "TITLE"                 NVARCHAR(255) NULL,
        "STATE"                 TINYINT       NOT NULL,
        "CREATED"               DATETIME      NOT NULL,
        "MODIFIED"              DATETIME      NOT NULL,
        "CLOSED"                DATETIME      NULL,
        "OWNER"                 NVARCHAR(255) NOT NULL,
        "LAST_PUBLISHED_BY"     NVARCHAR(255) NULL,
        CONSTRAINT UNIQUE_ICH_N UNIQUE ("NAME"),
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_INV_CH_ST ON INV_CHANGES("STATE");
END;
GO

SELECT COUNT(*) FROM INV_CHANGES;
COMMIT;

/* Table INV_CHANGES_MAPPINGS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CHANGES_MAPPINGS'))
BEGIN
    CREATE TABLE INV_CHANGES_MAPPINGS (
        "CHANGE_ID"             BIGINT        NOT NULL,
        "INV_ID"                BIGINT        NOT NULL,
        "TYPE"                  TINYINT       NOT NULL,   /* com.sos.joc.model.inventory.ConfigurationType */
        PRIMARY KEY ("CHANGE_ID", "INV_ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_CHANGES_MAPPINGS;
COMMIT;

/* Table INV_NOTES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_NOTES'))
BEGIN
    CREATE TABLE INV_NOTES (
        "ID"                    BIGINT        IDENTITY(1,1) NOT NULL,
        "CID"                   BIGINT        NOT NULL, /* INV_CONFIGURATIONS.ID */
        "CONTENT"               NVARCHAR(max) NOT NULL,
        "SEVERITY"              TINYINT       NOT NULL,
        "CREATED"               DATETIME      NOT NULL,
        "MODIFIED"              DATETIME      NOT NULL,
        CONSTRAINT UNIQUE_IN_C UNIQUE ("CID"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM INV_NOTES;
COMMIT;

/* Table INV_NOTE_NOTIFICATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_NOTE_NOTIFICATIONS'))
BEGIN
    CREATE TABLE INV_NOTE_NOTIFICATIONS (
        "ACCOUNT_NAME"          NVARCHAR(255)  NOT NULL,
        "CID"                   BIGINT         NOT NULL,  /* INV_CONFIGURATIONS.ID */
        PRIMARY KEY ("ACCOUNT_NAME", "CID")
    );
END;
GO

SELECT COUNT(*) FROM INV_NOTE_NOTIFICATIONS;
COMMIT;

/*
 | Tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for JOC_VARIABLES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_VARIABLES'))
BEGIN
    CREATE TABLE JOC_VARIABLES (
        "NAME"                  NVARCHAR(255)   NOT NULL,
        "NUMERIC_VALUE"         INT             NULL,
        "TEXT_VALUE"            NVARCHAR(255)   NULL,
        "BINARY_VALUE"          VARBINARY(max)  NULL,
        PRIMARY KEY ("NAME")
    );
END;
GO

SELECT COUNT(*) FROM JOC_VARIABLES;
COMMIT;

/* Table JOC_INSTANCES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_INSTANCES'))
BEGIN
    CREATE TABLE JOC_INSTANCES (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "CLUSTER_ID"            NVARCHAR(10)   NOT NULL,
        "MEMBER_ID"             NVARCHAR(165)  NOT NULL, /* HOSTNAME:hash(DATA_DIRECTORY) */
        "OS_ID"                 BIGINT         NOT NULL,
        "DATA_DIRECTORY"        NVARCHAR(255)  NOT NULL,
        "SECURITY_LEVEL"        NVARCHAR(10)   NOT NULL,
        "TIMEZONE"              NVARCHAR(30)   NOT NULL,
        "STARTED_AT"            DATETIME       NOT NULL,
        "TITLE"                 NVARCHAR(30)   NULL,
        "ORDERING"              TINYINT        DEFAULT 0 NOT NULL,
        "URI"                   NVARCHAR(255)  NULL,
        "HEART_BEAT"            DATETIME       NOT NULL,
        "API_SERVER"            TINYINT        NOT NULL,
        "VERSION"               NVARCHAR(30)   NULL,
        "CERTIFICATE"           NVARCHAR(4000) NULL,     /* X.509 Certificate*/
        CONSTRAINT UNIQUE_JI_MID UNIQUE ("MEMBER_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM JOC_INSTANCES;
COMMIT;

/* Table JOC_CLUSTER */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_CLUSTER'))
BEGIN
    CREATE TABLE JOC_CLUSTER (
        "ID"                        NVARCHAR(10)   NOT NULL,
        "MEMBER_ID"                 NVARCHAR(165)  NOT NULL,
        "HEART_BEAT"                DATETIME       NOT NULL,
        "SWITCH_MEMBER_ID"          NVARCHAR(165)  NULL,
        "SWITCH_HEART_BEAT"         DATETIME       NULL,
        "NOTIFICATION_MEMBER_ID"    NVARCHAR(165)  NULL,
        "NOTIFICATION"              NVARCHAR(100)  NULL,
        CONSTRAINT UNIQUE_JC_MID UNIQUE ("MEMBER_ID"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM JOC_CLUSTER;
COMMIT;

/* Table JOC_CONFIGURATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_CONFIGURATIONS'))
BEGIN
    CREATE TABLE JOC_CONFIGURATIONS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "INSTANCE_ID"           BIGINT         NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NULL,
        "ACCOUNT"               NVARCHAR(255)  NOT NULL,
        "OBJECT_TYPE"           NVARCHAR(30)   NULL,
        "CONFIGURATION_TYPE"    NVARCHAR(30)   NOT NULL,
        "NAME"                  NVARCHAR(255)  NULL,
        "SHARED"                TINYINT        DEFAULT 0 NOT NULL,
        "CONFIGURATION_ITEM"    NVARCHAR(max)  NOT NULL,
        "MODIFIED"              DATETIME       NOT NULL,
        CONSTRAINT UNIQUE_JC_CIDAOTCTN UNIQUE ("CONTROLLER_ID","ACCOUNT","OBJECT_TYPE","CONFIGURATION_TYPE","NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM JOC_CONFIGURATIONS;
COMMIT;

/* Table JOC_AUDIT_LOG */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_AUDIT_LOG'))
BEGIN
    CREATE TABLE JOC_AUDIT_LOG (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NOT NULL,
        "ACCOUNT"               NVARCHAR(255)  NOT NULL,
        "REQUEST"               NVARCHAR(50)   NOT NULL,
        "PARAMETERS"            NVARCHAR(max)  NULL,
        "CATEGORY"              TINYINT        DEFAULT 0 NOT NULL,
        "COMMENT"               NVARCHAR(2000) NULL,
        "CREATED"               DATETIME       NOT NULL,
        "TICKET_LINK"           NVARCHAR(255)  NULL,
        "TIME_SPENT"            INT            NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_JAL_CCC    ON JOC_AUDIT_LOG("CREATED","CONTROLLER_ID","CATEGORY");
END;
GO

SELECT COUNT(*) FROM JOC_AUDIT_LOG;
COMMIT;

/* Table JOC_AUDIT_LOG_DETAILS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_AUDIT_LOG_DETAILS'))
BEGIN
    CREATE TABLE JOC_AUDIT_LOG_DETAILS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "AUDITLOG_ID"           BIGINT         NOT NULL, /* ID from JOC_AUDIT_LOG */
        "TYPE"                  TINYINT        DEFAULT 0 NOT NULL, 
        "FOLDER"                NVARCHAR(255)  NOT NULL,
        "PATH"                  NVARCHAR(255)  NOT NULL,
        "NAME"                  NVARCHAR(255)  NOT NULL,
        "ORDER_ID"              NVARCHAR(255)  NULL, /*For an order the workflow name fills the NAME field */
        "CREATED"               DATETIME       NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_JALD_JALID     ON JOC_AUDIT_LOG_DETAILS("AUDITLOG_ID");
    CREATE INDEX IDX_JALD_FOLDER    ON JOC_AUDIT_LOG_DETAILS("FOLDER");
    CREATE INDEX IDX_JALD_TYPE      ON JOC_AUDIT_LOG_DETAILS("TYPE");
END;
GO
    
SELECT COUNT(*) FROM JOC_AUDIT_LOG_DETAILS;
COMMIT;

/* Table JOC_LOCKS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_LOCKS'))
BEGIN
    CREATE TABLE JOC_LOCKS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "RANGE"                 TINYINT        NOT NULL,
        "FOLDER"                NVARCHAR(255)  NOT NULL,
        "ACCOUNT"               NVARCHAR(255)  NOT NULL,
        "CREATED"               DATETIME       NOT NULL,
        CONSTRAINT UNIQUE_JL_RF UNIQUE ("RANGE", "FOLDER"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM JOC_LOCKS;
COMMIT;

/* Table JOC_APPROVERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_APPROVERS'))
BEGIN
    CREATE TABLE JOC_APPROVERS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "ACCOUNT_NAME"          NVARCHAR(255)  NOT NULL,
        "FIRST_NAME"            NVARCHAR(30)   NOT NULL,
        "LAST_NAME"             NVARCHAR(30)   NOT NULL,
        "EMAIL"                 NVARCHAR(255)  NULL,
        "ORDERING"              INT            DEFAULT 0 NOT NULL,
        CONSTRAINT UNIQUE_JA_A UNIQUE ("ACCOUNT_NAME"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM JOC_APPROVERS;
COMMIT;

/* Table JOC_APPROVAL_REQUESTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.JOC_APPROVAL_REQUESTS'))
BEGIN
    CREATE TABLE JOC_APPROVAL_REQUESTS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "REQUESTOR"             NVARCHAR(255)  NOT NULL,
        "REQUEST"               NVARCHAR(255)  NOT NULL,
        "PARAMETERS"            NVARCHAR(max)      NULL,
        "REQUESTOR_STATE"       TINYINT        NOT NULL,
        "APPROVER"              NVARCHAR(255)      NULL,
        "APPROVER_STATE"        TINYINT        NOT NULL,
        "CATEGORY"              TINYINT        DEFAULT 0 NOT NULL,
        "TITLE"                 NVARCHAR(255)  NOT NULL,
        "COMMENT"               NVARCHAR(255)      NULL,
        "REQUESTOR_STATE_DATE"  DATETIME       NOT NULL,
        "APPROVER_STATE_DATE"   DATETIME           NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_JAR_R      ON JOC_APPROVAL_REQUESTS("REQUESTOR");
    CREATE INDEX IDX_JAR_A      ON JOC_APPROVAL_REQUESTS("APPROVER");
    CREATE INDEX IDX_JAR_RSD    ON JOC_APPROVAL_REQUESTS("REQUESTOR_STATE_DATE");
END;
GO

SELECT COUNT(*) FROM JOC_APPROVAL_REQUESTS;
COMMIT;
/*
 | Monitoring Interface tables for MS SQL Server
*/
SET ANSI_DEFAULTS ON;

/* Table for MON_ORDERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_ORDERS'))
BEGIN
    CREATE TABLE MON_ORDERS(
        "HISTORY_ID"                BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID */
        "CONTROLLER_ID"             NVARCHAR(100)   NOT NULL,
        "ORDER_ID"                  NVARCHAR(255)   NOT NULL,
        "WORKFLOW_PATH"             NVARCHAR(255)   NOT NULL,
        "WORKFLOW_VERSION_ID"       NVARCHAR(255)   NOT NULL,   /* #2019-06-13T08:43:29Z */
        "WORKFLOW_POSITION"         NVARCHAR(255)   NOT NULL,   /* 1#fork_1#0 */
        "WORKFLOW_FOLDER"           NVARCHAR(255)   NOT NULL,
        "WORKFLOW_NAME"             NVARCHAR(255)   NOT NULL,
        "WORKFLOW_TITLE"            NVARCHAR(255)   NULL,                           
        "MAIN_PARENT_ID"            BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID of the main order */
        "PARENT_ID"                 BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID of the parent order */
        "PARENT_ORDER_ID"           NVARCHAR(255)   NOT NULL,   /* HISTORY_ORDERS.ORDER_ID */
        "HAS_CHILDREN"              TINYINT         NOT NULL,
        "NAME"                      NVARCHAR(255)   NOT NULL,   /* orderId or branchId by fork */
        "START_CAUSE"               NVARCHAR(50)    NOT NULL,   /* order, fork, file_trigger, setback, unskip, unstop */
        "START_TIME_SCHEDULED"      DATETIME        NULL,                               
        "START_TIME"                DATETIME        NOT NULL,
        "START_WORKFLOW_POSITION"   NVARCHAR(255)   NOT NULL,
        "START_VARIABLES"           NVARCHAR(max)   NULL,                          
        "CURRENT_HOS_ID"            BIGINT          NOT NULL,   /* HISTORY_ORDER_STEPS.ID */
        "END_TIME"                  DATETIME        NULL,
        "END_WORKFLOW_POSITION"     NVARCHAR(255)   NULL,
        "END_HOS_ID"                BIGINT          NOT NULL,   /* HISTORY_ORDER_STEPS.ID */
        "END_RETURN_CODE"           INT             NULL,
        "END_MESSAGE"               NVARCHAR(500)   NULL,    
        "SEVERITY"                  TINYINT         NOT NULL,   /* 0,1,2 */
        "STATE"                     TINYINT         NOT NULL,   
        "STATE_TIME"                DATETIME        NOT NULL,
        "ERROR"                     TINYINT         NOT NULL,
        "ERROR_STATE"               NVARCHAR(20)    NULL,       /* failed, disrupted ... - event outcome*/
        "ERROR_REASON"              NVARCHAR(50)    NULL,       /* other ... - event outcome*/
        "ERROR_RETURN_CODE"         INT             NULL,
        "ERROR_CODE"                NVARCHAR(50)    NULL,                            
        "ERROR_TEXT"                NVARCHAR(500)   NULL,                           
        "LOG_ID"                    BIGINT          NULL,       /* HISTORY_LOGS.ID */
        "CREATED"                   DATETIME        NOT NULL,
        "MODIFIED"                  DATETIME        NOT NULL,
        PRIMARY KEY ("HISTORY_ID")
    );
    CREATE INDEX IDX_MONO_CID  ON MON_ORDERS("CONTROLLER_ID");
    CREATE INDEX IDX_MONO_MPID ON MON_ORDERS("MAIN_PARENT_ID");
END;
GO
    
SELECT COUNT(*) FROM MON_ORDERS;
COMMIT;

/* Table for MON_ORDER_STEPS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_ORDER_STEPS'))
BEGIN
    CREATE TABLE MON_ORDER_STEPS(
        "HISTORY_ID"                BIGINT          NOT NULL,   /* HISTORY_ORDER_STEPS.ID */
        "WORKFLOW_POSITION"         NVARCHAR(255)   NOT NULL,   /* 1#fork_1#3 */
        "HO_MAIN_PARENT_ID"         BIGINT          NOT NULL,   /* HISTORY_ORDERS.MAIN_PARENT_ID */
        "HO_ID"                     BIGINT          NOT NULL,   /* HISTORY_ORDERS.ID */
        "POSITION"                  INT             NOT NULL,   /* 3 - last position from WORKFLOW_POSITION */
        "JOB_NAME"                  NVARCHAR(255)   NOT NULL,
        "JOB_LABEL"                 NVARCHAR(255)   NOT NULL,
        "JOB_TITLE"                 NVARCHAR(255)   NULL,                           
        "JOB_NOTIFICATION"          NVARCHAR(1000)  NULL,
        "JOB_CRITICALITY"           TINYINT         NOT NULL,
        "AGENT_ID"                  NVARCHAR(255)   NOT NULL,
        "AGENT_NAME"                NVARCHAR(255)   NULL,
        "AGENT_URI"                 NVARCHAR(255)   NOT NULL,
        "SUBAGENT_CLUSTER_ID"       NVARCHAR(255)   NULL,
        "START_CAUSE"               NVARCHAR(50)    NOT NULL,   /* order, file_trigger, setback, unskip, unstop */
        "START_TIME"                DATETIME        NOT NULL,
        "START_VARIABLES"           NVARCHAR(max)   NULL,                          
        "END_TIME"                  DATETIME        NULL,
        "END_VARIABLES"             NVARCHAR(max)   NULL,                          
        "RETURN_CODE"               INT             NULL,
        "SEVERITY"                  TINYINT         NOT NULL,   /* 0,1,2 */
        "ERROR"                     TINYINT         NOT NULL,   
        "ERROR_STATE"               NVARCHAR(20)    NULL,       /* failed, disrupted ... - event outcome*/
        "ERROR_REASON"              NVARCHAR(50)    NULL,       /* other ... - event outcome*/
        "ERROR_CODE"                NVARCHAR(50)    NULL,                            
        "ERROR_TEXT"                NVARCHAR(500)   NULL,                           
        "LOG_ID"                    BIGINT          NULL,       /* HISTORY_LOGS.ID */
        "CREATED"                   DATETIME        NOT NULL,
        "MODIFIED"                  DATETIME        NOT NULL,
        PRIMARY KEY ("HISTORY_ID")
    );
    CREATE INDEX IDX_MONOS_HMPID ON MON_ORDER_STEPS("HO_MAIN_PARENT_ID");
END;
GO
    
SELECT COUNT(*) FROM MON_ORDER_STEPS;
COMMIT;

/* Table for MON_NOTIFICATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOTIFICATIONS'))
BEGIN
    CREATE TABLE MON_NOTIFICATIONS(
        "ID"                        BIGINT          IDENTITY(1,1) NOT NULL,
        "TYPE"                      TINYINT         NOT NULL,   /* SUCCESS(0), ERROR(1), WARNING(2), RECOVERED(3), ACKNOWLEDGED(4) */
        "RANGE"                     TINYINT         NOT NULL,   /* WORKFLOW(0), WORKFLOW_JOB(1) */
        "NOTIFICATION_ID"           NVARCHAR(255)   NOT NULL,
        "RECOVERED_ID"              BIGINT          NOT NULL,   /* MON_NOTIFICATIONS.ID */
        "WARN"                      TINYINT         NOT NULL,  
        "WARN_TEXT"                 NVARCHAR(500)   NULL,                           
        "HAS_MONITORS"              TINYINT         NOT NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_MONN_C ON MON_NOTIFICATIONS("CREATED");
END;
GO

SELECT COUNT(*) FROM MON_NOTIFICATIONS;
COMMIT;

/* Table for MON_NOT_WORKFLOWS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_WORKFLOWS'))
BEGIN
    CREATE TABLE MON_NOT_WORKFLOWS(
        "NOT_ID"                    BIGINT          NOT NULL,   /* MON_NOTIFICATIONS.ID */
        "MON_O_HISTORY_ID"          BIGINT          NOT NULL,   /* MON_ORDERS.HISTORY_ID */
        "MON_OS_HISTORY_ID"         BIGINT          NOT NULL,   /* MON_ORDER_STEPS.HISTORY_ID */
        "WORKFLOW_POSITION"         NVARCHAR(255)   NOT NULL,   /* 1#fork_1#3 */
        PRIMARY KEY ("NOT_ID")
    );
    CREATE INDEX IDX_MONNW_OHID ON MON_NOT_WORKFLOWS("MON_O_HISTORY_ID");
    CREATE INDEX IDX_MONNW_OSHID ON MON_NOT_WORKFLOWS("MON_OS_HISTORY_ID");
END;
GO
    
SELECT COUNT(*) FROM MON_NOT_WORKFLOWS;
COMMIT;

/* Table for MON_SYSNOTIFICATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_SYSNOTIFICATIONS'))
BEGIN
    CREATE TABLE MON_SYSNOTIFICATIONS(
        "ID"                        BIGINT          IDENTITY(1,1) NOT NULL,
        "TYPE"                      TINYINT         NOT NULL,   /* ERROR(1), WARNING(2), ACKNOWLEDGED(4) */
        "CATEGORY"                  TINYINT         NOT NULL,   /* SYSTEM(0), JOC(1), CONTROLLER(2), AGENT(3) */
        "JOC_ID"                    NVARCHAR(13)    NOT NULL,   /* JOC_INSTANCES.CLUSTER_ID#JOC_INSTANCES.ORDERING */
        "SOURCE"                    NVARCHAR(100)   NOT NULL,
        "NOTIFIER"                  NVARCHAR(255)   NOT NULL,
        "TIME"                      DATETIME        NOT NULL,
        "MESSAGE"                   NVARCHAR(1000)  NULL,
        "EXCEPTION"                 NVARCHAR(4000)  NULL,
        "HAS_MONITORS"              TINYINT         NOT NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_MONSN_TYPE  ON MON_SYSNOTIFICATIONS("TYPE");
    CREATE INDEX IDX_MONSN_JOCID ON MON_SYSNOTIFICATIONS("JOC_ID");
    CREATE INDEX IDX_MONSN_TIME  ON MON_SYSNOTIFICATIONS("TIME");
END;
GO

SELECT COUNT(*) FROM MON_SYSNOTIFICATIONS;
COMMIT;

/* Table for MON_NOT_MONITORS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_MONITORS'))
BEGIN
    CREATE TABLE MON_NOT_MONITORS(
        "ID"                        BIGINT          IDENTITY(1,1) NOT NULL,
        "NOT_ID"                    BIGINT          NOT NULL,   /* MON_NOTIFICATIONS.ID or MON_SYSNOTIFICATIONS.ID  */
        "APPLICATION"               TINYINT         NOT NULL,   /* 0 - MON_NOTIFICATIONS, 1 - MON_SYSNOTIFICATIONS */
        "TYPE"                      TINYINT         NOT NULL,   /* COMMAND(0), MAIL(1), NSCA(2), JMS(3) */
        "NAME"                      NVARCHAR(255)   NOT NULL,
        "CONFIGURATION"             NVARCHAR(500)   NOT NULL,
        "MESSAGE"                   NVARCHAR(4000)  NOT NULL,
        "ERROR"                     TINYINT         NOT NULL,
        "ERROR_TEXT"                NVARCHAR(500)   NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_MONM_NIDA ON MON_NOT_MONITORS("NOT_ID","APPLICATION");
END;
GO
    
SELECT COUNT(*) FROM MON_NOT_MONITORS;
COMMIT;

/* Table for MON_NOT_ACKNOWLEDGEMENTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_ACKNOWLEDGEMENTS'))
BEGIN
    CREATE TABLE MON_NOT_ACKNOWLEDGEMENTS(
        "NOT_ID"                    BIGINT          NOT NULL,   /* MON_NOTIFICATIONS.ID or MON_SYSNOTIFICATIONS.ID */
        "APPLICATION"               TINYINT         NOT NULL,   /* 0 - MON_NOTIFICATIONS, 1 - MON_SYSNOTIFICATIONS */
        "ACCOUNT"                   NVARCHAR(255)   NOT NULL,
        "COMMENT"                   NVARCHAR(2000)  NULL,
        "CREATED"                   DATETIME        NOT NULL,
        PRIMARY KEY ("NOT_ID","APPLICATION")
    );
END;
GO
    
SELECT COUNT(*) FROM MON_NOT_ACKNOWLEDGEMENTS;
COMMIT;
SET ANSI_DEFAULTS ON;

/* MON_ORDER_STEPS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'START_VARIABLES'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=-1 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS ALTER COLUMN "START_VARIABLES" NVARCHAR(max) NULL');
    COMMIT;
END;
GO
/*
 | Tables for MS SQL Server
*/
SET ANSI_DEFAULTS ON;

/* Table for REPORTS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.REPORTS'))
BEGIN
    CREATE TABLE REPORTS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "RUN_ID"                BIGINT         NOT NULL, /* REPORT_RUNS.id */
        "FREQUENCY"             INT            NOT NULL,
        "DATE_FROM"             DATETIME       NOT NULL,
        "DATE_TO"               DATETIME       NOT NULL,
        "CONTENT"               NVARCHAR(max)  NOT NULL,
        "CONSTRAINT_HASH"       CHAR(64)       NOT NULL,
        "MODIFIED"              DATETIME      NOT NULL,
        "CREATED"               DATETIME       NOT NULL,
        CONSTRAINT UNIQUE_R_CH UNIQUE ("CONSTRAINT_HASH"),
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM REPORTS;
COMMIT;

/* Table for REPORT_RUNS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.REPORT_RUNS'))
BEGIN
    CREATE TABLE REPORT_RUNS (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "PATH"                  NVARCHAR(255)  NOT NULL,
        "FOLDER"                NVARCHAR(255)  NOT NULL,
        "NAME"                  NVARCHAR(255)  NOT NULL,
        "TITLE"                 NVARCHAR(255)  NULL,
        "TEMPLATE_ID"           INT            NOT NULL,
        "FREQUENCIES"           NVARCHAR(255)  NOT NULL,
		"SORT"                  INT            NOT NULL,
		"PERIOD_LENGTH"         INT                NULL,
		"PERIOD_STEP"           INT                NULL,
        "HITS"                  INT            NOT NULL,
        "REPORT_COUNT"          INT            NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)  NULL,
        "MONTH_FROM"            DATETIME       NOT NULL,
        "MONTH_TO"              DATETIME       NOT NULL,
        "STATE"                 TINYINT        NOT NULL,
        "ERROR_TEXT"            NVARCHAR(500)  NULL,
        "MODIFIED"              DATETIME       NOT NULL,
        "CREATED"               DATETIME       NOT NULL,
        PRIMARY KEY ("ID")
    );
END;
GO

SELECT COUNT(*) FROM REPORT_RUNS;
COMMIT;

 
/*
 | tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for SEARCH_WORKFLOWS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.SEARCH_WORKFLOWS'))
BEGIN
    CREATE TABLE SEARCH_WORKFLOWS (
        "ID"                    BIGINT           IDENTITY(1,1)  NOT NULL,
        "INV_CID"               BIGINT           NOT NULL, /* INV_CONFIGURATIONS.ID */
        "DEPLOYED"              TINYINT          NOT NULL, /* boolean */
        "CONTENT_HASH"          CHAR(64)         NOT NULL, /* workflow hash */
        "JOBS_COUNT"            INT              NOT NULL,
        "JOBS"                  NVARCHAR(max)    NOT NULL,
        "ARGS"                  NVARCHAR(max)    NOT NULL,
        "JOBS_SCRIPTS"          NVARCHAR(max)    NOT NULL,
        "INSTRUCTIONS"          NVARCHAR(max)    NOT NULL,
        "INSTRUCTIONS_ARGS"     NVARCHAR(max)    NOT NULL,
        "CREATED"               DATETIME         NOT NULL,
        "MODIFIED"              DATETIME         NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_SW_INVCID  ON SEARCH_WORKFLOWS("INV_CID");
    CREATE INDEX IDX_SW_DEP     ON SEARCH_WORKFLOWS("DEPLOYED");
    CREATE INDEX IDX_SW_CH      ON SEARCH_WORKFLOWS("CONTENT_HASH");
    CREATE INDEX IDX_SW_JC      ON SEARCH_WORKFLOWS("JOBS_COUNT");
END;
GO
    
SELECT COUNT(*) FROM SEARCH_WORKFLOWS;
COMMIT;

/* Table for SEARCH_WORKFLOWS_DEP_H */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.SEARCH_WORKFLOWS_DEP_H'))
BEGIN
    CREATE TABLE SEARCH_WORKFLOWS_DEP_H (
        "SEARCH_WID"            BIGINT               NOT NULL, /* SEARCH_WORKFLOWS.ID */
        "INV_CID"               BIGINT               NOT NULL, /* INV_CONFIGURATIONS.ID */
        "DEP_HID"               BIGINT               NOT NULL, /* DEP_HISTORY.ID */
        "CONTROLLER_ID"         NVARCHAR(100)        NOT NULL,
        PRIMARY KEY ("SEARCH_WID","INV_CID","CONTROLLER_ID")
    );
    CREATE INDEX IDX_SWDH_DEPHID    ON SEARCH_WORKFLOWS_DEP_H("DEP_HID");
END;
GO
    
SELECT COUNT(*) FROM SEARCH_WORKFLOWS_DEP_H;
COMMIT;
/*
 | tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* XMLEDITOR_CONFIGURATIONS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.XMLEDITOR_CONFIGURATIONS'))
BEGIN
    CREATE TABLE XMLEDITOR_CONFIGURATIONS (
        "ID"                            BIGINT          IDENTITY(1,1)  NOT NULL,
        "TYPE"                          NVARCHAR(25)    NOT NULL,
        "NAME"                          NVARCHAR(255)   NOT NULL,
        "SCHEMA_LOCATION"               NVARCHAR(255)   NOT NULL,
        "CONFIGURATION_DRAFT"           NVARCHAR(max)   NULL,
        "CONFIGURATION_DRAFT_JSON"      NVARCHAR(max)   NULL,
        "CONFIGURATION_RELEASED"        NVARCHAR(max)   NULL,
        "CONFIGURATION_RELEASED_JSON"   NVARCHAR(max)   NULL,
        "AUDIT_LOG_ID"                  BIGINT          NOT NULL,
        "ACCOUNT"                       NVARCHAR(255)   NOT NULL,
        "RELEASED"                      DATETIME        NULL,
        "MODIFIED"                      DATETIME        NOT NULL,
        "CREATED"                       DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_XEC_TN ON XMLEDITOR_CONFIGURATIONS("TYPE", "NAME");
END;
GO
    
SELECT COUNT(*) FROM XMLEDITOR_CONFIGURATIONS;
COMMIT;
/*
 | tables for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;

/* Table for YADE_TRANSFERS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.YADE_TRANSFERS'))
BEGIN
    CREATE TABLE YADE_TRANSFERS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "CONTROLLER_ID"         NVARCHAR(100)   NOT NULL,
        "WORKFLOW_PATH"         NVARCHAR(255)   NOT NULL,
        "WORKFLOW_NAME"         NVARCHAR(255)   NOT NULL,
        "ORDER_ID"              NVARCHAR(255)   NOT NULL,
        "JOB"                   NVARCHAR(255)   NOT NULL,
        "JOB_POSITION"          NVARCHAR(255)   NOT NULL,
        "HOS_ID"                BIGINT          NOT NULL,
        "SOURCE_PROTOCOL_ID"    BIGINT          NOT NULL,
        "TARGET_PROTOCOL_ID"    BIGINT          NULL,
        "JUMP_PROTOCOL_ID"      BIGINT          NULL,
        "OPERATION"             INT             NOT NULL,
        "PROFILE_NAME"          NVARCHAR(100)   NULL,
        "START"                 DATETIME        NOT NULL,
        "END"                   DATETIME        NULL,
        "NUM_OF_FILES"          INT             NOT NULL,
        "STATE"                 INT             NOT NULL,
        "ERROR_MESSAGE"         NVARCHAR(2000)  NULL,
        "CREATED"               DATETIME        NOT NULL,
        PRIMARY KEY ("ID")
    );
    CREATE INDEX IDX_YT_START   ON YADE_TRANSFERS("START");
END;
GO
    
SELECT COUNT(*) FROM YADE_TRANSFERS;
COMMIT;

/* Table for YADE_PROTOCOLS */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.YADE_PROTOCOLS'))
BEGIN
    CREATE TABLE YADE_PROTOCOLS (
        "ID"                    BIGINT          IDENTITY(1,1)  NOT NULL,
        "HOSTNAME"              NVARCHAR(255)   NOT NULL,
        "PORT"                  INT             NOT NULL,
        "PROTOCOL"              INT             NOT NULL,
        "ACCOUNT"               NVARCHAR(255)   NOT NULL,
        "CREATED"               DATETIME        NOT NULL,
        CONSTRAINT UNIQUE_YP_HPPA UNIQUE ("HOSTNAME", "PORT", "PROTOCOL", "ACCOUNT"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM YADE_PROTOCOLS;
COMMIT;

/* Table for YADE_FILES */
IF NOT EXISTS (SELECT "ID" FROM sysobjects WHERE "ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.YADE_FILES'))
BEGIN
    CREATE TABLE YADE_FILES (
        "ID"                    BIGINT         IDENTITY(1,1)  NOT NULL,
        "TRANSFER_ID"           BIGINT         NOT NULL,
        "SOURCE_PATH"           NVARCHAR(255)  NOT NULL,
        "TARGET_PATH"           NVARCHAR(255)  NULL,
        "SIZE"                  BIGINT         NULL,
        "MODIFICATION_DATE"     DATETIME       NULL,
        "STATE"                 INT            NOT NULL,
        "INTEGRITY_HASH"        NVARCHAR(255)  NULL,
        "ERROR_MESSAGE"         NVARCHAR(2000) NULL,
        "CREATED"               DATETIME       NOT NULL,
        CONSTRAINT INVENTORY_YF_UNIQUE UNIQUE ("TRANSFER_ID", "SOURCE_PATH"),
        PRIMARY KEY ("ID")
    );
END;
GO
    
SELECT COUNT(*) FROM YADE_FILES;
COMMIT;
SET ANSI_DEFAULTS ON;

/* IAM_IDENTITY_SERVICES OIDC */
    UPDATE IAM_IDENTITY_SERVICES SET IDENTITY_SERVICE_TYPE='OIDC-JOC' WHERE IDENTITY_SERVICE_TYPE='OIDC' AND ID IN (SELECT IDENTITY_SERVICE_ID FROM IAM_ACCOUNTS);
    UPDATE JOC_CONFIGURATIONS SET OBJECT_TYPE='OIDC-JOC' WHERE OBJECT_TYPE='OIDC' AND ID IN 
          (SELECT T.ID FROM (SELECT ID FROM JOC_CONFIGURATIONS JC
          WHERE JC.OBJECT_TYPE='OIDC' AND
          JC.NAME IN (SELECT IC.IDENTITY_SERVICE_NAME FROM IAM_IDENTITY_SERVICES IC, IAM_ACCOUNTS IA WHERE IA.IDENTITY_SERVICE_ID=IC.ID AND  IC.IDENTITY_SERVICE_NAME=JC.NAME)) T);
    COMMIT;
GO

  
/* IAM_HISTORY columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_HISTORY' AND COLUMN_NAME = 'IDENTITY_SERVICE_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_HISTORY ADD "IDENTITY_SERVICE_ID"  BIGINT NULL');
    EXEC('UPDATE IAM_HISTORY SET "IDENTITY_SERVICE_ID"=0');
    EXEC('ALTER TABLE IAM_HISTORY ALTER COLUMN "IDENTITY_SERVICE_ID" BIGINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

/* IAM_HISTORY indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_IAMH_ISID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_HISTORY'))
BEGIN
    CREATE INDEX IDX_IAMH_ISID ON IAM_HISTORY("IDENTITY_SERVICE_ID");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_IAMH_LD' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_HISTORY'))
BEGIN
    CREATE INDEX IDX_IAMH_LD ON IAM_HISTORY("LOGIN_DATE");
    COMMIT;
END;
GO

/* IAM_HISTORY_DETAILS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_IAMHD_HID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.IAM_HISTORY_DETAILS'))
BEGIN
    CREATE INDEX IDX_IAMHD_HID ON IAM_HISTORY_DETAILS("IAM_HISTORY_ID");
    COMMIT;
END;
GO

/* IAM_IDENTITY_SERVICES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_IDENTITY_SERVICES' AND COLUMN_NAME = 'SECOND_FACTOR' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_IDENTITY_SERVICES ADD "SECOND_FACTOR"  TINYINT NULL');
    EXEC('UPDATE IAM_IDENTITY_SERVICES SET "SECOND_FACTOR"=0');
    EXEC('ALTER TABLE IAM_IDENTITY_SERVICES ALTER COLUMN "SECOND_FACTOR" TINYINT NOT NULL');
    COMMIT;
END;
GO

/* IAM_IDENTITY_SERVICES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_IDENTITY_SERVICES' AND COLUMN_NAME = 'SECOND_FACTOR_IS_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_IDENTITY_SERVICES ADD "SECOND_FACTOR_IS_ID" BIGINT NULL');
    COMMIT;
END;
GO 

/* IAM_ACCOUNTS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_ACCOUNTS' AND COLUMN_NAME = 'EMAIL' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_ACCOUNTS ADD "EMAIL" NVARCHAR(255) NULL');
    COMMIT;
END;
GO 
 

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_IDENTITY_SERVICES' AND COLUMN_NAME = 'SINGLE_FACTOR_PWD' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN

DECLARE @default sysname, @sql nvarchar(max)
SELECT @default = name 
FROM sys.default_constraints 
WHERE parent_object_id = object_id('IAM_IDENTITY_SERVICES') AND type = 'D'
AND parent_column_id = (
    SELECT column_id 
	FROM sys.columns 
    WHERE object_id = object_id('IAM_IDENTITY_SERVICES')
	AND name = 'SINGLE_FACTOR_PWD'
)
SET @sql = N'alter table IAM_IDENTITY_SERVICES drop constraint ' + @default
EXEC sp_executesql @sql
ALTER TABLE [IAM_IDENTITY_SERVICES] DROP COLUMN SINGLE_FACTOR_PWD 
    COMMIT;
END;
GO


IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_IDENTITY_SERVICES' AND COLUMN_NAME = 'SINGLE_FACTOR_CERT' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN

DECLARE @default sysname, @sql nvarchar(max)
SELECT @default = name 
FROM sys.default_constraints 
WHERE parent_object_id = object_id('IAM_IDENTITY_SERVICES') AND type = 'D'
AND parent_column_id = (
    SELECT column_id 
	FROM sys.columns 
    WHERE object_id = object_id('IAM_IDENTITY_SERVICES')
	AND name = 'SINGLE_FACTOR_CERT'
)
SET @sql = N'alter table IAM_IDENTITY_SERVICES drop constraint ' + @default
EXEC sp_executesql @sql
ALTER TABLE [IAM_IDENTITY_SERVICES] DROP COLUMN SINGLE_FACTOR_CERT 
    COMMIT;
END;
GO




/* IAM_ACCOUNTS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_ACCOUNTS' AND COLUMN_NAME = 'FORCE_PASSWORD_CHANGE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_ACCOUNTS ADD "FORCE_PASSWORD_CHANGE"  TINYINT NULL');
    EXEC('UPDATE IAM_ACCOUNTS SET "FORCE_PASSWORD_CHANGE"=0');
    EXEC('ALTER TABLE IAM_ACCOUNTS ALTER COLUMN "FORCE_PASSWORD_CHANGE" TINYINT NOT NULL');
    COMMIT;
END;
GO


/* IAM_ACCOUNTS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_ACCOUNTS' AND COLUMN_NAME = 'DISABLED' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_ACCOUNTS ADD "DISABLED"  TINYINT NULL');
    EXEC('UPDATE IAM_ACCOUNTS SET "DISABLED"=0');
    EXEC('ALTER TABLE IAM_ACCOUNTS ALTER COLUMN "DISABLED" TINYINT NOT NULL');
    COMMIT;
END;
GO

/* IAM_ROLES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'IAM_ROLES' AND COLUMN_NAME = 'ORDERING' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE IAM_ROLES ADD "ORDERING"  INT NULL');
    COMMIT;
END;
GO 

/* IAM_ACCOUNTS Constraints */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_IAM_A_IN')
BEGIN
    ALTER TABLE IAM_ACCOUNTS ADD CONSTRAINT UNIQUE_IAM_A_IN UNIQUE ("IDENTITY_SERVICE_ID", "ACCOUNT_NAME");
    COMMIT;
END;
GO

/* IAM_ACCOUNTS Constraints */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_IAM_R_IN')
BEGIN
    ALTER TABLE IAM_ROLES ADD CONSTRAINT UNIQUE_IAM_R_IN UNIQUE ("IDENTITY_SERVICE_ID", "ROLE_NAME");
    COMMIT;
END;
GO


/* IAM_ACCOUNTS Constraints */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_IAM_S_N')
BEGIN
    ALTER TABLE IAM_IDENTITY_SERVICES ADD CONSTRAINT UNIQUE_IAM_S_N UNIQUE ("IDENTITY_SERVICE_NAME");
    COMMIT;
END;
GO



 
SET ANSI_DEFAULTS ON;

/* DPL_ORDERS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'DPL_ORDERS' AND COLUMN_NAME = 'START_MODE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE DPL_ORDERS ADD "START_MODE"  TINYINT NULL');
    EXEC('UPDATE DPL_ORDERS SET "START_MODE"=0 where PERIOD_BEGIN is null');
    EXEC('UPDATE DPL_ORDERS SET "START_MODE"=1 where PERIOD_BEGIN is not null');
    EXEC('ALTER TABLE DPL_ORDERS ALTER COLUMN "START_MODE" TINYINT NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'DPL_ORDERS' AND COLUMN_NAME = 'ORDER_PARAMETERISATION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE DPL_ORDERS ADD "ORDER_PARAMETERISATION" NVARCHAR(1000) NULL');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'DPL_ORDERS' AND COLUMN_NAME = 'MESSAGE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    DECLARE @name NVARCHAR(255);
    DECLARE @sql NVARCHAR(500);
    SET @name = (select df."NAME" from sys.default_constraints df
				INNER JOIN sys.columns c ON df."PARENT_OBJECT_ID" = c."OBJECT_ID" AND df."PARENT_COLUMN_ID" = c."COLUMN_ID"
				WHERE df."PARENT_OBJECT_ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS')
				AND c."NAME"='MESSAGE');
    IF @name IS NOT NULL
		BEGIN
			SET @sql = ('ALTER TABLE DPL_ORDERS DROP CONSTRAINT '+ @name); 
			EXEC(@sql)
		END;
        
    EXEC('ALTER TABLE DPL_ORDERS DROP COLUMN "MESSAGE"');
    COMMIT;
END;
GO


/* DPL_ORDERS drop indexes */
IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'UNIQUE_DO_CWOP' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    EXEC('ALTER TABLE DPL_ORDERS DROP CONSTRAINT UNIQUE_DO_CWOP');
    COMMIT;
END;
GO

IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_ORDER_ID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    DROP INDEX IDX_DPL_O_ORDER_ID ON DPL_ORDERS;
    COMMIT;
END;
GO

IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_PSTART' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    DROP INDEX IDX_DPL_O_PSTART ON DPL_ORDERS;
    COMMIT;
END;
GO

IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_START_MODE' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    DROP INDEX IDX_DPL_O_START_MODE ON DPL_ORDERS;
    COMMIT;
END;
GO

/* DPL_ORDERS add indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_SHID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    CREATE INDEX IDX_DPL_O_SHID ON DPL_ORDERS("SUBMISSION_HISTORY_ID");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_ON' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    CREATE INDEX IDX_DPL_O_ON ON DPL_ORDERS("ORDER_NAME");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_OID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    CREATE INDEX IDX_DPL_O_OID ON DPL_ORDERS("ORDER_ID");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_PSCID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    CREATE INDEX IDX_DPL_O_PSCID ON DPL_ORDERS("PLANNED_START","CONTROLLER_ID");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_O_WN' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDERS'))
BEGIN
    CREATE INDEX IDX_DPL_O_WN ON DPL_ORDERS("WORKFLOW_NAME");
    COMMIT;
END;
GO

/* DPL_HISTORY drop indexes */
IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_DPDATE' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_HISTORY'))
BEGIN
    DROP INDEX IDX_DPL_DPDATE ON DPL_HISTORY;
    COMMIT;
END;
GO

IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_CATEGORY' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_HISTORY'))
BEGIN
    DROP INDEX IDX_DPL_CATEGORY ON DPL_HISTORY;
    COMMIT;
END;
GO

IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_OH_ORDER_ID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_HISTORY'))
BEGIN
    DROP INDEX IDX_DPL_OH_ORDER_ID ON DPL_HISTORY;
    COMMIT;
END;
GO

/* DPL_HISTORY add indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_H_DPDSCID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_HISTORY'))
BEGIN
    CREATE INDEX IDX_DPL_H_DPDSCID ON DPL_HISTORY("DAILY_PLAN_DATE","SUBMITTED","CONTROLLER_ID");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_H_OID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_HISTORY'))
BEGIN
    CREATE INDEX IDX_DPL_H_OID ON DPL_HISTORY("ORDER_ID");
    COMMIT;
END;
GO

/* DPL_SUBMISSIONS add indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_S_SFDCID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_SUBMISSIONS'))
BEGIN
    CREATE INDEX IDX_DPL_S_SFDCID ON DPL_SUBMISSIONS("SUBMISSION_FOR_DATE","CONTROLLER_ID");
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* DPL_ORDER_VARIABLES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'DPL_ORDER_VARIABLES' AND COLUMN_NAME = 'ORDER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('DELETE FROM DPL_ORDER_VARIABLES WHERE "PLANNED_ORDER_ID" NOT IN (SELECT "ID" FROM DPL_ORDERS)');
    EXEC('ALTER TABLE DPL_ORDER_VARIABLES ADD "CONTROLLER_ID" NVARCHAR(100) NULL');
    EXEC('ALTER TABLE DPL_ORDER_VARIABLES ADD "ORDER_ID" NVARCHAR(255) NULL');
    EXEC('UPDATE DPL_ORDER_VARIABLES SET DPL_ORDER_VARIABLES."CONTROLLER_ID"=DPL_ORDERS."CONTROLLER_ID", DPL_ORDER_VARIABLES."ORDER_ID"=DPL_ORDERS."ORDER_ID" FROM DPL_ORDER_VARIABLES INNER JOIN DPL_ORDERS ON DPL_ORDER_VARIABLES."PLANNED_ORDER_ID"=DPL_ORDERS."ID"');
    EXEC('ALTER TABLE DPL_ORDER_VARIABLES ALTER COLUMN "CONTROLLER_ID" NVARCHAR(100) NOT NULL');
    EXEC('ALTER TABLE DPL_ORDER_VARIABLES ALTER COLUMN "ORDER_ID" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

/* DPL_ORDER_VARIABLES add indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_OV_OIDCID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDER_VARIABLES'))
BEGIN
    CREATE INDEX IDX_DPL_OV_OIDCID ON DPL_ORDER_VARIABLES("ORDER_ID","CONTROLLER_ID");
    COMMIT;
END;
GO

/* DPL_ORDER_VARIABLES drop indexes */
IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_DPL_OV_POID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.DPL_ORDER_VARIABLES'))
BEGIN
    DROP INDEX IDX_DPL_OV_POID ON DPL_ORDER_VARIABLES;
    COMMIT;
END;
GO

/* DPL_ORDER_VARIABLES drop columns */
IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'DPL_ORDER_VARIABLES' AND COLUMN_NAME = 'PLANNED_ORDER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE DPL_ORDER_VARIABLES DROP COLUMN PLANNED_ORDER_ID');
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* DPL_ORDER_VARIABLES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'DPL_ORDER_VARIABLES' AND COLUMN_NAME = 'VARIABLE_VALUE'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=-1 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE DPL_ORDER_VARIABLES ALTER COLUMN "VARIABLE_VALUE" NVARCHAR(max) NOT NULL');
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* DEP_HISTORY */
/* DROP CONSTRAINT UNIQUE_DH_NTCC */
IF EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_DH_NTCC')
BEGIN
    EXEC('ALTER TABLE DEP_HISTORY DROP CONSTRAINT UNIQUE_DH_NTCC');
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* HISTORY_AGENTS columns */
IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_AGENTS' AND COLUMN_NAME = 'AGENT_ID'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=100 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_AGENTS ALTER COLUMN "AGENT_ID" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_AGENTS' AND COLUMN_NAME = 'URI'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=100 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_AGENTS ALTER COLUMN "URI" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

/* HISTORY_ORDER columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDERS' AND COLUMN_NAME = 'END_RETURN_CODE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDERS ADD "END_RETURN_CODE" INT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDERS' AND COLUMN_NAME = 'END_MESSAGE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDERS ADD "END_MESSAGE" NVARCHAR(500) NULL');
    COMMIT;
END;
GO

/* HISTORY_ORDERS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_HO_LID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDERS'))
BEGIN
    CREATE INDEX IDX_HO_LID ON HISTORY_ORDERS("LOG_ID");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_HO_WNAME' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDERS'))
BEGIN
    CREATE INDEX IDX_HO_WNAME ON HISTORY_ORDERS("WORKFLOW_NAME");
    COMMIT;
END;
GO

/* HISTORY_ORDER_STEPS columns */
IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_STEPS' AND COLUMN_NAME = 'AGENT_ID'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=100 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_STEPS ALTER COLUMN "AGENT_ID" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_STEPS' AND COLUMN_NAME = 'AGENT_URI'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=100 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_STEPS ALTER COLUMN "AGENT_URI" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_STEPS' AND COLUMN_NAME = 'JOB_NOTIFICATION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_STEPS ADD "JOB_NOTIFICATION" NVARCHAR(1000)  NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_STEPS' AND COLUMN_NAME = 'AGENT_NAME' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_STEPS ADD "AGENT_NAME" NVARCHAR(255)  NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_STEPS' AND COLUMN_NAME = 'SUBAGENT_CLUSTER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_STEPS ADD "SUBAGENT_CLUSTER_ID" NVARCHAR(255)  NULL');
    COMMIT;
END;
GO

/* HISTORY_ORDER_STEPS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_HOSTEPS_WNAME' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDER_STEPS'))
BEGIN
    CREATE INDEX IDX_HOSTEPS_WNAME ON HISTORY_ORDER_STEPS("WORKFLOW_NAME");
    COMMIT;
END;
GO

/* HISTORY_LOGS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_HLOGS_HOMPID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_LOGS'))
BEGIN
    CREATE INDEX IDX_HLOGS_HOMPID ON HISTORY_LOGS("HO_MAIN_PARENT_ID");
    COMMIT;
END;
GO

/* DROP tables */
IF EXISTS (SELECT "NAME" FROM sys.tables WHERE "NAME" = 'HISTORY_TEMP_LOGS' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_TEMP_LOGS'))
BEGIN
    EXEC('DROP TABLE HISTORY_TEMP_LOGS');
    COMMIT;
END;
GO

/* add HISTORY_ORDER_TAGS.GROUP_ID */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_TAGS' AND COLUMN_NAME = 'GROUP_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_TAGS ADD "GROUP_ID" BIGINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

/* add HISTORY_ORDER_TAGS.DAILY_PLAN_DATE */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDER_TAGS' AND COLUMN_NAME = 'DAILY_PLAN_DATE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDER_TAGS ADD "DAILY_PLAN_DATE" DATETIME NULL');
    EXEC('UPDATE HISTORY_ORDER_TAGS SET "DAILY_PLAN_DATE" = TRY_CONVERT(DATETIME, SUBSTRING("ORDER_ID", 2, 10))');
    COMMIT;
END;
GO

/* HISTORY_ORDER_TAGS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_HOT_OID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.HISTORY_ORDER_TAGS'))
BEGIN
    CREATE INDEX IDX_HOT_OID ON HISTORY_ORDER_TAGS("ORDER_ID");
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* HISTORY_ORDER columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'HISTORY_ORDERS' AND COLUMN_NAME = 'START_VARIABLES'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=-1 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE HISTORY_ORDERS ALTER COLUMN "START_VARIABLES" NVARCHAR(max) NULL');
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* INV_AGENT_INSTANCES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_AGENT_INSTANCES' AND COLUMN_NAME = 'JAVA_VERSION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_AGENT_INSTANCES ADD "JAVA_VERSION" NVARCHAR(30) NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_AGENT_INSTANCES' AND COLUMN_NAME = 'DEPLOYED' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_AGENT_INSTANCES ADD "DEPLOYED" TINYINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_AGENT_INSTANCES' AND COLUMN_NAME = 'TITLE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_AGENT_INSTANCES ADD "TITLE" NVARCHAR(255) NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_AGENT_INSTANCES' AND COLUMN_NAME = 'HIDDEN' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_AGENT_INSTANCES ADD "HIDDEN" TINYINT DEFAULT 0 NOT NULL');
    EXEC('UPDATE INV_AGENT_INSTANCES SET "HIDDEN" = "DISABLED"');
    EXEC('UPDATE INV_AGENT_INSTANCES SET "DISABLED" = 0');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_AGENT_INSTANCES' AND COLUMN_NAME = 'ORDERING' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_AGENT_INSTANCES ADD "ORDERING" INT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_AGENT_INSTANCES' AND COLUMN_NAME = 'PROCESS_LIMIT' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_AGENT_INSTANCES ADD "PROCESS_LIMIT" INT NULL');
    COMMIT;
END;
GO

/* INV_JS_INSTANCES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_JS_INSTANCES' AND COLUMN_NAME = 'JAVA_VERSION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_JS_INSTANCES ADD "JAVA_VERSION" NVARCHAR(30) NULL');
    COMMIT;
END;
GO

/* INV_SUBAGENT_INSTANCES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_INSTANCES' AND COLUMN_NAME = 'DISABLED' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_INSTANCES ADD "DISABLED" TINYINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_INSTANCES' AND COLUMN_NAME = 'DEPLOYED' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_INSTANCES ADD "DEPLOYED" TINYINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_INSTANCES' AND COLUMN_NAME = 'TITLE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_INSTANCES ADD "TITLE" NVARCHAR(255) NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_CLUSTERS' AND COLUMN_NAME = 'ORDERING' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTERS ADD "ORDERING" INT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_ISC_AC')
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTERS DROP CONSTRAINT UNIQUE_ISC_AC');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_CLUSTERS' AND COLUMN_NAME = 'CONTROLLER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTERS ADD "CONTROLLER_ID" NVARCHAR(100) DEFAULT '''' NOT NULL');
    EXEC('UPDATE INV_SUBAGENT_CLUSTERS SET INV_SUBAGENT_CLUSTERS."CONTROLLER_ID"=INV_AGENT_INSTANCES."CONTROLLER_ID" FROM INV_SUBAGENT_CLUSTERS INNER JOIN INV_AGENT_INSTANCES ON INV_SUBAGENT_CLUSTERS."AGENT_ID"=INV_AGENT_INSTANCES."AGENT_ID"');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_ISC_CAC')
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTERS ADD CONSTRAINT UNIQUE_ISC_CAC UNIQUE ("CONTROLLER_ID", "SUBAGENT_CLUSTER_ID")');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_ISCM_CS')
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTER_MEMBERS DROP CONSTRAINT UNIQUE_ISCM_CS');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_CLUSTER_MEMBERS' AND COLUMN_NAME = 'CONTROLLER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTER_MEMBERS ADD "CONTROLLER_ID" NVARCHAR(100) DEFAULT '''' NOT NULL');
    EXEC('UPDATE INV_SUBAGENT_CLUSTER_MEMBERS SET INV_SUBAGENT_CLUSTER_MEMBERS."CONTROLLER_ID"=INV_SUBAGENT_CLUSTERS."CONTROLLER_ID" FROM INV_SUBAGENT_CLUSTER_MEMBERS INNER JOIN INV_SUBAGENT_CLUSTERS ON INV_SUBAGENT_CLUSTER_MEMBERS."SUBAGENT_CLUSTER_ID"=INV_SUBAGENT_CLUSTERS."SUBAGENT_CLUSTER_ID"');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_ISCM_CCS')
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTER_MEMBERS ADD CONSTRAINT UNIQUE_ISCM_CCS UNIQUE ("CONTROLLER_ID", "SUBAGENT_CLUSTER_ID", "SUBAGENT_ID")');
    COMMIT;
END;
GO

/* INV_CONFIGURATIONS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_CONFIGURATIONS' AND COLUMN_NAME = 'REPO_CTRL' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_CONFIGURATIONS ADD "REPO_CTRL" TINYINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

/* INV_CONFIGURATIONS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_IC_NT' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CONFIGURATIONS'))
BEGIN
    CREATE INDEX IDX_IC_NT ON INV_CONFIGURATIONS("NAME","TYPE");
    COMMIT;
END;
GO

/* INV_CONFIGURATION_TRASH indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_ICT_NT' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_CONFIGURATION_TRASH'))
BEGIN
    CREATE INDEX IDX_ICT_NT ON INV_CONFIGURATION_TRASH("NAME","TYPE");
    COMMIT;
END;
GO

/* INV_RELEASED_CONFIGURATIONS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_IRC_F' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_RELEASED_CONFIGURATIONS'))
BEGIN
    CREATE INDEX IDX_IRC_F ON INV_RELEASED_CONFIGURATIONS("FOLDER");
    COMMIT;
END;
GO

IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_IRC_NT' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.INV_RELEASED_CONFIGURATIONS'))
BEGIN
    CREATE INDEX IDX_IRC_NT ON INV_RELEASED_CONFIGURATIONS("NAME","TYPE");
    COMMIT;
END;
GO

/* INV_DEPENDENCIES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_DEPENDENCIES' AND COLUMN_NAME = 'INV_ENFORCE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_DEPENDENCIES ADD "INV_ENFORCE" TINYINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_DEPENDENCIES' AND COLUMN_NAME = 'DEP_ENFORCE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_DEPENDENCIES ADD "DEP_ENFORCE" TINYINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

/* INV_CERTS */
/* DROP UNIQUE CONSTRAINT UNIQUE_ICS_KTC */
IF EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_ICS_KTC')
BEGIN
    EXEC('ALTER TABLE INV_CERTS DROP CONSTRAINT UNIQUE_ICS_KTC');
    COMMIT;
END;
GO

/* ADD new UNIQUE CONSTRAINT UNIQUE_ICS_KTCAS */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where CONSTRAINT_NAME = 'UNIQUE_ICS_KTCAS')
BEGIN
    EXEC('ALTER TABLE INV_CERTS ADD CONSTRAINT UNIQUE_ICS_KTCAS UNIQUE ("KEY_TYPE", "CA", "ACCOUNT", "SECLVL")');
    COMMIT;
END;
GO

/* modify INV_SUBAGENT_CLUSTER_MEMBERS.PRIORITY */
IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_SUBAGENT_CLUSTER_MEMBERS' AND COLUMN_NAME = 'PRIORITY' AND upper(DATA_TYPE)='INT' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_SUBAGENT_CLUSTER_MEMBERS ALTER COLUMN "PRIORITY" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

/* modify INV_TAGS.GROUP_ID */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_TAGS' AND COLUMN_NAME = 'GROUP_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_TAGS ADD "GROUP_ID" BIGINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

/* modify INV_JOB_TAGS.GROUP_ID */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'INV_JOB_TAGS' AND COLUMN_NAME = 'GROUP_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE INV_JOB_TAGS ADD "GROUP_ID" BIGINT DEFAULT 0 NOT NULL');
    COMMIT;
END;
GO

/* INV_DEPENDENCIES JOC-2161 */
IF EXISTS (select * from INV_DEPENDENCIES WHERE INV_DEP_ID IS NULL OR INV_ID IS NULL)
BEGIN
    EXEC('TRUNCATE TABLE INV_DEPENDENCIES');
    COMMIT;
END;
GO

SET ANSI_DEFAULTS ON;

/* JOC_INSTANCES columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'JOC_INSTANCES' AND COLUMN_NAME = 'CLUSTER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE JOC_INSTANCES ADD "CLUSTER_ID" NVARCHAR(10) NULL');
    EXEC('UPDATE JOC_INSTANCES SET "CLUSTER_ID"=''${jocClusterId}''');
    EXEC('ALTER TABLE JOC_INSTANCES ALTER COLUMN "CLUSTER_ID" NVARCHAR(10) NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'JOC_INSTANCES' AND COLUMN_NAME = 'API_SERVER' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE JOC_INSTANCES ADD "API_SERVER" TINYINT NULL');
    EXEC('UPDATE JOC_INSTANCES SET "API_SERVER"=0');
    EXEC('ALTER TABLE JOC_INSTANCES ALTER COLUMN "API_SERVER" TINYINT NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'JOC_INSTANCES' AND COLUMN_NAME = 'VERSION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE JOC_INSTANCES ADD "VERSION" NVARCHAR(30) NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'JOC_INSTANCES' AND COLUMN_NAME = 'CERTIFICATE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE JOC_INSTANCES ADD "CERTIFICATE" NVARCHAR(4000) NULL');
    COMMIT;
END;
GO

/* JOC_APPROVAL_REQUESTS drop columns */
IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'JOC_APPROVAL_REQUESTS' AND COLUMN_NAME = 'ACTION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS DROP COLUMN "NUM_OF_OBJECTS"');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS DROP COLUMN "OBJECT_TYPE"');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS DROP COLUMN "OBJECT_NAME"');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS DROP COLUMN "ACTION"');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'JOC_APPROVAL_REQUESTS' AND COLUMN_NAME = 'CREATED' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS DROP COLUMN "CREATED"');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS ADD "REQUESTOR_STATE_DATE" DATETIME NULL');
    EXEC('UPDATE JOC_APPROVAL_REQUESTS SET "REQUESTOR_STATE_DATE"="MODIFIED"');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS ALTER COLUMN "REQUESTOR_STATE_DATE" DATETIME NOT NULL');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS DROP COLUMN "MODIFIED"');
    EXEC('ALTER TABLE JOC_APPROVAL_REQUESTS ADD "APPROVER_STATE_DATE" DATETIME NULL');
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* MON_NOTIFICATIONS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_NOTIFICATIONS' AND COLUMN_NAME = 'WARN' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_NOTIFICATIONS ADD "WARN" TINYINT NULL');
    EXEC('UPDATE MON_NOTIFICATIONS SET "WARN"=0');
    EXEC('ALTER TABLE MON_NOTIFICATIONS ALTER COLUMN "WARN" TINYINT NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_NOTIFICATIONS' AND COLUMN_NAME = 'WARN_TEXT' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_NOTIFICATIONS ADD "WARN_TEXT" NVARCHAR(500) NULL');
    COMMIT;
END;
GO

/* MON_ORDERS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDERS' AND COLUMN_NAME = 'END_RETURN_CODE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDERS ADD "END_RETURN_CODE" INT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDERS' AND COLUMN_NAME = 'END_MESSAGE' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDERS ADD "END_MESSAGE" NVARCHAR(500) NULL');
    COMMIT;
END;
GO

/* MON_ORDERS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_MONO_MPID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_ORDERS'))
BEGIN
    CREATE INDEX IDX_MONO_MPID ON MON_ORDERS("MAIN_PARENT_ID");
    COMMIT;
END;
GO

/* MON_ORDER_STEPS drop index */
IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_MONOS_W' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_ORDER_STEPS'))
BEGIN
    EXEC('DROP INDEX IDX_MONOS_W ON MON_ORDER_STEPS');
    COMMIT;
END;
GO

IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_MOS_W' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_ORDER_STEPS'))
BEGIN
    EXEC('DROP INDEX IDX_MOS_W ON MON_ORDER_STEPS');
    COMMIT;
END;
GO

/* MON_ORDER_STEPS columns */
IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'AGENT_ID'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=100 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS ALTER COLUMN "AGENT_ID" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'AGENT_URI'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=100 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS ALTER COLUMN "AGENT_URI" NVARCHAR(255) NOT NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'JOB_NOTIFICATION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS ADD "JOB_NOTIFICATION" NVARCHAR(1000)  NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'AGENT_NAME' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS ADD "AGENT_NAME" NVARCHAR(255)  NULL');
    COMMIT;
END;
GO

IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'SUBAGENT_CLUSTER_ID' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS ADD "SUBAGENT_CLUSTER_ID" NVARCHAR(255)  NULL');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'WARN' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS DROP COLUMN "WARN"');
    COMMIT;
END;
GO

IF EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDER_STEPS' AND COLUMN_NAME = 'WARN_TEXT' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDER_STEPS DROP COLUMN "WARN_TEXT"');
    COMMIT;
END;
GO

/* MON_ORDER_STEPS indexes */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_MONOS_HMPID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_ORDER_STEPS'))
BEGIN
    CREATE INDEX IDX_MONOS_HMPID ON MON_ORDER_STEPS("HO_MAIN_PARENT_ID");
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* starting with JS7 release 2.5.2 (JOC-1447) - MON_SYSNOTIFICATIONS related changes */

/* MON_NOT_MONITORS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_NOT_MONITORS' AND COLUMN_NAME = 'APPLICATION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_NOT_MONITORS ADD "APPLICATION" TINYINT NULL');
    EXEC('UPDATE MON_NOT_MONITORS SET "APPLICATION"=0');
    EXEC('ALTER TABLE MON_NOT_MONITORS ALTER COLUMN "APPLICATION" TINYINT NOT NULL');
    COMMIT;
END;
GO

/* MON_NOT_MONITORS drop index */
IF EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_MONM_NID' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_MONITORS'))
BEGIN
    EXEC('DROP INDEX IDX_MONM_NID ON MON_NOT_MONITORS');
    COMMIT;
END;
GO

/* MON_NOT_MONITORS create index */
IF NOT EXISTS (SELECT "NAME" FROM sys.indexes WHERE "NAME" = 'IDX_MONM_NIDA' AND OBJECT_ID = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_MONITORS'))
BEGIN
    CREATE INDEX IDX_MONM_NIDA ON MON_NOT_MONITORS("NOT_ID","APPLICATION");
    COMMIT;
END;
GO

/* MON_NOT_ACKNOWLEDGEMENTS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_NOT_ACKNOWLEDGEMENTS' AND COLUMN_NAME = 'APPLICATION' AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_NOT_ACKNOWLEDGEMENTS ADD "APPLICATION" TINYINT NULL');
    EXEC('UPDATE MON_NOT_ACKNOWLEDGEMENTS SET "APPLICATION"=0');
    EXEC('ALTER TABLE MON_NOT_ACKNOWLEDGEMENTS ALTER COLUMN "APPLICATION" TINYINT NOT NULL');
    COMMIT;
END;
GO

/* MON_NOT_ACKNOWLEDGEMENTS primary key */
BEGIN
    DECLARE @count_columns INTEGER;
    SET @count_columns = (SELECT COUNT(*) FROM sys.columns c
                        INNER JOIN sys.indexes i ON i."OBJECT_ID" = c."OBJECT_ID"
                        INNER JOIN sys.index_columns ic ON ic."OBJECT_ID" = c."OBJECT_ID" AND ic."COLUMN_ID" = c."COLUMN_ID" AND ic."INDEX_ID" = i."INDEX_ID"
                        WHERE i.IS_PRIMARY_KEY = 1 
                     	and c."OBJECT_ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_ACKNOWLEDGEMENTS')
                        )
    IF(@count_columns = 0) 
        BEGIN
           EXEC('ALTER TABLE MON_NOT_ACKNOWLEDGEMENTS ADD PRIMARY KEY("NOT_ID","APPLICATION")');
           COMMIT;
        END;
    ELSE
	    BEGIN
			IF (@count_columns <> 2)
				BEGIN
					DECLARE @name NVARCHAR(255);
					DECLARE @sql NVARCHAR(500);
					SET @name = (SELECT sc."NAME" FROM sys.key_constraints sc  WHERE sc."TYPE" = 'PK' AND sc."PARENT_OBJECT_ID" = OBJECT_ID(N''+DB_NAME()+'.'+SCHEMA_NAME()+'.MON_NOT_ACKNOWLEDGEMENTS'));
					SET @sql = ('ALTER TABLE MON_NOT_ACKNOWLEDGEMENTS DROP CONSTRAINT '+ @name); 
					EXEC(@sql);
					EXEC('ALTER TABLE MON_NOT_ACKNOWLEDGEMENTS ADD PRIMARY KEY("NOT_ID","APPLICATION")');
					COMMIT;
				END;
		END;
END;
GO
SET ANSI_DEFAULTS ON;

/* MON_ORDERS columns */
IF NOT EXISTS (select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MON_ORDERS' AND COLUMN_NAME = 'START_VARIABLES'  AND upper(DATA_TYPE)='NVARCHAR' AND CHARACTER_MAXIMUM_LENGTH=-1 AND TABLE_CATALOG=DB_NAME() AND TABLE_SCHEMA=SCHEMA_NAME())
BEGIN
    EXEC('ALTER TABLE MON_ORDERS ALTER COLUMN "START_VARIABLES" NVARCHAR(max) NULL');
    COMMIT;
END;
GO
SET ANSI_DEFAULTS ON;

/* XMLEDITOR_CONFIGURATIONS Columns */
/* Truncate stored JSON CONFIGURATION_DRAFT_JSON, CONFIGURATION_RELEASED_JSON to avoid version conflicts */
UPDATE XMLEDITOR_CONFIGURATIONS SET "CONFIGURATION_DRAFT_JSON"=NULL,"CONFIGURATION_RELEASED_JSON"=NULL;
COMMIT;
/*
 | Insert Script for default Keys for SecurityLevel LOW and MEDIUM
 | SOS GmbH, 2021-05-31
*/

/* import default */
SET ANSI_DEFAULTS ON;

BEGIN 
  DECLARE @row_exists1 INT, @row_exists2 INT, @row_exists3 INT, @row_exists4 INT, @row_exists5 INT;
  DECLARE @services_id BIGINT, @accounts_id BIGINT, @roles_id BIGINT;
  
  SELECT @row_exists1 = COUNT("ID") FROM IAM_IDENTITY_SERVICES;
  SELECT @row_exists2 = COUNT("ID") FROM IAM_ACCOUNT2ROLES;
  SELECT @row_exists3 = COUNT("ID") FROM IAM_ACCOUNTS;
  SELECT @row_exists4 = COUNT("ID") FROM IAM_PERMISSIONS;
  SELECT @row_exists5 = COUNT("ID") FROM IAM_ROLES;

  IF (@row_exists1 = 0 AND @row_exists2 = 0 AND @row_exists3 = 0 AND @row_exists4 = 0 AND @row_exists5 = 0)
    BEGIN
        INSERT INTO IAM_IDENTITY_SERVICES("IDENTITY_SERVICE_TYPE", "IDENTITY_SERVICE_NAME","REQUIRED","DISABLED", "AUTHENTICATION_SCHEME", "SECOND_FACTOR", "ORDERING") VALUES ('JOC','joc',0,0,'SINGLE',0,0);
        SELECT @services_id = @@IDENTITY;
    
        INSERT INTO IAM_ACCOUNTS("IDENTITY_SERVICE_ID", "ACCOUNT_NAME","ACCOUNT_PASSWORD","FORCE_PASSWORD_CHANGE") VALUES (@services_id,'root','$JS7-1.0$65536$9aRojy9RBlLyf40BVcE+pg==$QLXLz0CHFaYDNeIE3ioZIOAGoBy5xo2rTmp7i38DEEF5cK22MzpAL89jA2USWv5KfTth8yprRkvIk+iWS+q3Aw==',1);
        SELECT @accounts_id = @@IDENTITY;
    
        INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'all');
        SELECT @roles_id = @@IDENTITY;
    
        INSERT INTO IAM_ACCOUNT2ROLES("ROLE_ID", "ACCOUNT_ID") VALUES (@roles_id,@accounts_id);
        INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products',0,0);
/*
 Administrator
*/		
INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'administrator');
SELECT @roles_id = @@IDENTITY;
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:auditlog:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:calendars:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:cluster:manage',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:dailyplan:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:documentations:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:inventory:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:notification',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:others',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:restart',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:terminate',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:switch_over',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:agents:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:deployment:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:locks:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:workflows:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:orders:view',0,0);

/*
 application_manager
*/
INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'application_manager');
SELECT @roles_id = @@IDENTITY;
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:controller:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:customization',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:settings',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:auditlog:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:calendars:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:dailyplan',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:documentations',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:filetransfer',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:inventory',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:notification:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:agents:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:deployment',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:locks:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:workflows:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:orders',0,0);
 
/*
 it_operator
*/
 
INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'it_operator');
SELECT @roles_id = @@IDENTITY;
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:customization',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:settings:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:auditlog:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:calendars:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:dailyplan',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:documentations',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:filetransfer',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:inventory:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:notification:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:agents:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:deployment:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:locks:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:workflows:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:orders',0,0);


/*
 incident_manager
*/
 
INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'incident_manager');
SELECT @roles_id = @@IDENTITY;
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:accounts',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:customization',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:settings',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:auditlog:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:calendars:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:dailyplan',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:documentations',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:filetransfer',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:inventory',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:notification',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:others',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller',0,0);



/*
 business_user
*/

INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'business_user');
SELECT @roles_id = @@IDENTITY;
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:administration:customization:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:auditlog:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:calendars:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:dailyplan:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:documentations:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:filetransfer:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:agents:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:locks:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:workflows:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:orders:view',0,0);



/*
 api_user
*/

INSERT INTO IAM_ROLES("IDENTITY_SERVICE_ID", "ROLE_NAME") VALUES (@services_id,'api_user');
SELECT @roles_id = @@IDENTITY;
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:auditlog:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:calendars:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:dailyplan:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:documentations:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:joc:filetransfer:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:agents:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:deployment:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:locks:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:workflows:view',0,0);
INSERT INTO IAM_PERMISSIONS("IDENTITY_SERVICE_ID","ROLE_ID","ACCOUNT_PERMISSION", "EXCLUDED","RECURSIVE") VALUES (@services_id,@roles_id,'sos:products:controller:orders:view',0,0);
 
		
		
    END;
    
END;
GO

COMMIT;
SET ANSI_DEFAULTS ON;

/* set Security Level */
UPDATE INV_JS_INSTANCES SET "SECURITY_LEVEL" = 0 WHERE "SECURITY_LEVEL" <> 0;
COMMIT;
SET ANSI_DEFAULTS ON;

/* delete/insert version */
DELETE FROM JOC_VARIABLES WHERE "NAME"='version';
INSERT INTO JOC_VARIABLES ("NAME", "NUMERIC_VALUE", "TEXT_VALUE", "BINARY_VALUE") VALUES ('version',NULL,'2.8.3',NULL);
COMMIT;
/*
 | Insert Script for default Keys for SecurityLevel LOW and MEDIUM
 | SOS GmbH, 2021-05-31
*/

/* import default */
SET ANSI_DEFAULTS ON;

/*
 | ATTENTION:
 | The "SECLVL" field contains the security level (0=LOW, 1=MEDUIM, 2=HIGH).
 | This value MUST match the security level selected in the setup.
 | If the following two INSERT statements are to be executed before the setup, then the value of "SECLVL" may have to be adjusted.
 | 
 | SELECT @row_exists = COUNT(*) FROM DEP_KEY ... AND "SECLVL"=[number of security level]
 | INSERT INTO DEP_KEYS( ... , [number of security level])
 | INSERT INTO INV_CERTS( ... , [number of security level])
*/
DECLARE @current_cert  NVARCHAR(4000) = '-----BEGIN CERTIFICATE-----' + CHAR(10) + 'MIIEDjCCAfagAwIBAgIJAMxQSEdXteqVMA0GCSqGSIb3DQEBCwUAMIGNMQswCQYD' + CHAR(10) + 'VQQGEwJERTEPMA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xDDAKBgNV' + CHAR(10) + 'BAoMA1NPUzELMAkGA1UECwwCSVQxHDAaBgNVBAMME1NPUyBJbnRlcm1lZGlhdGUg' + CHAR(10) + 'Q0ExIzAhBgkqhkiG9w0BCQEWFGFkbWluQHNvcy1iZXJsaW4uY29tMB4XDTI1MDQy' + CHAR(10) + 'ODExMTUwM1oXDTMwMDYxNTExMTUwM1owbDELMAkGA1UEBhMCREUxDzANBgNVBAgM' + CHAR(10) + 'BkJlcmxpbjEPMA0GA1UEBwwGQmVybGluMQwwCgYDVQQKDANTT1MxCzAJBgNVBAsM' + CHAR(10) + 'AklUMQ8wDQYDVQQDDAZzb3MtZWMxDzANBgNVBC4TBlNPUyBDQTBZMBMGByqGSM49' + CHAR(10) + 'AgEGCCqGSM49AwEHA0IABFTf+XE54Wl99SuR4dDd7IDHyl2NyZLRy7xcV059qz4L' + CHAR(10) + 'aCgHn9DYwb0gORie7jOPM5cl9ya2qkjw5Hlyai50HcOjXDBaMBEGCWCGSAGG+EIB' + CHAR(10) + 'AQQEAwIEEDAOBgNVHQ8BAf8EBAMCBeAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwMw' + CHAR(10) + 'HQYDVR0OBBYEFBORoUzmc2PORMqo/hYc58JFDVqHMA0GCSqGSIb3DQEBCwUAA4IC' + CHAR(10) + 'AQDBI2kcWoz3MjRi15dhHQBxFbLz5F+ObYuivT0Rp21K1HJGnGakDYqMLiBNZLbX' + CHAR(10) + '35pSd3bEA85amNwsrknoxo1qDUk5rl+d+uaflBj0aIrOHPAO8gJPT1s7foaP6gAM' + CHAR(10) + 'UitsAMKbba1oGg91LoahOZ9x3uRT33g2IIwsuE81XGIz05A6l3mXor531vNsxXQE' + CHAR(10) + 'ummLoUqDykutSqe8XihjKuAeUhyBli8YVBwDSzGEeratoeorXgZ4P9NdTPdbYJ50' + CHAR(10) + 'oRCvHGKzI941pNcfR/3PClE9oGHvYJHifCNINcKdeJjc59+JawesujNdzwkO9iGZ' + CHAR(10) + 'NvQbCNtKZijDQO3Hw9CrBjfT/miuHu25mcS4dQ47xL5fV2x8zNXqSxKmN/zcSkI6' + CHAR(10) + 'YUtQ+hBV5YJUFKcXkOJh3rnA3NzeOQS0TsNLu9qUcu/5nhlM32zgYziSnzODa4gS' + CHAR(10) + 'CV3SnYE1JlnQFhMt4950Z10NEzVJ/upLThpy0EhAhjabv7CsQX2wasrzmhKFTsjo' + CHAR(10) + 'yGQ0syaesYL3fZx6bzC77X0KACGdY/qRYcByToehHtiW23yW9E1KF5SqrvgQbUgz' + CHAR(10) + '21lSHVo0EfHMoSdh7JGzG+/XPDAkT5TpW1g45uLDP7JAL0Tt6OpqdfyicVMAa49D' + CHAR(10) + 'gJlvDou4ZSth/gcuZ26Ph6JX8z09Umcj19Juj0roA7ukmg==' + CHAR(10) + '-----END CERTIFICATE-----';
DECLARE @outdated_cert NVARCHAR(4000) = '-----BEGIN CERTIFICATE-----' + CHAR(10) + 'MIID1zCCAb+gAwIBAgIJAMxQSEdXteoRMA0GCSqGSIb3DQEBCwUAMIGNMQswCQYD' + CHAR(10) + 'VQQGEwJERTEPMA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xDDAKBgNV' + CHAR(10) + 'BAoMA1NPUzELMAkGA1UECwwCSVQxHDAaBgNVBAMME1NPUyBJbnRlcm1lZGlhdGUg' + CHAR(10) + 'Q0ExIzAhBgkqhkiG9w0BCQEWFGFkbWluQHNvcy1iZXJsaW4uY29tMB4XDTIwMTAx' + CHAR(10) + 'MzEyNTA1NVoXDTI1MTAxMjEyNTA1NVowbDELMAkGA1UEBhMCREUxDzANBgNVBAgM' + CHAR(10) + 'BkJlcmxpbjEPMA0GA1UEBwwGQmVybGluMQwwCgYDVQQKDANTT1MxCzAJBgNVBAsM' + CHAR(10) + 'AklUMQ8wDQYDVQQDDAZzb3MtZWMxDzANBgNVBC4TBlNPUyBDQTBZMBMGByqGSM49' + CHAR(10) + 'AgEGCCqGSM49AwEHA0IABFTf+XE54Wl99SuR4dDd7IDHyl2NyZLRy7xcV059qz4L' + CHAR(10) + 'aCgHn9DYwb0gORie7jOPM5cl9ya2qkjw5Hlyai50HcOjJTAjMBEGCWCGSAGG+EIB' + CHAR(10) + 'AQQEAwIHgDAOBgNVHQ8BAf8EBAMCBeAwDQYJKoZIhvcNAQELBQADggIBAGC7BKCd' + CHAR(10) + 'kuhIzEGflG4tslnWlC7BXvbI2lKkUbDYlcBf04hYl4ootWfprFfF80LXBFgWUxGN' + CHAR(10) + '6HZIQDwWJch/h+UFjf/97zVxzbl0q1miZtNN2USbYK3yfrgWyOKEzZcAxUnr2pL4' + CHAR(10) + '9/t2LBmFKvgmh1RiB40Vf8s5frEQID2Am+I+pZsi4R7/OtwUo6dZJKP6IFlqZYzf' + CHAR(10) + 'klWlLMgwVK6Iqo+Lu8M2oxWRHxMCTOAQyQmVWf8ZsfzEn3k412v5tejWjQsoo057' + CHAR(10) + 'VCQ3p36UOl2+Qrif2PvYOz3pvdek6xwuJaqpr1fDSjEO/WSpl4Fdx0pavCFLniaN' + CHAR(10) + 'odP00FpH1OfwHf3XvYMCcHO+/JRlsc4uNaalEkD6n3pNbWlpJyaneEUr7GqC8TEX' + CHAR(10) + 'zHJ3r5SSKFxwEX/iAL5CyIgq8BUFLQtXFBiYVTMQXyUTNixo0h130bV4KMdpfLLm' + CHAR(10) + 'u+iekRBGM59sP5Ijfg4lvQqoMZ2Ck+BGBye/tlItgDOIh+FIIVMwfHY4KOlfaqRr' + CHAR(10) + 'JRzEpVkssoIVHNghl1kT3U9ZSbMtJ3W650uBtidhS0tYOXPixd5DJ8VI5cl16pwb' + CHAR(10) + 'DpkAS01bxgDhQrvQINzrLTXeDuY01Lr3HC8TD/NMS+p7X5CQ1KxUhgzxaPQ8LTau' + CHAR(10) + '9DzuuCRcbkIBI+KQl5KF8kZ2ohdw/tNOH+RK' + CHAR(10) + '-----END CERTIFICATE-----%';

BEGIN 
  DECLARE @row_exists int
  SELECT @row_exists = COUNT(*) FROM DEP_KEYS WHERE "ACCOUNT"='root' AND "SECLVL"=0
  IF @row_exists = 0
    BEGIN
	    IF 0 < 2
	      INSERT INTO DEP_KEYS("KEY_TYPE","KEY_ALG","KEY","CERTIFICATE","ACCOUNT","SECLVL") VALUES (0,2,'-----BEGIN EC PRIVATE KEY-----' + CHAR(10) + 'MHcCAQEEID+VjMgUjVph6n1lxu5Vx9qrhoCyMrr9vcmwKBx+MSG2oAoGCCqGSM49' + CHAR(10) + 'AwEHoUQDQgAEVN/5cTnhaX31K5Hh0N3sgMfKXY3JktHLvFxXTn2rPgtoKAef0NjB' + CHAR(10) + 'vSA5GJ7uM48zlyX3JraqSPDkeXJqLnQdww==' + CHAR(10) + '-----END EC PRIVATE KEY-----', @current_cert, 'root', 0)
      ELSE
        INSERT INTO DEP_KEYS("KEY_TYPE","KEY_ALG","KEY","CERTIFICATE","ACCOUNT","SECLVL") VALUES (1,2,null, @current_cert, 'root', 0)
    END; 
  ELSE
    BEGIN
	    UPDATE DEP_KEYS SET CERTIFICATE = @current_cert WHERE CERTIFICATE like @outdated_cert;
    END 
END;
GO
COMMIT;

BEGIN 
  DECLARE @row_exists int
  SELECT @row_exists = COUNT(*) FROM INV_CERTS WHERE "ACCOUNT"='root' AND "CA"=1
  IF @row_exists = 0
    INSERT INTO INV_CERTS("KEY_TYPE","KEY_ALG","PEM", "CA","ACCOUNT","SECLVL") VALUES (1,1,'-----BEGIN CERTIFICATE-----' + CHAR(10) + 'MIIGpTCCBI2gAwIBAgIRANBLkv2+/RYfqQXsW1mziIYwDQYJKoZIhvcNAQELBQAw' + CHAR(10) + 'gYUxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIDAZCZXJsaW4xDzANBgNVBAcMBkJlcmxp' + CHAR(10) + 'bjEMMAoGA1UECgwDU09TMQswCQYDVQQLDAJJVDEUMBIGA1UEAwwLU09TIFJvb3Qg' + CHAR(10) + 'Q0ExIzAhBgkqhkiG9w0BCQEWFGFkbWluQHNvcy1iZXJsaW4uY29tMB4XDTIwMDYx' + CHAR(10) + 'NzIzNDkxNFoXDTMwMDYxNTIzNDkxNFowgY0xCzAJBgNVBAYTAkRFMQ8wDQYDVQQI' + CHAR(10) + 'DAZCZXJsaW4xDzANBgNVBAcMBkJlcmxpbjEMMAoGA1UECgwDU09TMQswCQYDVQQL' + CHAR(10) + 'DAJJVDEcMBoGA1UEAwwTU09TIEludGVybWVkaWF0ZSBDQTEjMCEGCSqGSIb3DQEJ' + CHAR(10) + 'ARYUYWRtaW5Ac29zLWJlcmxpbi5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw' + CHAR(10) + 'ggIKAoICAQDGmo7XDw2Bd/Y9BmLLgNhVXh6oxuAwFpY9Bho3EbtBQp4OpeaC1irb' + CHAR(10) + 'm2ID8JlGtWOvCmCv//b00Zxx7KESa1PuF1J5XCxjPzoeRvlVR/BbZtdK8IZUZdL3' + CHAR(10) + 'gqWSVX9UX6Go/ghknM5LXPG7y8XhrIUA27F0ts3nYYtD/djrscTTlH6luh7lZiKK' + CHAR(10) + 'x5TX52YB5it7pxkHSO7DNaBgSlbDXvK/NEthwWAIHvqunwiBchWgUbH/qrne5MBW' + CHAR(10) + 'VvX2G8JCDyU8JK6Fab0InU9PB/yYWz1hDUqDhMhNvRrMLSQ0KwWkMWyEbXJoEHNA' + CHAR(10) + 'xBF+7Mp2pBy8gL11i46JaKvCEv5bSPCwQ+BdGDw6Oa4bt7H/aEsKHzNekl8U6pvc' + CHAR(10) + 'gpuoXQ6xY2xqLx9JLTYWKDvsMftuevPV2gqqcqqEBvISc9A2FvPN0uFmioDa9WK0' + CHAR(10) + 's7JI9HsbpqpinC4CZUpNohfkLBrzSEbf6aJx9SgE3pFDdQwd2wxVD5QngMMysFd7' + CHAR(10) + 'XCQnnPx5GUrMQ/us9qSiGYjuHqiH2x9gp5hurQ8qdwwO3aCwhwjYQA+czatrbWk+' + CHAR(10) + 'Fe3WSzDnZrriHIfwD0P12YDdpCx5Eh93NJDAptqn1oIRfK9z6TZjgIIbXLQg4PkA' + CHAR(10) + 'KTf+LGmAQItkIQKFiVAdH7daALF01erxl/n5M6FRd2ZpVZWQd+RyKQIDAQABo4IB' + CHAR(10) + 'BDCCAQAwHQYDVR0OBBYEFIlZIba80QjXo5Pm+A9P2wF46MPkMIG6BgNVHSMEgbIw' + CHAR(10) + 'ga+AFGt2X2MH0PCOWlWoPjVyimGYmK/PoYGLpIGIMIGFMQswCQYDVQQGEwJERTEP' + CHAR(10) + 'MA0GA1UECAwGQmVybGluMQ8wDQYDVQQHDAZCZXJsaW4xDDAKBgNVBAoMA1NPUzEL' + CHAR(10) + 'MAkGA1UECwwCSVQxFDASBgNVBAMMC1NPUyBSb290IENBMSMwIQYJKoZIhvcNAQkB' + CHAR(10) + 'FhRhZG1pbkBzb3MtYmVybGluLmNvbYIJAM3gM6k6sCzUMBIGA1UdEwEB/wQIMAYB' + CHAR(10) + 'Af8CAQAwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBd/NR493wc' + CHAR(10) + '2FvLHLKJwOoI7WucD7sP7L0G6NqmJ2dR3cbNRe7X4bXxugCSUD470RiWKTUVpD6O' + CHAR(10) + '/fcDawS6GgqkQI8Mn9KGSRbliqjfXaTcArt2wdNi84pbC+eLakJFqjS5SZxYzAZK' + CHAR(10) + 'Zdf0UmhrPkr+C1ndShkIkVLbMsZfQD5Uu78uHDDziVwdPVYVI4Ge2nLpi9i4zx06' + CHAR(10) + 'GtOHbKFmv67KdZX7sXXEzJJHc206aZ7wjRSSvh1mJsplm/yGY/jsnKAKqe1VT3hB' + CHAR(10) + 'JCxTnyFN5CYEnwCTF3qdZGJchv8MG5VA9QZeLpHh+ERM/BKZlXrU70JqCpmTaDov' + CHAR(10) + 'tZt1dXOS8EKOm2PbaNoXZm39ol+Ky2Co8ES8UWIb9PQV69ZP2zKXBtM0UWW17m9m' + CHAR(10) + 'BqjF4EfTGlViTdalorcl2UYH/1l1rR4CtJECpPr2njZD8msSs3Jh+BDKTrmJFMxn' + CHAR(10) + 'YQyWkyHxWfdR7/WxMNLh4WYx6Dw+FYqN/Hw+UMkByCRpVeIzal25AzLAvfHhzVXq' + CHAR(10) + 'bCOCXxSkn3d8N6V0P30BqkbieEwQx1T2SgLIfqo3G9QJ8BRCOaK+LhVJ2NaSe9FP' + CHAR(10) + 'yyRb8+sd/SHRiO6CvTxqy5iCozdgjb0SRufS01iBDMQT2r31nRn8qezRL0YMes1W' + CHAR(10) + 'HwphnWeOC52Ovuw2OLv1TomJKSzujvLzpA==' + CHAR(10) + '-----END CERTIFICATE-----', 1, 'root', 0)
END;
GO
COMMIT;
/*
 | Dependencies views for MS SQL Server
 | SOS GmbH, 2025-10-23
*/

SET ANSI_DEFAULTS ON;
GO

/* View for dependencies of current inventory objects */
CREATE OR ALTER VIEW INV_DEPENDENCIES_VIEW AS
    SELECT
      inva."ID" AS "INV_ID", inva."NAME" AS "INV_NAME", inva."FOLDER" AS "INV_FOLDER", inva."TYPE" AS "INV_TYPE", inva."VALID" AS "INV_VALID",
      inva."DEPLOYED" AS "INV_DEPLOYED", inva."RELEASED" AS "INV_RELEASED", deps."INV_ENFORCE" as "INV_ENFORCE", 
      invb."ID" AS "DEP_ID", invb."NAME" AS "DEP_NAME", invb."FOLDER" AS "DEP_FOLDER", invb."TYPE" AS "DEP_TYPE", invb."VALID" AS "DEP_VALID",
      invb."DEPLOYED" AS "DEP_DEPLOYED", invb."RELEASED" AS "DEP_RELEASED", deps."DEP_ENFORCE" as "DEP_ENFORCE" 
    FROM INV_DEPENDENCIES AS deps
      LEFT JOIN INV_CONFIGURATIONS AS inva ON deps."INV_ID" = inva."ID"
      LEFT JOIN INV_CONFIGURATIONS AS invb ON deps."INV_DEP_ID" = invb."ID"
    WHERE inva."ID" IS NOT NULL AND invb."ID" IS NOT NULL;
GO

COMMIT;
/*
 | Deployment views for MS SQL Server
 | SOS GmbH, 2021-05-31
*/

SET ANSI_DEFAULTS ON;
GO

/* View for current inventory at the controllers */
CREATE OR ALTER VIEW DEP_CONFIGURATIONS_JOIN AS
    SELECT "CONTROLLER_ID","NAME","TYPE",MAX("DEPLOYMENT_DATE") AS "MAX_DATE"
    FROM DEP_HISTORY
    WHERE "STATE" = 0 
    GROUP BY "CONTROLLER_ID", "NAME", "TYPE";
GO

CREATE OR ALTER VIEW DEP_CONFIGURATIONS AS
    SELECT a."ID",a."NAME",a."TITLE",a."PATH",a."FOLDER",a."TYPE",a."INV_CID",a."CONTROLLER_ID",a."INV_CONTENT" AS "CONTENT",a."COMMIT_ID",a."DEPLOYMENT_DATE" AS "CREATED"
    FROM DEP_HISTORY a INNER JOIN DEP_CONFIGURATIONS_JOIN b
    ON a."DEPLOYMENT_DATE" = b."MAX_DATE"
        AND a."CONTROLLER_ID" = b."CONTROLLER_ID"
        AND a."NAME" = b."NAME"
        AND a."TYPE" = b."TYPE" 
    WHERE a."OPERATION" = 0;
GO

CREATE OR ALTER VIEW DEP_NAMEPATHS AS
    SELECT a."ID",a."NAME",a."PATH", a."TYPE",a."CONTROLLER_ID"
    FROM DEP_HISTORY a INNER JOIN DEP_CONFIGURATIONS_JOIN b
    ON a."DEPLOYMENT_DATE" = b."MAX_DATE"
        AND a."CONTROLLER_ID" = b."CONTROLLER_ID"
        AND a."NAME" = b."NAME"
        AND a."TYPE" = b."TYPE";
GO

COMMIT;
/*
 | Inventory views for MS SQL Server
*/

SET ANSI_DEFAULTS ON;
GO

CREATE OR ALTER VIEW INV_SCHEDULE2CALENDARS AS
    SELECT 
        "CALENDAR_NAME",
        i."NAME"            AS "SCHEDULE_NAME",
        i."PATH"            AS "SCHEDULE_PATH",
        i."FOLDER"          AS "SCHEDULE_FOLDER",
        i."RELEASED"        AS "SCHEDULE_RELEASED"
    FROM INV_CONFIGURATIONS i
    OUTER APPLY OPENJSON (i."JSON_CONTENT",'$.calendars')
    WITH ("CALENDAR_NAME" NVARCHAR(255) '$.calendarName')
    WHERE i."TYPE"=7
        AND JSON_QUERY(i."JSON_CONTENT",'$.calendars') IS NOT NULL;
GO

CREATE OR ALTER VIEW INV_REL_SCHEDULE2CALENDARS AS
    SELECT 
        "CALENDAR_NAME",
        i."NAME"            AS "SCHEDULE_NAME",
        i."PATH"            AS "SCHEDULE_PATH",
        i."FOLDER"          AS "SCHEDULE_FOLDER"
    FROM INV_RELEASED_CONFIGURATIONS i
    OUTER APPLY OPENJSON (i."JSON_CONTENT",'$.calendars')
    WITH ("CALENDAR_NAME" NVARCHAR(255) '$.calendarName')
    WHERE i."TYPE"=7
        AND JSON_QUERY(i."JSON_CONTENT",'$.calendars') IS NOT NULL;
GO

COMMIT;
/*
 | Inventory views for MS SQL Server
*/

SET ANSI_DEFAULTS ON;
GO

CREATE OR ALTER VIEW INV_SCHEDULE2WORKFLOWS AS
    SELECT 
        CAST(JSON_VALUE("JSON_CONTENT",'$.workflowName') AS NVARCHAR(255)) AS "WORKFLOW_NAME",
        "NAME"          AS "SCHEDULE_NAME",
        "PATH"          AS "SCHEDULE_PATH",
        "FOLDER"        AS "SCHEDULE_FOLDER",
        "RELEASED"      AS "SCHEDULE_RELEASED",
        "JSON_CONTENT"  AS "SCHEDULE_CONTENT"
    FROM INV_CONFIGURATIONS
        WHERE "TYPE"=7
            AND JSON_QUERY("JSON_CONTENT",'$.workflowNames') IS NULL
    UNION ALL
    SELECT 
        "WORKFLOW_NAME",
        i."NAME"            AS "SCHEDULE_NAME",
        i."PATH"            AS "SCHEDULE_PATH",
        i."FOLDER"          AS "SCHEDULE_FOLDER",
        i."RELEASED"        AS "SCHEDULE_RELEASED",
        i."JSON_CONTENT"    AS "SCHEDULE_CONTENT"
    FROM INV_CONFIGURATIONS i
    OUTER APPLY OPENJSON (i."JSON_CONTENT",'$.workflowNames')
    WITH ("WORKFLOW_NAME" NVARCHAR(255) '$')
    WHERE i."TYPE"=7
        AND JSON_QUERY(i."JSON_CONTENT",'$.workflowNames') IS NOT NULL;
GO

DROP VIEW IF EXISTS INV_RELEASED_SCHEDULE2WORKFLOWS;
GO

CREATE OR ALTER VIEW INV_REL_SCHEDULE2WORKFLOWS AS
    SELECT 
        CAST(JSON_VALUE("JSON_CONTENT",'$.workflowName') AS NVARCHAR(255)) AS "WORKFLOW_NAME",
        "NAME"          AS "SCHEDULE_NAME",
        "PATH"          AS "SCHEDULE_PATH",
        "FOLDER"        AS "SCHEDULE_FOLDER",
        "JSON_CONTENT"  AS "SCHEDULE_CONTENT"
    FROM INV_RELEASED_CONFIGURATIONS
        WHERE "TYPE"=7
            AND JSON_QUERY("JSON_CONTENT",'$.workflowNames') IS NULL
    UNION ALL
    SELECT 
        "WORKFLOW_NAME",
        i."NAME"            AS "SCHEDULE_NAME",
        i."PATH"            AS "SCHEDULE_PATH",
        i."FOLDER"          AS "SCHEDULE_FOLDER",
        i."JSON_CONTENT"    AS "SCHEDULE_CONTENT"
    FROM INV_RELEASED_CONFIGURATIONS i
    OUTER APPLY OPENJSON (i."JSON_CONTENT",'$.workflowNames')
    WITH ("WORKFLOW_NAME" NVARCHAR(255) '$')
    WHERE i."TYPE"=7
        AND JSON_QUERY(i."JSON_CONTENT",'$.workflowNames') IS NOT NULL;
GO

COMMIT;
