我在 postgresql 数据库服务器中有多个数据库
每个数据库都有自己的用户名/密码,并且只能通过指定模式访问(实际上,模式与用户名相同)
我想创建一个 all_tables 视图,以便稍后进行查询。
我对
dblink
扩展做了一些研究,但仍然无法使其工作。
SELECT dblink_connect('source_db_1', 'postgres://db_1:[email protected]/db_1?sslmode=require');
CREATE SERVER source_db_1 FOREIGN DATA WRAPPER dblink_fdw OPTIONS (hostaddr 'psqlserver.postgres.database.azure.com', dbname 'db_1');
CREATE USER MAPPING FOR current_user SERVER source_db_1 OPTIONS (user 'db_1', password 'password');
SELECT dblink_connect('source_db_2', 'postgres://db_2:[email protected]/db_2?sslmode=require');
CREATE SERVER source_db_2 FOREIGN DATA WRAPPER dblink_fdw OPTIONS (hostaddr 'psqlserver.postgres.database.azure.com', dbname 'db_2');
CREATE USER MAPPING FOR current_user SERVER source_db_2 OPTIONS (user 'db_2', password 'password');
CREATE OR REPLACE VIEW all_tables_in_db_1 AS
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'db_1';
CREATE OR REPLACE VIEW all_tables_in_db_2 AS
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'db_2';
CREATE OR REPLACE VIEW all_tables_in_db_3 AS
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'db_3';
CREATE OR REPLACE VIEW all_tables AS
SELECT * FROM all_tables_in_db_1
UNION ALL
SELECT * FROM all_tables_in_db_2
UNION ALL
SELECT * FROM all_tables_in_db_3;
所有命令都运行良好,但是在
all_tables
中查询时,没有任何表
dblink_fdw
可以,但建议您使用原生 postgres_fdw
来代替。dblink_connect
并设置 server
和 user mapping
。您使用前者来管理连接以调用 dblink_execute
,后者用于设置外部数据包装器,然后使用它们的 foreign table
。information_schema
。您可以通过 dblink_exec
运行查询并处理其输出,或者同时为多个表设置 foreign table
或 import foreign schema
。以下示例展示了如何设置
information_schema.tables
但适用于多个数据库:demo
create extension postgres_fdw;
CREATE SERVER foreign_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (dbname 'template1');
CREATE USER MAPPING FOR current_user
SERVER foreign_server
OPTIONS (user 'postgres');
CREATE FOREIGN TABLE db_2_information_schema_tables (
table_catalog text, table_schema text, table_name text, table_type text, self_referencing_column_name text, reference_generation text, user_defined_type_catalog text, user_defined_type_schema text, user_defined_type_name text, is_insertable_into text, is_typed text, commit_action text)
SERVER foreign_server
OPTIONS (schema_name 'information_schema',
table_name 'tables');
create materialized view mv_pg_all_tables
as select 'local' as dbname, * from information_schema.tables
union all
select 'db_2', * from db_2_information_schema_tables;