Skip to content

Use dblink to Query Remote Databases

Connect from inside your Managed PostgreSQL service to another PostgreSQL database, another database of the same service or a remote server, and run queries there with the dblink extension.

Before You Start

  • Open a psql session as avnadmin. See Connect with psql.

  • Collect the host, port, database name, user and password of the target. For another Exoscale Managed PostgreSQL service, or another database of the same service, read them from the connection URI:

    exo dbaas show SERVICE_NAME -z ZONE --uri

    Parameters:

    • SERVICE_NAME: name of the service that holds the target database.
    • ZONE: zone of that service, for example ch-gva-2.

    To reach another database of the same service, use the same host and port and change only dbname.

Important

With dblink, the database server opens the connection, not your workstation. A remote server sees the address of the service, so its firewall must accept that address. Check which address it sees with SELECT inet_client_addr(); run through dblink on the remote side, or in the remote server’s connection log.

Enable the Extension

In the database you query from:

CREATE EXTENSION dblink;

Run a One-Off Query

Pass the connection string and the query. Declare the result columns, because PostgreSQL cannot know the remote row type:

SELECT *
FROM dblink(
    'host=REMOTE_HOST port=REMOTE_PORT dbname=REMOTE_DATABASE user=REMOTE_USER password=REMOTE_PASSWORD sslmode=require',
    'SELECT item_id, label FROM inventory'
) AS remote_inventory(item_id int, label text);

Parameters:

  • REMOTE_HOST, REMOTE_PORT, REMOTE_DATABASE, REMOTE_USER, REMOTE_PASSWORD: connection details of the target.

The password is mandatory. Without it, dblink stops with ERROR: password or GSSAPI delegated credentials required, because avnadmin is not a superuser. This also applies to another database of the same service: a connection string with only dbname=OTHER_DB fails the same way.

Warning

A connection string written in a query can end up in pg_stat_activity, pg_stat_statements and the service logs. For anything recurring, store the credentials in a user mapping, see Store Credentials in a User Mapping.

Use a Named Connection

To run several queries against the same target, open a named connection once:

SELECT dblink_connect(
    'inventory_conn',
    'host=REMOTE_HOST port=REMOTE_PORT dbname=REMOTE_DATABASE user=REMOTE_USER password=REMOTE_PASSWORD sslmode=require'
);
SELECT *
FROM dblink('inventory_conn', 'SELECT item_id, label FROM inventory')
    AS remote_inventory(item_id int, label text);

Run a statement that returns no rows, such as UPDATE or DELETE, with dblink_exec():

SELECT dblink_exec('inventory_conn', 'DELETE FROM inventory WHERE archived');

List the open connections of the session, then close the connection:

SELECT unnest(dblink_get_connections());
SELECT dblink_disconnect('inventory_conn');

Caution

A named connection belongs to the server session. Through a connection pool in transaction mode, consecutive statements can run on different server sessions, so the connection may be missing, or left open for another client. Use the PostgreSQL port of the service for work that relies on dblink_connect(). See Manage connection pools.

Store Credentials in a User Mapping

Define the target once as a foreign server, attach the credentials to a user mapping, then use the server name instead of a connection string:

CREATE SERVER inventory_srv
    FOREIGN DATA WRAPPER dblink_fdw
    OPTIONS (
        host 'REMOTE_HOST',
        port 'REMOTE_PORT',
        dbname 'REMOTE_DATABASE',
        sslmode 'require'
    );
CREATE USER MAPPING FOR avnadmin
    SERVER inventory_srv
    OPTIONS (
        user 'REMOTE_USER',
        password 'REMOTE_PASSWORD'
    );
SELECT *
FROM dblink('inventory_srv', 'SELECT item_id, label FROM inventory')
    AS remote_inventory(item_id int, label text);

The server name also works with dblink_connect('inventory_conn', 'inventory_srv').

To let another role use the server, grant it USAGE and create a mapping for it:

GRANT USAGE ON FOREIGN SERVER inventory_srv TO USERNAME;
CREATE USER MAPPING FOR USERNAME
    SERVER inventory_srv
    OPTIONS (
        user 'REMOTE_USER',
        password 'REMOTE_PASSWORD'
    );

Parameters:

  • USERNAME: a role of this service. Without its own mapping, it gets ERROR: user mapping not found for user "USERNAME", server "inventory_srv".

Security Considerations

  • Who can call dblink. The dblink functions are owned by the platform and executable by every role of the database. avnadmin cannot revoke that (REVOKE reports no privileges could be revoked). Create the extension only in the databases that need it.
  • Stored passwords. avnadmin can read the options of its own user mappings, password included, in pg_user_mappings. Other roles do not see the options of the mappings of avnadmin. Use a dedicated, least-privileged account on the remote side.
  • Certificate checks. sslmode=require encrypts the connection but does not check the remote certificate. For a server outside your control, use sslmode=verify-full with an sslrootcert option.

Use postgres_fdw Instead

postgres_fdw maps remote tables into the local catalog. The planner can then send filters, joins and aggregates to the remote server, and you write ordinary queries without declaring result types.

dblinkpostgres_fdw
Remote objectsQueries passed as textForeign tables
Result typesDeclared in every callImported once
PlannerRemote query is opaqueFilters, joins and aggregates can run remotely
Writesdblink_exec()INSERT, UPDATE, DELETE
Good forOne-off queries, dynamic SQLA standing link to a remote schema

Setup uses the same foreign server and user mapping model:

CREATE EXTENSION postgres_fdw;
CREATE SERVER inventory_fdw
    FOREIGN DATA WRAPPER postgres_fdw
    OPTIONS (
        host 'REMOTE_HOST',
        port 'REMOTE_PORT',
        dbname 'REMOTE_DATABASE',
        sslmode 'require'
    );
CREATE USER MAPPING FOR avnadmin
    SERVER inventory_fdw
    OPTIONS (
        user 'REMOTE_USER',
        password 'REMOTE_PASSWORD'
    );

Import remote tables into a local schema, then query them:

CREATE SCHEMA remote_inventory;
IMPORT FOREIGN SCHEMA public
    LIMIT TO (inventory, warehouses)
    FROM SERVER inventory_fdw
    INTO remote_inventory;
SELECT w.name, count(*) AS items
FROM remote_inventory.inventory i
JOIN remote_inventory.warehouses w ON w.id = i.warehouse_id
GROUP BY w.name;

Check what runs remotely:

EXPLAIN (VERBOSE)
SELECT count(*) FROM remote_inventory.inventory WHERE archived;

The plan shows a Foreign Scan whose Remote SQL line contains the WHERE clause and the count(*), which means both run on the remote server.

Related Pages

Last updated on