3

I am using PostgreSQL 9.1. I need to transfer required columns from one table of one database into another table of another database, but not schema.
I found that dblink.sql file has to be there in share/contrib. But my contrib folder is empty. Where can I download the dblink.sql file and can execute my query?

When I execute the query now it shows an error message:

cross database reference is not possible ...

Can anyone help me how to transfer the data between two databases?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
user1915182
  • 81
  • 2
  • 4
  • possible duplicate of [How to use (install) dblink in postgresql?](http://stackoverflow.com/questions/3862648/how-to-use-install-dblink-in-postgresql) – Erwin Brandstetter Feb 10 '13 at 11:47

1 Answers1

8

After you have installed the package into your system as detailed in the related question install the extension dblink into your database (the one you are running this code in, the foreign db does not need it):

CREATE EXTENSION dblink;

You can find code examples in the manual.
Here is a simple version of what I use to copy data between dbs: First, create a FOREIGN SERVER

CREATE SERVER mydb
FOREIGN DATA WRAPPER postgresql
OPTIONS (hostaddr '111.111.111.111',port '5432',dbname 'mydb');

FOREIGN DATA WRAPPER postgresql was pre-installed in my case.
Then create function that opens a connection, removes old data (opotional), fetches new data, runs ANALYZE and closes the connection:

CREATE OR REPLACE FUNCTION f_tbl_sync()
  RETURNS text AS
$BODY$
SELECT dblink_connect('mydb');  -- USER MAPPING for postgres, PW in .pgpass

TRUNCATE tbl;  -- optional

INSERT INTO tbl
SELECT * FROM dblink(
  'SELECT tbl_id, x, y
   FROM   tbl
   ORDER  BY tbl_id')
    AS b(
 tbl_id int
,x int
,y int)

ANALYZE tbl;

SELECT dblink_disconnect();
$BODY$
  LANGUAGE sql VOLATILE;
Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228