From d1b54830eea71b6afb465d4c86d9a4a92742dc98 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas.vondra@postgresql.org>
Date: Mon, 13 Dec 2021 02:48:58 +0100
Subject: [PATCH 3/5] relax the restrictions

---
 src/backend/utils/adt/selfuncs.c | 25 ++++++++++++++++---------
 1 file changed, 16 insertions(+), 9 deletions(-)

diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 1031a0fd9e..6b0dde66bf 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -4914,7 +4914,7 @@ matching_restriction_variables(PlannerInfo *root, List *args, int varRelid)
 {
 	Node	   *left,
 			   *right;
-	Var		   *lvar;
+	Bitmapset  *varnos;
 
 	/* Fail if not a binary opclause (probably shouldn't happen) */
 	if (list_length(args) != 2)
@@ -4931,17 +4931,24 @@ matching_restriction_variables(PlannerInfo *root, List *args, int varRelid)
 	if (IsA(right, RelabelType))
 		right = (Node *) ((RelabelType *) right)->arg;
 
-	/* We only care about simple Vars from our relation for now */
-	if (!IsA(left, Var) || !IsA(right, Var))
+	/*
+	 * Check if it's safe to compare the two expressions. The expressions
+	 * must not contain any volatile expressions, and must belong to the
+	 * same relation.
+	 *
+	 * XXX We do a small trick - we validate just one expression, and then
+	 * check it's equal to the other side.
+	 */
+	if (contain_volatile_functions(left))
 		return false;
 
-	lvar = (Var *) left;
+	/* Check it belongs to a single relation. */
+	varnos = pull_varnos(root, left);
 
-	/*
-	 * We only check one variable, because we call equals() later, which checks
-	 * the other variable automatically.
-	 */
-	if ((varRelid != 0) && (varRelid != lvar->varno))
+	if (bms_num_members(varnos) != 1)
+		return false;
+
+	if ((varRelid != 0) && (!bms_is_member(varRelid, varnos)))
 		return false;
 
 	/* The two variables need to match */
-- 
2.31.1

