CREATE SCHEMA IF NOT EXISTS BASIC;

CREATE TABLE BASIC.ATTRIBUTE_GROUP (
	ID BIGSERIAL PRIMARY KEY,
	GROUP_TYPE VARCHAR(64) NOT NULL DEFAULT '',
	GROUP_NAME VARCHAR(64) NOT NULL DEFAULT '',
	IS_PUBLIC SMALLINT NOT NULL DEFAULT -1,
	REMARK VARCHAR(128) NOT NULL DEFAULT '',
	
	UNIQUE (GROUP_TYPE)
);

CREATE TABLE BASIC.DATA_TYPE (
	ID BIGSERIAL PRIMARY KEY,
	DATA_TYPE VARCHAR(64) NOT NULL DEFAULT '',
	DATABASE_TYPE VARCHAR(32) NOT NULL DEFAULT '',
	
	UNIQUE (DATA_TYPE)
);

CREATE TABLE BASIC.MODEL_TYPE (
	ID BIGSERIAL PRIMARY KEY,
	MODEL_TYPE VARCHAR(64) NOT NULL DEFAULT '',
	MODEL_NAME VARCHAR(64) NOT NULL DEFAULT '',
	GRAPHIC_ELEMENT VARCHAR(64) NOT NULL DEFAULT '', -- 图元类型
	ICON BYTEA NOT NULL, -- 默认图标
	REMARK VARCHAR(128) NOT NULL DEFAULT '',
	
	UNIQUE (MODEL_TYPE)
);

CREATE TABLE BASIC.MODEL_GROUP (
	ID BIGSERIAL PRIMARY KEY,
	MODEL_TYPE_ID BIGINT NOT NULL,
	ATTRIBUTE_GROUP_ID BIGINT NOT NULL,
	
	UNIQUE (MODEL_TYPE_ID, ATTRIBUTE_GROUP_ID),

	FOREIGN KEY (MODEL_TYPE_ID) REFERENCES BASIC.MODEL_TYPE (ID) ON DELETE CASCADE,
	FOREIGN KEY (ATTRIBUTE_GROUP_ID) REFERENCES BASIC.ATTRIBUTE_GROUP (ID)
);

CREATE TABLE BASIC.ATTRIBUTE (
	ID BIGSERIAL PRIMARY KEY,
	ATTRIBUTE VARCHAR(128) NOT NULL DEFAULT '',
	ATTRIBUTE_NAME VARCHAR(64) NOT NULL DEFAULT '',
	DATA_TYPE_ID BIGINT NOT NULL,
	LENGTH_PRECISION INTEGER NOT NULL DEFAULT -1,
	SCALE INTEGER NOT NULL DEFAULT -1,
	IS_NOT_NULL SMALLINT NOT NULL DEFAULT -1,
	DEFAULT_VALUE VARCHAR(64) NOT NULL DEFAULT '',
	VALUE_RANGE VARCHAR(128) NOT NULL DEFAULT ',',
	IS_VISIBLE SMALLINT NOT NULL DEFAULT -1,

	FOREIGN KEY (DATA_TYPE_ID) REFERENCES BASIC.DATA_TYPE (ID)
);

CREATE TABLE BASIC.MODEL_ATTRIBUTE_PUBLIC (
	ID BIGSERIAL PRIMARY KEY,
	ATTRIBUTE_GROUP_ID BIGINT NOT NULL,
	ATTRIBUTE_ID BIGINT NOT NULL,

	UNIQUE (ATTRIBUTE_GROUP_ID, ATTRIBUTE_ID),

	FOREIGN KEY (ATTRIBUTE_GROUP_ID) REFERENCES BASIC.ATTRIBUTE_GROUP (ID),
	FOREIGN KEY (ATTRIBUTE_ID) REFERENCES BASIC.ATTRIBUTE (ID) ON DELETE CASCADE
);

CREATE TABLE BASIC.MODEL_ATTRIBUTE (
	ID BIGSERIAL PRIMARY KEY,
	MODEL_TYPE_ID BIGINT NOT NULL,
	ATTRIBUTE_GROUP_ID BIGINT NOT NULL,
	ATTRIBUTE_ID BIGINT NOT NULL,

	UNIQUE (MODEL_TYPE_ID, ATTRIBUTE_GROUP_ID, ATTRIBUTE_ID),

	FOREIGN KEY (MODEL_TYPE_ID) REFERENCES BASIC.MODEL_TYPE (ID) ON DELETE CASCADE,
	FOREIGN KEY (ATTRIBUTE_GROUP_ID) REFERENCES BASIC.ATTRIBUTE_GROUP (ID),
	FOREIGN KEY (ATTRIBUTE_ID) REFERENCES BASIC.ATTRIBUTE (ID) ON DELETE CASCADE
);

CREATE TABLE BASIC.ATTRIBUTE_TEMPLATE (
	ID BIGSERIAL PRIMARY KEY,
	TEMPLATE_NAME VARCHAR(64) NOT NULL DEFAULT '',
	DATA_TYPE_ID BIGINT NOT NULL,
	LENGTH_PRECISION INTEGER NOT NULL DEFAULT -1,
	SCALE INTEGER NOT NULL DEFAULT -1,
	IS_NOT_NULL SMALLINT NOT NULL DEFAULT -1,
	
	FOREIGN KEY (DATA_TYPE_ID) REFERENCES BASIC.DATA_TYPE (ID)
);

CREATE TABLE BASIC.MODEL_CONNECTIVITY (
	ID BIGSERIAL PRIMARY KEY,
	FROM_MODEL VARCHAR(64) NOT NULL DEFAULT '',
	TO_MODEL VARCHAR(64) NOT NULL DEFAULT '',
	CONNECTIVITY SMALLINT NOT NULL DEFAULT -1
);