The dblink extension lets you connect to remote PostgreSQL databases and run SQL queries or commands from within PolarDB for Oracle. Unlike foreign tables, dblink works with any database object—including stored procedures and functions—giving you more flexibility for cross-database operations.
For read-only access to remote tables, use postgres_fdw instead. It offers better performance for simple table queries.
Functions at a glance
| Function | Description |
|---|---|
dblink_connect | Opens a persistent connection to a remote database |
dblink_disconnect | Closes a persistent connection |
dblink | Runs a query in a remote database and returns rows |
dblink_exec | Runs a command (non-row-returning SQL) in a remote database |
dblink_open | Opens a cursor in a remote database |
dblink_fetch | Fetches rows from an open cursor |
dblink_close | Closes a cursor in a remote database |
dblink_get_connections | Returns the names of all open named connections |
dblink_error_message | Gets the last error message on a named connection |
dblink_send_query | Sends an asynchronous query to a remote database |
dblink_is_busy | Checks whether a connection is busy with an asynchronous query |
dblink_get_result | Gets the result of an asynchronous query |
dblink_cancel_query | Cancels a running asynchronous query on a connection |
dblink_connect
Opens a persistent connection to a remote database.
Syntax
dblink_connect(text connstr) returns text
dblink_connect(text connname, text connstr) returns textDescription
dblink_connect establishes a connection to a remote PostgreSQL database. The target server and database are identified by a standard libpq connection string. The connection persists until you close it explicitly or the database session ends.
Named connections: Assign a name to open multiple connections at the same time.
Unnamed connections: Omit the name to open a single unnamed connection. Opening a second unnamed connection replaces the first.
Foreign servers: Pass the name of an existing foreign server as the connection string. Use the
dblink_fdwforeign-data wrapper to define foreign servers.
Parameters
| Parameter | Description |
|---|---|
connname | The connection name. If omitted, the existing unnamed connection is replaced. |
connstr | A libpq connection string, for example: channel_name=local dbname=mydb user=postgres password=mypasswd. The host and port keywords are not supported—use channel_name instead. You can also pass the name of a foreign server. |
Return value
Returns OK on success. Reports an error otherwise.
Security notes
Only superusers can create connections that do not use password authentication. Non-superusers must use password authentication.
Examples
Connect with a connection string:
SELECT dblink_connect('channel_name=localhost dbname=postgres');
dblink_connect
----------------
OK
(1 row)Open a named connection:
SELECT dblink_connect('myconn', 'channel_name=localhost dbname=postgres options=-csearch_path=');
dblink_connect
----------------
OK
(1 row)Use a foreign server:
-- Note: local connection must require password authentication
-- Error if not: "password is required – Non-superuser cannot connect if
-- the server does not request a password."
CREATE SERVER fdtest FOREIGN DATA WRAPPER dblink_fdw OPTIONS (channel_name 'localhost', dbname 'contrib_regression');
CREATE USER regress_dblink_user WITH PASSWORD 'secret';
CREATE USER MAPPING FOR regress_dblink_user SERVER fdtest OPTIONS (user 'regress_dblink_user', password 'secret');
GRANT USAGE ON FOREIGN SERVER fdtest TO regress_dblink_user;
GRANT SELECT ON TABLE foo TO regress_dblink_user;
\set ORIGINAL_USER :USER
\c - regress_dblink_user
SELECT dblink_connect('myconn', 'fdtest');
dblink_connect
----------------
OK
(1 row)
SELECT * FROM dblink('myconn', 'SELECT * FROM foo') AS t(a int, b text, c text[]);
a | b | c
----+---+---------------
0 | a | {a0,b0,c0}
1 | b | {a1,b1,c1}
2 | c | {a2,b2,c2}
3 | d | {a3,b3,c3}
4 | e | {a4,b4,c4}
5 | f | {a5,b5,c5}
6 | g | {a6,b6,c6}
7 | h | {a7,b7,c7}
8 | i | {a8,b8,c8}
9 | j | {a9,b9,c9}
10 | k | {a10,b10,c10}
(11 rows)
\c - :ORIGINAL_USER
REVOKE USAGE ON FOREIGN SERVER fdtest FROM regress_dblink_user;
REVOKE SELECT ON TABLE foo FROM regress_dblink_user;
DROP USER MAPPING FOR regress_dblink_user SERVER fdtest;
DROP USER regress_dblink_user;
DROP SERVER fdtest;dblink_disconnect
Closes a persistent connection to a remote database.
Syntax
dblink_disconnect() returns text
dblink_disconnect(text connname) returns textDescription
dblink_disconnect closes a connection opened by dblink_connect. If no name is specified, the unnamed connection is closed.
Parameters
| Parameter | Description |
|---|---|
connname | The name of the connection to close. |
Return value
Returns OK on success. Reports an error otherwise.
Examples
SELECT dblink_disconnect();
dblink_disconnect
-------------------
OK
(1 row)
SELECT dblink_disconnect('myconn');
dblink_disconnect
-------------------
OK
(1 row)dblink
Runs a query in a remote database.
Syntax
dblink(text connname, text sql [, bool fail_on_error]) returns setof record
dblink(text connstr, text sql [, bool fail_on_error]) returns setof record
dblink(text sql [, bool fail_on_error]) returns setof recordDescription
dblink runs an SQL query—typically a SELECT statement—in a remote database and returns the resulting rows.
When called with two text parameters, the first is treated as a named connection. If no matching connection is found, it is used as a connection string and the connection is closed after the query completes.
Because dblink can run any query, it returns record rather than a fixed set of columns. You must declare the expected columns in the FROM clause alias of the calling query. PostgreSQL uses this declaration to resolve column references before the function runs. At runtime, the column count must match exactly; column names need not match and types are matched loosely (the returned strings must be valid input for the declared types).
Parameters
| Parameter | Description |
|---|---|
connname | The named connection to use. If omitted, the unnamed connection is used. |
connstr | A connection string, in the same format as dblink_connect. |
sql | The SQL query to run on the remote database, for example: select * from foo. |
fail_on_error | Defaults to true. When true, a remote error raises a local error. When false, a NOTICE is reported and no rows are returned. |
Return value
Returns the rows produced by the query. Declare the column names and types in the FROM clause alias, for example:
SELECT *
FROM dblink('dbname=mydb options=-csearch_path=',
'select proname, prosrc from pg_proc')
AS t1(proname name, prosrc text)
WHERE proname LIKE 'bytea%';Examples
Query using a connection string:
SELECT * FROM dblink('dbname=postgres options=-csearch_path=',
'select proname, prosrc from pg_proc')
AS t1(proname name, prosrc text) WHERE proname LIKE 'bytea%';
proname | prosrc
------------+------------
byteacat | byteacat
byteaeq | byteaeq
bytealt | bytealt
byteale | byteale
byteagt | byteagt
byteage | byteage
byteane | byteane
byteacmp | byteacmp
bytealike | bytealike
byteanlike | byteanlike
byteain | byteain
byteaout | byteaout
(12 rows)Query using an unnamed persistent connection:
SELECT dblink_connect('dbname=postgres options=-csearch_path=');
dblink_connect
----------------
OK
(1 row)
SELECT * FROM dblink('select proname, prosrc from pg_proc')
AS t1(proname name, prosrc text) WHERE proname LIKE 'bytea%';
proname | prosrc
------------+------------
byteacat | byteacat
byteaeq | byteaeq
bytealt | bytealt
byteale | byteale
byteagt | byteagt
byteage | byteage
byteane | byteane
byteacmp | byteacmp
bytealike | bytealike
byteanlike | byteanlike
byteain | byteain
byteaout | byteaout
(12 rows)Query using a named persistent connection:
SELECT dblink_connect('myconn', 'dbname=regression options=-csearch_path=');
dblink_connect
----------------
OK
(1 row)
SELECT * FROM dblink('myconn', 'select proname, prosrc from pg_proc')
AS t1(proname name, prosrc text) WHERE proname LIKE 'bytea%';
proname | prosrc
------------+------------
bytearecv | bytearecv
byteasend | byteasend
byteale | byteale
byteagt | byteagt
byteage | byteage
byteane | byteane
byteacmp | byteacmp
bytealike | bytealike
byteanlike | byteanlike
byteacat | byteacat
byteaeq | byteaeq
bytealt | bytealt
byteain | byteain
byteaout | byteaout
(14 rows)dblink_exec
Runs a command in a remote database.
Syntax
dblink_exec(text connname, text sql [, bool fail_on_error]) returns text
dblink_exec(text connstr, text sql [, bool fail_on_error]) returns text
dblink_exec(text sql [, bool fail_on_error]) returns textDescription
dblink_exec runs a command that does not return rows—such as INSERT, UPDATE, or DELETE—in a remote database.
When called with two text parameters, the first is treated as a named connection. If no matching connection is found, it is used as a connection string and the connection is closed after the command completes.
Parameters
| Parameter | Description |
|---|---|
connname | The named connection to use. If omitted, the unnamed connection is used. |
connstr | A connection string, in the same format as dblink_connect. |
sql | The command to run on the remote database, for example: insert into foo values(0, 'a', '{"a0","b0","c0"}'). |
fail_on_error | Defaults to true. When true, a remote error raises a local error. When false, a NOTICE is reported and ERROR is returned. |
Return value
Returns the command status string (for example, INSERT 0 1) on success, or ERROR if fail_on_error is set to false and an error occurs.
Examples
SELECT dblink_connect('dbname=dblink_test_standby');
dblink_connect
----------------
OK
(1 row)
SELECT dblink_exec('insert into foo values(21, ''z'', ''{"a0","b0","c0"}'');');
dblink_exec
-----------------
INSERT 943366 1
(1 row)
SELECT dblink_connect('myconn', 'dbname=regression');
dblink_connect
----------------
OK
(1 row)
SELECT dblink_exec('myconn', 'insert into foo values(21, ''z'', ''{"a0","b0","c0"}'');');
dblink_exec
------------------
INSERT 6432584 1
(1 row)
SELECT dblink_exec('myconn', 'insert into pg_class values (''foo'')',false);
NOTICE: sql error
DETAIL: ERROR: null value in column "relnamespace" violates not-null constraint
dblink_exec
-------------
ERROR
(1 row)dblink_open
Opens a cursor in a remote database.
Syntax
dblink_open(text cursorname, text sql [, bool fail_on_error]) returns text
dblink_open(text connname, text cursorname, text sql [, bool fail_on_error]) returns textDescription
dblink_open opens a cursor in a remote database. Use dblink_fetch to retrieve rows and dblink_close to close the cursor.
Because a cursor can only persist within a transaction, dblink_open issues a BEGIN on the remote side if the remote database is not already in a transaction. This transaction is committed when the matching dblink_close runs.
Parameters
| Parameter | Description |
|---|---|
connname | The named connection to use. If omitted, the unnamed connection is used. |
cursorname | The name to assign to the cursor. |
sql | A SELECT query to run on the remote database, for example: select * from pg_class. |
fail_on_error | Defaults to true. When true, a remote error raises a local error. When false, a NOTICE is reported and no rows are returned. |
Return value
Returns OK or ERROR.
Usage notes
If you use dblink_exec to modify data between dblink_open and dblink_close, and then an error occurs or dblink_disconnect is called before dblink_close, your changes will be lost because the transaction is aborted.
Examples
SELECT dblink_connect('dbname=postgres options=-csearch_path=');
dblink_connect
----------------
OK
(1 row)
SELECT dblink_open('foo', 'select proname, prosrc from pg_proc');
dblink_open
-------------
OK
(1 row)dblink_fetch
Fetches rows from an open cursor in a remote database.
Syntax
dblink_fetch(text cursorname, int howmany [, bool fail_on_error]) returns setof record
dblink_fetch(text connname, text cursorname, int howmany [, bool fail_on_error]) returns setof recordDescription
dblink_fetch retrieves rows from a cursor opened by dblink_open. Retrieval starts at the cursor's current position and stops when howmany rows are retrieved or the cursor reaches the end.
If the column count returned by the remote cursor does not match what is declared in the FROM clause, an error is raised and the cursor position is preserved. For column declaration syntax, see the dblink section.
Parameters
| Parameter | Description |
|---|---|
connname | The named connection to use. If omitted, the unnamed connection is used. |
cursorname | The name of the cursor to fetch rows from. |
howmany | The maximum number of rows to retrieve per call. |
fail_on_error | Defaults to true. When true, a remote error raises a local error. When false, a NOTICE is reported and no rows are returned. |
Return value
Returns the fetched rows. Declare the column names and types in the FROM clause alias (same as dblink).
Examples
SELECT dblink_connect('dbname=postgres options=-csearch_path=');
dblink_connect
----------------
OK
(1 row)
SELECT dblink_open('foo', 'select proname, prosrc from pg_proc where proname like ''bytea%''');
dblink_open
-------------
OK
(1 row)
SELECT * FROM dblink_fetch('foo', 5) AS (funcname name, source text);
funcname | source
----------+----------
byteacat | byteacat
byteacmp | byteacmp
byteaeq | byteaeq
byteage | byteage
byteagt | byteagt
(5 rows)
SELECT * FROM dblink_fetch('foo', 5) AS (funcname name, source text);
funcname | source
-----------+-----------
byteain | byteain
byteale | byteale
bytealike | bytealike
bytealt | bytealt
byteane | byteane
(5 rows)
SELECT * FROM dblink_fetch('foo', 5) AS (funcname name, source text);
funcname | source
------------+------------
byteanlike | byteanlike
byteaout | byteaout
(2 rows)
SELECT * FROM dblink_fetch('foo', 5) AS (funcname name, source text);
funcname | source
----------+--------
(0 rows)dblink_close
Closes a cursor in a remote database.
Syntax
dblink_close(text cursorname [, bool fail_on_error]) returns text
dblink_close(text connname, text cursorname [, bool fail_on_error]) returns textDescription
dblink_close closes a cursor opened by dblink_open. If the cursor is the last open cursor on a connection and dblink_open started an explicit transaction block, dblink_close issues a COMMIT to close the transaction.
Parameters
| Parameter | Description |
|---|---|
connname | The named connection to use. If omitted, the unnamed connection is used. |
cursorname | The name of the cursor to close. |
fail_on_error | Defaults to true. When true, a remote error raises a local error. When false, a NOTICE is reported and ERROR is returned. |
Return value
Returns OK or ERROR.
Examples
SELECT dblink_connect('dbname=postgres options=-csearch_path=');
dblink_connect
----------------
OK
(1 row)
SELECT dblink_open('foo', 'select proname, prosrc from pg_proc');
dblink_open
-------------
OK
(1 row)
SELECT dblink_close('foo');
dblink_close
--------------
OK
(1 row)dblink_get_connections
Returns the names of all open named connections.
Syntax
dblink_get_connections() returns text[]Description
dblink_get_connections returns an array of names of all currently open named dblink connections.
Return value
Returns a text array of connection names, or NULL if no named connections are open.
Examples
SELECT dblink_get_connections();dblink_error_message
Gets the last error message on a named connection.
Syntax
dblink_error_message(text connname) returns textDescription
dblink_error_message retrieves the most recent error message on a specific named connection.
Parameters
| Parameter | Description |
|---|---|
connname | The name of the connection to check. |
Return value
Returns the last error message, or an empty string if no error has occurred on the connection.
Examples
SELECT dblink_error_message('dtest1');dblink_send_query
Sends an asynchronous query to a remote database.
Syntax
dblink_send_query(text connname, text sql) returns intDescription
dblink_send_query submits a query to a remote database without waiting for it to complete. Only one asynchronous query can be active on a given connection at a time.
After sending, use dblink_is_busy to check status, dblink_get_result to collect results, and dblink_cancel_query to cancel if needed.
Parameters
| Parameter | Description |
|---|---|
connname | The named connection on which to run the asynchronous query. |
sql | The SQL query to run on the remote database, for example: select * from pg_class. |
Return value
Returns 1 if the query was sent successfully, or 0 on failure.
Examples
SELECT dblink_send_query('dtest1', 'SELECT * FROM foo WHERE f1 < 3');dblink_is_busy
Checks whether a connection is busy with an asynchronous query.
Syntax
dblink_is_busy(text connname) returns intDescription
dblink_is_busy checks whether an asynchronous query is still running on a connection.
Parameters
| Parameter | Description |
|---|---|
connname | The name of the connection to check. |
Return value
Returns 1 if an asynchronous query is in progress. Returns 0 if the connection is idle—in which case dblink_get_result will not block.
Examples
SELECT dblink_is_busy('dtest1');dblink_get_result
Gets the result of an asynchronous query.
Syntax
dblink_get_result(text connname [, bool fail_on_error]) returns setof recordDescription
dblink_get_result collects the result of an asynchronous query sent by dblink_send_query. If the query is not yet complete, the function waits until it finishes.
Parameters
| Parameter | Description |
|---|---|
connname | The named connection on which the asynchronous query was sent. |
fail_on_error | Defaults to true. When true, a remote error raises a local error. When false, a NOTICE is reported and no rows are returned. |
Return value
Row-returning queries: Returns the rows produced by the query. Declare the column names and types in the
FROMclause alias (same asdblink).Non-row-returning commands: Returns a single row with a single text column containing the command status string. Declare a single text column in the
FROMclause.
Usage notes
Call
dblink_get_resultonce for each query sent, plus one additional time to drain the empty-set result, before the connection can be reused.When using
dblink_send_queryanddblink_get_result,dblinkfetches the entire remote query result before returning any rows. For large result sets, this can cause memory bloat in the local session. To avoid this, usedblink_opento open a cursor and fetch rows in batches withdblink_fetch. Alternatively, usedblink(), which helps prevent the memory bloat caused by spooling large result sets to a disk.
Examples
contrib_regression=# SELECT dblink_connect('dtest1', 'dbname=contrib_regression');
dblink_connect
----------------
OK
(1 row)
contrib_regression=# SELECT * FROM
contrib_regression-# dblink_send_query('dtest1', 'select * from foo where f1 < 3') AS t1;
t1
----
1
(1 row)
contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
f1 | f2 | f3
----+----+------------
0 | a | {a0,b0,c0}
1 | b | {a1,b1,c1}
2 | c | {a2,b2,c2}
(3 rows)
contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
f1 | f2 | f3
----+----+----
(0 rows)
contrib_regression=# SELECT * FROM
contrib_regression-# dblink_send_query('dtest1', 'select * from foo where f1 < 3; select * from foo where f1 > 6') AS t1;
t1
----
1
(1 row)
contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
f1 | f2 | f3
----+----+------------
0 | a | {a0,b0,c0}
1 | b | {a1,b1,c1}
2 | c | {a2,b2,c2}
(3 rows)
contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
f1 | f2 | f3
----+----+---------------
7 | h | {a7,b7,c7}
8 | i | {a8,b8,c8}
9 | j | {a9,b9,c9}
10 | k | {a10,b10,c10}
(4 rows)
contrib_regression=# SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
f1 | f2 | f3
----+----+----
(0 rows)dblink_cancel_query
Cancels a running asynchronous query on a connection.
Syntax
dblink_cancel_query(text connname) returns textDescription
dblink_cancel_query sends a cancel request to the remote database for queries running on a named connection. Cancellation is not guaranteed—a query that has already completed cannot be canceled. A cancel request only improves the odds that a query fails. After sending a cancel request, still call dblink_get_result or use other methods to complete the query protocol.
Parameters
| Parameter | Description |
|---|---|
connname | The name of the connection on which to cancel the running query. |
Return value
Returns OK if the cancel request was sent, or an error message string if it could not be sent.
Examples
SELECT dblink_cancel_query('dtest1');