I have several databases on the same PostgreSQL server with the exact same tables with the same columns in it. I want to write a function that a user could use to query across all these databases at once, something like:
SELECT * FROM all_databases();
For the moment, I just found how to query another database:
-- 1. Get database names
SELECT datname
FROM pg_database
WHERE name LIKE '%someString%';
-- 2. Get data from different databases with postgres_fdw (same host or remote host)
-- 2.1. Install the module
CREATE EXTENSION postgres_fdw;
-- 2.2. Create a server connection
CREATE SERVER foreign_db
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'localhost', dbname 'foreignDbName', port '5432');
-- 2.3. Create user mapping for the foreign server
CREATE USER MAPPING FOR CURRENT_USER
SERVER foreign_db
OPTIONS (user 'postgres', password 'password');
-- 2.4. Import the foreign schema
IMPORT FOREIGN SCHEMA public
FROM SERVER foreign_db INTO public;
So, what I want to do is to execute something like what is written in 2 for every result returned by 1. It looks like I will have to use some dynamic SQL, but I am a little bit lost...