-- Nur Schema-Fix für falukant_predefine.political_office_benefit
-- (Fehler 23502: NULL in political_office_id trotz INSERT in office_type_id)
--
-- Ausführen, dann erneut falukant_political_office_benefits.sql

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'falukant_predefine' AND table_name = 'political_office_benefit'
  ) THEN
    RAISE EXCEPTION 'Tabelle fehlt.';
  END IF;

  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'falukant_predefine'
      AND table_name = 'political_office_benefit'
      AND column_name = 'political_office_id'
  ) AND NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'falukant_predefine'
      AND table_name = 'political_office_benefit'
      AND column_name = 'office_type_id'
  ) THEN
    ALTER TABLE falukant_predefine.political_office_benefit
      RENAME COLUMN political_office_id TO office_type_id;
  ELSIF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'falukant_predefine'
      AND table_name = 'political_office_benefit'
      AND column_name = 'political_office_id'
  ) AND EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'falukant_predefine'
      AND table_name = 'political_office_benefit'
      AND column_name = 'office_type_id'
  ) THEN
    UPDATE falukant_predefine.political_office_benefit
    SET office_type_id = COALESCE(office_type_id, political_office_id);
    ALTER TABLE falukant_predefine.political_office_benefit
      DROP COLUMN political_office_id;
  END IF;
END $$;
