ALTER TABLE kandangs
DROP CONSTRAINT IF EXISTS kandangs_project_flock_id_fkey;

ALTER TABLE kandangs DROP COLUMN IF EXISTS project_flock_id;

-- Only alter if tables exist
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_chickins') THEN
        ALTER TABLE project_chickins
          DROP CONSTRAINT IF EXISTS fk_project_flock_kandang_id;
        ALTER TABLE project_chickins
          ADD CONSTRAINT fk_project_flock_kandang_id
               FOREIGN KEY (project_flock_kandang_id)
               REFERENCES project_flock_kandangs(id)
               ON UPDATE CASCADE
               ON DELETE CASCADE;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'project_flock_populations') THEN
        ALTER TABLE project_flock_populations
          DROP CONSTRAINT IF EXISTS fk_project_flock_kandang_id;
        ALTER TABLE project_flock_populations
          ADD CONSTRAINT fk_project_flock_kandang_id
               FOREIGN KEY (project_flock_kandang_id)
               REFERENCES project_flock_kandangs(id)
               ON UPDATE CASCADE
               ON DELETE CASCADE;
    END IF;
END $$;