Skip to main content

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    /// Public so driver shells that bypass the `list_values` read path
156    /// (e.g. a REST shell's windowed fetch) can still apply lazy columns.
157    pub async fn apply_lazy_expressions(
158        &self,
159        record: &mut vantage_types::Record<T::Value>,
160    ) -> vantage_core::Result<()> {
161        for (name, f) in &self.lazy_expressions {
162            let value = f(record).await?;
163            record.insert(name.clone(), value);
164        }
165        Ok(())
166    }
167
168    /// Snapshot the table's relations as Vista references (name, target type,
169    /// cardinality, foreign key). Driver factories fold this into
170    /// `VistaMetadata` so the erased `Vista` carries enough to drive nested
171    /// insert and relation traversal.
172    pub fn vista_references(&self) -> Vec<vantage_vista::Reference> {
173        self.refs
174            .as_ref()
175            .map(|refs| {
176                refs.iter()
177                    .map(|(name, r)| {
178                        vantage_vista::Reference::new(
179                            name.clone(),
180                            r.target_type_name().to_string(),
181                            r.cardinality(),
182                            r.foreign_key().to_string(),
183                        )
184                    })
185                    .collect()
186            })
187            .unwrap_or_default()
188    }
189
190    /// Shape-only specs (name, host, kind, id) for the contained relations
191    /// declared on this table, for driver factories to fold into
192    /// `VistaMetadata`. Columns are derived at traversal from each relation's
193    /// `build_target` closure.
194    pub fn vista_contained(&self) -> Vec<vantage_vista::ContainedSpec> {
195        self.contained.iter().map(|c| c.spec()).collect()
196    }
197
198    /// Look up a contained relation by name (for the driver's traversal).
199    pub fn contained_relation(
200        &self,
201        name: &str,
202    ) -> Option<&crate::references::ContainedRelation<T>> {
203        self.contained.iter().find(|c| c.name() == name)
204    }
205
206    /// Use a callback with a builder pattern for configuration
207    pub fn with<F>(mut self, func: F) -> Self
208    where
209        F: FnOnce(&mut Self),
210    {
211        func(&mut self);
212        self
213    }
214
215    /// Get the table name.
216    ///
217    /// For a query-sourced table this is its FROM alias.
218    pub fn table_name(&self) -> &str {
219        self.source.name()
220    }
221
222    /// The table's source (a name, or a query used as a derived source).
223    pub fn source(&self) -> &T::Source {
224        &self.source
225    }
226
227    /// Override the table name. Used by REST API drivers to swap a
228    /// canonical resource path for a per-reference URI template at
229    /// traversal time.
230    ///
231    /// This replaces the source with a name-based one, so it must not be
232    /// called on a query-sourced (derived) table.
233    pub fn set_table_name(&mut self, name: impl Into<String>) {
234        self.source = T::Source::from_name(name.into());
235    }
236
237    /// Get the underlying data source
238    pub fn data_source(&self) -> &T {
239        &self.data_source
240    }
241
242    /// Get the title field column if set
243    pub fn title_field(&self) -> Option<&T::Column<T::AnyType>> {
244        self.title_field
245            .as_ref()
246            .and_then(|name| self.columns.get(name))
247    }
248
249    /// Names of columns marked as display titles (set via
250    /// [`Self::with_title_column_of`]). These show alongside the id in
251    /// list views and on the leading lines of single-record displays.
252    pub fn title_fields(&self) -> &[String] {
253        &self.title_fields
254    }
255
256    /// Get the id field column if set
257    pub fn id_field(&self) -> Option<&T::Column<T::AnyType>> {
258        self.id_field
259            .as_ref()
260            .and_then(|name| self.columns.get(name))
261    }
262
263    /// Mark an already-added column as the id field.
264    ///
265    /// Use this when the id column has been added via [`Self::add_column`]
266    /// (so its type and aliases were chosen explicitly) and you only need
267    /// to flag it. [`Self::with_id_column`] is the typed shortcut that
268    /// creates the column for you.
269    pub fn set_id_field(&mut self, name: impl Into<String>) {
270        self.id_field = Some(name.into());
271    }
272
273    /// Mark an already-added column as a display title.
274    ///
275    /// Companion to [`Self::set_id_field`] for spec-driven construction.
276    pub fn add_title_field(&mut self, name: impl Into<String>) {
277        let name = name.into();
278        if !self.title_fields.contains(&name) {
279            self.title_fields.push(name.clone());
280        }
281        if self.title_field.is_none() {
282            self.title_field = Some(name);
283        }
284    }
285
286    /// Get the current pagination configuration, if set
287    pub fn pagination(&self) -> Option<&Pagination> {
288        self.pagination.as_ref()
289    }
290
291    /// Column values every row in this set must hold (see the `invariants`
292    /// field): enforced on write — filled when null/absent, kept when matching,
293    /// rejected when conflicting.
294    pub fn invariants(&self) -> &IndexMap<String, T::Value> {
295        &self.invariants
296    }
297
298    /// Register an invariant value for `column` on this set.
299    ///
300    /// A later call for the same column overwrites the earlier invariant.
301    pub fn add_invariant(&mut self, column: impl Into<String>, value: T::Value) {
302        self.invariants.insert(column.into(), value);
303    }
304
305    /// Builder form of [`Self::add_invariant`].
306    pub fn with_invariant(mut self, column: impl Into<String>, value: T::Value) -> Self {
307        self.add_invariant(column, value);
308        self
309    }
310}
311
312impl<T: TableSource, E: Entity<T::Value>> std::ops::Index<&str> for Table<T, E> {
313    type Output = T::Column<T::AnyType>;
314
315    fn index(&self, index: &str) -> &Self::Output {
316        &self.columns[index]
317    }
318}
319
320impl<T: TableSource, E: Entity<T::Value>> std::fmt::Debug for Table<T, E> {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        f.debug_struct("Table")
323            .field("table_name", &self.table_name())
324            .field("columns", &self.columns.keys().collect::<Vec<_>>())
325            .field("conditions_count", &self.conditions.len())
326            .field(
327                "refs_count",
328                &self.refs.as_ref().map(|r| r.len()).unwrap_or(0),
329            )
330            .field("expressions_count", &self.expressions.len())
331            .finish()
332    }
333}