5

通过postgres_fdw实现跨库访问

 1 year ago
source link: https://blog.51cto.com/u_13646489/5913093
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

通过postgres_fdw实现跨库访问

精选 原创

瀚高数据库

介绍 Postgresql 跨库访问中 postgres_fdw 的使用方法

PostgreSQL 外部数据包装器,即 PostgreSQL Foreign Data Wrappers,是现实数据库使用场景中一个非常实用的功能,PostgreSQL 的 FDW 类似于 Oracle 的 dblink,DB2 的 Federation,使用其可以将本地数据库与外部数据库建立连接,从而可以像操作本地数据一样来操作外部数据。

postgrs_fdw 是 PostgreSQL 外部数据包装器中的一种,可用于访问储存在外部 postgresql 数据库的数据。

使用步骤如下:

1、使用 CREATE EXTENSION 来安装 postgres_fdw 扩展。

2、使用 CREATE SERVER 创建一个外部服务器对象,它用来表示你想连接的每一个远程数据库。指定除了 user 和 password 之外的连接信息作为该服务器对象的选项。

3、使用 CREATE USER MAPPING 创建一个用户映射,每一个用户映射都代表你想允许一个数据库用户访问一个外部服务器。指定远程用户名和口令作为用户映射的 user 和 password 选项。

4、为每一个你想访问的远程表使用 CREATE FOREIGN TABLE 或者 IMPORT FOREIGN SCHEMA 创建一个外部表。外部表的列必须匹配被引用的远程表。但是,如果你在外部表对象的选项中指定了正确的远程名称,你可以使用不同于远程表的表名和 / 或列名。

1、在数据库 A 创建测试表添加测试数据。

create table table1 (id int, crt_Time timestamp, info text, c1 int);
通过postgres_fdw实现跨库访问_服务器
insert into table1 select generate_series(1,1000000), clock_timestamp(), md5(random()::text), random()*1000;

通过postgres_fdw实现跨库访问_服务器_02

查看插入数据量

通过postgres_fdw实现跨库访问_数据库_03

2、数据库 B 查看表并创建扩展

通过postgres_fdw实现跨库访问_服务器_04

通过postgres_fdw实现跨库访问_数据库_05

查看扩展创建情况

通过postgres_fdw实现跨库访问_PostgreSQL_06

3、通过 fdw 创建外联服务

CREATE SERVER table1

FOREIGN DATA WRAPPER postgres_fdw

OPTIONS (host '192.168.80.131', port '5432', dbname 'postgres');

通过postgres_fdw实现跨库访问_服务器_07

4、创建外联用户信息

CREATE USER MAPPING FOR postgres

SERVER table1

OPTIONS (user 'postgres', password 'highgo@123');

通过postgres_fdw实现跨库访问_数据库_08

5、查看外联服务

通过postgres_fdw实现跨库访问_PostgreSQL_09

6、将数据库 A 模式中的所有表在数据库 B 中创建外联表

通过postgres_fdw实现跨库访问_服务器_10

查看数据库 B 的外联表

通过postgres_fdw实现跨库访问_数据库_11
通过postgres_fdw实现跨库访问_数据库_12

7、创建单个外联表

CREATE FOREIGN TABLE table2 (

id int, crt_Time timestamp, info text, c1 int)

SERVER table1

OPTIONS (schema_name 'public', table_name 'table1');
通过postgres_fdw实现跨库访问_数据库_13

查看数据库 B 的外联表

通过postgres_fdw实现跨库访问_PostgreSQL_14
通过postgres_fdw实现跨库访问_服务器_15

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK