-- ==============================================================
-- GNUmed database schema change script
--
-- License: GPL v2 or later
-- Author: karsten.hilbert@gmx.net
--
-- ==============================================================
\set ON_ERROR_STOP 1
--set default_transaction_read_only to off;

-- --------------------------------------------------------------
-- make sure we can setup labs
insert into dem.org_category (description)
select 'Laboratory'::text where not exists (
	select 1 from dem.org_category where description = 'Laboratory'
);

-- create "unknown laboratory" org
insert into dem.org (fk_category, description)
select
	(select pk from dem.org_category where description = 'Laboratory'),
	'unknown laboratory'::text
where not exists (
	select 1 from dem.org where description = 'unknown laboratory'
);

-- create "unknown lab" branch
insert into dem.org_unit (fk_org, fk_category, description)
select
	(select pk from dem.org where description = 'unknown laboratory'),
	(select pk from dem.org_category where description = 'Laboratory'),
	'branch of unknown laboratory'::text
where not exists (
	select 1 from dem.org_unit where
		description = 'branch of unknown laboratory'
			and
		fk_org = (select pk from dem.org where description = 'unknown laboratory')
);

-- create "unknown test org"
insert into clin.test_org (fk_org_unit, comment)
select
	(select pk from dem.org_unit where
		description = 'branch of unknown laboratory'
			and
		fk_org = (select pk from dem.org where description = 'unknown laboratory')
	),
	'auto-generated by v20-clin-test_type-dynamic.sql'::text
where not exists (
	select 1 from clin.test_org where fk_org_unit = (
		select pk from dem.org_unit where
			description = 'branch of unknown laboratory'
				and
			fk_org = (select pk from dem.org where description = 'unknown laboratory')
	)
);

-- .conversion_unit has been renamed to .reference_unit which
-- makes the audit trigger fail on update, thus we need to
-- disable this trigger for the update
alter table clin.test_type
	DISABLE TRIGGER zt_upd_test_type;

-- update test types
update clin.test_type set
	fk_test_org = (
		select pk from clin.test_org where fk_org_unit = (
			select pk from dem.org_unit where
				description = 'branch of unknown laboratory'
					and
				fk_org = (select pk from dem.org where description = 'unknown laboratory')
		)
	)
where
	fk_test_org is null
;

alter table clin.test_type
	ENABLE TRIGGER zt_upd_test_type;

-- set not null
alter table clin.test_type
	alter column fk_test_org
		set not null;

-- --------------------------------------------------------------
select gm.log_script_insertion('v20-clin-test_type-dynamic.sql', '20.3');
