Skip to main content

vantage_table/traits/
table_source.rs

1use std::hash::Hash;
2use std::pin::Pin;
3
4use async_trait::async_trait;
5use futures_core::Stream;
6use indexmap::IndexMap;
7use vantage_dataset::traits::Result;
8use vantage_expressions::{
9    Expression,
10    traits::associated_expressions::AssociatedExpression,
11    traits::datasource::{DataSource, ExprDataSource},
12    traits::expressive::ExpressiveEnum,
13};
14use vantage_types::{Entity, Record};
15
16use crate::{column::core::ColumnType, table::Table, traits::column_like::ColumnLike};
17
18/// Trait for table data sources that defines column type separate from execution
19/// TableSource represents a data source that can create and manage tables
20#[async_trait]
21pub trait TableSource: DataSource + Clone + 'static {
22    type Column<Type>: ColumnLike<Type> + Clone
23    where
24        Type: ColumnType;
25    type AnyType: ColumnType;
26    type Value: Clone + Send + Sync + 'static;
27    type Id: Send + Sync + Clone + Hash + Eq + 'static;
28
29    /// The condition type stored by `Table`. SQL/SurrealDB backends use
30    /// `Expression<Self::Value>`; document-oriented backends like MongoDB
31    /// can use a native filter type (e.g. `bson::Document`).
32    type Condition: Clone + Send + Sync + 'static;
33
34    /// Create a new column with the given name
35    fn create_column<Type: ColumnType>(&self, name: &str) -> Self::Column<Type>;
36
37    /// Convert a typed column to type-erased column
38    fn to_any_column<Type: ColumnType>(
39        &self,
40        column: Self::Column<Type>,
41    ) -> Self::Column<Self::AnyType>;
42
43    /// Attempt to convert a type-erased column back to typed column
44    fn convert_any_column<Type: ColumnType>(
45        &self,
46        any_column: Self::Column<Self::AnyType>,
47    ) -> Option<Self::Column<Type>>;
48
49    /// Create an expression from a template and parameters, similar to Expression::new
50    fn expr(
51        &self,
52        template: impl Into<String>,
53        parameters: Vec<ExpressiveEnum<Self::Value>>,
54    ) -> Expression<Self::Value>;
55
56    /// Create a search condition for a table (e.g., searches across searchable fields)
57    ///
58    /// Different vendors implement search differently:
59    /// - SQL: `field LIKE '%value%'` (returns Expression)
60    /// - SurrealDB: `field CONTAINS 'value'` (returns Expression)
61    /// - MongoDB: `{ field: { $regex: 'value' } }` (returns MongoCondition)
62    ///
63    /// The implementation should search across appropriate fields in the table.
64    fn search_table_condition<E>(
65        &self,
66        table: &Table<Self, E>,
67        search_value: &str,
68    ) -> Self::Condition
69    where
70        E: Entity<Self::Value>,
71        Self: Sized;
72
73    /// Get all data from a table as Record values with IDs (for ReadableValueSet implementation)
74    async fn list_table_values<E>(
75        &self,
76        table: &Table<Self, E>,
77    ) -> Result<IndexMap<Self::Id, Record<Self::Value>>>
78    where
79        E: Entity<Self::Value>,
80        Self: Sized;
81
82    /// Get a single record by ID as Record value (for ReadableValueSet implementation)
83    async fn get_table_value<E>(
84        &self,
85        table: &Table<Self, E>,
86        id: &Self::Id,
87    ) -> Result<Record<Self::Value>>
88    where
89        E: Entity<Self::Value>,
90        Self: Sized;
91
92    /// Get some data from a table as Record value with ID (for ReadableValueSet implementation)
93    async fn get_table_some_value<E>(
94        &self,
95        table: &Table<Self, E>,
96    ) -> Result<Option<(Self::Id, Record<Self::Value>)>>
97    where
98        E: Entity<Self::Value>,
99        Self: Sized;
100
101    /// Get count of records in the table
102    async fn get_table_count<E>(&self, table: &Table<Self, E>) -> Result<i64>
103    where
104        E: Entity<Self::Value>,
105        Self: Sized;
106
107    /// Get sum of a column in the table (returns native value type)
108    async fn get_table_sum<E>(
109        &self,
110        table: &Table<Self, E>,
111        column: &Self::Column<Self::AnyType>,
112    ) -> Result<Self::Value>
113    where
114        E: Entity<Self::Value>,
115        Self: Sized;
116
117    /// Get maximum value of a column in the table (returns native value type)
118    async fn get_table_max<E>(
119        &self,
120        table: &Table<Self, E>,
121        column: &Self::Column<Self::AnyType>,
122    ) -> Result<Self::Value>
123    where
124        E: Entity<Self::Value>,
125        Self: Sized;
126
127    /// Get minimum value of a column in the table (returns native value type)
128    async fn get_table_min<E>(
129        &self,
130        table: &Table<Self, E>,
131        column: &Self::Column<Self::AnyType>,
132    ) -> Result<Self::Value>
133    where
134        E: Entity<Self::Value>,
135        Self: Sized;
136
137    /// Insert a record as Record value (for WritableValueSet implementation)
138    async fn insert_table_value<E>(
139        &self,
140        table: &Table<Self, E>,
141        id: &Self::Id,
142        record: &Record<Self::Value>,
143    ) -> Result<Record<Self::Value>>
144    where
145        E: Entity<Self::Value>,
146        Self: Sized;
147
148    /// Replace a record as Record value (for WritableValueSet implementation)
149    async fn replace_table_value<E>(
150        &self,
151        table: &Table<Self, E>,
152        id: &Self::Id,
153        record: &Record<Self::Value>,
154    ) -> Result<Record<Self::Value>>
155    where
156        E: Entity<Self::Value>,
157        Self: Sized;
158
159    /// Patch a record as Record value (for WritableValueSet implementation)
160    async fn patch_table_value<E>(
161        &self,
162        table: &Table<Self, E>,
163        id: &Self::Id,
164        partial: &Record<Self::Value>,
165    ) -> Result<Record<Self::Value>>
166    where
167        E: Entity<Self::Value>,
168        Self: Sized;
169
170    /// Delete a record by ID (for WritableValueSet implementation)
171    async fn delete_table_value<E>(&self, table: &Table<Self, E>, id: &Self::Id) -> Result<()>
172    where
173        E: Entity<Self::Value>,
174        Self: Sized;
175
176    /// Delete all records (for WritableValueSet implementation)
177    async fn delete_table_all_values<E>(&self, table: &Table<Self, E>) -> Result<()>
178    where
179        E: Entity<Self::Value>,
180        Self: Sized;
181
182    /// Insert a record and return generated ID (for InsertableValueSet implementation)
183    async fn insert_table_return_id_value<E>(
184        &self,
185        table: &Table<Self, E>,
186        record: &Record<Self::Value>,
187    ) -> Result<Self::Id>
188    where
189        E: Entity<Self::Value>,
190        Self: Sized;
191
192    /// Stream all records from a table as (Id, Record) pairs.
193    ///
194    /// Default implementation wraps `list_table_values` into a stream.
195    /// Backends with native streaming (e.g. REST APIs with pagination)
196    /// can override this to yield records incrementally.
197    #[allow(clippy::type_complexity)]
198    fn stream_table_values<'a, E>(
199        &'a self,
200        table: &Table<Self, E>,
201    ) -> Pin<Box<dyn Stream<Item = Result<(Self::Id, Record<Self::Value>)>> + Send + 'a>>
202    where
203        E: Entity<Self::Value> + 'a,
204        Self: Sized,
205    {
206        let table = table.clone();
207        Box::pin(async_stream::stream! {
208            let records = self.list_table_values(&table).await;
209            match records {
210                Ok(map) => {
211                    for item in map {
212                        yield Ok(item);
213                    }
214                }
215                Err(e) => yield Err(e),
216            }
217        })
218    }
219
220    /// Build a condition for "target_field IN (values of source_column from source_table)".
221    ///
222    /// Used by the relationship traversal system (`get_ref_as`) to filter
223    /// a target table by foreign key values from a source table.
224    ///
225    /// Each backend implements this natively:
226    /// - SQL backends build a subquery: `"id" IN (SELECT "bakery_id" FROM "client" WHERE ...)`
227    /// - MongoDB builds a deferred `{ field: { "$in": [...] } }` document
228    /// - CSV fetches values in memory and builds an IN condition
229    fn related_in_condition<SourceE: Entity<Self::Value> + 'static>(
230        &self,
231        target_field: &str,
232        source_table: &Table<Self, SourceE>,
233        source_column: &str,
234    ) -> Self::Condition
235    where
236        Self: Sized;
237
238    /// Build a correlated condition: `target_table.target_field = source_table.source_column`.
239    ///
240    /// Used by `get_subquery_as` for embedding correlated subqueries inside SELECT
241    /// expressions (e.g. `(SELECT COUNT(*) FROM order WHERE order.client_id = client.id)`).
242    ///
243    /// SQL backends produce table-qualified equality; non-SQL backends may not support
244    /// correlated subqueries and should leave the default (which panics).
245    fn related_correlated_condition(
246        &self,
247        target_table: &str,
248        target_field: &str,
249        source_table: &str,
250        source_column: &str,
251    ) -> Self::Condition {
252        let _ = (target_table, target_field, source_table, source_column);
253        unimplemented!("correlated subqueries not supported by this backend")
254    }
255
256    /// Return an associated expression that, when resolved, yields all values
257    /// of the given typed column from this table (respecting current conditions).
258    ///
259    /// For query-language backends, this can be a subquery expression.
260    /// For simple backends (CSV), this uses a `DeferredFn` that loads data
261    /// and extracts the column values at execution time.
262    ///
263    /// The returned `AssociatedExpression` can be:
264    /// - Executed directly: `.get().await -> Result<Vec<Type>>`
265    /// - Composed into expressions: used via `Expressive` trait in `in_()` conditions
266    ///
267    /// ```rust,ignore
268    /// let fk_col = source.get_column::<String>("bakery_id").unwrap();
269    /// let fk_values = source.data_source().column_table_values_expr(&source, &fk_col);
270    /// // Execute: let ids = fk_values.get().await?;
271    /// // Or compose: target.add_condition(target["id"].in_((fk_values)));
272    /// ```
273    fn column_table_values_expr<'a, E, Type: ColumnType>(
274        &'a self,
275        table: &Table<Self, E>,
276        column: &Self::Column<Type>,
277    ) -> AssociatedExpression<'a, Self, Self::Value, Vec<Type>>
278    where
279        E: Entity<Self::Value> + 'static,
280        Self: ExprDataSource<Self::Value> + Sized;
281}