use super::{AppearsInFromClause, Plus}; use crate::backend::Backend; use crate::backend::DieselReserveSpecialization; use crate::expression::grouped::Grouped; use crate::expression::nullable::Nullable; use crate::prelude::*; use crate::query_builder::*; use crate::query_dsl::InternalJoinDsl; use crate::sql_types::BoolOrNullableBool; use crate::util::TupleAppend; /// A query source representing the join between two tables pub struct Join { left: FromClause, right: FromClause, kind: Kind, } impl Clone for Join where Left: QuerySource, FromClause: Clone, Right: QuerySource, FromClause: Clone, Kind: Clone, { fn clone(&self) -> Self { Self { left: self.left.clone(), right: self.right.clone(), kind: self.kind.clone(), } } } impl Copy for Join where Left: QuerySource, FromClause: Copy, Right: QuerySource, FromClause: Copy, Kind: Copy, { } impl std::fmt::Debug for Join where Left: QuerySource, FromClause: std::fmt::Debug, Right: QuerySource, FromClause: std::fmt::Debug, Kind: std::fmt::Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Join") .field("left", &self.left) .field("right", &self.right) .field("kind", &self.kind) .finish() } } impl QueryId for Join where Left: QueryId + QuerySource + 'static, Right: QueryId + QuerySource + 'static, Kind: QueryId, { type QueryId = Join; const HAS_STATIC_QUERY_ID: bool = Left::HAS_STATIC_QUERY_ID && Right::HAS_STATIC_QUERY_ID && Kind::HAS_STATIC_QUERY_ID; } #[derive(Debug, Clone, Copy, QueryId)] #[doc(hidden)] /// A query source representing the join between two tables with an explicit /// `ON` given. `Join` should usually be referenced instead, as all "type /// safety" traits are implemented in terms of `Join` implementing them. pub struct JoinOn { join: Join, on: On, } impl Join where Left: QuerySource, Right: QuerySource, { pub(crate) fn new(left: Left, right: Right, kind: Kind) -> Self { Join { left: FromClause::new(left), right: FromClause::new(right), kind, } } pub(crate) fn on(self, on: On) -> JoinOn { JoinOn { join: self, on: on } } } impl QuerySource for Join where Left: QuerySource + AppendSelection, Right: QuerySource, Left::Output: AppearsOnTable, Self: Clone, { type FromClause = Self; // combining two valid selectable expressions for both tables will always yield a // valid selectable expressions for the whole join, so no need to check that here // again. These checked turned out to be quite expensive in terms of compile time // so we use a wrapper type to just skip the check and forward other more relevant // trait implementations to the inner type // // See https://github.com/diesel-rs/diesel/issues/3223 for details type DefaultSelection = self::private::SkipSelectableExpressionBoundCheckWrapper; fn from_clause(&self) -> Self::FromClause { self.clone() } fn default_selection(&self) -> Self::DefaultSelection { self::private::SkipSelectableExpressionBoundCheckWrapper( self.left .source .append_selection(self.right.source.default_selection()), ) } } impl QuerySource for Join where Left: QuerySource + AppendSelection>, Right: QuerySource, Left::Output: AppearsOnTable, Self: Clone, { type FromClause = Self; // combining two valid selectable expressions for both tables will always yield a // valid selectable expressions for the whole join, so no need to check that here // again. These checked turned out to be quite expensive in terms of compile time // so we use a wrapper type to just skip the check and forward other more relevant // trait implementations to the inner type // // See https://github.com/diesel-rs/diesel/issues/3223 for details type DefaultSelection = self::private::SkipSelectableExpressionBoundCheckWrapper; fn from_clause(&self) -> Self::FromClause { self.clone() } fn default_selection(&self) -> Self::DefaultSelection { self::private::SkipSelectableExpressionBoundCheckWrapper( self.left .source .append_selection(self.right.source.default_selection().nullable()), ) } } #[derive(Debug, Clone, Copy)] pub struct OnKeyword; impl nodes::MiddleFragment for OnKeyword { fn push_sql(&self, mut pass: AstPass<'_, '_, DB>) { pass.push_sql(" ON "); } } impl QuerySource for JoinOn where Join: QuerySource, On: AppearsOnTable + Clone, On::SqlType: BoolOrNullableBool, Join::DefaultSelection: SelectableExpression, { type FromClause = Grouped>; type DefaultSelection = Join::DefaultSelection; fn from_clause(&self) -> Self::FromClause { Grouped(nodes::InfixNode::new( self.join.from_clause(), self.on.clone(), OnKeyword, )) } fn default_selection(&self) -> Self::DefaultSelection { self.join.default_selection() } } impl QueryFragment for Join where DB: Backend + DieselReserveSpecialization, Left: QuerySource, Left::FromClause: QueryFragment, Right: QuerySource, Right::FromClause: QueryFragment, Kind: QueryFragment, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { self.left.from_clause.walk_ast(out.reborrow())?; self.kind.walk_ast(out.reborrow())?; out.push_sql(" JOIN "); self.right.from_clause.walk_ast(out.reborrow())?; Ok(()) } } /// Indicates that two tables can be joined without an explicit `ON` clause. /// /// Implementations of this trait are generated by invoking [`joinable!`]. /// Implementing this trait means that you can call /// `left_table.inner_join(right_table)`, without supplying the `ON` clause /// explicitly. To join two tables which do not implement this trait, you will /// need to call [`.on`]. /// /// See [`joinable!`] and [`inner_join`] for usage examples. /// /// [`joinable!`]: crate::joinable! /// [`.on`]: crate::query_dsl::JoinOnDsl::on() /// [`inner_join`]: crate::query_dsl::QueryDsl::inner_join() #[diagnostic::on_unimplemented( message = "cannot join `{T}` to `{Self}` due to missing relation", note = "joining tables directly either requires a `diesel::joinable!` definition \ or calling `JoinOnDsl::on` to manually specify the `ON` clause of the join`" )] pub trait JoinTo { #[doc(hidden)] type FromClause; #[doc(hidden)] type OnClause; #[doc(hidden)] fn join_target(rhs: T) -> (Self::FromClause, Self::OnClause); } #[doc(hidden)] /// Used to ensure the sql type of `left.join(mid).join(right)` is /// `(Left, Mid, Right)` and not `((Left, Mid), Right)`. This needs /// to be separate from `TupleAppend` because we still want to keep /// the column lists (which are tuples) separate. pub trait AppendSelection { type Output; fn append_selection(&self, selection: Selection) -> Self::Output; } impl AppendSelection for T { type Output = (T::AllColumns, Selection); fn append_selection(&self, selection: Selection) -> Self::Output { (T::all_columns(), selection) } } impl AppendSelection for Join where Left: QuerySource, Mid: QuerySource, Self: QuerySource, ::DefaultSelection: TupleAppend, { type Output = <::DefaultSelection as TupleAppend>::Output; fn append_selection(&self, selection: Selection) -> Self::Output { self.default_selection().tuple_append(selection) } } impl AppendSelection for JoinOn where Join: AppendSelection, { type Output = Join::Output; fn append_selection(&self, selection: Selection) -> Self::Output { self.join.append_selection(selection) } } #[doc(hidden)] #[derive(Debug, Clone, Copy, Default, QueryId)] pub struct Inner; impl QueryFragment for Inner where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.push_sql(" INNER"); Ok(()) } } #[doc(hidden)] #[derive(Debug, Clone, Copy, Default, QueryId)] pub struct LeftOuter; impl QueryFragment for LeftOuter where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.push_sql(" LEFT OUTER"); Ok(()) } } impl JoinTo for Join where Left: JoinTo + QuerySource, Mid: QuerySource, { type FromClause = >::FromClause; type OnClause = Left::OnClause; fn join_target(rhs: Right) -> (Self::FromClause, Self::OnClause) { Left::join_target(rhs) } } impl JoinTo for JoinOn where Join: JoinTo, { type FromClause = Join::FromClause; type OnClause = Join::OnClause; fn join_target(rhs: Right) -> (Self::FromClause, Self::OnClause) { Join::join_target(rhs) } } impl AppearsInFromClause for Join where Left: AppearsInFromClause + QuerySource, Right: AppearsInFromClause + QuerySource, Left::Count: Plus, { type Count = >::Output; } impl AppearsInFromClause for JoinOn where Join: AppearsInFromClause, { type Count = Join::Count; } #[doc(hidden)] #[derive(Debug, Clone, Copy)] pub struct OnClauseWrapper { pub(crate) source: Source, pub(crate) on: On, } impl OnClauseWrapper { pub fn new(source: Source, on: On) -> Self { OnClauseWrapper { source, on } } } impl JoinTo> for Lhs where Lhs: Table, { type FromClause = Rhs; type OnClause = On; fn join_target(rhs: OnClauseWrapper) -> (Self::FromClause, Self::OnClause) { (rhs.source, rhs.on) } } impl JoinTo for OnClauseWrapper where Lhs: JoinTo, { type FromClause = >::FromClause; type OnClause = >::OnClause; fn join_target(rhs: Rhs) -> (Self::FromClause, Self::OnClause) { >::join_target(rhs) } } impl InternalJoinDsl for OnClauseWrapper where Lhs: InternalJoinDsl, { type Output = OnClauseWrapper<>::Output, On2>; fn join(self, rhs: Rhs, kind: Kind, on: On1) -> Self::Output { OnClauseWrapper { source: self.source.join(rhs, kind, on), on: self.on, } } } impl QueryDsl for OnClauseWrapper {} #[doc(hidden)] /// Convert any joins in a `FROM` clause into an inner join. /// /// This trait is used to determine whether /// `Nullable: SelectableExpression`. We consider it to be /// selectable if `T: SelectableExpression`. Since `SomeJoin` /// may be deeply nested, we need to recursively change any appearances of /// `LeftOuter` to `Inner` in order to perform this check. pub trait ToInnerJoin { type InnerJoin; } impl ToInnerJoin for Join where Left: ToInnerJoin + QuerySource, Left::InnerJoin: QuerySource, Right: ToInnerJoin + QuerySource, Right::InnerJoin: QuerySource, { type InnerJoin = Join; } impl ToInnerJoin for JoinOn where Join: ToInnerJoin, { type InnerJoin = JoinOn; } impl ToInnerJoin for SelectStatement> where From: ToInnerJoin + QuerySource, From::InnerJoin: QuerySource, { type InnerJoin = SelectStatement>; } impl ToInnerJoin for T { type InnerJoin = T; } mod private { use crate::backend::Backend; use crate::expression::{Expression, ValidGrouping}; use crate::query_builder::{AstPass, QueryFragment, SelectClauseExpression}; use crate::{AppearsOnTable, QueryResult, SelectableExpression}; #[derive(Debug, crate::query_builder::QueryId, Copy, Clone)] pub struct SkipSelectableExpressionBoundCheckWrapper(pub(super) T); impl QueryFragment for SkipSelectableExpressionBoundCheckWrapper where T: QueryFragment, DB: Backend, { fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> { self.0.walk_ast(pass) } } // The default select clause is only valid for no group by clause // anyway so we can just skip the recursive check here impl ValidGrouping<()> for SkipSelectableExpressionBoundCheckWrapper { type IsAggregate = crate::expression::is_aggregate::No; } // This needs to use the expression impl impl SelectClauseExpression for SkipSelectableExpressionBoundCheckWrapper where T: SelectClauseExpression, { type Selection = T::Selection; type SelectClauseSqlType = T::SelectClauseSqlType; } // The default select clause for joins is always valid assuming that // the default select clause of all involved query sources is // valid too. We can skip the recursive check here. // This is the main optimization. impl SelectableExpression for SkipSelectableExpressionBoundCheckWrapper where Self: AppearsOnTable { } impl AppearsOnTable for SkipSelectableExpressionBoundCheckWrapper where Self: Expression { } // Expression must recurse the whole expression // as this is required for the return type of the query impl Expression for SkipSelectableExpressionBoundCheckWrapper where T: Expression, { type SqlType = T::SqlType; } impl crate::util::TupleAppend for SkipSelectableExpressionBoundCheckWrapper where T: crate::util::TupleAppend, { // We're re-wrapping after anyway type Output = T::Output; fn tuple_append(self, right: Selection) -> Self::Output { self.0.tuple_append(right) } } }