Implement recovery mechanism for orphaned tablos in organization migration

- Add a safety net to handle legacy inconsistencies by assigning orphaned tablos to a dedicated recovery organization.
- Ensure that the NOT NULL constraint can be applied to the organization_id field in the tablos table.
This commit is contained in:
Arthur Belleville 2026-03-04 21:52:50 +01:00
parent 7c15ff3275
commit 521772becb
No known key found for this signature in database

View file

@ -133,6 +133,25 @@ FROM public.profiles p
WHERE p.id = t.owner_id
AND t.organization_id IS NULL;
-- Safety net for legacy inconsistencies: some historical tablos can reference
-- owners that do not have a profile row anymore. Assign these orphaned rows to
-- a dedicated recovery organization so the NOT NULL constraint can be applied.
DO $$
DECLARE
recovery_organization_id integer;
BEGIN
IF EXISTS (SELECT 1 FROM public.tablos WHERE organization_id IS NULL) THEN
INSERT INTO public.organizations (name)
VALUES ('Recovered Legacy Workspace')
RETURNING id INTO recovery_organization_id;
UPDATE public.tablos t
SET organization_id = recovery_organization_id
WHERE t.organization_id IS NULL;
END IF;
END;
$$;
-- Ensure future tablos inherit owner's organization when omitted
CREATE OR REPLACE FUNCTION public.set_tablo_organization_from_owner() RETURNS trigger
LANGUAGE plpgsql