postgres_fdw模块使数据库可以访问远程数据库中数据,其功能类似大家熟悉的dblink,但是postgres_fdw它以一种更现代和更加兼容标准的架构提供了相同的功能。
postgres_fdw使用起来也比较方便,大致有以下几步:
- 使用CREATE EXTENSION来安装postgres_fdw扩展。
- 使用CREATE SERVER创建一个外部服务器对象,它用来表示你想连接的每一个远程数据
库。指定除了user和password之外的连接信息作为该服务器对象的选项。 - 使用CREATE USER MAPPING创建一个用户映射,每一个用户映射都代表你想允许一个
数据库用户访问一个外部服务器。指定远程用户名和口令作为用户映射
的user和password选项。 - 为每一个你想访问的远程表使用CREATE FOREIGN TABLE或者IMPORT FOREIGN
SCHEMA创建一个外部表。外部表的列必须匹配被引用的远程表。但是,如果你在外部 表对象的选项中指定了正确的远程名称,你可以使用不同于远程表的表名和/或列名。
例如:
1、安装postgres_fdw扩展
bill=# create extension postgres_fdw ;
2、CREATE SERVER
bill=# create server fdw_server1
bill-# foreign data wrapper postgres_fdw
bill-# options
bill-# (host'192.168.xxx.xxx',port'1921',dbname'bill');
CREATE SERVER
3、CREATE USER MAPPING
bill=# create user MAPPING FOR bill
server fdw_server1
options (user'bill',password'xxx');
CREATE USER MAPPING
4、创建FOREIGN TABLE
bill=# create foreign table fdw_t1(
id int ,
info text)
server fdw_server1
options(schema_name'public',table_name't2');
CREATE FOREIGN TABLE
需要注意的是t2原先远程服务器上就已经查创建了的表。
5、验证
–在本地查询fdw_t1
bill=# select * from fdw_t1 ;
id | info
----+-------------
1 | -510270801
2 | -1770425015
3 | 8545603
4 | -70337263
5 | 50968907
6 | 1473976499
7 | -374757108
8 | 1950069046
9 | 666989090
10 | 696624195
(10 rows)
–远程服务器查询t2
bill=# select * from t2;
id | info
----+-------------
1 | -510270801
2 | -1770425015
3 | 8545603
4 | -70337263
5 | 50968907
6 | 1473976499
7 | -374757108
8 | 1950069046
9 | 666989090
10 | 696624195
(10 rows)
同样,也可以对表进行增删改查等操作,也会同步到t2上,但是不能对foreign table进行drop、truncate等操作,否则会报错:
bill=# truncate fdw_t1;
ERROR: "fdw_t1" is not a table
bill=# drop table fdw_t1;
ERROR: "fdw_t1" is not a table
HINT: Use DROP FOREIGN TABLE to remove a foreign table.
还有个有意思的是:尽管我们可以对foreign table进行add column之类的操作,但是不会同步到远程服务器上的表,同时再查询foreign table会报错!
bill=# alter foreign table fdw_t1 add column c3 integer;
ALTER FOREIGN TABLE
bill=# \d fdw_t1
Foreign table "public.fdw_t1"
Column | Type | Collation | Nullable | Default | FDW options
--------+---------+-----------+----------+---------+-------------
id | integer | | | |
info | text | | | |
c3 | integer | | | |
Server: fdw_server1
FDW options: (schema_name 'public', table_name 't2')
bill=# select * from fdw_t1 ;
ERROR: column "c3" does not exist
CONTEXT: remote SQL command: SELECT id, info, c3 FROM public.t2