skytf=# /dx List of installed extensions Name | Version | Schema | Description -----------+---------+------------+---------------------------------------------------- file_fdw | 1.0 | public | foreign-data wrapper for flat file access mysql_fdw | 1.0 | public | Foreign data wrapper for querying a MySQL server pgsql_fdw | 1.0 | public | foreign-data wrapper for remote PostgreSQL servers plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language (4 rows)
备注: pgsql_fdw 已创建。
2.2 创建 server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
skytf=# grant usage on foreign data wrapper pgsql_fdw to skytf; GRANT
skytf=# /c skytf skytf You are now connected to database "skytf" as user "skytf".
CREATE SERVER pgsql_srv FOREIGN DATA WRAPPER pgsql_fdw OPTIONS (host '127.0.0.1', port '1923', dbname 'mydb');
skytf=> /des List of foreign servers Name | Owner | Foreign-data wrapper --------------+-------+---------------------- file_srv | skytf | file_fdw mysql_svr_25 | skytf | mysql_fdw pgsql_srv | skytf | pgsql_fdw (3 rows)
skytf=> CREATE FOREIGN TABLE ft_test ( skytf(> id integer , skytf(> name character varying(32) ) skytf-> SERVER pgsql_srv skytf-> OPTIONS (nspname 'mydb', relname 'test'); CREATE FOREIGN TABLE
2.5 查询测试
1 2 3 4 5
skytf=> select * from ft_test limit1; id | name ------+------ 5024 | AAAA (1 row)
2.6 执行计划
1 2 3 4 5 6 7 8
skytf=> explain analyze select * from ft_test where id=1; QUERY PLAN ------------------------------------------------------------------------------------------------------------ Foreign Scan on ft_test (cost=100.00..111.46 rows=2 width=8) (actual time=2.190..2.190 rows=0 loops=1) Filter: (id = 1) Remote SQL: DECLARE pgsql_fdw_cursor_10 SCROLL CURSOR FOR SELECT id, name FROM mydb.test WHERE (id = 1) Total runtime: 3.092 ms (4 rows)
[postgres@pgb ~]$ psql skytf skytf psql (9.1.0) Type "help"for help.
skytf=> select * from ft_test limit 1; ERROR: password is required DETAIL: Non-superuser cannot connect if the server does not request a password. HINT: Target server is authentication method must be changed.
备注:上面报错是因为 pg_hba.conf 文件认证问题,本机配置的是 local 连接所有库都是 trust 方式,即不需要密码,而 pgsql_fdw 连接时需要提供用户名和密码。