Create a foreign table pointing to a view in Postgres
Asked Answered
B

3

15

Is it possible to create a foreign table, using Postgres Foreign Data Wrapper, that points to a view instead of a table?

Balfore answered 16/5, 2014 at 15:7 Comment(0)
B
17

Yes, it is possible!

The following query worked perfectly:

CREATE FOREIGN TABLE facts(name character varying(255))
SERVER my_server 
OPTIONS (table_name 'facts');

Where facts is a view in my_server instead of a table.

Balfore answered 16/5, 2014 at 15:7 Comment(2)
AFAIK you don't have to specify the table_name option if it is the same as the foreign table's name.Tessellated
You don't have to specify the table definition either if you use IMPORT FOREIGN SCHEMA, but you do have to explicitly include the view in the LIMIT TO clause.Giff
U
9

Recently I had to do the same thing and here are the steps that worked for me. All these commands are run on the local postgreSQL DB.

CREATE EXTENSION postgres_fdw;
CREATE SERVER remote_server_name
  FOREIGN DATA WRAPPER postgres_fdw
  OPTIONS (host '10.10.10.10', port '5432', dbname 'remote_db_name');

CREATE USER MAPPING FOR local_user_name
  SERVER remote_server_name
  OPTIONS (user 'remote_user', password 'remote_password');

CREATE FOREIGN TABLE local_table_name (
  id NUMERIC NOT NULL,
  row TEXT,
  another_row INTEGER,
  whatever_row TEXT
)
  SERVER remote_server_name
  OPTIONS (schema_name 'public', table_name 'remote_table_name');
Upbow answered 19/2, 2018 at 9:32 Comment(0)
C
1

I have the same question. In pgadmin4 for postgresql-11, if use GUI Command: Create -> Foreign Table... on table, it works; but on view, it does't works, you will get a empty table.

for view, i use this code, it works:

IMPORT FOREIGN SCHEMA remote_schema_name
LIMIT TO (remote_view_name)
FROM SERVER remote_host_map_name INTO local_shema_name;

The reason is, for table, pgadmin4 can create columns same as remote table in constract SQL statement, but for view, it create no columns in constract SQL statement.

Cobblestone answered 22/6, 2020 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.