forked from apache/datafusion-comet
-
Notifications
You must be signed in to change notification settings - Fork 0
3559: feat: Cast numeric (non int) to timestamp #44
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
martin-augment
wants to merge
10
commits into
main
Choose a base branch
from
pr-3559-2026-03-06-12-45-07
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
10 commits
Select commit
Hold shift + click to select a range
b9b0ad4
float_to_timestamp
coderfender b41a43a
non_numeric_to_timestamp
coderfender 55cae7f
fix_bool_to_timestamp_support
coderfender e64e194
fix_bool_to_timestamp_support
coderfender 3f3dd19
fix_ansi_support_when_non_using_collect
coderfender ac46828
TEST_SPARK_EXPRESSION_REFACTOR
coderfender 9bb2ea4
Merge branch 'main' into cast_float_to_timestamp
coderfender e593089
rebase_main
coderfender 61bbada
fix_review_comments
coderfender 44783c5
Merge branch 'main' into cast_float_to_timestamp
coderfender 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
143 changes: 143 additions & 0 deletions
143
native/spark-expr/benches/cast_non_int_numeric_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,143 @@ | ||
| // 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::builder::{BooleanBuilder, Decimal128Builder, Float32Builder, Float64Builder}; | ||
| use arrow::array::RecordBatch; | ||
| use arrow::datatypes::{DataType, Field, Schema, TimeUnit}; | ||
| use criterion::{criterion_group, criterion_main, Criterion}; | ||
| use datafusion::physical_expr::{expressions::Column, PhysicalExpr}; | ||
| use datafusion_comet_spark_expr::{Cast, EvalMode, SparkCastOptions}; | ||
| use std::sync::Arc; | ||
|
|
||
| const BATCH_SIZE: usize = 8192; | ||
|
|
||
| fn criterion_benchmark(c: &mut Criterion) { | ||
| let spark_cast_options = SparkCastOptions::new(EvalMode::Legacy, "UTC", false); | ||
| let timestamp_type = DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())); | ||
|
|
||
| let mut group = c.benchmark_group("cast_non_int_numeric_to_timestamp"); | ||
|
|
||
| // Float32 -> Timestamp | ||
| let batch_f32 = create_float32_batch(); | ||
| let expr_f32 = Arc::new(Column::new("a", 0)); | ||
| let cast_f32_to_ts = Cast::new(expr_f32, timestamp_type.clone(), spark_cast_options.clone()); | ||
| group.bench_function("cast_f32_to_timestamp", |b| { | ||
| b.iter(|| cast_f32_to_ts.evaluate(&batch_f32).unwrap()); | ||
| }); | ||
|
|
||
| // Float64 -> Timestamp | ||
| let batch_f64 = create_float64_batch(); | ||
| let expr_f64 = Arc::new(Column::new("a", 0)); | ||
| let cast_f64_to_ts = Cast::new(expr_f64, timestamp_type.clone(), spark_cast_options.clone()); | ||
| group.bench_function("cast_f64_to_timestamp", |b| { | ||
| b.iter(|| cast_f64_to_ts.evaluate(&batch_f64).unwrap()); | ||
| }); | ||
|
|
||
| // Boolean -> Timestamp | ||
| let batch_bool = create_boolean_batch(); | ||
| let expr_bool = Arc::new(Column::new("a", 0)); | ||
| let cast_bool_to_ts = Cast::new( | ||
| expr_bool, | ||
| timestamp_type.clone(), | ||
| spark_cast_options.clone(), | ||
| ); | ||
| group.bench_function("cast_bool_to_timestamp", |b| { | ||
| b.iter(|| cast_bool_to_ts.evaluate(&batch_bool).unwrap()); | ||
| }); | ||
|
|
||
| // Decimal128 -> Timestamp | ||
| let batch_decimal = create_decimal128_batch(); | ||
| let expr_decimal = Arc::new(Column::new("a", 0)); | ||
| let cast_decimal_to_ts = Cast::new( | ||
| expr_decimal, | ||
| timestamp_type.clone(), | ||
| spark_cast_options.clone(), | ||
| ); | ||
| group.bench_function("cast_decimal_to_timestamp", |b| { | ||
| b.iter(|| cast_decimal_to_ts.evaluate(&batch_decimal).unwrap()); | ||
| }); | ||
|
|
||
| group.finish(); | ||
| } | ||
|
|
||
| fn create_float32_batch() -> RecordBatch { | ||
| let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Float32, true)])); | ||
| let mut b = Float32Builder::with_capacity(BATCH_SIZE); | ||
| for i in 0..BATCH_SIZE { | ||
| if i % 10 == 0 { | ||
| b.append_null(); | ||
| } else { | ||
| b.append_value(rand::random::<f32>()); | ||
| } | ||
| } | ||
| RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap() | ||
| } | ||
|
|
||
| fn create_float64_batch() -> RecordBatch { | ||
| let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)])); | ||
| let mut b = Float64Builder::with_capacity(BATCH_SIZE); | ||
| for i in 0..BATCH_SIZE { | ||
| if i % 10 == 0 { | ||
| b.append_null(); | ||
| } else { | ||
| b.append_value(rand::random::<f64>()); | ||
| } | ||
| } | ||
| RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap() | ||
| } | ||
|
|
||
| fn create_boolean_batch() -> RecordBatch { | ||
| let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, true)])); | ||
| let mut b = BooleanBuilder::with_capacity(BATCH_SIZE); | ||
| for i in 0..BATCH_SIZE { | ||
| if i % 10 == 0 { | ||
| b.append_null(); | ||
| } else { | ||
| b.append_value(rand::random::<bool>()); | ||
| } | ||
| } | ||
| RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap() | ||
| } | ||
|
|
||
| fn create_decimal128_batch() -> RecordBatch { | ||
| let schema = Arc::new(Schema::new(vec![Field::new( | ||
| "a", | ||
| DataType::Decimal128(18, 6), | ||
| true, | ||
| )])); | ||
| let mut b = Decimal128Builder::with_capacity(BATCH_SIZE); | ||
| for i in 0..BATCH_SIZE { | ||
| if i % 10 == 0 { | ||
| b.append_null(); | ||
| } else { | ||
| b.append_value(i as i128 * 1_000_000); | ||
| } | ||
| } | ||
| let array = b.finish().with_precision_and_scale(18, 6).unwrap(); | ||
| RecordBatch::try_new(schema, vec![Arc::new(array)]).unwrap() | ||
| } | ||
|
|
||
| fn config() -> Criterion { | ||
| Criterion::default() | ||
| } | ||
|
|
||
| criterion_group! { | ||
| name = benches; | ||
| config = config(); | ||
| targets = criterion_benchmark | ||
| } | ||
| criterion_main!(benches); |
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,7 +16,7 @@ | |
| // under the License. | ||
|
|
||
| use crate::SparkResult; | ||
| use arrow::array::{ArrayRef, AsArray, Decimal128Array}; | ||
| use arrow::array::{Array, ArrayRef, AsArray, Decimal128Array, TimestampMicrosecondBuilder}; | ||
| use arrow::datatypes::DataType; | ||
| use std::sync::Arc; | ||
|
|
||
|
|
@@ -28,7 +28,6 @@ pub fn is_df_cast_from_bool_spark_compatible(to_type: &DataType) -> bool { | |
| ) | ||
| } | ||
|
|
||
| // only DF incompatible boolean cast | ||
| pub fn cast_boolean_to_decimal( | ||
| array: &ArrayRef, | ||
| precision: u8, | ||
|
|
@@ -43,6 +42,25 @@ pub fn cast_boolean_to_decimal( | |
| Ok(Arc::new(result.with_precision_and_scale(precision, scale)?)) | ||
| } | ||
|
|
||
| pub(crate) fn cast_boolean_to_timestamp( | ||
| array_ref: &ArrayRef, | ||
| target_tz: &Option<Arc<str>>, | ||
| ) -> SparkResult<ArrayRef> { | ||
| let bool_array = array_ref.as_boolean(); | ||
| let mut builder = TimestampMicrosecondBuilder::with_capacity(bool_array.len()); | ||
|
|
||
| for i in 0..bool_array.len() { | ||
| if bool_array.is_null(i) { | ||
| builder.append_null(); | ||
| } else { | ||
| let micros = if bool_array.value(i) { 1 } else { 0 }; | ||
| builder.append_value(micros); | ||
| } | ||
| } | ||
|
|
||
| Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef) | ||
| } | ||
|
Comment on lines
+45
to
+62
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. The implementation of pub(crate) fn cast_boolean_to_timestamp(
array_ref: &ArrayRef,
target_tz: &Option<Arc<str>>,
) -> SparkResult<ArrayRef> {
let bool_array = array_ref.as_boolean();
let result: arrow::array::TimestampMicrosecondArray = bool_array
.iter()
.map(|v| v.map(|b| if b { 1 } else { 0 }))
.collect();
Ok(Arc::new(result.with_timezone_opt(target_tz.clone())) as ArrayRef)
} |
||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
@@ -53,6 +71,7 @@ mod tests { | |
| Int64Array, Int8Array, StringArray, | ||
| }; | ||
| use arrow::datatypes::DataType::Decimal128; | ||
| use arrow::datatypes::TimestampMicrosecondType; | ||
| use std::sync::Arc; | ||
|
|
||
| fn test_input_bool_array() -> ArrayRef { | ||
|
|
@@ -193,4 +212,26 @@ mod tests { | |
| assert_eq!(arr.value(1), expected_arr.value(1)); | ||
| assert!(arr.is_null(2)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_cast_boolean_to_timestamp() { | ||
| let timezones: [Option<Arc<str>>; 3] = [ | ||
| Some(Arc::from("UTC")), | ||
| Some(Arc::from("America/Los_Angeles")), | ||
| None, | ||
| ]; | ||
|
|
||
| for tz in &timezones { | ||
| let bool_array: ArrayRef = | ||
| Arc::new(BooleanArray::from(vec![Some(true), Some(false), None])); | ||
|
|
||
| let result = cast_boolean_to_timestamp(&bool_array, tz).unwrap(); | ||
| let ts_array = result.as_primitive::<TimestampMicrosecondType>(); | ||
|
|
||
| assert_eq!(ts_array.value(0), 1); // true -> 1 microsecond | ||
| assert_eq!(ts_array.value(1), 0); // false -> 0 (epoch) | ||
| assert!(ts_array.is_null(2)); | ||
| assert_eq!(ts_array.timezone(), tz.as_ref().map(|s| s.as_ref())); | ||
| } | ||
| } | ||
| } | ||
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
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.
Boolean-to-timestamp maps true to 1µs instead of 1s
High Severity
cast_boolean_to_timestampmapstrueto1(1 microsecond) instead ofMICROS_PER_SECOND(1,000,000 = 1 second). In Spark, boolean-to-timestamp works by convertingtrue→1(second) →1_000_000microseconds. The existingcast_int_to_timestamp_implmacro confirms integers are treated as seconds and multiplied byMICROS_PER_SECOND. The result is thattrueproduces1970-01-01 00:00:00.000001instead of the correct1970-01-01 00:00:01. The unit test also encodes this wrong expectation.Additional Locations (1)
native/spark-expr/src/conversion_funcs/boolean.rs#L230-L231