Skip to content

fix(query): per-currency precision through PIVOT via column-name fallback - #1033

Merged
robcohen merged 4 commits into
mainfrom
fix/issue-1023-pivot-precision
May 8, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/issue-1023-pivot-precision

Conversation

@robcohen

@robcohen robcohen commented May 8, 2026 •

Copy link
Copy Markdown
Member

Summary

⚠️ Behavioral change: PIVOT output column shape

Pre-fix, apply_pivot produced output where the column header and row data didn't agree on length. Concretely, for SELECT account, currency, SUM(number) GROUP BY account, currency PIVOT BY currency:

Pre-fix Post-fix
Headers [account, SUM, USD] (3 cols) [account, USD] (2 cols)
Row data [Assets:Bank, -5.00] (2 cells) [Assets:Bank, -5.00] (2 cells)
JSON {"SUM": "-5.00", "account": "Assets:Bank"} — SUM column was eating the pivoted USD value, USD column was always empty {"USD": "-5.00", "account": "Assets:Bank"}

Anyone with a PIVOT query in production was getting wrong column→value mapping. This PR silently fixes it. If you have PIVOT queries in dashboards or scripts, re-validate the column names.

Why column-name fallback over a column-sidecar

Discussed in the issue review. The pivoted column names are already populated correctly by apply_pivot (Self::value_to_string(pv)), so adding ~10 lines to consult them is cheaper than a new sidecar field + new invariant. The same shape-check + precision-tracked gate prevents false positives.

Implementation

  • crates/rustledger/src/cmd/query/output.rs::write_text:
    • Precompute column_currency_hints once (parallel to currency_hints).
    • New resolve_cell_hint helper centralizes the precedence: row_hint.or(col_hint). Both width-calc and print passes use it, so they can't drift.
  • crates/rustledger-query/src/executor/sort.rs::apply_pivot: also exclude value_col_idx from new_columns so columns and rows agree on shape.

Test plan

  • 5 new unit tests for the cell-level hint behavior:
    • test_text_pivoted_column_uses_column_name_as_currency_hint — happy path.
    • test_text_pivoted_column_with_untracked_currency_falls_back_safely — pins the false-positive guard (untracked column "USD" must NOT route through format → would strip trailing zeros via normalize()).
    • test_row_sidecar_wins_over_column_name_fallback — precedence.
    • test_text_pivoted_multi_currency_uses_per_column_precision — USD (2dp) + JPY (0dp) on the same row, each column uses its own precision.
    • test_non_pivoted_currency_named_column_inherits_fallback_quantization — defensive regression test: pins the behavior of a non-pivoted query with a column aliased as a currency code (e.g. SELECT … AS USD). Today's contract: tracked currency drives quantization regardless of PIVOT path.
  • 1 e2e test test_e2e_pivot_by_currency_text_output_matches_per_currency_precision driving SELECT account, currency, SUM(number) GROUP BY account, currency PIVOT BY currency through Executor → write_text.
  • All 511 rustledger-query lib tests pass.
  • All 20 cmd::query::output tests pass (15 existing + 5 new).
  • cargo clippy --all-features -- -D warnings clean.
  • cargo fmt --all -- --check clean.
  • All pre-push hooks green.

Acceptance criteria

Why no BQL compat fixture

A draft commit added a sum-by-account-pivot-by-currency query to bql-queries.toml, but local verification against bean-query revealed that bean-query's PIVOT BY takes two columns (pivot value + group key) where rledger takes one. The two tools produce structurally different output for any PIVOT query, so a compat-harness diff is permanently red regardless of correctness. The fixture was removed and a comment placed in bql-queries.toml pointing to #1034, where the semantic-reconciliation question is tracked alongside two pre-existing PIVOT robustness gaps surfaced during the review.

Out of scope

Closes #1023.

🤖 Generated with Claude Code

…back

Closes #1023.

PR #1022 fixed #988 (SUM-aggregate text output matching bean-query's
per-currency precision) by carrying the GROUP BY currency in a per-row
sidecar. PIVOT regressed it: `apply_pivot` builds new rows via
`add_row` (not `add_aggregate_row`), so the sidecar drops to `None`
and the renderer can't recover the precision context.

After PIVOT, the GROUP BY currency moves into column position — each
pivoted column's name IS the currency code. The renderer can read it
from there.

Implementation:
- New `column_currency_hints` precomputed once per write_text invocation,
  symmetrical to the existing `currency_hints` row sidecar lookup. Uses
  the same `looks_like_currency` + `ctx.get_precision().is_some()`
  guard, so an untracked column-named "USD" still falls back safely
  (without the guard, `DisplayContext::format` strips trailing zeros
  via `normalize()`, making output WORSE than the unfixed state).
- Per-cell hint resolution: row sidecar wins over column-name fallback
  (the sidecar came from the actual GROUP BY key; the column name is a
  heuristic). Width-calc and print passes use the same precedence so
  rendered widths match rendered values.

Bonus: pre-existing column/row length mismatch in `apply_pivot`. The
column header included the value column ("SUM") but the row builder
explicitly excluded it from `group_cols`, leaving rows one cell short.
JSON output silently dropped the SUM cell. Fixed by also excluding
`value_col_idx` from `new_columns` so columns and rows agree on shape.
This blocked the e2e PIVOT test for #1023, so it had to be fixed here
rather than as a separate issue.

Tests:
- 3 new unit tests in `cmd::query::output::tests`:
  - `test_text_pivoted_column_uses_column_name_as_currency_hint`
  - `test_text_pivoted_column_with_untracked_currency_falls_back_safely`
    — pins the false-positive guard
  - `test_row_sidecar_wins_over_column_name_fallback`
- 1 new e2e test through Executor + write_text.
- New BQL compat fixture `sum-by-account-pivot-by-currency` in
  bql-queries.toml so #1000's harness catches future regressions.

511 query tests + 18 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 8, 2026 05:07
@robcohen
robcohen requested a review from a team as a code owner May 8, 2026 05:07

@robcohen robcohen left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self-review pass. Five real concerns, two pre-existing risks worth flagging.

Real concerns

1. Behavioral change in apply_pivot is broader than the PR title suggests.

The column-shape fix doesn't just unblock the e2e test — it changes user-visible output for every PIVOT query, not just precision-affected ones. Pre-fix:

  • Headers: [account, SUM, USD] (3 cols)
  • Row data: [Assets:Bank, -5.00] (2 cols)
  • JSON: {"SUM": "-5.00", "account": "Assets:Bank"} — the SUM column was eating the pivoted USD value, USD column was always empty.

Post-fix headers/data are aligned at [account, USD]. Anyone who had a PIVOT query in production was getting wrong column→value mapping (and an empty pivot column). My PR fixes this silently. Worth being explicit in the commit message that this is a breaking output-shape change for all PIVOT queries (going from broken to correct, but observable). Update the PR body to call it out so users with PIVOT in dashboards know to re-validate.

2. Non-pivoted query with a currency-named column triggers the fallback.

format_value_with_hint only consults the hint for Value::Number cells, so the affected case is narrow: a SELECT clause with an aliased column that both (a) looks like a currency code AND (b) has tracked precision in the active context. E.g. SELECT 1 AS USD FROM ... — that "USD" column would now route through DisplayContext::format(_, "USD") and quantize at 2dp.

In practice this is near-zero-impact (no one names unrelated columns "USD"), but I have no regression test pinning that the existing per-column-context path still works for the false-positive case where someone DOES. Worth one defensive test:

fn test_non_pivoted_currency_named_column_does_not_disrupt_existing_path() {
    // SELECT clause with `AS USD` shouldn't quantize cells whose
    // semantic precision differs from USD's tracked precision.
    // Concretely: a column literally named USD whose values were never
    // seeded as USD postings.
}

3. Cell-hint resolution is duplicated across width-calc and print passes.

let cell_hint = row_hint.or_else(|| column_currency_hints.get(i).copied().flatten());

