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