外部数据封装器(Foreign Data Wrapper,FDW) 是 PostgreSQL 等数据库中用于访问外部数据源(如其他数据库、文件、API、大数据系统等)的机制。通过 FDW,你可以像查询本地表一样查询外部数据。
下面以 PostgreSQL FDW 为例,系统说明如何使用。
| 概念 | 说明 |
|---|---|
| Foreign Data Wrapper | 访问外部数据的“驱动”(如 postgres_fdw、mysql_fdw) |
| Foreign Server | 外部数据源的连接定义 |
| User Mapping | 本地用户 ↔ 外部用户 的映射 |
| Foreign Table | 外部数据在本地“虚拟”的表 |
CREATE EXTENSION postgres_fdw;
不同数据源使用不同扩展,如:
mysql_fdwfile_fdwmongo_fdw
CREATE FOREIGN DATA WRAPPER fdw_name
HANDLER handler_function
VALIDATOR validator_function;
使用官方扩展时一般不用写
CREATE SERVER remote_pg
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (
host '192.168.1.10',
port '5432',
dbname 'remote_db'
);
CREATE USER MAPPING FOR current_user
SERVER remote_pg
OPTIONS (
user 'remote_user',
password 'remote_password'
);
CREATE FOREIGN TABLE foreign_orders (
id int,
amount numeric,
created_at timestamp
)
SERVER remote_pg
OPTIONS (
schema_name 'public',
table_name 'orders'
);
SELECT * FROM foreign_orders WHERE amount > 100;
CREATE EXTENSION postgres_fdw;
CREATE EXTENSION file_fdw;
CREATE SERVER file_server
FOREIGN DATA WRAPPER file_fdw;
CREATE FOREIGN TABLE csv_data (
id int,
name text
)
SERVER file_server
OPTIONS (
filename '/data/test.csv',
format 'csv',
header 'true'
);
✅ 优点
⚠️ 注意
如果你有 具体数据库类型或场景(如 MySQL、Oracle、API、Hive),我可以给你更针对性的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。