Split the foreign key sql script into an 'into' and 'from' portion

Also, make use of up-front defined arrays of the tables involved, for
ease of editing in the future.
This commit is contained in:
Jeff Bradberry
2024-05-08 14:09:34 -04:00
parent 9e22865d2e
commit b837d549ff

View File

@@ -1,13 +1,35 @@
SELECT DISTINCT DO $$
tc.table_name, DECLARE
ccu.table_name AS foreign_table_name topology text[] := ARRAY['main_instance', 'main_instancegroup', 'main_instancegroup_instances'];
FROM information_schema.table_constraints AS tc excluded text[] := ARRAY['main_instance', 'main_instancegroup', 'main_instancegroup_instances', 'main_organizationinstancegroupmembership', 'main_unifiedjobtemplateinstancegroupmembership', 'main_inventoryinstancegroupmembership'];
JOIN information_schema.constraint_column_usage AS ccu BEGIN
ON ccu.constraint_name = tc.constraint_name CREATE TABLE tmp_fk_from AS (
WHERE tc.constraint_type = 'FOREIGN KEY' SELECT DISTINCT
AND tc.table_name,
(tc.table_name IN ('main_instance', 'main_instancegroup', 'main_instancegroup_instances') ccu.table_name AS foreign_table_name
AND ccu.table_name NOT IN ('main_instance', 'main_instancegroup', 'main_instancegroup_instances')) FROM information_schema.table_constraints AS tc
OR JOIN information_schema.constraint_column_usage AS ccu
(ccu.table_name IN ('main_instance', 'main_instancegroup', 'main_instancegroup_instances') ON ccu.constraint_name = tc.constraint_name
AND tc.table_name NOT IN ('main_instance', 'main_instancegroup', 'main_instancegroup_instances')); WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_name = ANY (excluded)
AND NOT ccu.table_name = ANY (topology)
);
CREATE TABLE tmp_fk_into AS (
SELECT DISTINCT
tc.table_name,
ccu.table_name AS foreign_table_name
FROM information_schema.table_constraints AS tc
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY'
AND ccu.table_name = ANY (excluded)
AND NOT tc.table_name = ANY (topology)
);
END $$;
SELECT * FROM tmp_fk_from;
SELECT * FROM tmp_fk_into;
DROP TABLE tmp_fk_from;
DROP TABLE tmp_fk_into;