This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new 4e04fea272 feat: support casting strings to durations (#11572)
4e04fea272 is described below
commit 4e04fea272107a6716d5634c591d0d994ba1eed2
Author: Miguel Cordero Pamphile <[email protected]>
AuthorDate: Fri Nov 13 01:45:41 2026 +0000
feat: support casting strings to durations (#11572)
Fixes #4555.
The cast kernels supported strings to intervals, but not to durations.
This adds casts from `Utf8`, `LargeUtf8`, and `Utf8View` to `Duration`
in all four units. Integer strings are interpreted in the target unit,
while unit-bearing strings support fixed units, days, and weeks.
Month-based units are rejected.
- `can_cast_types` accepts the string → duration combination
- dispatch through `cast_string_to_duration` (`Utf8`/`LargeUtf8`) and
`cast_view_to_duration` (`Utf8View`)
- tests: safe casts with nulls and invalid values, unsafe errors,
unit-bearing strings, and large/view variants
`cargo test -p arrow-cast --lib`: 368 passed.
---
arrow-cast/src/cast/mod.rs | 172 ++++++++++++++++++++++++++++++++++++++++++
arrow-cast/src/cast/string.rs | 111 +++++++++++++++++++++++++++
arrow-cast/src/parse.rs | 38 +++++++++-
3 files changed, 317 insertions(+), 4 deletions(-)
diff --git a/arrow-cast/src/cast/mod.rs b/arrow-cast/src/cast/mod.rs
index d335b236da..2f75b1353e 100644
--- a/arrow-cast/src/cast/mod.rs
+++ b/arrow-cast/src/cast/mod.rs
@@ -397,6 +397,7 @@ pub fn can_cast_types(from_type: &DataType, to_type:
&DataType) -> bool {
| Time64(Microsecond | Nanosecond)
| Timestamp(Second | Millisecond | Microsecond | Nanosecond, _)
| Interval(_)
+ | Duration(_)
| BinaryView,
) => true,
(Utf8 | LargeUtf8, Utf8View) => true,
@@ -1173,6 +1174,18 @@ pub fn cast_with_options(
Interval(IntervalUnit::MonthDayNano) => {
cast_string_to_month_day_nano_interval::<i32>(array,
cast_options)
}
+ Duration(TimeUnit::Second) => {
+ cast_string_to_duration::<DurationSecondType, i32>(array,
cast_options)
+ }
+ Duration(TimeUnit::Millisecond) => {
+ cast_string_to_duration::<DurationMillisecondType, i32>(array,
cast_options)
+ }
+ Duration(TimeUnit::Microsecond) => {
+ cast_string_to_duration::<DurationMicrosecondType, i32>(array,
cast_options)
+ }
+ Duration(TimeUnit::Nanosecond) => {
+ cast_string_to_duration::<DurationNanosecondType, i32>(array,
cast_options)
+ }
_ => Err(ArrowError::InvalidArgumentError(format!(
"Casting from {from_type} to {to_type} not supported",
))),
@@ -1231,6 +1244,18 @@ pub fn cast_with_options(
Interval(IntervalUnit::MonthDayNano) => {
cast_view_to_month_day_nano_interval(array, cast_options)
}
+ Duration(TimeUnit::Second) => {
+ cast_view_to_duration::<DurationSecondType>(array,
cast_options)
+ }
+ Duration(TimeUnit::Millisecond) => {
+ cast_view_to_duration::<DurationMillisecondType>(array,
cast_options)
+ }
+ Duration(TimeUnit::Microsecond) => {
+ cast_view_to_duration::<DurationMicrosecondType>(array,
cast_options)
+ }
+ Duration(TimeUnit::Nanosecond) => {
+ cast_view_to_duration::<DurationNanosecondType>(array,
cast_options)
+ }
_ => Err(ArrowError::InvalidArgumentError(format!(
"Casting from {from_type} to {to_type} not supported",
))),
@@ -1306,6 +1331,18 @@ pub fn cast_with_options(
Interval(IntervalUnit::MonthDayNano) => {
cast_string_to_month_day_nano_interval::<i64>(array,
cast_options)
}
+ Duration(TimeUnit::Second) => {
+ cast_string_to_duration::<DurationSecondType, i64>(array,
cast_options)
+ }
+ Duration(TimeUnit::Millisecond) => {
+ cast_string_to_duration::<DurationMillisecondType, i64>(array,
cast_options)
+ }
+ Duration(TimeUnit::Microsecond) => {
+ cast_string_to_duration::<DurationMicrosecondType, i64>(array,
cast_options)
+ }
+ Duration(TimeUnit::Nanosecond) => {
+ cast_string_to_duration::<DurationNanosecondType, i64>(array,
cast_options)
+ }
_ => Err(ArrowError::InvalidArgumentError(format!(
"Casting from {from_type} to {to_type} not supported",
))),
@@ -2688,6 +2725,141 @@ mod tests {
}
}
+ #[test]
+ fn test_cast_string_to_duration() {
+ let array = StringArray::from(vec![Some("1"), Some("-2"), None,
Some("invalid")]);
+ let to_type = DataType::Duration(TimeUnit::Second);
+ assert!(can_cast_types(array.data_type(), &to_type));
+
+ let casted = cast(&array, &to_type).unwrap();
+ assert_eq!(
+ casted.as_primitive::<DurationSecondType>(),
+ &DurationSecondArray::from(vec![Some(1), Some(-2), None, None])
+ );
+
+ let options = CastOptions {
+ safe: false,
+ format_options: FormatOptions::default(),
+ };
+ let err = cast_with_options(&array, &to_type, &options).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Cast error: Cannot cast string 'invalid' to value of Duration(s)
type"
+ );
+ }
+
+ #[test]
+ fn test_cast_string_with_units_to_duration() {
+ let array = StringArray::from(vec![
+ Some("1 hour 10 minutes"),
+ Some("90 seconds"),
+ Some("0.5 hours"),
+ Some("-1 hour -30 minutes"),
+ Some("2 days"),
+ Some("1 week"),
+ Some("45 days 14 hours 2 mins 34 secs"),
+ None,
+ Some("2 months"),
+ ]);
+ let to_type = DataType::Duration(TimeUnit::Second);
+
+ let casted = cast(&array, &to_type).unwrap();
+ assert_eq!(
+ casted.as_primitive::<DurationSecondType>(),
+ &DurationSecondArray::from(vec![
+ Some(4200),
+ Some(90),
+ Some(1800),
+ Some(-5400),
+ Some(172800),
+ Some(604800),
+ Some(3938554),
+ None,
+ None
+ ])
+ );
+
+ let options = CastOptions {
+ safe: false,
+ format_options: FormatOptions::default(),
+ };
+ let err = cast_with_options(&array, &to_type, &options).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Compute error: Cannot convert interval containing non-zero months
to duration"
+ );
+ }
+
+ #[test]
+ fn test_cast_fractional_calendar_units_to_duration() {
+ let array = StringArray::from(vec![
+ Some("0.5 months"),
+ Some("-0.5 months"),
+ Some("1.5 months"),
+ Some("0.5 years"),
+ Some("0.5 decades"),
+ Some("15 days"),
+ Some("0.5 days"),
+ Some("0.5 weeks"),
+ ]);
+ let to_type = DataType::Duration(TimeUnit::Second);
+
+ let casted = cast(&array, &to_type).unwrap();
+ assert_eq!(
+ casted.as_primitive::<DurationSecondType>(),
+ &DurationSecondArray::from(vec![
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(1_296_000),
+ Some(43_200),
+ Some(302_400)
+ ])
+ );
+
+ let options = CastOptions {
+ safe: false,
+ format_options: FormatOptions::default(),
+ };
+ let err = cast_with_options(&array, &to_type, &options).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Cast error: Cannot cast string '0.5 months' to value of
Duration(s) type"
+ );
+ }
+
+ #[test]
+ fn test_cast_large_string_and_view_to_duration() {
+ let to_type = DataType::Duration(TimeUnit::Nanosecond);
+ for array in [
+ Arc::new(LargeStringArray::from(vec![
+ Some("10"),
+ Some("1 minute"),
+ Some("1 day"),
+ None,
+ ])) as ArrayRef,
+ Arc::new(StringViewArray::from(vec![
+ Some("10"),
+ Some("1 minute"),
+ Some("1 day"),
+ None,
+ ])) as ArrayRef,
+ ] {
+ let casted = cast(&array, &to_type).unwrap();
+ assert_eq!(
+ casted.as_primitive::<DurationNanosecondType>(),
+ &DurationNanosecondArray::from(vec![
+ Some(10),
+ Some(60_000_000_000),
+ Some(86_400_000_000_000),
+ None
+ ])
+ );
+ }
+ }
+
#[test]
fn test_cast_date32_to_int32() {
let array = Date32Array::from(vec![10000, 17890]);
diff --git a/arrow-cast/src/cast/string.rs b/arrow-cast/src/cast/string.rs
index 221b52bc69..0844f11c35 100644
--- a/arrow-cast/src/cast/string.rs
+++ b/arrow-cast/src/cast/string.rs
@@ -3,6 +3,10 @@
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
use crate::cast::*;
+use crate::parse::{
+ IntervalParseConfig, IntervalUnit as IntervalParseUnit, NANOS_PER_DAY,
+ parse_interval_month_day_nano_config,
+};
use arrow_buffer::NullBuffer;
pub(crate) fn cast_bool_to_string<A>(array: &dyn Array) -> Result<ArrayRef,
ArrowError>
@@ -119,6 +123,113 @@ fn parse_string_iter<
Ok(Arc::new(array) as ArrayRef)
}
+/// Parse a string to a duration, accepting integer strings (interpreted
+/// in the target unit) and interval strings with units, such as
+/// `"1 hour 10 minutes"`.
+fn parse_duration<D>(string: &str) -> Result<i64, ArrowError>
+where
+ D: ArrowTemporalType<Native = i64> + Parser,
+{
+ if let Some(duration) = D::parse(string) {
+ return Ok(duration);
+ }
+
+ let (unit, scale) = match D::DATA_TYPE {
+ DataType::Duration(TimeUnit::Second) => (IntervalParseUnit::Second,
1_000_000_000),
+ DataType::Duration(TimeUnit::Millisecond) =>
(IntervalParseUnit::Millisecond, 1_000_000),
+ DataType::Duration(TimeUnit::Microsecond) =>
(IntervalParseUnit::Microsecond, 1_000),
+ DataType::Duration(TimeUnit::Nanosecond) =>
(IntervalParseUnit::Nanosecond, 1),
+ _ => unreachable!(),
+ };
+
+ let interval = parse_interval_month_day_nano_config(
+ string,
+ IntervalParseConfig::new(unit).reject_fractional_calendar_units(),
+ )
+ .map_err(|_| {
+ ArrowError::CastError(format!(
+ "Cannot cast string '{string}' to value of {} type",
+ D::DATA_TYPE
+ ))
+ })?;
+
+ if interval.months != 0 {
+ return Err(ArrowError::ComputeError(
+ "Cannot convert interval containing non-zero months to
duration".to_string(),
+ ));
+ }
+
+ let nanos = NANOS_PER_DAY as i128 * interval.days as i128 +
interval.nanoseconds as i128;
+ i64::try_from(nanos / scale as i128).map_err(|_| {
+ ArrowError::CastError(format!(
+ "Cannot cast string '{string}' to value of {} type",
+ D::DATA_TYPE
+ ))
+ })
+}
+
+/// Casts generic string arrays to a Duration type
+pub(crate) fn cast_string_to_duration<D, O>(
+ array: &dyn Array,
+ cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+ D: ArrowTemporalType<Native = i64> + Parser,
+ O: OffsetSizeTrait,
+{
+ let string_array = array.as_string::<O>();
+ parse_duration_iter::<D, _>(
+ string_array.iter(),
+ cast_options,
+ string_array.nulls().cloned(),
+ )
+}
+
+/// Casts string view arrays to a Duration type
+pub(crate) fn cast_view_to_duration<D>(
+ array: &dyn Array,
+ cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError>
+where
+ D: ArrowTemporalType<Native = i64> + Parser,
+{
+ let string_view_array = array.as_string_view();
+ parse_duration_iter::<D, _>(
+ string_view_array.iter(),
+ cast_options,
+ string_view_array.nulls().cloned(),
+ )
+}
+
+fn parse_duration_iter<'a, D, I>(
+ iter: I,
+ cast_options: &CastOptions,
+ nulls: Option<NullBuffer>,
+) -> Result<ArrayRef, ArrowError>
+where
+ D: ArrowTemporalType<Native = i64> + Parser,
+ I: Iterator<Item = Option<&'a str>>,
+{
+ let array = if cast_options.safe {
+ let iter = iter.map(|x| {
+ let v = x?;
+ parse_duration::<D>(v).ok()
+ });
+
+ unsafe { PrimitiveArray::<D>::from_trusted_len_iter(iter) }
+ } else {
+ let v = iter
+ .map(|x| match x {
+ Some(v) => parse_duration::<D>(v),
+ None => Ok(D::Native::default()),
+ })
+ .collect::<Result<Vec<_>, ArrowError>>()?;
+ PrimitiveArray::try_new(v.into(), nulls)?
+ };
+
+ Ok(Arc::new(array) as ArrayRef)
+}
+
/// Casts generic string arrays to an ArrowTimestampType
(TimeStampNanosecondArray, etc.)
pub(crate) fn cast_string_to_timestamp<O: OffsetSizeTrait, T:
ArrowTimestampType>(
array: &dyn Array,
diff --git a/arrow-cast/src/parse.rs b/arrow-cast/src/parse.rs
index f0b444c623..65a33eea27 100644
--- a/arrow-cast/src/parse.rs
+++ b/arrow-cast/src/parse.rs
@@ -1324,23 +1324,36 @@ const NANOS_PER_MILLIS: i64 = 1_000_000;
const NANOS_PER_SECOND: i64 = 1_000 * NANOS_PER_MILLIS;
const NANOS_PER_MINUTE: i64 = 60 * NANOS_PER_SECOND;
const NANOS_PER_HOUR: i64 = 60 * NANOS_PER_MINUTE;
-#[cfg(test)]
-const NANOS_PER_DAY: i64 = 24 * NANOS_PER_HOUR;
+pub(crate) const NANOS_PER_DAY: i64 = 24 * NANOS_PER_HOUR;
/// Config to parse interval strings
///
-/// Currently stores the `default_unit` to use if the string doesn't have one
specified
+/// Stores the `default_unit` to use if the string doesn't have one specified,
+/// and whether fractional calendar units may be spilled into smaller units.
#[derive(Debug, Clone)]
pub struct IntervalParseConfig {
/// The default unit to use if none is specified
/// e.g. `INTERVAL 1` represents `INTERVAL 1 SECOND` when default_unit =
[IntervalUnit::Second]
default_unit: IntervalUnit,
+ /// Whether fractional calendar units (centuries, decades, years, months)
+ /// may be spilled into smaller units. `0.5 months` is parsed as 15 days
+ /// when this is `true`.
+ allow_fractional_calendar_units: bool,
}
impl IntervalParseConfig {
/// Create a new [IntervalParseConfig] with the given default unit
pub fn new(default_unit: IntervalUnit) -> Self {
- Self { default_unit }
+ Self {
+ default_unit,
+ allow_fractional_calendar_units: true,
+ }
+ }
+
+ /// Reject fractional calendar units instead of spilling them into smaller
units
+ pub(crate) fn reject_fractional_calendar_units(mut self) -> Self {
+ self.allow_fractional_calendar_units = false;
+ self
}
}
@@ -1418,6 +1431,13 @@ impl IntervalUnit {
None => Ok(config.default_unit),
}
}
+
+ fn is_calendar_unit(self) -> bool {
+ matches!(
+ self,
+ Self::Century | Self::Decade | Self::Year | Self::Month
+ )
+ }
}
/// A tuple representing (months, days, nanoseconds) in an interval
@@ -1736,6 +1756,16 @@ fn parse_interval_components(
)));
};
+ if !config.allow_fractional_calendar_units {
+ for (amount, unit) in &pairs {
+ if amount.frac != 0 && unit.is_calendar_unit() {
+ return Err(ArrowError::ParseError(format!(
+ "Fractional calendar units are not supported: {value:?}"
+ )));
+ }
+ }
+ }
+
// collect parsed results
let (amounts, units): (Vec<_>, Vec<_>) = pairs.into_iter().unzip();