Skip to main content

utopia_database/
datetime.rs

1//! Dates as the database stores them: `Y-m-d H:i:s.v` in the default
2//! timezone ([`FORMAT_DB`]), and as the API shows them, with the offset
3//! ([`FORMAT_TZ`]).
4//!
5//! Dates are [`php_std::datetime::DateTime`], a port of PHP's own date
6//! library, so parsing, timezone conversion and formatting are PHP's.
7//!
8//! PHP: `Utopia\Database\DateTime`. PHP's default timezone
9//! (`date_default_timezone_get()`) is UTC, as Appwrite sets it; here it is
10//! UTC.
11//!
12//! ```
13//! use utopia_database::datetime;
14//!
15//! assert_eq!(datetime::set_timezone("2024-01-02 03:04:05.678+02:00").unwrap(), "2024-01-02 01:04:05.678");
16//! assert_eq!(datetime::format_tz(Some("2024-01-02 01:04:05.678")).as_deref(), Some("2024-01-02T01:04:05.678+00:00"));
17//! ```
18
19use php_std::datetime::{DateTime, Interval, TimeZone, TzInfo};
20
21use crate::error::{Error, Kind, Result};
22
23/// How the database stores dates (`DateTime::$formatDb`).
24pub const FORMAT_DB: &str = "Y-m-d H:i:s.v";
25
26/// How dates are shown with their offset (`DateTime::$formatTz`).
27pub const FORMAT_TZ: &str = "Y-m-d\\TH:i:s.vP";
28
29/// The current time in the database format.
30///
31/// PHP: `DateTime::now()`.
32pub fn now() -> String {
33    // "now" always parses.
34    DateTime::new(b"now", None, &TzInfo::utc()).map(|date| format(&date)).unwrap_or_default()
35}
36
37/// A parse failure as PHP's library reports it: a database exception
38/// wrapping the `DateMalformedStringException` with the same message.
39fn malformed(message: &str) -> Error {
40    Error::database(message).with_previous(Error::new(Kind::DateMalformedString, message))
41}
42
43/// The current time in the database format, made later than `previous`:
44/// when `previous` is not before now (a clock that went back, or two
45/// writes within one millisecond), one millisecond after `previous`.
46///
47/// Fails with the parser's message when `previous` is not a date
48/// ([`Kind::Database`], wrapping the [`Kind::DateMalformedString`] error).
49///
50/// PHP: `DateTime::nowAfter($previous)`.
51pub fn now_after(previous: Option<&str>) -> Result<String> {
52    let current = now();
53    let Some(previous) = previous else { return Ok(current) };
54    let date = DateTime::new(current.as_bytes(), None, &TzInfo::utc()).map_err(|e| malformed(&e.message()))?;
55    let mut minimum = DateTime::new(previous.as_bytes(), None, &TzInfo::utc()).map_err(|e| malformed(&e.message()))?;
56    if date <= minimum {
57        minimum.modify(b"+1 millisecond").map_err(|e| malformed(&e.message()))?;
58        return Ok(format(&minimum));
59    }
60    Ok(current)
61}
62
63/// `date` in the database format ([`FORMAT_DB`]).
64///
65/// PHP: `DateTime::format($date)`.
66pub fn format(date: &DateTime) -> String {
67    text(date.format(FORMAT_DB.as_bytes()))
68}
69
70/// Adds `seconds` (negative to subtract) to `date`, and returns it in the
71/// database format.
72///
73/// Fails like PHP for `i64::MIN` seconds, which PHP's interval parser does
74/// not read as a number (a [`Kind::DateMalformedIntervalString`] error).
75///
76/// PHP: `DateTime::addSeconds($date, $seconds)`.
77pub fn add_seconds(date: &mut DateTime, seconds: i64) -> Result<String> {
78    let interval = Interval::from_date_string(format!("{seconds} seconds").as_bytes())
79        .map_err(|e| Error::new(Kind::DateMalformedIntervalString, e.message()))?;
80    date.add(&interval);
81    Ok(format(date))
82}
83
84/// `datetime` (any string PHP's `DateTime` parses) converted to the default
85/// timezone, in the database format.
86///
87/// Fails with the parser's message when `datetime` is not a date
88/// ([`Kind::Database`], wrapping the [`Kind::DateMalformedString`] error).
89///
90/// PHP: `DateTime::setTimezone($datetime)`.
91pub fn set_timezone(datetime: impl AsRef<[u8]>) -> Result<String> {
92    let mut value = DateTime::new(datetime.as_ref(), None, &TzInfo::utc()).map_err(|e| malformed(&e.message()))?;
93    value.set_timezone(&TimeZone::utc());
94    Ok(format(&value))
95}
96
97/// `value` with its offset ([`FORMAT_TZ`]); `value` itself when it is not
98/// a date, and `None` for `None`.
99///
100/// PHP: `DateTime::formatTz($dbFormat)`.
101pub fn format_tz(value: Option<&str>) -> Option<String> {
102    let value = value?;
103    if let Some(formatted) = format_tz_stored(value) {
104        return Some(formatted);
105    }
106    Some(match DateTime::new(value.as_bytes(), None, &TzInfo::utc()) {
107        Ok(date) => text(date.format(FORMAT_TZ.as_bytes())),
108        Err(_) => value.to_owned(),
109    })
110}
111
112/// [`format_tz`] of a date as the database returns it: `Y-m-d H:i:s` with
113/// up to six fraction digits and every field in range, which parses to
114/// itself in UTC, so its digits are copied (milliseconds are the first three
115/// fraction digits). `None` for anything else, which goes through the parser.
116fn format_tz_stored(value: &str) -> Option<String> {
117    let b = value.as_bytes();
118    if b.len() < 19 || b[4] != b'-' || b[7] != b'-' || b[10] != b' ' || b[13] != b':' || b[16] != b':' {
119        return None;
120    }
121    let number = |range: std::ops::Range<usize>| -> Option<u32> {
122        b[range].iter().try_fold(0u32, |n, c| c.is_ascii_digit().then(|| n * 10 + u32::from(c - b'0')))
123    };
124    let (year, month, day) = (number(0..4)?, number(5..7)?, number(8..10)?);
125    let (hour, minute, second) = (number(11..13)?, number(14..16)?, number(17..19)?);
126    let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
127    let days = match month {
128        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
129        4 | 6 | 9 | 11 => 30,
130        2 if leap => 29,
131        2 => 28,
132        _ => return None,
133    };
134    if year < 1000 || day == 0 || day > days || hour > 23 || minute > 59 || second > 59 {
135        return None;
136    }
137    let fraction = match &b[19..] {
138        [] => &[][..],
139        [b'.', digits @ ..] if (1..=6).contains(&digits.len()) && digits.iter().all(u8::is_ascii_digit) => digits,
140        _ => return None,
141    };
142    let mut out = String::with_capacity(29);
143    out.push_str(&value[..10]);
144    out.push('T');
145    out.push_str(&value[11..19]);
146    out.push('.');
147    for i in 0..3 {
148        out.push(char::from(*fraction.get(i).unwrap_or(&b'0')));
149    }
150    out.push_str("+00:00");
151    Some(out)
152}
153
154/// Formatted bytes as text (the formats here only produce ASCII).
155fn text(bytes: Vec<u8>) -> String {
156    String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    /// The parser's answer, which the stored-date path must match.
164    fn parsed(value: &str) -> String {
165        match DateTime::new(value.as_bytes(), None, &TzInfo::utc()) {
166            Ok(date) => text(date.format(FORMAT_TZ.as_bytes())),
167            Err(_) => value.to_owned(),
168        }
169    }
170
171    #[test]
172    fn stored_dates_format_as_the_parser_does() {
173        let mut values: Vec<String> = [
174            "2024-01-02 01:04:05.678",
175            "2024-01-02 01:04:05.67",
176            "2024-01-02 01:04:05.6",
177            "2024-01-02 01:04:05",
178            "2024-01-02 01:04:05.000",
179            "2024-01-02 01:04:05.123456",
180            "2024-02-29 23:59:59.999",
181            "2023-02-29 00:00:00.000",
182            "2100-02-29 00:00:00.000",
183            "2000-02-29 00:00:00.000",
184            "2024-04-31 00:00:00.000",
185            "2024-13-01 00:00:00.000",
186            "2024-00-10 00:00:00.000",
187            "2024-01-00 00:00:00.000",
188            "2024-01-01 24:00:00.000",
189            "2024-01-01 23:60:00.000",
190            "2024-01-01 23:59:60.000",
191            "0999-01-01 00:00:00.000",
192            "2024-01-01 00:00:00.1234567",
193            "2024-01-01 00:00:00.",
194            "2024-01-01T00:00:00.000",
195            "2024-01-01 00:00:00.000+02:00",
196            "2024-01-01 00:00:00.000 ",
197            "not a date",
198        ]
199        .map(str::to_owned)
200        .to_vec();
201        for year in [1970, 1999, 2000, 2024, 2025, 9999] {
202            for month in 1..=12 {
203                for day in [1, 28, 29, 30, 31] {
204                    values.push(format!("{year:04}-{month:02}-{day:02} 13:07:59.042"));
205                }
206            }
207        }
208        for value in &values {
209            assert_eq!(format_tz(Some(value)).unwrap(), parsed(value), "{value}");
210        }
211        assert_eq!(format_tz_stored("2024-01-02 01:04:05.67").as_deref(), Some("2024-01-02T01:04:05.670+00:00"));
212        assert_eq!(format_tz_stored("2024-01-02T01:04:05.678"), None);
213    }
214}