Skip to content

Commit

Permalink
feat: support ISO 8601 interval parsing (#14747)
Browse files Browse the repository at this point in the history
  • Loading branch information
xuefengze authored Jan 24, 2024
1 parent a9ce6c7 commit bf777a0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
18 changes: 18 additions & 0 deletions e2e_test/batch/types/interval.slt.part
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,24 @@ select v / d from t;
00:01:19.101562
00:03:57.304688

query T
select 'P1Y2M3DT4H5M6S'::interval;
----
1 year 2 mons 3 days 04:05:06

query T
select 'P0Y0M0DT0H0M0S'::interval;
----
00:00:00

query T
select 'P12Y2M30DT4H5M0.1234567S'::interval;
----
12 years 2 mons 30 days 04:05:00.123456

statement error
select 'P0Y0M0DT0H0M0S1'::interval;

# The following is an overflow bug present in PostgreSQL 15.2
# Their `days` overflows to a negative value, leading to the latter smaller
# than the former. We report an error in this case.
Expand Down
13 changes: 11 additions & 2 deletions src/common/src/types/interval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,7 @@ impl Interval {
pub fn from_iso_8601(s: &str) -> ParseResult<Self> {
// ISO pattern - PnYnMnDTnHnMnS
static ISO_8601_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"P([0-9]+)Y([0-9]+)M([0-9]+)DT([0-9]+)H([0-9]+)M([0-9]+(?:\.[0-9]+)?)S")
Regex::new(r"^P([0-9]+)Y([0-9]+)M([0-9]+)DT([0-9]+)H([0-9]+)M([0-9]+(?:\.[0-9]+)?)S$")
.unwrap()
});
// wrap into a closure to simplify error handling
Expand Down Expand Up @@ -1453,7 +1453,10 @@ impl Interval {
if let Some(leading_field) = leading_field {
Self::parse_sql_standard(s, leading_field)
} else {
Self::parse_postgres(s)
match s.as_bytes().get(0) {
Some(b'P') => Self::from_iso_8601(s),
_ => Self::parse_postgres(s),
}
}
}
}
Expand Down Expand Up @@ -1530,6 +1533,12 @@ mod tests {
interval,
Interval::from_month(14) + Interval::from_days(3) + Interval::from_minutes(62)
);

let interval = "P1Y2M3DT0H5M0S".parse::<Interval>().unwrap();
assert_eq!(
interval,
Interval::from_month(14) + Interval::from_days(3) + Interval::from_minutes(5)
);
}

#[test]
Expand Down

0 comments on commit bf777a0

Please sign in to comment.