From b9a9aa66195dbc7cedddcde5fbae792dcfd691b3 Mon Sep 17 00:00:00 2001 From: Ayush Tiwari Date: Wed, 2 Dec 2026 05:11:42 +0000 Subject: [PATCH v2] postgres_fdw: Validate remote query result shapes Require at least one row and exactly one column in remote EXPLAIN results before reading the first plan line. Require all eight columns in IMPORT FOREIGN SCHEMA results, while allowing a result with no rows. Report unexpected result shapes as errors instead of crashing the backend. Author: Ayush Tiwari Reviewed-by: Corey Huinker Reviewed-by: Fujii Masao Discussion: https://postgr.es/m/CAJTYsWUHPUhbQLBH0iyo4cviNOD8sJ5hh9bBrJUyU04DAN741Q@mail.gmail.com Backpatch-through: 15 --- contrib/postgres_fdw/postgres_fdw.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c index ccc97d53286..9b60cd4e71c 100644 --- a/contrib/postgres_fdw/postgres_fdw.c +++ b/contrib/postgres_fdw/postgres_fdw.c @@ -3939,6 +3939,9 @@ get_remote_estimate(const char *sql, PGconn *conn, if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, sql); + if (PQntuples(res) < 1 || PQnfields(res) != 1) + elog(ERROR, "unexpected result from remote EXPLAIN command"); + /* * Extract cost numbers for topmost plan node. Note we search for a left * paren from the end of the line to avoid being confused by other uses of @@ -6695,6 +6698,10 @@ postgresImportForeignSchema(ImportForeignSchemaStmt *stmt, Oid serverOid) if (PQresultStatus(res) != PGRES_TUPLES_OK) pgfdw_report_error(res, conn, buf.data); + /* The query always returns eight columns, using NULLs as needed. */ + if (PQnfields(res) != 8) + elog(ERROR, "unexpected result from remote schema import query"); + /* Process results */ numrows = PQntuples(res); /* note: incrementation of i happens in inner loop's while() test */ -- 2.43.0