Skip to main content

vantage_table/references/
one.rs

1//! HasOne — one-to-one relationship where the foreign key is on the source table.
2//!
3//! Example: Client has one Bakery (via client.bakery_id)
4
5use std::fmt::Display;
6use std::sync::OnceLock;
7use std::{any::Any, marker::PhantomData, sync::Arc};
8
9use vantage_core::{Result, error};
10use vantage_types::{EmptyEntity, Entity, Record};
11use vantage_vista::{JoinKey, Reference as VistaReference};
12
13use crate::{references::Reference, table::Table, traits::table_source::TableSource};
14
15pub struct HasOne<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>> {
16    /// Foreign key column on the source table (e.g. "bakery_id")
17    foreign_key: String,
18    /// Target column the foreign key matches; `None` is the target's id.
19    target_column: Option<String>,
20    /// Further keys the target is narrowed by.
21    more_keys: Vec<JoinKey>,
22    /// Factory: given a data source, produce the target table
23    build_target: Arc<dyn Fn(T) -> Result<Table<T, TargetE>> + Send + Sync>,
24    /// The target's metadata name (see `target_table_name`).
25    target_hint: Option<String>,
26    /// The built target's stored table name, once asked (see
27    /// `has_one_target`); shared by clones.
28    stored_target: Arc<OnceLock<String>>,
29    _phantom: PhantomData<SourceE>,
30}
31
32impl<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>>
33    HasOne<T, SourceE, TargetE>
34{
35    pub fn new(
36        foreign_key: impl Into<String>,
37        build_target: impl Fn(T) -> Table<T, TargetE> + Send + Sync + 'static,
38    ) -> Self {
39        Self {
40            foreign_key: foreign_key.into(),
41            target_column: None,
42            more_keys: Vec::new(),
43            build_target: Arc::new(move |source| Ok(build_target(source))),
44            target_hint: None,
45            stored_target: Arc::default(),
46            _phantom: PhantomData,
47        }
48    }
49
50    /// A relation whose target build can fail; traversal returns the error.
51    /// `target` names the target in metadata; the build isn't run for it.
52    pub fn try_new(
53        foreign_key: impl Into<String>,
54        target: impl Into<String>,
55        build_target: impl Fn(T) -> Result<Table<T, TargetE>> + Send + Sync + 'static,
56    ) -> Self {
57        Self {
58            foreign_key: foreign_key.into(),
59            target_column: None,
60            more_keys: Vec::new(),
61            build_target: Arc::new(build_target),
62            target_hint: Some(target.into()),
63            stored_target: Arc::default(),
64            _phantom: PhantomData,
65        }
66    }
67
68    /// Join by `keys` instead: the first key's `from` is the foreign key and
69    /// its `to` the target column it matches (the id when `None`); every
70    /// further key narrows the target too.
71    pub fn with_keys(mut self, keys: &[JoinKey]) -> Result<Self> {
72        let (first, more) = keys
73            .split_first()
74            .ok_or_else(|| error!("a has_one join needs at least one key"))?;
75        self.foreign_key = first.from.clone();
76        self.target_column = first.to.clone();
77        self.more_keys = more.to_vec();
78        Ok(self)
79    }
80
81    /// Joined on the target's id by a single key.
82    fn joins_target_id(&self) -> bool {
83        self.target_column.is_none() && self.more_keys.is_empty()
84    }
85}
86
87impl<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>> Clone
88    for HasOne<T, SourceE, TargetE>
89{
90    fn clone(&self) -> Self {
91        Self {
92            foreign_key: self.foreign_key.clone(),
93            target_column: self.target_column.clone(),
94            more_keys: self.more_keys.clone(),
95            build_target: self.build_target.clone(),
96            target_hint: self.target_hint.clone(),
97            stored_target: self.stored_target.clone(),
98            _phantom: PhantomData,
99        }
100    }
101}
102
103impl<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>> std::fmt::Debug
104    for HasOne<T, SourceE, TargetE>
105{
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        f.debug_struct("HasOne")
108            .field("foreign_key", &self.foreign_key)
109            .finish()
110    }
111}
112
113impl<
114    T: TableSource + 'static,
115    SourceE: Entity<T::Value> + 'static,
116    TargetE: Entity<T::Value> + 'static,
117> Reference for HasOne<T, SourceE, TargetE>
118where
119    T::Value: Into<ciborium::Value> + From<ciborium::Value>,
120    T::Id: Display + From<String>,
121{
122    fn columns(&self, _source_id: &str, target_id: &str) -> (String, String) {
123        let target = self.target_column.as_deref().unwrap_or(target_id);
124        (self.foreign_key.clone(), target.to_string())
125    }
126
127    fn vista_reference(&self, name: &str, target: String, _source_id: &str) -> VistaReference {
128        let first = match &self.target_column {
129            Some(column) => JoinKey::new(&self.foreign_key, column),
130            None => JoinKey::to_target_id(&self.foreign_key),
131        };
132        let mut reference = VistaReference::has_one(name, target, first);
133        reference.keys.extend(self.more_keys.iter().cloned());
134        reference
135    }
136
137    fn build_target(&self, data_source: &dyn Any) -> Result<Box<dyn Any>> {
138        let ds = data_source
139            .downcast_ref::<T>()
140            .ok_or_else(|| error!("data source type mismatch in HasOne::build_target"))?;
141        Ok(Box::new((self.build_target)(ds.clone())?))
142    }
143
144    fn build_target_erased(&self, data_source: &dyn Any) -> Result<Box<dyn Any>> {
145        let ds = data_source
146            .downcast_ref::<T>()
147            .ok_or_else(|| error!("data source type mismatch in HasOne::build_target_erased"))?;
148        Ok(Box::new(
149            (self.build_target)(ds.clone())?.into_entity::<EmptyEntity>(),
150        ))
151    }
152
153    fn resolve_from_row(
154        &self,
155        data_source: &dyn Any,
156        _source_id_field: &str,
157        source_row: &dyn Any,
158    ) -> Result<Box<dyn Any>> {
159        let ds = data_source
160            .downcast_ref::<T>()
161            .ok_or_else(|| error!("data source type mismatch in HasOne::resolve_from_row"))?;
162        let row = source_row
163            .downcast_ref::<Record<T::Value>>()
164            .ok_or_else(|| error!("source row type mismatch in HasOne::resolve_from_row"))?;
165
166        let mut target = (self.build_target)(ds.clone())?;
167        let target_id = target.id_field_name();
168
169        let (src_col, tgt_col) = self.columns("", &target_id);
170        let keys = std::iter::once(JoinKey::new(src_col, tgt_col)).chain(self.more_keys.clone());
171        for key in keys {
172            let join_value = row.get(&key.from).cloned().ok_or_else(|| {
173                error!(
174                    "source row missing foreign-key field",
175                    field = key.from.as_str()
176                )
177            })?;
178            // Rows arriving from a script/JSON surface carry ids in string form.
179            let join_value = ds.coerce_reference_value(join_value);
180            let to = key.to.unwrap_or_else(|| target_id.clone());
181            let condition = ds.eq_value_condition(&to, join_value.clone())?;
182            target.add_condition(condition);
183            target.add_invariant(to, join_value);
184        }
185
186        Ok(Box::new(target.into_entity::<EmptyEntity>()))
187    }
188
189    /// The `try_new` target name when set, without building: a metadata
190    /// snapshot mustn't run the target's build (and an injector with it).
191    fn target_table_name(&self, data_source: &dyn Any) -> String {
192        if let Some(hint) = &self.target_hint {
193            return hint.clone();
194        }
195        let ds = data_source
196            .downcast_ref::<T>()
197            .expect("data source type mismatch in HasOne::target_table_name");
198        (self.build_target)(ds.clone())
199            .map(|target| target.table_name().to_string())
200            .unwrap_or_default()
201    }
202
203    /// The built target's table name, which a spec's driver block may set
204    /// apart from the spec name; the metadata name when the build fails.
205    /// Built once per relation, and bare (no build injectors): only
206    /// the name is read.
207    fn has_one_target(&self, column: &str, data_source: &dyn Any) -> Option<String> {
208        // A join on another target column doesn't hold the target's links.
209        if column != self.foreign_key || !self.joins_target_id() {
210            return None;
211        }
212        let name = self.stored_target.get_or_init(|| {
213            data_source
214                .downcast_ref::<T>()
215                .and_then(|ds| crate::table::inject::bare(|| (self.build_target)(ds.clone())).ok())
216                .map(|target| target.table_name().to_string())
217                .or_else(|| self.target_hint.clone())
218                .unwrap_or_default()
219        });
220        (!name.is_empty()).then(|| name.clone())
221    }
222}