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 UNIX_TO_POSTGRES_SECS, USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC,
7 abbreviation_offset, date2j, 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 seconds
159/// from 1970.
160fn local_seconds(tm: &Tm) -> 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 * (USECS_PER_DAY / USECS_PER_SEC) + clock + UNIX_TO_POSTGRES_SECS
164}
165
166/// `DetermineTimeZoneOffset` and `DetermineTimeZoneAbbrevOffset` for a `timetz`, whose date
167/// may lie anywhere `ValidateDate` accepts. Outside `IS_VALID_JULIAN` PostgreSQL takes UTC and
168/// reads the abbreviation at the Unix epoch.
169fn time_zone_offset(zone: &PgTimeZone, abbreviation: Option<&str>, tm: &Tm) -> i32 {
170 if !is_valid_julian(tm.year, tm.mon) {
171 return abbreviation
172 .and_then(|abbreviation| zone.interpret_abbreviation(abbreviation, 0))
173 .map_or(0, |meaning| meaning.offset);
174 }
175 let local = local_seconds(tm);
176 match abbreviation {
177 Some(abbreviation) => zone.abbreviation_offset(abbreviation, local),
178 None => zone.local_offset(local),
179 }
180}
181
182impl PgDate {
183 /// PostgreSQL's `date_in`, reading every spelling `DecodeDateTime` reads, with a clock and
184 /// zone read, checked and ignored.
185 ///
186 /// # Errors
187 ///
188 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
189 /// context lacks, [`DateTimeError::NeedsDateOrder`], [`DateTimeError::NeedsCurrentTime`] or
190 /// [`DateTimeError::NeedsTimeZone`].
191 ///
192 /// ```
193 /// use sql_values::postgres::{DateOrder, DateTimeError, InputContext, PgDate, PgType};
194 ///
195 /// let read = |text, context| PgDate::parse(text, context).map(|d| d.to_string());
196 /// let context = InputContext::new();
197 /// assert_eq!(read("5874897-12-31", context).unwrap(), "5874897-12-31");
198 /// assert_eq!(read("January 8, 1999 BC", context).unwrap(), "1999-01-08 BC");
199 /// assert_eq!(read("J2451545", context).unwrap(), "2000-01-01");
200 /// // Under `YMD` a short number after a month name is the year, which `99` can be.
201 /// assert_eq!(read("January 8, 99", context), Err(DateTimeError::NeedsDateOrder));
202 /// assert_eq!(read("2024-02-30", context), Err(DateTimeError::FieldValueOutOfRange));
203 /// assert_eq!(read("nope", context), Err(DateTimeError::InvalidInputSyntax(PgType::Date)));
204 /// assert_eq!(read("01/02/2026", context), Err(DateTimeError::NeedsDateOrder));
205 /// let dmy = context.with_date_order(DateOrder::Dmy);
206 /// assert_eq!(read("01/02/2026", dmy).unwrap(), "2026-02-01");
207 /// ```
208 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
209 by_date_order(context, |context| Self::read(text, context))
210 }
211
212 /// [`Self::parse`] under the context's order alone.
213 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
214 let decoded = decode(text, context, PgType::Date, decode_date_time)?;
215 let tm = match decoded.dtype {
216 DateType::Date => decoded.tm,
217 DateType::Epoch => return Ok(Self(EPOCH_DAYS)),
218 DateType::Late => return Ok(Self::INFINITY),
219 DateType::Early => return Ok(Self::NEG_INFINITY),
220 };
221 if !is_valid_julian(tm.year, tm.mon) {
222 return Err(DateTimeError::DateOutOfRange);
223 }
224 Self::from_pg_days(date2j(tm.year, tm.mon, tm.mday) - POSTGRES_EPOCH_JDATE)
225 .filter(|date| date.is_finite())
226 .ok_or(DateTimeError::DateOutOfRange)
227 }
228}
229
230impl PgTimestamp {
231 /// PostgreSQL's `timestamp_in`, reading every spelling `DecodeDateTime` reads, with a zone
232 /// read, checked and ignored.
233 ///
234 /// # Errors
235 ///
236 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
237 /// context lacks.
238 ///
239 /// ```
240 /// use sql_values::postgres::{DateTimeError, InputContext, PgTimestamp};
241 ///
242 /// let read = |text| PgTimestamp::parse(text, InputContext::new()).map(|t| t.to_string());
243 /// assert_eq!(read("2024-12-31 24:00:00").unwrap(), "2025-01-01 00:00:00");
244 /// assert_eq!(read("Jan 1999 08 04:05:06 PM").unwrap(), "1999-01-08 16:05:06");
245 /// assert_eq!(read("19990108T040506.5").unwrap(), "1999-01-08 04:05:06.5");
246 /// assert_eq!(read("294277-01-01"), Err(DateTimeError::TimestampOutOfRange));
247 /// ```
248 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
249 by_date_order(context, |context| Self::read(text, context))
250 }
251
252 /// [`Self::parse`] under the context's order alone.
253 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
254 let decoded = decode(text, context, PgType::Timestamp, decode_date_time)?;
255 match decoded.dtype {
256 DateType::Date => {
257 let tm = decoded.tm;
258 tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), 0)
259 .map(Self)
260 .ok_or(DateTimeError::TimestampOutOfRange)
261 }
262 DateType::Epoch => Ok(Self(EPOCH_MICROS)),
263 DateType::Late => Ok(Self::INFINITY),
264 DateType::Early => Ok(Self::NEG_INFINITY),
265 }
266 }
267}
268
269impl PgTimestampTz {
270 /// PostgreSQL's `timestamptz_in`, reading every spelling `DecodeDateTime` reads. A zone the
271 /// literal names, or else the context's time zone, decides the offset of a literal without
272 /// a numeric one, its local clock resolved as [`PgTimestamp::to_timestamptz`] resolves it,
273 /// and an abbreviation whose meaning changed takes the one it had at that clock.
274 ///
275 /// # Errors
276 ///
277 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
278 /// context lacks.
279 ///
280 /// ```
281 /// use sql_values::postgres::{DateTimeError, InputContext, PgTimeZone, PgTimestampTz};
282 ///
283 /// let read = |text, context| PgTimestampTz::parse(text, context).map(|t| t.to_string());
284 /// let context = InputContext::new();
285 /// assert_eq!(read("2024-01-01 12:00+15:59:59", context).unwrap(), "2023-12-31 20:00:01+00");
286 /// assert_eq!(
287 /// read("2024-01-01 12:00+16", context),
288 /// Err(DateTimeError::TimeZoneDisplacementOutOfRange),
289 /// );
290 /// // `MSK` follows Europe/Moscow, which kept +04 from 2011 to 2014.
291 /// #[cfg(feature = "tzdb")]
292 /// {
293 /// assert_eq!(read("2012-01-01 12:00 MSK", context).unwrap(), "2012-01-01 08:00:00+00");
294 /// assert_eq!(read("2015-01-01 12:00 MSK", context).unwrap(), "2015-01-01 09:00:00+00");
295 /// let rome = read("2026-07-01 12:00 Europe/Rome", context);
296 /// assert_eq!(rome.unwrap(), "2026-07-01 10:00:00+00");
297 /// }
298 /// assert_eq!(read("now", context), Err(DateTimeError::NeedsCurrentTime));
299 /// #[cfg(feature = "tzdb")]
300 /// {
301 /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
302 /// let start = PgTimestampTz::parse("2026-07-01 23:30+00", context).unwrap();
303 /// let session = context.with_time_zone(&rome).with_now(start);
304 /// assert_eq!(read("today", session).unwrap(), "2026-07-01 22:00:00+00");
305 /// }
306 /// ```
307 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
308 by_date_order(context, |context| Self::read(text, context))
309 }
310
311 /// [`Self::parse`] under the context's order alone.
312 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
313 let decoded = decode(text, context, PgType::TimestampTz, decode_date_time)?;
314 let tm = match decoded.dtype {
315 DateType::Date => decoded.tm,
316 DateType::Epoch => return Ok(Self(EPOCH_MICROS)),
317 DateType::Late => return Ok(Self::INFINITY),
318 DateType::Early => return Ok(Self::NEG_INFINITY),
319 };
320 let out_of_range = DateTimeError::TimestampOutOfRange;
321 // The local clock as microseconds from 2000-01-01, for a zone to resolve.
322 let local = || {
323 if !is_valid_julian(tm.year, tm.mon) {
324 return Err(out_of_range);
325 }
326 let days =
327 i64::from(date2j(tm.year, tm.mon, tm.mday)) - i64::from(POSTGRES_EPOCH_JDATE);
328 days.checked_mul(USECS_PER_DAY)
329 .and_then(|micros| micros.checked_add(tm.clock()))
330 .ok_or(out_of_range)
331 };
332 let offset = match &decoded.zone {
333 ZoneSource::West(west) => -*west,
334 ZoneSource::Abbreviation { zone, upper } => abbreviation_offset(zone, upper, local()?),
335 ZoneSource::Named(zone) => local_offset(zone, local()?),
336 ZoneSource::Session => {
337 let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
338 local_offset(zone, local()?)
339 }
340 };
341 tm2timestamp(tm.year, tm.mon, tm.mday, tm.clock(), offset)
342 .map(Self)
343 .ok_or(out_of_range)
344 }
345}
346
347impl PgTime {
348 /// PostgreSQL's `time_in`, reading every spelling `DecodeTimeOnly` reads, with a date and
349 /// zone read, checked and ignored, and the fraction rounded to the microsecond.
350 ///
351 /// # Errors
352 ///
353 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
354 /// context lacks.
355 ///
356 /// ```
357 /// use sql_values::postgres::{DateTimeError, InputContext, PgTime, PgType};
358 ///
359 /// let read = |text| PgTime::parse(text, InputContext::new()).map(|t| t.to_string());
360 /// assert_eq!(read("23:59:60").unwrap(), "24:00:00");
361 /// assert_eq!(read("12:00:00.1234565").unwrap(), "12:00:00.123456");
362 /// assert_eq!(read("040506.5 PM").unwrap(), "16:05:06.5");
363 /// #[cfg(feature = "tzdb")]
364 /// {
365 /// let error = DateTimeError::InvalidInputSyntax(PgType::Time);
366 /// assert_eq!(read("T12:00 Europe/Rome"), Err(error));
367 /// assert_eq!(read("2026-07-01 12:00 Europe/Rome").unwrap(), "12:00:00");
368 /// }
369 /// assert_eq!(read("24:00:00.000001"), Err(DateTimeError::FieldValueOutOfRange));
370 /// ```
371 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
372 by_date_order(context, |context| Self::read(text, context))
373 }
374
375 /// [`Self::parse`] under the context's order alone.
376 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
377 let decoded = decode(text, context, PgType::Time, decode_time_only)?;
378 Ok(Self(decoded.tm.clock()))
379 }
380}
381
382impl PgTimeTz {
383 /// PostgreSQL's `timetz_in`, reading every spelling `DecodeTimeOnly` reads. A time without
384 /// an offset, or with a zone whose offset changes, takes the zone's offset on the date the
385 /// literal writes, or else on the current date in the context's time zone. A context time
386 /// zone with one offset on every date gives it without the current date.
387 ///
388 /// # Errors
389 ///
390 /// The [`DateTimeError`] PostgreSQL raises, or the session state the literal needs and the
391 /// context lacks.
392 ///
393 /// ```
394 /// use sql_values::postgres::{
395 /// DateTimeError, InputContext, PgTimeTz, PgTimeZone, PgTimestampTz,
396 /// };
397 ///
398 /// let read = |text, context| PgTimeTz::parse(text, context).map(|t| t.to_string());
399 /// let context = InputContext::new();
400 /// assert_eq!(read("12:00:00-05:30", context).unwrap(), "12:00:00-05:30");
401 /// assert_eq!(read("allballs", context).unwrap(), "00:00:00+00");
402 /// #[cfg(feature = "tzdb")]
403 /// assert_eq!(read("2026-07-01 12:00 Europe/Rome", context).unwrap(), "12:00:00+02");
404 /// assert_eq!(read("12:00", context), Err(DateTimeError::NeedsCurrentTime));
405 /// let gmt = PgTimeZone::parse("GMT").unwrap();
406 /// assert_eq!(read("12:00", context.with_time_zone(&gmt)).unwrap(), "12:00:00+00");
407 /// #[cfg(feature = "tzdb")]
408 /// {
409 /// let rome = PgTimeZone::parse("Europe/Rome").unwrap();
410 /// let start = PgTimestampTz::parse("2026-01-15 12:00+00", context).unwrap();
411 /// let session = context.with_time_zone(&rome).with_now(start);
412 /// assert_eq!(read("12:00", session).unwrap(), "12:00:00+01");
413 /// }
414 /// ```
415 pub fn parse(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
416 by_date_order(context, |context| Self::read(text, context))
417 }
418
419 /// [`Self::parse`] under the context's order alone.
420 fn read(text: &str, context: InputContext<'_>) -> Result<Self, DateTimeError> {
421 let pg_type = PgType::TimeTz;
422 let DecodedTime { tm, dated, zone } = decode(text, context, pg_type, decode_time_only)?;
423 // The literal's date, or the current one, at the literal's clock.
424 let at = || {
425 let mut at = if dated {
426 tm
427 } else {
428 current_time(context)
429 .map_err(|error| error.for_type(pg_type))?
430 .0
431 };
432 (at.hour, at.min, at.sec) = (tm.hour, tm.min, tm.sec);
433 Ok::<_, DateTimeError>(at)
434 };
435 let offset = match &zone {
436 ZoneSource::West(west) => -*west,
437 ZoneSource::Named(zone) => time_zone_offset(zone, None, &tm),
438 ZoneSource::Abbreviation { zone, upper } => time_zone_offset(zone, Some(upper), &at()?),
439 ZoneSource::Session => match context.time_zone.and_then(PgTimeZone::fixed_offset) {
440 Some(offset) if !dated => offset,
441 _ => {
442 let at = at()?;
443 let zone = context.time_zone.ok_or(DateTimeError::NeedsTimeZone)?;
444 time_zone_offset(zone, None, &at)
445 }
446 },
447 };
448 Ok(Self {
449 time: tm.clock(),
450 offset,
451 })
452 }
453}
454
455/// Parse `YYYY-MM-DD HH:MM:SS[.f]` with a space or `T` separator, a year of four or more digits,
456/// PostgreSQL's trailing ` BC`, and `infinity` and `-infinity`, the fraction rounded to the
457/// microsecond. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
458///
459/// ```
460/// let at = sql_values::postgres::parse_timestamp("2024-01-02 03:04:05.125").unwrap();
461/// assert_eq!(at.to_string(), "2024-01-02 03:04:05.125");
462/// ```
463#[must_use]
464pub fn parse_timestamp(text: &str) -> Option<PgTimestamp> {
465 match text {
466 "infinity" => return Some(PgTimestamp::INFINITY),
467 "-infinity" => return Some(PgTimestamp::NEG_INFINITY),
468 _ => {}
469 }
470 let (body, bc) = split_era(text.as_bytes());
471 match parse_datetime_prefix(body, bc)? {
472 (date, clock, []) => date.at(clock, 0).map(PgTimestamp),
473 _ => None,
474 }
475}
476
477/// Parse a [`parse_timestamp`] layout followed by a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS`
478/// offset, then PostgreSQL's optional ` BC`, or `infinity` and `-infinity`.
479///
480/// ```
481/// let at = sql_values::postgres::parse_timestamp_tz("2024-01-02T03:04:05+02:00").unwrap();
482/// assert_eq!(at.to_string(), "2024-01-02 01:04:05+00");
483/// ```
484#[must_use]
485pub fn parse_timestamp_tz(text: &str) -> Option<PgTimestampTz> {
486 match text {
487 "infinity" => return Some(PgTimestampTz::INFINITY),
488 "-infinity" => return Some(PgTimestampTz::NEG_INFINITY),
489 _ => {}
490 }
491 let (body, bc) = split_era(text.as_bytes());
492 let (date, clock, offset) = parse_datetime_prefix(body, bc)?;
493 date.at(clock, parse_offset(offset)?).map(PgTimestampTz)
494}
495
496/// Parse a `YYYY-MM-DD` date with a year of four or more digits and PostgreSQL's trailing ` BC`,
497/// or `infinity` and `-infinity`. Year `0000`, as MySQL and SQLite print 1 BC, is year 0.
498///
499/// ```
500/// let d = sql_values::postgres::parse_date("2024-01-02").unwrap();
501/// assert_eq!(d.to_string(), "2024-01-02");
502/// ```
503#[must_use]
504pub fn parse_date(text: &str) -> Option<PgDate> {
505 match text {
506 "infinity" => return Some(PgDate::INFINITY),
507 "-infinity" => return Some(PgDate::NEG_INFINITY),
508 _ => {}
509 }
510 let (body, bc) = split_era(text.as_bytes());
511 match parse_date_prefix(body, bc)? {
512 (date, []) => PgDate::from_ymd(date.year, date.month, date.day),
513 _ => None,
514 }
515}
516
517/// Parse `HH:MM:SS[.f]` with one to nine fraction digits, rounded to the microsecond, up to
518/// 24:00:00.
519///
520/// ```
521/// let t = sql_values::postgres::parse_time("03:04:05.125").unwrap();
522/// assert_eq!(t.to_string(), "03:04:05.125");
523/// ```
524#[must_use]
525pub fn parse_time(text: &str) -> Option<PgTime> {
526 match parse_time_prefix(text.as_bytes())? {
527 (micros, []) => Some(PgTime(micros)),
528 _ => None,
529 }
530}
531
532/// Split off PostgreSQL's ` BC`, which trails the whole value.
533fn split_era(bytes: &[u8]) -> (&[u8], bool) {
534 match bytes.strip_suffix(b" BC") {
535 Some(body) => (body, true),
536 None => (bytes, false),
537 }
538}
539
540/// A year, month and day as written, where year `Y` BC is year `1 - Y`.
541#[derive(Clone, Copy)]
542struct Ymd {
543 year: i32,
544 month: u8,
545 day: u8,
546}
547
548impl Ymd {
549 /// The timestamp of `clock` on this date with `offset` seconds east subtracted, or `None`
550 /// outside the calendar or PostgreSQL's range.
551 fn at(self, clock: i64, offset: i32) -> Option<i64> {
552 let (month, day) = (i32::from(self.month), i32::from(self.day));
553 if !(1..=12).contains(&month) || !(1..=days_in_month(self.year, month)).contains(&day) {
554 return None;
555 }
556 tm2timestamp(self.year, month, day, clock, offset)
557 }
558}
559
560/// Parse a leading `Y{4,}-MM-DD`, where year `Y` BC is year `1 - Y` and year `0000` is year 0.
561fn parse_date_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, &[u8])> {
562 let year_len = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
563 if year_len < 4 || (year_len > 4 && bytes[0] == b'0') {
564 return None;
565 }
566 let (year, _, erange) = strtoint(bytes, 0);
567 if erange {
568 return None;
569 }
570 let rest = &bytes[year_len..];
571 let year = match (year, bc) {
572 (0, true) => return None,
573 (_, true) => 1 - year,
574 (_, false) => year,
575 };
576 let Some((&[b'-', m1, m2, b'-', d1, d2], rest)) = rest.split_first_chunk() else {
577 return None;
578 };
579 let month = parse_two_digits([m1, m2])?;
580 let day = parse_two_digits([d1, d2])?;
581 Some((Ymd { year, month, day }, rest))
582}
583
584/// Parse a leading `HH:MM:SS[.f]` with one to nine fraction digits, as microseconds up to
585/// 24:00:00.
586fn parse_time_prefix(bytes: &[u8]) -> Option<(i64, &[u8])> {
587 let Some((&[h1, h2, b':', m1, m2, b':', s1, s2], rest)) = bytes.split_first_chunk() else {
588 return None;
589 };
590 let (fsec, rest) = match rest.split_first() {
591 Some((b'.', fraction)) => {
592 let len = fraction.iter().take_while(|b| b.is_ascii_digit()).count();
593 if !(1..=9).contains(&len) {
594 return None;
595 }
596 let fsec = parse_fractional_second(&rest[..=len]).ok()?;
597 (i64::from(fsec), &fraction[len..])
598 }
599 _ => (0, rest),
600 };
601 let (hour, minute, second) = (
602 parse_two_digits([h1, h2])?,
603 parse_two_digits([m1, m2])?,
604 parse_two_digits([s1, s2])?,
605 );
606 if minute > 59 || second > 59 {
607 return None;
608 }
609 let micros = i64::from(hour) * USECS_PER_HOUR
610 + i64::from(minute) * USECS_PER_MINUTE
611 + i64::from(second) * USECS_PER_SEC
612 + fsec;
613 (micros <= USECS_PER_DAY).then_some((micros, rest))
614}
615
616/// Parse a leading date and time joined by a space or `T`, the clock in microseconds.
617fn parse_datetime_prefix(bytes: &[u8], bc: bool) -> Option<(Ymd, i64, &[u8])> {
618 let (date, rest) = parse_date_prefix(bytes, bc)?;
619 let (&(b' ' | b'T'), rest) = rest.split_first()? else {
620 return None;
621 };
622 let (clock, rest) = parse_time_prefix(rest)?;
623 Some((date, clock, rest))
624}
625
626/// Two ASCII digits as a number.
627fn parse_two_digits(digits: [u8; 2]) -> Option<u8> {
628 if digits.iter().all(u8::is_ascii_digit) {
629 Some((digits[0] - b'0') * 10 + (digits[1] - b'0'))
630 } else {
631 None
632 }
633}
634
635/// Parse a `Z`, `±HH`, `±HHMM`, `±HH:MM` or `±HH:MM:SS` offset as seconds east of UTC, with an
636/// hour up to 23.
637fn parse_offset(bytes: &[u8]) -> Option<i32> {
638 if bytes == b"Z" {
639 return Some(0);
640 }
641 let (&sign, digits) = bytes.split_first()?;
642 let negative = match sign {
643 b'+' => false,
644 b'-' => true,
645 _ => return None,
646 };
647 let pair = |at: usize| parse_two_digits(digits.get(at..at + 2)?.try_into().ok()?);
648 let hour = pair(0)?;
649 let (minute, second) = match digits.len() {
650 2 => (0, 0),
651 4 => (pair(2)?, 0),
652 5 if digits[2] == b':' => (pair(3)?, 0),
653 8 if digits[2] == b':' && digits[5] == b':' => (pair(3)?, pair(6)?),
654 _ => return None,
655 };
656 if hour > 23 || minute > 59 || second > 59 {
657 return None;
658 }
659 let seconds = (i32::from(hour) * 60 + i32::from(minute)) * 60 + i32::from(second);
660 Some(if negative { -seconds } else { seconds })
661}