6

I want to you table which is located in the other database.

I am using the dblink for this.

Procedure:

Step 1: Created extension.

CREATE EXTENSION dblink;

Step 2: Making dblink connection string.

select dblink_connect('con','host=127.0.0.1 dbname=makdb user=postgres password=postgres');

Step 3:

select * from dblink('con','select cola,colb from tbl_test') as tbl(cola int,colb varchar(10));

My Question: How do i hide password in step 2?

By searching i came to know that i need to create .pgpass file. But got stuck in how to create and in which step i need to use that file name.

MAK
  • 6,824
  • 25
  • 74
  • 131
  • 3
    You may want to have a look to FDW (https://www.postgresql.org/docs/current/static/postgres-fdw.html) instead of dblink. In the former you only have to specify the password once, which a trusted user can do from a secure terminal. Then you can allow users from a given role to use it. – Fabian Pijcke Jan 05 '17 at 13:34
  • 3
    The `.pgpass` file must be created on the server where Postgres is running **and** must be in the `$HOME` directory of the operating system user under which Postgres is started (typically `postgres` on Linux). –  Jan 05 '17 at 13:55
  • Check this discussion https://stackoverflow.com/q/44663478/2160152 – cheffe Jan 31 '19 at 11:05

1 Answers1

4

Install dblink extension:

CREATE EXTENSION dblink;

Install postgres_fdw extension (which can be used to access data stored in external PostgreSQL servers):

CREATE EXTENSION postgres_fdw;

Create a new foreign server connection:

CREATE server myserver foreign data wrapper postgres_fdw
OPTIONS (dbname 'foreign_dbname', host 'foreign_host');

Create a user mapping for the foreign server connection that you recently created and your database.

CREATE USER MAPPING FOR "user_in_current_database"
SERVER myserver OPTIONS (user 'foreign_user', password 'foreign_password');

Select some fields in a remote db with the conexion created. Notice that you does not need use the user and password anyrmore.

SELECT tmp_table.*
FROM dblink(
             'myserver',
             '
             SELECT field1,
                 field2
             FROM table
             '
         )
         AS tmp_table(
                      field1 TEXT,
                      field2 BIGINT
        );

More info:

https://www.postgresql.org/docs/9.5/postgres-fdw.html

https://www.postgresql.org/docs/current/sql-createserver.html

https://www.postgresql.org/docs/current/sql-createusermapping.html

alvaro nortes
  • 570
  • 4
  • 10