I have a view as a union of several external tables (postgres_fdw). When selected in this view, some of the external servers may be unavailable (there is no network connection), and the select raise an error. Is it possible to ignore such errors and return only data from available tables?
Question posted in PostgreSQL
The official documentation can be found here.
The official documentation can be found here.
2
Answers
There isn’t a mechanism that would allow a view to ignore missing foreign tables using pure SQL. Conceptually, foreign tables that are inaccessible due to network connection issues aren’t any different than tables that can’t be accessed because the storage they are on is unavailable. Silently ignoring inaccessible tables seems illogical. How would one know that data is missing? A lack of data because tables are empty isn’t the same as a lack of data due to tables being unavailable.
If you insist on silently ignoring unavailable tables, then you could create table functions that return the results of querying the foreign tables or empty result sets when exceptions occur. Your view could then use the results of these functions instead of directly querying the foreign tables. Just because one can do this, doesn’t mean that one should.
You could try a function or stored procedure with error handling, along these lines:
Note as I have no idea what your current view query looks like, I have allowed for both multiple tables and different column names sequences per table which are passed into that function as an array of arrays:
see unit test: https://dbfiddle.uk/yBRur0Jr (Postgres 15)
nb: Using a procedure may suit better if data volumes are very large.