From 978831a89cc1f77a2fec7ab56773e6230c9698a4 Mon Sep 17 00:00:00 2001
From: pgsql-guo <richard.guo@openpie.com>
Date: Wed, 6 Apr 2022 07:29:18 +0000
Subject: [PATCH] Include entries in WHEN conditions into processed_tlist

---
 src/backend/optimizer/prep/preptlist.c | 32 ++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)

diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c
index 99ab3d7559..f805aed73e 100644
--- a/src/backend/optimizer/prep/preptlist.c
+++ b/src/backend/optimizer/prep/preptlist.c
@@ -150,6 +150,8 @@ preprocess_targetlist(PlannerInfo *root)
 		 */
 		foreach(l, parse->mergeActionList)
 		{
+			List	    *vars;
+			ListCell    *cell;
 			MergeAction *action = (MergeAction *) lfirst(l);
 
 			if (action->commandType == CMD_INSERT)
@@ -158,6 +160,36 @@ preprocess_targetlist(PlannerInfo *root)
 			else if (action->commandType == CMD_UPDATE)
 				action->updateColnos =
 					extract_update_targetlist_colnos(action->targetList);
+
+			/*
+			 * Add resjunk entries for any Vars used in WHEN conditions if any
+			 * that belong to other relations.
+			 */
+			vars = pull_var_clause((Node *) action->qual,
+								   PVC_RECURSE_AGGREGATES |
+								   PVC_RECURSE_WINDOWFUNCS |
+								   PVC_INCLUDE_PLACEHOLDERS);
+
+			foreach(cell, vars)
+			{
+				Var		    *var = (Var *) lfirst(cell);
+				TargetEntry *tle;
+
+				if (IsA(var, Var) &&
+					var->varno == result_relation)
+					continue;		/* don't need it */
+
+				if (tlist_member((Expr *) var, tlist))
+					continue;		/* already got it */
+
+				tle = makeTargetEntry((Expr *) var,
+									  list_length(tlist) + 1,
+									  NULL,
+									  true);
+
+				tlist = lappend(tlist, tle);
+			}
+			list_free(vars);
 		}
 	}
 
-- 
2.25.1

