Skip to main content

vantage_expressions/traits/
datasource.rs

1use serde_json::Value;
2use std::future::Future;
3
4use crate::Expression;
5use crate::Selectable;
6use crate::traits::associated_expressions::AssociatedExpression;
7use crate::traits::expressive::DeferredFn;
8use vantage_core::Result;
9
10/// DataSource can be referenced by other objects, and will help associate them
11/// with physical persistence. While DataSource might not be directly used,
12/// It is extended by varietty of other traits that provide
13/// real interface (like `QuerySource` and `SelectSource`)
14pub trait DataSource: Send + Sync {}
15
16/// DataSource that can also execute expressions.
17pub trait ExprDataSource<T = Value>: DataSource {
18    fn execute(&self, expr: &crate::Expression<T>) -> impl Future<Output = Result<T>> + Send;
19
20    fn defer(&self, expr: crate::Expression<T>) -> DeferredFn<T>
21    where
22        T: Clone + Send + Sync + 'static;
23
24    /// Create an associated expression with type-safe return type
25    ///
26    /// # Examples
27    ///
28    /// ```rust,ignore
29    /// let count_expr = expr!("SELECT COUNT(*) FROM users");
30    /// let associated = ds.associate::<usize>(count_expr);
31    /// let result: usize = associated.get().await?;
32    /// ```
33    fn associate<R>(&self, expr: crate::Expression<T>) -> AssociatedExpression<'_, Self, T, R>
34    where
35        Self: Sized,
36    {
37        AssociatedExpression::new(expr, self)
38    }
39}
40
41/// Datasource that support creation and execution of select queries
42pub trait SelectableDataSource<T = Value, C = Expression<T>>: DataSource {
43    type Select: Selectable<T, C>;
44
45    // Return SelectQuery
46    fn select(&self) -> Self::Select;
47
48    // Execute select query directly
49    fn execute_select(&self, select: &Self::Select) -> impl Future<Output = Result<Vec<T>>> + Send;
50
51    /// Add a column expression to a select query with optional alias.
52    /// Backends must override this if they support aliases.
53    fn add_select_column(
54        &self,
55        select: &mut Self::Select,
56        expression: Expression<T>,
57        alias: Option<&str>,
58    ) where
59        T: Clone,
60    {
61        if alias.is_some() {
62            panic!("add_select_column with alias not implemented for this backend");
63        }
64        select.add_expression(expression);
65    }
66}