Inline window inheritance `OVER (w ORDER BY ...)` ignores the base window
To reproduce
A window specification written inline in OVER (...) that names a base window ignores the base window. The query compiles and returns rows computed without the base window's PARTITION BY and ORDER BY.
SELECT x, sum(x) OVER (w1 ORDER BY x) a
FROM long_sequence(5)
WINDOW w1 AS (PARTITION BY x % 2);| x | actual a |
expected a |
|---|---|---|
| 1 | 1.0 | 1.0 |
| 2 | 3.0 | 2.0 |
| 3 | 6.0 | 4.0 |
| 4 | 10.0 | 6.0 |
| 5 | 15.0 | 9.0 |
The actual column is the running sum over all rows. The plan shows no partitioning:
CachedWindowLight
orderedFunctions: [[x] => [sum(x) over (rows between unbounded preceding and current row)]]
long_sequence count: 5The equivalent spellings return the expected rows (1, 2, 4, 6, 9):
-- the specification written out
SELECT x, sum(x) OVER (PARTITION BY x % 2 ORDER BY x) a FROM long_sequence(5);
-- the same inheritance through a second named window
SELECT x, sum(x) OVER w2 a
FROM long_sequence(5)
WINDOW w1 AS (PARTITION BY x % 2), w2 AS (w1 ORDER BY x);Two more forms of the same defect:
-- a bare base window in brackets drops the whole definition: returns 15.0 on every row,
-- while OVER w1 without brackets returns 1, 2, 4, 6, 9
SELECT x, sum(x) OVER (w1) a
FROM long_sequence(5)
WINDOW w1 AS (PARTITION BY x % 2 ORDER BY x);
-- an undefined base window compiles and runs: returns 1, 3, 6, 10, 15,
-- while OVER nosuch fails with "[22] window 'nosuch' is not defined"
SELECT x, sum(x) OVER (nosuch ORDER BY x) a FROM long_sequence(5);QuestDB version:
master at f56e72425c. Reproduced on a branch based on that commit; the branch does not change the code involved.
OS, in case of Docker specify Docker and the Host OS:
Linux. The defect is in SQL compilation and does not depend on the OS.
File System, in case of Docker specify Host File System:
Not relevant.
Full Name:
Andrei Pechkurov
Affiliation:
QuestDB
Additional context
ExpressionParser parses the inline form and stores the base name on the window column with windowCol.setBaseWindowName(...). Nothing resolves it afterwards:
SqlOptimiser.resolveWindowInheritance()walks onlymodel.getNamedWindows(), the definitions of theWINDOWclause, so it merges a base intow2 AS (w1 ORDER BY x)and never visits a window column of the select list.SqlOptimiser.resolveNamedWindows()visits the select list, and handles onlyisNamedWindowReference(), theOVER wform.
So a select-list window that has a base keeps its own clauses only, and the "is not defined" check never runs for it.
A fix would resolve hasBaseWindow() for the window columns that resolveNamedWindows() already visits, including windows nested in expressions, with the same resolveWindowInheritanceChain() merge and the same "is not defined" error. The named-window syntax came in with #6746.
Source: questdb/questdb