datafusion_python/expr/
sort_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 std::fmt::{self, Display, Formatter};
19
20use datafusion::logical_expr::SortExpr;
21use pyo3::prelude::*;
22
23use crate::expr::PyExpr;
24
25#[pyclass(frozen, name = "SortExpr", module = "datafusion.expr", subclass)]
26#[derive(Clone)]
27pub struct PySortExpr {
28    pub(crate) sort: SortExpr,
29}
30
31impl From<PySortExpr> for SortExpr {
32    fn from(sort: PySortExpr) -> Self {
33        sort.sort
34    }
35}
36
37impl From<SortExpr> for PySortExpr {
38    fn from(sort: SortExpr) -> PySortExpr {
39        PySortExpr { sort }
40    }
41}
42
43impl Display for PySortExpr {
44    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
45        write!(
46            f,
47            "Sort
48            Expr: {:?}
49            Asc: {:?}
50            NullsFirst: {:?}",
51            &self.sort.expr, &self.sort.asc, &self.sort.nulls_first
52        )
53    }
54}
55
56pub fn to_sort_expressions(order_by: Vec<PySortExpr>) -> Vec<SortExpr> {
57    order_by.iter().map(|e| e.sort.clone()).collect()
58}
59
60pub fn py_sort_expr_list(expr: &[SortExpr]) -> PyResult<Vec<PySortExpr>> {
61    Ok(expr.iter().map(|e| PySortExpr::from(e.clone())).collect())
62}
63
64#[pymethods]
65impl PySortExpr {
66    #[new]
67    fn new(expr: PyExpr, asc: bool, nulls_first: bool) -> Self {
68        Self {
69            sort: SortExpr {
70                expr: expr.into(),
71                asc,
72                nulls_first,
73            },
74        }
75    }
76
77    fn expr(&self) -> PyResult<PyExpr> {
78        Ok(self.sort.expr.clone().into())
79    }
80
81    fn ascending(&self) -> PyResult<bool> {
82        Ok(self.sort.asc)
83    }
84
85    fn nulls_first(&self) -> PyResult<bool> {
86        Ok(self.sort.nulls_first)
87    }
88
89    fn __repr__(&self) -> String {
90        format!("{self}")
91    }
92}