BEGIN;

do $$
declare
  cons_name text;
begin
  select constraint_name
     into cons_name
  from information_schema.constraint_column_usage
  where constraint_schema = current_schema()
  and column_name = 'name'
  and table_name = 'rules';

  execute 'alter table rules drop constraint IF EXISTS '||cons_name;
end;
$$;

ALTER TABLE rules ADD COLUMN flow_id bigint;

create table "flow_dest" (
    "flow_id" bigint not null,
    "instance_id" bigint not null, primary key ("flow_id", "instance_id"));

do $$
declare
  flow record;
begin
FOR flow IN (SELECT * FROM flows) LOOP
    INSERT INTO flow_dest (flow_id, instance_id) VALUES (flow.id, flow.destination_id);
END LOOP;
end;
$$;

ALTER TABLE flows DROP COLUMN destination_id;

COMMIT;