Skip to main content

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