-
Notifications
You must be signed in to change notification settings - Fork 304
feat: add support for timestamp_seconds expression #3146
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andygrove
wants to merge
12
commits into
apache:main
Choose a base branch
from
andygrove:feature/seconds-to-timestamp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
7ca1f89
feat: add support for timestamp_seconds expression
andygrove bbfd11e
update docs
andygrove 3a7d8d9
Merge remote-tracking branch 'origin/main' into feature/seconds-to-ti…
andygrove 650b6da
Merge remote-tracking branch 'apache/main' into feature/seconds-to-ti…
andygrove 03fb7a6
test: migrate timestamp_seconds tests to SQL file-based approach
andygrove 3ff2862
upmerge
andygrove b32b3e6
fmt
andygrove c6072e2
chore: merge latest from apache/main
andygrove 1c66349
fix: resolve merge conflicts after merging main
andygrove 1758cfa
fix: address review feedback for timestamp_seconds
andygrove d469b5e
cargo fmt
andygrove 3eda727
Merge remote-tracking branch 'apache/main' into feature/seconds-to-ti…
andygrove File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
192 changes: 192 additions & 0 deletions
192
native/spark-expr/src/datetime_funcs/seconds_to_timestamp.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| // 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::{ | ||
| Array, Float32Array, Float64Array, Int32Array, Int64Array, TimestampMicrosecondArray, | ||
| }; | ||
| use arrow::compute::try_unary; | ||
| use arrow::datatypes::{DataType, TimeUnit}; | ||
| use datafusion::common::{utils::take_function_args, DataFusionError, Result, ScalarValue}; | ||
| use datafusion::logical_expr::{ | ||
| ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility, | ||
| }; | ||
| use std::any::Any; | ||
| use std::sync::Arc; | ||
|
|
||
| const MICROS_PER_SECOND: i64 = 1_000_000; | ||
|
|
||
| /// Spark-compatible seconds_to_timestamp (timestamp_seconds) function. | ||
| /// Converts seconds since Unix epoch to a timestamp. | ||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct SparkSecondsToTimestamp { | ||
| signature: Signature, | ||
| aliases: Vec<String>, | ||
| } | ||
|
|
||
| impl SparkSecondsToTimestamp { | ||
| pub fn new() -> Self { | ||
| Self { | ||
| signature: Signature::one_of( | ||
| vec![ | ||
| TypeSignature::Exact(vec![DataType::Int32]), | ||
| TypeSignature::Exact(vec![DataType::Int64]), | ||
| TypeSignature::Exact(vec![DataType::Float32]), | ||
| TypeSignature::Exact(vec![DataType::Float64]), | ||
| ], | ||
| Volatility::Immutable, | ||
| ), | ||
| aliases: vec!["timestamp_seconds".to_string()], | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Default for SparkSecondsToTimestamp { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for SparkSecondsToTimestamp { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "seconds_to_timestamp" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Timestamp(TimeUnit::Microsecond, None)) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| let [seconds] = take_function_args(self.name(), args.args)?; | ||
|
|
||
| match seconds { | ||
| ColumnarValue::Array(arr) => { | ||
| // Handle Int32 input — no overflow possible since i32 * 1_000_000 fits in i64 | ||
| if let Some(int_array) = arr.as_any().downcast_ref::<Int32Array>() { | ||
| let result: TimestampMicrosecondArray = | ||
| try_unary(int_array, |s| Ok((s as i64) * MICROS_PER_SECOND))?; | ||
| return Ok(ColumnarValue::Array(Arc::new(result))); | ||
| } | ||
|
|
||
| // Handle Int64 input — error on overflow to match Spark's Math.multiplyExact | ||
| if let Some(int_array) = arr.as_any().downcast_ref::<Int64Array>() { | ||
| let result: TimestampMicrosecondArray = try_unary(int_array, |s| { | ||
| s.checked_mul(MICROS_PER_SECOND).ok_or_else(|| { | ||
| arrow::error::ArrowError::ComputeError("long overflow".to_string()) | ||
| }) | ||
| })?; | ||
| return Ok(ColumnarValue::Array(Arc::new(result))); | ||
| } | ||
|
|
||
| // Handle Float32 input — cast to f64 and use Float64 path | ||
| if let Some(float_array) = arr.as_any().downcast_ref::<Float32Array>() { | ||
| let result: arrow::array::TimestampMicrosecondArray = float_array | ||
| .iter() | ||
| .map(|opt| { | ||
| opt.and_then(|s| { | ||
| let s = s as f64; | ||
| if s.is_nan() || s.is_infinite() { | ||
| None | ||
| } else { | ||
| Some((s * (MICROS_PER_SECOND as f64)) as i64) | ||
| } | ||
| }) | ||
| }) | ||
| .collect(); | ||
| return Ok(ColumnarValue::Array(Arc::new(result))); | ||
| } | ||
|
|
||
| // Handle Float64 input — NaN and Infinity return null per Spark behavior | ||
| if let Some(float_array) = arr.as_any().downcast_ref::<Float64Array>() { | ||
| let result: arrow::array::TimestampMicrosecondArray = float_array | ||
| .iter() | ||
| .map(|opt| { | ||
| opt.and_then(|s| { | ||
| if s.is_nan() || s.is_infinite() { | ||
| None | ||
| } else { | ||
| Some((s * (MICROS_PER_SECOND as f64)) as i64) | ||
| } | ||
| }) | ||
| }) | ||
| .collect(); | ||
| return Ok(ColumnarValue::Array(Arc::new(result))); | ||
| } | ||
|
|
||
| Err(DataFusionError::Execution(format!( | ||
| "seconds_to_timestamp expects Int32, Int64, Float32 or Float64 input, got {:?}", | ||
| arr.data_type() | ||
| ))) | ||
| } | ||
| ColumnarValue::Scalar(scalar) => { | ||
| let ts_micros = match &scalar { | ||
| ScalarValue::Int32(Some(s)) => Some((*s as i64) * MICROS_PER_SECOND), | ||
| ScalarValue::Int64(Some(s)) => { | ||
| Some(s.checked_mul(MICROS_PER_SECOND).ok_or_else(|| { | ||
| DataFusionError::ArrowError( | ||
| Box::new(arrow::error::ArrowError::ComputeError( | ||
| "long overflow".to_string(), | ||
| )), | ||
| None, | ||
| ) | ||
| })?) | ||
| } | ||
| ScalarValue::Float32(Some(s)) => { | ||
| let s = *s as f64; | ||
| if s.is_nan() || s.is_infinite() { | ||
| None | ||
| } else { | ||
| Some((s * (MICROS_PER_SECOND as f64)) as i64) | ||
| } | ||
| } | ||
| ScalarValue::Float64(Some(s)) => { | ||
| if s.is_nan() || s.is_infinite() { | ||
| None | ||
| } else { | ||
| Some((s * (MICROS_PER_SECOND as f64)) as i64) | ||
| } | ||
| } | ||
| ScalarValue::Int32(None) | ||
| | ScalarValue::Int64(None) | ||
| | ScalarValue::Float32(None) | ||
| | ScalarValue::Float64(None) | ||
| | ScalarValue::Null => None, | ||
| _ => { | ||
| return Err(DataFusionError::Execution(format!( | ||
| "seconds_to_timestamp expects numeric scalar input, got {:?}", | ||
| scalar.data_type() | ||
| ))) | ||
| } | ||
| }; | ||
| Ok(ColumnarValue::Scalar(ScalarValue::TimestampMicrosecond( | ||
| ts_micros, None, | ||
| ))) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn aliases(&self) -> &[String] { | ||
| &self.aliases | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
80 changes: 80 additions & 0 deletions
80
spark/src/test/resources/sql-tests/expressions/datetime/timestamp_seconds.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| -- 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. | ||
|
|
||
| -- Config: spark.sql.session.timeZone=UTC | ||
| -- ConfigMatrix: parquet.enable.dictionary=false,true | ||
|
|
||
| -- bigint column | ||
| statement | ||
| CREATE TABLE test_ts_seconds_bigint(c0 bigint) USING parquet | ||
|
|
||
| statement | ||
| INSERT INTO test_ts_seconds_bigint VALUES (0), (1640995200), (-86400), (4102444800), (-2208988800), (NULL) | ||
|
|
||
| query | ||
| SELECT c0, timestamp_seconds(c0) FROM test_ts_seconds_bigint | ||
|
|
||
| -- int column | ||
| statement | ||
| CREATE TABLE test_ts_seconds_int(c0 int) USING parquet | ||
|
|
||
| statement | ||
| INSERT INTO test_ts_seconds_int VALUES (0), (1640995200), (-86400), (NULL) | ||
|
|
||
| query | ||
| SELECT c0, timestamp_seconds(c0) FROM test_ts_seconds_int | ||
|
|
||
| -- double column | ||
| statement | ||
| CREATE TABLE test_ts_seconds_double(c0 double) USING parquet | ||
|
|
||
| statement | ||
| INSERT INTO test_ts_seconds_double VALUES (0.0), (1640995200.123), (-86400.5), (NULL) | ||
|
|
||
| query | ||
| SELECT c0, timestamp_seconds(c0) FROM test_ts_seconds_double | ||
|
|
||
| -- literal arguments | ||
| query | ||
| SELECT timestamp_seconds(0) | ||
|
|
||
| query | ||
| SELECT timestamp_seconds(1640995200) | ||
|
|
||
| -- negative value (before epoch) | ||
| query | ||
| SELECT timestamp_seconds(-86400) | ||
|
|
||
| -- decimal seconds (fractional) | ||
| query | ||
| SELECT timestamp_seconds(CAST(1640995200.123 AS DOUBLE)) | ||
|
|
||
| -- null handling | ||
| query | ||
| SELECT timestamp_seconds(NULL) | ||
|
|
||
| -- NaN input (should return null) | ||
| query | ||
| SELECT timestamp_seconds(CAST('NaN' AS DOUBLE)) | ||
|
|
||
| -- Infinity input (should return null) | ||
| query | ||
| SELECT timestamp_seconds(CAST('Infinity' AS DOUBLE)) | ||
|
|
||
| -- Negative infinity input (should return null) | ||
| query | ||
| SELECT timestamp_seconds(CAST('-Infinity' AS DOUBLE)) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can this be byte or short type?
Spark is specifying
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah Matt already pointed out...