PostgreSQL – Using Foreign Data Wrapper for Query-Based Tables

postgresql

I have a db with sensitive data in a secure server, and a set of anonymization queries that I'd like to create foreign tables based on in a less secure server.

The Postgres native wrapper only enables you to create foreign tables directly mapped to tables in the source db, but it seems there are other wrappers which allow you to base the foreign tables based on queries.

Are there any foreign data wrappers for Postgres to Postgres porting that let you do this? Ideally it'd be like so:

create foreign table foreign_table (id integer)
  server foreign_server
  options (query 'some query')

Best Answer

To do what you need to do, you should be able to create a view on your secure server and reference that as the table in your less secure server, like this:

On the secure server:

CREATE OR REPLACE VIEW redacted_view AS SELECT col1, col2 FROM sensitive_table;

On the less secure server:

CREATE FOREIGN TABLE sensitive_table (col1 int, col2 int)
     SERVER foreign_server
     OPTIONS (table_name, 'redacted_view');

It's not your ideal scenario, but from what you're describing it should work. Hope that helps. =)