1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use crate::expression::grouped::Grouped;
use crate::expression::{helper_types, Expression};
use crate::sql_types::{BoolOrNullableBool, SqlType};
use diesel_derives::{DieselNumericOps, QueryId, ValidGrouping};

use super::{AsExpression, TypedExpressionType};

/// Creates a SQL `CASE WHEN ... END` expression
///
/// # Example
///
/// ```
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = &mut establish_connection();
/// use diesel::dsl::case_when;
///
/// let users_with_name: Vec<(i32, Option<i32>)> = users
///     .select((id, case_when(name.eq("Sean"), id)))
///     .load(connection)
///     .unwrap();
///
/// assert_eq!(&[(1, Some(1)), (2, None)], users_with_name.as_slice());
/// # }
/// ```
///
/// # `ELSE` clause
/// ```
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = &mut establish_connection();
/// use diesel::dsl::case_when;
///
/// let users_with_name: Vec<(i32, i32)> = users
///     .select((id, case_when(name.eq("Sean"), id).otherwise(0)))
///     .load(connection)
///     .unwrap();
///
/// assert_eq!(&[(1, 1), (2, 0)], users_with_name.as_slice());
/// # }
/// ```
///
/// Note that the SQL types of the `case_when` and `else` expressions should
/// be equal. This includes whether they are wrapped in
/// [`Nullable`](crate::sql_types::Nullable), so you may need to call
/// [`nullable`](crate::expression_methods::NullableExpressionMethods::nullable)
/// on one of them.
///
/// # More `WHEN` branches
/// ```
/// # include!("../doctest_setup.rs");
/// #
/// # fn main() {
/// #     use schema::users::dsl::*;
/// #     let connection = &mut establish_connection();
/// use diesel::dsl::case_when;
///
/// let users_with_name: Vec<(i32, Option<i32>)> = users
///     .select((id, case_when(name.eq("Sean"), id).when(name.eq("Tess"), 2)))
///     .load(connection)
///     .unwrap();
///
/// assert_eq!(&[(1, Some(1)), (2, Some(2))], users_with_name.as_slice());
/// # }
/// ```
pub fn case_when<C, T, ST>(condition: C, if_true: T) -> helper_types::case_when<C, T, ST>
where
    C: Expression,
    <C as Expression>::SqlType: BoolOrNullableBool,
    T: AsExpression<ST>,
    ST: SqlType + TypedExpressionType,
{
    CaseWhen {
        whens: CaseWhenConditionsLeaf {
            when: Grouped(condition),
            then: Grouped(if_true.as_expression()),
        },
        else_expr: NoElseExpression,
    }
}

/// A SQL `CASE WHEN ... END` expression
#[derive(Debug, Clone, Copy, QueryId, DieselNumericOps, ValidGrouping)]
pub struct CaseWhen<Whens, E> {
    whens: Whens,
    else_expr: E,
}

impl<Whens, E> CaseWhen<Whens, E> {
    /// Add an additional `WHEN ... THEN ...` branch to the `CASE` expression
    ///
    /// See the [`case_when`] documentation for more details.
    pub fn when<C, T>(self, condition: C, if_true: T) -> helper_types::When<Self, C, T>
    where
        Self: CaseWhenTypesExtractor<Whens = Whens, Else = E>,
        C: Expression,
        <C as Expression>::SqlType: BoolOrNullableBool,
        T: AsExpression<<Self as CaseWhenTypesExtractor>::OutputExpressionSpecifiedSqlType>,
    {
        CaseWhen {
            whens: CaseWhenConditionsIntermediateNode {
                first_whens: self.whens,
                last_when: CaseWhenConditionsLeaf {
                    when: Grouped(condition),
                    then: Grouped(if_true.as_expression()),
                },
            },
            else_expr: self.else_expr,
        }
    }
}

