1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! Table relationship methods for defining and traversing references.
use indexmap::IndexMap;
use std::sync::Arc;
use vantage_core::{Result, error};
use vantage_expressions::Expression;
use vantage_types::{EmptyEntity, Entity, Record};
use crate::{
any::AnyTable,
references::{HasMany, HasOne, Reference},
table::Table,
traits::{column_like::ColumnLike, table_source::TableSource},
};
impl<T: TableSource + 'static, E: Entity<T::Value> + 'static> Table<T, E> {
/// Define a one-to-one relationship.
///
/// ```rust,ignore
/// .with_one("bakery", "bakery_id", Bakery::postgres_table)
/// ```
pub fn with_one<E2: Entity<T::Value> + 'static>(
mut self,
relation: &str,
foreign_key: &str,
build_target: impl Fn(T) -> Table<T, E2> + Send + Sync + 'static,
) -> Self
where
T::Value: Into<ciborium::Value> + From<ciborium::Value>,
T::Id: std::fmt::Display + From<String>,
{
let reference = HasOne::<T, E, E2>::new(foreign_key, build_target);
self.add_ref(relation, Box::new(reference));
self
}
/// Define a one-to-many relationship.
///
/// ```rust,ignore
/// .with_many("orders", "client_id", Order::postgres_table)
/// ```
pub fn with_many<E2: Entity<T::Value> + 'static>(
mut self,
relation: &str,
foreign_key: &str,
build_target: impl Fn(T) -> Table<T, E2> + Send + Sync + 'static,
) -> Self
where
T::Value: Into<ciborium::Value> + From<ciborium::Value>,
T::Id: std::fmt::Display + From<String>,
{
let reference = HasMany::<T, E, E2>::new(foreign_key, build_target);
self.add_ref(relation, Box::new(reference));
self
}
pub(crate) fn add_ref(&mut self, relation: &str, reference: Box<dyn Reference>) {
if self.refs.is_none() {
self.refs = Some(IndexMap::new());
}
self.refs
.as_mut()
.unwrap()
.insert(relation.to_string(), Arc::from(reference));
}
pub fn references(&self) -> Vec<String> {
self.refs
.as_ref()
.map(|refs| refs.keys().cloned().collect())
.unwrap_or_default()
}
/// Narrow the table to a single row by id.
///
/// Pairs with `get_some_value` for the "I only know an id" workflow.
/// The actual condition construction goes through
/// `TableSource::eq_value_condition`, so backends that don't yet
/// implement that path return an error here.
pub fn with_id(mut self, id: impl Into<T::Value>) -> Result<Self> {
let id_name = self
.id_field()
.ok_or_else(|| error!("id field not set on table"))?
.name()
.to_string();
let condition = self.data_source().eq_value_condition(&id_name, id.into())?;
self.add_condition(condition);
Ok(self)
}
/// Traverse a same-persistence reference using a known source row as the
/// join origin.
///
/// Reads the join field value out of `row`, builds the target table via
/// the reference's stored factory, and applies one eq-condition that
/// selects the related rows. No subquery, no deferred fetch — `row`
/// already carries the value.
///
/// `HasOne` reads from its stored foreign-key column; `HasMany` reads
/// from the source's id field (looked up here and forwarded into the
/// reference). The returned table preserves columns, refs, and
/// expressions from the reference's factory; only the entity type
/// changes if `E2` differs from the factory's output.
pub fn get_ref_from_row<E2: Entity<T::Value> + 'static>(
&self,
relation: &str,
row: &Record<T::Value>,
) -> Result<Table<T, E2>> {
let (reference, _) = self.lookup_ref(relation)?;
let source_id = self
.id_field()
.map(|c| c.name().to_string())
.unwrap_or_else(|| "id".to_string());
let target_dyn = reference.resolve_from_row(
self.data_source() as &dyn std::any::Any,
&source_id,
row as &dyn std::any::Any,
)?;
let target_empty: Table<T, EmptyEntity> =
*target_dyn
.downcast::<Table<T, EmptyEntity>>()
.map_err(|_| error!("Failed to downcast target table to Table<T, EmptyEntity>"))?;
Ok(target_empty.into_entity::<E2>())
}
/// Get a same-backend related table with automatic downcasting.
///
/// Legacy AnyTable-flavoured path; slated for deletion in Stage 9 alongside
/// `AnyTable`. New code should prefer [`Table::get_ref_from_row`] (typed) or
/// `Vista::get_ref` (erased).
pub fn get_ref_as<E2: Entity<T::Value> + 'static>(
&self,
relation: &str,
) -> Result<Table<T, E2>> {
let (reference, relation_str) = self.lookup_ref(relation)?;
// 1. Build target
let source_id = self
.id_field()
.map(|c| c.name().to_string())
.unwrap_or_else(|| "id".to_string());
let mut target: Table<T, E2> = *reference
.build_target(self.data_source() as &dyn std::any::Any)
.downcast::<Table<T, E2>>()
.map_err(|_| {
error!(
"Failed to downcast related table",
relation = relation_str.as_str()
)
})?;
// 2. Get columns
let target_id = target
.id_field()
.map(|c| c.name().to_string())
.unwrap_or_else(|| "id".to_string());
let (src_col, tgt_col) = reference.columns(&source_id, &target_id);
// 3. Build and apply condition
let condition = self
.data_source()
.related_in_condition(&tgt_col, self, &src_col);
target.add_condition(condition);
Ok(target)
}
/// Get a related table as AnyTable.
///
/// Legacy AnyTable-flavoured path; slated for deletion in Stage 9.
pub fn get_ref(&self, relation: &str) -> Result<AnyTable> {
let (reference, _) = self.lookup_ref(relation)?;
reference.resolve_as_any(self as &dyn std::any::Any)
}
/// Get a correlated related table for use inside SELECT expressions.
///
/// Unlike `get_ref_as` (which uses `IN (subquery)`), this produces a
/// correlated condition like `order.client_id = client.id`, suitable
/// for embedding as a subquery in a SELECT clause.
pub fn get_subquery_as<E2: Entity<T::Value> + 'static>(
&self,
relation: &str,
) -> Result<Table<T, E2>> {
let (reference, relation_str) = self.lookup_ref(relation)?;
// 1. Build target
let source_id = self
.id_field()
.map(|c| c.name().to_string())
.unwrap_or_else(|| "id".to_string());
let mut target: Table<T, E2> = *reference
.build_target(self.data_source() as &dyn std::any::Any)
.downcast::<Table<T, E2>>()
.map_err(|_| {
error!(
"Failed to downcast related table",
relation = relation_str.as_str()
)
})?;
// 2. Get columns
let target_id = target
.id_field()
.map(|c| c.name().to_string())
.unwrap_or_else(|| "id".to_string());
let (src_col, tgt_col) = reference.columns(&source_id, &target_id);
// 3. Build correlated condition: target_table.tgt_col = source_table.src_col
let condition = self.data_source().related_correlated_condition(
target.table_name(),
&tgt_col,
self.table_name(),
&src_col,
);
target.add_condition(condition);
Ok(target)
}
/// Add a computed expression field using builder pattern.
///
/// The closure receives `&Table<T, E>` and returns an `Expression<T::Value>`.
/// It is evaluated lazily when `select()` builds the query.
///
/// ```rust,ignore
/// .with_expression("order_count", |t| {
/// t.get_subquery_as::<Order>("orders").unwrap().get_count_query()
/// })
/// ```
pub fn with_expression(
mut self,
name: &str,
expr_fn: impl Fn(&Table<T, E>) -> Expression<T::Value> + Send + Sync + 'static,
) -> Self {
self.expressions.insert(name.to_string(), Arc::new(expr_fn));
self
}
fn lookup_ref(&self, relation: &str) -> Result<(&dyn Reference, String)> {
let table_name = self.table_name().to_string();
let refs = self.refs.as_ref().ok_or_else(|| {
error!(
"No references defined on table",
table = table_name.as_str()
)
})?;
let relation_str = relation.to_string();
let reference = refs.get(relation).ok_or_else(|| {
error!(
"Reference not found on table",
relation = relation_str.as_str(),
table = table_name.as_str()
)
})?;
Ok((reference.as_ref(), relation_str))
}
/// Look up cardinality for a registered relation.
pub fn ref_cardinality(&self, relation: &str) -> Result<vantage_vista::ReferenceKind> {
let (reference, _) = self.lookup_ref(relation)?;
Ok(reference.cardinality())
}
/// List all registered relations with their cardinality.
pub fn ref_kinds(&self) -> Vec<(String, vantage_vista::ReferenceKind)> {
self.refs
.as_ref()
.map(|refs| {
refs.iter()
.map(|(name, r)| (name.clone(), r.cardinality()))
.collect()
})
.unwrap_or_default()
}
}