Skip to content

[CALCITE-7887] SubQueryRemoveRule fails for a sub-query inside a window function - #5359

Merged
iwanttobepowerful merged 1 commit into
apache:mainfrom
iwanttobepowerful:CALCITE-7887
Oct 26, 2026
Merged

iwanttobepowerful merged 1 commit into
apache:mainfrom
iwanttobepowerful:CALCITE-7887

Conversation

@iwanttobepowerful

Copy link
Copy Markdown
Contributor

CALCITE-7887

Root cause

SubQueryRemoveRule.matchProject locates the sub-query to rewrite with RexUtil.SubQueryFinder, which is a deep RexVisitorImpl and therefore descends into a RexOver's operands, partition keys and order keys. It then calls LogicVisitor.find to compute the Logic under which that sub-query is evaluated. However, LogicVisitor.visitOver only called end(over, arg) and never visited the operands or the window of the RexOver. As a result, a sub-query nested anywhere inside a window function was found by SubQueryFinder but was invisible to LogicVisitor, so the collected logic set was empty and LogicVisitor.find threw IllegalArgumentException: not found.

Fix

LogicVisitor.visitOver now visits the aggregate operands, the partition keys, the order keys and the bounds of the window. They are visited with Logic.TRUE_FALSE_UNKNOWN, because a window function consumes the value of these expressions, not just whether they are true. For example, COUNT(x) ignores NULLs, so UNKNOWN must be distinguished from FALSE; PARTITION BY / ORDER BY treat NULL and FALSE as different keys. Using a weaker logic such as UNKNOWN_AS_FALSE could therefore produce wrong results.

Only Project is affected, since window functions can only appear in the SELECT list (QUALIFY is converted to a Filter on top of a Project).

@sonarqubecloud

Copy link
Copy Markdown


# [CALCITE-7887] SubQueryRemoveRule fails for a sub-query inside a window function
# IN sub-query inside the argument of a windowed aggregate.
# The result of this query was validated using Postgres.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only this one or all of them?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all of them

@iwanttobepowerful iwanttobepowerful added the LGTM-will-merge-soon Overall PR looks OK. Only minor things left. label Oct 26, 2026
@iwanttobepowerful
iwanttobepowerful merged commit 2df193e into apache:main Oct 26, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

LGTM-will-merge-soon Overall PR looks OK. Only minor things left.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants