Skip to main content

sql_values/postgres/
datetime.rs

1//! PostgreSQL 18's `date`, `time`, `timetz`, `timestamp` and `timestamptz`, held as PostgreSQL
2//! stores them, printed by their output functions under `DateStyle` `ISO`, and converted into one
3//! another in a [`PgTimeZone`].
4
5mod arithmetic;
6mod decode;
7mod input;
8#[cfg(feature = "jiff")]
9mod jiff_conversions;
10mod to_char;
11pub(crate) mod tokens;
12
13use core::{cmp::Ordering, fmt};
14
15pub use arithmetic::DateArithmeticError;
16pub use decode::DateOrder;
17pub use input::{InputContext, parse_date, parse_time, parse_timestamp, parse_timestamp_tz};
18pub use to_char::TemporalFormatError;
19
20use super::{
21    PgTimeZone, PgType,
22    float::{int_to_f64, round_ties_even, truncate_to_i64},
23    zone::ZoneAbbreviation,
24};
25
26pub(crate) const USECS_PER_SEC: i64 = 1_000_000;
27pub(crate) const USECS_PER_MINUTE: i64 = 60_000_000;
28pub(crate) const USECS_PER_HOUR: i64 = 3_600_000_000;
29pub(crate) const USECS_PER_DAY: i64 = 86_400_000_000;
30pub(crate) const MONTHS_PER_YEAR: i32 = 12;
31/// `POSTGRES_EPOCH_JDATE`, the Julian day of 2000-01-01.
32pub(crate) const POSTGRES_EPOCH_JDATE: i32 = 2_451_545;
33/// Seconds from 1970-01-01, `UNIX_EPOCH_JDATE`, to 2000-01-01.
34pub(crate) const UNIX_TO_POSTGRES_SECS: i64 = 946_684_800;
35/// `DATE_END_JULIAN`, the Julian day of 5874898-01-01, past the last date.
36const DATE_END_JULIAN: i32 = 2_147_483_494;
37/// `TIMESTAMP_END_JULIAN - POSTGRES_EPOCH_JDATE`, the days from 2000-01-01 to 294277-01-01, the
38/// first date past the last timestamp.
39const TIMESTAMP_END_DAYS: i32 = 106_751_983;
40/// `MIN_TIMESTAMP`, 4714-11-24 00:00:00 BC.
41pub(crate) const MIN_TIMESTAMP: i64 = -211_813_488_000_000_000;
42/// `END_TIMESTAMP`, 294277-01-01 00:00:00, past the last timestamp.
43pub(crate) const END_TIMESTAMP: i64 = 9_223_371_331_200_000_000;
44/// `TZDISP_LIMIT`, the largest offset a `timetz` holds, in seconds.
45const TZDISP_LIMIT: i32 = 16 * 3_600;
46
47/// Why PostgreSQL refuses a date or time, one variant per message it raises, or why this crate
48/// cannot answer for it without more session state or within jiff's years.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
50#[non_exhaustive]
51pub enum DateTimeError {
52    /// A year, month, day, hour, minute or second no calendar or clock has.
53    #[error("date/time field value out of range")]
54    FieldValueOutOfRange,
55    /// An offset of 16 hours or more, or with minutes or seconds of 60 or more.
56    #[error("time zone displacement out of range")]
57    TimeZoneDisplacementOutOfRange,
58    /// A date before 4714-11-24 BC or from 5874898-01-01.
59    #[error("date out of range")]
60    DateOutOfRange,
61    /// A timestamp before 4714-11-24 BC or from 294277-01-01.
62    #[error("timestamp out of range")]
63    TimestampOutOfRange,
64    /// `NaN` given as a timestamp.
65    #[error("timestamp cannot be NaN")]
66    TimestampCannotBeNaN,
67    /// A value outside jiff's years -9999 to 9999, an infinity included, where jiff's types are
68    /// needed.
69    #[error("value outside jiff's years -9999 to 9999")]
70    OutsideJiffRange,
71    /// A literal without an offset read as a `timestamptz` with no time zone in the
72    /// [`InputContext`].
73    #[error("the literal needs a time zone to read as timestamp with time zone")]
74    NeedsTimeZone,
75    /// A zone name, or an abbreviation whose set names a zone, that does not exist.
76    #[error("time zone not recognized")]
77    TimeZoneNotRecognized,
78    /// Text the type's input function cannot read.
79    #[error("invalid input syntax for type {}", .0.input_name())]
80    InvalidInputSyntax(PgType),
81    /// A date whose reading the `DateStyle` field order decides, read with no order in the
82    /// [`InputContext`].
83    #[error("the literal needs a DateStyle field order")]
84    NeedsDateOrder,
85    /// `now`, `today`, `tomorrow` or `yesterday` read with no current time in the
86    /// [`InputContext`].
87    #[error("the literal needs the current time")]
88    NeedsCurrentTime,
89}
90
91/// A PostgreSQL `date`, days from 2000-01-01, from 4714-11-24 BC to 5874897-12-31 and the two
92/// infinities, ordered as PostgreSQL orders it.
93///
94/// ```
95/// use sql_values::postgres::{InputContext, PgDate};
96///
97/// let leap = PgDate::from_ymd(2024, 2, 29).unwrap();
98/// assert_eq!(leap.to_string(), "2024-02-29");
99/// assert_eq!(PgDate::parse("2024-02-29", InputContext::new()), Ok(leap));
100/// assert_eq!(PgDate::from_ymd(-4713, 11, 24).unwrap().to_string(), "4714-11-24 BC");
101/// assert!(PgDate::from_ymd(-4713, 11, 23).is_none());
102/// assert!(PgDate::NEG_INFINITY < leap && leap < PgDate::INFINITY);
103/// ```
104#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
105#[cfg_attr(
106    feature = "serde",
107    derive(serde::Serialize, serde::Deserialize),
108    serde(try_from = "i32", into = "i32")
109)]
110pub struct PgDate(i32);
111
112/// A PostgreSQL `time`, microseconds from midnight to 24:00:00 inclusive.
113///
114/// ```
115/// use sql_values::postgres::PgTime;
116///
117/// let noon = PgTime::from_hms_micro(12, 0, 0, 500_000).unwrap();
118/// assert_eq!(noon.to_string(), "12:00:00.5");
119/// assert_eq!(PgTime::from_micros(86_400_000_000).unwrap().to_string(), "24:00:00");
120/// ```
121#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
122#[cfg_attr(
123    feature = "serde",
124    derive(serde::Serialize, serde::Deserialize),
125    serde(try_from = "i64", into = "i64")
126)]
127pub struct PgTime(i64);
128
129/// A PostgreSQL `timetz`, a time of day with the offset east of UTC it was written with,
130/// ordered by the instant and then by the offset, as `timetz_cmp` orders it.
131///
132/// ```
133/// use sql_values::postgres::{PgTime, PgTimeTz};
134///
135/// let noon = PgTime::from_hms_micro(12, 0, 0, 0).unwrap();
136/// let rome = PgTimeTz::new(noon, 3_600).unwrap();
137/// assert_eq!(rome.to_string(), "12:00:00+01");
138/// let utc = PgTimeTz::new(PgTime::from_hms_micro(11, 0, 0, 0).unwrap(), 0).unwrap();
139/// // At one instant the offset decides, by PostgreSQL's zone in seconds west of UTC.
140/// assert_ne!(rome, utc);
141/// assert!(rome < utc);
142/// ```
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
144#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
145#[cfg_attr(feature = "serde", serde(try_from = "(i64, i32)", into = "(i64, i32)"))]
146pub struct PgTimeTz {
147    time: i64,
148    offset: i32,
149}
150
151/// A PostgreSQL `timestamp`, microseconds from 2000-01-01 00:00:00, from 4714-11-24 BC to
152/// 294276-12-31 23:59:59.999999 and the two infinities.
153///
154/// ```
155/// use sql_values::postgres::{InputContext, PgTimestamp};
156///
157/// let last = PgTimestamp::parse("294276-12-31 23:59:59.999999", InputContext::new()).unwrap();
158/// assert_eq!(last.to_string(), "294276-12-31 23:59:59.999999");
159/// assert_eq!(PgTimestamp::INFINITY.to_string(), "infinity");
160/// assert!(last < PgTimestamp::INFINITY);
161/// ```
162#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
163#[cfg_attr(
164    feature = "serde",
165    derive(serde::Serialize, serde::Deserialize),
166    serde(try_from = "i64", into = "i64")
167)]
168pub struct PgTimestamp(i64);
169
170/// A PostgreSQL `timestamptz`, the instant as microseconds from 2000-01-01 00:00:00 UTC, over the
171/// range of [`PgTimestamp`], printed as under `TimeZone` `UTC`.
172///
173/// ```
174/// use sql_values::postgres::{InputContext, PgTimestampTz};
175///
176/// let at = PgTimestampTz::parse("2026-03-29 12:00:00+02", InputContext::new()).unwrap();
177/// assert_eq!(at.to_string(), "2026-03-29 10:00:00+00");
178/// ```
179#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
180#[cfg_attr(
181    feature = "serde",
182    derive(serde::Serialize, serde::Deserialize),
183    serde(try_from = "i64", into = "i64")
184)]
185pub struct PgTimestampTz(i64);
186
187impl PgDate {
188    /// `infinity`, PostgreSQL's `DATEVAL_NOEND`, after every date.
189    pub const INFINITY: Self = Self(i32::MAX);
190    /// `-infinity`, PostgreSQL's `DATEVAL_NOBEGIN`, before every date.
191    pub const NEG_INFINITY: Self = Self(i32::MIN);
192
193    /// The date of the proleptic Gregorian `year`, `month` and `day`, where year `Y` BC is year
194    /// `1 - Y`, or `None` outside the calendar or PostgreSQL's dates.
195    #[must_use]
196    pub fn from_ymd(year: i32, month: u8, day: u8) -> Option<Self> {
197        let (month, day) = (i32::from(month), i32::from(day));
198        if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
199            return None;
200        }
201        if !is_valid_julian(year, month) {
202            return None;
203        }
204        Self::from_pg_days(date2j(year, month, day) - POSTGRES_EPOCH_JDATE)
205    }
206
207    /// The date `days` after 2000-01-01, as PostgreSQL stores it, where `i32::MAX` and `i32::MIN`
208    /// are the infinities, or `None` outside PostgreSQL's dates.
209    #[must_use]
210    pub const fn from_pg_days(days: i32) -> Option<Self> {
211        if is_valid_date(days) || days == i32::MAX || days == i32::MIN {
212            Some(Self(days))
213        } else {
214            None
215        }
216    }
217
218    /// Days from 2000-01-01, as PostgreSQL stores the date.
219    #[must_use]
220    pub const fn pg_days(self) -> i32 {
221        self.0
222    }
223
224    /// Whether the date is neither `infinity` nor `-infinity`.
225    #[must_use]
226    pub const fn is_finite(self) -> bool {
227        self.0 != i32::MAX && self.0 != i32::MIN
228    }
229
230    /// The year, month and day, where year `Y` BC is year `1 - Y`, or `None` for an infinity.
231    ///
232    /// ```
233    /// use sql_values::postgres::PgDate;
234    ///
235    /// assert_eq!(PgDate::from_pg_days(0).unwrap().ymd(), Some((2000, 1, 1)));
236    /// assert_eq!(PgDate::INFINITY.ymd(), None);
237    /// ```
238    #[must_use]
239    pub fn ymd(self) -> Option<(i32, u8, u8)> {
240        self.is_finite().then(|| {
241            let (year, month, day) = j2date(self.0 + POSTGRES_EPOCH_JDATE);
242            (year, narrow_u8(month.into()), narrow_u8(day.into()))
243        })
244    }
245}
246
247impl PgTime {
248    /// Midnight, `00:00:00`.
249    pub const MIDNIGHT: Self = Self(0);
250
251    /// The time `micros` microseconds after midnight, or `None` outside 00:00:00 to 24:00:00.
252    #[must_use]
253    pub const fn from_micros(micros: i64) -> Option<Self> {
254        if 0 <= micros && micros <= USECS_PER_DAY {
255            Some(Self(micros))
256        } else {
257            None
258        }
259    }
260
261    /// The time of `hour`, `minute`, `second` and `microsecond`, or `None` past 24:00:00 or
262    /// with a field beyond its clock.
263    #[must_use]
264    pub fn from_hms_micro(hour: u8, minute: u8, second: u8, microsecond: u32) -> Option<Self> {
265        if hour > 24 || minute > 59 || second > 59 || microsecond > 999_999 {
266            return None;
267        }
268        Self::from_micros(
269            i64::from(hour) * USECS_PER_HOUR
270                + i64::from(minute) * USECS_PER_MINUTE
271                + i64::from(second) * USECS_PER_SEC
272                + i64::from(microsecond),
273        )
274    }
275
276    /// Microseconds after midnight, as PostgreSQL stores the time.
277    #[must_use]
278    pub const fn micros(self) -> i64 {
279        self.0
280    }
281
282    /// The hour, minute, second and microsecond, where 24:00:00 is hour 24.
283    ///
284    /// ```
285    /// use sql_values::postgres::PgTime;
286    ///
287    /// let t = PgTime::from_micros(45_296_000_007).unwrap();
288    /// assert_eq!(t.hms_micro(), (12, 34, 56, 7));
289    /// ```
290    #[must_use]
291    pub fn hms_micro(self) -> (u8, u8, u8, u32) {
292        let (hour, minute, second, micro) = split_clock(self.0);
293        (
294            narrow_u8(hour),
295            narrow_u8(minute),
296            narrow_u8(second),
297            u32::try_from(micro).expect("a microsecond of a second fits u32"),
298        )
299    }
300
301    /// `AdjustTimeForTypmod`, as `time(p)` rounds the time, half up to `precision` digits.
302    /// A precision of 6 or more, or `None`, keeps the time as it is, and 23:59:59.99 rounds to
303    /// 24:00:00 at one digit.
304    ///
305    /// ```
306    /// use sql_values::postgres::{InputContext, PgTime};
307    ///
308    /// let time = PgTime::parse("23:59:59.99", InputContext::new()).unwrap();
309    /// assert_eq!(time.adjust_for_typmod(Some(1)).to_string(), "24:00:00");
310    /// ```
311    #[must_use]
312    pub fn adjust_for_typmod(self, precision: Option<u8>) -> Self {
313        let Some(precision @ 0..6) = precision else {
314            return self;
315        };
316        let scale = 10i64.pow(6 - u32::from(precision));
317        Self((self.0 + scale / 2) / scale * scale)
318    }
319}
320
321impl PgTimeTz {
322    /// The time `time` at `offset` seconds east of UTC, or `None` beyond PostgreSQL's 16 hours.
323    #[must_use]
324    pub const fn new(time: PgTime, offset: i32) -> Option<Self> {
325        if -TZDISP_LIMIT <= offset && offset <= TZDISP_LIMIT {
326            Some(Self {
327                time: time.0,
328                offset,
329            })
330        } else {
331            None
332        }
333    }
334
335    /// The time of day as written.
336    #[must_use]
337    pub const fn time(self) -> PgTime {
338        PgTime(self.time)
339    }
340
341    /// The offset east of UTC, in seconds.
342    #[must_use]
343    pub const fn offset(self) -> i32 {
344        self.offset
345    }
346
347    /// `AdjustTimeForTypmod` of the time of day, keeping the offset, as `timetz(p)` rounds it.
348    #[must_use]
349    pub fn adjust_for_typmod(self, precision: Option<u8>) -> Self {
350        Self {
351            time: self.time().adjust_for_typmod(precision).0,
352            offset: self.offset,
353        }
354    }
355
356    /// `timetz_cmp_internal`'s keys, the time at UTC and then PostgreSQL's zone, seconds west.
357    fn sort_key(self) -> (i64, i32) {
358        (
359            self.time - i64::from(self.offset) * USECS_PER_SEC,
360            -self.offset,
361        )
362    }
363}
364
365impl PartialOrd for PgTimeTz {
366    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
367        Some(self.cmp(other))
368    }
369}
370
371impl Ord for PgTimeTz {
372    fn cmp(&self, other: &Self) -> Ordering {
373        self.sort_key().cmp(&other.sort_key())
374    }
375}
376
377impl PgTimestamp {
378    /// `infinity`, PostgreSQL's `DT_NOEND`, after every timestamp.
379    pub const INFINITY: Self = Self(i64::MAX);
380    /// `-infinity`, PostgreSQL's `DT_NOBEGIN`, before every timestamp.
381    pub const NEG_INFINITY: Self = Self(i64::MIN);
382
383    /// The timestamp `micros` microseconds after 2000-01-01 00:00:00, as PostgreSQL stores it,
384    /// where `i64::MAX` and `i64::MIN` are the infinities, or `None` outside PostgreSQL's range.
385    #[must_use]
386    pub const fn from_pg_micros(micros: i64) -> Option<Self> {
387        if is_valid_timestamp(micros) || micros == i64::MAX || micros == i64::MIN {
388            Some(Self(micros))
389        } else {
390            None
391        }
392    }
393
394    /// The timestamp of `time` on a finite `date`, where 24:00:00 is midnight of the next day,
395    /// or `None` for an infinite date or outside PostgreSQL's range.
396    ///
397    /// ```
398    /// use sql_values::postgres::{PgDate, PgTime, PgTimestamp};
399    ///
400    /// let date = PgDate::from_ymd(2024, 12, 31).unwrap();
401    /// let at = PgTimestamp::new(date, PgTime::from_micros(86_400_000_000).unwrap()).unwrap();
402    /// assert_eq!(at.to_string(), "2025-01-01 00:00:00");
403    /// ```
404    #[must_use]
405    pub fn new(date: PgDate, time: PgTime) -> Option<Self> {
406        if !date.is_finite() {
407            return None;
408        }
409        i64::from(date.0)
410            .checked_mul(USECS_PER_DAY)
411            .and_then(|micros| micros.checked_add(time.0))
412            .and_then(Self::from_pg_micros)
413            .filter(|at| at.is_finite())
414    }
415
416    /// The timestamp PostgreSQL's arithmetic leaves in `micros`, unchecked as PostgreSQL leaves
417    /// it, as `AdjustTimestampForTypmod` rounds 294276-12-31 23:59:59.5 up to 294277-01-01.
418    pub(crate) const fn from_stored(micros: i64) -> Self {
419        Self(micros)
420    }
421
422    /// Microseconds from 2000-01-01 00:00:00, as PostgreSQL stores the timestamp.
423    #[must_use]
424    pub const fn pg_micros(self) -> i64 {
425        self.0
426    }
427
428    /// Whether the timestamp is neither `infinity` nor `-infinity`.
429    #[must_use]
430    pub const fn is_finite(self) -> bool {
431        self.0 != i64::MAX && self.0 != i64::MIN
432    }
433
434    /// The date, infinite for an infinite timestamp, as `timestamp_date` casts it.
435    #[must_use]
436    pub fn date(self) -> PgDate {
437        match self.0 {
438            i64::MAX => PgDate::INFINITY,
439            i64::MIN => PgDate::NEG_INFINITY,
440            micros => PgDate(narrow_days(micros.div_euclid(USECS_PER_DAY))),
441        }
442    }
443
444    /// The time of day, or `None` for an infinity.
445    #[must_use]
446    pub const fn time(self) -> Option<PgTime> {
447        if self.is_finite() {
448            Some(PgTime(self.0.rem_euclid(USECS_PER_DAY)))
449        } else {
450            None
451        }
452    }
453
454    /// `AdjustTimestampForTypmod`, as `timestamp(p)` rounds the timestamp, half away from
455    /// 2000-01-01 to `precision` digits. An infinity, a precision of 6 or more, or `None` keeps
456    /// the timestamp as it is. No range check follows, as PostgreSQL rounds
457    /// 294276-12-31 23:59:59.5 up to 294277-01-01.
458    ///
459    /// ```
460    /// use sql_values::postgres::{InputContext, PgTimestamp};
461    ///
462    /// let at = PgTimestamp::parse("1999-12-31 23:59:59.5", InputContext::new()).unwrap();
463    /// assert_eq!(at.adjust_for_typmod(Some(0)).to_string(), "1999-12-31 23:59:59");
464    /// ```
465    #[must_use]
466    pub fn adjust_for_typmod(self, precision: Option<u8>) -> Self {
467        Self(adjust_timestamp_for_typmod(self.0, precision))
468    }
469
470    /// PostgreSQL's `timestamp::timestamptz` with `zone` as the session's `TimeZone`, the local
471    /// clock resolved by `DetermineTimeZoneOffset`. A clock the spring-forward gap skips takes
472    /// the offset before the change, and a clock the fall-back repeats the offset after it.
473    ///
474    /// # Errors
475    ///
476    /// [`DateTimeError::TimestampOutOfRange`] where the instant leaves PostgreSQL's range.
477    ///
478    /// ```
479    /// use sql_values::postgres::{InputContext, PgTimeZone, PgTimestamp};
480    ///
481    /// #[cfg(feature = "tzdb")]
482    /// {
483    ///     let rome = PgTimeZone::parse("Europe/Rome").unwrap();
484    ///     let gap = PgTimestamp::parse("2026-03-29 02:30:00", InputContext::new()).unwrap();
485    ///     assert_eq!(gap.to_timestamptz(&rome).unwrap().to_string(), "2026-03-29 01:30:00+00");
486    /// }
487    /// ```
488    pub fn to_timestamptz(self, zone: &PgTimeZone) -> Result<PgTimestampTz, DateTimeError> {
489        if !self.is_finite() {
490            return Ok(PgTimestampTz(self.0));
491        }
492        let offset = local_offset(zone, self.0);
493        let instant = self.0 - i64::from(offset) * USECS_PER_SEC;
494        if is_valid_timestamp(instant) {
495            Ok(PgTimestampTz(instant))
496        } else {
497            Err(DateTimeError::TimestampOutOfRange)
498        }
499    }
500}
501
502impl PgTimestampTz {
503    /// `infinity`, PostgreSQL's `DT_NOEND`, after every instant.
504    pub const INFINITY: Self = Self(i64::MAX);
505    /// `-infinity`, PostgreSQL's `DT_NOBEGIN`, before every instant.
506    pub const NEG_INFINITY: Self = Self(i64::MIN);
507
508    /// The instant `micros` microseconds after 2000-01-01 00:00:00 UTC, as PostgreSQL stores it,
509    /// where `i64::MAX` and `i64::MIN` are the infinities, or `None` outside PostgreSQL's range.
510    #[must_use]
511    pub const fn from_pg_micros(micros: i64) -> Option<Self> {
512        match PgTimestamp::from_pg_micros(micros) {
513            Some(at) => Some(Self(at.0)),
514            None => None,
515        }
516    }
517
518    /// The instant PostgreSQL's arithmetic leaves in `micros`, unchecked as PostgreSQL leaves
519    /// it.
520    pub(crate) const fn from_stored(micros: i64) -> Self {
521        Self(micros)
522    }
523
524    /// Microseconds from 2000-01-01 00:00:00 UTC, as PostgreSQL stores the instant.
525    #[must_use]
526    pub const fn pg_micros(self) -> i64 {
527        self.0
528    }
529
530    /// Whether the instant is neither `infinity` nor `-infinity`.
531    #[must_use]
532    pub const fn is_finite(self) -> bool {
533        self.0 != i64::MAX && self.0 != i64::MIN
534    }
535
536    /// `AdjustTimestampForTypmod`, as `timestamptz(p)` rounds the instant, half away from
537    /// 2000-01-01 00:00:00 UTC to `precision` digits. An infinity, a precision of 6 or more, or
538    /// `None` keeps the instant as it is, and no range check follows.
539    #[must_use]
540    pub fn adjust_for_typmod(self, precision: Option<u8>) -> Self {
541        Self(adjust_timestamp_for_typmod(self.0, precision))
542    }
543
544    /// PostgreSQL's `to_timestamp(double precision)`, `float8_timestamptz`, the instant `seconds`
545    /// after 1970-01-01 00:00:00 UTC, rounded to the microsecond with ties to even after the
546    /// shift to 2000-01-01, and an infinity the like infinite instant.
547    ///
548    /// # Errors
549    ///
550    /// [`DateTimeError::TimestampCannotBeNaN`] for `NaN`, and
551    /// [`DateTimeError::TimestampOutOfRange`] for seconds before 4714-11-24 BC or from
552    /// 294277-01-01.
553    ///
554    /// ```
555    /// use sql_values::postgres::{DateTimeError, PgTimestampTz};
556    ///
557    /// let at = |seconds| PgTimestampTz::from_unix_seconds(seconds).unwrap().to_string();
558    /// assert_eq!(at(-1.25), "1969-12-31 23:59:58.75+00");
559    /// // 0.0078125 and 0.0234375 lie exactly between two microseconds.
560    /// assert_eq!(at(0.0078125), "1970-01-01 00:00:00.007812+00");
561    /// assert_eq!(at(0.0234375), "1970-01-01 00:00:00.023438+00");
562    /// assert_eq!(at(9_224_318_015_999.0), "294276-12-31 23:59:58.999552+00");
563    /// assert_eq!(
564    ///     PgTimestampTz::from_unix_seconds(f64::NEG_INFINITY),
565    ///     Ok(PgTimestampTz::NEG_INFINITY)
566    /// );
567    /// assert_eq!(
568    ///     PgTimestampTz::from_unix_seconds(f64::NAN),
569    ///     Err(DateTimeError::TimestampCannotBeNaN)
570    /// );
571    /// assert_eq!(
572    ///     PgTimestampTz::from_unix_seconds(9_224_318_016_000.0),
573    ///     Err(DateTimeError::TimestampOutOfRange)
574    /// );
575    /// ```
576    pub fn from_unix_seconds(seconds: f64) -> Result<Self, DateTimeError> {
577        if seconds.is_nan() {
578            return Err(DateTimeError::TimestampCannotBeNaN);
579        }
580        if seconds.is_infinite() {
581            return Ok(if seconds < 0.0 {
582                Self::NEG_INFINITY
583            } else {
584                Self::INFINITY
585            });
586        }
587        let first = int_to_f64(MIN_TIMESTAMP / USECS_PER_SEC + UNIX_TO_POSTGRES_SECS);
588        let end = int_to_f64(END_TIMESTAMP / USECS_PER_SEC + UNIX_TO_POSTGRES_SECS);
589        if !(first..end).contains(&seconds) {
590            return Err(DateTimeError::TimestampOutOfRange);
591        }
592        // Two roundings in PostgreSQL's order, never one fused multiply-add.
593        let shifted = seconds - int_to_f64(UNIX_TO_POSTGRES_SECS);
594        let micros = truncate_to_i64(round_ties_even(shifted * int_to_f64(USECS_PER_SEC)));
595        // Every step is monotonic and the bounds map to MIN_TIMESTAMP and below END_TIMESTAMP,
596        // so the result needs none of PostgreSQL's second range check.
597        debug_assert!(is_valid_timestamp(micros), "{seconds} left the range");
598        Ok(Self(micros))
599    }
600
601    /// PostgreSQL's `timestamptz::timestamp` with `zone` as the session's `TimeZone`, the local
602    /// clock of the instant.
603    ///
604    /// # Errors
605    ///
606    /// [`DateTimeError::TimestampOutOfRange`] where the local clock leaves PostgreSQL's range.
607    ///
608    /// ```
609    /// use sql_values::postgres::{InputContext, PgTimeZone, PgTimestampTz};
610    ///
611    /// #[cfg(feature = "tzdb")]
612    /// {
613    ///     let sydney = PgTimeZone::parse("Australia/Sydney").unwrap();
614    ///     let at = PgTimestampTz::parse("2026-01-01 00:00:00+00", InputContext::new()).unwrap();
615    ///     assert_eq!(at.to_timestamp(&sydney).unwrap().to_string(), "2026-01-01 11:00:00");
616    /// }
617    /// ```
618    pub fn to_timestamp(self, zone: &PgTimeZone) -> Result<PgTimestamp, DateTimeError> {
619        if !self.is_finite() {
620            return Ok(PgTimestamp(self.0));
621        }
622        let local = self.0 + i64::from(utc_offset(zone, self.0)) * USECS_PER_SEC;
623        if is_valid_timestamp(local) {
624            Ok(PgTimestamp(local))
625        } else {
626            Err(DateTimeError::TimestampOutOfRange)
627        }
628    }
629
630    /// PostgreSQL's `timestamptz::date` with `zone` as the session's `TimeZone`, the local date
631    /// of the instant, which PostgreSQL does not range-check.
632    #[must_use]
633    pub fn to_date(self, zone: &PgTimeZone) -> PgDate {
634        match self.0 {
635            i64::MAX => PgDate::INFINITY,
636            i64::MIN => PgDate::NEG_INFINITY,
637            utc => {
638                let local = utc + i64::from(utc_offset(zone, utc)) * USECS_PER_SEC;
639                PgDate(narrow_days(local.div_euclid(USECS_PER_DAY)))
640            }
641        }
642    }
643}
644
645/// The offset `zone` has at the instant `utc`, microseconds from 2000-01-01 UTC, as
646/// `timestamp2tm` asks `pg_localtime` for it.
647pub(crate) fn utc_offset(zone: &PgTimeZone, utc: i64) -> i32 {
648    zone.utc_offset(unix_seconds(utc))
649}
650
651/// The offset and the abbreviation `zone` has at the instant `utc`, microseconds from 2000-01-01
652/// UTC, as `timestamp2tm` asks `pg_localtime` for them.
653fn local_time_type(zone: &PgTimeZone, utc: i64) -> (i32, ZoneAbbreviation<'_>) {
654    zone.local_time_type(unix_seconds(utc))
655}
656
657/// The offset `DetermineTimeZoneOffset` gives the local clock `local`, microseconds from
658/// 2000-01-01, in `zone`.
659pub(crate) fn local_offset(zone: &PgTimeZone, local: i64) -> i32 {
660    zone.local_offset(unix_seconds(local))
661}
662
663/// `DetermineTimeZoneAbbrevOffset`, the offset the uppercased `abbreviation` had in `zone` at the
664/// local clock `local`, microseconds from 2000-01-01, or the zone's own offset there when the
665/// zone never used it.
666pub(crate) fn abbreviation_offset(zone: &PgTimeZone, abbreviation: &str, local: i64) -> i32 {
667    zone.abbreviation_offset(abbreviation, unix_seconds(local))
668}
669
670/// The whole seconds from 1970 of `micros` microseconds from 2000-01-01, rounded down.
671const fn unix_seconds(micros: i64) -> i64 {
672    micros.div_euclid(USECS_PER_SEC) + UNIX_TO_POSTGRES_SECS
673}
674
675/// `IS_VALID_TIMESTAMP`.
676pub(crate) const fn is_valid_timestamp(micros: i64) -> bool {
677    MIN_TIMESTAMP <= micros && micros < END_TIMESTAMP
678}
679
680/// `AdjustTimestampForTypmod` on the microseconds PostgreSQL stores.
681fn adjust_timestamp_for_typmod(micros: i64, precision: Option<u8>) -> i64 {
682    let Some(precision @ 0..6) = precision else {
683        return micros;
684    };
685    if micros == i64::MAX || micros == i64::MIN {
686        return micros;
687    }
688    let scale = 10i64.pow(6 - u32::from(precision));
689    let offset = scale / 2;
690    if micros >= 0 {
691        (micros + offset) / scale * scale
692    } else {
693        -((-micros + offset) / scale * scale)
694    }
695}
696
697/// `IS_VALID_DATE`.
698const fn is_valid_date(days: i32) -> bool {
699    -POSTGRES_EPOCH_JDATE <= days && days < DATE_END_JULIAN - POSTGRES_EPOCH_JDATE
700}
701
702/// `IS_VALID_JULIAN`, which checks the lower bound only to the month.
703pub(crate) const fn is_valid_julian(year: i32, month: i32) -> bool {
704    (year > -4713 || (year == -4713 && month >= 11))
705        && (year < 5_874_898 || (year == 5_874_898 && month < 6))
706}
707
708/// `tm2timestamp`, the timestamp of a date within `IS_VALID_JULIAN` and a clock up to
709/// 24:00:00, with `offset` seconds east subtracted, or `None` outside PostgreSQL's range.
710pub(crate) fn tm2timestamp(
711    year: i32,
712    month: i32,
713    day: i32,
714    clock: i64,
715    offset: i32,
716) -> Option<i64> {
717    if !is_valid_julian(year, month) {
718        return None;
719    }
720    let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
721    days.checked_mul(USECS_PER_DAY)?
722        .checked_add(clock)?
723        .checked_sub(i64::from(offset) * USECS_PER_SEC)
724        .filter(|&micros| is_valid_timestamp(micros))
725}
726
727/// `timestamp2tm` without a zone, the year, month, day and clock of a timestamp whose Julian
728/// day is at least -1.
729pub(crate) fn timestamp2tm(micros: i64) -> (i32, i32, i32, i64) {
730    let (year, month, day) =
731        j2date(narrow_days(micros.div_euclid(USECS_PER_DAY)) + POSTGRES_EPOCH_JDATE);
732    (year, month, day, micros.rem_euclid(USECS_PER_DAY))
733}
734
735/// `date2j`, the Julian day of a proleptic Gregorian date, wrapping past `int` as PostgreSQL's
736/// `-fwrapv` build does for a year far outside `IS_VALID_JULIAN`.
737pub(crate) const fn date2j(year: i32, month: i32, day: i32) -> i32 {
738    let (year, month) = if month > 2 {
739        (year.wrapping_add(4800), month + 1)
740    } else {
741        (year.wrapping_add(4799), month + 13)
742    };
743    let century = year / 100;
744    let mut julian = year.wrapping_mul(365).wrapping_sub(32_167);
745    julian = julian.wrapping_add(year / 4 - century + century / 4);
746    julian.wrapping_add(7_834 * month / 256).wrapping_add(day)
747}
748
749/// `j2date`, the proleptic Gregorian date of a Julian day, in C's unsigned arithmetic that
750/// wraps for a day before -32044.
751pub(crate) const fn j2date(julian_day: i32) -> (i32, i32, i32) {
752    let mut julian = julian_day.cast_unsigned().wrapping_add(32_044);
753    let mut quad = julian / 146_097;
754    let extra = (julian - quad * 146_097) * 4 + 3;
755    julian = julian.wrapping_add(60 + quad * 3 + extra / 146_097);
756    quad = julian / 1_461;
757    julian -= quad * 1_461;
758    let mut year = julian * 4 / 1_461;
759    julian = if year == 0 {
760        (julian + 306) % 366
761    } else {
762        (julian + 305) % 365
763    } + 123;
764    year += quad * 4;
765    let quad = julian * 2_141 / 65_536;
766    let day = julian - 7_834 * quad / 256;
767    let month = (quad + 10) % 12 + 1;
768    // The year is below 2^31 + 4800 and the day and month below 32.
769    (
770        year.cast_signed() - 4_800,
771        month.cast_signed(),
772        day.cast_signed(),
773    )
774}
775
776/// Days in `month` of the proleptic Gregorian `year`, `0` being 1 BC.
777pub(crate) const fn days_in_month(year: i32, month: i32) -> i32 {
778    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
779    match month {
780        2 if leap => 29,
781        2 => 28,
782        4 | 6 | 9 | 11 => 30,
783        _ => 31,
784    }
785}
786
787/// Days from 2000-01-01 of a value PostgreSQL holds, which always fit `int`.
788fn narrow_days(days: i64) -> i32 {
789    i32::try_from(days).expect("a timestamp lies under 2^31 days from 2000-01-01")
790}
791
792/// A month, day or clock field, which always fits `u8`.
793fn narrow_u8(field: i64) -> u8 {
794    u8::try_from(field).expect("a calendar or clock field fits u8")
795}
796
797/// The hour, minute, second and microsecond of `micros`, each truncated toward zero, as
798/// `time2tm` splits a clock up to 24:00:00 and `interval2itm` an interval's time.
799pub(crate) const fn split_clock(micros: i64) -> (i64, i64, i64, i64) {
800    (
801        micros / USECS_PER_HOUR,
802        micros % USECS_PER_HOUR / USECS_PER_MINUTE,
803        micros % USECS_PER_MINUTE / USECS_PER_SEC,
804        micros % USECS_PER_SEC,
805    )
806}
807
808/// `EncodeDateOnly` under `DateStyle` `ISO`, `Y BC` for year `1 - Y`, with the era left to the
809/// caller.
810fn write_ymd(f: &mut fmt::Formatter<'_>, year: i32, month: i32, day: i32) -> fmt::Result {
811    let shown = if year > 0 { year } else { 1 - year };
812    write!(f, "{shown:04}-{month:02}-{day:02}")
813}
814
815/// `HH:MM:SS` and `AppendSeconds`' fraction without trailing zeros.
816fn write_clock(f: &mut fmt::Formatter<'_>, micros: i64) -> fmt::Result {
817    let (hour, minute, second, mut fraction) = split_clock(micros);
818    write!(f, "{hour:02}:{minute:02}:{second:02}")?;
819    if fraction > 0 {
820        let mut width = 6;
821        while fraction % 10 == 0 {
822            fraction /= 10;
823            width -= 1;
824        }
825        write!(f, ".{fraction:0width$}")?;
826    }
827    Ok(())
828}
829
830/// `EncodeTimezone`, `±HH`, `±HH:MM` or `±HH:MM:SS` of an offset east of UTC.
831fn write_offset(f: &mut fmt::Formatter<'_>, offset: i32) -> fmt::Result {
832    let sign = if offset >= 0 { '+' } else { '-' };
833    let magnitude = offset.unsigned_abs();
834    let (hour, minute, second) = (magnitude / 3_600, magnitude / 60 % 60, magnitude % 60);
835    write!(f, "{sign}{hour:02}")?;
836    if second != 0 {
837        write!(f, ":{minute:02}:{second:02}")
838    } else if minute != 0 {
839        write!(f, ":{minute:02}")
840    } else {
841        Ok(())
842    }
843}
844
845/// `EncodeDateTime` under `DateStyle` `ISO`, with `+00` for a `timestamptz` in `UTC`.
846fn write_timestamp(f: &mut fmt::Formatter<'_>, micros: i64, zone: bool) -> fmt::Result {
847    match micros {
848        i64::MAX => return f.write_str("infinity"),
849        i64::MIN => return f.write_str("-infinity"),
850        _ => {}
851    }
852    let (year, month, day, clock) = timestamp2tm(micros);
853    write_ymd(f, year, month, day)?;
854    f.write_str(" ")?;
855    write_clock(f, clock)?;
856    if zone {
857        f.write_str("+00")?;
858    }
859    if year <= 0 {
860        f.write_str(" BC")?;
861    }
862    Ok(())
863}
864
865impl fmt::Display for PgDate {
866    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
867        match self.0 {
868            i32::MAX => f.write_str("infinity"),
869            i32::MIN => f.write_str("-infinity"),
870            days => {
871                let (year, month, day) = j2date(days + POSTGRES_EPOCH_JDATE);
872                write_ymd(f, year, month, day)?;
873                if year <= 0 {
874                    f.write_str(" BC")?;
875                }
876                Ok(())
877            }
878        }
879    }
880}
881
882impl fmt::Display for PgTime {
883    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884        write_clock(f, self.0)
885    }
886}
887
888impl fmt::Display for PgTimeTz {
889    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890        write_clock(f, self.time)?;
891        write_offset(f, self.offset)
892    }
893}
894
895impl fmt::Display for PgTimestamp {
896    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897        write_timestamp(f, self.0, false)
898    }
899}
900
901impl fmt::Display for PgTimestampTz {
902    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903        write_timestamp(f, self.0, true)
904    }
905}
906
907impl TryFrom<i32> for PgDate {
908    type Error = DateTimeError;
909
910    fn try_from(days: i32) -> Result<Self, Self::Error> {
911        Self::from_pg_days(days).ok_or(DateTimeError::DateOutOfRange)
912    }
913}
914
915impl From<PgDate> for i32 {
916    fn from(date: PgDate) -> Self {
917        date.0
918    }
919}
920
921impl TryFrom<i64> for PgTime {
922    type Error = DateTimeError;
923
924    fn try_from(micros: i64) -> Result<Self, Self::Error> {
925        Self::from_micros(micros).ok_or(DateTimeError::FieldValueOutOfRange)
926    }
927}
928
929impl From<PgTime> for i64 {
930    fn from(time: PgTime) -> Self {
931        time.0
932    }
933}
934
935impl TryFrom<(i64, i32)> for PgTimeTz {
936    type Error = DateTimeError;
937
938    fn try_from((micros, offset): (i64, i32)) -> Result<Self, Self::Error> {
939        let time = PgTime::try_from(micros)?;
940        Self::new(time, offset).ok_or(DateTimeError::TimeZoneDisplacementOutOfRange)
941    }
942}
943
944impl From<PgTimeTz> for (i64, i32) {
945    fn from(time: PgTimeTz) -> Self {
946        (time.time, time.offset)
947    }
948}
949
950impl TryFrom<i64> for PgTimestamp {
951    type Error = DateTimeError;
952
953    fn try_from(micros: i64) -> Result<Self, Self::Error> {
954        Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
955    }
956}
957
958impl From<PgTimestamp> for i64 {
959    fn from(at: PgTimestamp) -> Self {
960        at.0
961    }
962}
963
964impl TryFrom<i64> for PgTimestampTz {
965    type Error = DateTimeError;
966
967    fn try_from(micros: i64) -> Result<Self, Self::Error> {
968        Self::from_pg_micros(micros).ok_or(DateTimeError::TimestampOutOfRange)
969    }
970}
971
972impl From<PgTimestampTz> for i64 {
973    fn from(at: PgTimestampTz) -> Self {
974        at.0
975    }
976}