Appears twice with identical logic. The comment in the print pass explicitly says "must match the same precedence used in the width-calculation pass above" — that's exactly the kind of invariant that breaks when someone refactors one but not the other. Extract to a helper:

fn resolve_cell_hint<'a>(
    row_hints: &[Option<&'a str>],
    col_hints: &[Option<&'a str>],
    row_idx: usize,
    col_idx: usize,
) -> Option<&'a str> {
    row_hints.get(row_idx).copied().flatten()
        .or_else(|| col_hints.get(col_idx).copied().flatten())
}

Tiny, but locks in the precedence invariant.

4. Compat fixture isn't actually verified against bean-query yet.

I added sum-by-account-pivot-by-currency to bql-queries.toml but didn't run the harness to confirm rledger and bean-query produce matching output. The compat harness from #1000 will run on this PR's CI — if they diverge in column shape (likely — bean-query may keep different column conventions) or precision, the harness goes red. Worth running locally before declaring done, or accepting that CI will flag any mismatch.

5. Multi-currency PIVOT path is not tested.

The e2e test only exercises a single currency (USD). The interesting case is PIVOT BY currency with both USD and JPY postings — each pivoted column should use its OWN precision (USD=2dp, JPY=0dp), not a shared one. My implementation should handle this correctly (per-column hint computed per column), but there's no test pinning it. Add:

fn test_text_pivoted_multi_currency_uses_per_column_precision() {
    // USD column at 2dp, JPY column at 0dp, same row.
}

Pre-existing risks (not introduced, worth filing)

6. result.columns.len() - 1 can underflow.

The value_col_idx = result.columns.len() - 1 line panics if result.columns.is_empty(). Was at line 125 pre-fix, now at line 117. apply_pivot only runs when pivot_exprs is non-empty, and find_pivot_column would error before reaching this line for an empty result, so the path isn't reachable in practice. Still worth a checked_sub or saturating fallback.

7. Degenerate case: value_col_idx == pivot_col_idx.

For SELECT currency PIVOT BY currency (the value column IS the pivot column), the filter *i != pivot_col_idx && *i != value_col_idx excludes the index once. Behavior is probably fine but undefined. No test, no documented contract.

Verdict

Concerns 1–4 are blockers for "ship-ready" but easy to address: update commit message (1), one defensive test (2), helper extraction (3), let CI run (4). Concern 5 is a should-have, not a must. 6–7 belong in a separate cleanup issue.

Want me to land all five fixes in a follow-up commit on this branch?

@codecov

codecov Bot commented May 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.38710% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/query/output.rs 98.89% 2 Missing ⚠️
crates/rustledger-query/src/executor/sort.rs 80.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 30.9ms ± 0.7ms 21.7 MB
beancount 904.2ms ± 8.6ms 50.4 MB
Comparison 29.3x faster 2.3x less

vs main branch (2026-05-08)

Metric main this PR Change
Time 31ms 30.9ms -0.3% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

Copilot AI left a comment

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.

Pull request overview

