1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
910//! A time Date abstract data type.
1112use std::convert::TryFrom;
13use std::fmt;
14use std::ops::Sub;
15use std::sync::LazyLock;
1617use anyhow::anyhow;
18use chrono::NaiveDate;
19use mz_proto::{RustType, TryFromProtoError};
20use serde::{Deserialize, Serialize};
21use thiserror::Error;
2223include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.date.rs"));
2425#[derive(Debug, Error)]
26pub enum DateError {
27#[error("data out of range")]
28OutOfRange,
29}
3031/// A Postgres-compatible Date. Additionally clamp valid dates for the range
32/// that chrono supports to allow for safe string operations. Infinite dates are
33/// not yet supported.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Hash, Deserialize)]
35pub struct Date {
36/// Number of days from the postgres epoch (2000-01-01).
37days: i32,
38}
3940impl RustType<ProtoDate> for Date {
41fn into_proto(&self) -> ProtoDate {
42 ProtoDate { days: self.days }
43 }
4445fn from_proto(proto: ProtoDate) -> Result<Self, TryFromProtoError> {
46Ok(Date { days: proto.days })
47 }
48}
4950impl std::str::FromStr for Date {
51type Err = anyhow::Error;
5253fn from_str(s: &str) -> Result<Self, Self::Err> {
54crate::strconv::parse_date(s).map_err(|e| anyhow!(e))
55 }
56}
5758static PG_EPOCH: LazyLock<NaiveDate> =
59 LazyLock::new(|| NaiveDate::from_ymd_opt(2000, 1, 1).unwrap());
6061impl Date {
62pub const UNIX_EPOCH_TO_PG_EPOCH: i32 = 10957; // Number of days from 1970-01-01 to 2000-01-01.
63const CE_EPOCH_TO_PG_EPOCH: i32 = 730120; // Number of days since 0001-01-01 to 2000-01-01.
64pub const LOW_DAYS: i32 = -2451545; // 4714-11-24 BC
6566/// Largest date support by Materialize. Although Postgres can go up to
67 /// 5874897-12-31, chrono is limited to December 31, 262142, which we mirror
68 /// here so we can use chrono's formatting methods and have guaranteed safe
69 /// conversions.
70pub const HIGH_DAYS: i32 = 95_015_279;
7172/// Constructs a new `Date` as the days since the postgres epoch
73 /// (2000-01-01).
74pub fn from_pg_epoch(days: i32) -> Result<Date, DateError> {
75if days < Self::LOW_DAYS || days > Self::HIGH_DAYS {
76Err(DateError::OutOfRange)
77 } else {
78Ok(Date { days })
79 }
80 }
8182/// Constructs a new `Date` as the days since the Unix epoch.
83pub fn from_unix_epoch(unix_days: i32) -> Result<Date, DateError> {
84let pg_days = unix_days.saturating_sub(Self::UNIX_EPOCH_TO_PG_EPOCH);
85if pg_days == i32::MIN {
86return Err(DateError::OutOfRange);
87 }
88Self::from_pg_epoch(pg_days)
89 }
9091/// Returns the number of days since the postgres epoch.
92pub fn pg_epoch_days(&self) -> i32 {
93self.days
94 }
9596/// Returns whether this is the infinity or -infinity date.
97 ///
98 /// Currently we do not support these, so this function is a light
99 /// protection against if they are added for functions that will produce
100 /// incorrect results for these values.
101pub fn is_finite(&self) -> bool {
102self.days != i32::MAX && self.days != i32::MIN
103 }
104105/// Returns the number of days since the Unix epoch.
106pub fn unix_epoch_days(&self) -> i32 {
107assert!(self.is_finite());
108// Guaranteed to be safe because we clamp the high date by less than the
109 // result of this.
110self.days + Self::UNIX_EPOCH_TO_PG_EPOCH
111 }
112113/// Returns this date with `days` added to it.
114pub fn checked_add(self, days: i32) -> Result<Date, DateError> {
115let days = if let Some(days) = self.days.checked_add(days) {
116 days
117 } else {
118return Err(DateError::OutOfRange);
119 };
120Self::from_pg_epoch(days)
121 }
122}
123124impl Sub for Date {
125type Output = i32;
126127fn sub(self, rhs: Self) -> Self::Output {
128assert!(self.is_finite());
129self.days - rhs.days
130 }
131}
132133impl From<Date> for NaiveDate {
134fn from(date: Date) -> Self {
135Self::from(&date)
136 }
137}
138139impl From<&Date> for NaiveDate {
140fn from(date: &Date) -> Self {
141let days = date
142 .pg_epoch_days()
143 .checked_add(Date::CE_EPOCH_TO_PG_EPOCH)
144 .expect("out of range date are prevented");
145 NaiveDate::from_num_days_from_ce_opt(days).unwrap()
146 }
147}
148149impl TryFrom<NaiveDate> for Date {
150type Error = DateError;
151152fn try_from(value: NaiveDate) -> Result<Self, Self::Error> {
153let d = value.signed_duration_since(*PG_EPOCH);
154let days: i32 = d.num_days().try_into().map_err(|_| DateError::OutOfRange)?;
155Self::from_pg_epoch(days)
156 }
157}
158159/// Format an Date in a human form
160impl fmt::Display for Date {
161fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162let d: NaiveDate = (*self).into();
163 d.format("%Y-%m-%d").fmt(f)
164 }
165}
166167#[cfg(test)]
168mod test {
169use super::*;
170171#[mz_ore::test]
172fn test_date() {
173let pgepoch = Date::from_pg_epoch(0).unwrap();
174let unixepoch = Date::from_unix_epoch(0).unwrap();
175assert_eq!(pgepoch.pg_epoch_days(), 0);
176assert_eq!(pgepoch.unix_epoch_days(), 10957);
177assert_eq!(unixepoch.pg_epoch_days(), -10957);
178assert_eq!(unixepoch.unix_epoch_days(), 0);
179assert_eq!(
180 NaiveDate::from(pgepoch),
181 NaiveDate::from_ymd_opt(2000, 1, 1).unwrap()
182 );
183assert_eq!(
184 pgepoch,
185 Date::try_from(NaiveDate::from_ymd_opt(2000, 1, 1).unwrap()).unwrap()
186 );
187assert_eq!(
188 unixepoch,
189 Date::try_from(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()).unwrap()
190 );
191assert_eq!(
192 unixepoch,
193 Date::try_from(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()).unwrap()
194 );
195assert!(pgepoch > unixepoch);
196 }
197}