Skip to main content

datafusion_expr/
conditional_expressions.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Conditional expressions
6use crate::expr::Case;
7use crate::{Expr, expr_schema::ExprSchemable};
8use arrow::datatypes::DataType;
9use datafusion_common::{DFSchema, HashSet, Result, plan_err};
10use itertools::Itertools as _;
11
12/// Helper struct for building [Expr::Case]
13#[derive(Debug, Clone)]
14pub struct CaseBuilder {
15    expr: Option<Box<Expr>>,
16    when_expr: Vec<Expr>,
17    then_expr: Vec<Expr>,
18    else_expr: Option<Box<Expr>>,
19}
20
21impl CaseBuilder {
22    pub fn new(
23        expr: Option<Box<Expr>>,
24        when_expr: Vec<Expr>,
25        then_expr: Vec<Expr>,
26        else_expr: Option<Box<Expr>>,
27    ) -> Self {
28        Self {
29            expr,
30            when_expr,
31            then_expr,
32            else_expr,
33        }
34    }
35    pub fn when(&mut self, when: Expr, then: Expr) -> CaseBuilder {
36        self.when_expr.push(when);
37        self.then_expr.push(then);
38        CaseBuilder {
39            expr: self.expr.clone(),
40            when_expr: self.when_expr.clone(),
41            then_expr: self.then_expr.clone(),
42            else_expr: self.else_expr.clone(),
43        }
44    }
45    pub fn otherwise(&mut self, else_expr: Expr) -> Result<Expr> {
46        self.else_expr = Some(Box::new(else_expr));
47        self.build()
48    }
49
50    pub fn end(&self) -> Result<Expr> {
51        self.build()
52    }
53
54    fn build(&self) -> Result<Expr> {
55        // Collect all "then" expressions
56        let mut then_expr = self.then_expr.clone();
57        if let Some(e) = &self.else_expr {
58            then_expr.push(e.as_ref().to_owned());
59        }
60
61        let then_types: Vec<DataType> = then_expr
62            .iter()
63            .map(|e| match e {
64                Expr::Literal(_, _) => e.get_type(&DFSchema::empty()),
65                _ => Ok(DataType::Null),
66            })
67            .collect::<Result<Vec<_>>>()?;
68
69        if then_types.contains(&DataType::Null) {
70            // Cannot verify types until execution type
71        } else {
72            let unique_types: HashSet<&DataType> = then_types.iter().collect();
73            if unique_types.is_empty() {
74                return plan_err!("CASE expression 'then' values had no data types");
75            } else if unique_types.len() != 1 {
76                return plan_err!(
77                    "CASE expression 'then' values had multiple data types: {}",
78                    unique_types.iter().join(", ")
79                );
80            }
81        }
82
83        Ok(Expr::Case(Case::new(
84            self.expr.clone(),
85            self.when_expr
86                .iter()
87                .zip(self.then_expr.iter())
88                .map(|(w, t)| (Box::new(w.clone()), Box::new(t.clone())))
89                .collect(),
90            self.else_expr.clone(),
91        )))
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98    use crate::{col, lit, when};
99
100    #[test]
101    fn case_when_same_literal_then_types() -> Result<()> {
102        let _ = when(col("state").eq(lit("CO")), lit(303))
103            .when(col("state").eq(lit("NY")), lit(212))
104            .end()?;
105        Ok(())
106    }
107
108    #[test]
109    fn case_when_different_literal_then_types() {
110        let maybe_expr = when(col("state").eq(lit("CO")), lit(303))
111            .when(col("state").eq(lit("NY")), lit("212"))
112            .end();
113        assert!(maybe_expr.is_err());
114    }
115}