1use std::marker::PhantomData;
23use crate::expression::array_comparison::InExpression;
4use crate::expression::*;
5use crate::query_builder::*;
6use crate::result::QueryResult;
78/// 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}
2223impl<T, ST> Subselect<T, ST> {
24pub(crate) fn new(values: T) -> Self {
25Self {
26 values,
27 _sql_type: PhantomData,
28 }
29 }
30}
3132impl<T: SelectQuery, ST> Expression for Subselect<T, ST>
33where
34ST: SqlType + TypedExpressionType,
35{
36// This is useful for `.single_value()`
37type SqlType = ST;
38}
3940impl<T, ST: SqlType> InExpression for Subselect<T, ST> {
41type SqlType = ST;
42fn is_empty(&self) -> bool {
43false
44}
45fn is_array(&self) -> bool {
46false
47}
48}
4950impl<T, ST, QS> SelectableExpression<QS> for Subselect<T, ST>
51where
52Subselect<T, ST>: AppearsOnTable<QS>,
53 T: ValidSubselect<QS>,
54{
55}
5657impl<T, ST, QS> AppearsOnTable<QS> for Subselect<T, ST>
58where
59Subselect<T, ST>: Expression,
60 T: ValidSubselect<QS>,
61{
62}
6364// 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> {
68type IsAggregate = is_aggregate::Never;
69}
7071impl<T, ST, DB> QueryFragment<DB> for Subselect<T, ST>
72where
73DB: Backend,
74 T: QueryFragment<DB>,
75{
76fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
77self.values.walk_ast(out.reborrow())?;
78Ok(())
79 }
80}
8182pub trait ValidSubselect<QS> {}