The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(db): find no nearest day for a date the calendar does not have
Maurice62c03d71bf8a
diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.jsonindex 5198cc04f..1dc1d52e6 100644--- a/server/scripts/size-baseline.json+++ b/server/scripts/size-baseline.json@@ -2,7 +2,7 @@"scripts/db-call-graph.mjs": 1036,"scripts/generate-entities.ts": 2259,"src/db/repositories/Places.repository.ts": 1435,- "src/db/repositories/Reservations.repository.ts": 1551,+ "src/db/repositories/Reservations.repository.ts": 1550,"src/db/repositories/Trips.repository.ts": 1120,"src/db/repositories/Users.repository.ts": 1421,"src/nest/atlas/atlas.service.ts": 1174,diff --git a/server/src/db/dialect/sql-functions.ts b/server/src/db/dialect/sql-functions.tsindex 55abdd14e..f60e2cf34 100644--- a/server/src/db/dialect/sql-functions.ts+++ b/server/src/db/dialect/sql-functions.ts@@ -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)`, [diff --git a/server/src/db/repositories/Reservations.repository.ts b/server/src/db/repositories/Reservations.repository.tsindex 53cd7d6a2..299a7618b 100644--- a/server/src/db/repositories/Reservations.repository.ts+++ b/server/src/db/repositories/Reservations.repository.ts@@ -1,7 +1,7 @@import type { Reservations } from '../entities/Reservations.entity';import { DayAssignments } from '../entities/DayAssignments.entity';import { Days } from '../entities/Days.entity';-import { coalesceOverride, columnRef, dayDistance } from '../dialect/sql-functions';+import { coalesceOverride, columnRef, dayDistance, isCalendarDate } from '../dialect/sql-functions';import { concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';import { accommodationIdMatches, reservationStayIs } from './_shared/reservation-accommodation';import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';@@ -640,12 +640,11 @@ export class ReservationsRepository extends TrekRepository<Reservations> {/*** RS11 (`resolveDayIdFromTime`'s nearest-day fallback) — `SELECT id FROM* days WHERE trip_id = ? ORDER BY ABS(JULIANDAY(date) - JULIANDAY(?)) ASC,- * date ASC LIMIT 1`. `dayDistance`, through `DaysRepository`'s own QB (the- * same cross-repository-read shape as `getAssignmentTripId` above —- * `DaysRepository` stays Task 1's additive-method territory; no new- * method is added there).+ * date ASC LIMIT 1`, through `DaysRepository`'s own QB. A date the calendar does+ * not have (`2024-02-30`) finds no day on either engine (`isCalendarDate`).*/async findNearestDayId(trip_id: number, iso_date: string): Promise<number | undefined> {+ if (!isCalendarDate(iso_date)) return undefined;const platform = this.getEntityManager().getPlatform();const days = this.getEntityManager().getRepository(Days);const row = await daysdiff --git a/server/tests/integration/reservations.test.ts b/server/tests/integration/reservations.test.tsindex 9dde15e85..355fff945 100644--- a/server/tests/integration/reservations.test.ts+++ b/server/tests/integration/reservations.test.ts@@ -226,6 +226,20 @@ describe('Update reservation', () => {expect(res.body.reservation.end_day_id).toBe(day3.id);});+ it('RESV-004d — a reservation_time on a date the calendar does not have lands on no day, on every engine', async () => {+ const { user } = await makeUser(orm);+ const trip = await makeTrip(orm, user.id);+ await makeDay(orm, trip.id, { date: '2024-03-01' });++ // SQLite's JULIANDAY rolls 2024-02-30 over into March; Postgres refuses to cast it.+ const res = await request(app)+ .post(`/api/trips/${trip.id}/reservations`)+ .set('Cookie', authCookie(user.id))+ .send({ title: 'Event', type: 'event', reservation_time: '2024-02-30T10:00' });+ expect(res.status).toBe(201);+ expect(res.body.reservation.day_id).toBeNull();+ });+it('RESV-004 — PUT on non-existent reservation returns 404', async () => {const { user } = await makeUser(orm);const trip = await makeTrip(orm, user.id);diff --git a/server/tests/unit/db/dialect/sql-functions.test.ts b/server/tests/unit/db/dialect/sql-functions.test.tsindex 7c9a3129c..0cef4bdb2 100644--- a/server/tests/unit/db/dialect/sql-functions.test.ts+++ b/server/tests/unit/db/dialect/sql-functions.test.ts@@ -27,6 +27,7 @@ import {dateOf,dayDistance,foundAgainState,+ isCalendarDate,lower,lowerParam,lowerTrim,@@ -48,6 +49,7 @@ import { createJourney, createJourneyEntry } from '../../../helpers/factories';import { resetTestDb } from '../../../helpers/test-db';import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';import { Platform } from '@mikro-orm/core';+import { BasePostgreSqlPlatform, SqlitePlatform } from '@mikro-orm/sql';import { expressionBuilder, type ExpressionBuilder } from 'kysely';import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';@@ -982,6 +984,26 @@ describe('sql-functions (sqlite)', () => {expect(() => dayDistance(foreign, 'u.date', '2026-01-01')).toThrow(/no implementation for platform FakePlatform/);});+ it('SQLF-100: dayDistance refuses a date the calendar does not have, on every engine, which SQLite would roll over', () => {+ expect(isCalendarDate('2024-02-29')).toBe(true);+ expect(isCalendarDate('2026-12-31')).toBe(true);+ for (const text of [+ '2024-02-30',+ '2023-02-29',+ '2024-13-01',+ '2024-00-10',+ '2024-04-31',+ '2024-1-01',+ '2024-01-01T10:00',+ '',+ ]) {+ expect(isCalendarDate(text), text).toBe(false);+ }+ for (const platform of [new SqlitePlatform(), new BasePostgreSqlPlatform()]) {+ expect(() => dayDistance(platform, 'u.created_at', '2024-02-30')).toThrow(/needs a calendar date/);+ }+ });+// Plan 3d Task 0 review (H1/L1): the five helpers above return a MikroORM// RawQueryFragment, which stringifies to a literal `?` token and throws at// execution when handed into a Kysely statement — verified directly below