diff --git a/src/expr/src/scalar/func/impls/timestamp.rs b/src/expr/src/scalar/func/impls/timestamp.rs index f32f179618ce6..67101b913c809 100644 --- a/src/expr/src/scalar/func/impls/timestamp.rs +++ b/src/expr/src/scalar/func/impls/timestamp.rs @@ -9,9 +9,7 @@ use std::fmt; -use chrono::{ - DateTime, Duration, FixedOffset, NaiveDateTime, NaiveTime, Offset, TimeZone, Timelike, Utc, -}; +use chrono::{DateTime, Duration, NaiveDateTime, NaiveTime, Offset, TimeZone, Utc}; use mz_expr_derive::sqlfunc; use mz_ore::result::ResultExt; use mz_pgtz::timezone::{Timezone, TimezoneSpec}; @@ -19,7 +17,10 @@ use mz_repr::adt::date::Date; use mz_repr::adt::datetime::DateTimeUnits; use mz_repr::adt::interval::Interval; use mz_repr::adt::numeric::{DecimalLike, Numeric}; -use mz_repr::adt::timestamp::{CheckedTimestamp, MAX_PRECISION, TimestampPrecision}; +use mz_repr::adt::timestamp::{ + CheckedTimestamp, MAX_PRECISION, TimestampPrecision, checked_add_with_leapsecond, + checked_sub_with_leapsecond, +}; use mz_repr::{SqlColumnType, SqlScalarType, strconv}; use serde::{Deserialize, Serialize}; @@ -730,42 +731,6 @@ pub fn timezone_timestamptz(tz: Timezone, utc: DateTime) -> Result Option { - // extract and temporarily remove the fractional part and later recover it - let nanos = lhs.nanosecond(); - let lhs = lhs.with_nanosecond(0).unwrap(); - let rhs = rhs.local_minus_utc(); - let dt = lhs.checked_add_signed(chrono::Duration::try_seconds(i64::from(rhs))?)?; - // chrono represents a leap second as `nanos >= 1_000_000_000`, but only on a - // second-of-minute of 59. If the offset shifted us off `:59`, we can't keep - // the leap-second representation: the resulting `NaiveTime` would be - // unconstructable via `from_num_seconds_from_midnight_opt` and would panic - // when round-tripped through `Row` encoding. In that case, fold the leap - // second into the next regular second. - if nanos >= 1_000_000_000 && dt.second() != 59 { - dt.checked_add_signed(chrono::Duration::nanoseconds(i64::from(nanos))) - } else { - Some(dt.with_nanosecond(nanos).unwrap()) - } -} - -/// Checked subtraction that is missing from chrono. Adapt its methods here but add a check. -fn checked_sub_with_leapsecond(lhs: &NaiveDateTime, rhs: &FixedOffset) -> Option { - // extract and temporarily remove the fractional part and later recover it - let nanos = lhs.nanosecond(); - let lhs = lhs.with_nanosecond(0).unwrap(); - let rhs = rhs.local_minus_utc(); - let dt = lhs.checked_sub_signed(chrono::Duration::try_seconds(i64::from(rhs))?)?; - // See `checked_add_with_leapsecond` for why we have to special-case - // leap-second nanos that no longer land on `:59` after applying the offset. - if nanos >= 1_000_000_000 && dt.second() != 59 { - dt.checked_add_signed(chrono::Duration::nanoseconds(i64::from(nanos))) - } else { - Some(dt.with_nanosecond(nanos).unwrap()) - } -} - #[derive( Ord, PartialOrd, diff --git a/src/repr/src/adt/timestamp.rs b/src/repr/src/adt/timestamp.rs index 019d657567df2..ca24df9df7caa 100644 --- a/src/repr/src/adt/timestamp.rs +++ b/src/repr/src/adt/timestamp.rs @@ -24,7 +24,8 @@ use std::ops::Sub; use std::sync::LazyLock; use ::chrono::{ - DateTime, Datelike, Days, Duration, Months, NaiveDate, NaiveDateTime, NaiveTime, Utc, + DateTime, Datelike, Days, Duration, FixedOffset, Months, NaiveDate, NaiveDateTime, NaiveTime, + Utc, }; use chrono::Timelike; use mz_ore::cast::{self, CastFrom}; @@ -787,6 +788,10 @@ impl CheckedTimestamp { } /// Rounds the timestamp to the specified number of digits of precision. + /// + /// Returns [`TimestampError::OutOfRange`] when rounding up would leave + /// chrono's representable range, which the last microsecond of + /// [`HIGH_DATE`] does for every precision. pub fn round_to_precision( &self, precision: Option, @@ -809,7 +814,11 @@ impl CheckedTimestamp { let seventh_digit = (nanoseconds % 1_000) / 100; assert!(seventh_digit < 10); if seventh_digit >= 5 { - original = original + Duration::microseconds(1); + // Checked, not `+`: on the last microsecond of `HIGH_DATE` this + // nudge leaves chrono's range, and chrono's `Add` panics there. + original = original + .checked_add_signed(Duration::microseconds(1)) + .ok_or(TimestampError::OutOfRange)?; } // this is copied from [`chrono::round::duration_round`] // but using microseconds instead of nanoseconds precision @@ -824,11 +833,14 @@ impl CheckedTimestamp { } else { (round_to_micros - delta_down, delta_down) }; + // Both directions are checked for the same reason as the + // seventh-digit nudge above. if delta_up <= delta_down { - original + Duration::microseconds(delta_up) + original.checked_add_signed(Duration::microseconds(delta_up)) } else { - original - Duration::microseconds(delta_down) + original.checked_sub_signed(Duration::microseconds(delta_down)) } + .ok_or(TimestampError::OutOfRange)? } }; @@ -1040,11 +1052,58 @@ impl FixedSizeCodec for PackedNaiveDateTime { } } +/// Adds a fixed offset to `lhs`, returning `None` on overflow. +/// +/// chrono's own `NaiveDateTime + FixedOffset` panics on overflow, so this is the +/// only safe way to shift a timestamp that may sit at the edge of chrono's +/// range. Beyond the overflow check it also normalizes a leap second that the +/// shift moves off `:59`, see the note in the body. +pub fn checked_add_with_leapsecond( + lhs: &NaiveDateTime, + rhs: &FixedOffset, +) -> Option { + checked_offset_with_leapsecond(lhs, rhs.local_minus_utc()) +} + +/// Subtracts a fixed offset from `lhs`, returning `None` on overflow. +/// +/// The mirror of [`checked_add_with_leapsecond`], with the same guarantees. +pub fn checked_sub_with_leapsecond( + lhs: &NaiveDateTime, + rhs: &FixedOffset, +) -> Option { + checked_offset_with_leapsecond(lhs, rhs.local_minus_utc().checked_neg()?) +} + +/// Shifts `lhs` by `seconds`, keeping a leap second representable. +fn checked_offset_with_leapsecond(lhs: &NaiveDateTime, seconds: i32) -> Option { + // The fractional part is set aside so that the shift operates on whole + // seconds only, then recovered below. + let nanos = lhs.nanosecond(); + let whole = lhs.with_nanosecond(0).expect("0 is a valid nanosecond"); + let dt = whole.checked_add_signed(Duration::try_seconds(i64::from(seconds))?)?; + // chrono represents a leap second as `nanos >= 1_000_000_000`, but only on a + // second-of-minute of 59. If the shift moved us off `:59`, we can't keep the + // leap-second representation: the resulting `NaiveTime` would be + // unconstructable via `from_num_seconds_from_midnight_opt` and would panic + // when round-tripped through `Row` encoding. In that case, fold the leap + // second into the next regular second, which is also what PostgreSQL does + // with a `:60` literal. + if nanos >= 1_000_000_000 && dt.second() != 59 { + dt.checked_add_signed(Duration::nanoseconds(i64::from(nanos))) + } else { + Some( + dt.with_nanosecond(nanos) + .expect("nanos came from a NaiveTime"), + ) + } +} + #[cfg(test)] mod test { use super::*; use itertools::Itertools; - use mz_ore::assert_err; + use mz_ore::{assert_err, assert_ok}; use proptest::prelude::*; #[mz_ore::test] @@ -1142,6 +1201,46 @@ mod test { } } + #[mz_ore::test] + fn test_round_to_precision_high_date_overflow() { + // `HIGH_DATE` is exactly `NaiveDate::MAX`, so rounding *up* from the last + // fraction of that day leaves chrono's range. Both the seventh-digit + // nudge and the rounding branch used unchecked `+`, which panics in + // chrono rather than returning an error. + // + // A precision below 6 reaches this with far fewer fractional digits than + // the microsecond default: at precision 0 a single `.5` rounds up a whole + // second. Every precision is covered because each has its own quantum. + for (nanos, precision) in [ + (999_999_500, None), + (500_000_000, Some(0)), + (950_000_000, Some(1)), + (995_000_000, Some(2)), + (999_500_000, Some(3)), + (999_950_000, Some(4)), + (999_995_000, Some(5)), + (999_999_500, Some(6)), + ] { + let ts = + CheckedTimestamp::try_from(HIGH_DATE.and_hms_nano_opt(23, 59, 59, nanos).unwrap()) + .unwrap(); + assert!( + matches!( + ts.round_to_precision(precision.map(TimestampPrecision)), + Err(TimestampError::OutOfRange) + ), + "rounding {nanos}ns to {precision:?} should report out of range" + ); + } + + // The mirror case: rounding *down* stays in range, so it must still + // succeed rather than being caught by an over-broad check. + let ts = + CheckedTimestamp::try_from(HIGH_DATE.and_hms_nano_opt(23, 59, 59, 400_000).unwrap()) + .unwrap(); + assert_ok!(ts.round_to_precision(Some(TimestampPrecision(3)))); + } + #[mz_ore::test] fn test_precision_edge_cases() { #[allow(clippy::disallowed_methods)] // not using enhanced panic handler in tests diff --git a/src/repr/src/strconv.rs b/src/repr/src/strconv.rs index e5be98b9ba413..89d6f83b7b74f 100644 --- a/src/repr/src/strconv.rs +++ b/src/repr/src/strconv.rs @@ -58,7 +58,7 @@ use crate::adt::mz_acl_item::{AclItem, MzAclItem}; use crate::adt::numeric::{self, NUMERIC_DATUM_MAX_PRECISION, Numeric}; use crate::adt::pg_legacy_name::NAME_MAX_BYTES; use crate::adt::range::{Range, RangeBound, RangeInner}; -use crate::adt::timestamp::CheckedTimestamp; +use crate::adt::timestamp::{CheckedTimestamp, checked_sub_with_leapsecond}; include!(concat!(env!("OUT_DIR"), "/mz_repr.strconv.rs")); @@ -477,6 +477,11 @@ where write!(buf, "{:04}-{}", year, d.format("%m-%d")); if !year_ad { write!(buf, " BC"); + // The ` BC` suffix carries whitespace, which every element escaper + // treats as needing quotes. `Nestable::Yes` is only for renderings that + // can *never* need escaping, so it would be a lie here. A Common Era + // date is plain `YYYY-MM-DD` and keeps the cheaper answer. + return Nestable::MayNeedEscaping; } Nestable::Yes } @@ -489,18 +494,71 @@ where /// [ [ ] ] /// ``` pub fn parse_time(s: &str) -> Result { + parse_time_inner(s, TimeFields::Required) +} + +/// Parses a `NaiveTime` from `s`, resolving a string that names no time field at +/// all to midnight. +/// +/// NOTE: This exists solely to keep the storage source cast `CastStringToTime` +/// evaluation-stable across releases (see the stability contract in +/// `mz_storage_types::sources::casts`). Use [`parse_time`] everywhere else. +pub fn parse_time_legacy(s: &str) -> Result { + parse_time_inner(s, TimeFields::Optional) +} + +/// Whether a TIME string has to name at least one time field. +enum TimeFields { + /// Reject a string that names none, as PostgreSQL does. + Required, + /// Read a string that names none as midnight. + Optional, +} + +fn parse_time_inner(s: &str, fields: TimeFields) -> Result { ParsedDateTime::build_parsed_datetime_time(s) - .and_then(|pdt| pdt.compute_time()) + .and_then(|pdt| { + // A string carrying no time field at all, `""` or `":"`, tokenizes + // to nothing the time grammar has to consume, so it parses without + // filling a single field and every field then defaults to zero. + // PostgreSQL rejects such a string rather than reading it as + // midnight. Hour, minute and second are the only fields the time + // grammar fills, and the only ones `compute_time` reads. + if matches!(fields, TimeFields::Required) + && pdt.hour.is_none() + && pdt.minute.is_none() + && pdt.second.is_none() + { + return Err("no time fields found".into()); + } + pdt.compute_time() + }) .map_err(|e| ParseError::invalid_input_syntax("time", s).with_details(e)) } -/// Writes a [`NaiveDateTime`] timestamp to `buf`. +/// Writes a [`NaiveTime`] to `buf`. pub fn format_time(buf: &mut F, t: NaiveTime) -> Nestable where F: FormatBuffer, { + let (carry, micros) = split_nanos_to_micros(t.nanosecond()); + // A carry out of the last second of the day has nowhere to go: a + // `NaiveTime` wraps to midnight rather than reaching PostgreSQL's + // `24:00:00`, and rendering a time a whole day early is a worse lie than + // dropping the carry. Saturate at the largest renderable fraction instead. + let (t, micros) = match carry { + false => (t, micros), + true => match t + .with_nanosecond(0) + .expect("0 is a valid nanosecond") + .overflowing_add_signed(Duration::seconds(1)) + { + (carried, 0) => (carried, 0), + (_, _wrapped) => (t, MICROS_PER_SECOND - 1), + }, + }; write!(buf, "{}", t.format("%H:%M:%S")); - format_nanos_to_micros(buf, t.nanosecond()); + format_micros(buf, micros); Nestable::Yes } @@ -536,9 +594,10 @@ pub fn format_timestamp(buf: &mut F, ts: &NaiveDateTime) -> Nestable where F: FormatBuffer, { + let (ts, micros) = round_to_micros(*ts); let (year_ad, year) = ts.year_ce(); write!(buf, "{:04}-{}", year, ts.format("%m-%d %H:%M:%S")); - format_nanos_to_micros(buf, ts.and_utc().timestamp_subsec_nanos()); + format_micros(buf, micros); if !year_ad { write!(buf, " BC"); } @@ -566,32 +625,35 @@ fn parse_timestamptz_inner( s: &str, order: DateOrder, ) -> Result>, ParseError> { - parse_timestamp_string(s, order) - .and_then(|(date, time, timezone)| { - use Timezone::*; - let mut dt = date.and_time(time); - let offset = match timezone { - FixedOffset(offset) => offset, - Tz(tz) => match tz.offset_from_local_datetime(&dt).latest() { - Some(offset) => offset.fix(), - None => { - dt += Duration::try_hours(1).unwrap(); - tz.offset_from_local_datetime(&dt) - .latest() - .ok_or_else(|| "invalid timezone conversion".to_owned())? - .fix() - } - }, - }; - Ok(DateTime::from_naive_utc_and_offset(dt - offset, Utc)) - }) - .map_err(|e| { - ParseError::invalid_input_syntax("timestamp with time zone", s).with_details(e) - }) - .and_then(|ts| { - CheckedTimestamp::from_timestamplike(ts) - .map_err(|_| ParseError::out_of_range("timestamp with time zone", s)) - }) + let invalid_syntax = |details: String| { + ParseError::invalid_input_syntax("timestamp with time zone", s).with_details(details) + }; + let out_of_range = || ParseError::out_of_range("timestamp with time zone", s); + + let (date, time, timezone) = parse_timestamp_string(s, order).map_err(&invalid_syntax)?; + let mut dt = date.and_time(time); + let offset = match timezone { + Timezone::FixedOffset(offset) => offset, + Timezone::Tz(tz) => match tz.offset_from_local_datetime(&dt).latest() { + Some(offset) => offset.fix(), + None => { + dt = dt + .checked_add_signed(Duration::try_hours(1).unwrap()) + .ok_or_else(out_of_range)?; + tz.offset_from_local_datetime(&dt) + .latest() + .ok_or_else(|| invalid_syntax("invalid timezone conversion".to_owned()))? + .fix() + } + }, + }; + // `HIGH_DATE` is exactly `NaiveDate::MAX`, so applying a westward offset to + // a time late on that day leaves chrono's range, and chrono's own + // `NaiveDateTime - FixedOffset` panics there. This runs before the + // `CheckedTimestamp` bound check below, so that check cannot save it. + let dt = checked_sub_with_leapsecond(&dt, &offset).ok_or_else(out_of_range)?; + CheckedTimestamp::from_timestamplike(DateTime::from_naive_utc_and_offset(dt, Utc)) + .map_err(|_| out_of_range()) } /// Writes a [`DateTime`] timestamp to `buf`. @@ -599,9 +661,10 @@ pub fn format_timestamptz(buf: &mut F, ts: &DateTime) -> Nestable where F: FormatBuffer, { + let (ts, micros) = round_to_micros(ts.naive_utc()); let (year_ad, year) = ts.year_ce(); write!(buf, "{:04}-{}", year, ts.format("%m-%d %H:%M:%S")); - format_nanos_to_micros(buf, ts.timestamp_subsec_nanos()); + format_micros(buf, micros); write!(buf, "+00"); if !year_ad { write!(buf, " BC"); @@ -834,24 +897,79 @@ where Nestable::Yes } -fn format_nanos_to_micros(buf: &mut F, nanos: u32) +const NANOS_PER_SECOND: u32 = 1_000_000_000; +const MICROS_PER_SECOND: u32 = 1_000_000; + +/// Splits a sub-second nanosecond count into a whole-second carry and the +/// microsecond fraction to render, rounding half away from zero. +/// +/// The returned fraction is always below one second, so it can never be written +/// as a fractional field of more than six digits. Only a nanosecond count of +/// `.9999995` or more produces a carry. +/// +/// chrono spells a leap second as a nanosecond count of one second or more, and +/// its `%S` already accounts for that, rendering `60` on a second-of-minute of +/// 59 and folding into the next second elsewhere. The leap second is therefore +/// already in the seconds field and only the part below one second is ours to +/// write. +fn split_nanos_to_micros(nanos: u32) -> (bool, u32) { + let micros = (nanos % NANOS_PER_SECOND + 500) / 1_000; + if micros >= MICROS_PER_SECOND { + (true, 0) + } else { + (false, micros) + } +} + +/// Rounds `ts` to microseconds, returning the value whose date and seconds are +/// to be rendered plus the fraction to append to it. +/// +/// A fraction that rounds up to a full second is carried into the seconds field +/// rather than written as a fractional `1_000_000` microseconds, which the +/// trailing-zero stripper would turn into a nonsense `.1`, roughly one second +/// early. At the very end of chrono's range the carry has nowhere to go, so the +/// fraction saturates at `.999999` rather than the value rolling over to an +/// unrepresentable date. +fn round_to_micros(ts: NaiveDateTime) -> (NaiveDateTime, u32) { + let (carry, micros) = split_nanos_to_micros(ts.and_utc().timestamp_subsec_nanos()); + if !carry { + return (ts, micros); + } + // Dropping the fraction before adding the second is what makes this correct + // for a leap second too: `23:59:59` plus chrono's leap nanos is `23:59:60`, + // and the second after it is `00:00:00` of the next minute, which is exactly + // where clearing the nanos and adding a second lands. + match ts + .with_nanosecond(0) + .expect("0 is a valid nanosecond") + .checked_add_signed(Duration::seconds(1)) + { + Some(carried) => (carried, 0), + None => (ts, MICROS_PER_SECOND - 1), + } +} + +/// Writes a microsecond fraction to `buf` with trailing zeros stripped, or +/// nothing at all when it is zero. +/// +/// `micros` must be below one second, which is what [`split_nanos_to_micros`] +/// guarantees. A larger value would be written as a fraction it does not fit +/// in, silently shifting the rendered time by about a second. +fn format_micros(buf: &mut F, micros: u32) where F: FormatBuffer, { - if nanos >= 500 { - let mut micros = nanos / 1000; - let rem = nanos % 1000; - if rem >= 500 { - micros += 1; - } - // strip trailing zeros - let mut width = 6; - while micros % 10 == 0 { - width -= 1; - micros /= 10; - } - write!(buf, ".{:0width$}", micros, width = width); + assert!(micros < MICROS_PER_SECOND); + if micros == 0 { + return; } + let mut micros = micros; + let mut width = 6; + while micros % 10 == 0 { + width -= 1; + micros /= 10; + } + write!(buf, ".{:0width$}", micros, width = width); } #[derive(Debug, thiserror::Error)] @@ -1577,6 +1695,16 @@ where let lower_bound = match buf.peek() { Some(',') => None, + // A bound whose rendering needs escaping is emitted quoted by + // `format_range`, so the quotes have to come back off here. Without this + // the raw substring reaches the element parser, which mostly tolerates a + // stray `"` and then misreads it the moment it abuts a meaningful token, + // for example the `BC"` of a pre-Common-Era date or timestamp. + Some('"') => { + let v = lex_quoted_element(buf)?; + let v = gen_elem(v).map_err(|e| e.to_string())?; + Some(v) + } Some(_) => { let v = buf.take_while(|c| !matches!(c, ',')); let v = gen_elem(Cow::from(v)).map_err(|e| e.to_string())?; @@ -1593,6 +1721,12 @@ where let upper_bound = match buf.peek() { Some(']' | ')') => None, + // See the lower bound above. + Some('"') => { + let v = lex_quoted_element(buf)?; + let v = gen_elem(v).map_err(|e| e.to_string())?; + Some(v) + } Some(_) => { let v = buf.take_while(|c| !matches!(c, ')' | ']')); let v = gen_elem(Cow::from(v)).map_err(|e| e.to_string())?; @@ -2257,22 +2391,31 @@ mod tests { } #[mz_ore::test] - fn test_format_nanos_to_micros() { - let cases: Vec<(u32, &str)> = vec![ - (0, ""), - (1, ""), - (499, ""), - (500, ".000001"), - (500_000, ".0005"), - (5_000_000, ".005"), - // Leap second. This is possibly wrong and should maybe be reduced (nanosecond - // % 1_000_000_000), but we are at least now aware it does this. - (1_999_999_999, ".2"), + fn test_split_nanos_to_micros() { + let cases: Vec<(u32, bool, &str)> = vec![ + (0, false, ""), + (1, false, ""), + (499, false, ""), + (500, false, ".000001"), + (500_000, false, ".0005"), + (5_000_000, false, ".005"), + (999_999_499, false, ".999999"), + // Rounds up to a full second, which belongs in the seconds field. + // Written as a fraction it would render as `.1`. + (999_999_500, true, ""), + (999_999_900, true, ""), + // chrono's leap-second representation. The leap is already in the + // seconds field, so only the part below one second is rendered. + (1_000_000_000, false, ""), + (1_500_000_000, false, ".5"), + (1_999_999_999, true, ""), ]; - for (nanos, expect) in cases { + for (nanos, expect_carry, expect) in cases { + let (carry, micros) = split_nanos_to_micros(nanos); + assert_eq!(carry, expect_carry, "carry for {nanos}ns"); let mut buf = String::new(); - format_nanos_to_micros(&mut buf, nanos); - assert_eq!(&buf, expect); + format_micros(&mut buf, micros); + assert_eq!(&buf, expect, "fraction for {nanos}ns"); } } diff --git a/src/repr/tests/strconv.rs b/src/repr/tests/strconv.rs index 58364213a2ea1..75fedaab27e1c 100644 --- a/src/repr/tests/strconv.rs +++ b/src/repr/tests/strconv.rs @@ -7,7 +7,7 @@ // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. -use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc}; +use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Utc}; use mz_repr::adt::date::Date; use mz_repr::adt::datetime::DateTimeField; use mz_repr::adt::interval::Interval; @@ -142,6 +142,20 @@ fn test_parse_time_errors() { "03.456", "invalid input syntax for type time: have unprocessed tokens 3.456000000: \"03.456\"", ); + // A string that parses without naming a single time field is rejected rather + // than read as midnight, matching PostgreSQL. + run_test_parse_time_errors( + "", + "invalid input syntax for type time: no time fields found: \"\"", + ); + run_test_parse_time_errors( + " ", + "invalid input syntax for type time: no time fields found: \" \"", + ); + run_test_parse_time_errors( + ":", + "invalid input syntax for type time: no time fields found: \":\"", + ); fn run_test_parse_time_errors(s: &str, e: &str) { assert_eq!( @@ -151,6 +165,24 @@ fn test_parse_time_errors() { } } +/// The frozen storage-cast reading of a TIME string with no time field in it. +/// See the stability contract in `mz_storage_types::sources::casts`. +#[mz_ore::test] +fn test_parse_time_legacy_fieldless() { + for s in ["", " ", ":"] { + assert_eq!( + strconv::parse_time_legacy(s).unwrap(), + NaiveTime::from_hms_opt(0, 0, 0).unwrap(), + "for input {s:?}" + ); + } + // Everything else parses identically to `parse_time`. + assert_eq!( + strconv::parse_time_legacy("01:02:03").unwrap(), + strconv::parse_time("01:02:03").unwrap() + ); +} + #[mz_ore::test] fn test_parse_timestamp() { use mz_repr::adt::timestamp::CheckedTimestamp; @@ -314,6 +346,63 @@ fn test_parse_timestamptz_errors() { } } +#[mz_ore::test] +fn test_parse_timestamptz_offset_overflow() { + // `HIGH_DATE` is exactly `chrono::NaiveDate::MAX` and the low bound is + // PostgreSQL's 4713 BC, so applying the offset to a value just inside either + // bound leaves chrono's range. The offset is applied before the + // `CheckedTimestamp` bound check, so that check cannot catch it, and chrono's + // own `NaiveDateTime - FixedOffset` panics instead of erroring. + for s in [ + // High end: a westward offset moves the value past `NaiveDate::MAX`. One + // second of offset is enough on the last second of the day. + "262142-12-31 23:00:00-01", + "262142-12-31 23:59:59-00:00:01", + // Low end: an eastward offset moves the value below chrono's minimum, + // January 1, 262144 BCE. + "262144-01-01 00:00:00+01 BC", + "262144-01-01 00:00:00+00:00:01 BC", + ] { + assert_eq!( + format!("{}", strconv::parse_timestamptz(s).unwrap_err()), + format!("{s:?} is out of range for type timestamp with time zone"), + ); + } + + // The opposite offset direction on the high boundary stays in range and is + // still accepted, so the check is not simply rejecting the boundary day. The + // low boundary has no such counterpart: `LOW_DATE` is 4713 BC, far above + // chrono's minimum, so every value near that minimum is rejected either way. + assert!(strconv::parse_timestamptz("262142-12-31 23:00:00+01").is_ok()); + assert!(strconv::parse_timestamptz("262142-12-31 23:59:59+00:00:01").is_ok()); +} + +#[mz_ore::test] +fn test_parse_timestamptz_leap_second_offset_fold() { + // A parsed `:60` becomes chrono's leap-second representation (sub-second + // >= 1s), which is only representable at a second-of-minute of 59. An offset + // that is not a whole number of minutes shifts it off `:59`, and the + // resulting value used to panic in `Row` encoding. Fold it into the next + // regular second instead, which is also what PostgreSQL does with `:60`. + for (input, expected) in [ + ("1970-01-01 00:00:60+00:00:30", "1970-01-01 00:00:30+00"), + ("1970-01-01 12:00:60-00:00:30", "1970-01-01 12:01:30+00"), + ] { + let ts = strconv::parse_timestamptz(input).unwrap(); + assert_eq!(ts.nanosecond(), 0, "leap-second nanos survived the fold"); + let mut buf = String::new(); + strconv::format_timestamptz(&mut buf, &ts); + assert_eq!(buf, expected); + } + + // A whole-minute offset keeps the value on `:59`, where the leap-second + // representation is legal, so it is preserved rather than folded. + for input in ["1970-01-01 00:00:60+01", "1970-01-01 12:00:60-05:30"] { + let ts = strconv::parse_timestamptz(input).unwrap(); + assert_eq!(ts.nanosecond(), 1_000_000_000); + } +} + #[mz_ore::test] fn test_parse_interval_monthlike() { run_test_parse_interval_monthlike( @@ -682,6 +771,83 @@ fn test_format_timestamp() { } } +#[mz_ore::test] +fn test_format_subsecond_carry() { + // A sub-second fraction of `.9999995` or more rounds up to a full second. + // The renderer writes microseconds, so that second has to reach the seconds + // field. Written into the fraction instead it becomes `1000000` microseconds, + // which the trailing-zero stripper reduces to `.1`, i.e. a value rendered + // roughly one second early with a nonsense fraction. + // + // Nothing rounds on the way in: `pgrepr`'s text decoding (COPY, text-format + // bind parameters) and the TIME cast both keep the parsed nanoseconds, so + // these values reach the renderer as stored. + for (input, expected) in [ + ("2020-01-01 00:00:00.9999999", "2020-01-01 00:00:01"), + ("2020-01-01 00:00:00.9999995", "2020-01-01 00:00:01"), + ("2020-01-01 00:00:00.9999994", "2020-01-01 00:00:00.999999"), + // The carry crosses minute, day, month and year boundaries. + ("2020-01-01 00:00:59.9999999", "2020-01-01 00:01:00"), + ("2020-01-31 23:59:59.9999999", "2020-02-01 00:00:00"), + ("2020-12-31 23:59:59.9999999", "2021-01-01 00:00:00"), + // A leap second is already in the seconds field, where chrono's `%S` + // renders it as `60`, so only the part below one second is a fraction. + // The parser rejects a *fractional* leap second, so `.5` past `:60` is + // covered below by constructing the value directly. + ("2020-01-01 23:59:60", "2020-01-01 23:59:60"), + // `HIGH_DATE` is exactly `chrono::NaiveDate::MAX`, so the carry has + // nowhere to go and the fraction saturates instead. + ( + "262142-12-31 23:59:59.9999999", + "262142-12-31 23:59:59.999999", + ), + ] { + let ts = strconv::parse_timestamp(input).unwrap(); + let mut buf = String::new(); + strconv::format_timestamp(&mut buf, &ts); + assert_eq!(buf, expected, "formatting {input}"); + + // TIMESTAMPTZ shares the renderer, so it carries identically. + let tz = strconv::parse_timestamptz(input).unwrap(); + let mut buf = String::new(); + strconv::format_timestamptz(&mut buf, &tz); + assert_eq!(buf, format!("{expected}+00"), "formatting {input} as tz"); + } + + // The renderer takes a bare `NaiveDateTime`, so it also has to hold up on a + // leap second carrying a fraction, which the parser rejects but chrono can + // represent. The second after `23:59:60` is `00:00:00` of the next minute. + for (nanos, expected) in [ + (1_500_000_000, "2020-01-01 23:59:60.5"), + (1_999_999_999, "2020-01-02 00:00:00"), + ] { + let ts = NaiveDate::from_ymd_opt(2020, 1, 1) + .unwrap() + .and_hms_opt(23, 59, 59) + .unwrap() + .with_nanosecond(nanos) + .unwrap(); + let mut buf = String::new(); + strconv::format_timestamp(&mut buf, &ts); + assert_eq!(buf, expected, "formatting {nanos}ns past 23:59:59"); + } + + for (input, expected) in [ + ("12:34:56.9999999", "12:34:57"), + ("12:34:56.9999994", "12:34:56.999999"), + ("23:59:60", "23:59:60"), + // A `NaiveTime` wraps to midnight rather than reaching PostgreSQL's + // `24:00:00`, so the carry out of the last second of the day is dropped + // and the fraction saturates. + ("23:59:59.9999999", "23:59:59.999999"), + ] { + let t = strconv::parse_time(input).unwrap(); + let mut buf = String::new(); + strconv::format_time(&mut buf, t); + assert_eq!(buf, expected, "formatting {input}"); + } +} + #[mz_ore::test] fn test_format_timestamptz() { run_test_format_timestamptz( diff --git a/src/storage-types/src/sources/casts.rs b/src/storage-types/src/sources/casts.rs index 5813a22ca80e2..2d634c4a98bfa 100644 --- a/src/storage-types/src/sources/casts.rs +++ b/src/storage-types/src/sources/casts.rs @@ -223,9 +223,17 @@ impl CastFunc { CastFunc::CastStringToDate => Ok(Datum::Date( strconv::parse_date_legacy(a).map_err(parse_err)?, )), - CastFunc::CastStringToTime => { - Ok(Datum::Time(strconv::parse_time(a).map_err(parse_err)?)) - } + // NOTE: Uses the frozen `parse_time_legacy`, which reads a string + // carrying no time field at all as midnight, to satisfy the + // stability contract above. `parse_time` now rejects such a string + // as PostgreSQL does, but replication re-casts the old tuple on + // delete, so tightening this persisted cast would let a row ingested + // as a value later be retracted as an error. A PostgreSQL `time` + // column never renders as one of those strings, so no export loses + // a value it could have had. + CastFunc::CastStringToTime => Ok(Datum::Time( + strconv::parse_time_legacy(a).map_err(parse_err)?, + )), CastFunc::CastStringToInterval => Ok(Datum::Interval( strconv::parse_interval(a).map_err(parse_err)?, )), @@ -517,6 +525,24 @@ mod tests { } } + #[mz_ore::test] + fn test_cast_string_to_time_frozen_fieldless() { + // A string carrying no time field keeps the frozen reading of midnight, + // diverging from the SQL layer, which rejects it as PostgreSQL does. + // This must not change (see the stability contract above). + let arena = RowArena::new(); + let expr = cast_col0(CastFunc::CastStringToTime); + for input in ["", " ", ":"] { + let result = expr.eval(&[Datum::String(input)], &arena).unwrap(); + let Datum::Time(t) = result else { + panic!("expected Time, got {:?}", result); + }; + let mut buf = String::new(); + strconv::format_time(&mut buf, t); + assert_eq!(buf, "00:00:00", "for input {input:?}"); + } + } + #[mz_ore::test] fn test_cast_string_to_uuid() { let arena = RowArena::new(); @@ -1128,11 +1154,15 @@ mod tests { #[mz_ore::test] fn parity_time() { use mz_expr::func::CastStringToTime; + // No fieldless input here on purpose. The storage cast is frozen on + // `parse_time_legacy`, which reads `""`, `" "` and `":"` as midnight, + // while the SQL cast rejects them, so the two intentionally diverge + // there. See `test_cast_string_to_time_frozen_fieldless`. assert_parity( "Time", CastFunc::CastStringToTime, UnaryFunc::CastStringToTime(CastStringToTime), - &["12:34:56", "bad", ""], + &["12:34:56", "bad"], ); } diff --git a/test/pgtest-mz/datums.pt b/test/pgtest-mz/datums.pt index 5b6eef6f1f89e..bec32dbac9d56 100644 --- a/test/pgtest-mz/datums.pt +++ b/test/pgtest-mz/datums.pt @@ -27,7 +27,7 @@ DataRow {"fields":["1","t","0","0","0","0","0","0","0","0","0","2000-01-01","00: DataRow {"fields":["2","f","1","1","1","1","1","1","1","1","1","4714-11-24 BC","23:59:59.999999","4714-12-31 00:00:00 BC","4714-12-31 00:00:00 BC","4714-12-31 00:00:00 BC","4714-12-31 00:00:00+00 BC","4714-12-31 00:00:00+00 BC","4714-12-31 00:00:00+00 BC","1 mon 1 day 00:00:00.000001","[255]","\\x00"," ","'"," ","false","ffffffff-ffff-ffff-ffff-ffffffffffff","4294967295","4294967295","4294967295","4294967295","NULL","18446744073709551615","=arwdUCRBNP/p"]} DataRow {"fields":["3","NULL","-1","-1","-1","65535","4294967295","18446744073709551615","-1","-1","-1","262142-12-31","NULL","262142-12-31 23:59:59","262142-12-31 23:59:59","262142-12-31 23:59:59","262142-12-31 23:59:59+00","262142-12-31 23:59:59+00","262142-12-31 23:59:59+00","-1 mons -1 days -00:00:00.000001","NULL","\\xff","'","\"","'","null","NULL","NULL","NULL","NULL","NULL","NULL","NULL","u42=/p"]} DataRow {"fields":["4","NULL","-32768","-2147483648","-9223372036854775808","255","32767","2147483647","-3.4028235e+38","-1.7976931348623157e+308","-Infinity","NULL","NULL","1970-01-01 00:00:00.123457","1970-01-01 00:00:00.123457","1970-01-01 00:00:00.123457","1970-01-01 00:00:00.123457+00","1970-01-01 00:00:00.123457+00","1970-01-01 00:00:00.123457+00","1 mon","NULL","NULL","\"",".","\"","\"\"","NULL","NULL","NULL","NULL","NULL","NULL","NULL","u42=arwdUCRBNP/p"]} -DataRow {"fields":["5","NULL","-32767","-2147483647","-9223372036854775807","256","32768","2147483648","1.1754944e-38","2.2250738585072014e-308","0","NULL","NULL","2019-07-24 23:59:60.1234","2019-07-24 23:59:60.1234","2019-07-24 23:59:60.1234","NULL","NULL","NULL","1 day","NULL","NULL",".",",",".","\" \"","NULL","NULL","NULL","NULL","NULL","NULL","NULL","=/u42"]} +DataRow {"fields":["5","NULL","-32767","-2147483647","-9223372036854775807","256","32768","2147483648","1.1754944e-38","2.2250738585072014e-308","0","NULL","NULL","2019-07-24 23:59:60.234","2019-07-24 23:59:60.234","2019-07-24 23:59:60.234","NULL","NULL","NULL","1 day","NULL","NULL",".",",",".","\" \"","NULL","NULL","NULL","NULL","NULL","NULL","NULL","=/u42"]} DataRow {"fields":["6","NULL","32767","2147483647","9223372036854775807","NULL","NULL","NULL","3.4028235e+38","1.7976931348623157e+308","Infinity","NULL","NULL","NULL","NULL","NULL","NULL","NULL","NULL","00:00:00.000001","NULL","NULL","2015-09-18T23:56:04.123Z","\t","2015-09-18T23:56:04.123Z","\"'\"","NULL","NULL","NULL","NULL","NULL","NULL","NULL","=arwdUCRBNP/u42"]} DataRow {"fields":["7","NULL","127","32767","2147483647","NULL","NULL","NULL","1.1920929e-7","2.220446049250313e-16","0.0000000000000002220446049250313","NULL","NULL","NULL","NULL","NULL","NULL","NULL","NULL","-1 mons","NULL","NULL","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","\n","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","\"\\\"\"","NULL","NULL","NULL","NULL","NULL","NULL","NULL","NULL"]} DataRow {"fields":["8","NULL","128","32768","2147483648","NULL","NULL","NULL","NaN","NaN","NaN","NULL","NULL","NULL","NULL","NULL","NULL","NULL","NULL","-1 days","NULL","NULL","JAPAN","\r","JAPAN","\".\"","NULL","NULL","NULL","NULL","NULL","NULL","NULL","NULL"]} diff --git a/test/sqllogictest/dates-times.slt b/test/sqllogictest/dates-times.slt index 1bccc00e0c69e..dd1f5ee0f2663 100644 --- a/test/sqllogictest/dates-times.slt +++ b/test/sqllogictest/dates-times.slt @@ -1367,6 +1367,18 @@ select '9::60.1'::time statement error invalid input syntax for type time: HOUR must be \[0, 23\], got 24: "24:00:00" select '24:00:00'::time +# A TIME string that names no field at all is rejected rather than read as +# midnight, matching PostgreSQL. The storage source cast `CastStringToTime` is +# frozen on the older lenient reading, see `mz_storage_types::sources::casts`. +statement error invalid input syntax for type time: no time fields found: "" +select ''::time + +statement error invalid input syntax for type time: no time fields found: " " +select ' '::time + +statement error invalid input syntax for type time: no time fields found: ":" +select ':'::time + # BC years are properly formatted # Using INTERVAL to work around the parser not supporting BC identifiers yet query T @@ -1384,6 +1396,47 @@ select ('0001-01-01'::date - interval '1 DAY')::date ---- 0001-12-31 BC +# The ` BC` suffix carries whitespace, so a BC date nested in a container has to +# be quoted, the same as the timestamp renderings above. `format_date` reported +# `Nestable::Yes` unconditionally, which skips the escaping step entirely, so +# these came out unquoted and diverged from PostgreSQL's `array_out`. +query T +select ARRAY[('0001-02-24'::date - interval '1 YEAR')::date]::text +---- +{"0001-02-24 BC"} + +query T +select ARRAY[('0001-02-24'::date - interval '1 YEAR')::date, '2020-01-01'::date]::text +---- +{"0001-02-24 BC",2020-01-01} + +query T +select LIST[('0001-02-24'::date - interval '1 YEAR')::date]::text +---- +{"0001-02-24 BC"} + +query T +select daterange(('0001-02-24'::date - interval '1 YEAR')::date, '2020-01-01'::date)::text +---- +["0001-02-24 BC",2020-01-01) + +# Both renderings must survive being read back. +query T +select ARRAY[('0001-02-24'::date - interval '1 YEAR')::date, '2020-01-01'::date]::text::date[]::text +---- +{"0001-02-24 BC",2020-01-01} + +query T +select daterange(('0001-02-24'::date - interval '1 YEAR')::date, '2020-01-01'::date)::text::daterange::text +---- +["0001-02-24 BC",2020-01-01) + +# A Common Era date needs no quoting and must not acquire any. +query T +select ARRAY['2020-01-01'::date, '2020-06-01'::date]::text +---- +{2020-01-01,2020-06-01} + query error "-2147483648" interval out of range select '0001-02-24'::date - interval '-2147483648 MONTHS' @@ -1863,3 +1916,48 @@ query T SELECT TIMESTAMP WITH TIME ZONE '01/02/03 04:05:06+00' ---- 2003-01-02 04:05:06+00 + +# The text renderer writes microseconds. A sub-second fraction of `.9999995` or +# more rounds up to a full second, which has to reach the seconds field: written +# into the fraction it becomes `1000000` microseconds, and stripping trailing +# zeros turns that into `.1`, about a second early. +# +# `simple` is required. These assert on the *text* encoding, and the extended +# protocol that plain `query` uses returns TIME and TIMESTAMP in binary. +# +# The TIMESTAMP cast rounds to microseconds on the way in, so it hides this. The +# TIME cast does not round, and neither does DATE + TIME, so both carry the full +# parsed nanoseconds to the renderer, as does COPY ... FROM in TEXT/CSV format. +simple +SELECT TIME '12:34:56.9999999'; +---- +12:34:57 +COMPLETE 1 + +simple +SELECT DATE '2020-01-01' + TIME '00:00:00.9999999'; +---- +2020-01-01 00:00:01 +COMPLETE 1 + +# Just below the rounding threshold, so the fraction stays where it is. +simple +SELECT TIME '12:34:56.9999994'; +---- +12:34:56.999999 +COMPLETE 1 + +# The carry crosses the minute and the day. +simple +SELECT DATE '2020-01-31' + TIME '23:59:59.9999999'; +---- +2020-02-01 00:00:00 +COMPLETE 1 + +# A leap second is already in the seconds field, so only the part below one +# second is a fraction. It used to render as `23:59:60.1`. +simple +SELECT TIME '23:59:60'; +---- +23:59:60 +COMPLETE 1 diff --git a/test/sqllogictest/range.slt b/test/sqllogictest/range.slt index 5ca12a8aaef73..9d1a4aa5b2372 100644 --- a/test/sqllogictest/range.slt +++ b/test/sqllogictest/range.slt @@ -8744,3 +8744,59 @@ SELECT (('[1,100)')@>(t_disallowed_types.c0)) IS TRUE FROM t_disallowed_types; query error range type over real is not supported SELECT (('[1,100)')@>(t_disallowed_types.c1)) IS TRUE FROM t_disallowed_types; + +# A bound whose rendering contains whitespace is emitted quoted by +# `format_range`, so parsing has to strip the quotes again. It previously handed +# the raw substring to the element parser, which tolerates a stray `"` for most +# values and then misreads it as soon as it abuts a meaningful token: the `BC"` +# of a pre-Common-Era bound was consumed as a time zone, so a range with such a +# bound could not be read back from its own output. +query T +SELECT tsrange('0001-02-24 BC'::timestamp, '2020-01-01'::timestamp)::text +---- +["0001-02-24 00:00:00 BC","2020-01-01 00:00:00") + +query T +SELECT tsrange('0001-02-24 BC'::timestamp, '2020-01-01'::timestamp)::text::tsrange::text +---- +["0001-02-24 00:00:00 BC","2020-01-01 00:00:00") + +query T +SELECT '["0001-02-24 00:00:00 BC","2020-01-01 00:00:00")'::tsrange::text +---- +["0001-02-24 00:00:00 BC","2020-01-01 00:00:00") + +# Only the lower bound quoted, and only the upper bound quoted. +query T +SELECT '["0001-02-24 00:00:00 BC",2020-01-01)'::tsrange::text +---- +["0001-02-24 00:00:00 BC","2020-01-01 00:00:00") + +query T +SELECT '[2020-01-01,"2021-01-01 00:00:00")'::tsrange::text +---- +["2020-01-01 00:00:00","2021-01-01 00:00:00") + +# A `\`-escaped quote inside a quoted bound is unescaped rather than ending the +# bound early. Here that leaves a trailing `"` in the element text, which the +# datetime parser happens to tolerate, so the bound still resolves. +query T +SELECT '["2020-01-01\"",2021-01-01)'::tsrange::text +---- +["2020-01-01 00:00:00","2021-01-01 00:00:00") + +# Unquoted, absent and empty bounds are unaffected. +query T +SELECT '[2020-01-01,2020-06-01)'::daterange::text +---- +[2020-01-01,2020-06-01) + +query T +SELECT '(,)'::daterange::text +---- +(,) + +query T +SELECT 'empty'::daterange::text +---- +empty diff --git a/test/sqllogictest/timestamptz.slt b/test/sqllogictest/timestamptz.slt index 2e0c62762eac5..67afb34302070 100644 --- a/test/sqllogictest/timestamptz.slt +++ b/test/sqllogictest/timestamptz.slt @@ -207,6 +207,99 @@ SELECT timezone('+00:00', TIMESTAMPTZ '2024-06-30 23:59:60+00') ---- 2024-07-01 00:00:00 +# The mirror direction, TIMESTAMP -> TIMESTAMPTZ, needs the same fold in +# `checked_sub_with_leapsecond`. `timezone()` reads a numeric offset as POSIX, +# where a positive offset is *west* of Greenwich (see the note in timezone.slt), +# so `+00:00:01` has a `local_minus_utc` of -1 and moves the leap second forward +# past the minute boundary, while `-00:00:01` moves it back onto `:58`. Neither +# lands on `:59`, so both take the folding branch. +query T +SELECT timezone('+00:00:01', TIMESTAMP '2024-06-30 23:59:60') +---- +2024-07-01 00:00:01+00 + +query T +SELECT timezone('-00:00:01', TIMESTAMP '2024-06-30 23:59:60') +---- +2024-06-30 23:59:59+00 + +# A zero offset keeps the result on `:59`, exercising the `else` branch that +# restores the leap-second nanos. +query T +SELECT timezone('+00:00', TIMESTAMP '2024-06-30 23:59:60') +---- +2024-07-01 00:00:00+00 + +# The high end of the accepted range, 262142-12-31, is exactly +# `chrono::NaiveDate::MAX`. Applying a westward offset to a late time on that day +# leaves chrono's range, and the offset is applied before the range check, so the +# subtraction itself has to be checked. It previously panicked, which aborts the +# process through the enhanced panic handler. +query error is out of range for type timestamp with time zone +SELECT '262142-12-31 23:00:00-01'::timestamptz + +query error is out of range for type timestamp with time zone +SELECT '262142-12-31 23:59:59-00:00:01'::timestamptz + +# The mirror bound, chrono's minimum of January 1, 262144 BCE, with an eastward +# offset. +query error is out of range for type timestamp with time zone +SELECT '262144-01-01 00:00:00+01 BC'::timestamptz + +# The opposite offset direction on the same day stays in range. +query T +SELECT '262142-12-31 23:00:00+01'::timestamptz +---- +262142-12-31 22:00:00+00 + +# Rounding to the column's precision happens after the range check, so rounding +# *up* off the end of `HIGH_DATE` needs its own check. The lower the precision, +# the fewer fractional digits it takes: at precision 0 a single `.5` rounds up a +# whole second, well inside what any client can send. +query error timestamp out of range +SELECT '262142-12-31 23:59:59.5'::timestamptz(0) + +query error timestamp out of range +SELECT '262142-12-31 23:59:59.9995'::timestamptz(3) + +query error timestamp out of range +SELECT '262142-12-31 23:59:59.9999995'::timestamptz + +# Rounding down on the same day is unaffected. +query T +SELECT '262142-12-31 23:59:59.4'::timestamptz(0) +---- +262142-12-31 23:59:59+00 + +# A parsed `:60` is stored as chrono's leap second, which is only representable +# at a second-of-minute of 59. An offset that is not a whole number of minutes +# shifts it off `:59`; that value used to reach row encoding and panic there. +# It is folded into the next regular second instead, matching PostgreSQL. +query T +SELECT '1970-01-01 00:00:60+00:00:30'::timestamptz +---- +1970-01-01 00:00:30+00 + +query T +SELECT '1970-01-01 12:00:60-00:00:30'::timestamptz +---- +1970-01-01 12:01:30+00 + +# Storing and re-reading the same value exercises the row encoding that panicked. +statement ok +CREATE TABLE leap_tstz (ts timestamptz) + +statement ok +INSERT INTO leap_tstz VALUES ('1970-01-01 00:00:60+00:00:30') + +query T +SELECT ts FROM leap_tstz +---- +1970-01-01 00:00:30+00 + +statement ok +DROP TABLE leap_tstz + ### to_char statement ok