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    /// How this backend names its source. Most backends use `String`;
30    /// SQL/SurrealDB backends use `SelectSource<Self::Select>` so a table can
31    /// be sourced from an arbitrary sub-`SELECT`. See [`crate::source`].
32    type Source: crate::traits::table_source_spec::TableSourceSpec;
33
34    /// The condition type stored by `Table`. SQL/SurrealDB backends use
35    /// `Expression<Self::Value>`; document-oriented backends like MongoDB
36    /// can use a native filter type (e.g. `bson::Document`).
37    type Condition: Clone + Send + Sync + 'static;
38
39    /// Build a textual `field == value` condition.
40    ///
41    /// Generic UIs (e.g. CLI argument parsers) only have strings on
42    /// hand, so they need a way to construct a `Self::Condition` without
43    /// knowing the backend's native expression type. Backends that
44    /// don't support raw text filtering can leave the default, which
45    /// returns an error.
46    fn eq_condition(field: &str, value: &str) -> Result<Self::Condition> {
47        let _ = (field, value);
48        Err(vantage_core::error!(
49            "eq_condition not implemented for this TableSource"
50        ))
51    }
52
53    /// Build a `field == value` condition with a typed `Self::Value`.
54    ///
55    /// Sibling of [`TableSource::eq_condition`] for the case where the caller already
56    /// has a native-typed value in hand (e.g. `Reference::resolve_from_row`
57    /// pulling a join value out of a `Record<Self::Value>`). Avoids going
58    /// through string serialization and avoids the `Expression → T::Condition`
59    /// coercion that some document backends only support via a panic stub.
60    ///
61    /// Backends that participate in row-based reference traversal override;
62    /// the default returns an error so existing impls compile.
63    fn eq_value_condition(&self, field: &str, value: Self::Value) -> Result<Self::Condition> {
64        let _ = (field, value);
65        Err(vantage_core::error!(
66            "eq_value_condition not implemented for this TableSource"
67        ))
68    }
69
70    /// When `condition` is a literal `column = value`, return the pair.
71    ///
72    /// [`Table::add_condition`] registers it as a set invariant: an insert or
73    /// replace through the table fills an absent column, a patch may not change
74    /// it. Expression backends use [`crate::conditions::literal_equality`];
75    /// document backends read their own filter shape. Default `None`: the
76    /// condition still narrows, it just fills nothing.
77    fn condition_equality(&self, condition: &Self::Condition) -> Option<(String, Self::Value)> {
78        let _ = condition;
79        None
80    }
81
82    /// Whether every by-id write (`insert_table_value`, `replace_table_value`,
83    /// `patch_table_value`, `delete_table_value`, `insert_table_return_id_value`)
84    /// honours the write contract over `table.conditions()`: it only touches
85    /// rows in the set, and only leaves rows that still belong to it. A source
86    /// that returns `false` is refused any by-id write through a conditioned
87    /// table: `Table` refuses it with `Unsupported` before reaching the source.
88    /// Default `false`.
89    fn can_confine_writes(&self) -> bool {
90        false
91    }
92
93    /// Coerce a reference join value into the backend's native id form.
94    ///
95    /// Reference traversal (`resolve_from_row`) reads the join value raw out
96    /// of the parent row and uses it for both the narrowing eq-condition and
97    /// the target's insert invariant. On scalar-FK backends any value compares
98    /// as-is, so the default is identity. Backends with a richer id type
99    /// override: SurrealDB re-tags a `"table:key"` string — a record id that
100    /// round-tripped through JSON or a script — back into a record id, so the
101    /// condition renders a record literal (and an inserted child stores a
102    /// link), not a quoted string that matches nothing.
103    fn coerce_reference_value(&self, value: Self::Value) -> Self::Value {
104        value
105    }
106
107    /// Create a new column with the given name
108    fn create_column<Type: ColumnType>(&self, name: &str) -> Self::Column<Type>;
109
110    /// Convert a typed column to type-erased column
111    fn to_any_column<Type: ColumnType>(
112        &self,
113        column: Self::Column<Type>,
114    ) -> Self::Column<Self::AnyType>;
115
116    /// Attempt to convert a type-erased column back to typed column
117    fn convert_any_column<Type: ColumnType>(
118        &self,
119        any_column: Self::Column<Self::AnyType>,
120    ) -> Option<Self::Column<Type>>;
121
122    /// Create an expression from a template and parameters, similar to Expression::new
123    fn expr(
124        &self,
125        template: impl Into<String>,
126        parameters: Vec<ExpressiveEnum<Self::Value>>,
127    ) -> Expression<Self::Value>;
128
129    /// Create a search condition matching `search_value` across the table's
130    /// searchable fields. This is a *server-side* capability — it pushes the
131    /// match down to the backend's query engine.
132    ///
133    /// Different vendors implement search differently:
134    /// - SQL: `field LIKE '%value%'` (returns Expression)
135    /// - SurrealDB: `field CONTAINS 'value'` (returns Expression)
136    /// - MongoDB: `{ field: { $regex: 'value' } }` (returns MongoCondition)
137    ///
138    /// **Contract for backends that cannot search server-side** (e.g. CSV, redb):
139    /// return a condition that yields an `ErrorKind::Unsupported` error when it is
140    /// *resolved* — never a silent match-all (which leaks every row as if filtered)
141    /// and never a panic. Searching loaded/in-memory data is the Lens/Diorama
142    /// layer's responsibility, not the backend's.
143    fn search_table_condition<E>(
144        &self,
145        table: &Table<Self, E>,
146        search_value: &str,
147    ) -> Self::Condition
148    where
149        E: Entity<Self::Value>,
150        Self: Sized;
151
152    /// Get all data from a table as Record values with IDs (for ReadableValueSet implementation)
153    async fn list_table_values<E>(
154        &self,
155        table: &Table<Self, E>,
156    ) -> Result<IndexMap<Self::Id, Record<Self::Value>>>
157    where
158        E: Entity<Self::Value>,
159        Self: Sized;
160
161    /// Get a single record by ID as Record value (for ReadableValueSet implementation).
162    ///
163    /// Returns `Ok(None)` when no record exists with the given ID.
164    async fn get_table_value<E>(
165        &self,
166        table: &Table<Self, E>,
167        id: &Self::Id,
168    ) -> Result<Option<Record<Self::Value>>>
169    where
170        E: Entity<Self::Value>,
171        Self: Sized;
172
173    /// Get some data from a table as Record value with ID (for ReadableValueSet implementation)
174    async fn get_table_some_value<E>(
175        &self,
176        table: &Table<Self, E>,
177    ) -> Result<Option<(Self::Id, Record<Self::Value>)>>
178    where
179        E: Entity<Self::Value>,
180        Self: Sized;
181
182    /// Get count of records in the table
183    async fn get_table_count<E>(&self, table: &Table<Self, E>) -> Result<i64>
184    where
185        E: Entity<Self::Value>,
186        Self: Sized;
187
188    /// Get sum of a column in the table (returns native value type)
189    async fn get_table_sum<E>(
190        &self,
191        table: &Table<Self, E>,
192        column: &Self::Column<Self::AnyType>,
193    ) -> Result<Self::Value>
194    where
195        E: Entity<Self::Value>,
196        Self: Sized;
197
198    /// Get maximum value of a column in the table (returns native value type)
199    async fn get_table_max<E>(
200        &self,
201        table: &Table<Self, E>,
202        column: &Self::Column<Self::AnyType>,
203    ) -> Result<Self::Value>
204    where
205        E: Entity<Self::Value>,
206        Self: Sized;
207
208    /// Get minimum value of a column in the table (returns native value type)
209    async fn get_table_min<E>(
210        &self,
211        table: &Table<Self, E>,
212        column: &Self::Column<Self::AnyType>,
213    ) -> Result<Self::Value>
214    where
215        E: Entity<Self::Value>,
216        Self: Sized;
217
218    /// Insert a record by ID. **Confined and idempotent:** when the id is
219    /// already stored in `table.conditions()`, return the stored row unchanged;
220    /// when it is held by a row outside the set, fail with `Conflict`; a new
221    /// row must fit the conditions, else `Conflict` and nothing is stored.
222    /// Refuse with `Unsupported` when a condition can be neither applied nor
223    /// evaluated. See `WritableValueSet` for the table.
224    async fn insert_table_value<E>(
225        &self,
226        table: &Table<Self, E>,
227        id: &Self::Id,
228        record: &Record<Self::Value>,
229    ) -> Result<Record<Self::Value>>
230    where
231        E: Entity<Self::Value>,
232        Self: Sized;
233
234    /// Replace a record by ID, creating it when missing. **Confined and
235    /// idempotent:** an id held by a row outside `table.conditions()` fails
236    /// with `Conflict`; the written row must fit the conditions, else
237    /// `Conflict` and nothing changes. Refuse with `Unsupported` when a
238    /// condition can be neither applied nor evaluated. See `WritableValueSet`
239    /// for the table.
240    async fn replace_table_value<E>(
241        &self,
242        table: &Table<Self, E>,
243        id: &Self::Id,
244        record: &Record<Self::Value>,
245    ) -> Result<Record<Self::Value>>
246    where
247        E: Entity<Self::Value>,
248        Self: Sized;
249
250    /// Merge `partial` into the row with this ID. **Confined:** a missing row
251    /// or one outside `table.conditions()` is `NotFound` (marked); the merged
252    /// row must still fit the conditions, else `Conflict` and nothing changes.
253    /// Refuse with `Unsupported` when a condition can be neither applied nor
254    /// evaluated. See `WritableValueSet` for the table.
255    async fn patch_table_value<E>(
256        &self,
257        table: &Table<Self, E>,
258        id: &Self::Id,
259        partial: &Record<Self::Value>,
260    ) -> Result<Record<Self::Value>>
261    where
262        E: Entity<Self::Value>,
263        Self: Sized;
264
265    /// Delete a record by ID. **Confined and idempotent:** delete only when the
266    /// row is in `table.conditions()`; a missing row or a row outside the set
267    /// is `Ok(())` (no lookup is needed — SQL: `DELETE … WHERE id = ? AND
268    /// <conditions>`). Refuse with `Unsupported` when a condition can be
269    /// neither applied nor evaluated. See `WritableValueSet` for the table.
270    async fn delete_table_value<E>(&self, table: &Table<Self, E>, id: &Self::Id) -> Result<()>
271    where
272        E: Entity<Self::Value>,
273        Self: Sized;
274
275    /// Delete every record the table represents (for WritableValueSet).
276    ///
277    /// **Honour `table.conditions()`.** A conditioned table is a SUBSET, and
278    /// every read path already treats it as one, so deleting it must delete
279    /// that subset. An implementation that builds its statement from
280    /// `table_name()` alone silently truncates the table instead — the caller
281    /// narrowed to one row, and lost all of them. An unconditioned table
282    /// still deletes everything, which is the only case this looks like.
283    async fn delete_table_all_values<E>(&self, table: &Table<Self, E>) -> Result<()>
284    where
285        E: Entity<Self::Value>,
286        Self: Sized;
287
288    /// Insert a record under a generated ID and return it. **Confined, not
289    /// retry-safe:** the record must fit `table.conditions()`, else `Conflict`
290    /// and nothing is stored; a retry after a lost reply stores a second row.
291    /// Refuse with `Unsupported` when a condition can be neither applied nor
292    /// evaluated.
293    async fn insert_table_return_id_value<E>(
294        &self,
295        table: &Table<Self, E>,
296        record: &Record<Self::Value>,
297    ) -> Result<Self::Id>
298    where
299        E: Entity<Self::Value>,
300        Self: Sized;
301
302    /// Stream all records from a table as (Id, Record) pairs.
303    ///
304    /// Default implementation wraps `list_table_values` into a stream.
305    /// Backends with native streaming (e.g. REST APIs with pagination)
306    /// can override this to yield records incrementally.
307    #[allow(clippy::type_complexity)]
308    fn stream_table_values<'a, E>(
309        &'a self,
310        table: &Table<Self, E>,
311    ) -> Pin<Box<dyn Stream<Item = Result<(Self::Id, Record<Self::Value>)>> + Send + 'a>>
312    where
313        E: Entity<Self::Value> + 'a,
314        Self: Sized,
315    {
316        let table = table.clone();
317        Box::pin(async_stream::stream! {
318            let records = self.list_table_values(&table).await;
319            match records {
320                Ok(map) => {
321                    for item in map {
322                        yield Ok(item);
323                    }
324                }
325                Err(e) => yield Err(e),
326            }
327        })
328    }
329
330    /// Build a condition for "target_field IN (values of source_column from source_table)".
331    ///
332    /// Used by the relationship traversal system (`get_ref_as`) to filter
333    /// a target table by foreign key values from a source table.
334    ///
335    /// Each backend implements this natively:
336    /// - SQL backends build a subquery: `"id" IN (SELECT "bakery_id" FROM "client" WHERE ...)`
337    /// - MongoDB builds a deferred `{ field: { "$in": [...] } }` document
338    /// - CSV fetches values in memory and builds an IN condition
339    fn related_in_condition<SourceE: Entity<Self::Value> + 'static>(
340        &self,
341        target_field: &str,
342        source_table: &Table<Self, SourceE>,
343        source_column: &str,
344    ) -> Self::Condition
345    where
346        Self: Sized;
347
348    /// Build a correlated condition: `target_table.target_field = source_table.source_column`.
349    ///
350    /// Used by `get_subquery_as` / `get_subquery_erased` for embedding correlated
351    /// subqueries inside SELECT expressions (e.g.
352    /// `(SELECT COUNT(*) FROM order WHERE order.client_id = client.id)`), and by
353    /// the generic implicit-reference lowering. SQL and SurrealDB backends
354    /// produce table-qualified equality; backends without correlated subqueries
355    /// leave the default (which panics — they must also keep
356    /// [`supports_traversal`](Self::supports_traversal) `false`).
357    fn related_correlated_condition(
358        &self,
359        target_table: &str,
360        target_field: &str,
361        source_table: &str,
362        source_column: &str,
363    ) -> Self::Condition {
364        let _ = (target_table, target_field, source_table, source_column);
365        unimplemented!("correlated subqueries not supported by this backend")
366    }
367
368    /// Whether this backend can lower a dotted active column
369    /// (`"country.name"`) into its own query — a nested correlated subquery for
370    /// SQL, a native idiom path for SurrealDB. Backends that can build neither
371    /// (e.g. MongoDB, CSV, REST) leave the default `false`, and
372    /// [`Table::with_active_columns`](crate::table::Table::with_active_columns)
373    /// rejects dotted names against them at build time rather than at fetch time.
374    fn supports_traversal(&self) -> bool {
375        false
376    }
377
378    /// Build a backend-native path expression for a dotted active column,
379    /// tried before the generic correlated-subquery chain.
380    ///
381    /// `hops` holds each traversed relation's **foreign-key/link field** (not
382    /// its registry name — a relation named `owner` over a link field `client`
383    /// must lower to `client.…`), and `column` the final field. The default
384    /// returns `None`, so backends fall back to the generic chain built on
385    /// [`related_correlated_condition`](Self::related_correlated_condition).
386    /// SurrealDB overrides this to emit an idiom path (`batch.golf_course.name`,
387    /// each segment escaped separately); multi-hop comes for free. The returned
388    /// expression is unaliased — `select()` aliases it to the dotted name.
389    fn traversal_path_expr(&self, hops: &[&str], column: &str) -> Option<Expression<Self::Value>> {
390        let _ = (hops, column);
391        None
392    }
393
394    /// Return an associated expression that, when resolved, yields all values
395    /// of the given typed column from this table (respecting current conditions).
396    ///
397    /// For query-language backends, this can be a subquery expression.
398    /// For simple backends (CSV), this uses a `DeferredFn` that loads data
399    /// and extracts the column values at execution time.
400    ///
401    /// The returned `AssociatedExpression` can be:
402    /// - Executed directly: `.get().await -> Result<Vec<Type>>`
403    /// - Composed into expressions: used via `Expressive` trait in `in_()` conditions
404    ///
405    /// ```rust,ignore
406    /// let fk_col = source.get_column::<String>("bakery_id").unwrap();
407    /// let fk_values = source.data_source().column_table_values_expr(&source, &fk_col);
408    /// // Execute: let ids = fk_values.get().await?;
409    /// // Or compose: target.add_condition(target["id"].in_((fk_values)));
410    /// ```
411    fn column_table_values_expr<'a, E, Type: ColumnType>(
412        &'a self,
413        table: &Table<Self, E>,
414        column: &Self::Column<Type>,
415    ) -> AssociatedExpression<'a, Self, Self::Value, Vec<Type>>
416    where
417        E: Entity<Self::Value> + 'static,
418        Self: ExprDataSource<Self::Value> + Sized;
419}