From 68740de04e3bb21b15ed239def61474428a79cf4 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@2ndquadrant.com>
Date: Fri, 16 Apr 2021 03:09:48 +0200
Subject: [PATCH 2/2] tweaks

---
 src/backend/optimizer/path/equivclass.c | 25 ++++++++++++++++++++-----
 1 file changed, 20 insertions(+), 5 deletions(-)

diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 27867e16e8..bf1c95c847 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -799,6 +799,14 @@ find_em_expr_for_rel(EquivalenceClass *ec, RelOptInfo *rel)
 	return NULL;
 }
 
+/*
+ * Checks if node is member of the list. RelabelType is ignored for expressions
+ * in the list.
+ *
+ * XXX We have list_member_XXX for different types, so maybe make that consistent?
+ * XXX Perhaps explain why the relabel is ignored. Why is it ignored recursively?
+ * XXX Maybe reference tlist_member_ignore_relabel, which is doing the same thing?
+ */
 static Expr*
 expr_list_member_ignore_relabel(Expr *node, List *exprlist)
 {
@@ -882,24 +890,31 @@ find_em_expr_usable_for_sorting_rel(PlannerInfo *root, EquivalenceClass *ec,
 		 * up a volatile expression to the proper tlist entry, it doesn't seem
 		 * valuable here to expend the work trying to find a match in the
 		 * target's exprs since such a sort will have to be postponed anyway.
+		 *
+		 * XXX Doesn't this comment need an update?
+		 *
+		 * XXX Maybe we should start matching the tlist entries? After all,
+		 * prepare_sort_from_pathkeys matches directly, and only if not found
+		 * it does the pull_var_clause stuff, no?
 		 */
 		if (ec->ec_has_volatile)
 			return NULL;
 
-
+		/* XXX comment would be nice ... */
 		exprvars = pull_var_clause((Node *) em_expr,
 								   PVC_INCLUDE_AGGREGATES |
 								   PVC_INCLUDE_WINDOWFUNCS |
 								   PVC_INCLUDE_PLACEHOLDERS);
+
+		/* All expressions have to be present in the target list. */
 		foreach(k, exprvars)
 		{
 			if (!expr_list_member_ignore_relabel(lfirst(k), target->exprs))
-				break;
+				return NULL;
 		}
-		list_free(exprvars);
 
-		if (!k) /* If we made it through exprvars finding a tlist member for each */
-			return em->em_expr; /* found usable expression */
+		/* all the expressions have a matching target entry. */
+		return em->em_expr;
 	}
 
 	/* We didn't find any suitable equivalence class expression */
-- 
2.30.2

