diesel/query_dsl/
join_dsl.rs

1use query_builder::AsQuery;
2use query_source::joins::OnClauseWrapper;
3use query_source::{JoinTo, QuerySource, Table};
4
5#[doc(hidden)]
6/// `JoinDsl` support trait to emulate associated type constructors
7pub trait InternalJoinDsl<Rhs, Kind, On> {
8    type Output: AsQuery;
9
10    fn join(self, rhs: Rhs, kind: Kind, on: On) -> Self::Output;
11}
12
13impl<T, Rhs, Kind, On> InternalJoinDsl<Rhs, Kind, On> for T
14where
15    T: Table + AsQuery,
16    T::Query: InternalJoinDsl<Rhs, Kind, On>,
17{
18    type Output = <T::Query as InternalJoinDsl<Rhs, Kind, On>>::Output;
19
20    fn join(self, rhs: Rhs, kind: Kind, on: On) -> Self::Output {
21        self.as_query().join(rhs, kind, on)
22    }
23}
24
25#[doc(hidden)]
26/// `JoinDsl` support trait to emulate associated type constructors and grab
27/// the known on clause from the associations API
28pub trait JoinWithImplicitOnClause<Rhs, Kind> {
29    type Output: AsQuery;
30
31    fn join_with_implicit_on_clause(self, rhs: Rhs, kind: Kind) -> Self::Output;
32}
33
34impl<Lhs, Rhs, Kind> JoinWithImplicitOnClause<Rhs, Kind> for Lhs
35where
36    Lhs: JoinTo<Rhs>,
37    Lhs: InternalJoinDsl<<Lhs as JoinTo<Rhs>>::FromClause, Kind, <Lhs as JoinTo<Rhs>>::OnClause>,
38{
39    type Output = <Lhs as InternalJoinDsl<Lhs::FromClause, Kind, Lhs::OnClause>>::Output;
40
41    fn join_with_implicit_on_clause(self, rhs: Rhs, kind: Kind) -> Self::Output {
42        let (from, on) = Lhs::join_target(rhs);
43        self.join(from, kind, on)
44    }
45}
46
47/// Specify the `ON` clause for a join statement. This will override
48/// any implicit `ON` clause that would come from [`joinable!`]
49///
50/// [`joinable!`]: ../macro.joinable.html
51///
52/// # Example
53///
54/// ```rust
55/// # #[macro_use] extern crate diesel;
56/// # include!("../doctest_setup.rs");
57/// # use schema::{users, posts};
58/// #
59/// # fn main() {
60/// #     let connection = 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) -> OnClauseWrapper<Self, On> {
77        OnClauseWrapper::new(self, on)
78    }
79}
80
81impl<T: QuerySource> JoinOnDsl for T {}