1use super::{AppearsInFromClause, Plus};
2use crate::backend::Backend;
3use crate::backend::DieselReserveSpecialization;
4use crate::expression::grouped::Grouped;
5use crate::expression::nullable::Nullable;
6use crate::prelude::*;
7use crate::query_builder::*;
8use crate::query_dsl::InternalJoinDsl;
9use crate::sql_types::BoolOrNullableBool;
10use crate::util::TupleAppend;
11
12pub struct Join<Left: QuerySource, Right: QuerySource, Kind> {
14 left: FromClause<Left>,
15 right: FromClause<Right>,
16 kind: Kind,
17}
18
19impl<Left, Right, Kind> Clone for Join<Left, Right, Kind>
20where
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
36impl<Left, Right, Kind> Copy for Join<Left, Right, Kind>
37where
38 Left: QuerySource,
39 FromClause<Left>: Copy,
40 Right: QuerySource,
41 FromClause<Right>: Copy,
42 Kind: Copy,
43{
44}
45
46impl<Left, Right, Kind> std::fmt::Debug for Join<Left, Right, Kind>
47where
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
63impl<Left, Right, Kind> QueryId for Join<Left, Right, Kind>
64where
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)]
77pub struct JoinOn<Join, On> {
81 join: Join,
82 on: On,
83}
84
85impl<Left, Right, Kind> Join<Left, Right, Kind>
86where
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
103impl<Left, Right> QuerySource for Join<Left, Right, Inner>
104where
105 Left: QuerySource + AppendSelection<Right::DefaultSelection>,
106 Right: QuerySource,
107 Left::Output: AppearsOnTable<Self>,
108 Self: Clone,
109{
110 type FromClause = Self;
111 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
133impl<Left, Right> QuerySource for Join<Left, Right, LeftOuter>
134where
135 Left: QuerySource + AppendSelection<Nullable<Right::DefaultSelection>>,
136 Right: QuerySource,
137 Left::Output: AppearsOnTable<Self>,
138 Self: Clone,
139{
140 type FromClause = Self;
141 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)]
164pub struct OnKeyword;
165
166impl<DB: Backend> nodes::MiddleFragment<DB> for OnKeyword {
167 fn push_sql(&self, mut pass: AstPass<'_, '_, DB>) {
168 pass.push_sql(" ON ");
169 }
170}
171
172impl<Join, On> QuerySource for JoinOn<Join, On>
173where
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
195impl<Left, Right, Kind, DB> QueryFragment<DB> for Join<Left, Right, Kind>
196where
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#[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)]
231pub 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)]
241pub trait AppendSelection<Selection> {
246 type Output;
247
248 fn append_selection(&self, selection: Selection) -> Self::Output;
249}
250
251impl<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
259impl<Left, Mid, Selection, Kind> AppendSelection<Selection> for Join<Left, Mid, Kind>
260where
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
273impl<Join, On, Selection> AppendSelection<Selection> for JoinOn<Join, On>
274where
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)]
286pub struct Inner;
287
288impl<DB> QueryFragment<DB> for Inner
289where
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)]
300pub struct LeftOuter;
301
302impl<DB> QueryFragment<DB> for LeftOuter
303where
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
312impl<Left, Mid, Right, Kind> JoinTo<Right> for Join<Left, Mid, Kind>
313where
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
325impl<Join, On, Right> JoinTo<Right> for JoinOn<Join, On>
326where
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
337impl<T, Left, Right, Kind> AppearsInFromClause<T> for Join<Left, Right, Kind>
338where
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
346impl<T, Join, On> AppearsInFromClause<T> for JoinOn<Join, On>
347where
348 Join: AppearsInFromClause<T>,
349{
350 type Count = Join::Count;
351}
352
353#[doc(hidden)]
354#[derive(Debug, Clone, Copy)]
355pub struct OnClauseWrapper<Source, On> {
356 pub(crate) source: Source,
357 pub(crate) on: On,
358}
359
360impl<Source, On> OnClauseWrapper<Source, On> {
361 pub fn new(source: Source, on: On) -> Self {
362 OnClauseWrapper { source, on }
363 }
364}
365
366impl<Lhs, Rhs, On> JoinTo<OnClauseWrapper<Rhs, On>> for Lhs
367where
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
378impl<Lhs, Rhs, On> JoinTo<Rhs> for OnClauseWrapper<Lhs, On>
379where
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
390impl<Rhs, Kind, On1, On2, Lhs> InternalJoinDsl<Rhs, Kind, On1> for OnClauseWrapper<Lhs, On2>
391where
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
404impl<Qs, On> QueryDsl for OnClauseWrapper<Qs, On> {}
405
406#[doc(hidden)]
407pub trait ToInnerJoin {
415 type InnerJoin;
416}
417
418impl<Left, Right, Kind> ToInnerJoin for Join<Left, Right, Kind>
419where
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
428impl<Join, On> ToInnerJoin for JoinOn<Join, On>
429where
430 Join: ToInnerJoin,
431{
432 type InnerJoin = JoinOn<Join::InnerJoin, On>;
433}
434
435impl<From> ToInnerJoin for SelectStatement<FromClause<From>>
436where
437 From: ToInnerJoin + QuerySource,
438 From::InnerJoin: QuerySource,
439{
440 type InnerJoin = SelectStatement<FromClause<From::InnerJoin>>;
441}
442
443impl<T: Table> ToInnerJoin for T {
444 type InnerJoin = T;
445}
446
447mod 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 impl<T> ValidGrouping<()> for SkipSelectableExpressionBoundCheckWrapper<T> {
469 type IsAggregate = crate::expression::is_aggregate::No;
470 }
471
472 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 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 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 type Output = T::Output;
512
513 fn tuple_append(self, right: Selection) -> Self::Output {
514 self.0.tuple_append(right)
515 }
516 }
517}