fix(sql): fix order by position resolution with window functions over CTEs#6716
fix(sql): fix order by position resolution with window functions over CTEs#6716bluestreak01 merged 1 commit intomasterfrom
Conversation
WalkthroughModified SqlOptimiser to expand the condition for identifying outer models during ORDER BY rewriting. Previously only GROUP_BY was recognized as outer context; now WINDOW models are also treated as such. Added two test methods to verify window function ranking behavior with ORDER BY using both alias and positional references. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ast-grep (0.40.5)core/src/main/java/io/questdb/griffin/SqlOptimiser.javacore/src/test/java/io/questdb/test/griffin/SqlParserTest.javaThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
[PR Coverage check]😍 pass : 2 / 2 (100.00%) file detail
|
|
@CodeRabbit pls review |
|
🧠 Learnings used✅ Actions performedReview triggered.
|
Summary
ORDER BY <position>failed with "Invalid column" error when used with a CTE containing aggregation and a window function expressionProblem
The following query failed with
SqlException: [176] Invalid column: rank:Root Cause
In
SqlOptimiser.rewriteOrderByPosition(), when resolving positional ORDER BY (e.g.,order by 4), the code determines which model's columns to use for position-to-name resolution. The condition at line 6908 only setbaseOuterwhen a VIRTUAL model's direct nested model was GROUP_BY:With window functions, the model structure is:
Since VIRTUAL's nested is WINDOW (not GROUP_BY),
baseOuterwas not set, causing the wrong model's columns (windowModel withrank) to be used instead of the correct model (outerVirtualModel withrank1).Fix
Extended the condition to also check for
SELECT_MODEL_WINDOW:Test plan
testWithWindowFunctionRankAndOrderByAlias- tests ORDER BY with explicit aliastestWithWindowFunctionRankAndOrderByPosition- tests ORDER BY with position (the original failing case)🤖 Generated with Claude Code