Debian Codegraph @

src/query_source/joins.rs

raw
1 use super::{AppearsInFromClause, Plus};
2 use crate::backend::Backend;
3 use crate::backend::DieselReserveSpecialization;
4 use crate::expression::grouped::Grouped;
5 use crate::expression::nullable::Nullable;
6 use crate::prelude::*;
7 use crate::query_builder::*;
8 use crate::query_dsl::InternalJoinDsl;
9 use crate::sql_types::BoolOrNullableBool;
10 use crate::util::TupleAppend;
11
12 /// A query source representing the join between two tables
13 pub struct Join<Left: QuerySource, Right: QuerySource, Kind> {
14 left: FromClause<Left>,
15 right: FromClause<Right>,
16 kind: Kind,
17 }
18
19 impl<Left, Right, Kind> Clone for Join<Left, Right, Kind>
20 where
21 Left: QuerySource,
22 FromClause<Left>: Clone,
23 Right: QuerySource,
24 FromClause<Right>: Clone,
25 Kind: Clone,
26 {
27 fn clone(&self) -> Self {
28 Self {
29 left: self.left.clone(),
30 right: self.right.clone(),
31 kind: self.kind.clone(),
32 }
33 }
34 }
35
36 impl<Left, Right, Kind> Copy for Join<Left, Right, Kind>
37 where
38 Left: QuerySource,
39 FromClause<Left>: Copy,
40 Right: QuerySource,
41 FromClause<Right>: Copy,
42 Kind: Copy,
43 {
44 }
45
46 impl<Left, Right, Kind> std::fmt::Debug for Join<Left, Right, Kind>
47 where
48 Left: QuerySource,
49 FromClause<Left>: std::fmt::Debug,
50 Right: QuerySource,
51 FromClause<Right>: std::fmt::Debug,
52 Kind: std::fmt::Debug,
53 {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.debug_struct("Join")
56 .field("left", &self.left)
57 .field("right", &self.right)
58 .field("kind", &self.kind)
59 .finish()
60 }
61 }
62
63 impl<Left, Right, Kind> QueryId for Join<Left, Right, Kind>
64 where
65 Left: QueryId + QuerySource + 'static,
66 Right: QueryId + QuerySource + 'static,
67 Kind: QueryId,
68 {
69 type QueryId = Join<Left, Right, Kind::QueryId>;
70
71 const HAS_STATIC_QUERY_ID: bool =
72 Left::HAS_STATIC_QUERY_ID && Right::HAS_STATIC_QUERY_ID && Kind::HAS_STATIC_QUERY_ID;
73 }
74
75 #[derive(Debug, Clone, Copy, QueryId)]
76 #[doc(hidden)]
77 /// A query source representing the join between two tables with an explicit
78 /// `ON` given. `Join` should usually be referenced instead, as all "type
79 /// safety" traits are implemented in terms of `Join` implementing them.
80 pub struct JoinOn<Join, On> {
81 join: Join,
82 on: On,
83 }
84
85 impl<Left, Right, Kind> Join<Left, Right, Kind>
86 where
87 Left: QuerySource,
88 Right: QuerySource,
89 {
90 pub(crate) fn new(left: Left, right: Right, kind: Kind) -> Self {
91 Join {
92 left: FromClause::new(left),
93 right: FromClause::new(right),
94 kind,
95 }
96 }
97
98 pub(crate) fn on<On>(self, on: On) -> JoinOn<Self, On> {
99 JoinOn { join: self, on: on }
100 }
101 }
102
103 impl<Left, Right> QuerySource for Join<Left, Right, Inner>
104 where
105 Left: QuerySource + AppendSelection<Right::DefaultSelection>,
106 Right: QuerySource,
107 Left::Output: AppearsOnTable<Self>,
108 Self: Clone,
109 {
110 type FromClause = Self;
111 // combining two valid selectable expressions for both tables will always yield a
112 // valid selectable expressions for the whole join, so no need to check that here
113 // again. These checked turned out to be quite expensive in terms of compile time
114 // so we use a wrapper type to just skip the check and forward other more relevant
115 // trait implementations to the inner type
116 //
117 // See https://github.com/diesel-rs/diesel/issues/3223 for details
118 type DefaultSelection = self::private::SkipSelectableExpressionBoundCheckWrapper<Left::Output>;
119
120 fn from_clause(&self) -> Self::FromClause {
121 self.clone()
122 }
123
124 fn default_selection(&self) -> Self::DefaultSelection {
125 self::private::SkipSelectableExpressionBoundCheckWrapper(
126 self.left
127 .source
128 .append_selection(self.right.source.default_selection()),
129 )
130 }
131 }
132
133 impl<Left, Right> QuerySource for Join<Left, Right, LeftOuter>
134 where
135 Left: QuerySource + AppendSelection<Nullable<Right::DefaultSelection>>,
136 Right: QuerySource,
137 Left::Output: AppearsOnTable<Self>,
138 Self: Clone,
139 {
140 type FromClause = Self;
141 // combining two valid selectable expressions for both tables will always yield a
142 // valid selectable expressions for the whole join, so no need to check that here
143 // again. These checked turned out to be quite expensive in terms of compile time
144 // so we use a wrapper type to just skip the check and forward other more relevant
145 // trait implementations to the inner type
146 //
147 // See https://github.com/diesel-rs/diesel/issues/3223 for details
148 type DefaultSelection = self::private::SkipSelectableExpressionBoundCheckWrapper<Left::Output>;
149
150 fn from_clause(&self) -> Self::FromClause {
151 self.clone()
152 }
153
154 fn default_selection(&self) -> Self::DefaultSelection {
155 self::private::SkipSelectableExpressionBoundCheckWrapper(
156 self.left
157 .source
158 .append_selection(self.right.source.default_selection().nullable()),
159 )
160 }
161 }
162
163 #[derive(Debug, Clone, Copy)]
164 pub struct OnKeyword;
165
166 impl<DB: Backend> nodes::MiddleFragment<DB> for OnKeyword {
167 fn push_sql(&self, mut pass: AstPass<'_, '_, DB>) {
168 pass.push_sql(" ON ");
169 }
170 }
171
172 impl<Join, On> QuerySource for JoinOn<Join, On>
173 where
174 Join: QuerySource,
175 On: AppearsOnTable<Join::FromClause> + Clone,
176 On::SqlType: BoolOrNullableBool,
177 Join::DefaultSelection: SelectableExpression<Self>,
178 {
179 type FromClause = Grouped<nodes::InfixNode<Join::FromClause, On, OnKeyword>>;
180 type DefaultSelection = Join::DefaultSelection;
181
182 fn from_clause(&self) -> Self::FromClause {
183 Grouped(nodes::InfixNode::new(
184 self.join.from_clause(),
185 self.on.clone(),
186 OnKeyword,
187 ))
188 }
189
190 fn default_selection(&self) -> Self::DefaultSelection {
191 self.join.default_selection()
192 }
193 }
194
195 impl<Left, Right, Kind, DB> QueryFragment<DB> for Join<Left, Right, Kind>
196 where
197 DB: Backend + DieselReserveSpecialization,
198 Left: QuerySource,
199 Left::FromClause: QueryFragment<DB>,
200 Right: QuerySource,
201 Right::FromClause: QueryFragment<DB>,
202 Kind: QueryFragment<DB>,
203 {
204 fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
205 self.left.from_clause.walk_ast(out.reborrow())?;
206 self.kind.walk_ast(out.reborrow())?;
207 out.push_sql(" JOIN ");
208 self.right.from_clause.walk_ast(out.reborrow())?;
209 Ok(())
210 }
211 }
212
213 /// Indicates that two tables can be joined without an explicit `ON` clause.
214 ///
215 /// Implementations of this trait are generated by invoking [`joinable!`].
216 /// Implementing this trait means that you can call
217 /// `left_table.inner_join(right_table)`, without supplying the `ON` clause
218 /// explicitly. To join two tables which do not implement this trait, you will
219 /// need to call [`.on`].
220 ///
221 /// See [`joinable!`] and [`inner_join`] for usage examples.
222 ///
223 /// [`joinable!`]: crate::joinable!
224 /// [`.on`]: crate::query_dsl::JoinOnDsl::on()
225 /// [`inner_join`]: crate::query_dsl::QueryDsl::inner_join()
226 #[diagnostic::on_unimplemented(
227 message = "cannot join `{T}` to `{Self}` due to missing relation",
228 note = "joining tables directly either requires a `diesel::joinable!` definition \
229 or calling `JoinOnDsl::on` to manually specify the `ON` clause of the join`"
230 )]
231 pub trait JoinTo<T> {
232 #[doc(hidden)]
233 type FromClause;
234 #[doc(hidden)]
235 type OnClause;
236 #[doc(hidden)]
237 fn join_target(rhs: T) -> (Self::FromClause, Self::OnClause);
238 }
239
240 #[doc(hidden)]
241 /// Used to ensure the sql type of `left.join(mid).join(right)` is
242 /// `(Left, Mid, Right)` and not `((Left, Mid), Right)`. This needs
243 /// to be separate from `TupleAppend` because we still want to keep
244 /// the column lists (which are tuples) separate.
245 pub trait AppendSelection<Selection> {
246 type Output;
247
248 fn append_selection(&self, selection: Selection) -> Self::Output;
249 }
250
251 impl<T: Table, Selection> AppendSelection<Selection> for T {
252 type Output = (T::AllColumns, Selection);
253
254 fn append_selection(&self, selection: Selection) -> Self::Output {
255 (T::all_columns(), selection)
256 }
257 }
258
259 impl<Left, Mid, Selection, Kind> AppendSelection<Selection> for Join<Left, Mid, Kind>
260 where
261 Left: QuerySource,
262 Mid: QuerySource,
263 Self: QuerySource,
264 <Self as QuerySource>::DefaultSelection: TupleAppend<Selection>,
265 {
266 type Output = <<Self as QuerySource>::DefaultSelection as TupleAppend<Selection>>::Output;
267
268 fn append_selection(&self, selection: Selection) -> Self::Output {
269 self.default_selection().tuple_append(selection)
270 }
271 }
272
273 impl<Join, On, Selection> AppendSelection<Selection> for JoinOn<Join, On>
274 where
275 Join: AppendSelection<Selection>,
276 {
277 type Output = Join::Output;
278
279 fn append_selection(&self, selection: Selection) -> Self::Output {
280 self.join.append_selection(selection)
281 }
282 }
283
284 #[doc(hidden)]
285 #[derive(Debug, Clone, Copy, Default, QueryId)]
286 pub struct Inner;
287
288 impl<DB> QueryFragment<DB> for Inner
289 where
290 DB: Backend + DieselReserveSpecialization,
291 {
292 fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
293 out.push_sql(" INNER");
294 Ok(())
295 }
296 }
297
298 #[doc(hidden)]
299 #[derive(Debug, Clone, Copy, Default, QueryId)]
300 pub struct LeftOuter;
301
302 impl<DB> QueryFragment<DB> for LeftOuter
303 where
304 DB: Backend + DieselReserveSpecialization,
305 {
306 fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
307 out.push_sql(" LEFT OUTER");
308 Ok(())
309 }
310 }
311
312 impl<Left, Mid, Right, Kind> JoinTo<Right> for Join<Left, Mid, Kind>
313 where
314 Left: JoinTo<Right> + QuerySource,
315 Mid: QuerySource,
316 {
317 type FromClause = <Left as JoinTo<Right>>::FromClause;
318 type OnClause = Left::OnClause;
319
320 fn join_target(rhs: Right) -> (Self::FromClause, Self::OnClause) {
321 Left::join_target(rhs)
322 }
323 }
324
325 impl<Join, On, Right> JoinTo<Right> for JoinOn<Join, On>
326 where
327 Join: JoinTo<Right>,
328 {
329 type FromClause = Join::FromClause;
330 type OnClause = Join::OnClause;
331
332 fn join_target(rhs: Right) -> (Self::FromClause, Self::OnClause) {
333 Join::join_target(rhs)
334 }
335 }
336
337 impl<T, Left, Right, Kind> AppearsInFromClause<T> for Join<Left, Right, Kind>
338 where
339 Left: AppearsInFromClause<T> + QuerySource,
340 Right: AppearsInFromClause<T> + QuerySource,
341 Left::Count: Plus<Right::Count>,
342 {
343 type Count = <Left::Count as Plus<Right::Count>>::Output;
344 }
345
346 impl<T, Join, On> AppearsInFromClause<T> for JoinOn<Join, On>
347 where
348 Join: AppearsInFromClause<T>,
349 {
350 type Count = Join::Count;
351 }
352
353 #[doc(hidden)]
354 #[derive(Debug, Clone, Copy)]
355 pub struct OnClauseWrapper<Source, On> {
356 pub(crate) source: Source,
357 pub(crate) on: On,
358 }
359
360 impl<Source, On> OnClauseWrapper<Source, On> {
361 pub fn new(source: Source, on: On) -> Self {
362 OnClauseWrapper { source, on }
363 }
364 }
365
366 impl<Lhs, Rhs, On> JoinTo<OnClauseWrapper<Rhs, On>> for Lhs
367 where
368 Lhs: Table,
369 {
370 type FromClause = Rhs;
371 type OnClause = On;
372
373 fn join_target(rhs: OnClauseWrapper<Rhs, On>) -> (Self::FromClause, Self::OnClause) {
374 (rhs.source, rhs.on)
375 }
376 }
377
378 impl<Lhs, Rhs, On> JoinTo<Rhs> for OnClauseWrapper<Lhs, On>
379 where
380 Lhs: JoinTo<Rhs>,
381 {
382 type FromClause = <Lhs as JoinTo<Rhs>>::FromClause;
383 type OnClause = <Lhs as JoinTo<Rhs>>::OnClause;
384
385 fn join_target(rhs: Rhs) -> (Self::FromClause, Self::OnClause) {
386 <Lhs as JoinTo<Rhs>>::join_target(rhs)
387 }
388 }
389
390 impl<Rhs, Kind, On1, On2, Lhs> InternalJoinDsl<Rhs, Kind, On1> for OnClauseWrapper<Lhs, On2>
391 where
392 Lhs: InternalJoinDsl<Rhs, Kind, On1>,
393 {
394 type Output = OnClauseWrapper<<Lhs as InternalJoinDsl<Rhs, Kind, On1>>::Output, On2>;
395
396 fn join(self, rhs: Rhs, kind: Kind, on: On1) -> Self::Output {
397 OnClauseWrapper {
398 source: self.source.join(rhs, kind, on),
399 on: self.on,
400 }
401 }
402 }
403
404 impl<Qs, On> QueryDsl for OnClauseWrapper<Qs, On> {}
405
406 #[doc(hidden)]
407 /// Convert any joins in a `FROM` clause into an inner join.
408 ///
409 /// This trait is used to determine whether
410 /// `Nullable<T>: SelectableExpression<SomeJoin>`. We consider it to be
411 /// selectable if `T: SelectableExpression<InnerJoin>`. Since `SomeJoin`
412 /// may be deeply nested, we need to recursively change any appearances of
413 /// `LeftOuter` to `Inner` in order to perform this check.
414 pub trait ToInnerJoin {
415 type InnerJoin;
416 }
417
418 impl<Left, Right, Kind> ToInnerJoin for Join<Left, Right, Kind>
419 where
420 Left: ToInnerJoin + QuerySource,
421 Left::InnerJoin: QuerySource,
422 Right: ToInnerJoin + QuerySource,
423 Right::InnerJoin: QuerySource,
424 {
425 type InnerJoin = Join<Left::InnerJoin, Right::InnerJoin, Inner>;
426 }
427
428 impl<Join, On> ToInnerJoin for JoinOn<Join, On>
429 where
430 Join: ToInnerJoin,
431 {
432 type InnerJoin = JoinOn<Join::InnerJoin, On>;
433 }
434
435 impl<From> ToInnerJoin for SelectStatement<FromClause<From>>
436 where
437 From: ToInnerJoin + QuerySource,
438 From::InnerJoin: QuerySource,
439 {
440 type InnerJoin = SelectStatement<FromClause<From::InnerJoin>>;
441 }
442
443 impl<T: Table> ToInnerJoin for T {
444 type InnerJoin = T;
445 }
446
447 mod private {
448 use crate::backend::Backend;
449 use crate::expression::{Expression, ValidGrouping};
450 use crate::query_builder::{AstPass, QueryFragment, SelectClauseExpression};
451 use crate::{AppearsOnTable, QueryResult, SelectableExpression};
452
453 #[derive(Debug, crate::query_builder::QueryId, Copy, Clone)]
454 pub struct SkipSelectableExpressionBoundCheckWrapper<T>(pub(super) T);
455
456 impl<DB, T> QueryFragment<DB> for SkipSelectableExpressionBoundCheckWrapper<T>
457 where
458 T: QueryFragment<DB>,
459 DB: Backend,
460 {
461 fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
462 self.0.walk_ast(pass)
463 }
464 }
465
466 // The default select clause is only valid for no group by clause
467 // anyway so we can just skip the recursive check here
468 impl<T> ValidGrouping<()> for SkipSelectableExpressionBoundCheckWrapper<T> {
469 type IsAggregate = crate::expression::is_aggregate::No;
470 }
471
472 // This needs to use the expression impl
473 impl<QS, T> SelectClauseExpression<QS> for SkipSelectableExpressionBoundCheckWrapper<T>
474 where
475 T: SelectClauseExpression<QS>,
476 {
477 type Selection = T::Selection;
478
479 type SelectClauseSqlType = T::SelectClauseSqlType;
480 }
481
482 // The default select clause for joins is always valid assuming that
483 // the default select clause of all involved query sources is
484 // valid too. We can skip the recursive check here.
485 // This is the main optimization.
486 impl<QS, T> SelectableExpression<QS> for SkipSelectableExpressionBoundCheckWrapper<T> where
487 Self: AppearsOnTable<QS>
488 {
489 }
490
491 impl<QS, T> AppearsOnTable<QS> for SkipSelectableExpressionBoundCheckWrapper<T> where
492 Self: Expression
493 {
494 }
495
496 // Expression must recurse the whole expression
497 // as this is required for the return type of the query
498 impl<T> Expression for SkipSelectableExpressionBoundCheckWrapper<T>
499 where
500 T: Expression,
501 {
502 type SqlType = T::SqlType;
503 }
504
505 impl<T, Selection> crate::util::TupleAppend<Selection>
506 for SkipSelectableExpressionBoundCheckWrapper<T>
507 where
508 T: crate::util::TupleAppend<Selection>,
509 {
510 // We're re-wrapping after anyway
511 type Output = T::Output;
512
513 fn tuple_append(self, right: Selection) -> Self::Output {
514 self.0.tuple_append(right)
515 }
516 }
517 }