tank_core/
data_set.rs

1use crate::{
2    Driver, Executor, Expression, Query, Result, RowLabeled,
3    stream::Stream,
4    writer::{Context, SqlWriter},
5};
6
7/// Queryable data source (table or join tree).
8///
9/// Implementors know how to render themselves inside a FROM clause and whether
10/// column references should be qualified with schema and table.
11pub trait DataSet {
12    /// Should columns be qualified (`schema.table.col`)?
13    fn qualified_columns() -> bool
14    where
15        Self: Sized;
16    /// Render into `out`.
17    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut String);
18    /// Fetch a SELECT query and stream labeled rows.
19    fn select<'s, Exec, Item, Cols, Expr>(
20        &'s self,
21        executor: &'s mut Exec,
22        columns: Cols,
23        condition: Expr,
24        limit: Option<u32>,
25    ) -> impl Stream<Item = Result<RowLabeled>> + 's
26    where
27        Self: Sized,
28        Exec: Executor,
29        Item: Expression,
30        Cols: IntoIterator<Item = Item> + Clone,
31        Expr: Expression,
32    {
33        let mut query = String::with_capacity(1024);
34        executor
35            .driver()
36            .sql_writer()
37            .write_select(&mut query, columns, self, condition, limit);
38        executor.fetch(query)
39    }
40    /// Prepare a SELECT query.
41    fn prepare<Exec, Item, Cols, Expr>(
42        &self,
43        executor: &mut Exec,
44        columns: Cols,
45        condition: &Expr,
46        limit: Option<u32>,
47    ) -> impl Future<Output = Result<Query<Exec::Driver>>>
48    where
49        Self: Sized,
50        Item: Expression,
51        Cols: IntoIterator<Item = Item> + Clone,
52        Exec: Executor,
53        Expr: Expression,
54    {
55        let mut query = String::with_capacity(1024);
56        executor
57            .driver()
58            .sql_writer()
59            .write_select(&mut query, columns, self, condition, limit);
60        executor.prepare(query)
61    }
62}
63
64impl DataSet for &dyn DataSet {
65    fn qualified_columns() -> bool
66    where
67        Self: Sized,
68    {
69        unreachable!("Cannot call static qualified_columns on a dyn object directly");
70    }
71    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut String) {
72        (*self).write_query(writer, context, out)
73    }
74}