impl<Whens> CaseWhen<Whens, NoElseExpression> {
    /// Sets the `ELSE` branch of the `CASE` expression
    ///
    /// It is named this way because `else` is a reserved keyword in Rust
    ///
    /// See the [`case_when`] documentation for more details.
    pub fn otherwise<E>(self, if_no_other_branch_matched: E) -> helper_types::Otherwise<Self, E>
    where
        Self: CaseWhenTypesExtractor<Whens = Whens, Else = NoElseExpression>,
        E: AsExpression<<Self as CaseWhenTypesExtractor>::OutputExpressionSpecifiedSqlType>,
    {
        CaseWhen {
            whens: self.whens,
            else_expr: ElseExpression {
                expr: Grouped(if_no_other_branch_matched.as_expression()),
            },
        }
    }
}

pub(crate) use non_public_types::*;
mod non_public_types {
    use super::CaseWhen;

    use diesel_derives::{QueryId, ValidGrouping};

    use crate::expression::{
        AppearsOnTable, Expression, SelectableExpression, TypedExpressionType,
    };
    use crate::query_builder::{AstPass, QueryFragment};
    use crate::query_source::aliasing;
    use crate::sql_types::{BoolOrNullableBool, IntoNullable, SqlType};

    #[derive(Debug, Clone, Copy, QueryId, ValidGrouping)]
    pub struct CaseWhenConditionsLeaf<W, T> {
        pub(super) when: W,
        pub(super) then: T,
    }

    #[derive(Debug, Clone, Copy, QueryId, ValidGrouping)]
    pub struct CaseWhenConditionsIntermediateNode<W, T, Whens> {
        pub(super) first_whens: Whens,
        pub(super) last_when: CaseWhenConditionsLeaf<W, T>,
    }

    pub trait CaseWhenConditions {
        type OutputExpressionSpecifiedSqlType: SqlType + TypedExpressionType;
    }
    impl<W, T: Expression> CaseWhenConditions for CaseWhenConditionsLeaf<W, T>
    where
        <T as Expression>::SqlType: SqlType + TypedExpressionType,
    {
        type OutputExpressionSpecifiedSqlType = T::SqlType;
    }
    // This intentionally doesn't re-check inner `Whens` here, because this trait is
    // only used to allow expression SQL type inference for `.when` calls so we
    // want to make it as lightweight as possible for fast compilation. Actual
    // guarantees are provided by the other implementations below
    impl<W, T: Expression, Whens> CaseWhenConditions for CaseWhenConditionsIntermediateNode<W, T, Whens>
    where
        <T as Expression>::SqlType: SqlType + TypedExpressionType,
    {
        type OutputExpressionSpecifiedSqlType = T::SqlType;
    }

    #[derive(Debug, Clone, Copy, QueryId, ValidGrouping)]
    pub struct NoElseExpression;
    #[derive(Debug, Clone, Copy, QueryId, ValidGrouping)]
    pub struct ElseExpression<E> {
        pub(super) expr: E,
    }

    /// Largely internal trait used to define the [`When`] and [`Otherwise`]
    /// type aliases
    ///
    /// It should typically not be needed in user code unless writing extremely
    /// generic functions
    pub trait CaseWhenTypesExtractor {
        /// The
        /// This may not be the actual output expression type: if there is no
        /// `else` it will be made `Nullable`
        type OutputExpressionSpecifiedSqlType: SqlType + TypedExpressionType;
        type Whens;
        type Else;
    }
    impl<Whens, E> CaseWhenTypesExtractor for CaseWhen<Whens, E>
    where
        Whens: CaseWhenConditions,
    {
        type OutputExpressionSpecifiedSqlType = Whens::OutputExpressionSpecifiedSqlType;
        type Whens = Whens;
        type Else = E;
    }

    impl<W, T, QS> SelectableExpression<QS> for CaseWhen<CaseWhenConditionsLeaf<W, T>, NoElseExpression>
    where
        CaseWhen<CaseWhenConditionsLeaf<W, T>, NoElseExpression>: AppearsOnTable<QS>,
        W: SelectableExpression<QS>,
        T: SelectableExpression<QS>,
    {
    }

    impl<W, T, E, QS> SelectableExpression<QS>
        for CaseWhen<CaseWhenConditionsLeaf<W, T>, ElseExpression<E>>
    where
        CaseWhen<CaseWhenConditionsLeaf<W, T>, ElseExpression<E>>: AppearsOnTable<QS>,
        W: SelectableExpression<QS>,
        T: SelectableExpression<QS>,
        E: SelectableExpression<QS>,
    {
    }

    impl<W, T, Whens, E, QS> SelectableExpression<QS>
        for CaseWhen<CaseWhenConditionsIntermediateNode<W, T, Whens>, E>
    where
        Self: AppearsOnTable<QS>,
        W: SelectableExpression<QS>,
        T: SelectableExpression<QS>,
        CaseWhen<Whens, E>: SelectableExpression<QS>,
    {
    }

    impl<W, T, QS> AppearsOnTable<QS> for CaseWhen<CaseWhenConditionsLeaf<W, T>, NoElseExpression>
    where
        CaseWhen<CaseWhenConditionsLeaf<W, T>, NoElseExpression>: Expression,
        W: AppearsOnTable<QS>,
        T: AppearsOnTable<QS>,
    {
    }

    impl<W, T, E, QS> AppearsOnTable<QS> for CaseWhen<CaseWhenConditionsLeaf<W, T>, ElseExpression<E>>
    where
        CaseWhen<CaseWhenConditionsLeaf<W, T>, ElseExpression<E>>: Expression,
        W: AppearsOnTable<QS>,
        T: AppearsOnTable<QS>,
        E: AppearsOnTable<QS>,
    {
    }

    impl<W, T, Whens, E, QS> AppearsOnTable<QS>
        for CaseWhen<CaseWhenConditionsIntermediateNode<W, T, Whens>, E>
    where
        Self: Expression,
        W: AppearsOnTable<QS>,
        T: AppearsOnTable<QS>,
        CaseWhen<Whens, E>: AppearsOnTable<QS>,
    {
    }

    impl<W, T> Expression for CaseWhen<CaseWhenConditionsLeaf<W, T>, NoElseExpression>
    where
        W: Expression,
        <W as Expression>::SqlType: BoolOrNullableBool,
        T: Expression,
        <T as Expression>::SqlType: IntoNullable,
        <<T as Expression>::SqlType as IntoNullable>::Nullable: SqlType + TypedExpressionType,
    {
        type SqlType = <<T as Expression>::SqlType as IntoNullable>::Nullable;
    }
    impl<W, T, E> Expression for CaseWhen<CaseWhenConditionsLeaf<W, T>, ElseExpression<E>>
    where
        W: Expression,
        <W as Expression>::SqlType: BoolOrNullableBool,
        T: Expression,
    {
        type SqlType = T::SqlType;
    }
    impl<W, T, Whens, E> Expression for CaseWhen<CaseWhenConditionsIntermediateNode<W, T, Whens>, E>
    where
        CaseWhen<CaseWhenConditionsLeaf<W, T>, E>: Expression,
        CaseWhen<Whens, E>: Expression<
            SqlType = <CaseWhen<CaseWhenConditionsLeaf<W, T>, E> as Expression>::SqlType,
        >,
    {
        type SqlType = <CaseWhen<CaseWhenConditionsLeaf<W, T>, E> as Expression>::SqlType;
    }

    impl<Whens, E, DB> QueryFragment<DB> for CaseWhen<Whens, E>
    where
        DB: crate::backend::Backend,
        Whens: QueryFragment<DB>,
        E: QueryFragment<DB>,
    {
        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> crate::QueryResult<()> {
            out.push_sql("CASE");
            self.whens.walk_ast(out.reborrow())?;
            self.else_expr.walk_ast(out.reborrow())?;
            out.push_sql(" END");
            Ok(())
        }
    }

