Skip to main content

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 datafusion::logical_expr::conditional_expressions::CaseBuilder;
19use datafusion::prelude::Expr;
20use pyo3::prelude::*;
21
22use crate::errors::PyDataFusionResult;
23use crate::expr::PyExpr;
24
25// TODO(tsaucer) replace this all with CaseBuilder after it implements Clone
26#[derive(Clone, Debug)]
27#[pyclass(
28    from_py_object,
29    name = "CaseBuilder",
30    module = "datafusion.expr",
31    subclass,
32    frozen
33)]
34pub struct PyCaseBuilder {
35    expr: Option<Expr>,
36    when: Vec<Expr>,
37    then: Vec<Expr>,
38}
39
40#[pymethods]
41impl PyCaseBuilder {
42    #[new]
43    pub fn new(expr: Option<PyExpr>) -> Self {
44        Self {
45            expr: expr.map(Into::into),
46            when: vec![],
47            then: vec![],
48        }
49    }
50
51    pub fn when(&self, when: PyExpr, then: PyExpr) -> PyCaseBuilder {
52        let mut case_builder = self.clone();
53        case_builder.when.push(when.into());
54        case_builder.then.push(then.into());
55
56        case_builder
57    }
58
59    fn otherwise(&self, else_expr: PyExpr) -> PyDataFusionResult<PyExpr> {
60        let case_builder = CaseBuilder::new(
61            self.expr.clone().map(Box::new),
62            self.when.clone(),
63            self.then.clone(),
64            Some(Box::new(else_expr.into())),
65        );
66
67        let expr = case_builder.end()?;
68
69        Ok(expr.into())
70    }
71
72    fn end(&self) -> PyDataFusionResult<PyExpr> {
73        let case_builder = CaseBuilder::new(
74            self.expr.clone().map(Box::new),
75            self.when.clone(),
76            self.then.clone(),
77            None,
78        );
79
80        let expr = case_builder.end()?;
81
82        Ok(expr.into())
83    }
84}