Fixes a regression where PIVOT BY currency caused text output to lose per-currency precision (from the #988/#1022 renderer-side quantization), by falling back to the pivoted column name as the currency hint when the per-row GROUP BY sidecar is absent. Also aligns apply_pivot’s column header shape with its row shape and adds tests/fixtures to lock the behavior in.

Changes:

  • Text renderer: add per-column currency hint resolution from column names, with row-sidecar precedence.
  • Pivot executor: exclude the “value” column from the post-pivot column header to match row construction.
  • Tests/fixtures: add unit + e2e coverage and a new BQL compat fixture for pivot-by-currency precision.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
tests/compatibility/bql-queries.toml Adds a compat fixture query covering GROUP BY currency + PIVOT BY currency precision.
crates/rustledger/src/cmd/query/output.rs Implements column-name currency-hint fallback in write_text and adds targeted unit/e2e tests.
crates/rustledger-query/src/executor/sort.rs Fixes pivot column header/row length mismatch by excluding the value column from new_columns.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

github-actions Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 74%
Full AST Match 99%
Total Files 786
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 3 commits May 8, 2026 00:24
Five real concerns from the deep review, plus the pre-existing items
filed as #1034 follow-up.

- `resolve_cell_hint` helper: width-calc and print pass now share one
  function for the row-then-column precedence. Was duplicated with a
  "must match" comment — exactly the invariant a helper locks in.
- Multi-currency PIVOT test (`test_text_pivoted_multi_currency_uses_per_column_precision`):
  USD (2dp) + JPY (0dp) on the same row, each pivoted column uses its
  own precision. The implementation always handled this correctly; now
  pinned by a test.
- Defensive regression test (`test_non_pivoted_currency_named_column_inherits_fallback_quantization`):
  pins behavior of a non-pivoted query whose column happens to be aliased
  as a tracked currency code. Today's contract is that the fallback DOES
  apply — same as PIVOT. Future tightening would be a deliberate change.
- Compat fixture removed from `bql-queries.toml`. Local verification
  against bean-query revealed bean-query's `PIVOT BY` takes TWO columns
  (pivot value + group key) where rledger takes ONE — the tools produce
  structurally different output, so a row-by-row diff would be
  permanently red. Replaced the fixture with a comment pointing to #1034
  where the reconciliation is tracked.
- PR body updated to call out the apply_pivot column-shape fix as a
  user-visible behavioral change for ALL PIVOT queries (pre-fix the SUM
  column was eating the pivoted USD value, USD column was empty).

Pre-existing items 6+7 from the review (empty-columns underflow,
degenerate value==pivot case) filed as #1034.

20 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address Copilot review on #1033: `apply_pivot` was using
`result.columns.len() - 1` to find the value column, which incorrectly
identifies a hidden ORDER BY column as the value column when the
caller has appended hidden cols (via `find_hidden_order_by_targets`
in execute_select). Fix uses `targets.len() - 1` (last visible target),
since hidden cols are always appended AFTER the visible select
targets.

Defensive `targets.is_empty()` fallback retains the old behavior
rather than panicking — the parser/planner should reject pivot_by
with empty targets, but the function shouldn't trust that.

Surfaced a deeper related bug while writing a regression test: the
strip-hidden-columns step in execute_select truncates from the END
post-PIVOT, but apply_pivot moves hidden cols out of trailing
position into group_cols, so the strip removes the pivot value column
instead. That bug is orthogonal to value_col_idx — both need fixing
for PIVOT + ORDER BY (hidden) to work correctly. Filed as item 4 on
#1034 alongside the other PIVOT robustness gaps from the review.

The value_col_idx fix on its own is correct and necessary; without it
the hidden column's values end up in pivoted output cells (e.g. dates
where SUM values should be). The strip bug just means we can't easily
write a passing integration test for the combined path until #1034
item 4 lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…down

CI clippy runs `--all-targets` which catches doc-comment lints in test
modules; my local clippy run only covered the lib targets and missed
this one. The fix is one missing pair of backticks around `group_key`
in the new pivoted-column test's docstring.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 8, 2026 06:06
@robcohen
robcohen merged commit 4906802 into main May 8, 2026
35 checks passed
@robcohen
robcohen deleted the fix/issue-1023-pivot-precision branch May 8, 2026 06:07
robcohen added a commit that referenced this pull request May 8, 2026
* fix(query): align PIVOT BY semantics with bean-query (closes #1034)

Comprehensive fix for all four items in #1034 by aligning rledger's
PIVOT BY with bean-query's semantics. Items #1 (underflow), #2
(value==pivot), #3 (semantic divergence), and #4 (ORDER BY hidden-col
strip) all collapse into one design: match upstream.

CHANGES:

1. PIVOT BY now requires exactly TWO columns
   `PIVOT BY <pivot_value_col>, <group_by_col>` — first column's values
   become new column headers, second is the GROUP BY column to keep as
   the row key. Pre-fix rledger took ONE column and synthesized the
   row-key dimension from "all other GROUP BY columns"; bean-query's
   two-column form is more explicit and the upstream-compatible path.

