tank_core/
data_set.rs

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