The DBLink extension

更新时间:
复制 MD 格式

The dblink extension lets you query and execute commands on remote PostgreSQL databases from within your current database session. Unlike foreign tables, dblink works with any database object — including stored procedures and functions — making it useful when you need more than read access to remote tables.

To read data from remote tables only, use postgres_fdw instead. It provides better performance for table access.

Usage notes

  • In PolarDB for PostgreSQL, the host and port keywords are not supported in connection strings. Use channel_name instead.

    channel_name=local dbname=mydb user=postgres password=mypasswd
  • To reduce the risk of search_path injection when untrusted users have database access, set options=-csearch_path= in your connection strings.

Functions

Function Description
dblink_connect Opens a persistent connection to a remote database
dblink_disconnect Closes a persistent connection
dblink Runs a query and returns rows from a remote database
dblink_exec Runs a command (no rows returned) on a remote database
dblink_open Opens a cursor on a remote database
dblink_fetch Fetches rows from an open cursor
dblink_close Closes a cursor on a remote database
dblink_get_connections Lists 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 has an active async query
dblink_get_result Gets results from an asynchronous query
dblink_cancel_query Cancels the active query on a named 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 text

Parameters

Parameter Description
connname Name of the connection. If omitted, the existing unnamed connection is replaced. Only one unnamed connection can be open at a time.
connstr A libpq connection string or the name of an existing foreign server. In PolarDB for PostgreSQL, use channel_name in place of host and port. Example: channel_name=local dbname=mydb user=postgres password=mypasswd

Return value

Returns OK on success. Reports an error otherwise.

Example

Connect without a name (unnamed connection):

SELECT dblink_connect('channel_name=localhost dbname=postgres');
 dblink_connect
----------------
 OK
(1 row)

Connect with a name:

SELECT dblink_connect('myconn', 'channel_name=localhost dbname=postgres options=-csearch_path=');
 dblink_connect
----------------
 OK
(1 row)

Connect using a foreign server defined with dblink_fdw:

-- Create a foreign server and user mapping
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;

-- Connect and query as the mapped 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}
...
(11 rows)

-- Clean up
\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;
For foreign server connections to work, local connections must require password authentication. Without it, dblink_connect() returns: ERROR: password is required. Change the target server's authentication method to resolve this.

dblink_disconnect

Closes a persistent connection opened by dblink_connect.

Syntax

dblink_disconnect() returns text
dblink_disconnect(text connname) returns text

Parameters

Parameter Description
connname Name of the connection to close. If omitted, closes the unnamed connection.

Return value

Returns OK on success. Reports an error otherwise.

Example

SELECT dblink_disconnect();
 dblink_disconnect
-------------------
 OK
(1 row)

SELECT dblink_disconnect('myconn');
 dblink_disconnect
-------------------
 OK
(1 row)

dblink

Runs a query on a remote database and returns the resulting rows.

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 record

Parameters

Parameter Description
connname Name of an open persistent connection. If omitted, uses the unnamed connection.
connstr A connection string (same format as dblink_connect). If two text parameters are provided and the first matches no open connection name, it is treated as a connection string and a transient connection is used for the query.
sql The SQL query to run on the remote database. Example: select * from foo
fail_on_error Default: true. When true, remote errors raise a local error. When false, remote errors issue a NOTICE and return no rows.

Return value

Returns a set of records. Because dblink returns generic records, you must declare column names and types in the FROM clause alias. If the remote result does not match the declared column count, an error is raised.

Practical examples

Data synchronization — pull data from a remote table into a local staging table:

INSERT INTO local_staging_table (col1, col2)
SELECT remote_col1, remote_col2
FROM dblink('channel_name=remote_host dbname=remote_db user=myuser password=mypasswd',
            'SELECT col1, col2 FROM remote_table')
AS rt(remote_col1 INTEGER, remote_col2 TEXT);

Cross-database reporting — join local and remote data in a single query:

