Skip to main content

sql_values/postgres/
date_trunc.rs

1//! PostgreSQL 18's `date_trunc`, `timestamp_trunc`, `timestamptz_trunc_internal` and
2//! `interval_trunc`, with the unit `DecodeUnits` reads from text.
3
4use super::datetime::{
5    POSTGRES_EPOCH_JDATE, USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, date2j,
6    is_valid_julian, j2date, local_offset, timestamp2tm, tm2timestamp,
7    tokens::{
8        DTK_CENTURY, DTK_DAY, DTK_DECADE, DTK_HOUR, DTK_MICROSEC, DTK_MILLENNIUM, DTK_MILLISEC,
9        DTK_MINUTE, DTK_MONTH, DTK_QUARTER, DTK_SECOND, DTK_WEEK, DTK_YEAR, UNITS,
10    },
11    utc_offset,
12};
13use super::interval::decode_units;
14use super::{DateTimeError, PgInterval, PgTimeZone, PgTimestamp, PgTimestampTz};
15
16/// A unit `date_trunc` truncates a `timestamp`, `timestamptz` or `interval` to.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum DateTruncField {
19    /// `microseconds`, which leaves the value as it is.
20    Microseconds,
21    /// `milliseconds`, dropping the microseconds of the millisecond.
22    Milliseconds,
23    /// `second`.
24    Second,
25    /// `minute`.
26    Minute,
27    /// `hour`.
28    Hour,
29    /// `day`.
30    Day,
31    /// `week`, the Monday that starts the ISO week, which an interval refuses.
32    Week,
33    /// `month`.
34    Month,
35    /// `quarter`, the first month of the quarter.
36    Quarter,
37    /// `year`.
38    Year,
39    /// `decade`, as `timestamp_trunc` counts decades, 2020 for 2024 and 11 BC for 2 BC.
40    Decade,
41    /// `century`, its first year, 2001 for 2024 and 100 BC for 1 BC.
42    Century,
43    /// `millennium`, its first year, 2001 for 2024 and 1000 BC for 1 BC.
44    Millennium,
45}
46
47/// Why PostgreSQL refuses the unit of a `date_trunc`, one variant per message it raises, which
48/// quotes the lowercased unit and names the input type, as in `unit "epoch" not recognized for
49/// type timestamp without time zone`.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
51pub enum DateTruncError {
52    /// Text that names no unit, `epoch` and `dow` among them.
53    #[error("unit not recognized")]
54    UnitNotRecognized,
55    /// A unit `date_trunc` does not truncate the type to, `timezone` for every type and
56    /// [`DateTruncField::Week`] for an interval.
57    #[error("unit not supported")]
58    UnitNotSupported,
59}
60
61impl DateTruncField {
62    /// The unit PostgreSQL's `date_trunc` reads from `unit`, ASCII letters in either case, with
63    /// the first ten characters deciding as `DecodeUnits` compares them.
64    ///
65    /// # Errors
66    ///
67    /// [`DateTruncError::UnitNotRecognized`] for text `DecodeUnits` does not know, and
68    /// [`DateTruncError::UnitNotSupported`] for the `timezone` units it knows.
69    ///
70    /// ```
71    /// use sql_values::postgres::{DateTruncError, DateTruncField};
72    ///
73    /// assert_eq!(DateTruncField::parse("Hours"), Ok(DateTruncField::Hour));
74    /// assert_eq!(DateTruncField::parse("microseconds"), Ok(DateTruncField::Microseconds));
75    /// assert_eq!(DateTruncField::parse("epoch"), Err(DateTruncError::UnitNotRecognized));
76    /// assert_eq!(DateTruncField::parse("timezone"), Err(DateTruncError::UnitNotSupported));
77    /// ```
78    pub fn parse(unit: &str) -> Result<Self, DateTruncError> {
79        match decode_units(unit) {
80            (UNITS, DTK_MICROSEC) => Ok(Self::Microseconds),
81            (UNITS, DTK_MILLISEC) => Ok(Self::Milliseconds),
82            (UNITS, DTK_SECOND) => Ok(Self::Second),
83            (UNITS, DTK_MINUTE) => Ok(Self::Minute),
84            (UNITS, DTK_HOUR) => Ok(Self::Hour),
85            (UNITS, DTK_DAY) => Ok(Self::Day),
86            (UNITS, DTK_WEEK) => Ok(Self::Week),
87            (UNITS, DTK_MONTH) => Ok(Self::Month),
88            (UNITS, DTK_QUARTER) => Ok(Self::Quarter),
89            (UNITS, DTK_YEAR) => Ok(Self::Year),
90            (UNITS, DTK_DECADE) => Ok(Self::Decade),
91            (UNITS, DTK_CENTURY) => Ok(Self::Century),
92            (UNITS, DTK_MILLENNIUM) => Ok(Self::Millennium),
93            (UNITS, _) => Err(DateTruncError::UnitNotSupported),
94            _ => Err(DateTruncError::UnitNotRecognized),
95        }
96    }
97
98    /// Whether the truncated clock is a local midnight, whose offset `timestamptz_trunc`
99    /// determines again.
100    const fn reaches_midnight(self) -> bool {
101        !matches!(
102            self,
103            Self::Microseconds | Self::Milliseconds | Self::Second | Self::Minute | Self::Hour
104        )
105    }
106
107    /// `timestamp2tm`'s year, month, day and clock of the local clock `local`, microseconds from
108    /// 2000-01-01, truncated as `timestamp_trunc` truncates them.
109    fn truncate_local(self, local: i64) -> (i32, i32, i32, i64) {
110        let (mut year, mut month, mut day, clock) = timestamp2tm(local);
111        let clock_step = match self {
112            Self::Microseconds => 1,
113            Self::Milliseconds => 1_000,
114            Self::Second => USECS_PER_SEC,
115            Self::Minute => USECS_PER_MINUTE,
116            Self::Hour => USECS_PER_HOUR,
117            _ => USECS_PER_DAY,
118        };
119        let clock = clock - clock % clock_step;
120        match self {
121            Self::Week => {
122                // The Julian day of a Monday is a multiple of seven.
123                let julian_day = date2j(year, month, day);
124                (year, month, day) = j2date(julian_day - julian_day.rem_euclid(7));
125            }
126            Self::Month => day = 1,
127            Self::Quarter => (month, day) = (month - (month - 1) % 3, 1),
128            Self::Year => (month, day) = (1, 1),
129            Self::Decade => {
130                year = if year > 0 {
131                    year / 10 * 10
132                } else {
133                    -((8 - (year - 1)) / 10) * 10
134                };
135                (month, day) = (1, 1);
136            }
137            Self::Century => (year, month, day) = (first_year_of(year, 100), 1, 1),
138            Self::Millennium => (year, month, day) = (first_year_of(year, 1_000), 1, 1),
139            _ => {}
140        }
141        (year, month, day, clock)
142    }
143}
144
145/// The first year of the `span`-year period holding `year`, where year `Y` BC is year `1 - Y`,
146/// periods starting at year 1 AD and ending at year 1 BC, as `timestamp_trunc` counts centuries
147/// and millennia.
148const fn first_year_of(year: i32, span: i32) -> i32 {
149    if year > 0 {
150        (year + span - 1) / span * span - span + 1
151    } else {
152        -((span - 1 - (year - 1)) / span) * span + 1
153    }
154}
155
156impl PgTimestamp {
157    /// PostgreSQL's `date_trunc(field, timestamp)`, the timestamp with every field finer than
158    /// `field` reset, an infinity left as it is.
159    ///
160    /// # Errors
161    ///
162    /// [`DateTimeError::TimestampOutOfRange`] where the truncated timestamp leaves PostgreSQL's
163    /// range, as a year of 4714 BC does, or as every unit of the stored 294277-01-01 that
164    /// `timestamp(0)` rounds the last second up to does.
165    ///
166    /// ```
167    /// use sql_values::postgres::{DateTruncField, InputContext, PgTimestamp};
168    ///
169    /// let at = |text| PgTimestamp::parse(text, InputContext::new()).unwrap();
170    /// let late = at("2024-02-29 23:59:59.999500");
171    /// assert_eq!(late.date_trunc(DateTruncField::Milliseconds), Ok(at("2024-02-29 23:59:59.999")));
172    /// assert_eq!(late.date_trunc(DateTruncField::Week), Ok(at("2024-02-26 00:00:00")));
173    /// let first_bc = at("0001-12-31 23:59:59.999999 BC");
174    /// assert_eq!(first_bc.date_trunc(DateTruncField::Century), Ok(at("0100-01-01 BC")));
175    /// ```
176    pub fn date_trunc(self, field: DateTruncField) -> Result<Self, DateTimeError> {
177        if !self.is_finite() {
178            return Ok(self);
179        }
180        let (year, month, day, clock) = field.truncate_local(self.pg_micros());
181        tm2timestamp(year, month, day, clock, 0)
182            .map(Self::from_stored)
183            .ok_or(DateTimeError::TimestampOutOfRange)
184    }
185}
186
187impl PgTimestampTz {
188    /// PostgreSQL's `date_trunc(field, timestamptz, zone)`, the instant whose local clock in
189    /// `zone` has every field finer than `field` reset, an infinity left as it is.
190    ///
191    /// Truncating to an hour or finer keeps the offset the instant had, so each hour a fall-back
192    /// repeats truncates to its own start. Truncating to a day or coarser places the truncated
193    /// clock in `zone` as [`PgTimestamp::to_timestamptz`] does.
194    ///
195    /// The two-argument `date_trunc(field, timestamptz)` passes the session's `TimeZone` as
196    /// `zone`. PostgreSQL has no `date_trunc` of a `date`, and reads one as the `timestamptz`
197    /// of its midnight in the session's `TimeZone`,
198    /// [`PgDate::to_timestamp`](super::PgDate::to_timestamp) then
199    /// [`PgTimestamp::to_timestamptz`], before truncating it in `zone`.
200    ///
201    /// # Errors
202    ///
203    /// [`DateTimeError::TimestampOutOfRange`] where the local clock or the truncated instant
204    /// falls outside PostgreSQL's range.
205    ///
206    /// ```
207    /// use sql_values::postgres::{DateTruncField, InputContext, PgDate, PgTimeZone, PgTimestampTz};
208    ///
209    /// #[cfg(feature = "tzdb")]
210    /// {
211    ///     let at = |text| PgTimestampTz::parse(text, InputContext::new()).unwrap();
212    ///     let new_york = PgTimeZone::parse("America/New_York").unwrap();
213    ///     let (first, second) = (at("2024-11-03 05:30:00+00"), at("2024-11-03 06:30:00+00"));
214    ///     let hour = |at: PgTimestampTz| at.date_trunc(DateTruncField::Hour, &new_york);
215    ///     assert_eq!(hour(first), Ok(at("2024-11-03 05:00:00+00")));
216    ///     assert_eq!(hour(second), Ok(at("2024-11-03 06:00:00+00")));
217    ///     let day = second.date_trunc(DateTruncField::Day, &new_york);
218    ///     assert_eq!(day, Ok(at("2024-11-03 04:00:00+00")));
219    ///
220    ///     // date_trunc('day', date '2024-02-29', 'Australia/Sydney') in a New York session.
221    ///     let sydney = PgTimeZone::parse("Australia/Sydney").unwrap();
222    ///     let leap = PgDate::from_ymd(2024, 2, 29).unwrap();
223    ///     let midnight = leap.to_timestamp().unwrap().to_timestamptz(&new_york).unwrap();
224    ///     let day = midnight.date_trunc(DateTruncField::Day, &sydney);
225    ///     assert_eq!(day, Ok(at("2024-02-28 08:00:00-05")));
226    /// }
227    /// ```
228    pub fn date_trunc(
229        self,
230        field: DateTruncField,
231        zone: &PgTimeZone,
232    ) -> Result<Self, DateTimeError> {
233        if !self.is_finite() {
234            return Ok(self);
235        }
236        let offset = utc_offset(zone, self.pg_micros());
237        let local = self.pg_micros() + i64::from(offset) * USECS_PER_SEC;
238        let (year, month, day, clock) = field.truncate_local(local);
239        let offset = if field.reaches_midnight() {
240            if !is_valid_julian(year, month) {
241                return Err(DateTimeError::TimestampOutOfRange);
242            }
243            let days = i64::from(date2j(year, month, day) - POSTGRES_EPOCH_JDATE);
244            local_offset(zone, days * USECS_PER_DAY + clock)
245        } else {
246            offset
247        };
248        tm2timestamp(year, month, day, clock, offset)
249            .map(Self::from_stored)
250            .ok_or(DateTimeError::TimestampOutOfRange)
251    }
252}
253
254impl PgInterval {
255    /// PostgreSQL's `date_trunc(field, interval)`, every field finer than `field` reset, each
256    /// toward zero, where a year is twelve months and a month never folds into days. An infinity
257    /// is left as it is.
258    ///
259    /// # Errors
260    ///
261    /// [`DateTruncError::UnitNotSupported`] for [`DateTruncField::Week`], since a month holds no
262    /// whole number of weeks, infinities included.
263    ///
264    /// ```
265    /// use sql_values::postgres::{DateTruncError, DateTruncField, parse_interval};
266    ///
267    /// let span = parse_interval("-14 months -3 days -25:02:03.123500").unwrap();
268    /// let truncated = span.date_trunc(DateTruncField::Milliseconds).unwrap();
269    /// assert_eq!(truncated.to_string(), "-1 years -2 mons -3 days -25:02:03.123");
270    /// let quarter = span.date_trunc(DateTruncField::Quarter).unwrap();
271    /// assert_eq!(quarter.to_string(), "-1 years");
272    /// assert_eq!(span.date_trunc(DateTruncField::Week), Err(DateTruncError::UnitNotSupported));
273    /// ```
274    pub fn date_trunc(self, field: DateTruncField) -> Result<Self, DateTruncError> {
275        if !self.is_finite() {
276            return match field {
277                DateTruncField::Week => Err(DateTruncError::UnitNotSupported),
278                _ => Ok(self),
279            };
280        }
281        let Self {
282            months,
283            days,
284            microseconds,
285        } = self;
286        let clock = |step: i64| Self {
287            microseconds: microseconds - microseconds % step,
288            ..self
289        };
290        let calendar = |step: i32| Self {
291            months: months - months % step,
292            days: 0,
293            microseconds: 0,
294        };
295        let years = |step: i32| {
296            let years = months / 12;
297            Self {
298                months: (years - years % step) * 12,
299                days: 0,
300                microseconds: 0,
301            }
302        };
303        Ok(match field {
304            DateTruncField::Microseconds => self,
305            DateTruncField::Milliseconds => clock(1_000),
306            DateTruncField::Second => clock(USECS_PER_SEC),
307            DateTruncField::Minute => clock(USECS_PER_MINUTE),
308            DateTruncField::Hour => clock(USECS_PER_HOUR),
309            DateTruncField::Day => Self {
310                months,
311                days,
312                microseconds: 0,
313            },
314            DateTruncField::Week => return Err(DateTruncError::UnitNotSupported),
315            DateTruncField::Month => calendar(1),
316            DateTruncField::Quarter => calendar(3),
317            DateTruncField::Year => calendar(12),
318            DateTruncField::Decade => years(10),
319            DateTruncField::Century => years(100),
320            DateTruncField::Millennium => years(1_000),
321        })
322    }
323}