Repository navigation
fix(query): align PIVOT BY semantics with bean-query - #1037
Conversation
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]>
robcohen
left a comment
There was a problem hiding this comment.
Self-review pass. Five real concerns, two minor observations.
Real concerns
1. Migration is more invasive than the PR description claims.
The PR body says "Migration is mechanical: add the GROUP BY column they want as the row key" with a one-column example. The actual migration story for multi-column GROUP BY is more limiting:
-- Pre-fix: rows keyed by (account, year) — both visible
SELECT account, year, currency, SUM(amount)
GROUP BY account, year, currency
PIVOT BY currency
-- Post-fix: must pick ONE row key. Can't preserve both account AND year:
PIVOT BY currency, account -- year drops out of the row key
PIVOT BY currency, year -- account drops outBean-query has the same limitation (it's a fundamental property of their two-column form), so this is upstream-compatible behavior — but users who relied on rledger's "keep all other GROUP BY cols as composite key" semantics need to either restructure their query or aggregate further. Worth being explicit in the PR body so users can plan around it.
2. Hash-only dedup can collide silently.
let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();
for row in &result.rows {
let v = row.get(pivot_value_col_idx).cloned().unwrap_or(Value::Null);
let h = hash_single_value(&v);
if seen.insert(h) { pivot_values.push(v); }
}If two distinct Values hash to the same u64, the second one is silently dropped from pivot_values and its data ends up under the first one's column header. Probability ≈ 2⁻⁶⁴ per pair, so never in practice — but the pattern is already used in the existing pivot_lookup: HashMap<u64, &&Row> (line 296), so this PR doesn't make it worse. Worth filing a follow-up to swap to HashMap<Value, …> with structural Eq/PartialEq (Value already implements them).
3. Multi-value-column case not tested.
The new layout-string logic explicitly designs for multiple value columns:
if value_col_idxs.len() == 1 {
new_columns.push(pv_str);
} else {
for &vci in &value_col_idxs {
new_columns.push(format!("{} / {pv_str}", result.columns[vci]));
}
}But no test exercises the > 1 value cols branch. A query like SELECT account, currency, SUM(number), COUNT(*) GROUP BY 1, 2 PIVOT BY currency, account would hit the multi-value path with output columns like ["account", "SUM(number) / USD", "COUNT(*) / USD", "SUM(number) / EUR", ...]. Either add a test or #[cfg(test)] panic!() the multi-value path until someone needs it (YAGNI — bean-query's multi-value behavior should be the reference if/when it's added).
4. Implicit GROUP BY (no GROUP BY clause but aggregates in SELECT) + PIVOT errors with PivotSecondNotInGroupBy.
let key_in_group_by = group_by.as_ref().is_some_and(|gb| { ... });
if !key_in_group_by { return Err(QueryError::PivotSecondNotInGroupBy); }group_by.as_ref() is None when there's no explicit GROUP BY clause. The is_some_and short-circuits to false. Result: PivotSecondNotInGroupBy for ANY PIVOT on an implicit-grouping query.
This is probably correct (PIVOT BY without a key dimension is undefined), but it's not what the error message says. Either:
- Add a more specific error variant:
PivotRequiresExplicitGroupBy. - Document this case: implicit grouping is incompatible with PIVOT.
- Add a test pinning the current (somewhat misleading-message) behavior.
5. QueryError is not #[non_exhaustive].
pub enum QueryError {
...
PivotWrongArity(usize),
PivotSameColumn,
PivotSecondNotInGroupBy,
}Downstream consumers that match exhaustively on QueryError will fail to compile after this PR. Pre-existing concern (the enum has had additions before), but each addition compounds it. If we want a stable public API, slap #[non_exhaustive] on the enum either in this PR or a follow-up.
Minor observations
6. pivot_exprs.is_empty() check is dead code today.
if pivot_exprs.is_empty() { return Ok(result.clone()); }The parser uses at_least(1) for pivot_by_clause, so Option<Vec<Expr>> is either None or Some(vec) with ≥ 1 element. The caller (execute_select) only calls apply_pivot inside if let Some(pivot_exprs) = .... So pivot_exprs.is_empty() is unreachable in practice. Defensive-but-harmless. Could remove or convert to a debug_assert! for clarity.
7. The default-sort-by-first-column block runs pre-strip, so it sorts on the original column layout.
} else if has_grouping && !result.rows.is_empty() && !result.columns.is_empty() {
let first_col = result.columns[0].clone();
let default_order = vec![OrderSpec {
expr: Expr::Column(first_col),
direction: SortDirection::Asc,
}];
self.sort_results(&mut result, &default_order)?;
}result.columns[0] at this point is the first VISIBLE select target (hidden cols are appended later — verified at execution.rs:65 where extended_targets is built). Correct as-is, but the invariant "hidden cols are appended AFTER visible" is implicit. Worth a one-line comment so a future refactor doesn't reorder them and silently break this default-sort path.
Verdict
Concerns 1 and 4 are about clarity/correctness signaling and want either doc updates or tests. 2 and 5 are pre-existing code-quality issues that this PR puts in the spotlight; both could be follow-ups. 3 is "untested-by-design" — pin a panic!() or add a test. 6 and 7 are micro-comments.
Want me to land 1 (PR body update), 3 (multi-value test or panic), and 4 (test pinning implicit-grouping behavior) in a follow-up commit on this branch? 2 and 5 belong in their own follow-up issue. 6 and 7 can ride along.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-05-08)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Aligns rustledger-query’s PIVOT BY behavior and clause ordering with bean-query semantics (issue #1034), including executor validation and a reordered execution pipeline so pivoting happens after sorting and hidden-column stripping.
Changes:
- Flip SELECT clause parsing order to
ORDER BYbeforePIVOT BY(bean-query compatible). - Reorder executor pipeline to
aggregate → sort → strip-hidden → pivot → limit, and rewriteapply_pivotfor two-columnPIVOT BY+ new validation errors. - Update and add integration/E2E tests to cover the new syntax and regressions (including ORDER BY on hidden columns).
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger/src/cmd/query/output.rs | Updates renderer E2E test query strings to the new two-arg PIVOT BY syntax. |
| crates/rustledger-query/tests/bql_integration_test.rs | Adds/updates PIVOT BY parsing + execution behavior tests, including ORDER BY interaction regressions. |
| crates/rustledger-query/src/parser.rs | Reorders clause parsing to place ORDER BY before PIVOT BY. |
| crates/rustledger-query/src/executor/sort.rs | Rewrites apply_pivot for two-column semantics + validation; preserves pivot column order based on post-sort row order. |
| crates/rustledger-query/src/executor/execution.rs | Reorders execution so sorting/hidden-column stripping happen before pivot. |
| crates/rustledger-query/src/error.rs | Introduces new PIVOT validation errors matching bean-query wording. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| 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
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]>
robcohen
left a comment
There was a problem hiding this comment.
Self-review pass v2 (after the 6813f31 follow-up). Three real items, two minor.
Worth fixing
1. Docstring lists 3 validation rules but there are 4 now.
/// **Validation** (matches `_compile_pivot_by` in
/// `beanquery/compiler.py`):
/// - exactly two pivot columns (`PivotWrongArity` otherwise)
/// - the two columns must differ (`PivotSameColumn` otherwise)
/// - the second column must be a GROUP BY target
/// (`PivotSecondNotInGroupBy` otherwise)
I added PivotWithoutGroupBy but forgot to update the docstring. Should add a fourth bullet:
/// - PIVOT requires an explicit GROUP BY clause
/// (`PivotWithoutGroupBy` otherwise — distinct from
/// `PivotSecondNotInGroupBy`, which is for "GROUP BY exists but the
/// key column isn't in it")
Also worth noting: PivotWithoutGroupBy is rledger-specific — bean-query doesn't have it because their grammar requires the second pivot column to be in GROUP BY (and they don't reach apply_pivot when GROUP BY is absent). The docstring's "matches _compile_pivot_by" claim is now slightly overstated.
2. Multi-row same (key, pivot_value) pair silently picks the first row.
let matched = pivot_lookup.get(&pv_hash).and_then(|bucket| {
bucket.iter().find(|row| ...)
});bucket.iter().find(...) returns the FIRST match. If the input has two rows with the same (key, pivot_value) pair — say (Assets, USD, 100) and (Assets, USD, 200) — the second row's value silently disappears.
In practice this can't happen post-aggregation: GROUP BY account, currency produces one row per (account, currency) pair. But the function doesn't enforce that the input came from aggregation. A caller that constructs PIVOT input from non-aggregated data (or a future code path that bypasses the validator) would get silently-wrong output.
Mitigations to consider:
- Test: add
test_pivot_by_with_duplicate_key_pivot_pairs_uses_firstto pin the current behavior. Cheapest. - Comment: clarify "expects one row per (key, pivot_value) pair — typically guaranteed by GROUP BY".
debug_assert!: panic on the duplicate case. Catches programmer errors but ships fine.
I'd lean toward "comment + test pinning the behavior" — fix-it-if-it-becomes-a-problem.
3. Vec<&&Row> is an awkward type, simplifies to Vec<&Row>.
let mut pivot_lookup: HashMap<u64, Vec<&&Row>> = HashMap::new();
for row in &group_rows {
pivot_lookup.entry(...).or_default().push(row);
}group_rows: Vec<&Row>, so iterating &group_rows yields &&Row. The &&Row works but reads like a typo. Cleaner:
let mut pivot_lookup: HashMap<u64, Vec<&Row>> = HashMap::new();
for &row in &group_rows {
pivot_lookup.entry(...).or_default().push(row);
}Same behavior, one fewer borrow level. Pure readability win.
Minor (not blockers)
4. Untested edge cases. Empty result with PIVOT, ALL-NULL pivot values, NULL key column values. Each produces defensible-but-not-pinned output. Adding 1–2 tests for the canary cases would prevent silent regressions, but YAGNI is also defensible since these don't occur in real queries.
5. The if value_col_idxs.len() == 1 branch in column-name construction is a small special case. Without it, columns would always be <value_col_name> / <pivot_value>. With it, they're just <pivot_value>. The single-value case matches bean-query (which uses just the pivot value), so it's correct, but the asymmetry is worth a one-line comment explaining the bean-query alignment.
Verdict
Items 1–3 are easy fixes (docstring update, comment + test, type cleanup). 4 and 5 are documentation polish.
Want me to land 1+2+3 in a follow-up commit on this branch?
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]>
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]>
Summary
Closes #1034. All four items in that issue collapse into one fix: align rledger's PIVOT BY with bean-query's semantics.
result.columns.len() - 1underflowapply_pivotdoesn't needvalue_col_idxat allvalue_col_idx == pivot_col_idxPivotSameColumnerror, bean-query message verbatimPIVOT BY <pivot_value_col>, <group_by_col>What changed
Syntax (breaking — pre-existing PIVOT BY queries will error):
First column's values become new column headers; second is the GROUP BY column kept as the row key.
Three new validation errors (matching bean-query's
_compile_pivot_bywording verbatim for upstream parity):PivotWrongArity(n)PIVOT BY requires exactly two columns, got NPivotSameColumnthe two PIVOT BY columns cannot be the same columnPivotSecondNotInGroupBythe second PIVOT BY column must be a GROUP BY columnParser 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.
Execution pipeline reordered:
PIVOT now operates on the visible-only, sorted shape. The strip step always sees hidden cols at trailing positions (pre-pivot), so it correctly removes them. Item #4 dissolves cleanly without needing to track hidden col indices through PIVOT's reshape.
Rewritten
apply_pivot:SUM(number)case), the pivot value alone is the new column header; with multiple, columns are qualified<value_col_name> / <pivot_value>.column_currency_hintsfallback from fix(query): per-currency precision through PIVOT via column-name fallback #1033 (precision via BQL: PIVOT discards GROUP BY currency context, regressing #988 fix for pivoted output #1023) remains intact — pivoted column names are still currency strings.Test plan
New tests:
test_parse_pivot_by_two_columns— bean-query-compatible form parses.test_parse_pivot_by_one_column_parses_but_executes_with_arity_error— pins the parser/executor split.test_pivot_by_same_column_rejected— item chore: update dependencies and fix deny.toml for cargo-deny v0.18 #2.test_pivot_by_second_column_must_be_in_group_by— new validation.test_pivot_by_with_order_by_works— regression for item refactor: extract validate_transaction into focused helper functions #4 (visible-col case).test_pivot_by_with_order_by_on_hidden_column_works— the killer test for item refactor: extract validate_transaction into focused helper functions #4. Pre-fix this query silently dropped the pivot values; post-fix the USD column is intact and the hiddenMIN(date)is correctly stripped.Updated tests: existing renderer e2e tests in
cmd::query::outputupdated to use two-column form.cargo clippy --all-features --all-targets -- -D warningsclean.cargo fmt --all -- --checkclean.Migration impact
Any existing user PIVOT BY queries with one column will now error with
PivotWrongArity(1). Most queries migrate by adding the GROUP BY column to keep as the row key:Multi-column GROUP BY caveat. Pre-fix rledger kept ALL non-pivot, non-value GROUP BY columns as a composite row key. The new bean-query-aligned form lets you keep only ONE:
Bean-query has the same limitation (it's a property of the two-column form), so this is upstream-compatible behavior. Users who relied on the composite-key semantics need to either restructure (drop the extra dimension) or aggregate further.
Implicit GROUP BY. Queries that aggregate without an explicit
GROUP BYclause (SELECT SUM(amount) PIVOT BY currency, account) are now rejected with the newPivotWithoutGroupByerror, distinct fromPivotSecondNotInGroupBy.The post-fix output shape is also bean-query-compatible (key column first, then pivot-value columns) — that's a shape change for PIVOT users, but the pre-fix shape was inconsistent in its own right (column header included the value column but rows didn't, fixed in #1033).
🤖 Generated with Claude Code