Skip to main content

vantage_table/table/impls/
columns.rs

1use indexmap::IndexMap;
2use vantage_expressions::{Expression, Expressive, traits::datasource::ExprDataSource};
3use vantage_types::Entity;
4
5use crate::{
6    column::core::ColumnType, prelude::ColumnLike, table::Table, traits::table_source::TableSource,
7};
8
9impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
10    /// Add a column to the table (accepts any typed column, converts to `Column<AnyType>`)
11    pub fn add_column<NewColumnType>(&mut self, column: T::Column<NewColumnType>)
12    where
13        NewColumnType: ColumnType,
14    {
15        let name = column.name().to_string();
16
17        if self.columns.contains_key(&name) {
18            panic!("Duplicate column: {}", name);
19        }
20
21        // Convert typed column to Column<AnyType> for storage
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    /// Add a typed column AND mark it as a display title.
94    ///
95    /// Title columns show alongside the id in generic list views and
96    /// lead the body of single-record displays. Multiple title columns
97    /// are allowed; their order matches the order of these calls.
98    pub fn with_title_column_of<NewColumnType>(mut self, name: impl Into<String>) -> Self
99    where
100        NewColumnType: ColumnType,
101    {
102        let name = name.into();
103        if !self.title_fields.contains(&name) {
104            self.title_fields.push(name.clone());
105        }
106        if self.title_field.is_none() {
107            self.title_field = Some(name.clone());
108        }
109        let column = self.data_source.create_column::<NewColumnType>(&name);
110        self.add_column(column);
111        self
112    }
113
114    /// Add a typed column to the table (builder pattern)
115    pub fn with_column_of<NewColumnType>(self, name: impl Into<String>) -> Self
116    where
117        NewColumnType: ColumnType,
118    {
119        let column = self
120            .data_source
121            .create_column::<NewColumnType>(&name.into());
122        self.with_column(column)
123    }
124
125    /// Get all columns as type-erased columns (`Column<AnyType>`)
126    pub fn columns(&self) -> &IndexMap<String, T::Column<T::AnyType>> {
127        &self.columns
128    }
129
130    /// Get a typed column by converting from stored `Column<AnyType>`
131    pub fn get_column<Type>(&self, name: &str) -> Option<T::Column<Type>>
132    where
133        Type: ColumnType,
134    {
135        let any_column = self.columns.get(name)?;
136        self.data_source
137            .convert_any_column::<Type>(any_column.clone())
138    }
139
140    /// Get an expression for a column or computed expression by name.
141    ///
142    /// If `name` matches a registered expression (from `with_expression`), evaluates
143    /// and returns it. Otherwise returns the column as an expression. Returns `None`
144    /// if the name doesn't match either.
145    pub fn get_column_expr(&self, name: &str) -> Option<vantage_expressions::Expression<T::Value>>
146    where
147        T::Column<T::AnyType>: vantage_expressions::Expressive<T::Value>,
148    {
149        if let Some(expr_fn) = self.expressions.get(name) {
150            Some(expr_fn(self.as_entity_erased()))
151        } else {
152            use vantage_expressions::Expressive;
153            self.columns.get(name).map(|c| c.expr())
154        }
155    }
156}
157
158impl<T, E> Table<T, E>
159where
160    T: TableSource + ExprDataSource<T::Value>,
161    E: Entity<T::Value> + 'static,
162{
163    /// Expression yielding all values of the named column under the
164    /// table's current conditions.
165    ///
166    /// SQL backends materialise this as a `SELECT col FROM tbl WHERE …`
167    /// subquery (embeddable directly into IN clauses); non-query
168    /// backends wrap a `DeferredFn` that runs `list_table_values` and
169    /// projects the column at execute time.
170    ///
171    /// Panics if `column_name` isn't a column on this table — the
172    /// callsite is meant to be a literal column reference, so a typo
173    /// is a programmer error, not a runtime failure mode worth
174    /// surfacing as `Result`.
175    pub fn column_values_expr(&self, column_name: &str) -> Expression<T::Value> {
176        let col = self
177            .get_column::<T::AnyType>(column_name)
178            .unwrap_or_else(|| panic!("column {column_name:?} not found on table"));
179        self.data_source.column_table_values_expr(self, &col).expr()
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::mocks::mock_column::MockColumn;
187    use crate::prelude::MockTableSource;
188    use serde_json::Value;
189    use vantage_types::EmptyEntity;
190
191    #[test]
192    fn test_add_column() {
193        let ds = MockTableSource::new();
194        let mut table = Table::<MockTableSource, EmptyEntity>::new("test", ds);
195
196        table.add_column(MockColumn::<String>::new("name"));
197
198        assert!(table.columns().contains_key("name"));
199        assert_eq!(table.columns().len(), 1);
200    }
201
202    #[test]
203    fn test_with_column() {
204        let ds = MockTableSource::new();
205        let table = Table::<MockTableSource, EmptyEntity>::new("test", ds)
206            .with_column(MockColumn::<Value>::new("name"))
207            .with_column(MockColumn::<i32>::new("email"));
208
209        assert!(table.columns().contains_key("name"));
210        assert!(table.columns().contains_key("email"));
211        assert_eq!(table.columns().len(), 2);
212    }
213
214    #[test]
215    #[should_panic(expected = "Duplicate column")]
216    fn test_duplicate_column_panics() {
217        let ds = MockTableSource::new();
218        let mut table = Table::<MockTableSource, EmptyEntity>::new("test", ds);
219
220        table.add_column(MockColumn::<String>::new("name"));
221        table.add_column(MockColumn::<String>::new("name")); // Should panic
222    }
223
224    #[test]
225    fn test_with_column_of() {
226        let ds = MockTableSource::new();
227        let table = Table::<MockTableSource, EmptyEntity>::new("test", ds)
228            .with_column_of::<String>("name")
229            .with_column_of::<i64>("age")
230            .with_column_of::<bool>("active");
231
232        assert!(table.columns().contains_key("name"));
233        assert!(table.columns().contains_key("age"));
234        assert!(table.columns().contains_key("active"));
235        assert_eq!(table.columns().len(), 3);
236    }
237
238    #[test]
239    fn test_add_column_of() {
240        let ds = MockTableSource::new();
241        let mut table = Table::<MockTableSource, EmptyEntity>::new("test", ds);
242
243        table.add_column_of::<String>("email");
244        table.add_column_of::<i64>("balance");
245
246        assert!(table.columns().contains_key("email"));
247        assert!(table.columns().contains_key("balance"));
248        assert_eq!(table.columns().len(), 2);
249    }
250
251    #[test]
252    fn test_columns_access() {
253        let ds = MockTableSource::new();
254        let table = Table::<MockTableSource, EmptyEntity>::new("test", ds)
255            .with_column_of::<String>("name")
256            .with_column_of::<i64>("age");
257
258        let columns = table.columns();
259        assert!(columns.contains_key("name"));
260        assert!(columns.contains_key("age"));
261        assert_eq!(columns.len(), 2);
262
263        let name_column = table.columns().get("name");
264        assert!(name_column.is_some());
265        assert_eq!(name_column.unwrap().name(), "name");
266
267        let missing_column = table.columns().get("missing");
268        assert!(missing_column.is_none());
269    }
270}