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