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>(
20        &'s self,
21        executor: &'s mut Exec,
22        columns: impl IntoIterator<Item = Item> + Clone,
23        condition: impl Expression,
24        limit: Option<u32>,
25    ) -> impl Stream<Item = Result<RowLabeled>> + 's
26    where
27        Self: Sized,
28        Exec: Executor,
29        Item: Expression,
30    {
31        let mut query = String::with_capacity(1024);
32        executor
33            .driver()
34            .sql_writer()
35            .write_select(&mut query, columns, self, condition, limit);
36        executor.fetch(query)
37    }
38    /// Prepare a SELECT query.
39    fn prepare<Exec, Item>(
40        &self,
41        executor: &mut Exec,
42        columns: impl IntoIterator<Item = Item> + Clone,
43        condition: impl Expression,
44        limit: Option<u32>,
45    ) -> impl Future<Output = Result<Query<Exec::Driver>>>
46    where
47        Self: Sized,
48        Item: Expression,
49        Exec: Executor,
50    {
51        let mut query = String::with_capacity(1024);
52        executor
53            .driver()
54            .sql_writer()
55            .write_select(&mut query, columns, self, condition, limit);
56        executor.prepare(query)
57    }
58}
59
60impl DataSet for &dyn DataSet {
61    fn qualified_columns() -> bool
62    where
63        Self: Sized,
64    {
65        unreachable!("Cannot call static qualified_columns on a dyn object directly");
66    }
67    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut String) {
68        (*self).write_query(writer, context, out)
69    }
70}