-- Migration: repair foreign key between horaires_gares_desservies.horaire_id and horaires.id -- This script will: -- 1) check the column types of horaires.id and horaires_gares_desservies.horaire_id -- 2) if types match and FK doesn't exist, create the FK constraint -- 3) otherwise, print a NOTICE explaining the mismatch for manual resolution DO $$ DECLARE t_horaire TEXT; t_horaire_fk TEXT; cnt INT; BEGIN -- ensure target tables exist IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'horaires' AND relkind = 'r') THEN RAISE NOTICE 'Table public.horaires does not exist in this database/schema.'; RETURN; END IF; IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'horaires_gares_desservies' AND relkind = 'r') THEN RAISE NOTICE 'Table public.horaires_gares_desservies does not exist in this database/schema.'; RETURN; END IF; -- get formatted types SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) INTO t_horaire FROM pg_attribute a WHERE a.attrelid = 'public.horaires'::regclass AND a.attname = 'id'; SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) INTO t_horaire_fk FROM pg_attribute a WHERE a.attrelid = 'public.horaires_gares_desservies'::regclass AND a.attname = 'horaire_id'; RAISE NOTICE 'Detected types -> horaires.id: %, horaires_gares_desservies.horaire_id: %', t_horaire, t_horaire_fk; -- check existing FK from horaires_gares_desservies to horaires SELECT count(*) INTO cnt FROM pg_constraint c WHERE c.conrelid = 'public.horaires_gares_desservies'::regclass AND c.confrelid = 'public.horaires'::regclass AND c.contype = 'f'; IF cnt > 0 THEN RAISE NOTICE 'A foreign-key constraint from horaires_gares_desservies to horaires already exists (count=%). No action taken.', cnt; RETURN; END IF; -- If types match, create the FK IF t_horaire IS NOT NULL AND t_horaire_fk IS NOT NULL AND t_horaire = t_horaire_fk THEN EXECUTE 'ALTER TABLE public.horaires_gares_desservies ADD CONSTRAINT fk_horaires_gares_horaire_id FOREIGN KEY (horaire_id) REFERENCES public.horaires(id) ON DELETE CASCADE'; RAISE NOTICE 'Foreign key constraint fk_horaires_gares_horaire_id created successfully.'; ELSE RAISE NOTICE 'Column types do not match or could not be determined. Manual intervention required.'; RAISE NOTICE 'Detected types -> horaires.id: %, horaires_gares_desservies.horaire_id: %', t_horaire, t_horaire_fk; RAISE NOTICE 'If both should be UUID, consider converting [or recreating] the columns and then re-run this script.'; RAISE NOTICE 'If both should be BIGINT, consider altering types to bigint. Do not run automatic conversion without backup.'; END IF; END $$;