sql_values/postgres/datetime/input.rs
1//! PostgreSQL 18's `date_in`, `time_in`, `timetz_in`, `timestamp_in` and `timestamptz_in`, and
2//! the readers of the text PostgreSQL, MySQL and SQLite print.
3
4use super::{
5 DateTimeError, POSTGRES_EPOCH_JDATE, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
6 USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, abbreviation_offset, date2j,
7 days_in_month, is_valid_julian, local_offset, tm2timestamp,
8};
9use super::{
10 decode::{
11 DateOrder, DateType, DecodedTime, Dterr, Tm, ZoneSource, current_time, decode_date_time,
12 decode_time_only,
13 },
14 tokens::{Tokens, parse_date_time, parse_fractional_second, strtoint},
15};
16use crate::postgres::{PgTimeZone, PgType, TimeZoneAbbreviations, zone::DEFAULT_ABBREVIATIONS};
17
18/// 1970-01-01 00:00:00, `epoch`, in microseconds from 2000-01-01.
19const EPOCH_MICROS: i64 = -946_684_800_000_000;
20/// 1970-01-01, `epoch`, in days from 2000-01-01.
21const EPOCH_DAYS: i32 = -10_957;
22
23/// The session state PostgreSQL's input functions read, which the caller supplies.
24///
25/// ```
26/// use sql_values::postgres::{
27/// DateTimeError, InputContext, PgTimeZone, PgTimestampTz, TimeZoneAbbreviations,
28/// };
29///
30/// let local = "2026-07-01 12:00:00";
31/// assert_eq!(
32/// PgTimestampTz::parse(local, InputContext::new()),
33/// Err(DateTimeError::NeedsTimeZone),
34/// );
35/// #[cfg(feature = "tzdb")]
36/// {
37/// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
38/// let at = PgTimestampTz::parse(local, InputContext::new().with_time_zone(&rome)).unwrap();
39/// assert_eq!(at.to_string(), "2026-07-01 10:00:00+00");
40/// }
41///
42/// // `EST` is New York's time in `Default` and Brisbane's in `Australia`.
43/// let australia = TimeZoneAbbreviations::bundled("Australia").unwrap();
44/// let context = InputContext::new().with_time_zone_abbreviations(australia);
45/// let est = PgTimestampTz::parse("2026-07-01 12:00 EST", context).unwrap();
46/// assert_eq!(est.to_string(), "2026-07-01 02:00:00+00");
47/// ```
48#[derive(Debug, Clone, Copy)]
49pub struct InputContext<'a> {
50 pub(super) time_zone: Option<&'a PgTimeZone>,
51 pub(super) abbreviations: &'a TimeZoneAbbreviations,
52 pub(super) date_order: Option<DateOrder>,
53 pub(super) now: Option<PgTimestampTz>,
54}
55
56impl<'a> InputContext<'a> {
57 /// A context with no time zone, no `DateStyle` order and no current time, and the `Default`
58 /// abbreviations, as a stock installation's `timezone_abbreviations` names them.
59 #[must_use]
60 pub const fn new() -> Self {
61 Self {
62 time_zone: None,
63 abbreviations: &DEFAULT_ABBREVIATIONS,
64 date_order: None,
65 now: None,
66 }
67 }
68
69 /// The context with `zone` as the session's `TimeZone`, which reads a `timestamptz` or
70 /// `timetz` written without an offset, and whose own abbreviations a literal may write
71 /// before those of the set.
72 #[must_use]
73 pub const fn with_time_zone(self, zone: &'a PgTimeZone) -> Self {
74 Self {
75 time_zone: Some(zone),
76 ..self
77 }
78 }
79
80 /// The context with `abbreviations` as the session's `timezone_abbreviations`.
81 #[must_use]
82 pub const fn with_time_zone_abbreviations(
83 self,
84 abbreviations: &'a TimeZoneAbbreviations,
85 ) -> Self {
86 Self {
87 abbreviations,
88 ..self
89 }
90 }
91
92 /// The context with `order` as the field order of the session's `DateStyle`, which reads a
93 /// date written in numbers alone such as `01/02/2026`.
94 #[must_use]
95 pub const fn with_date_order(self, order: DateOrder) -> Self {
96 Self {
97 date_order: Some(order),
98 ..self
99 }
100 }
101
102 /// The context with `now` as the transaction's start, which `now`, `today`, `tomorrow` and
103 /// `yesterday` read, in the context's time zone, and whose date a `timetz` without a date
104 /// takes its zone's offset on. An infinite `now` reads as
105 /// [`DateTimeError::TimestampOutOfRange`], as no transaction starts at one.
106 #[must_use]
107 pub const fn with_now(self, now: PgTimestampTz) -> Self {
108 Self {
109 now: Some(now),
110 ..self
111 }
112 }
113}
114
115impl Default for InputContext<'_> {
116 fn default() -> Self {
117 Self::new()
118 }
119}
120
121/// `MAXDATELEN`, whose `workbuf` of one byte more bounds a literal's tokens.
122const MAX_DATE_LEN: usize = 128;
123
124/// `ParseDateTime` and `decoder`, `DecodeDateTime` or `DecodeTimeOnly`, over a literal of
125/// `pg_type`, which a NUL ends as it ends a C string.
126fn decode<'a, T>(
127 text: &str,
128 context: InputContext<'a>,
129 pg_type: PgType,
130 decoder: fn(&Tokens, InputContext<'a>) -> Result<T, Dterr>,
131) -> Result<T, DateTimeError> {
132 let text = text.split('\0').next().unwrap_or_default();
133 let tokens = parse_date_time(text.as_bytes(), MAX_DATE_LEN + 1)
134 .map_err(|_| DateTimeError::InvalidInputSyntax(pg_type))?;
135 decoder(&tokens, context).map_err(|error| error.for_type(pg_type))
136}
137
138/// `read` under the context's `DateStyle` order. Without one, a literal the order touches reads
139/// only if every order reads it alike, as `January 8, 1999` does.
140fn by_date_order<'a, T: PartialEq>(
141 context: InputContext<'a>,
142 read: impl Fn(InputContext<'a>) -> Result<T, DateTimeError>,
143) -> Result<T, DateTimeError> {
144 match read(context) {
145 Err(DateTimeError::NeedsDateOrder) => {
146 let [mdy, dmy, ymd] = [DateOrder::Mdy, DateOrder::Dmy, DateOrder::Ymd]
147 .map(|order| read(context.with_date_order(order)));
148 if mdy == dmy && dmy == ymd {
149 mdy
150 } else {
151 Err(DateTimeError::NeedsDateOrder)
152 }
153 }
154 other => other,
155 }
156}
157
158/// The local clock of `tm` to the second, as `DetermineTimeZoneOffset` reads it, in microseconds
159/// from 2000-01-01, or `None` where that overflows.
160fn local_seconds(tm: &Tm) -> Option<i64> {
161 let days = i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
162 let clock = (i64::from(tm.hour) * 60 + i64::from(tm.min)) * 60 + i64::from(tm.sec);
163 days.checked_mul(USECS_PER_DAY)?
164 .checked_add(clock * USECS_PER_SEC)
165}
166
167/// `DetermineTimeZoneOffset` and `DetermineTimeZoneAbbrevOffset` for a `timetz`, whose date
168/// may lie anywhere `ValidateDate` accepts. Outside `IS_VALID_JULIAN` PostgreSQL takes UTC and
169/// reads the abbreviation at the Unix epoch, and a date it can place that jiff cannot is
170/// [`DateTimeError::OutsideJiffRange`].
171fn time_zone_offset(
172 zone: &PgTimeZone,
173 abbreviation: Option<&str>,
174 tm: &Tm,
175) -> Result<i32, DateTimeError> {
176 if !is_valid_julian(tm.year, tm.mon) {
177 return match abbreviation {
178 Some(abbreviation) => Ok(zone
179 .interpret_abbreviation(abbreviation, 0)?
180 .map_or(0, |meaning| meaning.offset)),
181 None => Ok(0),
182 };
183 }
184 let local = local_seconds(tm).ok_or(DateTimeError::OutsideJiffRange)?;
185 match abbreviation {
186 Some(abbreviation) => abbreviation_offset(zone, abbreviation, local),
187 None => local_offset(zone, local),
188 }
189 .map_err(|_| DateTimeError::OutsideJiffRange)
190}
191
192impl PgDate {
193 /// PostgreSQL's `date_in`, reading every spelling `DecodeDateTime` reads, with a clock and
194 /// zone read, checked and ignored.
195 ///
196 /// # Errors
197 ///
198 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
199 /// context lacks, [`DateTimeError::NeedsDateOrder`], [`DateTimeError::NeedsCurrentTime`] or
200 /// [`DateTimeError::NeedsTimeZone`].
201 ///
202 /// ```
203 /// use sql_values::postgres::{DateOrder, DateTimeError, InputContext, PgDate, PgType};
204 ///
205 /// let read = |text, context| PgDate::parse(text, context).map(|d| d.to_string());
206 /// let context = InputContext::new();
207 /// assert_eq!(read("5874897-12-31", context).unwrap(), "5874897-12-31");
208 /// assert_eq!(read("January 8, 1999 BC", context).unwrap(), "1999-01-08 BC");
209 /// assert_eq!(read("J2451545", context).unwrap(), "2000-01-01");
210 /// // Under `YMD` a short number after a month name is the year, which `99` can be.
211 /// assert_eq!(read("January 8, 99", context), Err(DateTimeError::NeedsDateOrder));
212 /// assert_eq!(read("2024-02-30", context), Err(DateTimeError::FieldValueOutOfRange));
213 /// assert_eq!(read("nope", context), Err(DateTimeError::InvalidInputSyntax(PgType::Date)));
214 /// assert_eq!(read("01/02/2026", context), Err(DateTimeError::NeedsDateOrder));
215 /// let dmy = context.with_date_order(DateOrder::Dmy);
216 /// assert_eq!(read("01/02/2026", dmy).unwrap(), "2026-02-01");
217 /// ```
218 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
219 by_date_order(context, |context| Self::read(text, context))
220 }
221
222 /// [`Self::parse`] under the context's order alone.
223 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
224 let decoded = decode(text, context, PgType::Date, decode_date_time)?;
225 let tm = match decoded.dtype {
226 DateType::Date => decoded.tm,
227 DateType::Epoch => return Ok(Self(EPOCH_DAYS)),
228 DateType::Late => return Ok(Self::INFINITY),
229 DateType::Early => return Ok(Self::NEG_INFINITY),
230 };
231 if !is_valid_julian(tm.year, tm.mon) {
232 return Err(DateTimeError::DateOutOfRange);
233 }
234 Self::from_pg_days(date2j(tm.year, tm.mon, tm.mday) - POSTGRES_EPOCH_JDATE)
235 .filter(|date| date.is_finite())
236 .ok_or(DateTimeError::DateOutOfRange)
237 }
238}
239
240impl PgTimestamp {
241 /// PostgreSQL's `timestamp_in`, reading every spelling `DecodeDateTime` reads, with a zone
242 /// read, checked and ignored.
243 ///
244 /// # Errors
245 ///
246 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
247 /// context lacks.
248 ///
249 /// ```
250 /// use sql_values::postgres::{DateTimeError, InputContext, PgTimestamp};
251 ///
252 /// let read = |text| PgTimestamp::parse(text, InputContext::new()).map(|t| t.to_string());
253 /// assert_eq!(read("2024-12-31 24:00:00").unwrap(), "2025-01-01 00:00:00");
254 /// assert_eq!(read("Jan 1999 08 04:05:06 PM").unwrap(), "1999-01-08 16:05:06");
255 /// assert_eq!(read("19990108T040506.5").unwrap(), "1999-01-08 04:05:06.5");
256 /// assert_eq!(read("294277-01-01"), Err(DateTimeError::TimestampOutOfRange));
257 /// ```
258 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
259 by_date_order(context, |context| Self::read(text, context))
260 }
261
262 /// [`Self::parse`] under the context's order alone.
263 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
264 let decoded = decode(text, context, PgType::Timestamp, decode_date_time)?;
265 match decoded.dtype {
266 DateType::Date => {
267 let tm = decoded.tm;
268 tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), 0)
269 .map(Self)
270 .ok_or(DateTimeError::TimestampOutOfRange)
271 }
272 DateType::Epoch => Ok(Self(EPOCH_MICROS)),
273 DateType::Late => Ok(Self::INFINITY),
274 DateType::Early => Ok(Self::NEG_INFINITY),
275 }
276 }
277}
278
279impl PgTimestampTz {
280 /// PostgreSQL's `timestamptz_in`, reading every spelling `DecodeDateTime` reads. A zone the
281 /// literal names, or else the context's time zone, decides the offset of a literal without
282 /// a numeric one, its local clock resolved as [`PgTimestamp::to_timestamptz`] resolves it,
283 /// and an abbreviation whose meaning changed takes the one it had at that clock.
284 ///
285 /// # Errors
286 ///
287 /// The [`DateTimeError`] PostgreSQL raises, the session state the literal needs and the
288 /// context lacks, or [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about
289 /// a clock outside jiff's years.
290 ///
291 /// ```
292 /// use sql_values::postgres::{DateTimeError, InputContext, PgTimeZone, PgTimestampTz};
293 ///
294 /// let read = |text, context| PgTimestampTz::parse(text, context).map(|t| t.to_string());
295 /// let context = InputContext::new();
296 /// assert_eq!(read("2024-01-01 12:00+15:59:59", context).unwrap(), "2023-12-31 20:00:01+00");
297 /// assert_eq!(
298 /// read("2024-01-01 12:00+16", context),
299 /// Err(DateTimeError::TimeZoneDisplacementOutOfRange),
300 /// );
301 /// // `MSK` follows Europe/Moscow, which kept +04 from 2011 to 2014.
302 /// #[cfg(feature = "tzdb")]
303 /// {
304 /// assert_eq!(read("2012-01-01 12:00 MSK", context).unwrap(), "2012-01-01 08:00:00+00");
305 /// assert_eq!(read("2015-01-01 12:00 MSK", context).unwrap(), "2015-01-01 09:00:00+00");
306 /// let rome = read("2026-07-01 12:00 Europe/Rome", context);
307 /// assert_eq!(rome.unwrap(), "2026-07-01 10:00:00+00");
308 /// }
309 /// assert_eq!(read("now", context), Err(DateTimeError::NeedsCurrentTime));
310 /// #[cfg(feature = "tzdb")]
311 /// {
312 /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
313 /// let start = PgTimestampTz::parse("2026-07-01 23:30+00", context).unwrap();
314 /// let session = context.with_time_zone(&rome).with_now(start);
315 /// assert_eq!(read("today", session).unwrap(), "2026-07-01 22:00:00+00");
316 /// }
317 /// ```
318 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
319 by_date_order(context, |context| Self::read(text, context))
320 }
321
322 /// [`Self::parse`] under the context's order alone.
323 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
324 let decoded = decode(text, context, PgType::TimestampTz, decode_date_time)?;
325 let tm = match decoded.dtype {
326 DateType::Date => decoded.tm,
327 DateType::Epoch => return Ok(Self(EPOCH_MICROS)),
328 DateType::Late => return Ok(Self::INFINITY),
329 DateType::Early => return Ok(Self::NEG_INFINITY),
330 };
331 let out_of_range = DateTimeError::TimestampOutOfRange;
332 // The local clock as microseconds from 2000-01-01, for a zone to resolve.
333 let local = || {
334 if !is_valid_julian(tm.year, tm.mon) {
335 return Err(out_of_range);
336 }
337 let days =
338 i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
339 days.checked_mul(USECS_PER_DAY)
340 .and_then(|micros| micros.checked_add(tm.clock()))
341 .ok_or(out_of_range)
342 };
343 let offset = match &decoded.zone {
344 ZoneSource::West(west) => -*west,
345 ZoneSource::Abbreviation { zone, upper } => abbreviation_offset(zone, upper, local()?)?,
346 ZoneSource::Named(zone) => local_offset(zone, local()?)?,
347 ZoneSource::Session => {
348 let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
349 local_offset(zone, local()?)?
350 }
351 };
352 tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), offset)
353 .map(Self)
354 .ok_or(out_of_range)
355 }
356}
357
358impl PgTime {
359 /// PostgreSQL's `time_in`, reading every spelling `DecodeTimeOnly` reads, with a date and
360 /// zone read, checked and ignored, and the fraction rounded to the microsecond.
361 ///
362 /// # Errors
363 ///
364 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
365 /// context lacks.
366 ///
367 /// ```
368 /// use sql_values::postgres::{DateTimeError, InputContext, PgTime, PgType};
369 ///
370 /// let read = |text| PgTime::parse(text, InputContext::new()).map(|t| t.to_string());
371 /// assert_eq!(read("23:59:60").unwrap(), "24:00:00");
372 /// assert_eq!(read("12:00:00.1234565").unwrap(), "12:00:00.123456");
373 /// assert_eq!(read("040506.5 PM").unwrap(), "16:05:06.5");
374 /// #[cfg(feature = "tzdb")]
375 /// {
376 /// let error = DateTimeError::InvalidInputSyntax(PgType::Time);
377 /// assert_eq!(read("T12:00 Europe/Rome"), Err(error));
378 /// assert_eq!(read("2026-07-01 12:00 Europe/Rome").unwrap(), "12:00:00");
379 /// }
380 /// assert_eq!(read("24:00:00.000001"), Err(DateTimeError::FieldValueOutOfRange));
381 /// ```
382 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
383 by_date_order(context, |context| Self::read(text, context))
384 }
385
386 /// [`Self::parse`] under the context's order alone.
387 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
388 let decoded = decode(text, context, PgType::Time, decode_time_only)?;
389 Ok(Self(decoded.tm.clock()))
390 }
391}
392
393impl PgTimeTz {
394 /// PostgreSQL's `timetz_in`, reading every spelling `DecodeTimeOnly` reads. A time without
395 /// an offset, or with a zone whose offset changes, takes the zone's offset on the date the
396 /// literal writes, or else on the current date in the context's time zone.
397 ///
398 /// # Errors
399 ///
400 /// The [`DateTimeError`] PostgreSQL raises, the session state the literal needs and the
401 /// context lacks, or [`DateTimeError::OutsideJiffRange`] where an IANA zone is asked about
402 /// a date outside jiff's years.
403 ///
404 /// ```
405 /// use sql_values::postgres::{
406 /// DateTimeError, InputContext, PgTimeTz, PgTimeZone, PgTimestampTz,
407 /// };
408 ///
409 /// let read = |text, context| PgTimeTz::parse(text, context).map(|t| t.to_string());
410 /// let context = InputContext::new();
411 /// assert_eq!(read("12:00:00-05:30", context).unwrap(), "12:00:00-05:30");
412 /// assert_eq!(read("allballs", context).unwrap(), "00:00:00+00");
413 /// #[cfg(feature = "tzdb")]
414 /// assert_eq!(read("2026-07-01 12:00 Europe/Rome", context).unwrap(), "12:00:00+02");
415 /// assert_eq!(read("12:00", context), Err(DateTimeError::NeedsCurrentTime));
416 /// #[cfg(feature = "tzdb")]
417 /// {
418 /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
419 /// let start = PgTimestampTz::parse("2026-01-15 12:00+00", context).unwrap();
420 /// let session = context.with_time_zone(&rome).with_now(start);
421 /// assert_eq!(read("12:00", session).unwrap(), "12:00:00+01");
422 /// }
423 /// ```
424 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
425 by_date_order(context, |context| Self::read(text, context))
426 }
427
428 /// [`Self::parse`] under the context's order alone.
429 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
430 let pg_type = PgType::TimeTz;
431 let DecodedTime { tm, dated, zone } = decode(text, context, pg_type, decode_time_only)?;
432 // The literal's date, or the current one, at the literal's clock.
433 let at = || {
434 let mut at = if dated {
435 tm
436 } else {
437 current_time(context)
438 .map_err(|error| error.for_type(pg_type))?
439 .0
440 };
441 (at.hour, at.min, at.sec) = (tm.hour, tm.min, tm.sec);
442 Ok::<_, DateTimeError>(at)
443 };
444 let offset = match &zone {
445 ZoneSource::West(west) => -*west,
446 ZoneSource::Named(zone) => time_zone_offset(zone, None, &tm)?,
447 ZoneSource::Abbreviation { zone, upper } => {
448 time_zone_offset(zone, Some(upper), &at()?)?
449 }
450 ZoneSource::Session => {
451 let at = at()?;
452 let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
453 time_zone_offset(zone, None, &at)?
454 }
455 };
456 Ok(Self {
457 time: tm.clock(),
458 offset,
459 })
460 }
461}
462
463/// Parse `YYYY-MM-DD HH:MM:SS[.f]` with a space or `T` separator, a year of four or more digits,
464/// PostgreSQL's trailing ` BC`, and `infinity` and `-infinity`, the fraction rounded to the
465/// microsecond. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
466///
467/// ```
468/// let at = sql_values::postgres::parse_timestamp("2024-01-02 03:04:05.125").unwrap();
469/// assert_eq!(at.to_string(), "2024-01-02 03:04:05.125");
470/// ```
471#[must_use]
472pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
473 match text {
474 "infinity" => return Some(PgTimestamp::INFINITY),
475 "-infinity" => return Some(PgTimestamp::NEG_INFINITY),
476 _ => {}
477 }
478 let (body, bc) = split_era(text.as_bytes());
479 match parse_datetime_prefix(body, bc)? {
480 (date, clock, []) => date.at(clock, 0).map(PgTimestamp),
481 _ => None,
482 }
483}
484
485/// Parse a [`parse_timestamp`] layout followed by a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS`
486/// offset, then PostgreSQL's optional ` BC`, or `infinity` and `-infinity`.
487///
488/// ```
489/// let at = sql_values::postgres::parse_timestamp_tz("2024-01-02T03:04:05+02:00").unwrap();
490/// assert_eq!(at.to_string(), "2024-01-02 01:04:05+00");
491/// ```
492#[must_use]
493pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
494 match text {
495 "infinity" => return Some(PgTimestampTz::INFINITY),
496 "-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
497 _ => {}
498 }
499 let (body, bc) = split_era(text.as_bytes());
500 let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
501 date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
502}
503
504/// Parse a `YYYY-MM-DD` date with a year of four or more digits and PostgreSQL's trailing ` BC`,
505/// or `infinity` and `-infinity`. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
506///
507/// ```
508/// let d = sql_values::postgres::parse_date("2024-01-02").unwrap();
509/// assert_eq!(d.to_string(), "2024-01-02");
510/// ```
511#[must_use]
512pub fn parse_date(text: &str) -> Option<PgDate> {
513 match text {
514 "infinity" => return Some(PgDate::INFINITY),
515 "-infinity" => return Some(PgDate::NEG_INFINITY),
516 _ => {}
517 }
518 let (body, bc) = split_era(text.as_bytes());
519 match parse_date_prefix(body, bc)? {
520 (date, []) => PgDate::from_ymd(date.year, date.month, date.day),
521 _ => None,
522 }
523}
524
525/// Parse `HH:MM:SS[.f]` with one to nine fraction digits, rounded to the microsecond, up to
526/// 24:00:00.
527///
528/// ```
529/// let t = sql_values::postgres::parse_time("03:04:05.125").unwrap();
530/// assert_eq!(t.to_string(), "03:04:05.125");
531/// ```
532#[must_use]
533pub fn parse_time(text: &str) -> Option<PgTime> {
534 match parse_time_prefix(text.as_bytes())? {
535 (micros, []) => Some(PgTime(micros)),
536 _ => None,
537 }
538}
539
540/// Split off PostgreSQL's ` BC`, which trails the whole value.
541fn split_era(bytes: &[u8]) -> (&[u8], bool) {
542 match bytes.strip_suffix(b" BC") {
543 Some(body) => (body, true),
544 None => (bytes, false),
545 }
546}
547
548/// A year, month and day as written, where year `Y` BC is year `1 - Y`.
549#[derive(Clone, Copy)]
550struct Ymd {
551 year: i32,
552 month: u8,
553 day: u8,
554}
555
556impl Ymd {
557 /// The timestamp of `clock` on this date with `offset` seconds east subtracted, or `None`
558 /// outside the calendar or PostgreSQL's range.
559 fn at(self, clock: i64, offset: i32) -> Option<i64> {
560 let (month, day) = (i32::from(self.month), i32::from(self.day));
561 if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
562 return None;
563 }
564 tm2timestamp(self.year, month, day, clock, offset)
565 }
566}
567
568/// Parse a leading `Y{4,}-MM-DD`, where year `Y` BC is year `1 - Y` and year `0000` is year 0.
569fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
570 let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
571 if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
572 return None;
573 }
574 let (year, _, erange) = strtoint(bytes, 0);
575 if erange {
576 return None;
577 }
578 let rest = &bytes[year_len..];
579 let year = match (year, bc) {
580 (0, true) => return None,
581 (_, true) => 1 - year,
582 (_, false) => year,
583 };
584 let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
585 return None;
586 };
587 let month = parse_two_digits([m1, m2])?;
588 let day = parse_two_digits([d1, d2])?;
589 Some((Ymd { year, month, day }, rest))
590}
591
592/// Parse a leading `HH:MM:SS[.f]` with one to nine fraction digits, as microseconds up to
593/// 24:00:00.
594fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
595 let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
596 return None;
597 };
598 let (fsec, rest) = match rest.split_first() {
599 Some((b'.', fraction)) => {
600 let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
601 if !(1..=9).contains(&len) {
602 return None;
603 }
604 let fsec = parse_fractional_second(&rest[..=len]).ok()?;
605 (i64::from(fsec), &fraction[len..])
606 }
607 _ => (0, rest),
608 };
609 let (hour, minute, second) = (
610 parse_two_digits([h1, h2])?,
611 parse_two_digits([m1, m2])?,
612 parse_two_digits([s1, s2])?,
613 );
614 if minute > 59 || second > 59 {
615 return None;
616 }
617 let micros = i64::from(hour) * USECS_PER_HOUR
618 + i64::from(minute) * USECS_PER_MINUTE
619 + i64::from(second) * USECS_PER_SEC
620 + fsec;
621 (micros <= USECS_PER_DAY).then_some((micros, rest))
622}
623
624/// Parse a leading date and time joined by a space or `T`, the clock in microseconds.
625fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
626 let (date, rest) = parse_date_prefix(bytes, bc)?;
627 let (&(b' ' | b'T'), rest) = rest.split_first()? else {
628 return None;
629 };
630 let (clock, rest) = parse_time_prefix(rest)?;
631 Some((date, clock, rest))
632}
633
634/// Two ASCII digits as a number.
635fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
636 if digits.iter().all(u8::is_ascii_digit) {
637 Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
638 } else {
639 None
640 }
641}
642
643/// Parse a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS` offset as seconds east of UTC, with an
644/// hour up to 23.
645fn parse_offset(bytes: &[u8]) -> Option<i32> {
646 if bytes == b"Z" {
647 return Some(0);
648 }
649 let (&sign, digits) = bytes.split_first()?;
650 let negative = match sign {
651 b'+' => false,
652 b'-' => true,
653 _ => return None,
654 };
655 let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
656 let hour = pair(0)?;
657 let (minute, second) = match digits.len() {
658 2 => (0, 0),
659 4 => (pair(2)?, 0),
660 5 if digits[2] == b':' => (pair(3)?, 0),
661 8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
662 _ => return None,
663 };
664 if hour > 23 || minute > 59 || second > 59 {
665 return None;
666 }
667 let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
668 Some(if negative { -seconds } else { seconds })
669}