SELECT l.customer_name, r.order_total
FROM customers l
JOIN dblink('channel_name=orders_host dbname=orders_db user=myuser password=mypasswd',
            'SELECT customer_id, sum(amount) AS order_total FROM orders GROUP BY customer_id')
     AS r(customer_id INTEGER, order_total NUMERIC) ON l.customer_id = r.customer_id;

dblink_exec

Runs a command on a remote database. Use this for SQL statements that do not return rows, such as INSERT, UPDATE, or DELETE.

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 text

Parameters

Parameter Description
connname Name of an open persistent connection. If omitted, uses the unnamed connection.
connstr A connection string (same format as dblink_connect). If two text parameters are provided and the first matches no open connection name, it is used as a connection string and a transient connection is established.
sql The command to run on the remote database. Example: insert into foo values(0, 'a', '{"a0","b0","c0"}')
fail_on_error Default: true. When true, remote errors raise a local error. When false, remote errors issue a NOTICE and the return value is ERROR.

Return value

Returns a command status string such as INSERT 0 1, or ERROR if fail_on_error is false and the command fails.

Example

SELECT dblink_connect('dbname=dblink_test_standby');

-- Insert a row using the unnamed connection
SELECT dblink_exec('insert into foo values(21, ''z'', ''{"a0","b0","c0"}'');');
   dblink_exec
-----------------
 INSERT 943366 1
(1 row)

-- Insert using a named connection
SELECT dblink_connect('myconn', 'dbname=regression');

SELECT dblink_exec('myconn', 'insert into foo values(21, ''z'', ''{"a0","b0","c0"}'');');
   dblink_exec
------------------
 INSERT 6432584 1
(1 row)

-- Suppress errors with fail_on_error = false
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 on a remote database. Use cursors to fetch large result sets in batches rather than all at once.

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 text

Parameters

Parameter Description
connname Name of an open persistent connection. If omitted, uses the unnamed connection.
cursorname Name to assign to the cursor.
sql A SELECT query to run on the remote database. Example: select * from pg_class
fail_on_error Default: true. When true, remote errors raise a local error. When false, remote errors issue a NOTICE and return no rows.

Return value

Returns OK on success, or ERROR on failure.

How it works

A cursor exists only within a transaction. If the remote database is not already in a transaction when dblink_open is called, it starts one with BEGIN. That transaction is committed when the matching dblink_close runs and the cursor is the last one on the connection.

Warning

If you call dblink_exec to modify data between dblink_open and dblink_close, and an error occurs (or you call dblink_disconnect before dblink_close), the transaction is aborted and all changes are lost.

Example

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 a cursor opened by dblink_open.

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 record

Parameters

Parameter Description
connname Name of the connection the cursor belongs to. If omitted, uses the unnamed connection.
cursorname Name of the cursor to fetch from.
howmany Maximum number of rows to retrieve. Fetching starts at the current cursor position. Fewer rows are returned if the cursor reaches the end before the limit.
fail_on_error Default: true. When true, remote errors raise a local error. When false, remote errors issue a NOTICE and return no rows.

Return value

Returns a set of records. Declare column names and types in the FROM clause, the same as with dblink.

Example

SELECT dblink_connect('dbname=postgres options=-csearch_path=');

SELECT dblink_open('foo', 'select proname, prosrc from pg_proc where proname like ''bytea%''');

-- Fetch in batches of 5
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)

-- Cursor exhausted — returns 0 rows
SELECT * FROM dblink_fetch('foo', 5) AS (funcname name, source text);
 funcname | source
----------+--------
(0 rows)

dblink_close

Closes a cursor opened by dblink_open.

Syntax

dblink_close(text cursorname [, bool fail_on_error]) returns text
dblink_close(text connname, text cursorname [, bool fail_on_error]) returns text

Parameters

Parameter Description
connname Name of the connection the cursor belongs to. If omitted, uses the unnamed connection.
cursorname Name of the cursor to close.
fail_on_error Default: true. When true, remote errors raise a local error. When false, remote errors issue a NOTICE and the return value is ERROR.

Return value

Returns OK on success, or ERROR on failure.

If dblink_open started an explicit transaction and this cursor is the last open cursor on the connection, dblink_close commits that transaction with COMMIT.

Example

