fix_unused_subquery_columns_for_wfunc_runconditions.patch

text/plain

Filename: fix_unused_subquery_columns_for_wfunc_runconditions.patch
Type: text/plain
Part: 0
Message: Re: BUG #17495: Regression in 15beta1 when filtering subquery including row_number window function

Patch

Format: unified
File+
src/backend/optimizer/path/allpaths.c 40 0
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index 7ac116a791..c67a739dd9 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -3989,6 +3989,46 @@ remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel)
 		pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
 	}
 
+	/*
+	 * baserestrictinfo may have been pushed down into a WindowClause's
+	 * runCondition, so gather up the attrs from those too.
+	 */
+	foreach(lc, subquery->windowClause)
+	{
+		WindowClause	   *wc = (WindowClause *) lfirst(lc);
+		ListCell		   *lc2;
+
+		foreach(lc2, wc->runCondition)
+		{
+			OpExpr *opexpr = lfirst_node(OpExpr, lc2);
+			Expr	*left = linitial(opexpr->args);
+			Expr	*right = lsecond(opexpr->args);
+			WindowFunc *wfunc;
+			ListCell *lc3;
+
+			if (IsA(left, WindowFunc))
+				wfunc = (WindowFunc *) left;
+			else
+				wfunc = (WindowFunc *) right;
+
+			Assert(IsA(wfunc, WindowFunc));
+
+			foreach(lc3, subquery->targetList)
+			{
+				TargetEntry *tle = (TargetEntry *) lfirst(lc3);
+				Node	   *texpr = (Node *) tle->expr;
+
+				if (equal(wfunc, texpr))
+				{
+					attrs_used = bms_add_member(attrs_used,
+												foreach_current_index(lc3) -
+												FirstLowInvalidHeapAttributeNumber + 1);
+					break;
+				}
+			}
+		}
+	}
+
 	/*
 	 * If there's a whole-row reference to the subquery, we can't remove
 	 * anything.