andygrove commented on code in PR #2936:
URL: https://github.com/apache/datafusion-comet/pull/2936#discussion_r2692887855


##########
native/spark-expr/src/datetime_funcs/unix_timestamp.rs:
##########
@@ -0,0 +1,242 @@
+// 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 crate::utils::array_with_timezone;
+use arrow::array::{Array, AsArray, PrimitiveArray};
+use arrow::compute::cast;
+use arrow::datatypes::{DataType, Int64Type, TimeUnit::Microsecond};
+use datafusion::common::{internal_datafusion_err, DataFusionError};
+use datafusion::logical_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use num::integer::div_floor;
+use std::{any::Any, fmt::Debug, sync::Arc};
+
+const MICROS_PER_SECOND: i64 = 1_000_000;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkUnixTimestamp {
+    signature: Signature,
+    aliases: Vec<String>,
+    timezone: String,
+}
+
+impl SparkUnixTimestamp {
+    pub fn new(timezone: String) -> Self {
+        Self {
+            signature: Signature::user_defined(Volatility::Immutable),
+            aliases: vec![],
+            timezone,
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkUnixTimestamp {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "unix_timestamp"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> 
datafusion::common::Result<DataType> {
+        Ok(match &arg_types[0] {
+            DataType::Dictionary(_, _) => {
+                DataType::Dictionary(Box::new(DataType::Int32), 
Box::new(DataType::Int64))
+            }
+            _ => DataType::Int64,
+        })
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: ScalarFunctionArgs,
+    ) -> datafusion::common::Result<ColumnarValue> {
+        let args: [ColumnarValue; 1] = args
+            .args
+            .try_into()
+            .map_err(|_| internal_datafusion_err!("unix_timestamp expects 
exactly one argument"))?;
+
+        match args {

Review Comment:
   Good catch! I've added a test for TimestampNTZ and discovered it produces 
incorrect results - there's an 8-hour offset when using non-UTC timezones. 
   
   The issue is that TimestampNTZ stores local time without timezone, so we 
shouldn't apply timezone conversion. For now I've marked TimestampNTZ as 
unsupported and added a fallback test. We can add proper TimestampNTZ support 
in a follow-up PR.



##########
native/spark-expr/src/datetime_funcs/unix_timestamp.rs:
##########
@@ -0,0 +1,242 @@
+// 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 crate::utils::array_with_timezone;
+use arrow::array::{Array, AsArray, PrimitiveArray};
+use arrow::compute::cast;
+use arrow::datatypes::{DataType, Int64Type, TimeUnit::Microsecond};
+use datafusion::common::{internal_datafusion_err, DataFusionError};
+use datafusion::logical_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use num::integer::div_floor;
+use std::{any::Any, fmt::Debug, sync::Arc};
+
+const MICROS_PER_SECOND: i64 = 1_000_000;
+
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkUnixTimestamp {
+    signature: Signature,
+    aliases: Vec<String>,
+    timezone: String,
+}
+
+impl SparkUnixTimestamp {
+    pub fn new(timezone: String) -> Self {
+        Self {
+            signature: Signature::user_defined(Volatility::Immutable),
+            aliases: vec![],
+            timezone,
+        }
+    }
+}
+
+impl ScalarUDFImpl for SparkUnixTimestamp {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn name(&self) -> &str {
+        "unix_timestamp"
+    }
+
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> 
datafusion::common::Result<DataType> {
+        Ok(match &arg_types[0] {
+            DataType::Dictionary(_, _) => {
+                DataType::Dictionary(Box::new(DataType::Int32), 
Box::new(DataType::Int64))
+            }
+            _ => DataType::Int64,
+        })
+    }
+
+    fn invoke_with_args(
+        &self,
+        args: ScalarFunctionArgs,
+    ) -> datafusion::common::Result<ColumnarValue> {
+        let args: [ColumnarValue; 1] = args
+            .args
+            .try_into()
+            .map_err(|_| internal_datafusion_err!("unix_timestamp expects 
exactly one argument"))?;
+
+        match args {
+            [ColumnarValue::Array(array)] => match array.data_type() {
+                DataType::Timestamp(_, _) => {
+                    let is_utc = self.timezone == "UTC";
+                    let array = if is_utc
+                        && matches!(array.data_type(), 
DataType::Timestamp(Microsecond, Some(tz)) if tz.as_ref() == "UTC")
+                    {
+                        array
+                    } else {
+                        array_with_timezone(
+                            array,
+                            self.timezone.clone(),
+                            Some(&DataType::Timestamp(Microsecond, 
Some("UTC".into()))),
+                        )?
+                    };
+
+                    let timestamp_array =
+                        
array.as_primitive::<arrow::datatypes::TimestampMicrosecondType>();
+
+                    let result: PrimitiveArray<Int64Type> = if 
timestamp_array.null_count() == 0 {
+                        timestamp_array
+                            .values()
+                            .iter()
+                            .map(|&micros| micros / MICROS_PER_SECOND)
+                            .collect()
+                    } else {
+                        timestamp_array
+                            .iter()
+                            .map(|v| v.map(|micros| div_floor(micros, 
MICROS_PER_SECOND)))
+                            .collect()
+                    };
+
+                    Ok(ColumnarValue::Array(Arc::new(result)))
+                }
+                DataType::Date32 => {
+                    let timestamp_array = cast(&array, 
&DataType::Timestamp(Microsecond, None))?;
+
+                    let is_utc = self.timezone == "UTC";
+                    let array = if is_utc {
+                        timestamp_array
+                    } else {
+                        array_with_timezone(
+                            timestamp_array,
+                            self.timezone.clone(),
+                            Some(&DataType::Timestamp(Microsecond, 
Some("UTC".into()))),
+                        )?
+                    };
+
+                    let timestamp_array =
+                        
array.as_primitive::<arrow::datatypes::TimestampMicrosecondType>();
+
+                    let result: PrimitiveArray<Int64Type> = if 
timestamp_array.null_count() == 0 {
+                        timestamp_array
+                            .values()
+                            .iter()
+                            .map(|&micros| micros / MICROS_PER_SECOND)
+                            .collect()
+                    } else {
+                        timestamp_array
+                            .iter()
+                            .map(|v| v.map(|micros| div_floor(micros, 
MICROS_PER_SECOND)))
+                            .collect()
+                    };
+
+                    Ok(ColumnarValue::Array(Arc::new(result)))
+                }
+                _ => Err(DataFusionError::Execution(format!(

Review Comment:
   I've added explicit type checking to `getSupportLevel()` - only 
`TimestampType` and `DateType` are supported. String inputs (with or without 
format) correctly fall back to Spark. I've added tests to verify this behavior.
   
   String parsing with format support would be a good follow-up enhancement.



-- 
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