From 40a156eccb7ba745fe5d45810f5b66f80b82082f Mon Sep 17 00:00:00 2001
From: Greg Nancarrow <gregn4422@gmail.com>
Date: Sat, 6 Feb 2021 00:52:49 +1100
Subject: [PATCH] Fix bug in the query rewriter: hasModifyingCTE is not set in
 re-written queries.

If a query that has a modifying CTE is re-written by the query rewriter, the
hasModifyingCTE flag is not getting set in the re-written query. This bug
can result in the query being allowed to execute in parallel-mode, which
results in an error.
---
 src/backend/rewrite/rewriteHandler.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c
index 0672f497c6..05b80bd347 100644
--- a/src/backend/rewrite/rewriteHandler.c
+++ b/src/backend/rewrite/rewriteHandler.c
@@ -557,6 +557,21 @@ rewriteRuleAction(Query *parsetree,
 		/* OK, it's safe to combine the CTE lists */
 		sub_action->cteList = list_concat(sub_action->cteList,
 										  copyObject(parsetree->cteList));
+
+		/*
+		 * If the hasModifyingCTE flag is set in the source parsetree from
+		 * which the CTE list is copied, the flag needs to be set in the
+		 * sub_action and, if applicable, in the rule_action (INSERT...SELECT
+		 * case).
+		 */
+		if (parsetree->hasModifyingCTE)
+		{
+			sub_action->hasModifyingCTE = true;
+			if (sub_action_ptr)
+				rule_action->hasModifyingCTE = true;
+			else
+				Assert(sub_action == rule_action);
+		}
 	}
 
 	/*
-- 
2.27.0

