diesel/query_dsl/
join_dsl.rs

1use crate::helper_types;
2use crate::query_builder::AsQuery;
3use crate::query_source::joins::OnClauseWrapper;
4use crate::query_source::{JoinTo, QuerySource, Table};
5
6#[doc(hidden)]
7/// `JoinDsl` support trait to emulate associated type constructors
8pub trait InternalJoinDsl<Rhs, Kind, On> {
9    type Output;
10
11    fn join(self, rhs: Rhs, kind: Kind, on: On) -> Self::Output;
12}
13
14impl<T, Rhs, Kind, On> InternalJoinDsl<Rhs, Kind, On> for T
15where
16    T: Table + AsQuery,
17    T::Query: InternalJoinDsl<Rhs, Kind, On>,
18{
19    type Output = <T::Query as InternalJoinDsl<Rhs, Kind, On>>::Output;
20
21    fn join(self, rhs: Rhs, kind: Kind, on: On) -> Self::Output {
22        self.as_query().join(rhs, kind, on)
23    }
24}
25
26#[doc(hidden)]
27/// `JoinDsl` support trait to emulate associated type constructors and grab
28/// the known on clause from the associations API
29pub trait JoinWithImplicitOnClause<Rhs, Kind> {
30    type Output;
31
32    fn join_with_implicit_on_clause(self, rhs: Rhs, kind: Kind) -> Self::Output;
33}
34
35impl<Lhs, Rhs, Kind> JoinWithImplicitOnClause<Rhs, Kind> for Lhs
36where
37    Lhs: JoinTo<Rhs>,
38    Lhs: InternalJoinDsl<<Lhs as JoinTo<Rhs>>::FromClause, Kind, <Lhs as JoinTo<Rhs>>::OnClause>,
39{
40    type Output = <Lhs as InternalJoinDsl<Lhs::FromClause, Kind, Lhs::OnClause>>::Output;
41
42    fn join_with_implicit_on_clause(self, rhs: Rhs, kind: Kind) -> Self::Output {
43        let (from, on) = Lhs::join_target(rhs);
44        self.join(from, kind, on)
45    }
46}
47
48/// Specify the `ON` clause for a join statement. This will override
49/// any implicit `ON` clause that would come from [`joinable!`]
50///
51/// [`joinable!`]: crate::joinable!
52///
53/// # Example
54///
55/// ```rust
56/// # include!("../doctest_setup.rs");
57/// # use schema::{users, posts};
58/// #
59/// # fn main() {
60/// #     let connection = &mut establish_connection();
61/// let data = users::table
62///     .left_join(posts::table.on(
63///         users::id.eq(posts::user_id).and(
64///             posts::title.eq("My first post"))
65///     ))
66///     .select((users::name, posts::title.nullable()))
67///     .load(connection);
68/// let expected = vec![
69///     ("Sean".to_string(), Some("My first post".to_string())),
70///     ("Tess".to_string(), None),
71/// ];
72/// assert_eq!(Ok(expected), data);
73/// # }
74pub trait JoinOnDsl: Sized {
75    /// See the trait documentation.
76    fn on<On>(self, on: On) -> helper_types::On<Self, On> {
77        OnClauseWrapper::new(self, on)
78    }
79}
80
81impl<T: QuerySource> JoinOnDsl for T {}