Repository navigation
Conversation
|
Thank you for this, and for the clear tests. The behaviour you propose (a source column wins over a SELECT alias of the same name in HAVING) matches SQLite, and it is what we want for the next major version. We can't take it into the current releases, though. It changes the result of a common pattern: SELECT city, SUM(amount) AS amount FROM ? GROUP BY city HAVING amount > 100 which filters on the sum today and would filter on a single row's amount with this change. Code relies on that, so it is a breaking change. #2878 is now in the 5.0.0 milestone and marked as breaking, and the fix there will come with the column-resolution work already under way, so I'm closing this PR. Your tests and the cases in #2878 will be used for it, and you'll be credited. |
Fixes #2878.
The problem
A name in HAVING that is both a SELECT alias and a column of the source should read the source column. That only held for a table with column definitions. With a subquery,
FROM ?or a table without columns the alias replaced the column:And for a table with column definitions the alias was not used, but the column could not be read either, so the same query returned
[].The cause
resolveHavingAliases(src/select/having.js) askedquery.defcols[columnid]whether the name is a source column, anddefcolsonly lists the columns of tables that have a schema. When it did leave the name alone, the name compiled tog['cnt'], and the group object holds only the GROUP BY keys and the aggregates.The fix
For a name that is a SELECT alias, HAVING now reads the column from the row the group keeps in
query.groupSourceswhen a source has that column, and the alias when none has it.defcols['.'].incheck on the row. Not substituting at all for these sources would break the alias cases that already work (test887G,test2558), since nothing at compile time says whetherninFROM ? ... HAVING n > 1is a column.Names that are a GROUP BY key or ambiguous between two tables compile as before. The decision is made again on every compile, so a compiled statement follows the data of each run.
Tests
test/test2878.jscovers a subquery,FROM ?, a table without column definitions, a table with them, a joined parameter, the alias when no source has the name, and a compiled statement run on data with and without the column. Cases A to E and G fail before the change (A to C return[{a: 1, cnt: 2}], D returns[]).Test D of
test887.jsnow asserts the result,[{a: 2, cnt: 1}], in place ofnotDeepStrictEqual. It fails before the change too.yarn testpasses (2723 pass, 0 fail), andyarn test-format-allis clean.Note on #3003
#3003 edits the same function for #2769. The two do not depend on each other, and whichever lands second needs a small rebase.