In Postgres, you can link to your other databases using dblink
like so:
SELECT *
FROM dblink (
'dbname=name port=1234 host=host user=user password=password',
'select * from table'
) AS users([insert each column name and its type here]);
But this is quite verbose.
I've shortened it up by using dblink_connect
and dblink_disconnect
to abstract the connection string from my dblink
queries. However, that still leaves me with the manual table definition (i.e., [insert each column name and its type here]
).
Instead of defining the table manually, is there a way I can define it with a TYPE
or anything else that'd be re-usable?
In my case, the number of remote tables I have to join and the number of columns involved makes my query massive.
I tried something along the lines of:
SELECT *
FROM dblink (
'myconn',
'select * from table'
) AS users(postgres_pre_defined_type_here);
But I received the following error:
ERROR: a column definition list is required for functions returning "record"
Load the 'dblink' extension using 'CREATE EXTENSION' command. CREATE EXTENSION dblink; On database 'goku', create a foreign server object using the 'CREATE SERVER' command. Here, you need to enter the details of the host, the remote database you intend to connect and the port on which PostgreSQL is running.
Description. dblink executes a query (usually a SELECT , but it can be any SQL statement that returns rows) in a remote database. When two text 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.
Database Link in PostgreSQL enables a database user to access a table present on a different PostgreSQL cluster. It provides a functionality in PostgreSQL similar to that of DB Link in Oracle, Linked Server in SQL Server and Federated Table in MySQL.
As you considered creating several types for dblink, you can accept creating several functions as well. The functions will be well defined and very easy to use.
Example:
create or replace function dblink_tables()
returns table (table_schema text, table_name text)
language plpgsql
as $$
begin
return query select * from dblink (
'dbname=test password=mypassword',
'select table_schema, table_name from information_schema.tables')
as tables (table_schema text, table_name text);
end $$;
select table_name
from dblink_tables()
where table_schema = 'public'
order by 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With