Debian Codegraph @

src/expression/subselect.rs

raw
1 use std::marker::PhantomData;
2
3 use crate::expression::array_comparison::InExpression;
4 use crate::expression::*;
5 use crate::query_builder::*;
6 use 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)]
18 pub struct Subselect<T, ST> {
19 values: T,
20 _sql_type: PhantomData<ST>,
21 }
22
23 impl<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
32 impl<T: SelectQuery, ST> Expression for Subselect<T, ST>
33 where
34 ST: SqlType + TypedExpressionType,
35 {
36 // This is useful for `.single_value()`
37 type SqlType = ST;
38 }
39
40 impl<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
50 impl<T, ST, QS> SelectableExpression<QS> for Subselect<T, ST>
51 where
52 Subselect<T, ST>: AppearsOnTable<QS>,
53 T: ValidSubselect<QS>,
54 {
55 }
56
57 impl<T, ST, QS> AppearsOnTable<QS> for Subselect<T, ST>
58 where
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
67 impl<T, ST, GB> ValidGrouping<GB> for Subselect<T, ST> {
68 type IsAggregate = is_aggregate::Never;
69 }
70
71 impl<T, ST, DB> QueryFragment<DB> for Subselect<T, ST>
72 where
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
82 pub trait ValidSubselect<QS> {}