datafusion_functions_window/
ntile.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
18//! `ntile` window function implementation
19
20use crate::utils::{
21    get_scalar_value_from_args, get_signed_integer, get_unsigned_integer,
22};
23use arrow::datatypes::FieldRef;
24use datafusion_common::arrow::array::{ArrayRef, UInt64Array};
25use datafusion_common::arrow::datatypes::{DataType, Field};
26use datafusion_common::{exec_datafusion_err, exec_err, Result};
27use datafusion_expr::{
28    Documentation, LimitEffect, PartitionEvaluator, Signature, Volatility, WindowUDFImpl,
29};
30use datafusion_functions_window_common::field;
31use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
32use datafusion_macros::user_doc;
33use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
34use field::WindowUDFFieldArgs;
35use std::any::Any;
36use std::fmt::Debug;
37use std::sync::Arc;
38
39define_udwf_and_expr!(
40    Ntile,
41    ntile,
42    [arg],
43    "Integer ranging from 1 to the argument value, dividing the partition as equally as possible."
44);
45
46#[user_doc(
47    doc_section(label = "Ranking Functions"),
48    description = "Integer ranging from 1 to the argument value, dividing the partition as equally as possible",
49    syntax_example = "ntile(expression)",
50    argument(
51        name = "expression",
52        description = "An integer describing the number groups the partition should be split into"
53    ),
54    sql_example = r#"
55```sql
56-- Example usage of the ntile window function:
57SELECT employee_id,
58    salary,
59    ntile(4) OVER (ORDER BY salary DESC) AS quartile
60FROM employees;
61
62+-------------+--------+----------+
63| employee_id | salary | quartile |
64+-------------+--------+----------+
65| 1           | 90000  | 1        |
66| 2           | 85000  | 1        |
67| 3           | 80000  | 2        |
68| 4           | 70000  | 2        |
69| 5           | 60000  | 3        |
70| 6           | 50000  | 3        |
71| 7           | 40000  | 4        |
72| 8           | 30000  | 4        |
73+-------------+--------+----------+
74```
75"#
76)]
77#[derive(Debug, PartialEq, Eq, Hash)]
78pub struct Ntile {
79    signature: Signature,
80}
81
82impl Ntile {
83    /// Create a new `ntile` function
84    pub fn new() -> Self {
85        Self {
86            signature: Signature::uniform(
87                1,
88                vec![
89                    DataType::UInt64,
90                    DataType::UInt32,
91                    DataType::UInt16,
92                    DataType::UInt8,
93                    DataType::Int64,
94                    DataType::Int32,
95                    DataType::Int16,
96                    DataType::Int8,
97                ],
98                Volatility::Immutable,
99            ),
100        }
101    }
102}
103
104impl Default for Ntile {
105    fn default() -> Self {
106        Self::new()
107    }
108}
109
110impl WindowUDFImpl for Ntile {
111    fn as_any(&self) -> &dyn Any {
112        self
113    }
114
115    fn name(&self) -> &str {
116        "ntile"
117    }
118
119    fn signature(&self) -> &Signature {
120        &self.signature
121    }
122
123    fn partition_evaluator(
124        &self,
125        partition_evaluator_args: PartitionEvaluatorArgs,
126    ) -> Result<Box<dyn PartitionEvaluator>> {
127        let scalar_n =
128            get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 0)?
129                .ok_or_else(|| {
130                    exec_datafusion_err!("NTILE requires a positive integer")
131                })?;
132
133        if scalar_n.is_null() {
134            return exec_err!("NTILE requires a positive integer, but finds NULL");
135        }
136
137        if scalar_n.is_unsigned() {
138            let n = get_unsigned_integer(scalar_n)?;
139            Ok(Box::new(NtileEvaluator { n }))
140        } else {
141            let n: i64 = get_signed_integer(scalar_n)?;
142            if n <= 0 {
143                return exec_err!("NTILE requires a positive integer");
144            }
145            Ok(Box::new(NtileEvaluator { n: n as u64 }))
146        }
147    }
148    fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
149        let nullable = false;
150
151        Ok(Field::new(field_args.name(), DataType::UInt64, nullable).into())
152    }
153
154    fn documentation(&self) -> Option<&Documentation> {
155        self.doc()
156    }
157
158    fn limit_effect(&self, _args: &[Arc<dyn PhysicalExpr>]) -> LimitEffect {
159        LimitEffect::Unknown
160    }
161}
162
163#[derive(Debug)]
164struct NtileEvaluator {
165    n: u64,
166}
167
168impl PartitionEvaluator for NtileEvaluator {
169    fn evaluate_all(
170        &mut self,
171        _values: &[ArrayRef],
172        num_rows: usize,
173    ) -> Result<ArrayRef> {
174        let num_rows = num_rows as u64;
175        let mut vec: Vec<u64> = Vec::new();
176        let n = u64::min(self.n, num_rows);
177        for i in 0..num_rows {
178            let res = i * n / num_rows;
179            vec.push(res + 1)
180        }
181        Ok(Arc::new(UInt64Array::from(vec)))
182    }
183}