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