vantage_table/table/base.rs
1use std::marker::PhantomData;
2use std::sync::Arc;
3
4use indexmap::IndexMap;
5use vantage_expressions::Expression;
6use vantage_types::{EmptyEntity, Entity};
7
8use crate::{
9 pagination::Pagination, references::Reference, sorting::SortDirection, table::hooks::Hooks,
10 traits::table_source::TableSource, traits::table_source_spec::TableSourceSpec,
11};
12
13/// Type alias for expression closures stored on Table.
14///
15/// Stored against the entity-erased `Table<T, EmptyEntity>` rather than the
16/// concrete `Table<T, E>` so the closures survive [`Table::into_entity`] — an
17/// expression only ever reads entity-agnostic table state (columns and
18/// relations by name, conditions, subqueries), never the entity's typed fields.
19/// [`Table::with_expression`] adapts the caller's `Fn(&Table<T, E>)` into this
20/// shape; see `Table::as_entity_erased` for the soundness of the cast.
21pub type ExpressionFn<T> =
22 Arc<dyn Fn(&Table<T, EmptyEntity>) -> Expression<<T as TableSource>::Value> + Send + Sync>;
23
24/// Type alias for lazy-expression callbacks stored on Table.
25///
26/// A lazy expression runs *after* the data source returns a record.
27/// Callbacks apply in declaration order: each borrows the record as built
28/// so far, and the value it returns is inserted under the expression's
29/// name. A later lazy expression therefore sees the columns produced by
30/// earlier ones — one expensive fetch (a file's contents) can feed several
31/// cheap derived columns. See [`Table::with_lazy_expression`].
32pub type LazyExpressionFn<T> = Arc<
33 dyn Fn(
34 &vantage_types::Record<<T as TableSource>::Value>,
35 ) -> std::pin::Pin<
36 Box<
37 dyn std::future::Future<Output = vantage_core::Result<<T as TableSource>::Value>>
38 + Send,
39 >,
40 > + Send
41 + Sync,
42>;
43
44#[derive(Clone)]
45pub struct Table<T, E>
46where
47 T: TableSource,
48 E: Entity<T::Value>,
49{
50 pub(super) data_source: T,
51 pub(super) _phantom: PhantomData<E>,
52 pub(super) source: T::Source,
53 pub(super) columns: IndexMap<String, T::Column<T::AnyType>>,
54 pub(super) conditions: IndexMap<i64, T::Condition>,
55 pub(super) next_condition_id: i64,
56 pub(super) order_by: IndexMap<i64, (T::Condition, SortDirection)>,
57 pub(super) next_order_id: i64,
58 pub(super) refs: Option<IndexMap<String, Arc<dyn Reference>>>,
59 pub(super) contained: Vec<crate::references::ContainedRelation<T>>,
60 pub(super) expressions: IndexMap<String, ExpressionFn<T>>,
61 pub(super) lazy_expressions: IndexMap<String, LazyExpressionFn<T>>,
62 pub(super) pagination: Option<Pagination>,
63 pub(super) title_field: Option<String>,
64 pub(super) title_fields: Vec<String>,
65 pub(super) id_field: Option<String>,
66 /// When true, the id column is a text/string key and backends must NOT
67 /// numerically coerce it (e.g. the Postgres backend otherwise binds an
68 /// all-digit id like `"121"` as `bigint`, which breaks against a `TEXT` id
69 /// column). Set via [`Self::with_text_id`]. Defaults to false to preserve
70 /// the integer-id convention used by other models.
71 pub(super) id_text: bool,
72 /// Column values every row in this set must hold, because they are part of
73 /// the set's definition (e.g. a has-many child carries the parent's foreign
74 /// key). Registered wherever the table is narrowed by a literal
75 /// `column = value` (see [`Self::with_id`], `Reference::resolve_from_row`);
76 /// never from an expression scope. Enforced on write: a column the caller
77 /// left null/absent is filled, a matching value is kept, and a conflicting
78 /// value is rejected.
79 pub(super) invariants: IndexMap<String, T::Value>,
80 /// Lifecycle hooks (see [`Hook`](super::Hook)). Registered via [`Self::with_hook`].
81 pub(super) hooks: Hooks<T>,
82}
83
84impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
85 /// Create a new Table with the given table name and data source
86 pub fn new(table_name: impl Into<String>, data_source: T) -> Self {
87 Self {
88 data_source,
89 _phantom: PhantomData,
90 source: T::Source::from_name(table_name.into()),
91 columns: IndexMap::new(),
92 conditions: IndexMap::new(),
93 next_condition_id: 1,
94 order_by: IndexMap::new(),
95 next_order_id: 1,
96 refs: None,
97 contained: Vec::new(),
98 expressions: IndexMap::new(),
99 lazy_expressions: IndexMap::new(),
100 pagination: None,
101 title_field: None,
102 title_fields: Vec::new(),
103 id_field: None,
104 id_text: false,
105 invariants: IndexMap::new(),
106 hooks: Hooks::default(),
107 }
108 }
109
110 /// Convert this table to use a different entity type.
111 ///
112 /// Computed expressions are carried over — they're stored entity-erased
113 /// (see [`ExpressionFn`]), so aggregates survive reference traversal that
114 /// erases the entity to `EmptyEntity` (e.g. `get_ref_from_row`).
115 pub fn into_entity<E2: Entity<T::Value>>(self) -> Table<T, E2> {
116 Table {
117 data_source: self.data_source,
118 _phantom: PhantomData,
119 source: self.source,
120 columns: self.columns,
121 conditions: self.conditions,
122 next_condition_id: self.next_condition_id,
123 order_by: self.order_by,
124 next_order_id: self.next_order_id,
125 refs: self.refs,
126 contained: self.contained,
127 expressions: self.expressions,
128 lazy_expressions: self.lazy_expressions,
129 pagination: self.pagination,
130 title_field: self.title_field,
131 title_fields: self.title_fields,
132 id_field: self.id_field,
133 id_text: self.id_text,
134 invariants: self.invariants,
135 hooks: self.hooks,
136 }
137 }
138
139 /// Borrow this table as its entity-erased form `Table<T, EmptyEntity>`.
140 ///
141 /// `E` appears in `Table` only as `PhantomData<E>` (a zero-sized field), so
142 /// `Table<T, E>` and `Table<T, EmptyEntity>` are layout-identical and this
143 /// reinterpret is sound. Used to feed `self` to the entity-erased
144 /// [`ExpressionFn`] closures at evaluation time.
145 pub(crate) fn as_entity_erased(&self) -> &Table<T, EmptyEntity> {
146 // SAFETY: identical layout (E is PhantomData only); lifetime is tied to
147 // `&self`, and the borrow is shared/read-only.
148 unsafe { &*(self as *const Table<T, E> as *const Table<T, EmptyEntity>) }
149 }
150
151 /// Apply lazy expressions to one returned record, in declaration order.
152 /// Each callback borrows the record as built so far; the value it
153 /// returns is inserted under the expression's name before the next
154 /// callback runs. See [`Self::with_lazy_expression`].
155 pub(crate) async fn apply_lazy_expressions(
156 &self,
157 record: &mut vantage_types::Record<T::Value>,
158 ) -> vantage_core::Result<()> {
159 for (name, f) in &self.lazy_expressions {
160 let value = f(record).await?;
161 record.insert(name.clone(), value);
162 }
163 Ok(())
164 }
165
166 /// Snapshot the table's relations as Vista references (name, target type,
167 /// cardinality, foreign key). Driver factories fold this into
168 /// `VistaMetadata` so the erased `Vista` carries enough to drive nested
169 /// insert and relation traversal.
170 pub fn vista_references(&self) -> Vec<vantage_vista::Reference> {
171 self.refs
172 .as_ref()
173 .map(|refs| {
174 refs.iter()
175 .map(|(name, r)| {
176 vantage_vista::Reference::new(
177 name.clone(),
178 r.target_type_name().to_string(),
179 r.cardinality(),
180 r.foreign_key().to_string(),
181 )
182 })
183 .collect()
184 })
185 .unwrap_or_default()
186 }
187
188 /// Shape-only specs (name, host, kind, id) for the contained relations
189 /// declared on this table, for driver factories to fold into
190 /// `VistaMetadata`. Columns are derived at traversal from each relation's
191 /// `build_target` closure.
192 pub fn vista_contained(&self) -> Vec<vantage_vista::ContainedSpec> {
193 self.contained.iter().map(|c| c.spec()).collect()
194 }
195
196 /// Look up a contained relation by name (for the driver's traversal).
197 pub fn contained_relation(
198 &self,
199 name: &str,
200 ) -> Option<&crate::references::ContainedRelation<T>> {
201 self.contained.iter().find(|c| c.name() == name)
202 }
203
204 /// Use a callback with a builder pattern for configuration
205 pub fn with<F>(mut self, func: F) -> Self
206 where
207 F: FnOnce(&mut Self),
208 {
209 func(&mut self);
210 self
211 }
212
213 /// Get the table name.
214 ///
215 /// For a query-sourced table this is its FROM alias.
216 pub fn table_name(&self) -> &str {
217 self.source.name()
218 }
219
220 /// The table's source (a name, or a query used as a derived source).
221 pub fn source(&self) -> &T::Source {
222 &self.source
223 }
224
225 /// Override the table name. Used by REST API drivers to swap a
226 /// canonical resource path for a per-reference URI template at
227 /// traversal time.
228 ///
229 /// This replaces the source with a name-based one, so it must not be
230 /// called on a query-sourced (derived) table.
231 pub fn set_table_name(&mut self, name: impl Into<String>) {
232 self.source = T::Source::from_name(name.into());
233 }
234
235 /// Get the underlying data source
236 pub fn data_source(&self) -> &T {
237 &self.data_source
238 }
239
240 /// Get the title field column if set
241 pub fn title_field(&self) -> Option<&T::Column<T::AnyType>> {
242 self.title_field
243 .as_ref()
244 .and_then(|name| self.columns.get(name))
245 }
246
247 /// Names of columns marked as display titles (set via
248 /// [`Self::with_title_column_of`]). These show alongside the id in
249 /// list views and on the leading lines of single-record displays.
250 pub fn title_fields(&self) -> &[String] {
251 &self.title_fields
252 }
253
254 /// Get the id field column if set
255 pub fn id_field(&self) -> Option<&T::Column<T::AnyType>> {
256 self.id_field
257 .as_ref()
258 .and_then(|name| self.columns.get(name))
259 }
260
261 /// Mark an already-added column as the id field.
262 ///
263 /// Use this when the id column has been added via [`Self::add_column`]
264 /// (so its type and aliases were chosen explicitly) and you only need
265 /// to flag it. [`Self::with_id_column`] is the typed shortcut that
266 /// creates the column for you.
267 pub fn set_id_field(&mut self, name: impl Into<String>) {
268 self.id_field = Some(name.into());
269 }
270
271 /// Mark an already-added column as a display title.
272 ///
273 /// Companion to [`Self::set_id_field`] for spec-driven construction.
274 pub fn add_title_field(&mut self, name: impl Into<String>) {
275 let name = name.into();
276 if !self.title_fields.contains(&name) {
277 self.title_fields.push(name.clone());
278 }
279 if self.title_field.is_none() {
280 self.title_field = Some(name);
281 }
282 }
283
284 /// Get the current pagination configuration, if set
285 pub fn pagination(&self) -> Option<&Pagination> {
286 self.pagination.as_ref()
287 }
288
289 /// Column values every row in this set must hold (see the `invariants`
290 /// field): enforced on write — filled when null/absent, kept when matching,
291 /// rejected when conflicting.
292 pub fn invariants(&self) -> &IndexMap<String, T::Value> {
293 &self.invariants
294 }
295
296 /// Register an invariant value for `column` on this set.
297 ///
298 /// A later call for the same column overwrites the earlier invariant.
299 pub fn add_invariant(&mut self, column: impl Into<String>, value: T::Value) {
300 self.invariants.insert(column.into(), value);
301 }
302
303 /// Builder form of [`Self::add_invariant`].
304 pub fn with_invariant(mut self, column: impl Into<String>, value: T::Value) -> Self {
305 self.add_invariant(column, value);
306 self
307 }
308}
309
310impl<T: TableSource, E: Entity<T::Value>> std::ops::Index<&str> for Table<T, E> {
311 type Output = T::Column<T::AnyType>;
312
313 fn index(&self, index: &str) -> &Self::Output {
314 &self.columns[index]
315 }
316}
317
318impl<T: TableSource, E: Entity<T::Value>> std::fmt::Debug for Table<T, E> {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 f.debug_struct("Table")
321 .field("table_name", &self.table_name())
322 .field("columns", &self.columns.keys().collect::<Vec<_>>())
323 .field("conditions_count", &self.conditions.len())
324 .field(
325 "refs_count",
326 &self.refs.as_ref().map(|r| r.len()).unwrap_or(0),
327 )
328 .field("expressions_count", &self.expressions.len())
329 .finish()
330 }
331}