Skip to main content

datafusion_python/expr/
filter.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 std::fmt::{self, Display, Formatter};
19
20use datafusion::logical_expr::logical_plan::Filter;
21use pyo3::IntoPyObjectExt;
22use pyo3::prelude::*;
23
24use crate::common::df_schema::PyDFSchema;
25use crate::expr::PyExpr;
26use crate::expr::logical_node::LogicalNode;
27use crate::sql::logical::PyLogicalPlan;
28
29#[pyclass(
30    from_py_object,
31    frozen,
32    name = "Filter",
33    module = "datafusion.expr",
34    subclass
35)]
36#[derive(Clone)]
37pub struct PyFilter {
38    filter: Filter,
39}
40
41impl From<Filter> for PyFilter {
42    fn from(filter: Filter) -> PyFilter {
43        PyFilter { filter }
44    }
45}
46
47impl From<PyFilter> for Filter {
48    fn from(filter: PyFilter) -> Self {
49        filter.filter
50    }
51}
52
53impl Display for PyFilter {
54    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
55        write!(
56            f,
57            "Filter
58            Predicate: {:?}
59            Input: {:?}",
60            &self.filter.predicate, &self.filter.input
61        )
62    }
63}
64
65#[pymethods]
66impl PyFilter {
67    /// Retrieves the predicate expression for this `Filter`
68    fn predicate(&self) -> PyExpr {
69        PyExpr::from(self.filter.predicate.clone())
70    }
71
72    /// Retrieves the input `LogicalPlan` to this `Filter` node
73    fn input(&self) -> PyResult<Vec<PyLogicalPlan>> {
74        Ok(Self::inputs(self))
75    }
76
77    /// Resulting Schema for this `Filter` node instance
78    fn schema(&self) -> PyDFSchema {
79        self.filter.input.schema().as_ref().clone().into()
80    }
81
82    fn __repr__(&self) -> String {
83        format!("Filter({self})")
84    }
85}
86
87impl LogicalNode for PyFilter {
88    fn inputs(&self) -> Vec<PyLogicalPlan> {
89        vec![PyLogicalPlan::from((*self.filter.input).clone())]
90    }
91
92    fn to_variant<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
93        self.clone().into_bound_py_any(py)
94    }
95}