Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL 9.5: Hide password from dblink connection

Tags:

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.

like image 279
MAK Avatar asked Jan 05 '17 13:01

MAK


1 Answers

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

like image 109
alvaro nortes Avatar answered Sep 21 '22 10:09

alvaro nortes