2. Three new validation errors (matching bean-query's wording verbatim):
   - `PivotWrongArity(n)` — "PIVOT BY requires exactly two columns"
   - `PivotSameColumn` — "the two PIVOT BY columns cannot be the same
     column" (subsumes item #2)
   - `PivotSecondNotInGroupBy` — "the second PIVOT BY column must be a
     GROUP BY column"

3. Parser clause order flipped: ORDER BY before PIVOT BY (matches
   bean-query grammar). Pre-fix rledger had PIVOT BY before ORDER BY,
   which is bean-query-incompatible at the grammar level.

4. Execution pipeline reordered:
   pre-fix:  aggregate → PIVOT → sort → strip-hidden → LIMIT
   post-fix: aggregate → sort → strip-hidden → PIVOT → LIMIT
   PIVOT now operates on the visible-only, sorted shape. The strip-
   hidden step always sees hidden cols at the trailing position
   (pre-pivot), so it correctly removes them. Item #4 (strip-from-end
   silently dropping pivot values when num_hidden > 0) dissolves.

5. Item #1 (`result.columns.len() - 1` underflow) was already
   addressed by #1033's `targets.len() - 1` change. The new apply_pivot
   no longer needs the value_col_idx heuristic at all — the value
   columns are derived from "everything except pivot and key columns".

REWRITTEN apply_pivot:
- Validates arity, distinctness, GROUP-BY membership before any work.
- Collects pivot values in first-seen order (preserves user's ORDER BY
  through to the new column header order).
- Generalizes to multiple value columns: with exactly one value col
  (the typical SUM(number) case), the pivot value alone is the new
  column header; with multiple, columns are qualified
  `<value_col_name> / <pivot_value>`.
- Bug fix from PR #1033 (column-name fallback for precision via #1023)
  remains intact — pivoted column names are still currency strings.

