1

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?

asked Jan 13, 2020 at 8:47

2 Answers 2

0

Try a DO statement:

DO
$$BEGIN
 CREATE SERVER ...;
EXCEPTION
 WHEN duplicate_object THEN
 NULL; -- ignore
END;$$;
answered Jan 13, 2020 at 10:07
0

You can check if a foreign server exists with name 'my_server_name' using the following:

DECLARE
 srvExists boolean DEFAULT false;
BEGIN 
SELECT true INTO srvExists FROM pg_catalog.pg_foreign_server 
 WHERE lower(srvname) = lower( 'my_server_name' );
IF srvExists THEN
 RAISE NOTICE 'foreign server my_server_name exists';
ELSE
 CREATE SERVER my_server_name FOREIGN DATA WRAPPER postgres_fdw
 OPTIONS (dbname '<your DB>', host '<your host>', port '<your port');
END IF;
END;
answered May 8, 2021 at 16:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.