Repository navigation
fix(query): head expression targets the way bean-query renders them - #2175
Conversation
`SELECT number + 1` headed `col0`, `SELECT 'lit'` headed `col0`. A name
that identifies nothing, and one a script reading our CSV by header cannot
find at all.
bean-query renders the parse tree FAITHFULLY. It keeps the parentheses
the query wrote, including ones precedence does not require, and adds
none of its own:
(number > 0) AND (number < 5) -> both pairs kept
number + 1 * 2 -> nothing added
NOT number > 0 -> nothing added
((number + 1)) -> number + 1, outer pair dropped
That is measured, not derived. Minimal parenthesization by precedence was
the obvious implementation and it disagrees on the first case, which is
why #2171 was filed rather than fixed inline.
The new `ast::header_name` renders that way. It is deliberately NOT
`Display`: `Display` parenthesizes every binary node and double-quotes
strings, which is right for what it is used for -- naming the synthetic
hidden ORDER BY columns, where round-tripping matters -- and wrong for a
header. `Display` is untouched.
This also fixes a divergence #2164 left behind and I did not catch there:
function targets were headed with `Display`, so `sum(number + 1)` headed
`sum((number + 1))`. My testing on that PR used only simple column
arguments.
Unary operators needed care. `UnaryOperator`'s Display bakes in its own
spacing and position -- `NOT ` prefix with a trailing space, `-` prefix
with none, and ` IS NULL` / ` IS NOT NULL` POSTFIX with a leading space.
Formatting them uniformly as prefix produced `NOT x` and `IS NULL x`.
`colN` is gone, so `expr_to_name` no longer needs the target index; the
parameter and both `enumerate()` calls are removed.
24 header shapes checked against bean-query, all matching. Unit tests
cover the rendering rules directly and were confirmed to fail when the
parenthesizing, the postfix position, or the top-level stripping is
reverted.
Closes #2171
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
Pull request overview
This PR updates rustledger-query’s result-column header naming so expression targets (literals, unary/binary expressions, and function calls) are headed using a bean-query-compatible renderer (ast::header_name) instead of defaulting to colN or relying on Display.
Changes:
- Introduces
ast::header_name/header_fragmentto render header text in a way intended to match bean-query’s column headings (preserving user-written parentheses, stripping only top-level wrapping parens). - Switches
Executor::expr_to_nameto useheader_namefor functions and all non-identifier expressions, removing thecolNfallback and dropping the now-unused target index plumbing. - Adds unit tests that compare a set of header shapes against expected bean-query renderings.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| crates/rustledger-query/src/ast.rs | Adds header_name rendering logic for expression-based headers. |
| crates/rustledger-query/src/executor/mod.rs | Routes expression-to-header naming through ast::header_name; removes colN naming/index usage. |
| crates/rustledger-query/src/executor/execution.rs | Updates target iteration and calls into the new expr_to_name signature (no index). |
| crates/rustledger-query/src/executor/tests.rs | Adds direct unit coverage for ast::header_name against expected header renderings. |
Suppressed comments (1)
crates/rustledger-query/src/ast.rs:681
Expr::Subscriptheaders always render the key as['{key}']. Since keys are parsed as generic string literals, they can come from double-quoted input and contain an unpaired'(e.g.["o'clock"]), which this renderer would turn into['o'clock']and misrepresent the original expression. Consider the same “unpaired quote ⇒ use double quotes” rule as for string literals.
Expr::Subscript { operand, key } => {
format!("{}['{key}']", header_fragment(operand))
}
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Review catch on #2175 from Copilot. Every string literal was rendered single-quoted, so a value containing a single quote produced 'o'clock' -- not a well-formed literal, and not what the query wrote. Now double-quoted when the value contains a single quote and no double quote. That case also happens to agree with bean-query. Full parity is out of reach here and is filed as #2176: bean-query echoes the quote character the query used, and Literal::String does not record which it was, so "dq" still heads 'dq'. Confirmed the test fails when the condition is forced false.
Review catch on #2175. `write_csv` escaped every value but joined the header names raw. That was harmless while headers were identifiers or `colN`; this PR makes them able to contain commas -- `SELECT number IN (1, 2)` heads `number IN (1, 2)` -- and an unescaped one splits in two: ours: ['number IN (1', ' 2)'] bean-query: ['number IN (1, 2)'] A consumer then reads more headers than there are columns and misaligns every field after it, with no error anywhere. Now escaped with the same helper the value rows already used, which also makes the three `IN` shapes match bean-query. Confirmed the test fails against the unescaped join.
Self-review catch on #2175. `ast` is a `pub mod`, so declaring `pub fn header_name` put an internal rendering helper into rustledger-query's API surface. Every caller is in this crate -- two arms of `expr_to_name` and one test -- so it is `pub(crate)` now. Nothing outside could have depended on it yet; it was added in this same PR.
Sixth review pass on #2175 found no defect; this locks in what it verified. Nested calls in both directions (sum(neg(number)), length(payee) + 1), the wildcard argument (count(*)), and the postfix targets (entry.narration, meta['k'], entry.meta['k']) all match bean-query but had no test. The postfix ones are worth pinning specifically: expr_to_name routes them through Display rather than header_name, for the ORDER BY reason in #1800. The two renderings agree on these shapes, so the split is not observable -- this keeps it that way, and would catch it if either renderer moved.
`SELECT number + 1 ORDER BY number + 1` failed with `ORDER BY expression not found in SELECT: (number + 1)`. The header and the lookup spelled the same expression two ways: `ast::header_name` gives `number + 1`, `Display` parenthesizes and gives `(number + 1)`, and `sort_results` looked up by `Display`. `find_column`'s case-insensitive fallback cannot bridge that -- the two spellings differ by punctuation, not case. Before #2175 the header was `col0`, so the lookup missed for a different reason; the query has never worked. Both sites move together, and that is not tidiness. `sort_results` looks the target up, and `find_hidden_order_by_targets` NAMES the synthetic column when the expression is not reachable in the projection. Changing one alone trades one miss for another: a hidden column named by `Display` is invisible to a lookup by `header_name`. Each half has a test only it satisfies -- reverting the lookup fails three of four, reverting the naming fails exactly the hidden-column one. The issue asked for the neighboring paths to be re-verified rather than trusted, so they were, against bean-query: ordinals (`ORDER BY 1`, `ORDER BY 2`), multi-key, DESC, aggregate targets, and an aliased target whose ORDER BY needs the hidden column all match row for row. The wildcard is unchanged -- `SELECT *` output is byte-identical to main. Numbers differ from bean-query only by its right-alignment padding in CSV (`, 10.00` against `,10.00`), which is pre-existing and independent of ordering. `order-by-expression` joins the BQL compat corpus, verified to be real coverage: it reports `match: True`, and `match: False` when the lookup is reverted. Closes #2177
* fix(query): ORDER BY an expression finds the column it names `SELECT number + 1 ORDER BY number + 1` failed with `ORDER BY expression not found in SELECT: (number + 1)`. The header and the lookup spelled the same expression two ways: `ast::header_name` gives `number + 1`, `Display` parenthesizes and gives `(number + 1)`, and `sort_results` looked up by `Display`. `find_column`'s case-insensitive fallback cannot bridge that -- the two spellings differ by punctuation, not case. Before #2175 the header was `col0`, so the lookup missed for a different reason; the query has never worked. Both sites move together, and that is not tidiness. `sort_results` looks the target up, and `find_hidden_order_by_targets` NAMES the synthetic column when the expression is not reachable in the projection. Changing one alone trades one miss for another: a hidden column named by `Display` is invisible to a lookup by `header_name`. Each half has a test only it satisfies -- reverting the lookup fails three of four, reverting the naming fails exactly the hidden-column one. The issue asked for the neighboring paths to be re-verified rather than trusted, so they were, against bean-query: ordinals (`ORDER BY 1`, `ORDER BY 2`), multi-key, DESC, aggregate targets, and an aliased target whose ORDER BY needs the hidden column all match row for row. The wildcard is unchanged -- `SELECT *` output is byte-identical to main. Numbers differ from bean-query only by its right-alignment padding in CSV (`, 10.00` against `,10.00`), which is pre-existing and independent of ordering. `order-by-expression` joins the BQL compat corpus, verified to be real coverage: it reports `match: True`, and `match: False` when the lookup is reverted. Closes #2177 * fix(query): the function arm of the ORDER BY lookup had the same bug Review feedback, and correct. I changed the arm that handles binary expressions and left `Expr::Function` on `Display`, which parenthesizes its arguments the same way. So `abs(number + 1)` still looked for `abs((number + 1))` against an `abs(number + 1)` header. `abs(number)` resolves either way, which is how the gap hid: the argument has to be COMPOUND before the two spellings part company, and every function case I had reached for was a bare column. Both arms now name the target the way the header does. Two tests rather than one, so a regression tells you which case broke: the compound-argument form, and the bare-column form that worked before. Reverting only this arm fails exactly the first. Swept wider against bean-query while here -- `number * 2`, unary `-number`, `ORDER BY <expr> DESC`, a function as a secondary sort key, and an aliased target sorted by its alias all match row for row.
…2229) `SELECT "dq"` headed `'dq'`. bean-query names such a column by reproducing the literal as typed, quote character included. Closes #2176. `Literal::String` did not record which quote the source used, so the header had to guess: single quotes unless the value contained one. It now carries a `QuotedString`, and the header echoes what was written. Verified against beanquery 0.2.0 -- `'plain'`, `"dq"`, `"o'clock"`, `'it''s'`, `'say "hi"'`, and the same inside a call like `length('abc')`, all agree. The body is reproduced VERBATIM, as bean-query does: `'it''s'` heads `'it''s'`, the doubled quote left as written rather than re-escaped. That matches the value semantics already pinned in `string_literal_escapes_test.rs`, where `''` stays in the value. Quote style is source provenance, not part of the value, so `QuotedString` implements `PartialEq` and `Hash` on the text alone -- `'x'` and `"x"` are the same string, and AST equality must not depend on typing style. Same reasoning as `Spanned`, which keeps equality on its value rather than its span. Pinned, including the Hash/Eq agreement a `HashMap` keyed on literals would need. `quote` is `None` for a literal built in code rather than parsed, which has no style to echo; those keep the #2175 fallback, so that fix is untouched. `Display` echoes the source quote too, which makes a parsed literal round-trip as written -- the issue notes this may matter more than the header does -- and still falls back to double quotes. `string_literal` now delegates to the new `quoted_string_literal` instead of restating the grammar. The two arms were about to be duplicated, and a fix applied to one and not the other would make a literal parse differently depending on which caller reached it. The header and `Display` paths are controlled separately: making either ignore the recorded style fails tests, and the equality test fails if `PartialEq` starts comparing it.
What
SELECT number + 1headedcol0.SELECT 'lit'headedcol0. A name thatidentifies nothing, and one a script reading our CSV by header cannot find.
SELECT 11col01SELECT 'lit''lit'col0'lit'SELECT number + 1number + 1col0number + 1SELECT (number + 1) * 2(number + 1) * 2col0(number + 1) * 2SELECT sum(number + 1)sum(number + 1)sum((number + 1))sum(number + 1)bean-query renders the tree faithfully, not minimally
This is why #2171 was filed rather than fixed inline in #2164. The obvious
implementation — parenthesize by precedence — disagrees with bean-query:
So bean-query preserves the parentheses the query wrote and adds none, except
around the whole target. Every expectation here was read off bean-query 3.x
rather than derived.
Why not just use
DisplayDisplayparenthesizes every binary node and double-quotes strings. That iscorrect for what it is used for — naming the synthetic hidden ORDER BY columns,
where round-tripping is what matters, and which #2170 repaired — and wrong for
a header.
Displayis untouched;ast::header_nameis separate.A divergence #2164 left behind
Function targets were headed with
Display, sosum(number + 1)headedsum((number + 1)). I did not catch it there because my testing used onlysimple column arguments. Same renderer fixes it.
Unary operators
UnaryOperator'sDisplaybakes in its own spacing and position:NOTis prefix with a trailing space,
-is prefix with none, andIS NULL/IS NOT NULLare postfix with a leading space. Formatting them uniformlyas prefix produced
NOT xandIS NULL x.A CSV bug this exposed
Headers could not contain a comma before this change — they were identifiers
or
colN. NowSELECT number IN (1, 2)headsnumber IN (1, 2), andwrite_csvwas joining header names raw while escaping every value:A consumer reads more headers than there are columns and misaligns every field
after it, with no error. Fixed with the same
escape_csvthe value rowsalready used, which also brings the three
INshapes into agreement withbean-query.
Cleanup
colNis gone, soexpr_to_nameno longer needs the target index. Theparameter and both
enumerate()calls went with it.Verification
after each refactor rather than assumed.
parenthesizing, the postfix position, or the top-level stripping is reverted
— checked one at a time.
known 34, found 34, new 0);corpus_paritydivergences still exactly 20, matching
main.Closes #2171