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