DECLARE
    i INTEGER;
    j INTEGER;
    k INTEGER;
    q INTEGER;
    v_sql LONG;
    p_sql LONG;
    l_sql LONG;
    CURRENT_SCHEMA VARCHAR(128);
BEGIN
	SELECT SYS_CONTEXT( 'USERENV', 'CURRENT_SCHEMA' ) INTO CURRENT_SCHEMA FROM DUAL;
    SELECT COUNT(*) INTO i FROM ALL_TABLES where OWNER = CURRENT_SCHEMA AND table_name = upper('IDN_USER_FUNCTIONALITY_PROPERTY');
    SELECT COUNT(*) INTO j FROM ALL_TABLES where OWNER = CURRENT_SCHEMA AND table_name = upper('IDN_USR_FUNCTIONALITY_PROPERTY');
    SELECT COUNT(*) INTO k FROM ALL_TABLES where OWNER = CURRENT_SCHEMA AND table_name = upper('IDN_USER_FUNCTIONALITY_MAPPING');
    SELECT COUNT(*) INTO q FROM USER_CONSTRAINTS WHERE OWNER = CURRENT_SCHEMA AND CONSTRAINT_NAME = upper('IDN_USER_FUNCTIONALITY_MAPPING_CONSTRAINT');

    IF i = 0 AND j = 0 THEN
    v_sql:='CREATE TABLE IDN_USR_FUNCTIONALITY_PROPERTY (
	            ID VARCHAR(255) NOT NULL,
	            USER_ID VARCHAR(255) NOT NULL,
	            TENANT_ID INTEGER NOT NULL,
	            FUNCTIONALITY_ID VARCHAR(255) NOT NULL,
	            PROPERTY_NAME VARCHAR(255),
	            PROPERTY_VALUE VARCHAR(255),
	            PRIMARY KEY (ID),
	            CONSTRAINT IDN_USR_FUNC_PROP_CONSTRAINT UNIQUE (USER_ID, TENANT_ID, FUNCTIONALITY_ID, PROPERTY_NAME))';
    EXECUTE IMMEDIATE v_sql;
    END IF;

    IF i = 1 AND j = 0 THEN
    v_sql:='ALTER TABLE IDN_USER_FUNCTIONALITY_PROPERTY RENAME TO IDN_USR_FUNCTIONALITY_PROPERTY';
    EXECUTE IMMEDIATE v_sql;
    p_sql:='ALTER TABLE IDN_USR_FUNCTIONALITY_PROPERTY RENAME CONSTRAINT IDN_USER_FUNCTIONALITY_PROPERTY_CONSTRAINT TO IDN_USR_FUNC_PROP_CONSTRAINT';
    EXECUTE IMMEDIATE p_sql;
    END IF;

    IF k = 0 THEN
    l_sql:='CREATE TABLE IDN_USER_FUNCTIONALITY_MAPPING (
	            ID VARCHAR(255) NOT NULL,
	            USER_ID VARCHAR(255) NOT NULL,
	            TENANT_ID INTEGER NOT NULL,
	            FUNCTIONALITY_ID VARCHAR(255) NOT NULL,
	            IS_FUNCTIONALITY_LOCKED NUMBER(1) NOT NULL,
	            FUNCTIONALITY_UNLOCK_TIME NUMBER(19) NOT NULL,
	            FUNCTIONALITY_LOCK_REASON VARCHAR(1023),
	            FUNCTIONALITY_LOCK_REASON_CODE VARCHAR(255),
	            PRIMARY KEY (ID),
	            CONSTRAINT IDN_USR_FUNC_MAP_CONSTRAINT UNIQUE (USER_ID, TENANT_ID, FUNCTIONALITY_ID))';
    EXECUTE IMMEDIATE l_sql;
    END IF;

    IF k = 1 AND q = 1 THEN
    l_sql:='ALTER TABLE IDN_USER_FUNCTIONALITY_MAPPING RENAME CONSTRAINT IDN_USER_FUNCTIONALITY_MAPPING_CONSTRAINT TO IDN_USR_FUNC_MAP_CONSTRAINT';
    EXECUTE IMMEDIATE l_sql;
    END IF;
END;
/
