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?

1

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.