-
Notifications
You must be signed in to change notification settings - Fork 341
feat: extract TimeType to int/decimal #4997
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
YutaLin
wants to merge
5
commits into
apache:main
Choose a base branch
from
YutaLin:4983_TimeType_to_Int_Decimal
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
5 commits
Select commit
Hold shift + click to select a range
fd81b73
feat: extract hour from TimeType
YutaLin f64058e
feat: extract minute/second from TimeType
YutaLin 1203371
refactor: consolidate TimeType extraction serde
YutaLin 7b04896
feat: extract fractional seconds from TimeType
YutaLin c6c2e51
Merge remote-tracking branch 'upstream/main' into 4983_TimeType_to_In…
YutaLin 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,13 +16,21 @@ | |
| // under the License. | ||
|
|
||
| use crate::utils::array_with_timezone; | ||
| use arrow::array::{Array, Decimal128Builder, Int32Array, Time64NanosecondArray}; | ||
| use arrow::compute::{date_part, DatePart}; | ||
| use arrow::datatypes::{DataType, TimeUnit::Microsecond}; | ||
| use datafusion::common::{internal_datafusion_err, DataFusionError}; | ||
| use datafusion::common::{ | ||
| internal_datafusion_err, utils::take_function_args, DataFusionError, Result, | ||
| }; | ||
| use datafusion::logical_expr::{ | ||
| ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, | ||
| }; | ||
| use std::fmt::Debug; | ||
| use std::{fmt::Debug, sync::Arc}; | ||
|
|
||
| const NANOS_PER_SECOND: i64 = 1_000_000_000; | ||
| const MICROS_PER_SECOND: i128 = 1_000_000; | ||
| const SECOND_DECIMAL_PRECISION: u8 = 8; | ||
| const SECOND_DECIMAL_SCALE: i8 = 6; | ||
|
|
||
| /// Returns true when the type is a timestamp without a timezone (Spark's TimestampNTZType), | ||
| /// including when wrapped in a dictionary. Such values store local wall-clock time and must not | ||
|
|
@@ -117,10 +125,113 @@ extract_date_part!(SparkHour, "hour", Hour); | |
| extract_date_part!(SparkMinute, "minute", Minute); | ||
| extract_date_part!(SparkSecond, "second", Second); | ||
|
|
||
| fn second_with_fraction(nanos: i64, precision: i32) -> Result<i128> { | ||
| if !(0..=SECOND_DECIMAL_SCALE as i32).contains(&precision) { | ||
| return Err(DataFusionError::Execution(format!( | ||
| "second_with_fraction: precision must be between 0 and 6, found {precision}" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Defensive suggestion: |
||
| ))); | ||
| } | ||
|
|
||
| let whole_seconds = (nanos / NANOS_PER_SECOND) % 60; | ||
| let fraction_nanos = nanos % NANOS_PER_SECOND; | ||
| let scale_factor: i64 = 10_i64.pow(precision as u32); | ||
| let fraction_digits = (fraction_nanos * scale_factor) / NANOS_PER_SECOND; | ||
| let output_scale_factor = 10_i128.pow((SECOND_DECIMAL_SCALE as i32 - precision) as u32); | ||
| let result = | ||
| whole_seconds as i128 * MICROS_PER_SECOND + fraction_digits as i128 * output_scale_factor; | ||
|
|
||
| Ok(result) | ||
| } | ||
|
|
||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct SparkSecondWithFraction { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl SparkSecondWithFraction { | ||
| pub fn new() -> Self { | ||
| Self { | ||
| signature: Signature::any(2, Volatility::Immutable), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Default for SparkSecondWithFraction { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for SparkSecondWithFraction { | ||
| fn name(&self) -> &str { | ||
| "second_with_fraction" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Decimal128( | ||
| SECOND_DECIMAL_PRECISION, | ||
| SECOND_DECIMAL_SCALE, | ||
| )) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| let [time, precision] = take_function_args(self.name(), args.args)?; | ||
|
|
||
| let num_rows = [&time, &precision] | ||
| .iter() | ||
| .find_map(|arg| match arg { | ||
| ColumnarValue::Array(array) => Some(array.len()), | ||
| ColumnarValue::Scalar(_) => None, | ||
| }) | ||
| .unwrap_or(1); | ||
|
|
||
| let time = time.into_array(num_rows)?; | ||
| let precision = precision.into_array(num_rows)?; | ||
| let time = time | ||
| .as_any() | ||
| .downcast_ref::<Time64NanosecondArray>() | ||
| .ok_or_else(|| { | ||
| DataFusionError::Execution( | ||
| "second_with_fraction: expected Time64(Nanosecond) input".to_string(), | ||
| ) | ||
| })?; | ||
| let precision = precision | ||
| .as_any() | ||
| .downcast_ref::<Int32Array>() | ||
| .ok_or_else(|| { | ||
| DataFusionError::Execution( | ||
| "second_with_fraction: expected Int32 precision".to_string(), | ||
| ) | ||
| })?; | ||
|
|
||
| let mut result = Decimal128Builder::with_capacity(num_rows); | ||
|
|
||
| for index in 0..num_rows { | ||
| if time.is_null(index) || precision.is_null(index) { | ||
| result.append_null(); | ||
| } else { | ||
| let value = second_with_fraction(time.value(index), precision.value(index))?; | ||
|
|
||
| result.append_value(value); | ||
| } | ||
| } | ||
|
|
||
| let result = result | ||
| .with_precision_and_scale(SECOND_DECIMAL_PRECISION, SECOND_DECIMAL_SCALE)? | ||
| .finish(); | ||
|
|
||
| Ok(ColumnarValue::Array(Arc::new(result))) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use arrow::array::{ArrayRef, Int32Array, TimestampMicrosecondArray}; | ||
| use arrow::array::{ArrayRef, Int32Array, Time64NanosecondArray, TimestampMicrosecondArray}; | ||
| use arrow::datatypes::{Field, TimeUnit}; | ||
| use datafusion::config::ConfigOptions; | ||
| use std::sync::Arc; | ||
|
|
@@ -256,4 +367,34 @@ mod tests { | |
| .value(key); | ||
| assert_eq!(extracted, 18); | ||
| } | ||
|
|
||
| #[test] | ||
| fn time64_extracts_time_parts_without_timezone_conversion() { | ||
| let nanos = (12 * 60 * 60 + 30 * 60 + 45) * 1_000_000_000; | ||
| let array = Arc::new(Time64NanosecondArray::from(vec![Some(nanos)])) as ArrayRef; | ||
|
|
||
| for timezone in ["UTC", "America/Los_Angeles", "Asia/Tokyo"] { | ||
| assert_eq!( | ||
| invoke(&SparkHour::new(timezone.to_string()), Arc::clone(&array)), | ||
| 12 | ||
| ); | ||
| assert_eq!( | ||
| invoke(&SparkMinute::new(timezone.to_string()), Arc::clone(&array)), | ||
| 30 | ||
| ); | ||
| assert_eq!( | ||
| invoke(&SparkSecond::new(timezone.to_string()), Arc::clone(&array)), | ||
| 45 | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn time64_extract_seconds_with_fraction() { | ||
| let nanos = (12 * 60 * 60 + 30 * 60 + 45) * NANOS_PER_SECOND + 123_456_000; | ||
|
|
||
| assert_eq!(second_with_fraction(nanos, 0).unwrap(), 45_000_000); | ||
| assert_eq!(second_with_fraction(nanos, 3).unwrap(), 45_123_000); | ||
| assert_eq!(second_with_fraction(nanos, 6).unwrap(), 45_123_456); | ||
| } | ||
| } | ||
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
49 changes: 49 additions & 0 deletions
49
spark/src/test/resources/sql-tests/expressions/datetime/time_extract.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,49 @@ | ||
| -- 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. | ||
|
|
||
| -- MinSparkVersion: 4.1 | ||
| -- Config: spark.sql.timeType.enabled=true | ||
|
|
||
| statement | ||
| CREATE TABLE test_time_extract(hours int, minutes int, secs DECIMAL(16, 6)) USING parquet | ||
|
|
||
| statement | ||
| INSERT INTO test_time_extract VALUES | ||
| (0, 0, 0.000000), | ||
| (12, 30, 45.123456), | ||
| (23, 59, 59.999999), | ||
| (NULL, NULL, NULL) | ||
|
|
||
| query | ||
| SELECT hour(make_time(hours, minutes, secs)) | ||
| FROM test_time_extract | ||
|
|
||
| query | ||
| SELECT minute(make_time(hours, minutes, secs)) | ||
| FROM test_time_extract | ||
|
|
||
| query | ||
| SELECT second(make_time(hours, minutes, secs)) | ||
| FROM test_time_extract | ||
|
|
||
| query | ||
| SELECT extract(SECOND FROM make_time(hours, minutes, secs)) | ||
| FROM test_time_extract | ||
|
|
||
| query | ||
| SELECT date_part('SECOND', make_time(hours, minutes, secs)) | ||
| FROM test_time_extract |
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.
Nit:
MICROS_PER_SECONDis technically correct (1M µs/s) but here it serves as the Decimal(8,6) unscaled-unit factor. A name likeUNSCALED_UNITS_PER_SECONDor just inlining10_i128.pow(SECOND_DECIMAL_SCALE as u32)would make the intent clearer — currently readers have to reason about why "micros" appears in a nanosecond-based function.