You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/20 04:52:09 UTC
(datafusion-comet) branch gh-readonly-queue/main/pr-6969-177fef162a8e8d2eb8d4e4c02f2e9edcecfd046e created (now 99c4873d52)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-6969-177fef162a8e8d2eb8d4e4c02f2e9edcecfd046e
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
at 99c4873d52 perf: vectorize int, decimal, float and boolean casts to timestamp (#6969)
This branch includes the following new commits:
new 99c4873d52 perf: vectorize int, decimal, float and boolean casts to timestamp (#6969)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org
(datafusion-comet) 01/01: perf: vectorize int, decimal, float and boolean casts to timestamp (#6969)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-6969-177fef162a8e8d2eb8d4e4c02f2e9edcecfd046e
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
commit 99c4873d52e47bc466d740b4023e0de7be797e28
Author: Bill <St...@gmail.com>
AuthorDate: Tue Oct 20 02:02:32 2026 +0000
perf: vectorize int, decimal, float and boolean casts to timestamp (#6969)
* test: extend timestamp cast benchmarks
Cover 8192-row batches with no nulls, sparse nulls, dense nulls, and an
all-null batch for the integer, float, decimal, and boolean casts to
timestamp, in legacy and ANSI modes where the mode changes the kernel.
Generated-by: Cursor Grok 4.7
Co-authored-by: Bill <Er...@users.noreply.github.com>
* perf: vectorize numeric and boolean casts to timestamp
Replace the per-element TimestampMicrosecondBuilder loops in
cast_int_to_timestamp, cast_decimal_to_timestamp, cast_float_to_timestamp,
and cast_boolean_to_timestamp with Arrow unary, try_unary, unary_opt,
and from_unary.
Integer and boolean casts are about 5-12x faster. Float casts are
14-35% faster when nulls are rare and several times faster when most
rows are null. Decimal with no nulls is under 10%; denser batches
skip null slots and are faster. No benchmarked shape regressed.
Generated-by: Cursor Grok 4.7
Co-authored-by: Bill <Er...@users.noreply.github.com>
* perf: use one unary kernel for decimal-to-timestamp
Drop the quarter-null dispatch. unary_opt is faster on every measured
decimal shape, including a batch with no nulls. Trim the benches and
edge tests to the shapes and cases the cast perf PRs keep.
Generated-by: Cursor Grok 4.7
Co-authored-by: Bill <Er...@users.noreply.github.com>
* perf: note that timestamp unary kernels run on null slots
`unary` and `from_unary` visit null slots. Say so, and that the
integer and boolean conversions are infallible for any bit pattern.
Float legacy uses `unary_opt`, which skips those slots.
Generated-by: Cursor Grok 4.7
Co-authored-by: Bill <Er...@users.noreply.github.com>
* test: pin null-slot timestamp casts to the builder
Generated-by: Cursor Grok 4.7
Co-authored-by: Bill <Er...@users.noreply.github.com>
* test: close timestamp-cast gaps from review
Generated-by: Cursor Grok 4.7
Co-authored-by: Bill <Er...@users.noreply.github.com>
---------
Co-authored-by: Cursor Agent <cu...@cursor.com>
Co-authored-by: Bill <Er...@users.noreply.github.com>
---
.../expression-audits/conversion_funcs.md | 1 +
native/spark-expr/benches/cast_int_to_timestamp.rs | 180 ++++-----
.../benches/cast_non_int_numeric_timestamp.rs | 306 ++++++++------
native/spark-expr/src/conversion_funcs/boolean.rs | 76 +++-
native/spark-expr/src/conversion_funcs/numeric.rs | 447 ++++++++++++++++-----
native/spark-expr/src/conversion_funcs/utils.rs | 20 +-
6 files changed, 695 insertions(+), 335 deletions(-)
diff --git a/docs/source/contributor-guide/expression-audits/conversion_funcs.md b/docs/source/contributor-guide/expression-audits/conversion_funcs.md
index 0b52c96d01..c5e2f1369f 100644
--- a/docs/source/contributor-guide/expression-audits/conversion_funcs.md
+++ b/docs/source/contributor-guide/expression-audits/conversion_funcs.md
@@ -39,5 +39,6 @@
- Performance (tuned 2026-07-15, PR [#4940](https://github.com/apache/datafusion-comet/pull/4940)): float/double-to-decimal casts (`cast_floating_point_to_decimal128`) now convert in a single vectorized `unary_opt` pass that maps out-of-range values (NaN, infinity, precision overflow) to null, replacing the per-element `Decimal128Builder` loop. ANSI raises via an O(1) null-count check plus a rare element-wise rescan. 15-36% faster with no regression on any shape. Benchmark: `benches/cast [...]
- Performance (tuned 2026-07-15, PR [#4939](https://github.com/apache/datafusion-comet/pull/4939)): integer-to-decimal casts (`cast_int_to_decimal128_internal`) now convert in a single vectorized `unary_opt` pass that maps overflowing values to null, replacing the per-element `Decimal128Builder` loop. ANSI raises via an O(1) null-count check plus a rare element-wise rescan. 28-50% faster with no regression on any shape. Benchmark: `benches/cast_int_to_decimal.rs`.
- Performance (tuned 2026-09-30, PR [#5130](https://github.com/apache/datafusion-comet/pull/5130)): string-to-timestamp and string-to-timestamp_ntz (`timestamp_parser` / `timestamp_ntz_parser`) classify the input shape once with a single byte scan, replacing up to 34 sequential regex `is_match` calls per row (27 for the NTZ variant). The shapes only accept ASCII digits, so the cast no longer runs a regex at all. 40-86% faster (1.7x-6.9x, median 3.0x) across all 118 benchmark cases, none [...]
+- Performance (tuned 2026-10-14, PR [#6969](https://github.com/apache/datafusion-comet/pull/6969)): casts to timestamp from int, decimal, float, and boolean (`cast_int_to_timestamp`, `cast_decimal_to_timestamp`, `cast_float_to_timestamp`, `cast_boolean_to_timestamp`) use Arrow `unary` / `try_unary` / `unary_opt` / `from_unary` instead of a per-row `TimestampMicrosecondBuilder`. Integer casts are about 9-12x faster and boolean casts about 5-7x. Float casts are 14-35% faster with few nulls [...]
[Spark Expression Support]: ../../user-guide/latest/expressions.md
diff --git a/native/spark-expr/benches/cast_int_to_timestamp.rs b/native/spark-expr/benches/cast_int_to_timestamp.rs
index 04a62280d5..6e7367b5f5 100644
--- a/native/spark-expr/benches/cast_int_to_timestamp.rs
+++ b/native/spark-expr/benches/cast_int_to_timestamp.rs
@@ -15,136 +15,102 @@
// specific language governing permissions and limitations
// under the License.
-use arrow::array::builder::{Int16Builder, Int32Builder, Int64Builder, Int8Builder};
-use arrow::array::RecordBatch;
+//! i64 to timestamp. 8192 rows. The narrower integer widths use the same
+//! `unary` kernel. Shapes: no nulls, sparse nulls (1 in 10), dense nulls
+//! (7 in 8), and an all-null batch.
+
+use arrow::array::{Int32Array, Int64Array, RecordBatch};
use arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use criterion::{criterion_group, criterion_main, Criterion};
-use datafusion::physical_expr::{expressions::Column, PhysicalExpr};
+use datafusion::physical_expr::expressions::Column;
+use datafusion::physical_expr::PhysicalExpr;
use datafusion_comet_spark_expr::{Cast, EvalMode, SparkCastOptions};
+use std::hint::black_box;
use std::sync::Arc;
+use std::time::Duration;
const BATCH_SIZE: usize = 8192;
-fn criterion_benchmark(c: &mut Criterion) {
- // Test with UTC timezone
- let spark_cast_options = SparkCastOptions::new(EvalMode::Legacy, "UTC");
- let timestamp_type = DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into()));
-
- let mut group = c.benchmark_group("cast_int_to_timestamp");
-
- // Int8 -> Timestamp
- let batch_i8 = create_int8_batch();
- let expr_i8 = Arc::new(Column::new("a", 0));
- let cast_i8_to_ts = Cast::new(
- expr_i8,
- timestamp_type.clone(),
- spark_cast_options.clone(),
- None,
- None,
- );
- group.bench_function("cast_i8_to_timestamp", |b| {
- b.iter(|| cast_i8_to_ts.evaluate(&batch_i8).unwrap());
- });
-
- // Int16 -> Timestamp
- let batch_i16 = create_int16_batch();
- let expr_i16 = Arc::new(Column::new("a", 0));
- let cast_i16_to_ts = Cast::new(
- expr_i16,
- timestamp_type.clone(),
- spark_cast_options.clone(),
- None,
- None,
- );
- group.bench_function("cast_i16_to_timestamp", |b| {
- b.iter(|| cast_i16_to_ts.evaluate(&batch_i16).unwrap());
- });
+#[derive(Clone, Copy)]
+enum Nulls {
+ None,
+ /// One null in every ten rows.
+ Sparse,
+ /// Seven nulls in every eight rows.
+ Dense,
+ All,
+}
- // Int32 -> Timestamp
- let batch_i32 = create_int32_batch();
- let expr_i32 = Arc::new(Column::new("a", 0));
- let cast_i32_to_ts = Cast::new(
- expr_i32,
- timestamp_type.clone(),
- spark_cast_options.clone(),
- None,
- None,
- );
- group.bench_function("cast_i32_to_timestamp", |b| {
- b.iter(|| cast_i32_to_ts.evaluate(&batch_i32).unwrap());
- });
+fn is_null(i: usize, nulls: Nulls) -> bool {
+ match nulls {
+ Nulls::None => false,
+ Nulls::Sparse => i.is_multiple_of(10),
+ Nulls::Dense => !i.is_multiple_of(8),
+ Nulls::All => true,
+ }
+}
- // Int64 -> Timestamp
- let batch_i64 = create_int64_batch();
- let expr_i64 = Arc::new(Column::new("a", 0));
- let cast_i64_to_ts = Cast::new(
- expr_i64,
- timestamp_type.clone(),
- spark_cast_options.clone(),
+fn timestamp_cast() -> Cast {
+ Cast::new(
+ Arc::new(Column::new("a", 0)),
+ DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())),
+ SparkCastOptions::new(EvalMode::Legacy, "UTC"),
None,
None,
- );
- group.bench_function("cast_i64_to_timestamp", |b| {
- b.iter(|| cast_i64_to_ts.evaluate(&batch_i64).unwrap());
- });
-
- group.finish();
+ )
}
-fn create_int8_batch() -> RecordBatch {
- let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int8, true)]));
- let mut b = Int8Builder::with_capacity(BATCH_SIZE);
- for i in 0..BATCH_SIZE {
- if i % 10 == 0 {
- b.append_null();
- } else {
- b.append_value(rand::random::<i8>());
- }
- }
- RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap()
+fn batch_i32() -> RecordBatch {
+ let values: Int32Array = (0..BATCH_SIZE)
+ .map(|i| Some(1_600_000_000 + i as i32))
+ .collect();
+ record_batch(DataType::Int32, Arc::new(values))
}
-fn create_int16_batch() -> RecordBatch {
- let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int16, true)]));
- let mut b = Int16Builder::with_capacity(BATCH_SIZE);
- for i in 0..BATCH_SIZE {
- if i % 10 == 0 {
- b.append_null();
- } else {
- b.append_value(rand::random::<i16>());
- }
- }
- RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap()
+fn batch_i64(nulls: Nulls) -> RecordBatch {
+ let values: Int64Array = (0..BATCH_SIZE)
+ .map(|i| {
+ if is_null(i, nulls) {
+ None
+ } else {
+ Some(1_600_000_000 + i as i64)
+ }
+ })
+ .collect();
+ record_batch(DataType::Int64, Arc::new(values))
}
-fn create_int32_batch() -> RecordBatch {
- let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));
- let mut b = Int32Builder::with_capacity(BATCH_SIZE);
- for i in 0..BATCH_SIZE {
- if i % 10 == 0 {
- b.append_null();
- } else {
- b.append_value(rand::random::<i32>());
- }
- }
- RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap()
+fn record_batch(dtype: DataType, column: arrow::array::ArrayRef) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("a", dtype, true)]));
+ RecordBatch::try_new(schema, vec![column]).unwrap()
}
-fn create_int64_batch() -> RecordBatch {
- let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, true)]));
- let mut b = Int64Builder::with_capacity(BATCH_SIZE);
- for i in 0..BATCH_SIZE {
- if i % 10 == 0 {
- b.append_null();
- } else {
- b.append_value(rand::random::<i64>());
- }
- }
- RecordBatch::try_new(schema, vec![Arc::new(b.finish())]).unwrap()
+fn criterion_benchmark(c: &mut Criterion) {
+ let cast = timestamp_cast();
+ let mut bench = |name: &str, batch: RecordBatch| {
+ c.bench_function(name, |b| {
+ b.iter(|| black_box(cast.evaluate(black_box(&batch)).unwrap()))
+ });
+ };
+
+ bench("cast_i32_to_timestamp: no nulls", batch_i32());
+ bench("cast_i64_to_timestamp: no nulls", batch_i64(Nulls::None));
+ bench(
+ "cast_i64_to_timestamp: sparse nulls",
+ batch_i64(Nulls::Sparse),
+ );
+ bench(
+ "cast_i64_to_timestamp: dense nulls",
+ batch_i64(Nulls::Dense),
+ );
+ bench("cast_i64_to_timestamp: all nulls", batch_i64(Nulls::All));
}
fn config() -> Criterion {
Criterion::default()
+ .warm_up_time(Duration::from_secs(1))
+ .measurement_time(Duration::from_secs(2))
+ .sample_size(50)
}
criterion_group! {
diff --git a/native/spark-expr/benches/cast_non_int_numeric_timestamp.rs b/native/spark-expr/benches/cast_non_int_numeric_timestamp.rs
index 9c071aae4b..e9b1bbef0d 100644
--- a/native/spark-expr/benches/cast_non_int_numeric_timestamp.rs
+++ b/native/spark-expr/benches/cast_non_int_numeric_timestamp.rs
@@ -15,140 +15,222 @@
// specific language governing permissions and limitations
// under the License.
-use arrow::array::builder::{BooleanBuilder, Decimal128Builder, Float32Builder, Float64Builder};
-use arrow::array::RecordBatch;
+//! f64, decimal, and boolean casts to timestamp. 8192 rows. f32 uses the same
+//! kernel as f64. Shapes: no nulls, sparse nulls (1 in 10), dense nulls (7 in 8).
+//! Float covers legacy and ANSI, plus a legacy batch of NaN and infinities.
+
+use arrow::array::{
+ ArrayRef, BooleanArray, Decimal128Array, Float32Array, Float64Array, RecordBatch,
+};
use arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use criterion::{criterion_group, criterion_main, Criterion};
-use datafusion::physical_expr::{expressions::Column, PhysicalExpr};
+use datafusion::physical_expr::expressions::Column;
+use datafusion::physical_expr::PhysicalExpr;
use datafusion_comet_spark_expr::{Cast, EvalMode, SparkCastOptions};
+use std::hint::black_box;
use std::sync::Arc;
+use std::time::Duration;
const BATCH_SIZE: usize = 8192;
-fn criterion_benchmark(c: &mut Criterion) {
- let spark_cast_options = SparkCastOptions::new(EvalMode::Legacy, "UTC");
- 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(),
- None,
- None,
- );
- 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(),
- None,
- None,
- );
- 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(),
- None,
- None,
- );
- 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(),
+#[derive(Clone, Copy)]
+enum Nulls {
+ None,
+ Sparse,
+ Dense,
+ All,
+}
+
+fn is_null(i: usize, nulls: Nulls) -> bool {
+ match nulls {
+ Nulls::None => false,
+ Nulls::Sparse => i.is_multiple_of(10),
+ Nulls::Dense => !i.is_multiple_of(8),
+ Nulls::All => true,
+ }
+}
+
+fn timestamp_cast(mode: EvalMode) -> Cast {
+ Cast::new(
+ Arc::new(Column::new("a", 0)),
+ DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())),
+ SparkCastOptions::new(mode, "UTC"),
None,
None,
- );
- group.bench_function("cast_decimal_to_timestamp", |b| {
- b.iter(|| cast_decimal_to_ts.evaluate(&batch_decimal).unwrap());
- });
+ )
+}
- group.finish();
+fn record_batch(dtype: DataType, column: ArrayRef) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("a", dtype, true)]));
+ RecordBatch::try_new(schema, vec![column]).unwrap()
}
-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 batch_f64(nulls: Nulls, non_finite: bool) -> RecordBatch {
+ let values: Float64Array = (0..BATCH_SIZE)
+ .map(|i| {
+ if is_null(i, nulls) {
+ None
+ } else if non_finite && i.is_multiple_of(16) {
+ Some(f64::NAN)
+ } else if non_finite && i % 16 == 1 {
+ Some(f64::INFINITY)
+ } else if non_finite && i % 16 == 2 {
+ Some(f64::NEG_INFINITY)
+ } else {
+ // Fractional seconds, all inside the i64 microsecond range.
+ Some((i as f64) * 0.5 - 100.0)
+ }
+ })
+ .collect();
+ record_batch(DataType::Float64, Arc::new(values))
}
-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 batch_f32() -> RecordBatch {
+ let values: Float32Array = (0..BATCH_SIZE)
+ .map(|i| Some((i as f32) * 0.5 - 100.0))
+ .collect();
+ record_batch(DataType::Float32, Arc::new(values))
}
-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 batch_bool(nulls: Nulls) -> RecordBatch {
+ let values: BooleanArray = (0..BATCH_SIZE)
+ .map(|i| {
+ if is_null(i, nulls) {
+ None
+ } else {
+ Some(i.is_multiple_of(2))
+ }
+ })
+ .collect();
+ record_batch(DataType::Boolean, Arc::new(values))
}
-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 batch_decimal(scale: i8, nulls: Nulls) -> RecordBatch {
+ let factor = 10_i128.pow(scale as u32);
+ // Unscaled values of a few thousand at this scale: small enough that
+ // value * 1_000_000 fits in i128 for every scale we bench.
+ let values: Decimal128Array = (0..BATCH_SIZE)
+ .map(|i| {
+ if is_null(i, nulls) {
+ None
+ } else {
+ Some((i as i128 - 100) * factor / 2)
+ }
+ })
+ .collect();
+ let array = values.with_precision_and_scale(38, scale).unwrap();
+ record_batch(DataType::Decimal128(38, scale), Arc::new(array))
+}
+
+fn criterion_benchmark(c: &mut Criterion) {
+ let legacy = timestamp_cast(EvalMode::Legacy);
+ let ansi = timestamp_cast(EvalMode::Ansi);
+
+ let mut bench = |name: &str, cast: &Cast, batch: RecordBatch| {
+ c.bench_function(name, |b| {
+ b.iter(|| black_box(cast.evaluate(black_box(&batch)).unwrap()))
+ });
+ };
+
+ bench(
+ "cast_f32_to_timestamp: legacy, no nulls",
+ &legacy,
+ batch_f32(),
+ );
+ bench(
+ "cast_f64_to_timestamp: legacy, no nulls",
+ &legacy,
+ batch_f64(Nulls::None, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: legacy, sparse nulls",
+ &legacy,
+ batch_f64(Nulls::Sparse, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: legacy, dense nulls",
+ &legacy,
+ batch_f64(Nulls::Dense, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: legacy, all nulls",
+ &legacy,
+ batch_f64(Nulls::All, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: legacy, nan and inf",
+ &legacy,
+ batch_f64(Nulls::None, true),
+ );
+
+ bench(
+ "cast_f64_to_timestamp: ansi, no nulls",
+ &ansi,
+ batch_f64(Nulls::None, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: ansi, sparse nulls",
+ &ansi,
+ batch_f64(Nulls::Sparse, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: ansi, dense nulls",
+ &ansi,
+ batch_f64(Nulls::Dense, false),
+ );
+ bench(
+ "cast_f64_to_timestamp: ansi, all nulls",
+ &ansi,
+ batch_f64(Nulls::All, false),
+ );
+
+ bench(
+ "cast_decimal_to_timestamp: scale 6, no nulls",
+ &legacy,
+ batch_decimal(6, Nulls::None),
+ );
+ bench(
+ "cast_decimal_to_timestamp: scale 6, sparse nulls",
+ &legacy,
+ batch_decimal(6, Nulls::Sparse),
+ );
+ bench(
+ "cast_decimal_to_timestamp: scale 6, dense nulls",
+ &legacy,
+ batch_decimal(6, Nulls::Dense),
+ );
+ bench(
+ "cast_decimal_to_timestamp: scale 6, all nulls",
+ &legacy,
+ batch_decimal(6, Nulls::All),
+ );
+ bench(
+ "cast_bool_to_timestamp: no nulls",
+ &legacy,
+ batch_bool(Nulls::None),
+ );
+ bench(
+ "cast_bool_to_timestamp: sparse nulls",
+ &legacy,
+ batch_bool(Nulls::Sparse),
+ );
+ bench(
+ "cast_bool_to_timestamp: dense nulls",
+ &legacy,
+ batch_bool(Nulls::Dense),
+ );
+ bench(
+ "cast_bool_to_timestamp: all nulls",
+ &legacy,
+ batch_bool(Nulls::All),
+ );
}
fn config() -> Criterion {
Criterion::default()
+ .warm_up_time(Duration::from_secs(1))
+ .measurement_time(Duration::from_secs(2))
+ .sample_size(50)
}
criterion_group! {
diff --git a/native/spark-expr/src/conversion_funcs/boolean.rs b/native/spark-expr/src/conversion_funcs/boolean.rs
index 7e9dffd330..c1fef4238c 100644
--- a/native/spark-expr/src/conversion_funcs/boolean.rs
+++ b/native/spark-expr/src/conversion_funcs/boolean.rs
@@ -15,9 +15,10 @@
// specific language governing permissions and limitations
// under the License.
+use crate::conversion_funcs::utils::timestamp_micros_with_tz;
use crate::SparkResult;
-use arrow::array::{Array, ArrayRef, AsArray, TimestampMicrosecondBuilder};
-use arrow::datatypes::DataType;
+use arrow::array::{ArrayRef, AsArray, PrimitiveArray};
+use arrow::datatypes::{DataType, TimestampMicrosecondType};
use std::sync::Arc;
/// Boolean -> Decimal is intentionally absent: it has no native path and is routed through the
@@ -35,18 +36,11 @@ pub(crate) fn cast_boolean_to_timestamp(
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)
+ // true is 1 microsecond and false is 0.
+ let micros = PrimitiveArray::<TimestampMicrosecondType>::from_unary(bool_array, |value| {
+ i64::from(value)
+ });
+ Ok(timestamp_micros_with_tz(micros, target_tz))
}
#[cfg(test)]
@@ -56,10 +50,11 @@ mod tests {
use crate::{EvalMode, SparkCastOptions};
use arrow::array::{
Array, ArrayRef, BooleanArray, Float32Array, Float64Array, Int16Array, Int32Array,
- Int64Array, Int8Array, StringArray,
+ Int64Array, Int8Array, StringArray, TimestampMicrosecondBuilder,
};
- use arrow::datatypes::DataType::Decimal128;
- use arrow::datatypes::TimestampMicrosecondType;
+ use arrow::buffer::NullBuffer;
+ use arrow::datatypes::DataType::{Decimal128, Timestamp};
+ use arrow::datatypes::{TimeUnit, TimestampMicrosecondType};
use std::sync::Arc;
fn test_input_bool_array() -> ArrayRef {
@@ -222,4 +217,51 @@ mod tests {
assert_eq!(ts_array.timezone(), tz.as_ref().map(|s| s.as_ref()));
}
}
+
+ #[test]
+ fn test_cast_boolean_to_timestamp_edges() {
+ let all_true: ArrayRef = Arc::new(BooleanArray::from(vec![true, true]));
+ let out = cast_boolean_to_timestamp(&all_true, &None).unwrap();
+ let ts = out.as_primitive::<TimestampMicrosecondType>();
+ assert_eq!(ts.values().as_ref(), &[1, 1]);
+ assert!(ts.nulls().is_none());
+ }
+
+ #[test]
+ fn test_cast_boolean_to_timestamp_null_slot_matches_builder() {
+ let tz = Some(Arc::from("UTC"));
+ // The slice starts on a null whose bit is set.
+ let bits = BooleanArray::from(vec![false, true, false, true]);
+ let masked = BooleanArray::new(
+ bits.values().clone(),
+ Some(NullBuffer::from(vec![true, false, true, false])),
+ );
+ let input = Array::slice(&masked, 1, 3);
+ let bools = input.as_boolean();
+ let mut builder = TimestampMicrosecondBuilder::with_capacity(bools.len());
+ for i in 0..bools.len() {
+ if bools.is_null(i) {
+ builder.append_null();
+ } else {
+ builder.append_value(i64::from(bools.value(i)));
+ }
+ }
+ let expected = builder.finish().with_timezone_opt(tz.clone());
+
+ let out = cast_array(
+ Arc::clone(&input),
+ &Timestamp(TimeUnit::Microsecond, tz),
+ &SparkCastOptions::new(EvalMode::Ansi, "UTC"),
+ )
+ .unwrap();
+ let actual = out.as_primitive::<TimestampMicrosecondType>();
+ assert_eq!(actual.len(), expected.len());
+ assert_eq!(actual.timezone(), expected.timezone());
+ for i in 0..actual.len() {
+ assert_eq!(actual.is_null(i), expected.is_null(i), "index {i}");
+ if actual.is_valid(i) {
+ assert_eq!(actual.value(i), expected.value(i), "index {i}");
+ }
+ }
+ }
}
diff --git a/native/spark-expr/src/conversion_funcs/numeric.rs b/native/spark-expr/src/conversion_funcs/numeric.rs
index d78afe5444..9a9a7bf915 100644
--- a/native/spark-expr/src/conversion_funcs/numeric.rs
+++ b/native/spark-expr/src/conversion_funcs/numeric.rs
@@ -17,18 +17,19 @@
use crate::conversion_funcs::string::{digits_to_i128, div_round_half_up_i128, pow10_i128};
use crate::conversion_funcs::utils::cast_overflow;
-use crate::conversion_funcs::utils::MICROS_PER_SECOND;
+use crate::conversion_funcs::utils::{timestamp_micros_with_tz, MICROS_PER_SECOND};
use crate::{EvalMode, SparkError, SparkResult};
use arrow::array::{
Array, ArrayRef, AsArray, BooleanArray, Decimal128Array, Float32Array, Float64Array,
GenericStringBuilder, Int16Array, Int32Array, Int64Array, Int8Array, OffsetSizeTrait,
- PrimitiveArray, Scalar, StringBuilder, TimestampMicrosecondBuilder,
+ PrimitiveArray, Scalar, StringBuilder,
};
use arrow::buffer::BooleanBuffer;
use arrow::compute::kernels::cmp::neq;
use arrow::datatypes::{
format_decimal_str, i256, is_validate_decimal_precision, ArrowPrimitiveType, DataType,
Decimal128Type, Float32Type, Float64Type, Int16Type, Int32Type, Int64Type, Int8Type,
+ TimestampMicrosecondType,
};
use num::{cast::AsPrimitive, Float, ToPrimitive};
use std::fmt::{self, Write};
@@ -89,54 +90,79 @@ pub(crate) fn is_df_cast_from_decimal_spark_compatible(to_type: &DataType) -> bo
// the same precision/scale, bypassing the DataFusion cast kernel entirely.
}
-macro_rules! cast_float_to_timestamp_impl {
- ($array:expr, $builder:expr, $primitive_type:ty, $eval_mode:expr) => {{
- let arr = $array.as_primitive::<$primitive_type>();
- for i in 0..arr.len() {
- if arr.is_null(i) {
- $builder.append_null();
- } else {
- let val = arr.value(i) as f64;
- // Path 1: NaN/Infinity check - error says TIMESTAMP
- if val.is_nan() || val.is_infinite() {
- if $eval_mode == EvalMode::Ansi {
- return Err(SparkError::CastInvalidValue {
- value: val.to_string(),
- from_type: "DOUBLE".to_string(),
- to_type: "TIMESTAMP".to_string(),
- });
- }
- $builder.append_null();
- } else {
- // Path 2: Multiply then check overflow - error says BIGINT
- let micros = val * MICROS_PER_SECOND as f64;
- if micros.floor() <= i64::MAX as f64 && micros.ceil() >= i64::MIN as f64 {
- $builder.append_value(micros as i64);
- } else {
- if $eval_mode == EvalMode::Ansi {
- let value_str = if micros.is_infinite() {
- if micros.is_sign_positive() {
- "Infinity".to_string()
- } else {
- "-Infinity".to_string()
- }
- } else if micros.is_nan() {
- "NaN".to_string()
- } else {
- format!("{:e}", micros).to_uppercase() + "D"
- };
- return Err(SparkError::CastOverFlow {
- value: value_str,
- from_type: "DOUBLE".to_string(),
- to_type: "BIGINT".to_string(),
- });
- }
- $builder.append_null();
- }
- }
- }
+/// Seconds since the epoch as microseconds, or `None` when the value is NaN,
+/// infinite, or the product does not fit in an i64. Legacy and Try turn that
+/// into null. ANSI reports it via [`float_timestamp_error`].
+fn float_timestamp_micros(val: f64) -> Option<i64> {
+ if val.is_nan() || val.is_infinite() {
+ return None;
+ }
+ // Widen-and-multiply, then Spark's range check from DoubleExactNumeric:
+ // floor(x) <= Long.MaxValue && ceil(x) >= Long.MinValue, with the bounds
+ // converted to double. A value that passes is truncated toward zero by `as`.
+ let micros = val * MICROS_PER_SECOND as f64;
+ if micros.floor() <= i64::MAX as f64 && micros.ceil() >= i64::MIN as f64 {
+ Some(micros as i64)
+ } else {
+ None
+ }
+}
+
+/// ANSI error for a value [`float_timestamp_micros`] rejected. NaN and infinity
+/// are `CAST_INVALID_INPUT` into TIMESTAMP. A finite value whose product does
+/// not fit is `CAST_OVERFLOW` into BIGINT. The source type is DOUBLE even when
+/// the array was float32, because the check runs after the widening.
+fn float_timestamp_error(val: f64) -> SparkError {
+ if val.is_nan() || val.is_infinite() {
+ SparkError::CastInvalidValue {
+ value: val.to_string(),
+ from_type: "DOUBLE".to_string(),
+ to_type: "TIMESTAMP".to_string(),
}
- }};
+ } else {
+ let micros = val * MICROS_PER_SECOND as f64;
+ SparkError::CastOverFlow {
+ value: float_timestamp_overflow_text(micros),
+ from_type: "DOUBLE".to_string(),
+ to_type: "BIGINT".to_string(),
+ }
+ }
+}
+
+fn float_timestamp_overflow_text(micros: f64) -> String {
+ if micros.is_infinite() {
+ if micros.is_sign_positive() {
+ "Infinity".to_string()
+ } else {
+ "-Infinity".to_string()
+ }
+ } else if micros.is_nan() {
+ "NaN".to_string()
+ } else {
+ format!("{:e}", micros).to_uppercase() + "D"
+ }
+}
+
+fn cast_float_to_timestamp_array<T>(
+ array: &PrimitiveArray<T>,
+ eval_mode: EvalMode,
+) -> SparkResult<PrimitiveArray<TimestampMicrosecondType>>
+where
+ T: ArrowPrimitiveType,
+ T::Native: Into<f64>,
+{
+ if eval_mode == EvalMode::Ansi {
+ // `try_unary` skips null slots, so a NaN sitting under a null does not raise.
+ // The first invalid value, in index order, is the error.
+ Ok(array.try_unary(|value| {
+ let val = value.into();
+ float_timestamp_micros(val).ok_or_else(|| float_timestamp_error(val))
+ })?)
+ } else {
+ // Legacy and Try null the same values ANSI rejects, without allocating an
+ // error string. `unary_opt` skips null slots, so this closure does not see them.
+ Ok(array.unary_opt(|value| float_timestamp_micros(value.into())))
+ }
}
/// A float width that Java renders through `Float.toString` / `Double.toString`.
@@ -333,21 +359,20 @@ macro_rules! cast_whole_num_to_binary {
}};
}
-macro_rules! cast_int_to_timestamp_impl {
- ($array:expr, $builder:expr, $primitive_type:ty) => {{
- let arr = $array.as_primitive::<$primitive_type>();
- for i in 0..arr.len() {
- if arr.is_null(i) {
- $builder.append_null();
- } else {
- // saturating_mul limits to i64::MIN/MAX on overflow instead of panicking,
- // which could occur when converting extreme values (e.g., Long.MIN_VALUE)
- // matching spark behavior (irrespective of EvalMode)
- let micros = (arr.value(i) as i64).saturating_mul(MICROS_PER_SECOND);
- $builder.append_value(micros);
- }
- }
- }};
+fn cast_int_to_timestamp_array<T>(
+ array: &PrimitiveArray<T>,
+) -> PrimitiveArray<TimestampMicrosecondType>
+where
+ T: ArrowPrimitiveType,
+ T::Native: Into<i64>,
+{
+ // saturating_mul limits to i64::MIN/MAX on overflow instead of panicking,
+ // which could occur when converting extreme values (e.g., Long.MIN_VALUE)
+ // matching spark behavior (irrespective of EvalMode)
+ array.unary(|value| {
+ let seconds: i64 = value.into();
+ seconds.saturating_mul(MICROS_PER_SECOND)
+ })
}
macro_rules! cast_int_to_int_macro {
@@ -1292,22 +1317,30 @@ pub(crate) fn cast_int_to_timestamp(
target_tz: &Option<Arc<str>>,
) -> SparkResult<ArrayRef> {
// Input is seconds since epoch, multiply by MICROS_PER_SECOND to get microseconds.
- let mut builder = TimestampMicrosecondBuilder::with_capacity(array_ref.len());
-
- match array_ref.data_type() {
- DataType::Int8 => cast_int_to_timestamp_impl!(array_ref, builder, Int8Type),
- DataType::Int16 => cast_int_to_timestamp_impl!(array_ref, builder, Int16Type),
- DataType::Int32 => cast_int_to_timestamp_impl!(array_ref, builder, Int32Type),
- DataType::Int64 => cast_int_to_timestamp_impl!(array_ref, builder, Int64Type),
+ let micros = match array_ref.data_type() {
+ DataType::Int8 => cast_int_to_timestamp_array(array_ref.as_primitive::<Int8Type>()),
+ DataType::Int16 => cast_int_to_timestamp_array(array_ref.as_primitive::<Int16Type>()),
+ DataType::Int32 => cast_int_to_timestamp_array(array_ref.as_primitive::<Int32Type>()),
+ DataType::Int64 => cast_int_to_timestamp_array(array_ref.as_primitive::<Int64Type>()),
dt => {
return Err(SparkError::Internal(format!(
"Unsupported type for cast_int_to_timestamp: {:?}",
dt
)))
}
- }
+ };
- Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef)
+ Ok(timestamp_micros_with_tz(micros, target_tz))
+}
+
+/// Spark truncates toward zero through a 256-bit product and keeps the low 64
+/// bits. It does not raise, in any eval mode.
+#[inline(always)]
+fn decimal_to_timestamp_micros(value: i128, scale_factor: i128) -> i64 {
+ let value_256 = i256::from_i128(value);
+ let micros_256 = value_256 * i256::from_i128(MICROS_PER_SECOND as i128);
+ let ts = micros_256 / i256::from_i128(scale_factor);
+ ts.as_i128() as i64
}
pub(crate) fn cast_decimal_to_timestamp(
@@ -1317,23 +1350,13 @@ pub(crate) fn cast_decimal_to_timestamp(
) -> SparkResult<ArrayRef> {
let arr = array_ref.as_primitive::<Decimal128Type>();
let scale_factor = 10_i128.pow(scale as u32);
- let mut builder = TimestampMicrosecondBuilder::with_capacity(arr.len());
-
- for i in 0..arr.len() {
- if arr.is_null(i) {
- builder.append_null();
- } else {
- let value = arr.value(i);
- // Note: spark's big decimal truncates to
- // long value and does not throw error (in all leval modes)
- let value_256 = i256::from_i128(value);
- let micros_256 = value_256 * i256::from_i128(MICROS_PER_SECOND as i128);
- let ts = micros_256 / i256::from_i128(scale_factor);
- builder.append_value(ts.as_i128() as i64);
- }
- }
+ // `unary_opt` visits valid rows only. `unary` also divides null slots, and
+ // that was slower on every measured shape, including a batch with no nulls.
+ let micros = arr.unary_opt::<_, TimestampMicrosecondType>(|value| {
+ Some(decimal_to_timestamp_micros(value, scale_factor))
+ });
- Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef)
+ Ok(timestamp_micros_with_tz(micros, target_tz))
}
pub(crate) fn cast_float_to_timestamp(
@@ -1341,14 +1364,12 @@ pub(crate) fn cast_float_to_timestamp(
target_tz: &Option<Arc<str>>,
eval_mode: EvalMode,
) -> SparkResult<ArrayRef> {
- let mut builder = TimestampMicrosecondBuilder::with_capacity(array_ref.len());
-
- match array_ref.data_type() {
+ let micros = match array_ref.data_type() {
DataType::Float32 => {
- cast_float_to_timestamp_impl!(array_ref, builder, Float32Type, eval_mode)
+ cast_float_to_timestamp_array(array_ref.as_primitive::<Float32Type>(), eval_mode)?
}
DataType::Float64 => {
- cast_float_to_timestamp_impl!(array_ref, builder, Float64Type, eval_mode)
+ cast_float_to_timestamp_array(array_ref.as_primitive::<Float64Type>(), eval_mode)?
}
dt => {
return Err(SparkError::Internal(format!(
@@ -1356,16 +1377,19 @@ pub(crate) fn cast_float_to_timestamp(
dt
)))
}
- }
+ };
- Ok(Arc::new(builder.finish().with_timezone_opt(target_tz.clone())) as ArrayRef)
+ Ok(timestamp_micros_with_tz(micros, target_tz))
}
#[cfg(test)]
mod tests {
use super::*;
- use arrow::array::AsArray;
- use arrow::datatypes::TimestampMicrosecondType;
+ use crate::cast::cast_array;
+ use crate::SparkCastOptions;
+ use arrow::array::{Array, AsArray, TimestampMicrosecondBuilder};
+ use arrow::buffer::NullBuffer;
+ use arrow::datatypes::{TimeUnit, TimestampMicrosecondType};
#[test]
fn test_spark_cast_int_to_int_overflow() {
@@ -2592,6 +2616,7 @@ mod tests {
let result = cast_decimal_to_timestamp(&decimal_array, tz, 6).unwrap();
let ts_array = result.as_primitive::<TimestampMicrosecondType>();
+ assert!(ts_array.is_valid(0));
assert_eq!(ts_array.value(0), 0);
assert_eq!(ts_array.value(1), 1_000_000);
assert_eq!(ts_array.value(2), -1_000_000);
@@ -2726,4 +2751,230 @@ mod tests {
"-1.70141183460469231731687303715884105727E-7"
);
}
+
+ fn assert_ts(array: &ArrayRef, expected: &[Option<i64>], tz: Option<&str>) {
+ let ts = array.as_primitive::<TimestampMicrosecondType>();
+ assert_eq!(ts.len(), expected.len());
+ assert_eq!(ts.timezone(), tz);
+ let mut nulls = 0;
+ for (i, slot) in expected.iter().enumerate() {
+ match slot {
+ None => {
+ assert!(ts.is_null(i), "index {i} should be null");
+ nulls += 1;
+ }
+ Some(value) => {
+ assert!(ts.is_valid(i), "index {i} should be valid");
+ assert_eq!(ts.value(i), *value, "index {i}");
+ }
+ }
+ }
+ assert_eq!(ts.null_count(), nulls);
+ if nulls == 0 {
+ assert!(
+ ts.nulls().is_none(),
+ "a batch with no nulls has no null buffer"
+ );
+ }
+ }
+
+ /// Logical nulls and valid values. Values stored under nulls are not compared:
+ /// the builder writes 0 there, and `unary` writes the converted payload.
+ fn assert_logical_timestamps(actual: &ArrayRef, expected: &ArrayRef) {
+ let actual = actual.as_primitive::<TimestampMicrosecondType>();
+ let expected = expected.as_primitive::<TimestampMicrosecondType>();
+ assert_eq!(actual.len(), expected.len());
+ assert_eq!(actual.timezone(), expected.timezone());
+ for i in 0..actual.len() {
+ assert_eq!(actual.is_null(i), expected.is_null(i), "index {i}");
+ if actual.is_valid(i) {
+ assert_eq!(actual.value(i), expected.value(i), "index {i}");
+ }
+ }
+ }
+
+ #[test]
+ fn test_cast_int_to_timestamp_null_slot_matches_builder() {
+ let tz = Some(Arc::from("UTC"));
+ // The slice starts on a null whose payload is i64::MIN. Multiplying that
+ // payload by MICROS_PER_SECOND overflows i64.
+ let raw = Int64Array::from(vec![7_i64, i64::MIN, 5, i64::MAX]);
+ let masked = Int64Array::new(
+ raw.values().clone(),
+ Some(NullBuffer::from(vec![true, false, true, false])),
+ );
+ let input = Array::slice(&masked, 1, 3);
+ let ints = input.as_primitive::<Int64Type>();
+ let mut builder = TimestampMicrosecondBuilder::with_capacity(ints.len());
+ for i in 0..ints.len() {
+ if ints.is_null(i) {
+ builder.append_null();
+ } else {
+ builder.append_value(ints.value(i).saturating_mul(MICROS_PER_SECOND));
+ }
+ }
+ let expected: ArrayRef = Arc::new(builder.finish().with_timezone_opt(tz.clone()));
+
+ let out = cast_array(
+ Arc::clone(&input),
+ &DataType::Timestamp(TimeUnit::Microsecond, tz),
+ &SparkCastOptions::new(EvalMode::Ansi, "UTC"),
+ )
+ .unwrap();
+ assert_logical_timestamps(&out, &expected);
+ }
+
+ #[test]
+ fn test_cast_int_to_timestamp_edges() {
+ let extremes: ArrayRef = Arc::new(Int64Array::from(vec![Some(i64::MIN), Some(i64::MAX)]));
+ let out = cast_int_to_timestamp(&extremes, &None).unwrap();
+ assert_ts(&out, &[Some(i64::MIN), Some(i64::MAX)], None);
+ }
+
+ #[test]
+ fn test_cast_decimal_to_timestamp_edges() {
+ let tz = Some(Arc::from("UTC"));
+ // Toward zero, and the low 64 bits when the 256-bit product does not fit in i64.
+ let cases = [
+ (15_i128, 7_i8, 1_i64),
+ (-15, 7, -1),
+ (9, 7, 0),
+ (i128::MAX, 6, -1),
+ (i128::MIN, 6, 0),
+ (i128::MAX, 0, -1_000_000),
+ ];
+ for (unscaled, scale, expected) in cases {
+ let array: ArrayRef = Arc::new(
+ Decimal128Array::from(vec![Some(unscaled)])
+ .with_precision_and_scale(38, scale)
+ .unwrap(),
+ );
+ let out = cast_decimal_to_timestamp(&array, &tz, scale).unwrap();
+ assert_ts(&out, &[Some(expected)], Some("UTC"));
+ }
+
+ let all_null: ArrayRef = Arc::new(
+ Decimal128Array::new_null(3)
+ .with_precision_and_scale(10, 6)
+ .unwrap(),
+ );
+ let out = cast_decimal_to_timestamp(&all_null, &tz, 6).unwrap();
+ assert_ts(&out, &[None, None, None], Some("UTC"));
+ }
+
+ #[test]
+ fn test_cast_float_to_timestamp_edges() {
+ let tz = Some(Arc::from("UTC"));
+
+ // First valid offender, in index order. 1e16 overflows; 1e20 would be "1E26D".
+ let overflow: ArrayRef = Arc::new(Float64Array::from(vec![
+ None,
+ Some(1.0),
+ Some(1e16),
+ Some(1e20),
+ ]));
+ match cast_float_to_timestamp(&overflow, &tz, EvalMode::Ansi).unwrap_err() {
+ SparkError::CastOverFlow {
+ value,
+ from_type,
+ to_type,
+ } => {
+ assert_eq!(value, "1E22D");
+ assert_eq!(from_type, "DOUBLE");
+ assert_eq!(to_type, "BIGINT");
+ }
+ other => panic!("expected overflow, got {other:?}"),
+ }
+
+ for (value, text) in [(f64::MAX, "Infinity"), (f64::MIN, "-Infinity")] {
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(value)]));
+ match cast_float_to_timestamp(&array, &tz, EvalMode::Ansi).unwrap_err() {
+ SparkError::CastOverFlow {
+ value: got,
+ from_type,
+ to_type,
+ } => {
+ assert_eq!(got, text);
+ assert_eq!(from_type, "DOUBLE");
+ assert_eq!(to_type, "BIGINT");
+ }
+ other => panic!("expected overflow, got {other:?}"),
+ }
+ }
+
+ // Legacy and Try null the same values and do not raise.
+ let mixed: ArrayRef = Arc::new(Float64Array::from(vec![
+ Some(2.0),
+ Some(f64::NAN),
+ Some(f64::INFINITY),
+ None,
+ Some(-3.0),
+ ]));
+ let legacy = cast_float_to_timestamp(&mixed, &tz, EvalMode::Legacy).unwrap();
+ let try_mode = cast_float_to_timestamp(&mixed, &tz, EvalMode::Try).unwrap();
+ assert_eq!(
+ legacy.as_primitive::<TimestampMicrosecondType>(),
+ try_mode.as_primitive::<TimestampMicrosecondType>()
+ );
+ assert_ts(
+ &legacy,
+ &[Some(2_000_000), None, None, None, Some(-3_000_000)],
+ Some("UTC"),
+ );
+
+ // A NaN under a null is not read, so ANSI does not raise.
+ let raw = Float64Array::from(vec![f64::NAN, 4.0]);
+ let masked = Float64Array::new(
+ raw.values().clone(),
+ Some(NullBuffer::from(vec![false, true])),
+ );
+ let out =
+ cast_float_to_timestamp(&(Arc::new(masked) as ArrayRef), &tz, EvalMode::Ansi).unwrap();
+ assert_ts(&out, &[None, Some(4_000_000)], Some("UTC"));
+
+ // float32 widens to double. f32::MAX's product is a finite f64 that does not fit.
+ let f32_max: ArrayRef = Arc::new(Float32Array::from(vec![Some(f32::MAX)]));
+ match cast_float_to_timestamp(&f32_max, &tz, EvalMode::Ansi).unwrap_err() {
+ SparkError::CastOverFlow {
+ value, from_type, ..
+ } => {
+ assert_eq!(value, "3.4028234663852886E44D");
+ assert_eq!(from_type, "DOUBLE");
+ }
+ other => panic!("expected overflow, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn test_cast_float_invalid_from_type_is_double() {
+ let tz = Some(Arc::from("UTC"));
+ for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(value)]));
+ let err = cast_float_to_timestamp(&array, &tz, EvalMode::Ansi).unwrap_err();
+ let from_type = match err {
+ SparkError::CastInvalidValue { from_type, .. }
+ | SparkError::InvalidInputInCastToDatetime { from_type, .. } => from_type,
+ other => panic!("expected an invalid-input error, got {other:?}"),
+ };
+ assert_eq!(from_type, "DOUBLE");
+ }
+ }
+
+ #[test]
+ fn test_cast_float_timestamp_bounds_at_i64_extremes() {
+ let tz = Some(Arc::from("UTC"));
+ let hi = (i64::MAX as f64) / (MICROS_PER_SECOND as f64);
+ let lo = (i64::MIN as f64) / (MICROS_PER_SECOND as f64);
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(hi), Some(lo)]));
+ let out = cast_float_to_timestamp(&array, &tz, EvalMode::Ansi).unwrap();
+ assert_ts(&out, &[Some(i64::MAX), Some(i64::MIN)], Some("UTC"));
+ }
+
+ #[test]
+ fn test_cast_float_timestamp_truncates_toward_zero() {
+ let tz = Some(Arc::from("UTC"));
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![Some(1.5e-6), Some(-1.5e-6)]));
+ let out = cast_float_to_timestamp(&array, &tz, EvalMode::Ansi).unwrap();
+ assert_ts(&out, &[Some(1), Some(-1)], Some("UTC"));
+ }
}
diff --git a/native/spark-expr/src/conversion_funcs/utils.rs b/native/spark-expr/src/conversion_funcs/utils.rs
index 174efb0b87..469b4b1b93 100644
--- a/native/spark-expr/src/conversion_funcs/utils.rs
+++ b/native/spark-expr/src/conversion_funcs/utils.rs
@@ -20,7 +20,7 @@ use arrow::array::{
Array, ArrayRef, ArrowPrimitiveType, AsArray, GenericStringArray, PrimitiveArray,
};
use arrow::compute::unary;
-use arrow::datatypes::{DataType, Int64Type};
+use arrow::datatypes::{DataType, Int64Type, TimestampMicrosecondType};
use arrow::error::ArrowError;
use datafusion::common::cast::as_generic_string_array;
use num::integer::div_floor;
@@ -28,6 +28,24 @@ use std::sync::Arc;
pub(crate) const MICROS_PER_SECOND: i64 = 1000000;
+/// Attach `target_tz` to a microsecond timestamp array.
+///
+/// A batch with no nulls keeps `nulls() == None`. `unary_opt` always builds a
+/// null buffer, and `unary` copies an all-valid one; the builder these kernels
+/// replace did neither.
+pub(crate) fn timestamp_micros_with_tz(
+ array: PrimitiveArray<TimestampMicrosecondType>,
+ target_tz: &Option<Arc<str>>,
+) -> ArrayRef {
+ let array = if array.null_count() == 0 && array.nulls().is_some() {
+ let (_, values, _) = array.into_parts();
+ PrimitiveArray::new(values, None)
+ } else {
+ array
+ };
+ Arc::new(array.with_timezone_opt(target_tz.clone()))
+}
+
/// A fork & modified version of Arrow's `unary_dyn` which is being deprecated
pub fn unary_dyn<F, T>(array: &ArrayRef, op: F) -> Result<ArrayRef, ArrowError>
where
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org