fix(db): find no nearest day for a date the calendar does not have

The nearest-day fallback of a booking's time cast the bound date to a
timestamp on Postgres, which refuses 2024-02-30 with a 500, while SQLite's
JULIANDAY rolled it over into March and placed the booking there.
dayDistance now refuses anything but a calendar date on both engines
(isCalendarDate), so a caller that forgets the check fails on SQLite too,
and findNearestDayId answers no day for such a date. The size baseline of
Reservations.repository.ts drops by one line.
This commit is contained in:
Maurice
2026-11-17 21:23:31 +01:00
parent 1b216d8f48
commit 143e2ae447
5 changed files with 63 additions and 6 deletions
+22
View File
@@ -538,6 +538,20 @@ export function castInteger(platform: Platform, ref: string): RawQueryFragment &
return unsupported(platform);
}
/**
* Whether `text` is a date as `YYYY-MM-DD` that the calendar has: `2024-02-29`
* is one, `2024-02-30` and `2023-02-29` are not. A bound value either engine
* reads as a date goes through this first, since SQLite rolls an impossible
* day over into the next month while Postgres refuses it.
*/
export function isCalendarDate(text: string): boolean {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
if (!match) return false;
const [, year, month, day] = match.map(Number);
const date = new Date(Date.UTC(year, month - 1, day));
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
}
/**
* `ABS(JULIANDAY(<col>) - JULIANDAY(?))` — the legacy shape at
* `reservations.service.ts:307` (RS11, `resolveDayIdFromTime`'s
@@ -557,8 +571,16 @@ export function castInteger(platform: Platform, ref: string): RawQueryFragment &
* comment documents; ordering by the EXPRESSION itself is what works).
* Postgres measures the same distance in days from the epoch difference of
* the two values cast to `timestamp`.
*
* `isoDate` must be a real calendar date ({@link isCalendarDate}): Postgres
* refuses to cast `2024-02-30` while SQLite's JULIANDAY rolls it over into
* March, so the two engines would answer it differently. Any other value is
* refused here, on both engines alike, and the caller checks first.
*/
export function dayDistance(platform: Platform, ref: string, isoDate: string): RawQueryFragment & symbol {
if (!isCalendarDate(isoDate)) {
throw new Error(`sql-functions: dayDistance needs a calendar date (YYYY-MM-DD), got ${JSON.stringify(isoDate)}`);
}
if (isSqlite(platform)) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]);
if (isPostgres(platform)) {
return raw(`ABS(EXTRACT(EPOCH FROM (CAST(${column(ref)} AS timestamp) - CAST(? AS timestamp))) / 86400)`, [