Files
ljwx-deploy/apps/ljwx-health/base/sql/epic-360/50-tenant-root-closure.sql
T

35 lines
1.2 KiB
SQL

-- #350 local idempotent repair. Run the count queries before and after the INSERT.
SELECT COUNT(*) AS missing_root_closure_before
FROM sys_org_units o
WHERE o.parent_id = 0
AND COALESCE(o.is_deleted, 0) = 0
AND o.customer_id > 0
AND NOT EXISTS (
SELECT 1 FROM sys_org_closure c
WHERE c.ancestor_id = o.id AND c.descendant_id = o.id
AND c.customer_id = o.customer_id AND c.depth = 0);
INSERT INTO sys_org_closure (
ancestor_id, descendant_id, depth, customer_id, create_time, update_time)
SELECT o.id, o.id, 0, o.customer_id, NOW(), NOW()
FROM sys_org_units o
WHERE o.parent_id = 0
AND COALESCE(o.is_deleted, 0) = 0
AND o.customer_id > 0
AND NOT EXISTS (
SELECT 1 FROM sys_org_closure c
WHERE c.ancestor_id = o.id AND c.descendant_id = o.id
AND c.customer_id = o.customer_id AND c.depth = 0)
ON CONFLICT (ancestor_id, descendant_id, customer_id) DO NOTHING;
SELECT COUNT(*) AS missing_root_closure_after
FROM sys_org_units o
WHERE o.parent_id = 0
AND COALESCE(o.is_deleted, 0) = 0
AND o.customer_id > 0
AND NOT EXISTS (
SELECT 1 FROM sys_org_closure c
WHERE c.ancestor_id = o.id AND c.descendant_id = o.id
AND c.customer_id = o.customer_id AND c.depth = 0);