jcsherin commented on code in PR #13040:
URL: https://github.com/apache/datafusion/pull/13040#discussion_r1811195982


##########
datafusion/functions-window/src/ntile.rs:
##########
@@ -0,0 +1,201 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::any::Any;
+use std::fmt::Debug;
+use std::sync::{Arc, OnceLock};
+
+use crate::utils::{
+    get_scalar_value_from_args, get_signed_integer, get_unsigned_integer,
+};
+use datafusion_common::arrow::array::ArrayRef;
+use datafusion_common::arrow::array::UInt64Array;
+use datafusion_common::arrow::datatypes::DataType;
+use datafusion_common::arrow::datatypes::Field;
+use datafusion_common::{exec_err, DataFusionError, Result, ScalarValue};
+use datafusion_expr::window_doc_sections::DOC_SECTION_RANKING;
+use datafusion_expr::{
+    Documentation, Literal, PartitionEvaluator, Signature, Volatility, 
WindowUDFImpl,
+};
+use datafusion_functions_window_common::expr::ExpressionArgs;
+use datafusion_functions_window_common::field;
+use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
+use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
+use field::WindowUDFFieldArgs;
+
+get_or_init_udwf!(
+    Ntile,
+    ntile,
+    "integer ranging from 1 to the argument value, dividing the partition as 
equally as possible",
+    Ntile::create
+);
+
+pub fn ntile(arg: i64) -> datafusion_expr::Expr {
+    ntile_udwf().call(vec![arg.lit()])
+}
+
+#[derive(Debug)]
+pub struct Ntile {
+    signature: Signature,
+}
+
+impl Ntile {
+    /// Create a new `ntile` function
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::uniform(
+                1,
+                vec![
+                    DataType::UInt64,
+                    DataType::UInt32,
+                    DataType::UInt16,
+                    DataType::UInt8,
+                    DataType::Int64,
+                    DataType::Int32,
+                    DataType::Int16,
+                    DataType::Int8,
+                ],
+                Volatility::Immutable,
+            ),
+        }
+    }
+
+    pub fn create() -> Self {
+        Self::new()
+    }
+}
+
+static DOCUMENTATION: OnceLock<Documentation> = OnceLock::new();
+
+fn get_ntile_doc() -> &'static Documentation {
+    DOCUMENTATION.get_or_init(|| {
+        Documentation::builder()
+            .with_doc_section(DOC_SECTION_RANKING)
+            .with_description(
+                "Integer ranging from 1 to the argument value, dividing the 
partition as equally as possible",
+            )
+            .with_syntax_example("ntile(expression)")
+            .with_argument("expression","An integer describing the number 
groups the partition should be split into")
+            .build()
+            .unwrap()
+    })
+}
+
+impl WindowUDFImpl for Ntile {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "ntile"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn expressions(&self, expr_args: ExpressionArgs) -> Vec<Arc<dyn 
PhysicalExpr>> {
+        parse_expr(expr_args.input_exprs(), expr_args.input_types())
+            .into_iter()
+            .collect::<Vec<_>>()
+    }
+
+    fn partition_evaluator(
+        &self,
+        partition_evaluator_args: PartitionEvaluatorArgs,
+    ) -> Result<Box<dyn PartitionEvaluator>> {
+        let scalar_n =
+            get_scalar_value_from_args(partition_evaluator_args.input_exprs(), 
0)?
+                .ok_or_else(|| {
+                    DataFusionError::Execution(
+                        "NTILE requires a positive integer".to_string(),
+                    )
+                })?;
+
+        let n = get_unsigned_integer(scalar_n)?;
+
+        Ok(Box::new(NtileEvaluator { n }))
+    }
+    fn field(&self, field_args: WindowUDFFieldArgs) -> Result<Field> {
+        let nullable = false;
+        let return_type: &DataType = field_args.input_types().first().unwrap();
+
+        Ok(Field::new(self.name(), return_type.clone(), nullable))

Review Comment:
   When constructing the result field (column) we need to pass the fully 
qualified name in the schema which is available in `WindowUDFFieldArgs`.
   
https://github.com/apache/datafusion/blob/818ce3f01efe1213a9a1eda5dff1542bb9d457f7/datafusion/expr/src/udwf.rs#L387-L390
   
   It is easy to get confused with the name of the udwf 😅. 
   
   > 
   > ```
   > External error: query failed: DataFusion error: Internal error: Input 
field name ntile does not match with the projection expression ntile(Int64(8)) 
ORDER BY [aggregate_test_100.c4 ASC NULLS LAST] RANGE BETWEEN UNBOUNDED 
PRECEDING AND CURRENT ROW.
   > This was likely caused by a bug in DataFusion's code and we would welcome 
that you file an bug report in our issue tracker
   > [SQL] SELECT
   > NTILE(8) OVER (ORDER BY C4) as ntile1,
   > NTILE(12) OVER (ORDER BY C12 DESC) as ntile2
   > FROM aggregate_test_100
   > ORDER BY c7
   > LIMIT 5
   > at test_files/window.slt:743
   > ```
   
   ```suggestion
           Ok(Field::new(field_args.name(), return_type.clone(), nullable))
   ```
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to