Skip to main content

sql_values/postgres/
zone.rs

1//! PostgreSQL 18's `TimeZone` setting as `check_timezone`, `pg_tzset` and `tzparse` read it, and the
2//! offsets `pg_localtime` and `DetermineTimeZoneOffset` find in a zone.
3//!
4//! IANA zones come from jiff's bundled database under the `tzdb` feature, which is asked only for
5//! a zone's offset and abbreviation at an instant and for its transitions. Without it a name
6//! loads as in a PostgreSQL with no time zone files. Fixed offsets and POSIX rules are ported and
7//! hold over PostgreSQL's whole range.
8//!
9//! The `timezone_abbreviations` sets PostgreSQL installs are bundled from its source, under the
10//! PostgreSQL license in `zone/timezonesets/COPYRIGHT`.
11
12mod tznames;
13
14use alloc::{borrow::Cow, string::String, vec::Vec};
15use core::{
16    fmt,
17    hash::{Hash, Hasher},
18};
19
20#[cfg(feature = "tzdb")]
21use jiff::{Timestamp, tz::TimeZone};
22use tznames::Abbreviation;
23pub(crate) use tznames::Meaning;
24pub use tznames::TimeZoneAbbreviationsError;
25
26use super::{
27    DateTimeError, IntervalError,
28    datetime::{date2j, days_in_month, j2date},
29    interval::strtod,
30    parse_interval,
31};
32
33/// The bundled sets as static tables, which the build script writes with the parser in
34/// `tznames`.
35mod bundled {
36    use alloc::borrow::Cow;
37
38    use super::tznames::{Abbreviation, Meaning};
39
40    include!(concat!(env!("OUT_DIR"), "/timezone_abbreviations.rs"));
41}
42
43/// 2200-01-01 00:00:00 UTC in seconds from 1970, where a scan of an IANA zone's abbreviations
44/// stops, past every rule change the database records and a century of the POSIX rules that
45/// then only repeat the same abbreviations.
46#[cfg(feature = "tzdb")]
47const ABBREVIATION_SCAN_END: i64 = 7_258_118_400;
48
49/// A `timezone_abbreviations` set, the abbreviations a literal may write for its zone.
50///
51/// ```
52/// use sql_values::postgres::{TimeZoneAbbreviations, TimeZoneAbbreviationsError};
53///
54/// let local = |name: &str| Some(match name {
55///     "Local" => "@INCLUDE Default\n@OVERRIDE\nIST 19800 # India\n",
56///     other => TimeZoneAbbreviations::bundled_file(other)?,
57/// });
58/// assert!(TimeZoneAbbreviations::load("Local", local).is_ok());
59/// let clash = |name: &str| match name {
60///     "Clash" => Some("@INCLUDE Default\nIST 19800\n"),
61///     other => TimeZoneAbbreviations::bundled_file(other),
62/// };
63/// assert_eq!(
64///     TimeZoneAbbreviations::load("Clash", clash),
65///     Err(TimeZoneAbbreviationsError::MultiplyDefined {
66///         abbreviation: "ist".to_owned(),
67///         file: "Clash".to_owned(),
68///         line: 2,
69///     }),
70/// );
71/// ```
72#[derive(Debug, Clone, PartialEq, Eq, Hash)]
73pub struct TimeZoneAbbreviations {
74    entries: Cow<'static, [Abbreviation]>,
75}
76
77/// `Default`, the set `timezone_abbreviations` names in a stock installation.
78pub(crate) static DEFAULT_ABBREVIATIONS: TimeZoneAbbreviations = TimeZoneAbbreviations {
79    entries: Cow::Borrowed(&bundled::DEFAULT),
80};
81static AUSTRALIA: TimeZoneAbbreviations = TimeZoneAbbreviations {
82    entries: Cow::Borrowed(&bundled::AUSTRALIA),
83};
84static INDIA: TimeZoneAbbreviations = TimeZoneAbbreviations {
85    entries: Cow::Borrowed(&bundled::INDIA),
86};
87
88impl TimeZoneAbbreviations {
89    /// The set PostgreSQL installs as `name`, `Default`, `Australia` or `India`, as
90    /// `timezone_abbreviations` names it.
91    #[must_use]
92    pub fn bundled(name: &str) -> Option<&'static Self> {
93        match name {
94            "Default" => Some(&DEFAULT_ABBREVIATIONS),
95            "Australia" => Some(&AUSTRALIA),
96            "India" => Some(&INDIA),
97            _ => None,
98        }
99    }
100
101    /// The text of the file PostgreSQL installs as `name`, for a set of its own that includes
102    /// one.
103    #[must_use]
104    pub fn bundled_file(name: &str) -> Option<&'static str> {
105        match name {
106            "Default" => Some(include_str!("zone/timezonesets/Default")),
107            "Australia" => Some(include_str!("zone/timezonesets/Australia")),
108            "India" => Some(include_str!("zone/timezonesets/India")),
109            _ => None,
110        }
111    }
112
113    /// PostgreSQL 18's `load_tzoffsets`, the set of the file `name`, which `files` holds with
114    /// every file it includes, as PostgreSQL's `timezonesets` directory holds them.
115    ///
116    /// # Errors
117    ///
118    /// The [`TimeZoneAbbreviationsError`] PostgreSQL raises for the file or one it includes.
119    pub fn load<'f>(
120        name: &str,
121        mut files: impl FnMut(&str) -> Option<&'f str>,
122    ) -> Result<Self, TimeZoneAbbreviationsError> {
123        let mut entries = Vec::new();
124        tznames::parse_file(name, 0, &mut files, &mut entries)?;
125        Ok(Self {
126            entries: Cow::Owned(entries),
127        })
128    }
129
130    /// The meaning of the lowercased `word`, as `datebsearch` finds it.
131    pub(crate) fn lookup(&self, word: &[u8]) -> Option<&Meaning> {
132        tznames::search(&self.entries, word).map(|entry| &entry.meaning)
133    }
134}
135
136/// What an abbreviation means in the zone that uses it, as `pg_timezone_abbrev_is_known` and
137/// `pg_interpret_timezone_abbrev` find it.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub(crate) struct AbbreviationUse {
140    /// Seconds east of UTC.
141    pub(crate) offset: i32,
142    pub(crate) dst: bool,
143}
144
145const SECS_PER_MINUTE: i32 = 60;
146const SECS_PER_HOUR: i32 = 3_600;
147const SECS_PER_DAY: i64 = 86_400;
148/// `UNIX_EPOCH_JDATE`, the Julian day of 1970-01-01.
149const UNIX_EPOCH_JDATE: i32 = 2_440_588;
150/// 2000-01-01 00:00:00 UTC in seconds from 1970, where `pg_tz_acceptable` looks for leap seconds.
151const TIME_2000: i64 = 946_684_800;
152/// `TZ_STRLEN_MAX`, the longest name `pg_tzset` takes.
153const TZ_STRLEN_MAX: usize = 255;
154/// The largest hour `getsecs` reads, `HOURSPERDAY * DAYSPERWEEK - 1`.
155const MAX_RULE_HOUR: i32 = 167;
156/// `TZDEFRULESTRING`, the rules of a POSIX zone that names daylight saving time but no rules.
157const DEFAULT_RULES: &str = "M3.2.0,M11.1.0";
158/// Years after which the Gregorian calendar, and so every POSIX rule, repeats.
159const YEARS_PER_REPEAT: i32 = 400;
160
161/// Why PostgreSQL refuses a `TimeZone` setting, one variant per message or detail it raises.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
163pub enum TimeZoneError {
164    /// Neither an offset, an IANA name nor a POSIX specification.
165    #[error("invalid value for parameter \"TimeZone\"")]
166    InvalidValue,
167    /// An offset in hours or an interval of 168 hours or more.
168    #[error("UTC timezone offset is out of range")]
169    OffsetOutOfRange,
170    /// An `interval '...'` setting with months.
171    #[error("cannot specify months in time zone interval")]
172    MonthsInInterval,
173    /// An `interval '...'` setting with days.
174    #[error("cannot specify days in time zone interval")]
175    DaysInInterval,
176    /// A zone whose offset at 2000-01-01 00:00:00 UTC has seconds, which PostgreSQL takes for
177    /// leap seconds.
178    #[error("time zone appears to use leap seconds")]
179    LeapSeconds,
180    /// An `interval '...'` setting `interval_in` refuses.
181    #[error(transparent)]
182    Interval(#[from] IntervalError),
183}
184
185/// A time zone as PostgreSQL's `TimeZone` setting reads it, equal to another when `SHOW timezone`
186/// names both alike.
187///
188/// ```
189/// use sql_values::postgres::{PgTimeZone, TimeZoneError};
190///
191/// #[cfg(feature = "tzdb")]
192/// assert_eq!(PgTimeZone::parse("europe/rome").unwrap().name(), "Europe/Rome");
193/// // A number is hours east of UTC, a POSIX specification hours west of it.
194/// assert_eq!(PgTimeZone::parse("+02").unwrap().name(), "<+02>-02");
195/// assert_eq!(PgTimeZone::parse("utc+2").unwrap().name(), "UTC+2");
196/// assert_eq!(PgTimeZone::parse("+168"), Err(TimeZoneError::OffsetOutOfRange));
197/// assert_eq!(PgTimeZone::parse("CEST"), Err(TimeZoneError::InvalidValue));
198/// ```
199#[derive(Debug, Clone)]
200pub struct PgTimeZone {
201    name: String,
202    rules: Rules,
203}
204
205/// How a zone's offset is found.
206#[derive(Debug, Clone)]
207enum Rules {
208    /// One offset east of UTC, in seconds, forever, and its abbreviation.
209    Fixed { offset: i32, abbreviation: String },
210    /// A POSIX specification with daylight saving time, and its two abbreviations.
211    Posix {
212        rules: Posix,
213        std_name: String,
214        dst_name: String,
215    },
216    /// An IANA zone with transitions, from jiff's database.
217    #[cfg(feature = "tzdb")]
218    Iana(TimeZone),
219}
220
221/// A POSIX specification with daylight saving time, offsets west of UTC as `tzparse` keeps them.
222#[derive(Debug, Clone, Copy)]
223struct Posix {
224    std_offset: i32,
225    dst_offset: i32,
226    start: Rule,
227    end: Rule,
228    /// Whether any year has transitions. A zone without is in daylight saving time throughout.
229    switches: bool,
230}
231
232/// A POSIX transition rule and its local time of day in seconds.
233#[derive(Debug, Clone, Copy)]
234struct Rule {
235    date: RuleDate,
236    time: i32,
237}
238
239/// The day a POSIX rule names.
240#[derive(Debug, Clone, Copy)]
241enum RuleDate {
242    /// `Jn`, day 1 to 365 with February 29 never counted.
243    Julian(i32),
244    /// `n`, day 0 to 365 with February 29 counted.
245    DayOfYear(i32),
246    /// `Mm.w.d`, day `d` of week `w` of month `m`.
247    MonthWeekDay { month: i32, week: i32, weekday: i32 },
248}
249
250/// A cursor over a POSIX specification.
251struct Spec<'a> {
252    bytes: &'a [u8],
253    at: usize,
254}
255
256impl<'a> Spec<'a> {
257    fn peek(&self) -> Option<u8> {
258        self.bytes.get(self.at).copied()
259    }
260
261    fn eat(&mut self, byte: u8) -> bool {
262        let found = self.peek() == Some(byte);
263        self.at += usize::from(found);
264        found
265    }
266
267    fn is_done(&self) -> bool {
268        self.at == self.bytes.len()
269    }
270
271    /// `getzname` or `getqzname`, the abbreviation read.
272    fn name(&mut self) -> Option<&'a [u8]> {
273        if self.eat(b'<') {
274            let start = self.at;
275            while self.peek().is_some_and(|b| b != b'>') {
276                self.at += 1;
277            }
278            let name = &self.bytes[start..self.at];
279            self.eat(b'>').then_some(name)
280        } else {
281            let start = self.at;
282            while self
283                .peek()
284                .is_some_and(|b| !b.is_ascii_digit() && !matches!(b, b',' | b'-' | b'+'))
285            {
286                self.at += 1;
287            }
288            Some(&self.bytes[start..self.at])
289        }
290    }
291
292    /// `getnum`, a decimal number within `min..=max`.
293    fn number(&mut self, min: i32, max: i32) -> Option<i32> {
294        if !self.peek().is_some_and(|b| b.is_ascii_digit()) {
295            return None;
296        }
297        let mut value = 0;
298        while let Some(digit) = self.peek().filter(u8::is_ascii_digit) {
299            value = value * 10 + i32::from(digit - b'0');
300            if value > max {
301                return None;
302            }
303            self.at += 1;
304        }
305        (value >= min).then_some(value)
306    }
307
308    /// `getsecs`, `hh[:mm[:ss]]` in seconds.
309    fn seconds(&mut self) -> Option<i32> {
310        let mut seconds = self.number(0, MAX_RULE_HOUR)? * SECS_PER_HOUR;
311        if self.eat(b':') {
312            seconds += self.number(0, 59)? * SECS_PER_MINUTE;
313            if self.eat(b':') {
314                seconds += self.number(0, 60)?;
315            }
316        }
317        Some(seconds)
318    }
319
320    /// `getoffset`, `[+-]hh[:mm[:ss]]` in seconds.
321    fn offset(&mut self) -> Option<i32> {
322        let negative = self.eat(b'-');
323        if !negative {
324            self.eat(b'+');
325        }
326        let seconds = self.seconds()?;
327        Some(if negative { -seconds } else { seconds })
328    }
329
330    /// `getrule`, `Jn`, `n` or `Mm.w.d` with an optional `/time`, 02:00 by default.
331    fn rule(&mut self) -> Option<Rule> {
332        let date = if self.eat(b'J') {
333            RuleDate::Julian(self.number(1, 365)?)
334        } else if self.eat(b'M') {
335            let month = self.number(1, 12)?;
336            if !self.eat(b'.') {
337                return None;
338            }
339            let week = self.number(1, 5)?;
340            if !self.eat(b'.') {
341                return None;
342            }
343            let weekday = self.number(0, 6)?;
344            RuleDate::MonthWeekDay {
345                month,
346                week,
347                weekday,
348            }
349        } else {
350            RuleDate::DayOfYear(self.number(0, 365)?)
351        };
352        let time = if self.eat(b'/') {
353            self.offset()?
354        } else {
355            2 * SECS_PER_HOUR
356        };
357        Some(Rule { date, time })
358    }
359}
360
361/// `tzparse` without `lastditch`, the rules of an uppercased POSIX specification.
362fn tzparse(spec: &str) -> Option<Rules> {
363    let mut cursor = Spec {
364        bytes: spec.as_bytes(),
365        at: 0,
366    };
367    let text = |name: &[u8]| String::from_utf8_lossy(name).into_owned();
368    let std_name = text(cursor.name()?);
369    if cursor.is_done() {
370        return None;
371    }
372    let std_offset = cursor.offset()?;
373    if cursor.is_done() {
374        return Some(Rules::Fixed {
375            offset: -std_offset,
376            abbreviation: std_name,
377        });
378    }
379    let dst_name = text(cursor.name()?);
380    if dst_name.is_empty() {
381        return None;
382    }
383    let dst_offset = if cursor.is_done() || matches!(cursor.peek(), Some(b',' | b';')) {
384        std_offset - SECS_PER_HOUR
385    } else {
386        cursor.offset()?
387    };
388    let mut rules = Spec {
389        bytes: DEFAULT_RULES.as_bytes(),
390        at: 0,
391    };
392    let rules = if cursor.is_done() {
393        &mut rules
394    } else if cursor.eat(b',') || cursor.eat(b';') {
395        &mut cursor
396    } else {
397        return None;
398    };
399    let start = rules.rule()?;
400    if !rules.eat(b',') {
401        return None;
402    }
403    let end = rules.rule()?;
404    if !rules.is_done() {
405        return None;
406    }
407    let mut posix = Posix {
408        std_offset,
409        dst_offset,
410        start,
411        end,
412        switches: false,
413    };
414    posix.switches = (2000..2000 + YEARS_PER_REPEAT).any(|year| posix.year(year).is_some());
415    Some(Rules::Posix {
416        rules: posix,
417        std_name,
418        dst_name,
419    })
420}
421
422/// C's `isleap`.
423const fn is_leap(year: i32) -> bool {
424    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
425}
426
427impl Rule {
428    /// `transtime`, the rule's moment in seconds from January 1 of `year` at 00:00 UTC, with
429    /// `offset` seconds west of UTC in effect.
430    fn transtime(self, year: i32, offset: i32) -> i64 {
431        let leap = is_leap(year);
432        let day = match self.date {
433            RuleDate::Julian(day) => day - 1 + i32::from(leap && day >= 60),
434            RuleDate::DayOfYear(day) => day,
435            RuleDate::MonthWeekDay {
436                month,
437                week,
438                weekday,
439            } => {
440                // Zeller's congruence for the weekday of the month's first day.
441                let m1 = (month + 9) % 12 + 1;
442                let yy0 = if month <= 2 { year - 1 } else { year };
443                let (yy1, yy2) = (yy0 / 100, yy0 % 100);
444                let mut dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7;
445                if dow < 0 {
446                    dow += 7;
447                }
448                let mut d = weekday - dow;
449                if d < 0 {
450                    d += 7;
451                }
452                let length = days_in_month(year, month);
453                for _ in 1..week {
454                    if d + 7 >= length {
455                        break;
456                    }
457                    d += 7;
458                }
459                d + (1..month).map(|m| days_in_month(year, m)).sum::<i32>()
460            }
461        };
462        i64::from(day) * SECS_PER_DAY + i64::from(self.time) + i64::from(offset)
463    }
464}
465
466impl Posix {
467    /// The year's two transitions, in seconds from 1970 and whether daylight saving time follows
468    /// each, as `tzparse` lays them out, or `None` when the year has none.
469    fn year(self, year: i32) -> Option<[(i64, bool); 2]> {
470        // The calendar of the same year in 2000 to 2399, where `tzparse` computes it, since
471        // Zeller's congruence in C's arithmetic holds for positive years only.
472        let calendar = 2000 + (year - 2000).rem_euclid(YEARS_PER_REPEAT);
473        let mut start = self.start.transtime(calendar, self.std_offset);
474        let mut end = self.end.transtime(calendar, self.dst_offset);
475        let year_secs = if is_leap(calendar) { 366 } else { 365 } * SECS_PER_DAY;
476        let reversed = end < start;
477        if reversed {
478            core::mem::swap(&mut start, &mut end);
479        }
480        let spans =
481            start < end && end - start < year_secs + i64::from(self.std_offset - self.dst_offset);
482        if !(reversed || spans) {
483            return None;
484        }
485        let jan_first = i64::from(date2j(year, 1, 1) - UNIX_EPOCH_JDATE) * SECS_PER_DAY;
486        Some([(jan_first + start, !reversed), (jan_first + end, reversed)])
487    }
488
489    /// The offset east of UTC on either side of a transition.
490    const fn offset(self, dst: bool) -> i32 {
491        if dst {
492            -self.dst_offset
493        } else {
494            -self.std_offset
495        }
496    }
497
498    /// The transitions of the years around `year`, in order.
499    fn around(self, year: i32) -> impl DoubleEndedIterator<Item = (i64, bool)> {
500        (year - 1..=year + 1).flat_map(move |year| self.year(year).into_iter().flatten())
501    }
502
503    /// The offset east of UTC in effect at `unix`, as `localsub` finds it.
504    fn offset_at(self, unix: i64) -> i32 {
505        if !self.switches {
506            return self.offset(true);
507        }
508        let year = year_of(unix);
509        (0..=YEARS_PER_REPEAT)
510            .find_map(|back| {
511                self.around(year - back)
512                    .rev()
513                    .find(|&(at, _)| at <= unix)
514                    .map(|(_, dst)| self.offset(dst))
515            })
516            .expect("a zone that switches has a transition within 400 years")
517    }
518
519    /// The first transition after `unix`, its moment and the offset east after it.
520    fn next_transition(self, unix: i64) -> Option<(i64, i32)> {
521        if !self.switches {
522            return None;
523        }
524        let year = year_of(unix);
525        (0..=YEARS_PER_REPEAT).find_map(|ahead| {
526            self.around(year + ahead)
527                .find(|&(at, _)| at > unix)
528                .map(|(at, dst)| (at, self.offset(dst)))
529        })
530    }
531}
532
533/// The UTC year of `unix` seconds from 1970.
534fn year_of(unix: i64) -> i32 {
535    let julian = unix.div_euclid(SECS_PER_DAY) + i64::from(UNIX_EPOCH_JDATE);
536    j2date(i32::try_from(julian).expect("PostgreSQL's instants lie within int Julian days")).0
537}
538
539/// C's `strtod` over the whole of `text`, skipping leading blanks and a `+`, or `None` when
540/// characters are left over.
541fn strtod_whole(text: &str) -> Option<f64> {
542    let bytes = text.as_bytes();
543    let mut at = bytes
544        .iter()
545        .take_while(|&&b| super::cast::is_pg_space(b))
546        .count();
547    if bytes.get(at) == Some(&b'+') {
548        at += 1;
549        if bytes.get(at) == Some(&b'-') {
550            return None;
551        }
552    }
553    let (value, end, _) = strtod(bytes, at)?;
554    (end == bytes.len()).then_some(value)
555}
556
557impl PgTimeZone {
558    /// PostgreSQL 18's `check_timezone`, reading an `interval '...'`, else a number of hours east of UTC
559    /// as C's `strtod` reads it, else a name `pg_tzset` loads, `GMT`, an IANA name in jiff's
560    /// bundled database or a POSIX specification, refused when its offset at 2000-01-01 has
561    /// seconds.
562    ///
563    /// # Errors
564    ///
565    /// The [`TimeZoneError`] PostgreSQL raises.
566    ///
567    /// ```
568    /// use sql_values::postgres::PgTimeZone;
569    ///
570    /// let name = |setting| PgTimeZone::parse(setting).map(|zone| zone.to_string());
571    /// assert_eq!(name("2.5").unwrap(), "<+02:30>-02:30");
572    /// assert_eq!(name("interval '-01:00'").unwrap(), "<-01>+01");
573    /// assert_eq!(name("est5edt").unwrap(), "EST5EDT");
574    /// assert_eq!(name("xxx3yyy").unwrap(), "XXX3YYY");
575    /// ```
576    pub fn parse(setting: &str) -> Result<Self, TimeZoneError> {
577        if setting
578            .get(..8)
579            .is_some_and(|prefix| prefix.eq_ignore_ascii_case("interval"))
580        {
581            let blanks = setting.as_bytes()[8..]
582                .iter()
583                .take_while(|&&b| super::cast::is_pg_space(b))
584                .count();
585            let body = setting[8 + blanks..]
586                .strip_prefix('\'')
587                .and_then(|rest| rest.strip_suffix('\''))
588                .filter(|body| !body.contains('\''))
589                .ok_or(TimeZoneError::InvalidValue)?;
590            let interval = parse_interval(body)?;
591            if interval.months != 0 {
592                return Err(TimeZoneError::MonthsInInterval);
593            }
594            if interval.days != 0 {
595                return Err(TimeZoneError::DaysInInterval);
596            }
597            return Self::from_offset_west(-(interval.microseconds / 1_000_000));
598        }
599        if let Some(hours) = strtod_whole(setting) {
600            // C's conversion of `-hours * SECS_PER_HOUR` to `long` truncates, and one beyond
601            // `tzparse`'s 167:59:59 is refused, as is an infinity or NaN.
602            let west = -hours * f64::from(SECS_PER_HOUR);
603            let limit = f64::from(MAX_RULE_HOUR + 1) * f64::from(SECS_PER_HOUR);
604            if !west.is_finite() || west.abs() >= limit {
605                return Err(TimeZoneError::OffsetOutOfRange);
606            }
607            return Self::from_offset_west(super::float::truncate_to_i64(west));
608        }
609        let zone = Self::load(setting).ok_or(TimeZoneError::InvalidValue)?;
610        if zone
611            .utc_offset(TIME_2000)
612            .is_some_and(|offset| offset % 60 != 0)
613        {
614            return Err(TimeZoneError::LeapSeconds);
615        }
616        Ok(zone)
617    }
618
619    /// `pg_tzset_offset`, the zone of a fixed offset `west` seconds west of UTC, named as a
620    /// POSIX specification with the offset east in its abbreviation.
621    fn from_offset_west(west: i64) -> Result<Self, TimeZoneError> {
622        let magnitude = west.unsigned_abs();
623        if magnitude >= u64::from((MAX_RULE_HOUR + 1).unsigned_abs()) * 3_600 {
624            return Err(TimeZoneError::OffsetOutOfRange);
625        }
626        let mut clock = alloc::format!("{:02}", magnitude / 3_600);
627        if !magnitude.is_multiple_of(3_600) {
628            clock += &alloc::format!(":{:02}", magnitude % 3_600 / 60);
629            if !magnitude.is_multiple_of(60) {
630                clock += &alloc::format!(":{:02}", magnitude % 60);
631            }
632        }
633        let (abbreviation, name) = if west > 0 {
634            (
635                alloc::format!("-{clock}"),
636                alloc::format!("<-{clock}>+{clock}"),
637            )
638        } else {
639            (
640                alloc::format!("+{clock}"),
641                alloc::format!("<+{clock}>-{clock}"),
642            )
643        };
644        let west = i32::try_from(west).expect("an offset under 168 hours fits int");
645        Ok(Self {
646            name,
647            rules: Rules::Fixed {
648                offset: -west,
649                abbreviation,
650            },
651        })
652    }
653
654    /// `pg_tzset`, loading `GMT`, an IANA name, or an uppercased POSIX specification.
655    pub(crate) fn load(name: &str) -> Option<Self> {
656        if name.len() > TZ_STRLEN_MAX {
657            return None;
658        }
659        let upper = name.to_ascii_uppercase();
660        if upper == "GMT" {
661            return Some(Self {
662                name: upper.clone(),
663                rules: Rules::Fixed {
664                    offset: 0,
665                    abbreviation: upper,
666                },
667            });
668        }
669        // `tzload` drops one leading colon, and a name that keeps one is no POSIX specification.
670        #[cfg(feature = "tzdb")]
671        if let Some(zone) = Self::load_iana(name.strip_prefix(':').unwrap_or(name)) {
672            return Some(zone);
673        }
674        if upper.starts_with(':') {
675            return None;
676        }
677        let rules = tzparse(&upper)?;
678        Some(Self { name: upper, rules })
679    }
680
681    /// `tzload`, the IANA zone `file` names in jiff's bundled database.
682    #[cfg(feature = "tzdb")]
683    fn load_iana(file: &str) -> Option<Self> {
684        let zone = jiff::tz::db()
685            .get(file)
686            .ok()
687            .filter(|zone| !zone.is_unknown())?;
688        let canonical = String::from(zone.iana_name().unwrap_or(file));
689        // A zone with no transitions keeps its one offset beyond jiff's years too.
690        let rules = match zone.following(Timestamp::MIN).next() {
691            None => {
692                let info = zone.to_offset_info(Timestamp::MIN);
693                Rules::Fixed {
694                    offset: info.offset().seconds(),
695                    abbreviation: String::from(info.abbreviation()),
696                }
697            }
698            Some(_) => Rules::Iana(zone),
699        };
700        Some(Self {
701            name: canonical,
702            rules,
703        })
704    }
705
706    /// The name `SHOW timezone` prints for the zone.
707    #[must_use]
708    pub fn name(&self) -> &str {
709        &self.name
710    }
711
712    /// The zone's one offset east of UTC in seconds when it never changes, as
713    /// `pg_get_timezone_offset` finds it. A POSIX specification counts hours west of UTC, so
714    /// `+05:30` is five and a half hours behind it.
715    ///
716    /// ```
717    /// use sql_values::postgres::PgTimeZone;
718    ///
719    /// let offset = |setting| PgTimeZone::parse(setting).unwrap().fixed_offset();
720    /// #[cfg(feature = "tzdb")]
721    /// {
722    ///     assert_eq!(offset("UTC"), Some(0));
723    ///     assert_eq!(offset("Etc/GMT+5"), Some(-18_000));
724    ///     assert_eq!(offset("Europe/Rome"), None);
725    /// }
726    /// assert_eq!(offset("+2"), Some(7_200));
727    /// assert_eq!(offset("interval '-01:00'"), Some(-3_600));
728    /// assert_eq!(offset("+05:30"), Some(-19_800));
729    /// // Daylight saving time all year, and a daylight offset equal to the standard one.
730    /// assert_eq!(offset("EST5EDT,0/0,J365/26"), Some(-14_400));
731    /// assert_eq!(offset("EST5EDT5"), Some(-18_000));
732    /// // Daylight saving time that ends at the instant it starts again still has two offsets.
733    /// assert_eq!(offset("EST5EDT,0/0,J365/25"), None);
734    /// assert_eq!(offset("EST5EDT"), None);
735    /// ```
736    #[must_use]
737    pub fn fixed_offset(&self) -> Option<i32> {
738        match &self.rules {
739            Rules::Fixed { offset, .. } => Some(*offset),
740            Rules::Posix { rules, .. } => (!rules.switches || rules.std_offset == rules.dst_offset)
741                .then(|| rules.offset(true)),
742            // `load` keeps an IANA zone without transitions as `Fixed`, and every transition in
743            // jiff's database changes the offset.
744            #[cfg(feature = "tzdb")]
745            Rules::Iana(_) => None,
746        }
747    }
748
749    /// Seconds east of UTC in effect at `unix` seconds from 1970, as `pg_localtime` finds it, or
750    /// `None` where an IANA zone is asked about an instant outside jiff's years.
751    pub(crate) fn utc_offset(&self, unix: i64) -> Option<i32> {
752        match &self.rules {
753            Rules::Fixed { offset, .. } => Some(*offset),
754            Rules::Posix { rules, .. } => Some(rules.offset_at(unix)),
755            #[cfg(feature = "tzdb")]
756            Rules::Iana(zone) => Some(zone.to_offset(Timestamp::from_second(unix).ok()?).seconds()),
757        }
758    }
759
760    /// The offset east of UTC in effect at `unix` and the first transition after it, its moment
761    /// and the offset east after it, as `pg_next_dst_boundary` finds them.
762    fn next_boundary(&self, unix: i64) -> Option<(i32, Option<(i64, i32)>)> {
763        match &self.rules {
764            Rules::Fixed { offset, .. } => Some((*offset, None)),
765            Rules::Posix { rules, .. } => {
766                Some((rules.offset_at(unix), rules.next_transition(unix)))
767            }
768            #[cfg(feature = "tzdb")]
769            Rules::Iana(zone) => {
770                let at = Timestamp::from_second(unix).ok()?;
771                let next = zone
772                    .following(at)
773                    .next()
774                    .map(|change| (change.timestamp().as_second(), change.offset().seconds()));
775                Some((zone.to_offset(at).seconds(), next))
776            }
777        }
778    }
779
780    /// The offset east of UTC that `DetermineTimeZoneOffsetInternal` gives a local clock of
781    /// `local` seconds from 1970 read as UTC: the offset at the first transition after the
782    /// clock less a day, a clock the change skips taking the offset before it and one it repeats
783    /// the offset after it. `None` where an IANA zone is asked about a clock outside jiff's
784    /// years.
785    pub(crate) fn local_offset(&self, local: i64) -> Option<i32> {
786        let (before, next) = self.next_boundary(local - SECS_PER_DAY)?;
787        let Some((boundary, after)) = next else {
788            return Some(before);
789        };
790        let before_time = local - i64::from(before);
791        let after_time = local - i64::from(after);
792        Some(if before_time < boundary && after_time < boundary {
793            before
794        } else if before_time >= boundary && after_time >= boundary {
795            after
796        } else if before_time > after_time {
797            before
798        } else {
799            after
800        })
801    }
802}
803
804impl PgTimeZone {
805    /// `pg_timezone_abbrev_is_known`, the meaning of the uppercased `abbreviation` among the
806    /// zone's own, and whether it has only that one.
807    pub(crate) fn abbreviation_is_known(
808        &self,
809        abbreviation: &str,
810    ) -> Option<(AbbreviationUse, bool)> {
811        let mut uses = Vec::new();
812        match &self.rules {
813            Rules::Fixed {
814                offset,
815                abbreviation: own,
816            } => {
817                if own == abbreviation {
818                    uses.push(AbbreviationUse {
819                        offset: *offset,
820                        dst: false,
821                    });
822                }
823            }
824            Rules::Posix {
825                rules,
826                std_name,
827                dst_name,
828            } => uses.extend(posix_use(rules, std_name, dst_name, abbreviation)),
829            #[cfg(feature = "tzdb")]
830            Rules::Iana(zone) => {
831                let first = zone.to_offset_info(Timestamp::MIN);
832                if first.abbreviation() == abbreviation {
833                    uses.push(AbbreviationUse {
834                        offset: first.offset().seconds(),
835                        dst: first.dst().is_dst(),
836                    });
837                }
838                for change in zone
839                    .following(Timestamp::MIN)
840                    .take_while(|change| change.timestamp().as_second() <= ABBREVIATION_SCAN_END)
841                {
842                    if change.abbreviation() == abbreviation {
843                        uses.push(AbbreviationUse {
844                            offset: change.offset().seconds(),
845                            dst: change.dst().is_dst(),
846                        });
847                    }
848                }
849            }
850        }
851        let first = *uses.first()?;
852        Some((first, uses.iter().all(|other| *other == first)))
853    }
854
855    /// `pg_interpret_timezone_abbrev`, the meaning the uppercased `abbreviation` had in the zone
856    /// at `unix` seconds from 1970: the latest before it, else the one before every transition,
857    /// else the first after it.
858    ///
859    /// # Errors
860    ///
861    /// [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about an instant outside
862    /// jiff's years.
863    pub(crate) fn interpret_abbreviation(
864        &self,
865        abbreviation: &str,
866        #[cfg_attr(
867            not(feature = "tzdb"),
868            expect(unused_variables, reason = "only an IANA zone reads the instant")
869        )]
870        unix: i64,
871    ) -> Result<Option<AbbreviationUse>, DateTimeError> {
872        match &self.rules {
873            Rules::Fixed { .. } | Rules::Posix { .. } => Ok(self
874                .abbreviation_is_known(abbreviation)
875                .map(|(use_, _)| use_)),
876            #[cfg(feature = "tzdb")]
877            Rules::Iana(zone) => interpret_iana_abbreviation(zone, abbreviation, unix),
878        }
879    }
880}
881
882/// [`PgTimeZone::interpret_abbreviation`] in an IANA zone.
883#[cfg(feature = "tzdb")]
884fn interpret_iana_abbreviation(
885    zone: &TimeZone,
886    abbreviation: &str,
887    unix: i64,
888) -> Result<Option<AbbreviationUse>, DateTimeError> {
889    let at = Timestamp::from_second(unix).map_err(|_| DateTimeError::OutsideJiffRange)?;
890    let after = Timestamp::from_second(unix + 1).unwrap_or(Timestamp::MAX);
891    let matching = |abbreviation_used: &str, offset: jiff::tz::Offset, dst: jiff::tz::Dst| {
892        (abbreviation_used == abbreviation).then(|| AbbreviationUse {
893            offset: offset.seconds(),
894            dst: dst.is_dst(),
895        })
896    };
897    if let Some(found) = zone
898        .preceding(after)
899        .find_map(|change| matching(change.abbreviation(), change.offset(), change.dst()))
900    {
901        return Ok(Some(found));
902    }
903    let first = zone.to_offset_info(Timestamp::MIN);
904    if let Some(found) = matching(first.abbreviation(), first.offset(), first.dst()) {
905        return Ok(Some(found));
906    }
907    Ok(zone
908        .following(at)
909        .take_while(|change| change.timestamp().as_second() <= ABBREVIATION_SCAN_END)
910        .find_map(|change| matching(change.abbreviation(), change.offset(), change.dst())))
911}
912
913/// The meaning of `abbreviation` in a POSIX zone, whose `tzparse` types are the standard one,
914/// named first, and the daylight one, or the daylight one alone for a zone in daylight saving
915/// time throughout.
916fn posix_use(
917    rules: &Posix,
918    std_name: &str,
919    dst_name: &str,
920    abbreviation: &str,
921) -> Option<AbbreviationUse> {
922    if std_name == abbreviation {
923        rules.switches.then(|| AbbreviationUse {
924            offset: rules.offset(false),
925            dst: false,
926        })
927    } else if dst_name == abbreviation {
928        Some(AbbreviationUse {
929            offset: rules.offset(true),
930            dst: true,
931        })
932    } else {
933        None
934    }
935}
936
937impl PartialEq for PgTimeZone {
938    fn eq(&self, other: &Self) -> bool {
939        self.name == other.name
940    }
941}
942
943impl Eq for PgTimeZone {}
944
945impl Hash for PgTimeZone {
946    fn hash<H: Hasher>(&self, state: &mut H) {
947        self.name.hash(state);
948    }
949}
950
951impl fmt::Display for PgTimeZone {
952    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
953        f.write_str(&self.name)
954    }
955}