Repository navigation
feat(query): add six missing beanquery BQL functions - #2155
Conversation
Closes #2153, except for `repr`, which is argued against below. `COMMODITY`, `COMMODITY_META`, `CURRENCY_META`, `FINDFIRST` and `YEARMONTH` had no implementation. `HAS_ACCOUNT` did: it has always worked as a FROM predicate, and was simply not reachable from a projection, so `BALANCES FROM has_account('Assets')` returned rows while `SELECT has_account('Assets')` raised `no function matches`. Placement follows the split already documented in `evaluate_function`. `HAS_ACCOUNT` asks about the whole entry, so like the META family and WEIGHT it stays on the lazy path where the row's transaction is still in scope. The other five need only their argument values and go through the shared value registry. `COMMODITY_META` / `CURRENCY_META` read the `commodity` directive rather than any posting, so the executor now collects that metadata in the same directive walk that already builds `account_info`. Both constructors were updated; missing the second would have left the sourced-directives path answering Null for every currency. Each function is pinned against what bean-query 3.2.3 returns for the same ledger, including the cases that are easy to fake: a currency with no `commodity` directive is Null rather than an error, `FINDFIRST` with no match is Null, and `HAS_ACCOUNT` is asserted false as well as true. The test also asserts the FROM spelling still selects the entry the projection reports true for, since those are now two paths to one answer. Not implementing `repr`. beanquery's version returns Python's own object syntax: `Decimal('10.00')`, `datetime.date(2024, 2, 1)`, `frozenset({'t1'})`. Matching it means emitting CPython type names from Rust, which describes another language's runtime rather than the ledger, and would pin us to CPython's formatting for every value type we ever add. Left absent deliberately, with the reasoning recorded in the test that covers the rest. One known difference on the one-argument form: bean-query's metadata dicts carry synthetic `filename` and `lineno` keys and ours do not. That is pre-existing and not specific to these functions, and it points both ways -- `entry_meta("filename")` returns a path here and None in bean-query. Verified: 7 of 67 beanquery functions were unreachable before this change, 1 after. Clippy clean on 1.96 and on CI's 1.97. The 34 query shapes swept while finding #2153 are unchanged, and the new test was confirmed to fail on a wrong expectation before being trusted. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 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?
|
…ity must reject a position Two defects found reviewing the previous commit against bean-query. A currency declared twice resolved to the FIRST `commodity` directive. The collection used `or_insert_with`, so a ledger with `commodity USD` at the top of the year and again in June answered with January's metadata where bean-query answers with June's. Nothing else in the query output reveals which directive was used, so this would have been invisible outside a side-by-side comparison. Now `insert`, in both constructors. `COMMODITY` accepted a position. bean-query types it strictly as `commodity(Amount)` and rejects `commodity(position)` at compile time, so we were accepting an input it refuses. The comment justifying the extra arm said `cost()` "may hand back either" an amount or a position; that is not true, `cost()` yields an Amount, which the `commodity(cost(position))` case demonstrates by returning the COST currency rather than the units currency. The arm was added on a premise that does not hold, so it is gone and the error message no longer advertises positions. Both are now pinned. The duplicate-declaration test was confirmed to fail against the old `or_insert_with` (`left: "First", right: "Second"`) before being trusted, and `COMMODITY(position)` is asserted to error rather than merely to return something. Re-verified against bean-query 3.2.3: duplicate declaration gives Second on both sides, `commodity(position)` errors on both, and `commodity(cost(position))` / `commodity(units(position))` still give USD and HOOL respectively. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
There was a problem hiding this comment.
Pull request overview
Adds missing Beanquery BQL functions to the rustledger-query executor so they can be used in SELECT projections (and aligns HAS_ACCOUNT behavior between projection vs FROM usage), with new regression tests pinned to bean-query outputs.
Changes:
- Extend the query executor with implementations for
COMMODITY,COMMODITY_META/CURRENCY_META,FINDFIRST,YEARMONTH, and projection support forHAS_ACCOUNT. - Add executor-side caching of
commoditydirective metadata to back*_METAlookups. - Add a new regression test covering the newly-supported functions and key null/false cases.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.
| File | Description |
|---|---|
| crates/rustledger-query/src/executor/mod.rs | Adds commodity metadata caching and implements the missing/previously-unreachable BQL functions in the executor. |
| crates/rustledger-query/src/executor/tests.rs | Adds a new regression test exercising the newly-supported functions against expected bean-query results. |
Suppressed comments (1)
crates/rustledger-query/src/executor/mod.rs:286
- Same as the non-sourced constructor:
commodity_metausesor_insert_with, which preserves only the firstcommoditydirective per currency. This can makeCOMMODITY_META/CURRENCY_METAreturn stale metadata if later directives override earlier ones.
Directive::Commodity(commodity) => {
commodity_meta
.entry(commodity.currency.to_string())
.or_insert_with(|| commodity.meta.clone());
}
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
… the test Review follow-ups on #2155. `HAS_ACCOUNT` had two implementations after the previous commit: the FROM predicate in `evaluate_from_filter` and the new projection arm. They answered the same question about the same entry and had already drifted in their error text, which is exactly how the pair would keep drifting. Both now call `Executor::entry_has_account`. The test's `one()` helper read `rows[0][0]`. These functions evaluate per posting and the fixture has two, so a second row disagreeing with the first would not have been noticed. It now asserts every row matches, and names the offending index when one does not. Confirmed by pointing the helper at `SELECT account`, whose rows legitimately differ: `row 1 disagrees with row 0`. `FINDFIRST` cloned the whole string set before scanning. It now scans the borrowed slice and clones only the element that matches, so a hit on the first tag no longer copies the rest. The FROM spelling still returns both accounts for `BALANCES FROM has_account('Assets')` after the extraction, and the existing assertion that the two spellings agree still passes. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Codecov flagged 36 uncovered lines in `evaluate_function_on_values`, and almost all of them were the guard arms added with these functions. Those branches were verified by hand against bean-query while writing the feature, which is worth nothing once someone refactors the match. Manual verification does not survive; a test does. Covers three shapes per function where they apply: wrong arity, wrong argument type, and Null in. The Null rows are the ones worth having. bean-query answers Null rather than raising for a Null input, so an arm that errored instead would turn a query over a ledger with one missing payee into a hard failure, and `payee` is genuinely Null on the fixture rather than a hand-built value. Invalid regexes are asserted to error rather than to behave as "matches nothing", which would silently answer false for a typo'd pattern. Confirmed the error assertions fail for the intended reason and not because the query failed to parse: each message names its own function (`COMMODITY expects an amount`, `YEARMONTH expects a date`). Confirmed the test bites by flipping a Null expectation to `Boolean(true)` (`left: Null, right: Boolean(true)`). Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ata form Coverage pointed at the one block of #2153's change that no test reached: the `Directive::Commodity` arm inside `new_with_sources`. That is the arm the commit adding it singled out as easy to miss, on the grounds that the two constructors build their own caches and a lookup added to one and not the other fails only on the path that constructor serves. The claim was right and went untested, which is the same shape as the bug it warns about. `new_with_sources` is the CLI and LSP path, so it is where a user would actually hit it. Deleting that arm now fails the new test with `left: Null, right: "US Dollar"`, which is exactly the described failure: metadata resolves under `Executor::new` and comes back Null under the sourced constructor. Verified by removing it, running, and restoring. Also covers the one-argument form returning a populated metadata map. The existing tests only reached that spelling on the missing-currency path, where it returns Null and the `Value::Metadata` construction never runs. Patch coverage went 65% to 82% with the previous commit; this takes the remaining structural gap. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Six user-facing functions landed with no way to discover them. The BQL
reference keeps curated tables per category and none of the six appeared in
any of them, so the only route to `yearmonth` or `commodity_meta` was reading
the executor.
Each entry states something checked against the running binary rather than
inferred from the implementation:
- `commodity()` versus `currency()` is the entry most worth having. They
overlap and are not interchangeable. `commodity()` takes an amount, which
is bean-query's spelling, so `commodity(units(position))` and
`commodity(cost(position))` separate the units currency from the cost
currency -- `HOOL` and `USD` on `2 HOOL {10.00 USD}`. `currency(position)`
takes a position, always answers about units, and is a rustledger extension
that bean-query rejects outright. Anyone writing a query to run under both
wants `commodity()`, and nothing said so.
- `has_account()` asks about the ENTRY, so it is true on every row of a
matching transaction, including postings to other accounts. Verified: on a
transaction touching Assets:A and Equity:O, both rows report true. Without
that sentence the natural reading is per-posting, which would quietly make
`WHERE has_account(...)` look broken.
- Commodity metadata gets its own table next to the meta family, because it
resolves from a `commodity` directive rather than from a transaction or
posting, and the existing section is entirely about that distinction. The
last-declaration-wins rule is stated there too, since it is otherwise only
discoverable by declaring a currency twice.
`repr` stays undocumented, matching its absence from the implementation.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…low-up Reading the finished diff end to end turned up a doc describing a design this branch had already replaced. `build_entries_table` still explained that `meta` and `_entry_meta` carry the same value and that the underscore copy cannot be renamed. Both sentences were true when written and false two commits later: the duplicate column was removed precisely because storing the map twice cost a deep clone per entry. A reader would have gone looking for `_entry_meta` in that table's column list and not found it. Now describes what is there: metadata in one column, `ENTRY_META` resolving through the fallback, and why `#postings` still needs its own `_entry_meta` (there `meta` is the POSTING's metadata and `_entry_meta` the TRANSACTION's, two different maps on one row). This is the same defect an automated reviewer caught on #2155, where a comment justified an argument type using a premise that no longer held. A stale comment that merely repeats the code is noise; one that explains why something must be a certain way, after that stopped being true, actively misleads. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
* fix(query): give #entries the five columns bean-query exposes `SELECT * FROM #entries` returned 11 columns against bean-query's 16. Missing: `year`, `month`, `day`, `description`, `meta`. None of them needed building. Every name already resolved against `#postings`, and `description` is the same "payee | narration" shape that table already produces. The `#entries` schema simply did not list them, so `SELECT year FROM #entries` -- a query that runs under bean-query -- failed here with `column 'year' not found`. Column order now matches bean-query position for position, not just as a set. `SELECT *` is positional for anyone reading rows as tuples, so getting the membership right and the order wrong would still break them. Date parts come from the entry's own date rather than from a transaction, so they are populated for every directive type: bean-query reports `year` on an `open`, and now so do we. `description` is Null on a non-transaction, matching how `payee` and `narration` already behave there. `meta` and `_entry_meta` deliberately hold the same value. The underscore copy cannot be renamed: `ENTRY_META` resolves through it, and `wildcard_hidden` uses the underscore prefix to keep helpers out of `SELECT *`. Verified the hidden spelling still answers, that `ENTRY_META` / `ANY_META` still work, and that `_entry_meta` still does not leak into the wildcard now that a visible `meta` sits beside it. Values checked row by row against bean-query 3.2.3 on a ledger mixing opens, a payee transaction, a narration-only transaction and a note: identical on all five columns. The test asserts order and was confirmed to fail with `year` removed before being trusted. `#transactions.meta` is left for #2154. bean-query carries it as a column but excludes it from `SELECT *`, and `wildcard_hidden` keys on the name alone with no table context. Adding it visibly would trade a missing column for a wildcard that returns 8 where bean-query returns 7, which is a worse bug than the one being fixed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * refactor(query): one description helper, and stop storing entry metadata twice Review follow-ups on #2157. `"payee | narration"` was written out twice, once for `#entries` and once for `#postings`. Both describe the same transaction, so a change to the separator or the no-payee case on one side would have produced two tables disagreeing about the same row. Now one `transaction_description`. `#entries` stored its metadata in two columns, `meta` and `_entry_meta`, holding the same map. That cost a deep clone per entry on every query that touches the table, projected or not. The table now carries it once, and `eval_meta_on_table_row` falls back to the visible `meta` when the helper column is absent. The fallback cannot misfire on `#postings`, which is the case that matters: that table carries `meta`, `_entry_meta` and `_posting_meta` as three DISTINCT values, so the helper column is present and the fallback is never reached. Confirmed by comparing against main rather than by reading the code -- `ANY_META("postkey")` returns `postval` on both, and `META` / `ENTRY_META` still separate posting metadata from entry metadata on the same row. `ENTRY_META` and `ANY_META` now resolve on `#entries` too, returning the transaction's value and Null on directives that carry none. The test previously asserted `_entry_meta` was addressable on `#entries`. That was pinning the duplicate storage, so it now asserts the opposite, plus the part a user actually depends on: the functions that used to read it still answer. `SELECT *` unchanged at 31 columns for `#postings` and 16 for `#entries`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * test(query): pin that the entries metadata fallback leaves #postings alone Coverage showed the untested half of the fallback was the branch that takes the helper column when it IS present. That is the branch the safety argument rests on, so the claim "cannot misfire on #postings" was the part with no test behind it. `#postings` is where a wrong answer would be silent rather than loud: `meta` there is the POSTING's metadata and `_entry_meta` is the TRANSACTION's, two different maps on one row. Resolving `ENTRY_META` through `meta` would return posting metadata and look plausible. The fixture sets the same key at both levels with different values, so an accessor reading the wrong column returns the wrong string rather than Null, and all three of `META`, `ENTRY_META` and `ANY_META` are pinned on the same row. Confirmed it bites before trusting it: making the fallback unconditional fails with `ENTRY_META on #postings must read the transaction's metadata, not the posting's`. The one remaining uncovered line is the `_ => (Null, Null, Null)` arm for date parts. Every directive variant maps to `Value::Date`, so it is defensive rather than reachable; the alternative is an unwrap, which is worse. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * docs(query): correct the entries-table note left stale by its own follow-up Reading the finished diff end to end turned up a doc describing a design this branch had already replaced. `build_entries_table` still explained that `meta` and `_entry_meta` carry the same value and that the underscore copy cannot be renamed. Both sentences were true when written and false two commits later: the duplicate column was removed precisely because storing the map twice cost a deep clone per entry. A reader would have gone looking for `_entry_meta` in that table's column list and not found it. Now describes what is there: metadata in one column, `ENTRY_META` resolving through the fallback, and why `#postings` still needs its own `_entry_meta` (there `meta` is the POSTING's metadata and `_entry_meta` the TRANSACTION's, two different maps on one row). This is the same defect an automated reviewer caught on #2155, where a comment justified an argument type using a premise that no longer held. A stale comment that merely repeats the code is noise; one that explains why something must be a certain way, after that stopped being true, actively misleads. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5 <[email protected]>
Reading the finished diff turned up a doc describing a design this branch tried and abandoned. `lookup_dated_at` said the chained lookup needs the rate's date "so it can value the second leg as of that same moment". That was true of the anchoring attempt and false once it was backed out: both legs are dated the caller's way now, and the date is used for RANKING paths rather than for pinning one leg to the other. A reader would have gone looking for anchoring logic that is not there. Same defect as the one an automated reviewer caught on #2155 and I caught on #2157: a comment that merely restates code is noise, but one explaining why something must be a certain way, after that stopped being true, actively misleads. Also folds two near-verbatim copies of the ranking rationale into one. `get_chained_price` and `best_chain` each carried the full explanation of path selection and the stale-chain policy; the caller now points at the function that owns the logic. Two copies of an argument drift the same way two copies of a sort do, which is what this branch already fixed in the code. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
) * test(query): pin the chained-price tie-break, and say what it is Two of the three items in #2152. The third is left deliberately, below. `get_chained_price` documents that "intermediates are tried in sorted order so the result is deterministic when several paths exist". Nothing tested it. The three existing chained-price tests each build a single chain, so the sort could have been dropped in a refactor and all three would still pass. Both `get_chained_price` and `get_chained_latest_price` carry their own copy of the sort line, so both were unheld. The new test builds two complete same-dated paths worth deliberately different amounts, 20.00 via AAA and 50.00 via MMM, and asserts the alphabetically first wins in both functions. Equal-valued paths would have passed whichever way iteration went, which is the property being detected. It also rebuilds the database eight times, because the underlying map is a hash map and insertion-order luck shows up across constructions rather than within one run. Confirmed it bites, once per function: removing the sort from `get_chained_price` fails it, and so does removing the sort from `get_chained_latest_price`. Two copies, two independent proofs. The doc now says what the guarantee is worth. Deterministic is not principled: 20.00 wins because `AAA` sorts before `MMM`, and nothing in the output mentions that 50.00 was equally available. A reader of the old sentence could reasonably assume the choice meant something. It also records that legs are dated independently, so a 2010 leg times a 2024 leg yields a current valuation with no diagnostic. NOT fixing the staleness half. There is no precedent to align with: the only age concept in the tree is the price-FETCH cache, which governs how long a downloaded quote is reused rather than whether a rate is too old to value with. A bound would be new user-facing policy -- someone has to choose a window, choose error versus warn, and choose whether reports differ -- and that is a decision to make deliberately, not to smuggle in as a bug fix. #2152 stays open for it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * fix(query): rank chained price paths by evidence, not by spelling Replaces the alphabetical tie-break in chained lookups. When several one-hop routes exist, the winner is now the one whose OLDEST leg is most recent, then the one whose legs sit closest together, then the currency name so the order stays total and independent of hash iteration. A chain is only as current as its oldest leg. Multiplying a 2010 `A -> B` by a 2024 `B -> C` yields a figure that looks 2024-dated and rests on 2010 data, so ranking by that date is what makes the chosen path the best-supported one rather than the alphabetically luckiest. The corpus made the case. Chaining is needed in 54 of 761 files across 1152 pairs, and multi-path ambiguity reaches only 2 of them -- but the real one is `ledger_prices.beancount`, BTC to CNY via USD or USDT, where the answers are 125,856 and 74,763 CNY. A 68% spread, and the paths do not disagree about BTC: one route's quotes stop 16 months earlier. We returned the right number because `USD` sorts before `USDT`. A currency named `AUSDT` would have flipped it. Both lookups now share one ranking through `best_chain`; the latest-rate variant used to carry its own copy of the sort and could drift from the as-of one. NOT refusing stale chains, after trying it. beancount's `prices.project()` anchors its second leg to the first leg's date and declines when no rate existed then, and porting that rule here was wrong for two reasons. It is built for a different question -- `project` synthesizes a price SERIES at the base commodity's own dates, while this answers "value as of D" -- and it refuses when the second leg is merely NEWER, which broke `test_chained_lookup_uses_newest_rate_per_leg`: valuing an 07-10 close with an 07-11 rate is ordinary, not suspect. More decisively, a stale DIRECT price is returned here without complaint, so refusing only the chained case would be an inconsistent rule rather than a stricter one. Verified: the era-mixing fixture from #2152 is unchanged in value, the freshness case now picks the 2020 route over the alphabetically-first 2019 one, and the booked-value gate against beancount reports `known 34, found 34, new 0` across 761 files, so no divergence moved. Both properties are pinned and both proofs are real: ranking the name ahead of freshness fails with `left: 74763, right: 125856`, and removing the name tie-break fails the stability assertions. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr * docs(query): correct the note left stale by backing out anchoring Reading the finished diff turned up a doc describing a design this branch tried and abandoned. `lookup_dated_at` said the chained lookup needs the rate's date "so it can value the second leg as of that same moment". That was true of the anchoring attempt and false once it was backed out: both legs are dated the caller's way now, and the date is used for RANKING paths rather than for pinning one leg to the other. A reader would have gone looking for anchoring logic that is not there. Same defect as the one an automated reviewer caught on #2155 and I caught on #2157: a comment that merely restates code is noise, but one explaining why something must be a certain way, after that stopped being true, actively misleads. Also folds two near-verbatim copies of the ranking rationale into one. `get_chained_price` and `best_chain` each carried the full explanation of path selection and the stale-chain policy; the caller now points at the function that owns the logic. Two copies of an argument drift the same way two copies of a sort do, which is what this branch already fixed in the code. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr --------- Co-authored-by: Claude Opus 5 <[email protected]>
Closes #2153, except for
repr, which I argue below should stay absent.What was missing, and why they differ
Five had no implementation at all:
COMMODITY,COMMODITY_META,CURRENCY_META,FINDFIRST,YEARMONTH.HAS_ACCOUNTis a different case and the more interesting one. It has always worked as aFROMpredicate and was simply unreachable from a projection:So this is one name that resolved on one path and not its sibling.
Placement
evaluate_functionalready documents the split: functions needing the row's context stay on the lazy path, everything else goes through the shared value registry.HAS_ACCOUNTasks about the whole entry, so it joinsMETAandWEIGHTon the lazy path. The other five need only their argument values.COMMODITY_META/CURRENCY_METAanswer from thecommoditydirective rather than from any posting, so the executor now collects that metadata in the same directive walk that already buildsaccount_info. Both constructors were updated -- missingnew_with_sourceswould have left the sourced-directives path returning Null for every currency while the plain path worked.Verified against bean-query 3.2.3
commodity(units(position))'USD'USDcommodity_meta("USD","name")'US Dollar'US Dollarcommodity_meta("USD","asset-class")'cash'cashcurrency_meta("HOOL","name")'Hooli Inc'Hooli Inccommodity_meta("NOPE","name")NoneNonefindfirst("z", tags)'zz'zzfindfirst("nomatch", tags)NoneNoneyearmonth(date)datetime.date(2024, 2, 1)2024-02-01has_account("Assets")Truetruehas_account("Nope")FalsefalseThe negative rows are deliberate. An early version of this check used a ledger with no
commoditydirective, socommodity_metareturned Null on both sides and the row proved nothing. The fixture now carries realcommoditydirectives with metadata, and the Null cases are pinned separately.Coverage, measured the same way #2153 was:
Why
repris not implementedbeanquery's
reprreturns Python's own object syntax:Matching that means emitting CPython type names from Rust. It describes another language's runtime rather than the ledger, and it would pin us to CPython's formatting for every value type we ever add. I would rather leave it absent and say so than ship a function whose contract is "guess what CPython prints".
The reasoning is recorded in the test that covers the other six, so the next person to notice the gap finds the argument rather than re-deriving it.
One known difference
The one-argument form returns the directive's metadata without bean-query's synthetic
filename/linenokeys. That difference is pre-existing and not specific to these functions, and it runs both ways:entry_meta("filename")returns a path here andNonein bean-query. Aligning metadata modelling is a separate question from adding these functions.Review rounds
Two defects found reviewing my own first commit against bean-query, before the automated review landed:
commoditydirectives resolved to the first, not the last.or_insert_withkept January's metadata where bean-query answers with June's. Nothing else in query output reveals which directive was used, so this was invisible without a side-by-side run. Nowinsert, pinned by a test confirmed to fail against the old behaviour (left: "First", right: "Second").COMMODITYaccepted a position. bean-query types itcommodity(Amount)and rejectscommodity(position), so we were accepting an input it refuses. The comment justifying the extra arm claimedcost()"may hand back either"; it does not, whichcommodity(cost(position))proves by returning the COST currency. Arm removed, and the rejection is now asserted.From the automated review, four more:
HAS_ACCOUNTwas implemented twice, in the FROM predicate and the new projection arm, and had already drifted in error text after one commit. Both now callExecutor::entry_has_account.rows[0][0]. These evaluate per posting and the fixture has two rows, so a disagreeing second row would have passed. It now pins every row and names the offending index; confirmed by pointing it atSELECT account, whose rows legitimately differ.FINDFIRSTcloned the whole string set before scanning. Now scans borrowed and clones only the match.doc_markdownrewrite.One residual asymmetry, pre-existing and left alone
HAS_ACCOUNTnow shares its matching logic across both spellings, but argument handling still differs. The FROM path accepts an unquoted account, the projection path does not:The projection side matches bean-query. The FROM side is more permissive than bean-query, and that is pre-existing: the same query behaves identically on
main, before any change here. I left it rather than tighten it inside this PR, since rejecting it would break queries that work today and that is a compatibility decision worth making on its own.Checks
FROMspelling still selects the entry the projection now reports true for.YEARMONTHexpectation to2024-02-15producedleft: Date(2024-02-01), right: Date(2024-02-15), and restoring it returned to green.cargo test -p rustledger-query: 174 passed, 0 failed.doc_markdownfinding onCPythononly appeared under one of them).🤖 Generated with Claude Code
https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr