Foreign Data Wrappers with Postgres
21 Jan 2016Foreign data wrappers are extensions that can be engaged within PostgreSQL that allow you access to remote objects in other databases.
In today’s post, I’m going to run through the basic method of gaining access to a table that sits in one PostgreSQL database from another.
Commands
First of all, you need to install the fdw extension with the CREATE EXTENSION command:
Next, you need to make the target database (the database that you want to import data from) accessible to this database. You define a foreign server using the CREATE SERVER command:
This is going to address a database called the_target
on the same host (because of localhost
).
Next, you need to link up the locally running user to a remote user. This is done using the CREATE USER MAPPING command.
So this links up a local user called local_user
with a remote user called remote_user
.
These steps only need to be run once for each remote connection to be established.
Get some data
To actually start writing some queries against the foreign data interface, you need to create the table using CREATE FOREIGN TABLE. After you’ve done this, the foreign table will appear as a first-class, queryable object in your database.
So, this creates a table called local_name_for_remote_table
which is latched up to some_remote_table
.
And that’s it.