qail_core/ast/builders/
case_when.rs

1//! CASE WHEN expression builders.
2
3use crate::ast::{Condition, Expr};
4
5/// Start a CASE WHEN expression
6pub fn case_when(condition: Condition, then_expr: impl Into<Expr>) -> CaseBuilder {
7    CaseBuilder {
8        when_clauses: vec![(condition, Box::new(then_expr.into()))],
9        else_value: None,
10        alias: None,
11    }
12}
13
14/// Builder for CASE expressions
15#[derive(Debug, Clone)]
16pub struct CaseBuilder {
17    pub(crate) when_clauses: Vec<(Condition, Box<Expr>)>,
18    pub(crate) else_value: Option<Box<Expr>>,
19    pub(crate) alias: Option<String>,
20}
21
22impl CaseBuilder {
23    /// Add another WHEN clause
24    pub fn when(mut self, condition: Condition, then_expr: impl Into<Expr>) -> Self {
25        self.when_clauses
26            .push((condition, Box::new(then_expr.into())));
27        self
28    }
29
30    /// Add ELSE clause
31    pub fn otherwise(mut self, else_expr: impl Into<Expr>) -> Self {
32        self.else_value = Some(Box::new(else_expr.into()));
33        self
34    }
35
36    /// Add alias (AS name)
37    pub fn alias(mut self, name: &str) -> Expr {
38        self.alias = Some(name.to_string());
39        self.build()
40    }
41
42    /// Build the final Expr
43    pub fn build(self) -> Expr {
44        Expr::Case {
45            when_clauses: self.when_clauses,
46            else_value: self.else_value,
47            alias: self.alias,
48        }
49    }
50}
51
52impl From<CaseBuilder> for Expr {
53    fn from(builder: CaseBuilder) -> Self {
54        builder.build()
55    }
56}