dblink
dblink — executes a query in a remote database
Synopsis
Description
dblink
executes a query (usually aSELECT
, but it can be any SQL statement that returns rows) in a remote database.
When twotext
arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as fordblink_connect
, and the indicated connection is made just for the duration of this command.
Arguments
connname
Name of the connection to use; omit this parameter to use the unnamed connection.
connstr
A connection info string, as previously described fordblink_connect
.
sql
The SQL query that you wish to execute in the remote database, for exampleselect * from foo
.
fail_on_error
If true (the default when omitted) then an error thrown on the remote side of the connection causes an error to also be thrown locally. If false, the remote error is locally reported as a NOTICE, and the function returns no rows.
Return Value
The function returns the row(s) produced by the query. Sincedblink
can be used with any query, it is declared to returnrecord
, rather than specifying any particular set of columns. This means that you must specify the expected set of columns in the calling query — otherwisePostgreSQLwould not know what to expect. Here is an example:
The“alias”part of theFROM
clause must specify the column names and types that the function will return. (Specifying column names in an alias is actually standard SQL syntax, but specifying column types is aPostgreSQLextension.) This allows the system to understand what*
should expand to, and whatproname
in theWHERE
clause refers to, in advance of trying to execute the function. At run time, an error will be thrown if the actual query result from the remote database does not have the same number of columns shown in theFROM
clause. The column names need not match, however, anddblink
does not insist on exact type matches either. It will succeed so long as the returned data strings are valid input for the column type declared in theFROM
clause.
Notes
A convenient way to usedblink
with predetermined queries is to create a view. This allows the column type information to be buried in the view, instead of having to spell it out in every query. For example,
Examples
Last updated