-- create table
CREATE TABLE AKUZ.T_RESOURCE_QUOTA_LINK
(
    "resourcequotalinkid" uuid NOT NULL,
    "weektype" integer NOT NULL,
    "daytype" integer NOT NULL,
    "resource" uuid NOT NULL,
    "resourcescheduleid" uuid NOT NULL
);

ALTER TABLE AKUZ.T_RESOURCE_QUOTA_LINK ADD CONSTRAINT PK_T_RESOURCE_QUOTA_LINK
PRIMARY KEY (ResourceQuotaLinkID);

ALTER TABLE AKUZ.T_RESOURCE_QUOTA_LINK ADD CONSTRAINT FK_T_RESOURCE_T_RESOURCE_QUOTA_LINK_Resource
FOREIGN KEY("resource") REFERENCES AKUZ.T_RESOURCE (ResourceID);


-- insert table
insert into AKUZ.T_RESOURCE_QUOTA_LINK(ResourceQuotaLinkID,WeekType,DayType,Resource,ResourceScheduleID)
select uuid_generate_v4(),WeekType,DayType,Resource,ResourceScheduleID from AKUZ.T_RESOURCE_SCHEDULE

-- alter table / update records
ALTER TABLE AKUZ.T_RESOURCE_QUOTA ADD "resourcequotalink" uuid NULL;

UPDATE rq
SET "resourcequotalink" = l.ResourceQuotaLinkID
from AKUZ.T_RESOURCE_QUOTA rq
	join AKUZ.T_RESOURCE_QUOTA_LINK l on rq.ResourceSchedule = l.ResourceScheduleID;


ALTER TABLE AKUZ.T_RESOURCE_QUOTA ALTER COLUMN "resourcequotalink" SET NOT NULL;

ALTER TABLE AKUZ.T_RESOURCE_QUOTA ADD CONSTRAINT FK_T_RESOURCE_QUOTA_LINK_T_RESOURCE_QUOTA_ResourceQuotaLink
FOREIGN KEY("resourcequotalink") REFERENCES AKUZ.T_RESOURCE_QUOTA_LINK (ResourceQuotaLinkID);

ALTER TABLE AKUZ.T_RESOURCE_QUOTA_LINK drop column "resourcescheduleid";

ALTER TABLE AKUZ.T_RESOURCE_QUOTA DROP CONSTRAINT FK_T_RESOURCE_SCHEDULE_T_RESOURCE_QUOTA_ResourceSchedule;

DROP INDEX IF EXISTS UQ_T_RESOURCE_QUOTA_ResourceSchedule;

ALTER TABLE AKUZ.T_RESOURCE_QUOTA DROP COLUMN "resourceschedule";


-- trigger
DO 
$$ 
BEGIN 
	DROP TRIGGER IF EXISTS RESOURCE_SCHEDULE_Unique ON akuz.t_resource_schedule;
END; 
$$ ;


DROP FUNCTION IF EXISTS akuz.RESOURCE_SCHEDULE_Unique_Check();