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};
7use vantage_vista::Denials;
8
9use crate::{
10    pagination::Pagination, references::Reference, sorting::SortDirection, table::hooks::Hooks,
11    traits::table_source::TableSource, traits::table_source_spec::TableSourceSpec,
12};
13
14mod accessors;
15mod computed;
16mod relations;
17
18/// An expression closure stored on a table, against the entity-erased table so
19/// it survives [`Table::into_entity`]. It runs when a query that includes the
20/// column is built ([`Table::try_select`]), never when the table is; an error
21/// fails that query. See [`Table::with_expression`] and
22/// [`Table::with_try_expression`].
23pub type ExpressionFn<T> = Arc<
24    dyn Fn(&Table<T, EmptyEntity>) -> vantage_core::Result<Expression<<T as TableSource>::Value>>
25        + Send
26        + Sync,
27>;
28
29/// Context key a failed expression callback's error gains: the column whose
30/// callback failed.
31pub const EXPRESSION_COLUMN: &str = "expression_column";
32/// Context key a failed expression callback's error gains: the table the
33/// column is on.
34pub const EXPRESSION_TABLE: &str = "expression_table";
35
36/// A lazy-expression callback stored on a table: runs on each returned record
37/// and sees the columns earlier callbacks produced. See
38/// [`Table::with_lazy_expression`].
39pub type LazyExpressionFn<T> = Arc<
40    dyn Fn(
41            &vantage_types::Record<<T as TableSource>::Value>,
42        ) -> std::pin::Pin<
43            Box<
44                dyn std::future::Future<Output = vantage_core::Result<<T as TableSource>::Value>>
45                    + Send,
46            >,
47        > + Send
48        + Sync,
49>;
50
51#[derive(Clone)]
52pub struct Table<T, E>
53where
54    T: TableSource,
55    E: Entity<T::Value>,
56{
57    pub(super) data_source: T,
58    pub(super) _phantom: PhantomData<E>,
59    pub(super) source: T::Source,
60    pub(super) columns: IndexMap<String, T::Column<T::AnyType>>,
61    pub(super) conditions: IndexMap<i64, T::Condition>,
62    pub(super) next_condition_id: i64,
63    pub(super) order_by: IndexMap<i64, (T::Condition, SortDirection)>,
64    pub(super) next_order_id: i64,
65    pub(super) refs: Option<IndexMap<String, Arc<dyn Reference>>>,
66    pub(super) contained: Vec<crate::references::ContainedRelation<T>>,
67    pub(super) expressions: IndexMap<String, ExpressionFn<T>>,
68    pub(super) lazy_expressions: IndexMap<String, LazyExpressionFn<T>>,
69    /// Vista-computed columns with their position among all columns, stored
70    /// and computed. The table never selects or writes them.
71    pub(super) computed_columns: IndexMap<String, (usize, vantage_vista::Column)>,
72    /// When `Some`, `select()` projects only these names (plus the id column);
73    /// dotted names are implicit references. See [`Self::with_active_columns`].
74    pub(super) active_columns: Option<indexmap::IndexSet<String>>,
75    /// Dotted implicit-reference columns (`"country.name"`): read-only
76    /// projections that write paths must never persist (a SCHEMALESS store
77    /// would create a literal `country.name` field).
78    pub(super) imported_columns: indexmap::IndexSet<String>,
79    pub(super) pagination: Option<Pagination>,
80    pub(super) title_field: Option<String>,
81    pub(super) title_fields: Vec<String>,
82    pub(super) id_field: Option<String>,
83    /// See [`Self::with_text_id`].
84    pub(super) id_text: bool,
85    /// See [`Self::with_auto_id`].
86    pub(super) id_auto: bool,
87    /// See [`Self::invariants`].
88    pub(super) invariants: IndexMap<String, T::Value>,
89    pub(super) hooks: Hooks<T>,
90    /// See [`Self::set_lock`].
91    pub(super) lock: bool,
92    /// See [`Self::deny`].
93    pub(super) denials: Denials,
94}
95
96impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
97    /// Create a new Table with the given table name and data source
98    pub fn new(table_name: impl Into<String>, data_source: T) -> Self {
99        Self {
100            data_source,
101            _phantom: PhantomData,
102            source: T::Source::from_name(table_name.into()),
103            columns: IndexMap::new(),
104            conditions: IndexMap::new(),
105            next_condition_id: 1,
106            order_by: IndexMap::new(),
107            next_order_id: 1,
108            refs: None,
109            contained: Vec::new(),
110            expressions: IndexMap::new(),
111            lazy_expressions: IndexMap::new(),
112            computed_columns: IndexMap::new(),
113            active_columns: None,
114            imported_columns: indexmap::IndexSet::new(),
115            pagination: None,
116            title_field: None,
117            title_fields: Vec::new(),
118            id_field: None,
119            id_text: false,
120            id_auto: false,
121            invariants: IndexMap::new(),
122            hooks: Hooks::default(),
123            lock: false,
124            denials: Denials::default(),
125        }
126    }
127
128    /// Convert this table to use a different entity type.
129    ///
130    /// Computed expressions are carried over — they're stored entity-erased
131    /// (see [`ExpressionFn`]), so aggregates survive reference traversal that
132    /// erases the entity to `EmptyEntity` (e.g. `get_ref_from_row`).
133    pub fn into_entity<E2: Entity<T::Value>>(self) -> Table<T, E2> {
134        Table {
135            data_source: self.data_source,
136            _phantom: PhantomData,
137            source: self.source,
138            columns: self.columns,
139            conditions: self.conditions,
140            next_condition_id: self.next_condition_id,
141            order_by: self.order_by,
142            next_order_id: self.next_order_id,
143            refs: self.refs,
144            contained: self.contained,
145            expressions: self.expressions,
146            lazy_expressions: self.lazy_expressions,
147            computed_columns: self.computed_columns,
148            active_columns: self.active_columns,
149            imported_columns: self.imported_columns,
150            pagination: self.pagination,
151            title_field: self.title_field,
152            title_fields: self.title_fields,
153            id_field: self.id_field,
154            id_text: self.id_text,
155            id_auto: self.id_auto,
156            invariants: self.invariants,
157            hooks: self.hooks,
158            lock: self.lock,
159            denials: self.denials,
160        }
161    }
162
163    /// Borrow this table as its entity-erased form `Table<T, EmptyEntity>`.
164    ///
165    /// `E` appears in `Table` only as `PhantomData<E>` (a zero-sized field), so
166    /// `Table<T, E>` and `Table<T, EmptyEntity>` are layout-identical and this
167    /// reinterpret is sound. Used to feed `self` to the entity-erased
168    /// [`ExpressionFn`] closures at evaluation time.
169    pub(crate) fn as_entity_erased(&self) -> &Table<T, EmptyEntity> {
170        // SAFETY: identical layout (E is PhantomData only); lifetime is tied to
171        // `&self`, and the borrow is shared/read-only.
172        unsafe { &*(self as *const Table<T, E> as *const Table<T, EmptyEntity>) }
173    }
174}
175
176impl<T: TableSource, E: Entity<T::Value>> std::ops::Index<&str> for Table<T, E> {
177    type Output = T::Column<T::AnyType>;
178
179    fn index(&self, index: &str) -> &Self::Output {
180        &self.columns[index]
181    }
182}
183
184impl<T: TableSource, E: Entity<T::Value>> std::fmt::Debug for Table<T, E> {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.debug_struct("Table")
187            .field("table_name", &self.table_name())
188            .field("columns", &self.columns.keys().collect::<Vec<_>>())
189            .field("conditions_count", &self.conditions.len())
190            .field(
191                "refs_count",
192                &self.refs.as_ref().map(|r| r.len()).unwrap_or(0),
193            )
194            .field("expressions_count", &self.expressions.len())
195            .finish()
196    }
197}