From 8fb3ccfcba5d17461ff82b71ba5b3a23670c7223 Mon Sep 17 00:00:00 2001
From: "Andrey V. Lepikhov" <a.lepikhov@postgrespro.ru>
Date: Fri, 27 Oct 2023 17:55:04 +0700
Subject: [PATCH] Don't alter parse tree during the procedure of outer join
 reduction

---
 src/backend/optimizer/path/allpaths.c     |  3 +++
 src/backend/optimizer/plan/planner.c      |  3 +++
 src/backend/optimizer/plan/subselect.c    |  9 +++++++++
 src/backend/optimizer/prep/prepjointree.c | 24 +++++++++++------------
 src/backend/optimizer/prep/prepunion.c    |  3 +++
 src/backend/rewrite/rewriteManip.c        | 15 +++++++++++++-
 src/include/rewrite/rewriteManip.h        |  5 ++++-
 7 files changed, 48 insertions(+), 14 deletions(-)

diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index 67921a08262..fa0ca346050 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -2652,6 +2652,9 @@ set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel,
 									root,
 									false, tuple_fraction);
 
+	/* There should be only one copy of the subquery */
+	Assert(subquery == rel->subroot->parse);
+
 	/* Isolate the params needed by this specific subplan */
 	rel->subplan_params = root->plan_params;
 	root->plan_params = NIL;
diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index a8cea5efe14..ad194b96c57 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -413,6 +413,9 @@ standard_planner(Query *parse, const char *query_string, int cursorOptions,
 	root = subquery_planner(glob, parse, NULL,
 							false, tuple_fraction);
 
+	/* There should be only one copy of the subquery */
+	Assert(parse == root->parse);
+
 	/* Select best Path and turn it into a Plan */
 	final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
 	best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c
index 7a9fe88fec3..b6ce1e56ada 100644
--- a/src/backend/optimizer/plan/subselect.c
+++ b/src/backend/optimizer/plan/subselect.c
@@ -222,6 +222,9 @@ make_subplan(PlannerInfo *root, Query *orig_subquery,
 							   root,
 							   false, tuple_fraction);
 
+	/* There should be only one copy of subquery */
+	Assert(subquery == subroot->parse);
+
 	/* Isolate the params needed by this specific subplan */
 	plan_params = root->plan_params;
 	root->plan_params = NIL;
@@ -269,6 +272,9 @@ make_subplan(PlannerInfo *root, Query *orig_subquery,
 									   root,
 									   false, 0.0);
 
+			/* There should be only one copy of subquery */
+			Assert(subquery == subroot->parse);
+
 			/* Isolate the params needed by this specific subplan */
 			plan_params = root->plan_params;
 			root->plan_params = NIL;
@@ -982,6 +988,9 @@ SS_process_ctes(PlannerInfo *root)
 								   root,
 								   cte->cterecursive, 0.0);
 
+		/* There should be only one copy of subquery */
+		Assert(subquery == subroot->parse);
+
 		/*
 		 * Since the current query level doesn't yet contain any RTEs, it
 		 * should not be possible for the CTE to have requested parameters of
diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c
index 73ff40721c9..00cd50774aa 100644
--- a/src/backend/optimizer/prep/prepjointree.c
+++ b/src/backend/optimizer/prep/prepjointree.c
@@ -2687,14 +2687,14 @@ reduce_outer_joins(PlannerInfo *root)
 	if (!bms_is_empty(state2.inner_reduced))
 	{
 		root->parse = (Query *)
-			remove_nulling_relids((Node *) root->parse,
+			remove_nulling_relids_flags((Node *) root->parse,
 								  state2.inner_reduced,
-								  NULL);
+								  NULL, QTW_DONT_COPY_QUERY);
 		/* There could be references in the append_rel_list, too */
 		root->append_rel_list = (List *)
