| 65 | } |
| 66 | |
| 67 | fn build(&self) -> Result<Expr> { |
| 68 | // Collect all "then" expressions |
| 69 | let mut then_expr = self.then_expr.clone(); |
| 70 | if let Some(e) = &self.else_expr { |
| 71 | then_expr.push(e.as_ref().to_owned()); |
| 72 | } |
| 73 | |
| 74 | let then_types: Vec<DataType> = then_expr |
| 75 | .iter() |
| 76 | .map(|e| match e { |
| 77 | Expr::Literal(_, _) => e.get_type(&DFSchema::empty()), |
| 78 | _ => Ok(DataType::Null), |
| 79 | }) |
| 80 | .collect::<Result<Vec<_>>>()?; |
| 81 | |
| 82 | if then_types.contains(&DataType::Null) { |
| 83 | // Cannot verify types until execution type |
| 84 | } else { |
| 85 | let unique_types: HashSet<&DataType> = then_types.iter().collect(); |
| 86 | if unique_types.is_empty() { |
| 87 | return plan_err!("CASE expression 'then' values had no data types"); |
| 88 | } else if unique_types.len() != 1 { |
| 89 | return plan_err!( |
| 90 | "CASE expression 'then' values had multiple data types: {}", |
| 91 | unique_types.iter().join(", ") |
| 92 | ); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | Ok(Expr::Case(Case::new( |
| 97 | self.expr.clone(), |
| 98 | self.when_expr |
| 99 | .iter() |
| 100 | .zip(self.then_expr.iter()) |
| 101 | .map(|(w, t)| (Box::new(w.clone()), Box::new(t.clone()))) |
| 102 | .collect(), |
| 103 | self.else_expr.clone(), |
| 104 | ))) |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | #[cfg(test)] |