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::Entity;
7
8use crate::{
9    pagination::Pagination, references::Reference, sorting::SortDirection,
10    traits::table_source::TableSource,
11};
12
13/// Type alias for expression closures stored on Table.
14pub type ExpressionFn<T, E> =
15    Arc<dyn Fn(&Table<T, E>) -> Expression<<T as TableSource>::Value> + Send + Sync>;
16
17#[derive(Clone)]
18pub struct Table<T, E>
19where
20    T: TableSource,
21    E: Entity<T::Value>,
22{
23    pub(super) data_source: T,
24    pub(super) _phantom: PhantomData<E>,
25    pub(super) table_name: String,
26    pub(super) columns: IndexMap<String, T::Column<T::AnyType>>,
27    pub(super) conditions: IndexMap<i64, T::Condition>,
28    pub(super) next_condition_id: i64,
29    pub(super) order_by: IndexMap<i64, (T::Condition, SortDirection)>,
30    pub(super) next_order_id: i64,
31    pub(super) refs: Option<IndexMap<String, Arc<dyn Reference>>>,
32    pub(super) expressions: IndexMap<String, ExpressionFn<T, E>>,
33    pub(super) pagination: Option<Pagination>,
34    pub(super) title_field: Option<String>,
35    pub(super) title_fields: Vec<String>,
36    pub(super) id_field: Option<String>,
37}
38
39impl<T: TableSource, E: Entity<T::Value>> Table<T, E> {
40    /// Create a new Table with the given table name and data source
41    pub fn new(table_name: impl Into<String>, data_source: T) -> Self {
42        Self {
43            data_source,
44            _phantom: PhantomData,
45            table_name: table_name.into(),
46            columns: IndexMap::new(),
47            conditions: IndexMap::new(),
48            next_condition_id: 1,
49            order_by: IndexMap::new(),
50            next_order_id: 1,
51            refs: None,
52            expressions: IndexMap::new(),
53            pagination: None,
54            title_field: None,
55            title_fields: Vec::new(),
56            id_field: None,
57        }
58    }
59
60    /// Convert this table to use a different entity type
61    pub fn into_entity<E2: Entity<T::Value>>(self) -> Table<T, E2> {
62        Table {
63            data_source: self.data_source,
64            _phantom: PhantomData,
65            table_name: self.table_name,
66            columns: self.columns,
67            conditions: self.conditions,
68            next_condition_id: self.next_condition_id,
69            order_by: self.order_by,
70            next_order_id: self.next_order_id,
71            refs: self.refs,
72            expressions: IndexMap::new(),
73            pagination: self.pagination,
74            title_field: self.title_field,
75            title_fields: self.title_fields,
76            id_field: self.id_field,
77        }
78    }
79
80    /// Use a callback with a builder pattern for configuration
81    pub fn with<F>(mut self, func: F) -> Self
82    where
83        F: FnOnce(&mut Self),
84    {
85        func(&mut self);
86        self
87    }
88
89    /// Get the table name
90    pub fn table_name(&self) -> &str {
91        &self.table_name
92    }
93
94    /// Override the table name. Used by REST API drivers to swap a
95    /// canonical resource path for a per-reference URI template at
96    /// traversal time.
97    pub fn set_table_name(&mut self, name: impl Into<String>) {
98        self.table_name = name.into();
99    }
100
101    /// Get the underlying data source
102    pub fn data_source(&self) -> &T {
103        &self.data_source
104    }
105
106    /// Get mutable access to conditions (pub(crate) for TableLike impl)
107    pub(crate) fn conditions_mut(&mut self) -> &mut IndexMap<i64, T::Condition> {
108        &mut self.conditions
109    }
110
111    /// Get mutable access to next_condition_id (pub(crate) for TableLike impl)
112    pub(crate) fn next_condition_id_mut(&mut self) -> &mut i64 {
113        &mut self.next_condition_id
114    }
115
116    /// Get the title field column if set
117    pub fn title_field(&self) -> Option<&T::Column<T::AnyType>> {
118        self.title_field
119            .as_ref()
120            .and_then(|name| self.columns.get(name))
121    }
122
123    /// Names of columns marked as display titles (set via
124    /// [`Self::with_title_column_of`]). These show alongside the id in
125    /// list views and on the leading lines of single-record displays.
126    pub fn title_fields(&self) -> &[String] {
127        &self.title_fields
128    }
129
130    /// Get the id field column if set
131    pub fn id_field(&self) -> Option<&T::Column<T::AnyType>> {
132        self.id_field
133            .as_ref()
134            .and_then(|name| self.columns.get(name))
135    }
136
137    /// Mark an already-added column as the id field.
138    ///
139    /// Use this when the id column has been added via [`Self::add_column`]
140    /// (so its type and aliases were chosen explicitly) and you only need
141    /// to flag it. [`Self::with_id_column`] is the typed shortcut that
142    /// creates the column for you.
143    pub fn set_id_field(&mut self, name: impl Into<String>) {
144        self.id_field = Some(name.into());
145    }
146
147    /// Mark an already-added column as a display title.
148    ///
149    /// Companion to [`Self::set_id_field`] for spec-driven construction.
150    pub fn add_title_field(&mut self, name: impl Into<String>) {
151        let name = name.into();
152        if !self.title_fields.contains(&name) {
153            self.title_fields.push(name.clone());
154        }
155        if self.title_field.is_none() {
156            self.title_field = Some(name);
157        }
158    }
159
160    /// Get the current pagination configuration, if set
161    pub fn pagination(&self) -> Option<&Pagination> {
162        self.pagination.as_ref()
163    }
164}
165
166impl<T: TableSource, E: Entity<T::Value>> std::ops::Index<&str> for Table<T, E> {
167    type Output = T::Column<T::AnyType>;
168
169    fn index(&self, index: &str) -> &Self::Output {
170        &self.columns[index]
171    }
172}
173
174impl<T: TableSource, E: Entity<T::Value>> std::fmt::Debug for Table<T, E> {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        f.debug_struct("Table")
177            .field("table_name", &self.table_name)
178            .field("columns", &self.columns.keys().collect::<Vec<_>>())
179            .field("conditions_count", &self.conditions.len())
180            .field(
181                "refs_count",
182                &self.refs.as_ref().map(|r| r.len()).unwrap_or(0),
183            )
184            .field("expressions_count", &self.expressions.len())
185            .finish()
186    }
187}