|
| 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::{Array, Decimal128Array, Int32Array, Time64NanosecondArray}; |
| 19 | +use arrow::compute::cast; |
| 20 | +use arrow::datatypes::{DataType, TimeUnit}; |
| 21 | +use datafusion::common::{utils::take_function_args, DataFusionError, Result}; |
| 22 | +use datafusion::logical_expr::{ |
| 23 | + ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, |
| 24 | +}; |
| 25 | +use std::any::Any; |
| 26 | +use std::sync::Arc; |
| 27 | + |
| 28 | +const MICROS_PER_SECOND: i128 = 1_000_000; |
| 29 | +const NANOS_PER_MICRO: i64 = 1_000; |
| 30 | +const NANOS_PER_SECOND: i64 = 1_000_000_000; |
| 31 | + |
| 32 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 33 | +pub struct SparkMakeTime { |
| 34 | + signature: Signature, |
| 35 | +} |
| 36 | + |
| 37 | +impl SparkMakeTime { |
| 38 | + pub fn new() -> Self { |
| 39 | + Self { |
| 40 | + signature: Signature::any(3, Volatility::Immutable), |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl Default for SparkMakeTime { |
| 46 | + fn default() -> Self { |
| 47 | + Self::new() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/// Converts hours, minutes, and fractional seconds (Decimal(16,6)) to nanoseconds from midnight. |
| 52 | +/// Returns an error for invalid inputs (matching Spark's always-throw behavior). |
| 53 | +fn make_time(hours: i32, minutes: i32, secs_and_micros_unscaled: i128) -> Result<i64> { |
| 54 | + let full_secs = secs_and_micros_unscaled.div_euclid(MICROS_PER_SECOND); |
| 55 | + let frac_micros = secs_and_micros_unscaled.rem_euclid(MICROS_PER_SECOND); |
| 56 | + |
| 57 | + if full_secs > i32::MAX as i128 || full_secs < 0 { |
| 58 | + return Err(DataFusionError::Execution(format!( |
| 59 | + "Invalid value for SecondOfMinute (valid values 0 - 59): {}", |
| 60 | + secs_and_micros_unscaled / MICROS_PER_SECOND |
| 61 | + ))); |
| 62 | + } |
| 63 | + |
| 64 | + let secs = full_secs as i32; |
| 65 | + let nanos = (frac_micros as i64) * NANOS_PER_MICRO; |
| 66 | + |
| 67 | + if !(0..=23).contains(&hours) { |
| 68 | + return Err(DataFusionError::Execution(format!( |
| 69 | + "Invalid value for HourOfDay (valid values 0 - 23): {hours}" |
| 70 | + ))); |
| 71 | + } |
| 72 | + if !(0..=59).contains(&minutes) { |
| 73 | + return Err(DataFusionError::Execution(format!( |
| 74 | + "Invalid value for MinuteOfHour (valid values 0 - 59): {minutes}" |
| 75 | + ))); |
| 76 | + } |
| 77 | + if !(0..=59).contains(&secs) { |
| 78 | + return Err(DataFusionError::Execution(format!( |
| 79 | + "Invalid value for SecondOfMinute (valid values 0 - 59): {secs}" |
| 80 | + ))); |
| 81 | + } |
| 82 | + |
| 83 | + let total_nanos = |
| 84 | + hours as i64 * 3_600 * NANOS_PER_SECOND + minutes as i64 * 60 * NANOS_PER_SECOND + secs as i64 * NANOS_PER_SECOND + nanos; |
| 85 | + |
| 86 | + Ok(total_nanos) |
| 87 | +} |
| 88 | + |
| 89 | +impl ScalarUDFImpl for SparkMakeTime { |
| 90 | + fn as_any(&self) -> &dyn Any { |
| 91 | + self |
| 92 | + } |
| 93 | + |
| 94 | + fn name(&self) -> &str { |
| 95 | + "make_time" |
| 96 | + } |
| 97 | + |
| 98 | + fn signature(&self) -> &Signature { |
| 99 | + &self.signature |
| 100 | + } |
| 101 | + |
| 102 | + fn return_type(&self, _: &[DataType]) -> Result<DataType> { |
| 103 | + Ok(DataType::Time64(TimeUnit::Nanosecond)) |
| 104 | + } |
| 105 | + |
| 106 | + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { |
| 107 | + let [hours, minutes, secs_and_micros] = take_function_args(self.name(), args.args)?; |
| 108 | + |
| 109 | + let num_rows = [&hours, &minutes, &secs_and_micros] |
| 110 | + .iter() |
| 111 | + .find_map(|arg| match arg { |
| 112 | + ColumnarValue::Array(array) => Some(array.len()), |
| 113 | + ColumnarValue::Scalar(_) => None, |
| 114 | + }) |
| 115 | + .unwrap_or(1); |
| 116 | + |
| 117 | + let hours_arr = hours.into_array(num_rows)?; |
| 118 | + let minutes_arr = minutes.into_array(num_rows)?; |
| 119 | + let secs_arr = secs_and_micros.into_array(num_rows)?; |
| 120 | + |
| 121 | + let hours_arr = cast_to_int32(&hours_arr)?; |
| 122 | + let minutes_arr = cast_to_int32(&minutes_arr)?; |
| 123 | + |
| 124 | + let hours_array = hours_arr.as_any().downcast_ref::<Int32Array>().ok_or_else(|| { |
| 125 | + DataFusionError::Execution("make_time: failed to cast hours to Int32".to_string()) |
| 126 | + })?; |
| 127 | + |
| 128 | + let minutes_array = |
| 129 | + minutes_arr |
| 130 | + .as_any() |
| 131 | + .downcast_ref::<Int32Array>() |
| 132 | + .ok_or_else(|| { |
| 133 | + DataFusionError::Execution( |
| 134 | + "make_time: failed to cast minutes to Int32".to_string(), |
| 135 | + ) |
| 136 | + })?; |
| 137 | + |
| 138 | + let secs_array = secs_arr |
| 139 | + .as_any() |
| 140 | + .downcast_ref::<Decimal128Array>() |
| 141 | + .ok_or_else(|| { |
| 142 | + DataFusionError::Execution( |
| 143 | + "make_time: expected Decimal128 for seconds argument".to_string(), |
| 144 | + ) |
| 145 | + })?; |
| 146 | + |
| 147 | + let len = hours_array.len(); |
| 148 | + let mut builder = Time64NanosecondArray::builder(len); |
| 149 | + |
| 150 | + for i in 0..len { |
| 151 | + if hours_array.is_null(i) || minutes_array.is_null(i) || secs_array.is_null(i) { |
| 152 | + builder.append_null(); |
| 153 | + } else { |
| 154 | + let h = hours_array.value(i); |
| 155 | + let m = minutes_array.value(i); |
| 156 | + let s = secs_array.value(i); |
| 157 | + |
| 158 | + let nanos = make_time(h, m, s)?; |
| 159 | + builder.append_value(nanos); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + Ok(ColumnarValue::Array(Arc::new(builder.finish()))) |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +fn cast_to_int32(arr: &Arc<dyn Array>) -> Result<Arc<dyn Array>> { |
| 168 | + if arr.data_type() == &DataType::Int32 { |
| 169 | + Ok(Arc::clone(arr)) |
| 170 | + } else { |
| 171 | + cast(arr.as_ref(), &DataType::Int32) |
| 172 | + .map_err(|e| DataFusionError::Execution(format!("Failed to cast to Int32: {e}"))) |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +#[cfg(test)] |
| 177 | +mod tests { |
| 178 | + use super::*; |
| 179 | + |
| 180 | + #[test] |
| 181 | + fn test_make_time_valid() { |
| 182 | + // Midnight |
| 183 | + assert_eq!(make_time(0, 0, 0).unwrap(), 0); |
| 184 | + // 1 hour |
| 185 | + assert_eq!(make_time(1, 0, 0).unwrap(), 3_600_000_000_000); |
| 186 | + // 1 minute |
| 187 | + assert_eq!(make_time(0, 1, 0).unwrap(), 60_000_000_000); |
| 188 | + // 1 second (unscaled: 1_000_000) |
| 189 | + assert_eq!(make_time(0, 0, 1_000_000).unwrap(), 1_000_000_000); |
| 190 | + // 1.5 seconds (unscaled: 1_500_000) |
| 191 | + assert_eq!(make_time(0, 0, 1_500_000).unwrap(), 1_500_000_000); |
| 192 | + // 23:59:59.999999 (unscaled: 59_999_999) |
| 193 | + assert_eq!( |
| 194 | + make_time(23, 59, 59_999_999).unwrap(), |
| 195 | + 86_399_999_999_000 |
| 196 | + ); |
| 197 | + // 12:30:45.123456 (unscaled: 45_123_456) |
| 198 | + assert_eq!( |
| 199 | + make_time(12, 30, 45_123_456).unwrap(), |
| 200 | + 12 * 3_600_000_000_000 + 30 * 60_000_000_000 + 45_123_456_000 |
| 201 | + ); |
| 202 | + } |
| 203 | + |
| 204 | + #[test] |
| 205 | + fn test_make_time_invalid_hours() { |
| 206 | + assert!(make_time(24, 0, 0).is_err()); |
| 207 | + assert!(make_time(25, 0, 0).is_err()); |
| 208 | + assert!(make_time(-1, 0, 0).is_err()); |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn test_make_time_invalid_minutes() { |
| 213 | + assert!(make_time(0, 60, 0).is_err()); |
| 214 | + assert!(make_time(0, -1, 0).is_err()); |
| 215 | + } |
| 216 | + |
| 217 | + #[test] |
| 218 | + fn test_make_time_invalid_seconds() { |
| 219 | + // 60 seconds (unscaled: 60_000_000) |
| 220 | + assert!(make_time(0, 0, 60_000_000).is_err()); |
| 221 | + // 100.5 seconds (unscaled: 100_500_000) |
| 222 | + assert!(make_time(0, 0, 100_500_000).is_err()); |
| 223 | + // negative seconds (unscaled: -1_000_000) |
| 224 | + assert!(make_time(0, 0, -1_000_000).is_err()); |
| 225 | + } |
| 226 | + |
| 227 | + #[test] |
| 228 | + fn test_make_time_overflow_seconds() { |
| 229 | + // Very large value that overflows i32 |
| 230 | + let large = (i32::MAX as i128 + 1) * MICROS_PER_SECOND; |
| 231 | + assert!(make_time(0, 0, large).is_err()); |
| 232 | + } |
| 233 | +} |
0 commit comments