Cross database query using dblink

Deadly 提交于 2021-02-10 17:44:38

问题


I'd like to use dblink in postgres to copy data from a local database to a remote one. This what I came up with:

SELECT * FROM dblink('archive', 'INSERT INTO data SELECT * FROM local.data')

It wont work and I think I understand why. I get the error relation "local.data" does not exist, If possible, Id like to run this inside a stored procedure on the local database, in other words I want to push the data to the 'archive' server, rather than pull it to the 'archive'.

How can I tell postgres to look in the local database? How can I address the local database from inside the dblink query?


回答1:


I couldn't find a way to do this through dblink, but was able to do it using postgres_fwd. I had to create a foreign table first associated with the table I want to insert into.

CREATE EXTENSION postgres_fdw;
CREATE SERVER archive FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost',  dbname 'archive_db');
CREATE USER MAPPING FOR CURRENT_USER SERVER archive OPTIONS (user 'user', password 'pass');
CREATE FOREIGN TABLE archivedata (..) SERVER archive OPTIONS (schema_name 'public', table_name 'data');

INSERT INTO archivedata SELECT * FROM data;



回答2:


To copy rows from local database to remote database you should run the insert statement on remote host and make the search on local host. the syntax is this:

INSERT INTO t1(id, name, description, "date")
    SELECT id_foo, full_name, des, "date" FROM 
    dblink('host= ? user= ? password= ? dbname= externaldb'::text,
    'SELECT id, name, description, "date" FROM t2'::text, false)
    ttemp(id integer, name character varying,  description character varying, "date" date)
)

Change the ? for the local information.



来源:https://stackoverflow.com/questions/49263100/cross-database-query-using-dblink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!