From 521772becbd88af85ce059e0953c9c1ab315d9d0 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 4 Mar 2026 21:52:50 +0100 Subject: [PATCH] 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. --- ...add_organizations_and_org_owned_tablos.sql | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/supabase/migrations/20260304221500_add_organizations_and_org_owned_tablos.sql b/supabase/migrations/20260304221500_add_organizations_and_org_owned_tablos.sql index 7ce81ee..2eb6daf 100644 --- a/supabase/migrations/20260304221500_add_organizations_and_org_owned_tablos.sql +++ b/supabase/migrations/20260304221500_add_organizations_and_org_owned_tablos.sql @@ -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