diesel/expression/
subselect.rs

1use std::marker::PhantomData;
2
3use crate::expression::array_comparison::InExpression;
4use crate::expression::*;
5use crate::query_builder::*;
6use crate::result::QueryResult;
7
8/// This struct tells our type system that the whatever we put in `values`
9/// will be handled by SQL as an expression of type `ST`.
10/// It also implements the usual `SelectableExpression` and `AppearsOnTable` traits
11/// (which is useful when using this as an expression). To enforce correctness here, it checks
12/// the dedicated [`ValidSubselect`]. This however does not check that the `SqlType` of
13/// [`SelectQuery`], matches `ST`, so appropriate constraints should be checked in places that
14/// construct Subselect. (It's not always equal, notably .single_value() makes `ST` nullable, and
15/// `exists` checks bounds on `SubSelect<T, Bool>` although there is actually no such subquery in
16/// the final SQL.)
17#[derive(Debug, Copy, Clone, QueryId)]
18pub struct Subselect<T, ST> {
19    values: T,
20    _sql_type: PhantomData<ST>,
21}
22
23impl<T, ST> Subselect<T, ST> {
24    pub(crate) fn new(values: T) -> Self {
25        Self {
26            values,
27            _sql_type: PhantomData,
28        }
29    }
30}
31
32impl<T: SelectQuery, ST> Expression for Subselect<T, ST>
33where
34    ST: SqlType + TypedExpressionType,
35{
36    // This is useful for `.single_value()`
37    type SqlType = ST;
38}
39
40impl<T, ST: SqlType> InExpression for Subselect<T, ST> {
41    type SqlType = ST;
42    fn is_empty(&self) -> bool {
43        false
44    }
45    fn is_array(&self) -> bool {
46        false
47    }
48}
49
50impl<T, ST, QS> SelectableExpression<QS> for Subselect<T, ST>
51where
52    Subselect<T, ST>: AppearsOnTable<QS>,
53    T: ValidSubselect<QS>,
54{
55}
56
57impl<T, ST, QS> AppearsOnTable<QS> for Subselect<T, ST>
58where
59    Subselect<T, ST>: Expression,
60    T: ValidSubselect<QS>,
61{
62}
63
64// FIXME: This probably isn't sound. The subselect can reference columns from
65// the outer query, and is affected by the `GROUP BY` clause of the outer query
66// identically to using it outside of a subselect
67impl<T, ST, GB> ValidGrouping<GB> for Subselect<T, ST> {
68    type IsAggregate = is_aggregate::Never;
69}
70
71impl<T, ST, DB> QueryFragment<DB> for Subselect<T, ST>
72where
73    DB: Backend,
74    T: QueryFragment<DB>,
75{
76    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
77        self.values.walk_ast(out.reborrow())?;
78        Ok(())
79    }
80}
81
82pub trait ValidSubselect<QS> {}