    impl<W, T, DB> QueryFragment<DB> for CaseWhenConditionsLeaf<W, T>
    where
        DB: crate::backend::Backend,
        W: QueryFragment<DB>,
        T: QueryFragment<DB>,
    {
        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> crate::QueryResult<()> {
            out.push_sql(" WHEN ");
            self.when.walk_ast(out.reborrow())?;
            out.push_sql(" THEN ");
            self.then.walk_ast(out.reborrow())?;
            Ok(())
        }
    }

    impl<W, T, Whens, DB> QueryFragment<DB> for CaseWhenConditionsIntermediateNode<W, T, Whens>
    where
        DB: crate::backend::Backend,
        Whens: QueryFragment<DB>,
        W: QueryFragment<DB>,
        T: QueryFragment<DB>,
    {
        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> crate::QueryResult<()> {
            self.first_whens.walk_ast(out.reborrow())?;
            self.last_when.walk_ast(out.reborrow())?;
            Ok(())
        }
    }

    impl<DB> QueryFragment<DB> for NoElseExpression
    where
        DB: crate::backend::Backend,
    {
        fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> crate::result::QueryResult<()> {
            let _ = out;
            Ok(())
        }
    }
    impl<E, DB> QueryFragment<DB> for ElseExpression<E>
    where
        E: QueryFragment<DB>,
        DB: crate::backend::Backend,
    {
        fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> crate::result::QueryResult<()> {
            out.push_sql(" ELSE ");
            self.expr.walk_ast(out.reborrow())?;
            Ok(())
        }
    }

    impl<S, Conditions, E> aliasing::FieldAliasMapper<S> for CaseWhen<Conditions, E>
    where
        S: aliasing::AliasSource,
        Conditions: aliasing::FieldAliasMapper<S>,
        E: aliasing::FieldAliasMapper<S>,
    {
        type Out = CaseWhen<
            <Conditions as aliasing::FieldAliasMapper<S>>::Out,
            <E as aliasing::FieldAliasMapper<S>>::Out,
        >;
        fn map(self, alias: &aliasing::Alias<S>) -> Self::Out {
            CaseWhen {
                whens: self.whens.map(alias),
                else_expr: self.else_expr.map(alias),
            }
        }
    }

    impl<S, W, T> aliasing::FieldAliasMapper<S> for CaseWhenConditionsLeaf<W, T>
    where
        S: aliasing::AliasSource,
        W: aliasing::FieldAliasMapper<S>,
        T: aliasing::FieldAliasMapper<S>,
    {
        type Out = CaseWhenConditionsLeaf<
            <W as aliasing::FieldAliasMapper<S>>::Out,
            <T as aliasing::FieldAliasMapper<S>>::Out,
        >;
        fn map(self, alias: &aliasing::Alias<S>) -> Self::Out {
            CaseWhenConditionsLeaf {
                when: self.when.map(alias),
                then: self.then.map(alias),
            }
        }
    }

    impl<S, W, T, Whens> aliasing::FieldAliasMapper<S>
        for CaseWhenConditionsIntermediateNode<W, T, Whens>
    where
        S: aliasing::AliasSource,
        W: aliasing::FieldAliasMapper<S>,
        T: aliasing::FieldAliasMapper<S>,
        Whens: aliasing::FieldAliasMapper<S>,
    {
        type Out = CaseWhenConditionsIntermediateNode<
            <W as aliasing::FieldAliasMapper<S>>::Out,
            <T as aliasing::FieldAliasMapper<S>>::Out,
            <Whens as aliasing::FieldAliasMapper<S>>::Out,
        >;
        fn map(self, alias: &aliasing::Alias<S>) -> Self::Out {
            CaseWhenConditionsIntermediateNode {
                first_whens: self.first_whens.map(alias),
                last_when: self.last_when.map(alias),
            }
        }
    }
}