kosiew commented on code in PR #20808:
URL: https://github.com/apache/datafusion/pull/20808#discussion_r2964784271


##########
datafusion/spark/src/function/datetime/quarter.rs:
##########
@@ -0,0 +1,111 @@
+// 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 arrow::array::{ArrayRef, AsArray, Int32Array};
+use arrow::datatypes::{DataType, Date32Type, Field, FieldRef};
+use chrono::Datelike;
+use datafusion::logical_expr::{ColumnarValue, Signature, Volatility};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl};
+use std::any::Any;
+use std::sync::Arc;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkQuarter {
+    signature: Signature,
+}
+
+impl Default for SparkQuarter {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkQuarter {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::exact(vec![DataType::Date32], 
Volatility::Immutable),

Review Comment:
   I think this is the main thing we should fix before merging. Right now the 
UDF is registered with an exact `Date32` signature, which means we no longer 
preserve Spark’s documented call shape for `quarter`.
   
   Spark’s SQL docs show `SELECT quarter('2016-08-31');` returning `3`, and 
this SLT file used to carry that example before it was replaced with explicit 
`::DATE` casts. With the current signature, we only validate the casted form 
and could end up rejecting the plain string-literal case that Spark accepts.
   
   Could we switch this to a coercible signature, or possibly just route 
through the existing `date_part('quarter', ...)` behavior, and add coverage for 
the uncasted query?



##########
datafusion/spark/src/function/datetime/quarter.rs:
##########
@@ -0,0 +1,111 @@
+// 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 arrow::array::{ArrayRef, AsArray, Int32Array};
+use arrow::datatypes::{DataType, Date32Type, Field, FieldRef};
+use chrono::Datelike;
+use datafusion::logical_expr::{ColumnarValue, Signature, Volatility};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl};
+use std::any::Any;
+use std::sync::Arc;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkQuarter {
+    signature: Signature,
+}
+
+impl Default for SparkQuarter {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkQuarter {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::exact(vec![DataType::Date32], 
Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkQuarter {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "quarter"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        internal_err!("return_field_from_args should be used instead")
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        Ok(Arc::new(Field::new(
+            self.name(),
+            DataType::Int32,
+            args.arg_fields[0].is_nullable(),
+        )))
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let [arg] = take_function_args("quarter", args.args)?;

Review Comment:
   Small suggestion here: this seems to repeat the same scalar/array `Date32` 
dispatching pattern we already have in other datetime helpers, while 
`datafusion_functions::datetime::date_part()` already supports `"quarter"`.
   
   Would it make sense to delegate to that existing implementation instead? It 
feels like that would help keep coercion rules, null handling, and any future 
date-part behavior aligned in one place.



##########
datafusion/spark/src/function/datetime/quarter.rs:
##########
@@ -0,0 +1,111 @@
+// 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 arrow::array::{ArrayRef, AsArray, Int32Array};
+use arrow::datatypes::{DataType, Date32Type, Field, FieldRef};
+use chrono::Datelike;
+use datafusion::logical_expr::{ColumnarValue, Signature, Volatility};
+use datafusion_common::utils::take_function_args;
+use datafusion_common::{Result, ScalarValue, internal_err};
+use datafusion_expr::{ReturnFieldArgs, ScalarFunctionArgs, ScalarUDFImpl};
+use std::any::Any;
+use std::sync::Arc;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkQuarter {
+    signature: Signature,
+}
+
+impl Default for SparkQuarter {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl SparkQuarter {
+    pub fn new() -> Self {
+        Self {
+            signature: Signature::exact(vec![DataType::Date32], 
Volatility::Immutable),
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkQuarter {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "quarter"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
+        internal_err!("return_field_from_args should be used instead")
+    }
+
+    fn return_field_from_args(&self, args: ReturnFieldArgs) -> 
Result<FieldRef> {
+        Ok(Arc::new(Field::new(
+            self.name(),
+            DataType::Int32,
+            args.arg_fields[0].is_nullable(),
+        )))
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let [arg] = take_function_args("quarter", args.args)?;
+        match arg {
+            ColumnarValue::Scalar(ScalarValue::Date32(days)) => {
+                if let Some(days) = days {
+                    Ok(ColumnarValue::Scalar(ScalarValue::Int32(Some(
+                        spark_quarter(days)?,
+                    ))))
+                } else {
+                    Ok(ColumnarValue::Scalar(ScalarValue::Int32(None)))
+                }
+            }
+            ColumnarValue::Array(array) => {
+                let result = match array.data_type() {
+                    DataType::Date32 => {
+                        let result: Int32Array = array
+                            .as_primitive::<Date32Type>()
+                            .try_unary(spark_quarter)?
+                            .with_data_type(DataType::Int32);
+                        Ok(Arc::new(result) as ArrayRef)
+                    }
+                    other => {
+                        internal_err!(
+                            "Unsupported data type {other:?} for Spark 
function `quarter`"
+                        )
+                    }
+                }?;
+                Ok(ColumnarValue::Array(result))
+            }
+            other => {
+                internal_err!("Unsupported arg {other:?} for Spark function 
`quarter")
+            }
+        }
+    }
+}
+
+fn spark_quarter(days: i32) -> Result<i32> {
+    let quarter = Date32Type::to_naive_date_opt(days).unwrap().quarter();

Review Comment:
   One thing that made me a little nervous here is the `unwrap()`. That 
introduces a panic path if a malformed `Date32` value ever makes it down to 
this helper.
   
   `last_day` handles the same kind of conversion by returning an explicit 
error instead, which feels a bit safer for a public UDF. Could we do the same 
here so bad inputs show up as query errors rather than aborting execution?



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to