datafusion_python/expr/
conditional_expr.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::{errors::PyDataFusionResult, expr::PyExpr};
19use datafusion::logical_expr::conditional_expressions::CaseBuilder;
20use datafusion::prelude::Expr;
21use pyo3::prelude::*;
22
23// TODO(tsaucer) replace this all with CaseBuilder after it implements Clone
24#[derive(Clone, Debug)]
25#[pyclass(name = "CaseBuilder", module = "datafusion.expr", subclass, frozen)]
26pub struct PyCaseBuilder {
27    expr: Option<Expr>,
28    when: Vec<Expr>,
29    then: Vec<Expr>,
30}
31
32#[pymethods]
33impl PyCaseBuilder {
34    #[new]
35    pub fn new(expr: Option<PyExpr>) -> Self {
36        Self {
37            expr: expr.map(Into::into),
38            when: vec![],
39            then: vec![],
40        }
41    }
42
43    pub fn when(&self, when: PyExpr, then: PyExpr) -> PyCaseBuilder {
44        let mut case_builder = self.clone();
45        case_builder.when.push(when.into());
46        case_builder.then.push(then.into());
47
48        case_builder
49    }
50
51    fn otherwise(&self, else_expr: PyExpr) -> PyDataFusionResult<PyExpr> {
52        let case_builder = CaseBuilder::new(
53            self.expr.clone().map(Box::new),
54            self.when.clone(),
55            self.then.clone(),
56            Some(Box::new(else_expr.into())),
57        );
58
59        let expr = case_builder.end()?;
60
61        Ok(expr.into())
62    }
63
64    fn end(&self) -> PyDataFusionResult<PyExpr> {
65        let case_builder = CaseBuilder::new(
66            self.expr.clone().map(Box::new),
67            self.when.clone(),
68            self.then.clone(),
69            None,
70        );
71
72        let expr = case_builder.end()?;
73
74        Ok(expr.into())
75    }
76}