From e95d4fd05a6880d979d4e332bc9e142c0b21e6f7 Mon Sep 17 00:00:00 2001
From: Richard Guo <guofenglinux@gmail.com>
Date: Thu, 7 Sep 2023 10:06:06 +0800
Subject: [PATCH v2] Reorder the tests in get_cheapest_path_for_pathkeys().

Checking 'parallel_safe' should be even cheaper than cost comparison, so
reorder the tests to do that first.  I doubt that there would be any
measurable performance gains from this minor tweak.  It is more about
being cosmetic.

While we are here, also add some comments for the requirement about
being parallel_safe.
---
 src/backend/optimizer/path/pathkeys.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c
index e53ea84224..fdb60aaa8d 100644
--- a/src/backend/optimizer/path/pathkeys.c
+++ b/src/backend/optimizer/path/pathkeys.c
@@ -407,7 +407,8 @@ pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
 /*
  * get_cheapest_path_for_pathkeys
  *	  Find the cheapest path (according to the specified criterion) that
- *	  satisfies the given pathkeys and parameterization.
+ *	  satisfies the given pathkeys and parameterization, and is parallel-safe
+ *	  if required.
  *	  Return NULL if no such path.
  *
  * 'paths' is a list of possible paths that all generate the same relation
@@ -429,6 +430,10 @@ get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
 	{
 		Path	   *path = (Path *) lfirst(l);
 
+		/* If required, reject paths that are not parallel-safe */
+		if (require_parallel_safe && !path->parallel_safe)
+			continue;
+
 		/*
 		 * Since cost comparison is a lot cheaper than pathkey comparison, do
 		 * that first.  (XXX is that still true?)
@@ -437,9 +442,6 @@ get_cheapest_path_for_pathkeys(List *paths, List *pathkeys,
 			compare_path_costs(matched_path, path, cost_criterion) <= 0)
 			continue;
 
-		if (require_parallel_safe && !path->parallel_safe)
-			continue;
-
 		if (pathkeys_contained_in(pathkeys, path->pathkeys) &&
 			bms_is_subset(PATH_REQ_OUTER(path), required_outer))
 			matched_path = path;
-- 
2.31.0

