PostgreSQL – Creating Foreign Server Only If Not Exists

postgresql

As far as I know in order to create a foreign server (for a FDW) you need to do the following:

CREATE SERVER my_wrapper FOREIGN DATA WRAPPER postgres_fdw OPTIONS (
    dbname 'wrapperDB',
    host '127.0.0.1',
    port '5432'
);")

But because I create a migration script for an existing database, I want to be able to check whether this server exists with the same name and then create in a similar approach that is used upon tables:

CREATE TABLE IF NOT EXISTS mytable ...

Or in stored procedures:

CREATE OR REPLACE FUNCTION public.myfunction(text)....

Do you have any idea how to do that?

Best Answer

Try a DO statement:

DO
$$BEGIN
   CREATE SERVER ...;
EXCEPTION
   WHEN duplicate_object THEN
      NULL;  -- ignore
END;$$;