|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use arrow::array::{ |
| 19 | + Array, Float32Array, Float64Array, Int32Array, Int64Array, TimestampMicrosecondArray, |
| 20 | +}; |
| 21 | +use arrow::compute::try_unary; |
| 22 | +use arrow::datatypes::{DataType, TimeUnit}; |
| 23 | +use datafusion::common::{utils::take_function_args, DataFusionError, Result, ScalarValue}; |
| 24 | +use datafusion::logical_expr::{ |
| 25 | + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature, Volatility, |
| 26 | +}; |
| 27 | +use std::any::Any; |
| 28 | +use std::sync::Arc; |
| 29 | + |
| 30 | +const MICROS_PER_SECOND: i64 = 1_000_000; |
| 31 | + |
| 32 | +/// Spark-compatible seconds_to_timestamp (timestamp_seconds) function. |
| 33 | +/// Converts seconds since Unix epoch to a timestamp. |
| 34 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 35 | +pub struct SparkSecondsToTimestamp { |
| 36 | + signature: Signature, |
| 37 | + aliases: Vec<String>, |
| 38 | +} |
| 39 | + |
| 40 | +impl SparkSecondsToTimestamp { |
| 41 | + pub fn new() -> Self { |
| 42 | + Self { |
| 43 | + signature: Signature::one_of( |
| 44 | + vec![ |
| 45 | + TypeSignature::Exact(vec![DataType::Int32]), |
| 46 | + TypeSignature::Exact(vec![DataType::Int64]), |
| 47 | + TypeSignature::Exact(vec![DataType::Float32]), |
| 48 | + TypeSignature::Exact(vec![DataType::Float64]), |
| 49 | + ], |
| 50 | + Volatility::Immutable, |
| 51 | + ), |
| 52 | + aliases: vec!["timestamp_seconds".to_string()], |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl Default for SparkSecondsToTimestamp { |
| 58 | + fn default() -> Self { |
| 59 | + Self::new() |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +impl ScalarUDFImpl for SparkSecondsToTimestamp { |
| 64 | + fn as_any(&self) -> &dyn Any { |
| 65 | + self |
| 66 | + } |
| 67 | + |
| 68 | + fn name(&self) -> &str { |
| 69 | + "seconds_to_timestamp" |
| 70 | + } |
| 71 | + |
| 72 | + fn signature(&self) -> &Signature { |
| 73 | + &self.signature |
| 74 | + } |
| 75 | + |
| 76 | + fn return_type(&self, _: &[DataType]) -> Result<DataType> { |
| 77 | + Ok(DataType::Timestamp(TimeUnit::Microsecond, None)) |
| 78 | + } |
| 79 | + |
| 80 | + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { |
| 81 | + let [seconds] = take_function_args(self.name(), args.args)?; |
| 82 | + |
| 83 | + match seconds { |
| 84 | + ColumnarValue::Array(arr) => { |
| 85 | + // Handle Int32 input — no overflow possible since i32 * 1_000_000 fits in i64 |
| 86 | + if let Some(int_array) = arr.as_any().downcast_ref::<Int32Array>() { |
| 87 | + let result: TimestampMicrosecondArray = |
| 88 | + try_unary(int_array, |s| Ok((s as i64) * MICROS_PER_SECOND))?; |
| 89 | + return Ok(ColumnarValue::Array(Arc::new(result))); |
| 90 | + } |
| 91 | + |
| 92 | + // Handle Int64 input — error on overflow to match Spark's Math.multiplyExact |
| 93 | + if let Some(int_array) = arr.as_any().downcast_ref::<Int64Array>() { |
| 94 | + let result: TimestampMicrosecondArray = try_unary(int_array, |s| { |
| 95 | + s.checked_mul(MICROS_PER_SECOND).ok_or_else(|| { |
| 96 | + arrow::error::ArrowError::ComputeError("long overflow".to_string()) |
| 97 | + }) |
| 98 | + })?; |
| 99 | + return Ok(ColumnarValue::Array(Arc::new(result))); |
| 100 | + } |
| 101 | + |
| 102 | + // Handle Float32 input — cast to f64 and use Float64 path |
| 103 | + if let Some(float_array) = arr.as_any().downcast_ref::<Float32Array>() { |
| 104 | + let result: arrow::array::TimestampMicrosecondArray = float_array |
| 105 | + .iter() |
| 106 | + .map(|opt| { |
| 107 | + opt.and_then(|s| { |
| 108 | + let s = s as f64; |
| 109 | + if s.is_nan() || s.is_infinite() { |
| 110 | + None |
| 111 | + } else { |
| 112 | + Some((s * (MICROS_PER_SECOND as f64)) as i64) |
| 113 | + } |
| 114 | + }) |
| 115 | + }) |
| 116 | + .collect(); |
| 117 | + return Ok(ColumnarValue::Array(Arc::new(result))); |
| 118 | + } |
| 119 | + |
| 120 | + // Handle Float64 input — NaN and Infinity return null per Spark behavior |
| 121 | + if let Some(float_array) = arr.as_any().downcast_ref::<Float64Array>() { |
| 122 | + let result: arrow::array::TimestampMicrosecondArray = float_array |
| 123 | + .iter() |
| 124 | + .map(|opt| { |
| 125 | + opt.and_then(|s| { |
| 126 | + if s.is_nan() || s.is_infinite() { |
| 127 | + None |
| 128 | + } else { |
| 129 | + Some((s * (MICROS_PER_SECOND as f64)) as i64) |
| 130 | + } |
| 131 | + }) |
| 132 | + }) |
| 133 | + .collect(); |
| 134 | + return Ok(ColumnarValue::Array(Arc::new(result))); |
| 135 | + } |
| 136 | + |
| 137 | + Err(DataFusionError::Execution(format!( |
| 138 | + "seconds_to_timestamp expects Int32, Int64, Float32 or Float64 input, got {:?}", |
| 139 | + arr.data_type() |
| 140 | + ))) |
| 141 | + } |
| 142 | + ColumnarValue::Scalar(scalar) => { |
| 143 | + let ts_micros = match &scalar { |
| 144 | + ScalarValue::Int32(Some(s)) => Some((*s as i64) * MICROS_PER_SECOND), |
| 145 | + ScalarValue::Int64(Some(s)) => { |
| 146 | + Some(s.checked_mul(MICROS_PER_SECOND).ok_or_else(|| { |
| 147 | + DataFusionError::ArrowError( |
| 148 | + Box::new(arrow::error::ArrowError::ComputeError( |
| 149 | + "long overflow".to_string(), |
| 150 | + )), |
| 151 | + None, |
| 152 | + ) |
| 153 | + })?) |
| 154 | + } |
| 155 | + ScalarValue::Float32(Some(s)) => { |
| 156 | + let s = *s as f64; |
| 157 | + if s.is_nan() || s.is_infinite() { |
| 158 | + None |
| 159 | + } else { |
| 160 | + Some((s * (MICROS_PER_SECOND as f64)) as i64) |
| 161 | + } |
| 162 | + } |
| 163 | + ScalarValue::Float64(Some(s)) => { |
| 164 | + if s.is_nan() || s.is_infinite() { |
| 165 | + None |
| 166 | + } else { |
| 167 | + Some((s * (MICROS_PER_SECOND as f64)) as i64) |
| 168 | + } |
| 169 | + } |
| 170 | + ScalarValue::Int32(None) |
| 171 | + | ScalarValue::Int64(None) |
| 172 | + | ScalarValue::Float32(None) |
| 173 | + | ScalarValue::Float64(None) |
| 174 | + | ScalarValue::Null => None, |
| 175 | + _ => { |
| 176 | + return Err(DataFusionError::Execution(format!( |
| 177 | + "seconds_to_timestamp expects numeric scalar input, got {:?}", |
| 178 | + scalar.data_type() |
| 179 | + ))) |
| 180 | + } |
| 181 | + }; |
| 182 | + Ok(ColumnarValue::Scalar(ScalarValue::TimestampMicrosecond( |
| 183 | + ts_micros, None, |
| 184 | + ))) |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + fn aliases(&self) -> &[String] { |
| 190 | + &self.aliases |
| 191 | + } |
| 192 | +} |
0 commit comments