From b4933ee484d71bd90c96cc0cafabbc2529be4ea3 Mon Sep 17 00:00:00 2001
From: amitlan <amitlangote09@gmail.com>
Date: Mon, 19 Oct 2020 17:17:33 +0900
Subject: [PATCH v1 2/3] Initialize ForeignScanState.resultRelInfo in
 ExecForeignScan()

An upcoming patch will make the initialization of the individual
elements of es_result_relations[] to be delayed until the ModifyTable
node, from where the result relations come from, actually begins
executing.  To allow that, initialize ForeignScanState.resultRelInfo
in ExecForeignScan instead of in ExecInitForeignScan(), because
child result relations' ResultRelInfos are now not available during
the latter.
---
 contrib/postgres_fdw/postgres_fdw.c    |  2 +-
 src/backend/executor/nodeForeignscan.c | 19 ++++++++++++-------
 2 files changed, 13 insertions(+), 8 deletions(-)

diff --git a/contrib/postgres_fdw/postgres_fdw.c b/contrib/postgres_fdw/postgres_fdw.c
index 9c5aaac..523ffac 100644
--- a/contrib/postgres_fdw/postgres_fdw.c
+++ b/contrib/postgres_fdw/postgres_fdw.c
@@ -2357,7 +2357,7 @@ postgresBeginDirectModify(ForeignScanState *node, int eflags)
 	 * Identify which user to do the remote access as.  This should match what
 	 * ExecCheckRTEPerms() does.
 	 */
-	rtindex = node->resultRelInfo->ri_RangeTableIndex;
+	rtindex = fsplan->resultRelation;
 	rte = exec_rt_fetch(rtindex, estate);
 	userid = rte->checkAsUser ? rte->checkAsUser : GetUserId();
 
diff --git a/src/backend/executor/nodeForeignscan.c b/src/backend/executor/nodeForeignscan.c
index 0b20f94..503ef8b 100644
--- a/src/backend/executor/nodeForeignscan.c
+++ b/src/backend/executor/nodeForeignscan.c
@@ -111,6 +111,18 @@ static TupleTableSlot *
 ExecForeignScan(PlanState *pstate)
 {
 	ForeignScanState *node = castNode(ForeignScanState, pstate);
+	ForeignScan *plan = (ForeignScan *) node->ss.ps.plan;
+
+	/*
+	 * For the FDW's convenience, look up the modification target relation's
+	 * ResultRelInfo.
+	 */
+	if (plan->resultRelation > 0 && node->resultRelInfo == NULL)
+	{
+		EState   *estate = node->ss.ps.state;
+
+		node->resultRelInfo = estate->es_result_relations[plan->resultRelation - 1];
+	}
 
 	return ExecScan(&node->ss,
 					(ExecScanAccessMtd) ForeignNext,
@@ -215,13 +227,6 @@ ExecInitForeignScan(ForeignScan *node, EState *estate, int eflags)
 	scanstate->fdwroutine = fdwroutine;
 	scanstate->fdw_state = NULL;
 
-	/*
-	 * For the FDW's convenience, look up the modification target relation's.
-	 * ResultRelInfo.
-	 */
-	if (node->resultRelation > 0)
-		scanstate->resultRelInfo = estate->es_result_relations[node->resultRelation - 1];
-
 	/* Initialize any outer plan. */
 	if (outerPlan(node))
 		outerPlanState(scanstate) =
-- 
1.8.3.1