-			remove_nulling_relids((Node *) root->append_rel_list,
+			remove_nulling_relids_flags((Node *) root->append_rel_list,
 								  state2.inner_reduced,
-								  NULL);
+								  NULL, QTW_DONT_COPY_QUERY);
 	}
 
 	/*
@@ -2707,13 +2707,13 @@ reduce_outer_joins(PlannerInfo *root)
 		Relids		full_join_relids = bms_make_singleton(statep->full_join_rti);
 
 		root->parse = (Query *)
-			remove_nulling_relids((Node *) root->parse,
+			remove_nulling_relids_flags((Node *) root->parse,
 								  full_join_relids,
-								  statep->unreduced_side);
+								  statep->unreduced_side, QTW_DONT_COPY_QUERY);
 		root->append_rel_list = (List *)
-			remove_nulling_relids((Node *) root->append_rel_list,
+			remove_nulling_relids_flags((Node *) root->append_rel_list,
 								  full_join_relids,
-								  statep->unreduced_side);
+								  statep->unreduced_side, QTW_DONT_COPY_QUERY);
 	}
 }
 
@@ -3172,14 +3172,14 @@ remove_useless_result_rtes(PlannerInfo *root)
 	if (!bms_is_empty(dropped_outer_joins))
 	{
 		root->parse = (Query *)
-			remove_nulling_relids((Node *) root->parse,
+			remove_nulling_relids_flags((Node *) root->parse,
 								  dropped_outer_joins,
-								  NULL);
+								  NULL, QTW_DONT_COPY_QUERY);
 		/* There could be references in the append_rel_list, too */
 		root->append_rel_list = (List *)
-			remove_nulling_relids((Node *) root->append_rel_list,
+			remove_nulling_relids_flags((Node *) root->append_rel_list,
 								  dropped_outer_joins,
-								  NULL);
+								  NULL, QTW_DONT_COPY_QUERY);
 	}
 
 	/*
diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c
index 0c68ec011be..3f6e08d53bd 100644
--- a/src/backend/optimizer/prep/prepunion.c
+++ b/src/backend/optimizer/prep/prepunion.c
@@ -243,6 +243,9 @@ recurse_set_operations(Node *setOp, PlannerInfo *root,
 												  false,
 												  root->tuple_fraction);
 
+		/* Keep only one copy of the subquery */
+		Assert(rte->subquery == subroot->parse);
+
 		/*
 		 * It should not be possible for the primitive query to contain any
 		 * cross-references to other primitive queries in the setop tree.
diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c
index 32bd2f1dc99..a6621421c26 100644
--- a/src/backend/rewrite/rewriteManip.c
+++ b/src/backend/rewrite/rewriteManip.c
@@ -1226,6 +1226,19 @@ Node *
 remove_nulling_relids(Node *node,
 					  const Bitmapset *removable_relids,
 					  const Bitmapset *except_relids)
+{
+	return remove_nulling_relids_flags(node, removable_relids, except_relids, 0);
+
+}
+
+/*
+ * The same as remove_nulling_relids(), but also accepts flags argument, which
+ * gets passed to the tree mutator.
+ */
+Node *
+remove_nulling_relids_flags(Node *node,
+							const Bitmapset *removable_relids,
+							const Bitmapset *except_relids, int flags)
 {
 	remove_nulling_relids_context context;
 
@@ -1235,7 +1248,7 @@ remove_nulling_relids(Node *node,
 	return query_or_expression_tree_mutator(node,
 											remove_nulling_relids_mutator,
 											&context,
-											0);
+											flags);
 }
 
 static Node *
diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h
index ca12780bc78..e9828a4f6f0 100644
--- a/src/include/rewrite/rewriteManip.h
+++ b/src/include/rewrite/rewriteManip.h
@@ -71,7 +71,10 @@ extern Node *add_nulling_relids(Node *node,
 extern Node *remove_nulling_relids(Node *node,
 								   const Bitmapset *removable_relids,
 								   const Bitmapset *except_relids);
-
+extern Node *remove_nulling_relids_flags(Node *node,
+									   const Bitmapset *removable_relids,
+									   const Bitmapset *except_relids,
+									   int flags);
 extern Node *replace_rte_variables(Node *node,
 								   int target_varno, int sublevels_up,
 								   replace_rte_variables_callback callback,
-- 
2.39.3 (Apple Git-145)

