vantage_table/references/
many.rs1use std::fmt::Display;
6use std::{any::Any, marker::PhantomData, sync::Arc};
7
8use vantage_core::{Result, error};
9use vantage_types::{EmptyEntity, Entity, Record};
10use vantage_vista::{JoinKey, Reference as VistaReference};
11
12use crate::{references::Reference, table::Table, traits::table_source::TableSource};
13
14pub struct HasMany<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>> {
15 target_foreign_key: String,
17 source_column: Option<String>,
19 more_keys: Vec<JoinKey>,
21 build_target: Arc<dyn Fn(T) -> Result<Table<T, TargetE>> + Send + Sync>,
23 target_hint: Option<String>,
25 _phantom: PhantomData<SourceE>,
26}
27
28impl<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>>
29 HasMany<T, SourceE, TargetE>
30{
31 pub fn new(
32 target_foreign_key: impl Into<String>,
33 build_target: impl Fn(T) -> Table<T, TargetE> + Send + Sync + 'static,
34 ) -> Self {
35 Self {
36 target_foreign_key: target_foreign_key.into(),
37 build_target: Arc::new(move |source| Ok(build_target(source))),
38 target_hint: None,
39 source_column: None,
40 more_keys: Vec::new(),
41 _phantom: PhantomData,
42 }
43 }
44
45 pub fn try_new(
48 target_foreign_key: impl Into<String>,
49 target: impl Into<String>,
50 build_target: impl Fn(T) -> Result<Table<T, TargetE>> + Send + Sync + 'static,
51 ) -> Self {
52 Self {
53 target_foreign_key: target_foreign_key.into(),
54 build_target: Arc::new(build_target),
55 target_hint: Some(target.into()),
56 source_column: None,
57 more_keys: Vec::new(),
58 _phantom: PhantomData,
59 }
60 }
61
62 pub fn with_keys(mut self, keys: &[JoinKey]) -> Result<Self> {
66 let mut keys = keys.iter();
67 let first = keys
68 .next()
69 .ok_or_else(|| error!("a has_many join needs at least one key"))?;
70 let to = |key: &JoinKey| {
71 key.to.clone().ok_or_else(|| {
72 error!(
73 "a has_many join key needs a target column",
74 from = key.from.as_str()
75 )
76 })
77 };
78 self.target_foreign_key = to(first)?;
79 self.source_column = Some(first.from.clone());
80 self.more_keys = keys
81 .map(|key| Ok(JoinKey::new(&key.from, to(key)?)))
82 .collect::<Result<_>>()?;
83 Ok(self)
84 }
85}
86
87impl<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>> Clone
88 for HasMany<T, SourceE, TargetE>
89{
90 fn clone(&self) -> Self {
91 Self {
92 target_foreign_key: self.target_foreign_key.clone(),
93 build_target: self.build_target.clone(),
94 target_hint: self.target_hint.clone(),
95 source_column: self.source_column.clone(),
96 more_keys: self.more_keys.clone(),
97 _phantom: PhantomData,
98 }
99 }
100}
101
102impl<T: TableSource, SourceE: Entity<T::Value>, TargetE: Entity<T::Value>> std::fmt::Debug
103 for HasMany<T, SourceE, TargetE>
104{
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 f.debug_struct("HasMany")
107 .field("target_foreign_key", &self.target_foreign_key)
108 .finish()
109 }
110}
111
112impl<
113 T: TableSource + 'static,
114 SourceE: Entity<T::Value> + 'static,
115 TargetE: Entity<T::Value> + 'static,
116> Reference for HasMany<T, SourceE, TargetE>
117where
118 T::Value: Into<ciborium::Value> + From<ciborium::Value>,
119 T::Id: Display + From<String>,
120{
121 fn columns(&self, source_id: &str, _target_id: &str) -> (String, String) {
122 let source = self.source_column.as_deref().unwrap_or(source_id);
123 (source.to_string(), self.target_foreign_key.clone())
124 }
125
126 fn vista_reference(&self, name: &str, target: String, source_id: &str) -> VistaReference {
127 let (source, foreign_key) = self.columns(source_id, "");
128 let mut reference =
129 VistaReference::has_many(name, target, JoinKey::new(source, foreign_key));
130 reference.keys.extend(self.more_keys.iter().cloned());
131 reference
132 }
133
134 fn build_target(&self, data_source: &dyn Any) -> Result<Box<dyn Any>> {
135 let ds = data_source
136 .downcast_ref::<T>()
137 .ok_or_else(|| error!("data source type mismatch in HasMany::build_target"))?;
138 Ok(Box::new((self.build_target)(ds.clone())?))
139 }
140
141 fn build_target_erased(&self, data_source: &dyn Any) -> Result<Box<dyn Any>> {
142 let ds = data_source
143 .downcast_ref::<T>()
144 .ok_or_else(|| error!("data source type mismatch in HasMany::build_target_erased"))?;
145 Ok(Box::new(
146 (self.build_target)(ds.clone())?.into_entity::<EmptyEntity>(),
147 ))
148 }
149
150 fn resolve_from_row(
151 &self,
152 data_source: &dyn Any,
153 source_id_field: &str,
154 source_row: &dyn Any,
155 ) -> Result<Box<dyn Any>> {
156 let ds = data_source
157 .downcast_ref::<T>()
158 .ok_or_else(|| error!("data source type mismatch in HasMany::resolve_from_row"))?;
159 let row = source_row
160 .downcast_ref::<Record<T::Value>>()
161 .ok_or_else(|| error!("source row type mismatch in HasMany::resolve_from_row"))?;
162
163 let mut target = (self.build_target)(ds.clone())?;
164 let (src_col, tgt_col) = self.columns(source_id_field, "");
165 let keys = std::iter::once(JoinKey::new(src_col, tgt_col)).chain(self.more_keys.clone());
166 for key in keys {
167 let join_value = row.get(&key.from).cloned().ok_or_else(|| {
168 error!("source row missing join field", field = key.from.as_str())
169 })?;
170 let join_value = ds.coerce_reference_value(join_value);
172 let to = key.to.unwrap_or_default();
173 let condition = ds.eq_value_condition(&to, join_value.clone())?;
174 target.add_condition(condition);
175 target.add_invariant(to, join_value);
176 }
177
178 Ok(Box::new(target.into_entity::<EmptyEntity>()))
179 }
180
181 fn target_table_name(&self, data_source: &dyn Any) -> String {
184 if let Some(hint) = &self.target_hint {
185 return hint.clone();
186 }
187 let ds = data_source
188 .downcast_ref::<T>()
189 .expect("data source type mismatch in HasMany::target_table_name");
190 (self.build_target)(ds.clone())
191 .map(|target| target.table_name().to_string())
192 .unwrap_or_default()
193 }
194}