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(name = "CaseBuilder", module = "datafusion.expr", subclass, frozen)]
28pub struct PyCaseBuilder {
29    expr: Option<Expr>,
30    when: Vec<Expr>,
31    then: Vec<Expr>,
32}
33
34#[pymethods]
35impl PyCaseBuilder {
36    #[new]
37    pub fn new(expr: Option<PyExpr>) -> Self {
38        Self {
39            expr: expr.map(Into::into),
40            when: vec![],
41            then: vec![],
42        }
43    }
44
45    pub fn when(&self, when: PyExpr, then: PyExpr) -> PyCaseBuilder {
46        let mut case_builder = self.clone();
47        case_builder.when.push(when.into());
48        case_builder.then.push(then.into());
49
50        case_builder
51    }
52
53    fn otherwise(&self, else_expr: PyExpr) -> PyDataFusionResult<PyExpr> {
54        let case_builder = CaseBuilder::new(
55            self.expr.clone().map(Box::new),
56            self.when.clone(),
57            self.then.clone(),
58            Some(Box::new(else_expr.into())),
59        );
60
61        let expr = case_builder.end()?;
62
63        Ok(expr.into())
64    }
65
66    fn end(&self) -> PyDataFusionResult<PyExpr> {
67        let case_builder = CaseBuilder::new(
68            self.expr.clone().map(Box::new),
69            self.when.clone(),
70            self.then.clone(),
71            None,
72        );
73
74        let expr = case_builder.end()?;
75
76        Ok(expr.into())
77    }
78}