From d97b98833680ee67a3c35c02e6dda235b67b7cf3 Mon Sep 17 00:00:00 2001
From: Richard Guo <guofenglinux@gmail.com>
Date: Mon, 13 Feb 2023 15:11:53 +0800
Subject: [PATCH v1] Fix for have_unsafe_outer_join_ref

---
 src/backend/optimizer/path/joinpath.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)

diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c
index 9d4a9197ee..fd881467c8 100644
--- a/src/backend/optimizer/path/joinpath.c
+++ b/src/backend/optimizer/path/joinpath.c
@@ -388,10 +388,10 @@ have_unsafe_outer_join_ref(PlannerInfo *root,
 {
 	bool		result = false;
 	Relids		unsatisfied = bms_difference(inner_paramrels, outerrelids);
+	Relids		satisfied = bms_intersect(inner_paramrels, outerrelids);
 
 	if (unlikely(bms_overlap(unsatisfied, root->outer_join_rels)))
 	{
-#ifdef NOT_USED
 		/* If we ever weaken the join order restrictions, we might need this */
 		ListCell   *lc;
 
@@ -401,22 +401,19 @@ have_unsafe_outer_join_ref(PlannerInfo *root,
 
 			if (!bms_is_member(sjinfo->ojrelid, unsatisfied))
 				continue;		/* not relevant */
-			if (bms_overlap(inner_paramrels, sjinfo->min_righthand) ||
+			if (bms_overlap(satisfied, sjinfo->min_righthand) ||
 				(sjinfo->jointype == JOIN_FULL &&
-				 bms_overlap(inner_paramrels, sjinfo->min_lefthand)))
+				 bms_overlap(satisfied, sjinfo->min_lefthand)))
 			{
 				result = true;	/* doesn't work */
 				break;
 			}
 		}
-#else
-		/* For now, if we do see an overlap, just assume it's trouble */
-		result = true;
-#endif
 	}
 
 	/* Waste no memory when we reject a path here */
 	bms_free(unsatisfied);
+	bms_free(satisfied);
 
 	return result;
 }
-- 
2.31.0

