Skip to main content

vantage_table/table/impls/
columns.rs

1use indexmap::IndexMap;
2use vantage_core::Result;
3use vantage_expressions::{Expression, Expressive, traits::datasource::ExprDataSource};
4use vantage_types::Entity;
5
6use crate::{
7    column::core::ColumnType, prelude::ColumnLike, table::Table, traits::table_source::TableSource,
8};
9
10impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
11    /// Add a column to the table (accepts any typed column, converts to `Column<AnyType>`)
12    pub fn add_column<NewColumnType>(&mut self, column: T::Column<NewColumnType>)
13    where
14        NewColumnType: ColumnType,
15    {
16        let name = column.name().to_string();
17
18        if self.columns.contains_key(&name) {
19            panic!("Duplicate column: {}", name);
20        }
21
22        let any_column = self.data_source.to_any_column(column);
23        self.columns.insert(name, any_column);
24    }
25
26    /// Add a column using builder pattern
27    pub fn with_column<NewColumnType>(mut self, column: T::Column<NewColumnType>) -> Self
28    where
29        NewColumnType: ColumnType,
30    {
31        self.add_column(column);
32        self
33    }
34
35    /// Copy column definitions from another table, skipping any whose name is
36    /// already present. With `names = None`, copies all columns; otherwise only
37    /// the listed ones. Used to inherit columns when deriving a table from
38    /// another (see `Table::derive_from`).
39    pub fn copy_columns_from<E2: Entity<T::Value>>(
40        &mut self,
41        other: &Table<T, E2>,
42        names: Option<&[&str]>,
43    ) {
44        for col in other.columns().values() {
45            let name = col.name();
46            if names.is_some_and(|ns| !ns.contains(&name)) {
47                continue;
48            }
49            if !self.columns.contains_key(name) {
50                self.add_column(col.clone());
51            }
52        }
53    }
54
55    /// Add a typed column to the table (mutable)
56    pub fn add_column_of<NewColumnType>(&mut self, name: impl Into<String>)
57    where
58        NewColumnType: ColumnType,
59    {
60        let column = self
61            .data_source
62            .create_column::<NewColumnType>(&name.into());
63        self.add_column(column);
64    }
65
66    /// Add an ID column — sets both the column and the id_field flag.
67    pub fn with_id_column(mut self, name: impl Into<String>) -> Self
68    where
69        T::Id: ColumnType,
70    {
71        let name = name.into();
72        self.id_field = Some(name.clone());
73        let column = self.data_source.create_column::<T::Id>(&name);
74        self.add_column(column);
75        self
76    }
77
78    /// Mark the id column as a text/string key so backends do not numerically
79    /// coerce it. Use for models whose id column is `TEXT` even when some ids
80    /// look numeric (e.g. ids from an external API mixed with generated UUIDs);
81    /// without this the Postgres backend binds an all-digit id like `"121"` as
82    /// `bigint`, which fails against a `TEXT` id column.
83    pub fn with_text_id(mut self) -> Self {
84        self.id_text = true;
85        self
86    }
87
88    /// Whether the id column is a text key (see [`Self::with_text_id`]).
89    pub fn id_is_text(&self) -> bool {
90        self.id_text
91    }
92
93    /// Mark the id column as backend-made (SQL auto-increment, SurrealDB
94    /// generated record ids, MongoDB ObjectIds). Vista metadata then flags it
95    /// [`ColumnFlag::Auto`](vantage_vista::ColumnFlag::Auto).
96    pub fn with_auto_id(mut self) -> Self {
97        self.id_auto = true;
98        self
99    }
100
101    /// Whether the backend makes this table's ids (see [`Self::with_auto_id`]).
102    pub fn has_auto_id(&self) -> bool {
103        self.id_auto
104    }
105
106    /// Add a typed column AND mark it as a display title.
107    ///
108    /// Title columns show alongside the id in generic list views and
109    /// lead the body of single-record displays. Multiple title columns
110    /// are allowed; their order matches the order of these calls.
111    pub fn with_title_column_of<NewColumnType>(mut self, name: impl Into<String>) -> Self
112    where
113        NewColumnType: ColumnType,
114    {
115        let name = name.into();
116        if !self.title_fields.contains(&name) {
117            self.title_fields.push(name.clone());
118        }
119        if self.title_field.is_none() {
120            self.title_field = Some(name.clone());
121        }
122        let column = self.data_source.create_column::<NewColumnType>(&name);
123        self.add_column(column);
124        self
125    }
126
127    /// Add a pre-built column AND mark it as a display title — the
128    /// flag-carrying twin of [`Self::with_title_column_of`], for callers
129    /// that need flags (searchable, mandatory) on a title column.
130    pub fn with_title_column<NewColumnType>(mut self, column: T::Column<NewColumnType>) -> Self
131    where
132        NewColumnType: ColumnType,
133    {
134        let name = column.name().to_string();
135        if !self.title_fields.contains(&name) {
136            self.title_fields.push(name.clone());
137        }
138        if self.title_field.is_none() {
139            self.title_field = Some(name);
140        }
141        self.add_column(column);
142        self
143    }
144
145    /// Add a typed column to the table (builder pattern)
146    pub fn with_column_of<NewColumnType>(self, name: impl Into<String>) -> Self
147    where
148        NewColumnType: ColumnType,
149    {
150        let column = self
151            .data_source
152            .create_column::<NewColumnType>(&name.into());
153        self.with_column(column)
154    }
155
156    /// Take a column out of the table: stored, expression, lazy or
157    /// vista-computed, so it is neither selected nor shown. Invariants and
158    /// conditions naming it stay, so inserts are still stamped with its
159    /// value and rows are still narrowed by it; references hold their
160    /// foreign key by name and keep traversing.
161    pub fn remove_column(&mut self, name: &str) -> vantage_core::Result<()> {
162        if name == self.id_field_name() {
163            return Err(vantage_core::error!(format!(
164                "`{name}` is the id column of `{}`; it can't be removed",
165                self.table_name()
166            )));
167        }
168        let mut found = false;
169        if let Some((stored_index, _, _)) = self.columns.shift_remove_full(name) {
170            found = true;
171            let removed = self.position_of_stored(stored_index);
172            for (at, _) in self.computed_columns.values_mut() {
173                if *at > removed {
174                    *at -= 1;
175                }
176            }
177        }
178        if let Some((removed, _)) = self.computed_columns.shift_remove(name) {
179            found = true;
180            for (at, _) in self.computed_columns.values_mut() {
181                if *at > removed {
182                    *at -= 1;
183                }
184            }
185        }
186        found |= self.expressions.shift_remove(name).is_some();
187        found |= self.lazy_expressions.shift_remove(name).is_some();
188        if !found {
189            return Err(vantage_core::error!(format!(
190                "no column `{name}` in `{}`",
191                self.table_name()
192            )));
193        }
194        self.imported_columns.shift_remove(name);
195        if let Some(active) = &mut self.active_columns {
196            active.shift_remove(name);
197        }
198        self.title_fields.retain(|title| title != name);
199        if self.title_field.as_deref() == Some(name) {
200            self.title_field = self.title_fields.first().cloned();
201        }
202        Ok(())
203    }
204
205    /// Get all columns as type-erased columns (`Column<AnyType>`)
206    pub fn columns(&self) -> &IndexMap<String, T::Column<T::AnyType>> {
207        &self.columns
208    }
209
210    /// Get a typed column by converting from stored `Column<AnyType>`
211    pub fn get_column<Type>(&self, name: &str) -> Option<T::Column<Type>>
212    where
213        Type: ColumnType,
214    {
215        let any_column = self.columns.get(name)?;
216        self.data_source
217            .convert_any_column::<Type>(any_column.clone())
218    }
219
220    /// Get an expression for a column or computed expression by name.
221    ///
222    /// If `name` matches a registered expression (from `with_expression`), evaluates
223    /// and returns it. Otherwise returns the column as an expression. Returns `None`
224    /// if the name doesn't match either.
225    ///
226    /// Panics if the expression callback fails; use
227    /// [`try_get_column_expr`](Self::try_get_column_expr).
228    pub fn get_column_expr(&self, name: &str) -> Option<Expression<T::Value>>
229    where
230        T::Column<T::AnyType>: Expressive<T::Value>,
231    {
232        self.try_get_column_expr(name)
233            .unwrap_or_else(|e| panic!("{e}"))
234    }
235
236    /// [`get_column_expr`](Self::get_column_expr) returning the error of a
237    /// failed expression callback.
238    pub fn try_get_column_expr(&self, name: &str) -> Result<Option<Expression<T::Value>>>
239    where
240        T::Column<T::AnyType>: Expressive<T::Value>,
241    {
242        Ok(match self.try_expression_column(name)? {
243            Some(expr) => Some(expr),
244            None => self.columns.get(name).map(|c| c.expr()),
245        })
246    }
247
248    /// The expression an aggregate or a one-column subquery reads for
249    /// `column`: its callback's when it is an expression column of this
250    /// table, the column itself otherwise.
251    pub fn try_column_expr_of<Type>(&self, column: &T::Column<Type>) -> Result<Expression<T::Value>>
252    where
253        Type: ColumnType,
254        T::Column<Type>: Expressive<T::Value>,
255    {
256        Ok(self
257            .try_expression_column(column.name())?
258            .unwrap_or_else(|| column.expr()))
259    }
260}
261
262impl<T, E> Table<T, E>
263where
264    T: TableSource + ExprDataSource<T::Value>,
265    E: Entity<T::Value> + 'static,
266{
267    /// Expression yielding all values of the named column under the
268    /// table's current conditions.
269    ///
270    /// SQL backends materialise this as a `SELECT col FROM tbl WHERE …`
271    /// subquery (embeddable directly into IN clauses); non-query
272    /// backends wrap a `DeferredFn` that runs `list_table_values` and
273    /// projects the column at execute time.
274    ///
275    /// Panics if `column_name` isn't a column on this table — the
276    /// callsite is meant to be a literal column reference, so a typo
277    /// is a programmer error, not a runtime failure mode worth
278    /// surfacing as `Result`.
279    pub fn column_values_expr(&self, column_name: &str) -> Expression<T::Value> {
280        let col = self
281            .get_column::<T::AnyType>(column_name)
282            .unwrap_or_else(|| panic!("column {column_name:?} not found on table"));
283        self.data_source.column_table_values_expr(self, &col).expr()
284    }
285}