Skip to main content

vantage_table/
references.rs

1//! Table reference system for relationships between tables.
2//!
3//! The `Reference` trait describes a relationship (field names, target factory).
4//! Same-persistence resolution happens in `Table::get_ref_from_row` via
5//! `Reference::resolve_from_row` — the join value is read out of a known source
6//! row and pushed as a plain eq-condition on the target.
7//!
8//! Two concrete types:
9//! - `HasOne` — foreign key on source table (e.g. Client.bakery_id → Bakery)
10//! - `HasMany` — foreign key on target table (e.g. Bakery → Client.bakery_id)
11//!
12//! Cross-persistence references live at the Vista layer (`Vista::with_foreign`),
13//! not here. Typed `Table<T, E>` is single-backend by construction.
14
15use std::any::Any;
16
17use vantage_core::Result;
18
19pub mod many;
20pub mod one;
21
22pub use many::HasMany;
23pub use one::HasOne;
24
25/// Describes a relationship between two tables.
26pub trait Reference: Send + Sync {
27    /// Given source and target id field names, return (source_column, target_column).
28    fn columns(&self, source_id: &str, target_id: &str) -> (String, String);
29
30    /// Produce a fresh target table (no conditions applied), wrapped in
31    /// `Box<dyn Any>` so callers can downcast back to the concrete
32    /// `Table<T, TargetE>`. Used by [`Table::get_ref_as`] and
33    /// [`Table::get_subquery_as`] to build the target before applying the
34    /// join condition.
35    fn build_target(&self, data_source: &dyn Any) -> Box<dyn Any>;
36
37    /// Cardinality of this relation. `HasOne` if traversing yields at most
38    /// one record (the FK lives on the source); `HasMany` if it can yield
39    /// any number (the FK lives on the target). Surfaced by
40    /// `Vista::list_references` so CLIs / UIs can pick a record-card vs
41    /// list-grid renderer.
42    fn cardinality(&self) -> vantage_vista::ReferenceKind;
43
44    /// Resolve traversal using a known source row. Returns the target table
45    /// (entity type erased to `EmptyEntity`) wrapped in `Box<dyn Any>`, with
46    /// one eq-condition applied that selects the related rows.
47    ///
48    /// `data_source` is `&T` for the source's `TableSource`; `source_id_field`
49    /// is the name of the source table's id column (needed by `HasMany` to
50    /// pull the join value out of the row); `source_row` is `&Record<T::Value>`.
51    /// `HasOne` ignores `source_id_field` and reads its stored `foreign_key`
52    /// instead.
53    ///
54    /// Callers immediately downcast the result to `Table<T, EmptyEntity>`.
55    fn resolve_from_row(
56        &self,
57        data_source: &dyn Any,
58        source_id_field: &str,
59        source_row: &dyn Any,
60    ) -> Result<Box<dyn Any>>;
61
62    /// Type name of the target table (for error messages).
63    fn target_type_name(&self) -> &'static str;
64}