Skip to content

Commit a871909

Browse files
committed
feat(migrate): add migration script to delete orphan templates
This script identifies and removes templates without associated dataverses, addressing issue IQSS#8600. It also updates dataverses using such templates as defaults before deleting the orphan templates to ensure data integrity.
1 parent 4dd8b40 commit a871909

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
-- Migration script to delete orphan templates (templates with no associated dataverse), see also issue #8600
2+
3+
DO
4+
$$
5+
DECLARE
6+
orphan_templates_count INTEGER;
7+
affected_collections_count INTEGER;
8+
row_count INTEGER;
9+
BEGIN
10+
-- Get the count of orphan templates
11+
SELECT COUNT(t.id) INTO orphan_templates_count
12+
FROM template t
13+
WHERE dataverse_id IS NULL;
14+
15+
-- Count dataverse collections that use orphan templates as default
16+
SELECT COUNT(*) INTO affected_collections_count
17+
FROM dataverse d
18+
WHERE d.defaulttemplate_id IN (
19+
SELECT t.id FROM template t WHERE dataverse_id IS NULL
20+
);
21+
22+
-- Only show hint if count is greater than 0
23+
IF orphan_templates_count > 0 THEN
24+
RAISE NOTICE '--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---';
25+
RAISE NOTICE 'Found % orphan templates (templates with no associated dataverse)', orphan_templates_count;
26+
RAISE NOTICE 'Found % dataverses using orphan templates as their default template', affected_collections_count;
27+
28+
-- First, update all dataverses that use orphan templates as default template
29+
UPDATE dataverse
30+
SET defaulttemplate_id = NULL
31+
WHERE defaulttemplate_id IN (
32+
SELECT t.id FROM template t WHERE dataverse_id IS NULL
33+
);
34+
35+
GET DIAGNOSTICS row_count = ROW_COUNT;
36+
RAISE NOTICE 'Updated % collections to remove references to orphan templates', row_count;
37+
38+
-- Then delete all orphan templates
39+
DELETE FROM template
40+
WHERE dataverse_id IS NULL;
41+
42+
GET DIAGNOSTICS row_count = ROW_COUNT;
43+
RAISE NOTICE 'Deleted % orphan templates', row_count;
44+
45+
COMMIT;
46+
RAISE NOTICE '--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---';
47+
END IF;
48+
END
49+
$$;

0 commit comments

Comments
 (0)