parthchandra commented on code in PR #2936: URL: https://github.com/apache/datafusion-comet/pull/2936#discussion_r2674278849
########## 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: Input could be Timestamp with no timezone. Do you need to handle that differently? ########## native/proto/src/proto/expr.proto: ########## @@ -85,7 +85,8 @@ message Expr { Rand randn = 62; EmptyExpr spark_partition_id = 63; EmptyExpr monotonically_increasing_id = 64; - FromJson from_json = 89; + UnixTimestamp unix_timestamp = 65; + FromJson from_json = 66; Review Comment: I believe it is bad form to renumber protobuf fields. ########## 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(|µs| 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(|µs| 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 believe input to unix_timestamp could be a string (and an optional format) https://spark.apache.org/docs/latest/api/sql/index.html#unix_timestamp -- 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]
