首页 > 解决方案 > 如果外部数据库在同一台服务器中,我可以简化 postgres_fdw 的使用吗

问题描述

我的服务器有几个数据库。我希望能够从 db2 中的查询中读取 db1。我知道我可以使用 postgres_fdw 来做到这一点,但这有几个缺点。主要的一个是我必须传递凭据,担心我何时更改密码等。

标签: postgresqlpostgres-fdwpg-hba.conf

解决方案


所以你设置服务器、用户映射和创建表:

t=# create server l foreign data wrapper postgres_fdw options (host 'localhost', dbname 't');
CREATE SERVER
t=# create user mapping FOR postgres SERVER l;
CREATE USER MAPPING
t=# create table lt(i serial);
CREATE TABLE
t=# insert into lt default values;
INSERT 0 1
t=# create foreign table ft (i int) server l options(table_name 'lt') ;
CREATE FOREIGN TABLE
t=# select * from ft;
 i
---
 1
(1 row)

现在如果我在信任本地默认连接之前将 md5 添加到 hba,我得到:

t=# select * from ft;
ERROR:  could not connect to server "l"
DETAIL:  fe_sendauth: no password supplied

并恢复:

t=# \! sed -i '43s/host/#host/' /pg/d10/pg_hba.conf
t=# select pg_reload_conf();
 pg_reload_conf
----------------
 t
(1 row)

t=# select * from ft;
 i
---
 1
(1 row)

而这条线是:

t=# \! sed '43,43!d' /pg/d10/pg_hba.conf
#host   all     postgres    127.0.0.1/32        md5

所以我的观点是:如果你有本地数据库,默认情况下你不需要操作密码,因为你对 localhost 有对等或信任......

更新 ,以便在没有密码的情况下在 localhost 上为您需要的某些用户使用密码,例如:

host    fdw_db      postgres    127.0.0.1/32        trust

走在这条线之前:

host    all     all 127.0.0.1/32        md5

或任何其他限制或拒绝连接的线路

https://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html

由于每次连接尝试都会按顺序检查 pg_hba.conf 记录,因此记录的顺序很重要。通常,较早的记录将具有紧密的连接匹配参数和较弱的身份验证方法,而较晚的记录将具有较宽松的匹配参数和更强的身份验证方法。例如,可能希望对本地 TCP/IP 连接使用信任身份验证,但对远程 TCP/IP 连接需要密码。在这种情况下,为来自 127.0.0.1 的连接指定信任身份验证的记录将出现在为更广泛的允许客户端 IP 地址指定密码身份验证的记录之前。


推荐阅读