TESTS:
- Updated `test_parse_pivot_by` → `test_parse_pivot_by_two_columns`.
- New: `test_parse_pivot_by_one_column_parses_but_executes_with_arity_error`.
- New: `test_pivot_by_same_column_rejected` (item #2).
- New: `test_pivot_by_second_column_must_be_in_group_by`.
- New: `test_pivot_by_with_order_by_works` (regression for item #4).
- New: `test_pivot_by_with_order_by_on_hidden_column_works` (the
  killer — pre-fix this silently dropped the pivot values).
- Updated existing renderer e2e tests to use two-column form.

511 query tests + 307 rustledger lib tests + 20 renderer tests pass.
Clippy --all-targets clean. fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(query): address self-review on #1037

Five concerns from the deep review, all landed in this PR:

1. Multi-column GROUP BY migration limitation — clarified in PR body.
   Bean-query's two-arg form means rledger users with a multi-column
   GROUP BY must pick ONE column to keep as the row key; can't preserve
   a composite. Pre-fix rledger kept all non-pivot, non-value GROUP BY
   columns as the composite key, so users restructuring need to either
   drop the extra dimension or aggregate further.

2. Hash-only dedup risk fixed. Two paths:
   - `pivot_values` collection: linear-scan with structural PartialEq
     (Value is Eq but not Hash; pivot values are typically small,
     so O(N) per insert is fine).
   - `group_index` and `pivot_lookup`: hash-bucket + structural
     PartialEq inside the bucket. Same correctness as a HashMap<Value, …>
     would give but works around Value's missing Hash impl.

3. Multi-value-column case now tested. New
   `test_pivot_by_multi_value_column_qualifies_headers` exercises the
   `value_col_idxs.len() > 1` branch with `SUM + COUNT` side-by-side.
   Confirmed the qualified-header format `<value_col_name> / <pivot_value>`
   actually fires.

4. Implicit GROUP BY + PIVOT now produces a specific error. New
   `PivotWithoutGroupBy` variant fires when `query.group_by` is None.
   Pre-fix this would fall through to the misleading
   `PivotSecondNotInGroupBy` message. New test
   `test_pivot_by_without_group_by_clause_rejected` pins the message.

5. `QueryError` is now `#[non_exhaustive]`. Adding variants no longer
   breaks downstream exhaustive matches.

Bonus: removed the dead `pivot_exprs.is_empty()` early return (parser
guarantees ≥ 1; replaced with `debug_assert!`) and added a comment
about the hidden-cols-trailing invariant the default-sort-by-first-column
block depends on.

518 query tests pass (137 lib + 365 integration + 13 prop + 3 doc).
Clippy --all-targets clean. Fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(query): address self-review v2 on #1037

Five items from the second deep review:

1. Docstring drift on apply_pivot. Validation rules block now lists 4
   rules (was 3), with the bean-query parity claim narrowed to rules
   1-3 — `PivotWithoutGroupBy` is rledger-specific because bean-query's
   grammar typically rejects PIVOT-without-GROUP-BY earlier.

2. Multi-row same `(key, pivot_value)` pair: documented as "first wins"
   in the function's new "Input contract" section. Aggregate queries
   (the typical caller) always satisfy uniqueness via GROUP BY; the
   contract is for non-aggregate or pre-aggregation callers. Test
   `test_pivot_by_duplicate_key_pivot_pairs_first_wins` pins the happy
   path; the policy itself is documented + asserted via `find` returning
   the first match.

3. `Vec<&&Row>` → `Vec<&Row>` cleanup. Use `for &row in &group_rows`
   to destructure the iter item once. Same behavior, one fewer borrow
   level — pure readability.

4. Edge case test added: `test_pivot_by_empty_result_yields_key_column_no_rows`.
   When the pre-pivot result is empty (e.g. WHERE filters everything),
   PIVOT now produces a single-column header (the key column) with
   zero rows. Pinning so a future "skip PIVOT on empty input"
   optimization doesn't accidentally also skip the header.

5. The `value_col_idxs.len() == 1` special case in column-name
   construction now has an inline comment explaining the bean-query
   alignment: single-aggregate users expect bare pivot value as
   header (e.g. `USD`), multi-aggregate qualifies with the value
   column name to disambiguate.

Bonus: clippy `--all-targets` flagged a 2-arm `match` on `Option`;
converted to `if let` per `clippy::single_match`.

10 pivot tests pass (was 8), 518 total query tests pass. Clippy
clean. Fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(query): handle Function exprs in find_pivot_column + tighten test

Address Copilot inline comments on PR #1037:

- Comments 1-3 (hash-only dedup): already addressed by commit 6813f31
  in this PR. New code uses hash-bucket + structural-eq verify inside
  the bucket — defense against u64 collisions.

- Comment 4: find_pivot_column's `_` arm rejected ALL non-Column non-
  Literal exprs with "PIVOT BY must reference a column name or index",
  meaning Function exprs (like `YEAR(date)`) couldn't resolve at all.
  This had two fallout consequences:
    * `PIVOT BY YEAR(date), account` would error before even reaching
      the GROUP BY membership check.
    * `GROUP BY YEAR(date)` exprs would silently fail to resolve via
      `find_pivot_column(...).ok()` in the membership iteration,
      misreporting `PivotSecondNotInGroupBy` for valid queries.
  Added an explicit `Expr::Function` arm that mirrors `sort_results`'s
  ORDER BY two-tier resolution: try the function name first
  (e.g. column `YEAR` for expr `YEAR(date)`), then fall back to the
  full expression string. The `_` arm now also handles other complex
  exprs by string-match (matches the hidden-column alias convention).

- Comment 5: `test_pivot_by_with_order_by_works` previously asserted
  only "result non-empty" + "account column present" — would have
  passed even if PIVOT didn't run. Strengthened with four assertions:
  the key column (`account`) survives, at least one pivoted column
  (`USD`) appears, and the original `currency` and `SUM` columns are
  GONE (their values moved into the pivoted cells).

10 pivot tests + 518 total query tests pass. Clippy --all-targets
clean. Fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BQL: PIVOT discards GROUP BY currency context, regressing #988 fix for pivoted output

2 participants