From 6f952ead63241b2a89df0c87255b3361b50af420 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Thu, 26 Nov 2026 15:45:20 +0000
Subject: [PATCH v1] postgres_fdw: Validate remote query result shapes

Require at least one row and 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.

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..dae4d890cca 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

