Skip to main content

xsd_schema/compose/
mod.rs

1//! XQuery-style composition from Rust.
2//!
3//! This module lets a host build XML from query results without an XQuery
4//! processor. The XPath 2.0 engine already evaluates every expression a
5//! FLWOR body needs — `max`, `count`, `avg`, `distinct-values`, quantified
6//! expressions, date component extraction; Rust supplies the iteration and
7//! the binding; and this module supplies the composition: a place to keep the
8//! documents, a description of the result elements, and the emission rules
9//! that make the result an XDM tree rather than a string of tags.
10//!
11//! There is no query parser here, no FLWOR runtime, and no new value model.
12//!
13//! # The pieces
14//!
15//! | Piece | What it is |
16//! |---|---|
17//! | [`Composer`] | the arena, the name table, the namespace context, and a cache of compiled expressions |
18//! | [`Doc`] | a finished document in that arena — loaded or built — as a `Copy` handle |
19//! | [`Value`] | one evaluation's result: an XDM sequence, with the conversions a host asks for |
20//! | [`IntoXPathValue`] | the way Rust values, navigators and sequences are bound to `$variables` |
21//! | [`Form`] / [`Content`] / [`AttrValue`] / [`Name`] | a result element, described but not yet built |
22//! | [`IntoContent`] | the way Rust values become element content |
23//! | [`Emitter`] | the walk that turns forms into a document |
24//! | [`order`] | `order by`, with XDM comparison and stable sorting |
25//! | [`pipe`] | fallible iterator pipelines: the FLWOR clauses as adapters |
26//! | [`ComposeError`] | every way a composition can fail |
27//! | [`xpath!`](crate::xpath!) / [`form!`](crate::form!) | the two macros: one evaluation, one result element |
28//!
29//! The macros are exported at the crate root, so the canonical import is
30//! `use xsd_schema::{form, xpath};` — see [`macros`] for the grammar they
31//! accept. In a form, a prefixed name is written with two colons —
32//! `form! { (p::title "One") }` — because one colon after the element name is
33//! always the start of an attribute: `form! { (book :id "b1") }`.
34//!
35//! A composer starts with `xs`, `xsi` and `fn` bound, so a cast —
36//! `xs:date('1999-01-31')` — and a form name like `(xs::schema …)` need no
37//! declaration of their own; [`Composer::new`] carries the table and the
38//! reasoning.
39//!
40//! # Lifetimes
41//!
42//! A [`Composer<'a>`] borrows an arena and a name table. Every document it
43//! loads or builds is finalized into that arena, so every navigator,
44//! [`Value`] and [`Form`] shares the one lifetime `'a`: a node taken from one
45//! document splices into another with no lifetime work at all. The price is
46//! that nothing is freed until the composer and its arena go away, which
47//! makes the model one composer per request or per batch.
48//!
49//! Every method takes `&self`, so a composer can be used inside iterator
50//! closures and nested loops. It is neither `Send` nor `Sync`.
51//!
52//! # Values
53//!
54//! An evaluation hands back a [`Value`], which is the engine's own sequence
55//! with nothing atomized, copied or flattened. `nodes`, `atomics`, `boolean`,
56//! `string`, `number` and `key` each convert exactly as far as asked, and each
57//! refuses rather than guessing: an atomic item where a node was required is
58//! [`ComposeError::NotANode`], and several items where one was required is
59//! [`ComposeError::NotSingleton`].
60//!
61//! # Forms
62//!
63//! A [`Form`] is an owned, eager tree holding no closures. Every Rust value
64//! inside one has already been evaluated, which is why a `?` inside a form's
65//! construction returns from the enclosing function and why a form can be
66//! returned, stored and spliced later.
67//!
68//! # Emission
69//!
70//! [`Composer::build`] walks the form once. Prefixes resolve against the
71//! forms' own declarations first and the composer's table second; the
72//! declarations an element must carry are computed by the namespace fixup, so
73//! every name in the result resolves; attribute sequences are atomized and
74//! joined with single spaces; and spliced nodes are copied with the
75//! constructor content rules — atomic values separated from each other by one
76//! space and from a node by nothing, document nodes flattened, empty
77//! sequences contributing nothing at all. An empty sequence spliced into an
78//! element therefore leaves an empty element, which is the XDM answer and not
79//! something the host has to special-case.
80//!
81//! # Pipelines, and what is not lazy
82//!
83//! [`pipe`] turns the FLWOR clauses into fallible iterator adapters: a source
84//! supplies rows, `try_map` carries a `let` binding along in a tuple,
85//! `try_filter` is `where`, `try_flat_map` is a nested `for`, and `order_by`
86//! is `order by`. Errors travel to the consumer instead of turning into
87//! missing rows, and a pipe is fused after the first one.
88//!
89//! The adapters are pulled on demand, but three things are eager and stay
90//! eager: an expression that feeds a source has already been evaluated and
91//! its sequence is already materialized; `order_by` buffers its input, which
92//! is what makes it a stable sort with one key evaluation per row; and a
93//! completed form tree is a tree. The pipelines remove the intermediate
94//! vectors between stages and make the query's structure visible. They do not
95//! promise XML streaming, incremental evaluation, or a form-free result.
96//!
97//! # Example
98//!
99//! One document in, one document out, with a filter, a sort and a projection:
100//!
101//! ```
102//! use bumpalo::Bump;
103//! use xsd_schema::compose::order::{Direction, EmptyOrder};
104//! use xsd_schema::compose::{pipe, ComposeError, Composer, Content, Form, IntoContent, Name};
105//! use xsd_schema::document::SerializeOptions;
106//! use xsd_schema::namespace::NameTable;
107//!
108//! let arena = Bump::new();
109//! let names = NameTable::new();
110//! let c = Composer::new(&arena, &names);
111//!
112//! let stock = c.load_str(
113//!     "<stock>\
114//!        <part name='bolt' qty='7'/>\
115//!        <part name='nut' qty='0'/>\
116//!        <part name='washer' qty='3'/>\
117//!      </stock>",
118//! )?;
119//!
120//! // for $p in //part where $p/@qty > 0 order by $p/@name return <part>…</part>
121//! let rows = pipe::nodes(c.eval("//part", &[], Some(stock.root()), Vec::new())?)
122//!     .try_filter(|p| c.eval("@qty > 0", &[], Some(p.clone()), Vec::new())?.boolean())
123//!     .order_by(Direction::Ascending, EmptyOrder::Least, |p| {
124//!         c.eval("@name", &[], Some(p.clone()), Vec::new())?.key()
125//!     })?
126//!     .try_map(|p| {
127//!         let mut part = Form::new(Name::local("part"));
128//!         part.push(c.eval("string(@name)", &[], Some(p), Vec::new())?.into_content());
129//!         Ok(part)
130//!     });
131//!
132//! let mut result = Form::new(Name::local("in_stock"));
133//! for row in rows {
134//!     result.push(Content::Element(row?));
135//! }
136//!
137//! assert_eq!(
138//!     c.build(result)?.to_xml(&SerializeOptions::default())?,
139//!     "<in_stock><part>bolt</part><part>washer</part></in_stock>",
140//! );
141//! # Ok::<(), ComposeError>(())
142//! ```
143//!
144//! # Walkthroughs
145//!
146//! Three queries from the relational use case of the XQuery 1.0 test suite,
147//! over its own `items.xml`, `bids.xml` and `users.xml`. Every one of the
148//! eighteen queries in that use case is rewritten this way in
149//! `tests/compose_usecase_r.rs` and compared with the suite's expected
150//! result; these three are the ones worth reading. They are `no_run` here
151//! because they need the suite checked out — the test is what runs them.
152//!
153//! The shared setup, and the canonical import list:
154//!
155//! ```no_run
156//! use bumpalo::Bump;
157//! use xsd_schema::compose::order::{Direction, EmptyOrder};
158//! use xsd_schema::compose::{pipe, ComposeError, Composer};
159//! use xsd_schema::document::SerializeOptions;
160//! use xsd_schema::namespace::NameTable;
161//! use xsd_schema::{form, xpath};
162//!
163//! let arena = Bump::new();
164//! let names = NameTable::new();
165//! let c = Composer::new(&arena, &names);
166//! let items = c.load_file("XQTS_1_0_2/TestSources/items.xml")?;
167//! let bids = c.load_file("XQTS_1_0_2/TestSources/bids.xml")?;
168//! let users = c.load_file("XQTS_1_0_2/TestSources/users.xml")?;
169//! # Ok::<(), ComposeError>(())
170//! ```
171//!
172//! ## RQ2 — the highest bid for every bicycle
173//!
174//! ```xquery
175//! <result>{
176//!   for $i in $input-context1//item_tuple
177//!   let $b := $input-context2//bid_tuple[itemno = $i/itemno]
178//!   where contains($i/description, "Bicycle")
179//!   order by $i/itemno
180//!   return <item_tuple>{ $i/itemno }{ $i/description }
181//!          <high_bid>{ max($b/bid) }</high_bid></item_tuple>
182//! }</result>
183//! ```
184//!
185//! In C# with LINQ the same query reads as an expression with a host value
186//! bound to `$i` and a constructor taking the result — the shape this module
187//! follows:
188//!
189//! ```csharp
190//! // C# with LINQ, abridged
191//! var bid = bids.XPath2Select<XElement>(
192//!     "//bid_tuple[itemno = $i/itemno]", new { i = item });
193//! new XElement("item_tuple", item.Element("itemno"), item.Element("description"),
194//!     !bid.Any() ? null
195//!                : new XElement("high_bid", bid.AsQueryable().Max(/* … */)));
196//! ```
197//!
198//! `new { i = item }` is `i = &i` below. The `!bid.Any() ? null : …` is the
199//! part that does not carry over, and deliberately: the query says
200//! `<high_bid>{ max($b/bid) }</high_bid>` with no conditional in it, and the
201//! broken bicycle's empty `high_bid` element is what the content rules
202//! produce from an empty sequence. There is no Rust test for "no bids"
203//! anywhere in the version below.
204//!
205//! ```no_run
206//! # use bumpalo::Bump;
207//! # use xsd_schema::compose::order::{Direction, EmptyOrder};
208//! # use xsd_schema::compose::{pipe, ComposeError, Composer};
209//! # use xsd_schema::document::SerializeOptions;
210//! # use xsd_schema::namespace::NameTable;
211//! # use xsd_schema::{form, xpath};
212//! # let arena = Bump::new();
213//! # let names = NameTable::new();
214//! # let c = Composer::new(&arena, &names);
215//! # let items = c.load_file("XQTS_1_0_2/TestSources/items.xml")?;
216//! # let bids = c.load_file("XQTS_1_0_2/TestSources/bids.xml")?;
217//! // for $i in ...
218//! let rows = pipe::nodes(xpath!(c, "//item_tuple", items)?)
219//!     // let $b := ...
220//!     .try_map(|i| {
221//!         let b = xpath!(c, "//bid_tuple[itemno = $i/itemno]", bids, i = &i)?;
222//!         Ok((i, b))
223//!     })
224//!     // where ...
225//!     .try_filter(|(i, _)| xpath!(c, "contains(description, 'Bicycle')", i)?.boolean())
226//!     // order by ...
227//!     .order_by(Direction::Ascending, EmptyOrder::Least, |(i, _)| {
228//!         xpath!(c, "itemno", i)?.key()
229//!     })?
230//!     // return ...
231//!     .try_map(|(i, b)| {
232//!         Ok(form! {
233//!             (item_tuple
234//!                 ^{ xpath!(c, "itemno", &i)? }
235//!                 ^{ xpath!(c, "description", &i)? }
236//!                 (high_bid ^{ xpath!(c, "max($b/bid)", b = &b)? }))
237//!         })
238//!     });
239//!
240//! let doc = c.build(form! { (result ..?^{ rows }) })?;
241//! assert_eq!(
242//!     doc.to_xml(&SerializeOptions::default())?,
243//!     concat!(
244//!         "<result>",
245//!         "<item_tuple><itemno>1001</itemno><description>Red Bicycle</description>",
246//!         "<high_bid>55</high_bid></item_tuple>",
247//!         "<item_tuple><itemno>1003</itemno><description>Old Bicycle</description>",
248//!         "<high_bid>20</high_bid></item_tuple>",
249//!         "<item_tuple><itemno>1007</itemno><description>Racing Bicycle</description>",
250//!         "<high_bid>225</high_bid></item_tuple>",
251//!         "<item_tuple><itemno>1008</itemno><description>Broken Bicycle</description>",
252//!         "<high_bid/></item_tuple>",
253//!         "</result>",
254//!     ),
255//! );
256//! # Ok::<(), ComposeError>(())
257//! ```
258//!
259//! Every closure is one FLWOR clause. The `let` is a projection that carries
260//! the bid sequence beside its item as `(i, b)`; the filter and the key
261//! selector borrow that row; the last projection consumes it. Relative
262//! expressions take the node as their context item rather than rebinding it
263//! as a variable, and no result element is built before the sort — `order_by`
264//! owns the buffer, and computes each key once.
265//!
266//! ## RQ3 — users rated worse than "C" offering items over 1000
267//!
268//! ```xquery
269//! <result>{
270//!   for $u in $input-context2//user_tuple
271//!   for $i in $input-context1//item_tuple
272//!   where $u/rating > "C" and $i/reserve_price > 1000
273//!     and $i/offered_by = $u/userid
274//!   return <warning>{ $u/name }{ $u/rating }
275//!          { $i/description }{ $i/reserve_price }</warning>
276//! }</result>
277//! ```
278//!
279//! ```no_run
280//! # use bumpalo::Bump;
281//! # use xsd_schema::compose::{pipe, ComposeError, Composer};
282//! # use xsd_schema::document::SerializeOptions;
283//! # use xsd_schema::namespace::NameTable;
284//! # use xsd_schema::{form, xpath};
285//! # let arena = Bump::new();
286//! # let names = NameTable::new();
287//! # let c = Composer::new(&arena, &names);
288//! # let items = c.load_file("XQTS_1_0_2/TestSources/items.xml")?;
289//! # let users = c.load_file("XQTS_1_0_2/TestSources/users.xml")?;
290//! // for $u in ..., for $i in ...
291//! let warnings = pipe::nodes(xpath!(c, "//user_tuple", users)?)
292//!     .try_flat_map(|u| {
293//!         Ok(pipe::nodes(xpath!(c, "//item_tuple", items)?)
294//!             .try_map(move |i| Ok((u.clone(), i))))
295//!     })
296//!     // where ...
297//!     .try_filter(|(u, i)| {
298//!         xpath!(
299//!             c,
300//!             "$u/rating > 'C' and $i/reserve_price > 1000 \
301//!              and $i/offered_by = $u/userid",
302//!             u = u,
303//!             i = i
304//!         )?
305//!         .boolean()
306//!     })
307//!     // return ...
308//!     .try_map(|(u, i)| {
309//!         Ok(form! {
310//!             (warning
311//!                 ^{ xpath!(c, "name", &u)? }
312//!                 ^{ xpath!(c, "rating", &u)? }
313//!                 ^{ xpath!(c, "description", &i)? }
314//!                 ^{ xpath!(c, "reserve_price", &i)? })
315//!         })
316//!     });
317//!
318//! let doc = c.build(form! { (result ..?^{ warnings }) })?;
319//! assert_eq!(
320//!     doc.to_xml(&SerializeOptions::default())?,
321//!     concat!(
322//!         "<result><warning><name>Dee Linquent</name><rating>D</rating>",
323//!         "<description>Helicopter</description>",
324//!         "<reserve_price>50000</reserve_price></warning></result>",
325//!     ),
326//! );
327//! # Ok::<(), ComposeError>(())
328//! ```
329//!
330//! The nested `for` is `try_flat_map`: the item source is created for each
331//! user and exhausted before the next user, which is the query's own order.
332//! The inner `move` closure owns `u` and clones the handle into each pair —
333//! a navigator handle, not a copied subtree; the copying happens later, when
334//! the form is built. The three-part `where` stays one expression with two
335//! nodes bound to it, which is the shape the C# version has too.
336//!
337//! ## RQ9 — how many auctions ended in each month
338//!
339//! ```xquery
340//! <result>{
341//!   let $end_dates := $input-context//item_tuple/end_date
342//!   for $m in distinct-values(for $e in $end_dates
343//!                             return month-from-date($e))
344//!   let $item := $input-context//item_tuple
345//!       [year-from-date(end_date) = 1999 and month-from-date(end_date) = $m]
346//!   order by $m
347//!   return <monthly_result><month>{ $m }</month>
348//!          <item_count>{ count($item) }</item_count></monthly_result>
349//! }</result>
350//! ```
351//!
352//! ```no_run
353//! # use bumpalo::Bump;
354//! # use xsd_schema::compose::order::{Direction, EmptyOrder};
355//! # use xsd_schema::compose::{pipe, ComposeError, Composer};
356//! # use xsd_schema::document::SerializeOptions;
357//! # use xsd_schema::namespace::NameTable;
358//! # use xsd_schema::{form, xpath};
359//! # let arena = Bump::new();
360//! # let names = NameTable::new();
361//! let c = Composer::new(&arena, &names);
362//! # let items = c.load_file("XQTS_1_0_2/TestSources/items.xml")?;
363//!
364//! // let $end_dates := ...
365//! let end_dates = xpath!(c, "//item_tuple/end_date", items)?;
366//! // for $m in distinct-values(...)
367//! let months = xpath!(
368//!     c,
369//!     "distinct-values(for $e in $end_dates return month-from-date($e))",
370//!     end_dates = &end_dates
371//! )?
372//! .atomics()?;
373//!
374//! let rows = pipe::from(months)
375//!     // let $item := ...
376//!     .try_map(|m| {
377//!         let item = xpath!(
378//!             c,
379//!             "//item_tuple[year-from-date(end_date) = 1999 \
380//!              and month-from-date(end_date) = $m]",
381//!             items,
382//!             m = &m
383//!         )?;
384//!         Ok((m, item))
385//!     })
386//!     // order by $m
387//!     .order_by(Direction::Ascending, EmptyOrder::Least, |(m, _)| Ok(Some(m.clone())))?
388//!     // return ...
389//!     .try_map(|(m, item)| {
390//!         Ok(form! {
391//!             (monthly_result
392//!                 (month ^{ m })
393//!                 (item_count ^{ xpath!(c, "count($item)", item = &item)? }))
394//!         })
395//!     });
396//!
397//! let doc = c.build(form! { (result ..?^{ rows }) })?;
398//! assert_eq!(
399//!     doc.to_xml(&SerializeOptions::default())?,
400//!     concat!(
401//!         "<result>",
402//!         "<monthly_result><month>1</month><item_count>1</item_count></monthly_result>",
403//!         "<monthly_result><month>2</month><item_count>2</item_count></monthly_result>",
404//!         "<monthly_result><month>3</month><item_count>3</item_count></monthly_result>",
405//!         "<monthly_result><month>4</month><item_count>1</item_count></monthly_result>",
406//!         "<monthly_result><month>5</month><item_count>1</item_count></monthly_result>",
407//!         "</result>",
408//!     ),
409//! );
410//! # Ok::<(), ComposeError>(())
411//! ```
412//!
413//! Here the rows are atomic values rather than nodes: `pipe::from` adapts the
414//! atomized months, the key closure hands the month straight back, and the
415//! sort is numeric because a month is an `xs:integer` whose string value is
416//! `1` and not `1.0`. `atomics()` materializes its conversion — the pipeline
417//! makes the structure declarative, it does not make XPath evaluation lazy.
418//!
419//! One detail this query settles: the distinct months come from *all* end
420//! dates while the year restriction sits in the per-month lookup, so a month
421//! with end dates but no matching 1999 items would still return a count of
422//! zero. Note also that `month-from-date(end_date)` is written exactly as the
423//! query has it, with no constructor: these documents carry no schema, so
424//! their dates are `xs:untypedAtomic`, and the function conversion rules of
425//! XPath 2.0 §3.1.5 cast such an argument to the declared `xs:date` parameter.
426
427pub mod composer;
428pub mod emit;
429pub mod error;
430pub mod form;
431pub mod macros;
432pub mod order;
433pub mod pipe;
434pub mod value;
435
436pub use composer::{Composer, Doc};
437pub use emit::Emitter;
438pub use error::ComposeError;
439pub use form::{AttrValue, Content, Form, IntoContent, Name};
440pub use value::{IntoContextNode, IntoXPathValue, Value};
441
442// What `form!` calls, and nothing a host writes by hand. The macros are
443// exported at the crate root (`xsd_schema::form!`, `xsd_schema::xpath!`) and
444// expand to `$crate::compose::…` paths only, so these have to be reachable
445// from outside the crate even though they are not part of the surface.
446#[doc(hidden)]
447pub use form::{__display_text, __name_from_literal};
448
449/// The navigator every composed value and form uses.
450///
451/// v1 fixes the navigator type to the document buffer's own. A composer
452/// generic over [`DomNavigator`](crate::navigator::DomNavigator) is a
453/// mechanical extension, and is not needed until a host wants to splice nodes
454/// from another tree implementation.
455pub type Nav<'a> = crate::document::BufferDocNavigator<'a>;
456
457#[cfg(test)]
458mod use_case_tests {
459    use std::path::{Path, PathBuf};
460
461    use bumpalo::Bump;
462
463    use super::order::{Direction, EmptyOrder};
464    use super::{pipe, ComposeError, Composer, Content, Form, IntoContent, IntoXPathValue, Name};
465    use crate::document::SerializeOptions;
466    use crate::namespace::NameTable;
467
468    /// The XQuery 1.0 test-suite root, or `None` when it is not around.
469    ///
470    /// Same convention as the conformance drivers: an environment variable
471    /// first, then the checkout next to this crate, and a printed message
472    /// rather than a failure when neither is there.
473    fn suite_root() -> Option<PathBuf> {
474        let candidate = match std::env::var_os("XQTS_DIR") {
475            Some(dir) => PathBuf::from(dir),
476            None => PathBuf::from("../../XQTS_1_0_2"),
477        };
478        if candidate.join("TestSources/items.xml").is_file() {
479            Some(candidate)
480        } else {
481            println!(
482                "skipping: no XQuery test suite at {} (set XQTS_DIR)",
483                candidate.display()
484            );
485            None
486        }
487    }
488
489    /// The highest bid for every bicycle, in item-number order.
490    ///
491    /// The query this rewrites, from the test suite's relational use case:
492    ///
493    /// ```xquery
494    /// <result>{
495    ///   for $i in $input-context1//item_tuple
496    ///   let $b := $input-context2//bid_tuple[itemno = $i/itemno]
497    ///   where contains($i/description, "Bicycle")
498    ///   order by $i/itemno
499    ///   return <item_tuple>{ $i/itemno }{ $i/description }
500    ///          <high_bid>{ max($b/bid) }</high_bid></item_tuple>
501    /// }</result>
502    /// ```
503    ///
504    /// Written with [`Composer::eval`] and the [`Form`] API directly, since
505    /// the macros are a later step.
506    fn highest_bid_per_bicycle(root: &Path) -> Result<String, ComposeError> {
507        let arena = Bump::new();
508        let names = NameTable::new();
509        let c = Composer::new(&arena, &names);
510
511        let items = c.load_file(root.join("TestSources/items.xml"))?;
512        let bids = c.load_file(root.join("TestSources/bids.xml"))?;
513
514        // for $i in //item_tuple
515        let rows = pipe::nodes(c.eval("//item_tuple", &[], Some(items.root()), Vec::new())?)
516            // let $b := //bid_tuple[itemno = $i/itemno]
517            .try_map(|i| {
518                let b = c.eval(
519                    "//bid_tuple[itemno = $i/itemno]",
520                    &["i"],
521                    Some(bids.root()),
522                    vec![("i", (&i).into_xpath_value())],
523                )?;
524                Ok((i, b))
525            })
526            // where contains($i/description, "Bicycle")
527            .try_filter(|(i, _)| {
528                c.eval(
529                    "contains(description, 'Bicycle')",
530                    &[],
531                    Some(i.clone()),
532                    Vec::new(),
533                )?
534                .boolean()
535            })
536            // order by $i/itemno
537            .order_by(Direction::Ascending, EmptyOrder::Least, |(i, _)| {
538                c.eval("itemno", &[], Some(i.clone()), Vec::new())?.key()
539            })?
540            // return <item_tuple>…</item_tuple>
541            .try_map(|(i, b)| {
542                let mut high_bid = Form::new(Name::local("high_bid"));
543                high_bid.push(
544                    c.eval(
545                        "max($b/bid)",
546                        &["b"],
547                        None,
548                        vec![("b", (&b).into_xpath_value())],
549                    )?
550                    .into_content(),
551                );
552
553                let mut item = Form::new(Name::local("item_tuple"));
554                item.push(
555                    c.eval("itemno", &[], Some(i.clone()), Vec::new())?
556                        .into_content(),
557                )
558                .push(
559                    c.eval("description", &[], Some(i.clone()), Vec::new())?
560                        .into_content(),
561                )
562                .push(Content::Element(high_bid));
563                Ok(item)
564            });
565
566        let mut result = Form::new(Name::local("result"));
567        for row in rows {
568            result.push(Content::Element(row?));
569        }
570
571        c.build(result)?.to_xml(&SerializeOptions::default())
572    }
573
574    #[test]
575    fn the_relational_use_case_matches_its_oracle() {
576        let Some(root) = suite_root() else { return };
577
578        let written = highest_bid_per_bicycle(&root).expect("the composition succeeds");
579
580        // The expected result of the use case, byte for byte.
581        assert_eq!(
582            written,
583            "<result><item_tuple><itemno>1001</itemno><description>Red Bicycle</description><high_bid>55</high_bid></item_tuple>\
584             <item_tuple><itemno>1003</itemno><description>Old Bicycle</description><high_bid>20</high_bid></item_tuple>\
585             <item_tuple><itemno>1007</itemno><description>Racing Bicycle</description><high_bid>225</high_bid></item_tuple>\
586             <item_tuple><itemno>1008</itemno><description>Broken Bicycle</description><high_bid/></item_tuple></result>",
587        );
588    }
589}