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