Ecosystem Integrations
Optional schemars and utoipa integrations, storing identifiers and enums in a database with any driver, property testing with proptest, and the convenience accessors on generated types.
Every integration is behind a feature gate. Where a plain string is enough — a database column, a query parameter — none is needed: identifiers and enums convert to and from their wire strings with the standard traits. There is no framework-specific glue; see Design Boundary.
🔗schemars — JSON Schema Generation
Feature flag: schemars
Dependency: schemars = "1"
Derives JsonSchema on all types.
cargo add rubo4e --features schemarsuse schemars::{schema_for, JsonSchema};
let schema = schema_for!(rubo4e::v202607::Vertrag);
let json = serde_json::to_string_pretty(&schema)?;
println!("{json}");Identifier types appear as strings with a pattern, matching the wire format.
🔗The Decimal and time schema impls hang off decimal / time
schemars?/rust_decimal1 (the impl JsonSchema for Decimal) is enabled by rubo4e's decimal feature, not by schemars; utoipa?/decimal and utoipa?/time likewise ride on decimal and time. The ? means neither pulls in the integration. If your own crate derives JsonSchema over a Decimal, declare the feature yourself rather than relying on rubo4e's:
schemars = { version = "1", features = ["rust_decimal1"] }🔗utoipa — OpenAPI Schema Derivation
Feature flag: utoipa
Dependency: utoipa = "5"
Derives ToSchema on all BO, COM, enum, and identifier types.
cargo add rubo4e --features utoipause utoipa::OpenApi;
#[derive(OpenApi)]
#[openapi(components(schemas(rubo4e::v202607::Vertrag)))]
struct ApiDoc;
let openapi = ApiDoc::openapi();Property names use German camelCase, as on the wire.
🔗Identifier schemas come from one table
Every identifier emits a pattern, a German description and a valid example, and both generators emit the same three:
{
"type": "string",
"pattern": "^[1-9][0-9]{10}$",
"example": "41373559241",
"description": "11-stellige BDEW Marktlokations-ID: Vergabestelle (1-3 DVGW, 4-9 BDEW) + 9 Ziffern + Prüfziffer nach dem Lok- und Waggon-Kennzeichnungsverfahren (BDEW §8.1)"
}Both read rubo4e::identifiers::schema, one const per identifier, rather than the type's rustdoc. tests/identifier_schemas.rs checks, for every identifier, that both outputs agree, that no rustdoc markup leaks in, and that each example matches its pattern and passes the type's constructor — so every example carries a valid check digit. Generated types publish BO4E's own descriptions; tests/schema_descriptions.rs guards those.
🔗Storing values in a database
rubo4e has no database dependency. Identifiers and enums cross a database boundary as their wire strings, so the same code works with any driver and any version of it — shown here with sqlx:
use rubo4e::current::Sparte;
use rubo4e::identifiers::MaloId;
use sqlx::Row as _;
// Write: the wire string.
sqlx::query("INSERT INTO malo (id, sparte) VALUES ($1, $2)")
.bind(malo_id.as_ref()) // &str
.bind(sparte.as_wire()) // &'static str
.execute(&pool).await?;
// Read: parse, which validates exactly as the constructor does.
let id: MaloId = row.try_get::<&str, _>("id")?.parse()?;
let sparte: Sparte = row.try_get::<&str, _>("sparte")?.parse()?; // strict
// Lenient, for rows a newer schema version may have written:
let sparte = Sparte::from_wire(s).unwrap_or(Sparte::Unknown);TEXT[] columns take a Vec<&str> built the same way.
Reading an identifier back validates it. MaloId's FromStr runs the same check-digit test as MaloId::new, so a malformed value already in the table surfaces as an error rather than as a silently accepted bad ID.
Reading an enum back is strict or lenient — your choice, at the call site. Every generated enum implements FromStr, with no feature needed. It accepts exactly the wire values the schema version defines, the same as from_wire, and rejects anything else — including "UNKNOWN", which is the catch-all's own spelling rather than a value — with rubo4e::error::UnknownVariant:
use rubo4e::error::UnknownVariant;
match "INVALID_SPARTE".parse::<Sparte>() {
Err(UnknownVariant { value, .. }) => { /* `value` is the rejected string */ }
Ok(sparte) => { /* … */ }
}Deserialize, by contrast, maps an unrecognised string to Unknown. A column holds what your application wrote, so strict is usually right there; use from_wire(s).unwrap_or(E::Unknown) where rows may come from a newer schema version.
To keep a CHECK (col IN (...)) constraint in step with an enum, generate or test it from VARIANTS — see Schema Versioning for a drift guard that does exactly that.
🔗proptest — Property Testing
proptest is a dev-dependency, so no feature flag is involved. The Arbitrary impls for identifier types are #[cfg(test)] only and are not exposed to external crates.
To write property tests against BO4E-integrated code in your own crate, add both as dev-dependencies:
cargo add --dev rubo4e --features versioned,serde
cargo add --dev proptestYour property tests can use the same strategy pattern this crate's own use — generate the base, and let from_base append the check digit:
use proptest::prelude::*;
use rubo4e::identifiers::MaloId;
/// A valid 11-digit MaLo-ID: 10 base digits (the first is the Vergabestelle,
/// never `0`) plus the BDEW §8.1 check digit `from_base` computes.
fn valid_malo_id() -> impl Strategy<Value = String> {
prop::string::string_regex("[1-9][0-9]{9}")
.expect("MaLo base regex")
.prop_map(|base| MaloId::from_base(&base).expect("valid base").to_string())
}
proptest! {
#[test]
fn my_service_handles_valid_malo(s in valid_malo_id()) {
let malo = MaloId::new(&s).unwrap();
let result = my_service.process_location(malo);
prop_assert!(result.is_ok());
}
}Derive the check digit with from_base / from_prefix rather than reimplementing it: BDEW §8.1 is not Luhn, and a Luhn-based strategy generates strings MaloId::new rejects.
See tests/proptest_roundtrips.rs in the rubo4e source for complete reference strategy implementations for all identifier types, enum variants, and date fields.
🔗time_serde — Date Serde Helpers
Feature flag: time
Module: rubo4e::time_serde
When the time feature is enabled, generated structs use rubo4e::time_serde for time::Date fields instead of raw strings. The module is also available to consumers who need the same "YYYY-MM-DD" serde behaviour on their own types:
cargo add rubo4e --features timeuse time::Date;
#[derive(serde::Serialize, serde::Deserialize)]
struct MyRecord {
// Required date — "YYYY-MM-DD" wire format, zero-allocation deserializer
#[serde(with = "rubo4e::time_serde::date_serde")]
billing_date: Date,
// Optional date — null or "YYYY-MM-DD"
#[serde(with = "rubo4e::time_serde::opt_date_serde")]
expiry_date: Option<Date>,
}JSON null maps to None; neither deserializer allocates.
🔗convenience — Ergonomic Helpers on Generated Types
Feature flag: versioned, plus time for date accessors and decimal for amounts
Module: rubo4e::convenience
Hand-written accessors on generated types.
🔗Amounts and invoices
use rubo4e::prelude::*; // BetragExt, MengeExt, PreisExt, PreisstaffelSliceExt
// Option<Com> → Option<Decimal>, instead of `.as_ref().and_then(|b| b.wert)`.
let net = pos.gesamtpreis.wert_decimal(); // BetragExt
let qty = pos.positions_menge.wert_decimal(); // MengeExt
let unit = pos.einzelpreis.wert_decimal(); // PreisExt
// Rechnung
let net = rechnung.gesamtnetto_decimal(); // also gesamtsteuer_, gesamtbrutto_, zu_zahlen_,
let adv = rechnung.vorauszahlungen_summe(); // rabatt_netto_, zukuenftiger_abschlag_decimal()
let due = rechnung.faelligkeitsdatum_date();
let start = rechnung.period_start(); // and period_end()
if rechnung.is_storno() { /* … */ } // and is_original(); false when absent
for pos in rechnung.positions() { /* … */ }
// Rechnungsposition — delivery period from lieferungszeitraum
let von = pos.lieferung_von_date();
let in_period = pos.lieferungszeitraum_contains(date!(2026-10-01));PreisstaffelSliceExt::select_for(value) picks a price tier, including BO4E's rule that a value between two tiers "rutscht in die obere Zone".
🔗Periods and validity
use rubo4e::v202607::{Rechnung, PreisblattNetznutzung, Zeitraum};
// Rechnung — closed billing period, as a RangeInclusive<Date>
// (`None` unless both `rechnungsperiode` dates are present)
let r: Rechnung = todo!();
if let Some(period) = r.billing_period() {
println!("Invoice period: {} – {} inclusive", period.start(), period.end());
}
// PreisblattNetznutzung — validity bounds, either of which may be open.
// `validity()` returns a pair, not an Option: a missing `gueltigkeit` reads as
// (None, None), the same shape as "stated, but unbounded on both sides".
// Use `is_valid_at(date)` where "no validity stated" must read as *not* valid.
let p: PreisblattNetznutzung = todo!();
match p.validity() {
(Some(start), Some(end)) => println!("valid {start} – {end} inclusive"),
(Some(start), None) => println!("valid from {start} (open-ended)"),
(None, Some(end)) => println!("valid until {end} inclusive"),
(None, None) => println!("no validity stated"),
}
// Zeitraum — range accessors (every `gueltigkeit` field is a Zeitraum)
let z: Zeitraum = todo!();
let range = z.as_inclusive_range(); // Option<RangeInclusive<Date>> — both bounds stated
let bounds = z.bounds(); // (Option<Date>, Option<Date>) — either may be open
let days = z.whole_days(); // Option<i64> — January is 31
let active = z.contains(some_date); // bool — end date included
let dauer = z.duration(); // Option<Result<time::Duration, _>>Interval conventions are not uniform in BO4E:
| Kind | Interval |
|---|---|
date-time pairs (vertragsbeginn/vertragsende, von/bis) | [start, end) |
Zeitraum's date pair | [start, end] — "Enddatum … ist inklusiv" |
Zeitraum's time pair and instant range | [start, end) |
price-tier bounds (staffelgrenzeVon/Bis) | [von, bis], plus the gap rule above |
start == end is a valid one-day Zeitraum. as_inclusive_range returns a RangeInclusive<Date> so the convention travels with the value. tests/interval_conventions.rs checks each convention against the schema.
🔗The three fields that stay String, and how to read them
Zeitraum carries three values no time type can hold directly, so the generated fields keep the wire string and an accessor parses on demand:
// `dauer` — an ISO 8601 duration, e.g. "P1DT30H4S"
let d: Option<Result<time::Duration, _>> = z.duration();
// `startuhrzeit` / `enduhrzeit` — a time of day *with a UTC offset*
let start: Option<Result<(time::Time, Option<time::UtcOffset>), _>> = z.startuhrzeit_parsed();
let end = z.enduhrzeit_parsed();
// …and the same format on Umschaltzeit, the HT/NT switching time
let switch = umschaltzeit.umschaltzeit_parsed();duration() refuses P1Y and P1M (their length depends on a start date); weeks and below are exact. See iso8601_duration.
The time-of-day accessors return the UTC offset separately, because time has no offset-bearing time-of-day type. It is an Option, not defaulted to UTC: BO4E does not require one.