1 實驗環境
- 兩個數據庫節點:node1, node2,使用postgresql 11.3
- node1是主節點,供客戶端(psql)訪問;node2是外節點,由node1直接訪問。
1.1 node1
- hostname=node1
- port=5432
- 應用程序(psql)訪問該節點
- table:'test1',外表,指向node2的表’test2‘
- user: 'user1'
1.2 node2
- hostname=node2
- port=5432
- node1訪問該節點
- table:'test2',本地表
- user: 'user2'
2 配置node2
psql -h node2 -d postgres
2.1 建立表,添加數據
create table test2( id int, name varchar(100));
insert into test2 values (generate_series(1,10), md5(random()::text));
2.2 建立用戶,授予權限
create role user2 with login password 'ks839#@s';
grant select, insert, update, delete on test2 to user2;
3 配置node1
psql -h node1 -d postgres
3.1 建立帳號
create role user1 with login password '56ak!@#$';
3.2 建立fdw擴展
create extension postgres_fdw;
3.3 建立外表,授予權限
create server fnode2
foreign data wrapper postgres_fdw
options (host 'node2', port '6432', dbname 'postgres');
create user mapping for user1
server fnode2
options (user 'user2', password 'ks839#@s');
create foreign table test1 (
id int,
name varchar(100)
)
server fnode2
options (schema_name 'public', table_name 'test2');
grant select, insert, update, delete on test1 to user1;
4 在node1上對外表執行讀寫
psql -h node1 -Uuser1 -d postgres
select * from test1;
insert into test1 values (100,'100');
select * from test1 where id=100;
update test1 set id=200 where id=100;
select * from test1 where id=200;
delete from test1 where id=200;