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