SELECT dblink_connect('dbname=postgres options=-csearch_path=');

SELECT dblink_open('foo', 'select proname, prosrc from pg_proc');

SELECT dblink_close('foo');
 dblink_close
--------------
 OK
(1 row)

dblink_get_connections

Returns an array of all open named connection names.

Syntax

dblink_get_connections() returns text[]

Return value

A text array of connection names. Returns NULL if no named connections are open.

Example

SELECT dblink_get_connections();

dblink_error_message

Gets the last error message on a named connection.

Syntax

dblink_error_message(text connname) returns text

Parameters

Parameter Description
connname Name of the connection to check.

Return value

The last error message on the connection, or an empty string if no errors have occurred.

Example

SELECT dblink_error_message('dtest1');

dblink_send_query

Sends an asynchronous query to a remote database without waiting for it to complete.

Syntax

dblink_send_query(text connname, text sql) returns int

Parameters

Parameter Description
connname Name of the connection on which to send the query.
sql The SQL query to run on the remote database. Example: select * from pg_class

Return value

Returns 1 if the query was sent successfully, or 0 on failure.

Usage notes

  • Only one async query can be active per connection at a time.

  • After sending, use dblink_is_busy to check the query status and dblink_get_result to collect results.

  • To cancel an active async query, use dblink_cancel_query.

  • dblink_send_query combined with dblink_get_result buffers the entire remote result set locally before returning rows. For large result sets, use dblink_open with a cursor to fetch rows in batches and avoid memory bloat. Alternatively, use dblink() directly, which avoids the memory bloat caused by spooling large result sets to disk.

Example

SELECT dblink_send_query('dtest1', 'SELECT * FROM foo WHERE f1 < 3');

dblink_is_busy

Checks whether a named connection has an active asynchronous query.

Syntax

dblink_is_busy(text connname) returns int

Parameters

Parameter Description
connname Name of the connection to check.

Return value

Returns 1 if the connection is busy with an async query. Returns 0 if it is not busy — at which point calling dblink_get_result will not block.

Example

SELECT dblink_is_busy('dtest1');

dblink_get_result

Collects the result of an asynchronous query sent by dblink_send_query. Blocks until the query completes if it has not finished yet.

Syntax

dblink_get_result(text connname [, bool fail_on_error]) returns setof record

Parameters

Parameter Description
connname Name of the connection on which the async query was sent.
fail_on_error Default: true. When true, remote errors raise a local error. When false, remote errors issue a NOTICE and return no rows.

Return value

  • For queries that return rows: returns a set of records. Declare column names and types in the FROM clause, the same as with dblink.

  • For commands that do not return rows: returns a single row with one text column containing the command status string. Declare the result as (status text) in the FROM clause.

Call dblink_get_result once for each query sent. After all results are consumed, call it once more to get the empty-set result — this clears the connection for reuse.

Example

SELECT dblink_connect('dtest1', 'dbname=contrib_regression');

-- Send an async query
SELECT * FROM dblink_send_query('dtest1', 'select * from foo where f1 < 3') AS t1;
 t1
----
  1
(1 row)

-- Collect results
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)

-- Consume the empty-set result to release the connection
SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
 f1 | f2 | f3
----+----+----
(0 rows)

-- Send a query with two result sets
SELECT * FROM dblink_send_query('dtest1', 'select * from foo where f1 < 3; select * from foo where f1 > 6') AS t1;

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)

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)

SELECT * FROM dblink_get_result('dtest1') AS t1(f1 int, f2 text, f3 text[]);
 f1 | f2 | f3
----+----+----
(0 rows)

dblink_cancel_query

Cancels the active query on a named connection.

Syntax

dblink_cancel_query(text connname) returns text

Parameters

Parameter Description
connname Name of the connection on which to cancel the active query.

Return value

Returns OK if the cancel request was sent. Returns an error message string otherwise.

Cancellation is best-effort — a query that has already completed cannot be canceled. After calling dblink_cancel_query, you must still call dblink_get_result to complete the query protocol and release the connection.

Example

SELECT dblink_cancel_query('dtest1');