PostgreSQL 中的postgres_fdw扩展详情

这篇文章主要介绍了PostgreSQL 中的postgres_fdw扩展详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧。
 
通过postgres_fdw 扩展,访问远程数据库表
 
一、环境准备
 
虚拟机(node107):centos7、PostgreSQL10
 
远程服务器(百度云服务BBC): centos7、PostgreSQL10
 
在本地虚拟机上访问远程服务器的数据表。
 
二、配置连接
 
(1)创建扩展: 在本地107这个节点上创建扩展。
 
[root@107 ~]# su postgre
su: user postgre does not exist
[root@107 ~]# su postgres
bash-4.2$ psql mydb postgres
could not change directory to "/root": 权限不够
psql (10.7)
Type "help" for help.
 
mydb=# CREATE EXTENSION postgres_fdw;
CREATE EXTENSION
 
 
 
如果是普通用户使用 ·postgres_fdw 需要单独授权
 
grant usage on foreign data wrapper postgres_fdw to 用户名
 
(2) 创建 foreign server 外部服务器,外部服务是指连接外部数据源的连接信息
 
mydb=# create server fs_postgres_bbc
foreign data wrapper postgres_fdw options(host '182.61.136.109',port '5432',dbname 'technology');
mydb=#
 
 
 
定义名称为 fs_postgres_bbc的外部服务,options 设置远程PostgreSQL数据源连接选项,通常设置主机名、端口、数据库名称。
 
(3)需要给外部服务创建映射用户
 
mydb=# create user mapping for postgres server
fs_postgres_bbc options(user 'postgres',password 'password');
CREATE USER MAPPING
mydb=#
 
 
 
for 后面接的是 node107 的数据库用户,options 里接的是远程PostgreSQL数据库的用户和密码。password 注意修改成自己的
 
其实想访问远程数据库,无非就是知道连接信息。包括host、port、dbname、user、password
 
(4)BBC上准备数据。
 
technology=# select * from public.customers where id < 5;
 id | name
—-+——-
 1 | name1
 2 | name2
 3 | name3
 4 | name4
(4 rows)
 
technology=#
— schemaname = public
 
 
 
(5) 在node107上创建外部表:
 
mydb=# create foreign table ft_customers
(
 id int4 primary key ,
 name varchar(200)
 ) server fs_postgres_bbc options (schema_name 'public',table_name 'customers');
 
 
 
错误: 外部表上不支持主键约束
 
第1行create foreign table ft_customers (id int4 primary key , nam…
            ^
mydb=#
 
 
 
错误: 外部表上不支持主键约束
 
第1行create foreign table ft_customers (id int4 primary key , nam… ^mydb=#
 
可以看见,外部表不支持主键约束。想想也是合理
 
mydb=# create foreign table ft_customers (
 id int4 ,
 name varchar(200)
) server fs_postgres_bbc options (schema_name 'public',table_name 'customers');
CREATE FOREIGN TABLE
mydb=#
 
 
 
options 选项中: 需要指定外部表的schema和表名
 
(6)在node107上去访问远程BBC的数据
 
mydb=# select * from ft_customers where id < 5;
 id | name
—-+——-
 1 | name1
 2 | name2
 3 | name3
 4 | name4
(4 rows)
 
mydb=#
 
 
 
可以看见在mydb上能够访问远程数据库上 的数据了。
 
如果出现报错,如报pg_hba.conf 文件没有访问策略,在需要在对修改配置文件。
 
(7)本地数据库表与远程数据库表进行进行关联查询
 
create table orders (
 id int PRIMARY KEY,
 customerid int
);
 
INSERT INTO orders(id,customerid) VALUES(1,1),(2,2);
 
SELECT * FROM orders;
 
— 和外部表关联查询。
mydb=# SELECT o.*,c.*
mydb-# FROM orders o
mydb-# INNER JOIN ft_customers c ON o.customerid = c.id
mydb-# WHERE c.id < 10000;
 id | customerid | id | name
—-+————+—-+——-
 1 |   1 | 1 | name1
 2 |   2 | 2 | name2
(2 rows)
 
mydb=#
【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章