Skip to main content

vantage_table/table/impls/
references.rs

1//! Table relationship methods for defining and traversing references.
2
3use std::sync::Arc;
4
5use indexmap::IndexMap;
6use vantage_core::{Result, error};
7use vantage_types::Entity;
8use vantage_vista::JoinKey;
9
10use crate::{
11    references::{HasMany, HasOne, Reference},
12    table::Table,
13    traits::table_source::TableSource,
14};
15
16mod contained;
17mod traversal;
18
19impl<T: TableSource + 'static, E: Entity<T::Value> + 'static> Table<T, E> {
20    /// Define a one-to-one relationship.
21    ///
22    /// ```rust,ignore
23    /// .with_one("bakery", "bakery_id", Bakery::postgres_table)
24    /// ```
25    pub fn with_one<E2: Entity<T::Value> + 'static>(
26        mut self,
27        relation: &str,
28        foreign_key: &str,
29        build_target: impl Fn(T) -> Table<T, E2> + Send + Sync + 'static,
30    ) -> Self
31    where
32        T::Value: Into<ciborium::Value> + From<ciborium::Value>,
33        T::Id: std::fmt::Display + From<String>,
34    {
35        let reference = HasOne::<T, E, E2>::new(foreign_key, build_target);
36        self.add_ref(relation, Box::new(reference));
37        self
38    }
39
40    /// Define a one-to-many relationship.
41    ///
42    /// ```rust,ignore
43    /// .with_many("orders", "client_id", Order::postgres_table)
44    /// ```
45    pub fn with_many<E2: Entity<T::Value> + 'static>(
46        mut self,
47        relation: &str,
48        foreign_key: &str,
49        build_target: impl Fn(T) -> Table<T, E2> + Send + Sync + 'static,
50    ) -> Self
51    where
52        T::Value: Into<ciborium::Value> + From<ciborium::Value>,
53        T::Id: std::fmt::Display + From<String>,
54    {
55        let reference = HasMany::<T, E, E2>::new(foreign_key, build_target);
56        self.add_ref(relation, Box::new(reference));
57        self
58    }
59
60    /// [`with_one`](Self::with_one) whose target build can fail: traversing
61    /// the relation returns the error instead of an unconditioned table.
62    /// `target` names the target in metadata, read without running the build.
63    pub fn try_with_one<E2: Entity<T::Value> + 'static>(
64        mut self,
65        relation: &str,
66        foreign_key: &str,
67        target: &str,
68        build_target: impl Fn(T) -> Result<Table<T, E2>> + Send + Sync + 'static,
69    ) -> Self
70    where
71        T::Value: Into<ciborium::Value> + From<ciborium::Value>,
72        T::Id: std::fmt::Display + From<String>,
73    {
74        let reference = HasOne::<T, E, E2>::try_new(foreign_key, target, build_target);
75        self.add_ref(relation, Box::new(reference));
76        self
77    }
78
79    /// [`with_many`](Self::with_many) whose target build can fail.
80    pub fn try_with_many<E2: Entity<T::Value> + 'static>(
81        mut self,
82        relation: &str,
83        foreign_key: &str,
84        target: &str,
85        build_target: impl Fn(T) -> Result<Table<T, E2>> + Send + Sync + 'static,
86    ) -> Self
87    where
88        T::Value: Into<ciborium::Value> + From<ciborium::Value>,
89        T::Id: std::fmt::Display + From<String>,
90    {
91        let reference = HasMany::<T, E, E2>::try_new(foreign_key, target, build_target);
92        self.add_ref(relation, Box::new(reference));
93        self
94    }
95
96    /// [`try_with_one`](Self::try_with_one) joined by `keys`: a row's `from`
97    /// column narrows the target's `to` column (its id when `None`), for
98    /// every key.
99    pub fn try_with_one_keyed<E2: Entity<T::Value> + 'static>(
100        mut self,
101        relation: &str,
102        keys: &[JoinKey],
103        target: &str,
104        build_target: impl Fn(T) -> Result<Table<T, E2>> + Send + Sync + 'static,
105    ) -> Result<Self>
106    where
107        T::Value: Into<ciborium::Value> + From<ciborium::Value>,
108        T::Id: std::fmt::Display + From<String>,
109    {
110        let reference = HasOne::<T, E, E2>::try_new("", target, build_target).with_keys(keys)?;
111        self.add_ref(relation, Box::new(reference));
112        Ok(self)
113    }
114
115    /// [`try_with_many`](Self::try_with_many) joined by `keys`: a row's
116    /// `from` column narrows the target's `to` column, for every key.
117    pub fn try_with_many_keyed<E2: Entity<T::Value> + 'static>(
118        mut self,
119        relation: &str,
120        keys: &[JoinKey],
121        target: &str,
122        build_target: impl Fn(T) -> Result<Table<T, E2>> + Send + Sync + 'static,
123    ) -> Result<Self>
124    where
125        T::Value: Into<ciborium::Value> + From<ciborium::Value>,
126        T::Id: std::fmt::Display + From<String>,
127    {
128        let reference = HasMany::<T, E, E2>::try_new("", target, build_target).with_keys(keys)?;
129        self.add_ref(relation, Box::new(reference));
130        Ok(self)
131    }
132
133    pub(crate) fn add_ref(&mut self, relation: &str, reference: Box<dyn Reference>) {
134        self.add_ref_arc(relation, Arc::from(reference));
135    }
136
137    /// Insert an already-shared reference. Used to inherit relations when
138    /// deriving a table from another (the same `Arc` is shared, not rebuilt).
139    pub(crate) fn add_ref_arc(&mut self, relation: &str, reference: Arc<dyn Reference>) {
140        self.refs
141            .get_or_insert_with(IndexMap::new)
142            .insert(relation.to_string(), reference);
143    }
144
145    /// Copy relations from another table, sharing the underlying `Arc`s. With
146    /// `names = None`, copies all relations; otherwise only the listed ones.
147    /// An inherited relation keeps working as long as the derived table still
148    /// projects the column its foreign key references.
149    pub fn copy_relations_from<E2: Entity<T::Value> + 'static>(
150        &mut self,
151        other: &Table<T, E2>,
152        names: Option<&[&str]>,
153    ) {
154        let Some(refs) = &other.refs else {
155            return;
156        };
157        for (name, reference) in refs {
158            if names.is_some_and(|ns| !ns.contains(&name.as_str())) {
159                continue;
160            }
161            self.add_ref_arc(name, reference.clone());
162        }
163    }
164
165    pub fn references(&self) -> Vec<String> {
166        self.refs
167            .as_ref()
168            .map(|refs| refs.keys().cloned().collect())
169            .unwrap_or_default()
170    }
171
172    fn lookup_ref(&self, relation: &str) -> Result<&dyn Reference> {
173        let table_name = self.table_name();
174        let refs = self
175            .refs
176            .as_ref()
177            .ok_or_else(|| error!("No references defined on table", table = table_name))?;
178
179        let reference = refs.get(relation).ok_or_else(|| {
180            error!(
181                "Reference not found on table",
182                relation = relation,
183                table = table_name
184            )
185        })?;
186
187        Ok(reference.as_ref())
188    }
189
190    /// A registered relation as Vista metadata. Kind and key questions are
191    /// read off this, so they can't disagree with what `vista_references`
192    /// publishes. The target name stays empty: nothing here reads it, and
193    /// naming it would build the target.
194    fn ref_shape(&self, relation: &str) -> Result<vantage_vista::Reference> {
195        let reference = self.lookup_ref(relation)?;
196        Ok(reference.vista_reference(relation, String::new(), &self.id_field_name()))
197    }
198
199    /// Look up cardinality for a registered relation.
200    pub fn ref_cardinality(&self, relation: &str) -> Result<vantage_vista::ReferenceKind> {
201        Ok(self.ref_shape(relation)?.kind)
202    }
203
204    /// Look up the foreign-key/link field for a registered relation. For a
205    /// `has_one` this is the source-side column carrying the link — the field
206    /// a backend-native traversal (e.g. a SurrealDB idiom path) descends
207    /// through, which need not match the relation's registry name. For a
208    /// `has_many` it is the target-side column carrying the parent's id.
209    pub fn ref_foreign_key(&self, relation: &str) -> Result<String> {
210        let shape = self.ref_shape(relation)?;
211        let key = shape
212            .keys
213            .first()
214            .ok_or_else(|| error!("Reference has no join key", relation = relation))?;
215        Ok(match shape.kind {
216            vantage_vista::ReferenceKind::HasMany => key.to.clone().unwrap_or_default(),
217            _ => key.from.clone(),
218        })
219    }
220
221    /// The join keys of a registered relation: each reads a parent column
222    /// (`from`) and constrains a target column (`to`, the target's id when
223    /// `None`).
224    pub fn ref_keys(&self, relation: &str) -> Result<Vec<JoinKey>> {
225        Ok(self.ref_shape(relation)?.keys)
226    }
227
228    /// List all registered relations with their cardinality.
229    pub fn ref_kinds(&self) -> Vec<(String, vantage_vista::ReferenceKind)> {
230        let Some(refs) = &self.refs else {
231            return Vec::new();
232        };
233        let source_id = self.id_field_name();
234        refs.iter()
235            .map(|(name, r)| {
236                let kind = r.vista_reference(name, String::new(), &source_id).kind;
237                (name.clone(), kind)
238            })
239            .collect()
240    }
241}