mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 19:16:08 +00:00
fix(db): run every repository statement the Postgres probe reaches
The probe's baseline is empty now: no repository method Postgres refuses, none it cannot measure. - reservations.accommodation_id (TEXT) is cast where it is compared with day_accommodations.id (INTEGER), in the four reservation reads and the two stay reads; SQLite coerced the bare comparison, Postgres refuses it. The joined RS18/RR1 read moves to reservation-join.ts beside the repository. - The usage counters qualify the target row's column in DO UPDATE SET, which Postgres reads as ambiguous with `excluded` otherwise. - ReservationDayPositions.upsertScoped upserts on its primary key instead of INSERT OR REPLACE; position is the only other column and nothing references the table, so the row left behind is the same. - PRAGMA wal_checkpoint and VACUUM INTO move from MaintenanceRepository to SqliteMaintenance under src/db/engine/sqlite/, the SQLite engine's folder, where lint:dialect allows PRAGMA. - The places list takes category and tag ids as numbers: the service converts the query text with toRowId and answers an empty list for one that is no id, instead of binding the text to an integer column. - The probe samples the `present` flag of a partial update's pair as true, so the four update methods that sent no SQL are measured, and it now holds SQLSTATE class 22 too: a value of the wrong type reaching a column is the code's, since the sampler sends what each parameter declares.
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The SQLite engine's whole-file maintenance: the two statements a backup,
|
||||
* a restore and the demo reset need that are about the database file rather
|
||||
* than any table (`PRAGMA wal_checkpoint`, `VACUUM INTO`). Neither has a
|
||||
* Postgres spelling, so they live under the engine that owns the file instead
|
||||
* of in `MaintenanceRepository`, whose remaining statements run on every
|
||||
* engine (and which the Postgres probe calls method by method).
|
||||
*
|
||||
* Provided through Nest DI by `MaintenanceModule` (`nest/database/`), a
|
||||
* factory over the context-resolving global `EntityManager`, and injected by
|
||||
* the SQLite backup port (`SqliteDatabaseBackup`). Free of Nest decorators
|
||||
* like every other file under `db/`, so a test can build one over its own
|
||||
* `EntityManager`.
|
||||
*/
|
||||
export class SqliteMaintenance {
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
|
||||
/**
|
||||
* MikroORM's own validating `getContext()`: throws outside a request
|
||||
* context, the fail-closed check `TrekRepository` applies to every
|
||||
* repository, since a raw `connection.execute()` has no such guard.
|
||||
*/
|
||||
private validateRequestContext(): void {
|
||||
this.em.getContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* `PRAGMA wal_checkpoint(TRUNCATE)`: flushes the WAL into the main file
|
||||
* before a snapshot or a swap. Reached through the backup port's
|
||||
* `checkpoint()`; every caller treats it as best effort.
|
||||
*/
|
||||
async walCheckpoint(): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
await this.em.getConnection().execute('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
}
|
||||
|
||||
/**
|
||||
* `` VACUUM INTO '<path>' ``: a consistent point-in-time copy of the file
|
||||
* under concurrent writers, reached through the backup port's
|
||||
* `snapshot()`. Single quotes in `path` are escaped by doubling.
|
||||
*/
|
||||
async vacuumInto(path: string): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
const escaped = path.replaceAll("'", "''");
|
||||
await this.em.getConnection().execute(`VACUUM INTO '${escaped}'`);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { castIntegerKysely } from '../dialect/kysely-functions';
|
||||
import { coalesceOverride, columnRef } from '../dialect/sql-functions';
|
||||
import type { DayAccommodations } from '../entities/DayAccommodations.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
@@ -249,10 +250,15 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
|
||||
* parity keeps the duplicates, no `DISTINCT`.
|
||||
*/
|
||||
async listForTripWithPlaceAndBooking(trip_id: number | string): Promise<DayAccommodationListRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.kysely<DayAccommodationListKyselyDB>()
|
||||
.selectFrom('day_accommodations as a')
|
||||
.leftJoin('places as p', 'p.id', 'a.place_id')
|
||||
.leftJoin('reservations as r', 'r.accommodation_id', 'a.id')
|
||||
// TEXT `accommodation_id` against INTEGER `a.id`: cast, as Postgres refuses
|
||||
// to compare the two (42883) where SQLite coerces.
|
||||
.leftJoin('reservations as r', (join) =>
|
||||
join.on((eb) => eb(castIntegerKysely(platform, eb, 'r.accommodation_id'), '=', eb.ref('a.id'))),
|
||||
)
|
||||
.selectAll('a')
|
||||
.select([
|
||||
'p.name as place_name',
|
||||
@@ -469,6 +475,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
|
||||
* this table (see {@link DayAccommodationListKyselyDB}).
|
||||
*/
|
||||
async listRoadtripStays(trip_id: number): Promise<RoadtripStayRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.kysely<RoadtripStaysKyselyDB>()
|
||||
.selectFrom('day_accommodations as a')
|
||||
.leftJoin('places as p', 'p.id', 'a.place_id')
|
||||
@@ -485,7 +492,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
|
||||
eb
|
||||
.selectFrom('reservations as r')
|
||||
.select((eb2) => eb2.fn.min<number | null>('r.id').as('m'))
|
||||
.whereRef('r.accommodation_id', '=', 'a.id')
|
||||
.where((eb2) => eb2(castIntegerKysely(platform, eb2, 'r.accommodation_id'), '=', eb2.ref('a.id')))
|
||||
.as('reservation_id'),
|
||||
])
|
||||
.where('a.trip_id', '=', trip_id)
|
||||
|
||||
@@ -43,7 +43,11 @@ export class GoogleApiUsageRepository extends TrekRepository<GoogleApiUsage> {
|
||||
await this.kysely<GoogleApiUsageKyselyDB>()
|
||||
.insertInto('google_api_usage')
|
||||
.values({ day, calls: 1 })
|
||||
.onConflict((oc) => oc.column('day').doUpdateSet({ calls: (eb) => eb('calls', '+', 1) }))
|
||||
.onConflict((oc) =>
|
||||
// Qualified: Postgres reads a bare `calls` here as ambiguous between the
|
||||
// target row and `excluded` (42702); SQLite accepts both spellings.
|
||||
oc.column('day').doUpdateSet({ calls: (eb) => eb(eb.ref('google_api_usage.calls'), '+', 1) }),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
|
||||
@@ -6,22 +6,20 @@ import type { EntityManager } from '@mikro-orm/core';
|
||||
* MaintenanceRepository/DemoRepository, with a comment)").
|
||||
*
|
||||
* Not a `TrekRepository<Entity>` — it backs no table and no entity of its
|
||||
* own. It exists purely as the one place two whole-database-file statements
|
||||
* (a `PRAGMA` and a `VACUUM INTO`) run against the ORM's own bound driver
|
||||
* connection instead of scattering raw `better-sqlite3` calls across
|
||||
* `backup.impl.ts`/`demo-reset.ts`. `find/findOne → create/assign/flush →
|
||||
* nativeUpdate/nativeDelete → em.upsert → qb() → em.getKysely()` all fail
|
||||
* for these two statements — neither is expressible against an entity at
|
||||
* all — so `connection.execute()` (the last tier in the program's query-API
|
||||
* order) is the correct tool, not a shortcut around it.
|
||||
* own. It holds the statements no entity can express that run on every
|
||||
* engine: the readiness ping and the plugin-table erasure. `find/findOne →
|
||||
* create/assign/flush → nativeUpdate/nativeDelete → em.upsert → qb() →
|
||||
* em.getKysely()` all fail for them, so `connection.execute()` (the last
|
||||
* tier in the program's query-API order) is the correct tool, not a
|
||||
* shortcut around it. The SQLite file's own maintenance (`PRAGMA
|
||||
* wal_checkpoint`, `VACUUM INTO`) is `SqliteMaintenance`, under
|
||||
* `db/engine/sqlite/`.
|
||||
*
|
||||
* Provided through Nest DI by `MaintenanceModule` (`nest/database/`), a
|
||||
* factory over the context-resolving global `EntityManager`; its consumers
|
||||
* inject it: the readiness probe, `UserCleanupService` and the SQLite backup
|
||||
* port (`SqliteDatabaseBackup`), which the backup, the restore and the demo
|
||||
* reset all go through. The class stays free of Nest decorators like every
|
||||
* other file under `db/`, so a test can still build one over its own
|
||||
* `EntityManager`.
|
||||
* inject it: the readiness probe and `UserCleanupService`. The class stays
|
||||
* free of Nest decorators like every other file under `db/`, so a test can
|
||||
* still build one over its own `EntityManager`.
|
||||
*/
|
||||
export class MaintenanceRepository {
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
@@ -30,7 +28,7 @@ export class MaintenanceRepository {
|
||||
* MikroORM's own validating `getContext()` — throws
|
||||
* `ValidationError.cannotUseGlobalContext()` outside a request context (the
|
||||
* production default), the same fail-closed ratchet `TrekRepository`
|
||||
* applies to every entity-bound repository. Called first by both methods
|
||||
* applies to every entity-bound repository. Called first by every method
|
||||
* below, since raw `connection.execute()` has no such guard of its own.
|
||||
*/
|
||||
private validateRequestContext(): void {
|
||||
@@ -43,32 +41,6 @@ export class MaintenanceRepository {
|
||||
await this.em.getConnection().execute('SELECT 1');
|
||||
}
|
||||
|
||||
/**
|
||||
* `PRAGMA wal_checkpoint(TRUNCATE)` — rendered text pinned, identical to
|
||||
* the legacy `db.exec('PRAGMA wal_checkpoint(TRUNCATE)')` it replaces.
|
||||
* Reached through the backup port's `checkpoint()`, which the backup
|
||||
* (BK1) and the demo reset (DMR3) call. Flushes the WAL into the main db
|
||||
* file before a snapshot or a swap; every caller treats it as best effort.
|
||||
*/
|
||||
async walCheckpoint(): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
await this.em.getConnection().execute('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
}
|
||||
|
||||
/**
|
||||
* `` VACUUM INTO '<path>' `` — rendered text pinned, identical to the
|
||||
* legacy `` db.exec(`VACUUM INTO '${dbSnap.replaceAll("'", "''")}'`) ``
|
||||
* (BK2, reached through the backup port's `snapshot()`): single quotes in `path` are
|
||||
* escaped by doubling, the same escaping the legacy statement used — a
|
||||
* consistent point-in-time snapshot under concurrent writers, with no
|
||||
* MikroORM/Kysely equivalent.
|
||||
*/
|
||||
async vacuumInto(path: string): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
const escaped = path.replaceAll("'", "''");
|
||||
await this.em.getConnection().execute(`VACUUM INTO '${escaped}'`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan 4 Task 4 — UC1 (`UserCleanupService.erasePluginUserData`): a
|
||||
* best-effort per-user delete across the three plugin-held tables
|
||||
@@ -77,13 +49,13 @@ export class MaintenanceRepository {
|
||||
* narrowed by Plan 4 Task 8a to just this trio — UC2/UC3 already moved to
|
||||
* `PluginsRepository`/`PluginUserErasureQueueRepository`), not an entity
|
||||
* managed by any repository, so `connection.execute()` (rule 4's last
|
||||
* tier) is the correct tool here, same shape as `walCheckpoint`/
|
||||
* `vacuumInto` above — with ONE difference those two don't need: this is
|
||||
* tier) is the correct tool here, same shape as `ping` above and
|
||||
* `SqliteMaintenance`'s statements — with ONE difference those don't need: this is
|
||||
* the first `MaintenanceRepository` caller ever invoked from INSIDE an
|
||||
* open `UnitOfWork.transactional(...)` (`deleteUserCompletely`'s
|
||||
* transaction). `Connection#execute(query, params, method, ctx)`'s `ctx`
|
||||
* defaults to the plain (non-transactional) Kysely client when omitted —
|
||||
* `walCheckpoint`/`vacuumInto` always omit it because their callers
|
||||
* `SqliteMaintenance`'s statements always omit it because their callers
|
||||
* (the backup port) never run inside a transaction, but
|
||||
* omitting it here deadlocked: this repo's `better-sqlite3` connection is
|
||||
* single-connection/single-writer, the open transaction holds it for its
|
||||
|
||||
@@ -659,8 +659,8 @@ export class PlacesRepository extends TrekRepository<Places> {
|
||||
*/
|
||||
async listForTrip(trip_id: string, filters: {
|
||||
searchPattern?: string;
|
||||
category?: string;
|
||||
tag?: string;
|
||||
category?: number;
|
||||
tag?: number;
|
||||
assignment?: 'all' | 'unassigned' | 'assigned';
|
||||
}): Promise<PlaceListRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
@@ -685,10 +685,10 @@ export class PlacesRepository extends TrekRepository<Places> {
|
||||
[filters.searchPattern, filters.searchPattern, filters.searchPattern],
|
||||
);
|
||||
}
|
||||
if (filters.category) {
|
||||
if (filters.category !== undefined) {
|
||||
qb.andWhere('p.category_id = ?', [filters.category]);
|
||||
}
|
||||
if (filters.tag) {
|
||||
if (filters.tag !== undefined) {
|
||||
qb.andWhere('p.id IN (SELECT place_id FROM place_tags WHERE tag_id = ?)', [filters.tag]);
|
||||
}
|
||||
if (filters.assignment === 'unassigned') {
|
||||
|
||||
@@ -52,10 +52,14 @@ export class ReservationDayPositionsRepository extends TrekRepository<Reservatio
|
||||
* position) SELECT r.id, d.id, ? FROM reservations r JOIN days d ON
|
||||
* d.trip_id = r.trip_id WHERE r.id = ? AND d.id = ? AND r.trip_id = ?`.
|
||||
*
|
||||
* Kysely `insertInto().orReplace().columns().expression(selectFrom…)`
|
||||
* (the MikroORM QueryBuilder's `insertFrom` has no `OR REPLACE` flag —
|
||||
* `.onConflict().merge()` is semantically different, a real UPDATE rather
|
||||
* than REPLACE's delete-then-insert). The trip scoping lives IN the
|
||||
* Kysely `insertInto().columns().expression(selectFrom…)` with an
|
||||
* `ON CONFLICT (reservation_id, day_id) DO UPDATE SET position`, which both
|
||||
* engines read (`INSERT OR REPLACE` is SQLite only). The pair is the
|
||||
* table's whole primary key and `position` its only other column, so the
|
||||
* update leaves the same row REPLACE's delete-then-insert did, and no
|
||||
* foreign key points at this table for the delete to have cascaded to.
|
||||
* The SELECT keeps its WHERE, which SQLite needs to read the trailing
|
||||
* ON CONFLICT as the upsert clause. The trip scoping lives IN the
|
||||
* SELECT (a foreign `reservation_id`/`day_id` materialises zero rows to
|
||||
* insert, never a foreign-key error) — preserved exactly, not hoisted
|
||||
* into a pre-check.
|
||||
@@ -68,7 +72,6 @@ export class ReservationDayPositionsRepository extends TrekRepository<Reservatio
|
||||
): Promise<void> {
|
||||
await this.kysely<ReservationDayPositionsKyselyDB>()
|
||||
.insertInto('reservation_day_positions')
|
||||
.orReplace()
|
||||
.columns(['reservation_id', 'day_id', 'position'])
|
||||
.expression((eb) =>
|
||||
eb
|
||||
@@ -79,6 +82,9 @@ export class ReservationDayPositionsRepository extends TrekRepository<Reservatio
|
||||
.where('d.id', '=', day_id)
|
||||
.where('r.trip_id', '=', trip_id as number),
|
||||
)
|
||||
.onConflict((oc) =>
|
||||
oc.columns(['reservation_id', 'day_id']).doUpdateSet((eb) => ({ position: eb.ref('excluded.position') })),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { coalesceOverride, columnRef, dayDistance } from '../dialect/sql-functio
|
||||
import { castIntegerKysely, concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
|
||||
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';
|
||||
import type { DayAssignmentRow } from './day-assignment-rows';
|
||||
import { selectReservationsWithJoins, type ReservationJoinKyselyDB, type ReservationJoinRow } from './reservation-join';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { ROADTRIP_RESERVATION_TYPES } from '@trek/shared';
|
||||
@@ -18,47 +19,15 @@ import type {
|
||||
PublicApiUnscheduledReservationRow,
|
||||
} from './reservation-public-api-rows';
|
||||
|
||||
// The public API row types moved to their own module; re-exported so callers keep one import path.
|
||||
// The joined and public API row types moved to their own modules; re-exported so callers keep one import path.
|
||||
export type {
|
||||
ReservationJoinRow,
|
||||
PublicApiAccommodationRow,
|
||||
PublicApiScheduledReservationRow,
|
||||
PublicApiUnplannedPlaceRow,
|
||||
PublicApiUnscheduledReservationRow,
|
||||
};
|
||||
|
||||
/**
|
||||
* RS18/RR1's shared joined projection — `SELECT r.*, d.day_number, p.name as
|
||||
* place_name, r.assignment_id, ap.place_id as accommodation_place_id,
|
||||
* acc_p.name as accommodation_name, ap.start_day_id as
|
||||
* accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id FROM
|
||||
* reservations r LEFT JOIN days d ON r.day_id = d.id LEFT JOIN places p ON
|
||||
* r.place_id = p.id LEFT JOIN day_accommodations ap ON r.accommodation_id =
|
||||
* ap.id LEFT JOIN places acc_p ON ap.place_id = acc_p.id`. The service
|
||||
* folds `accommodation_id` (`Math.trunc(Number(x))`), `day_positions`,
|
||||
* `endpoints` and `travelers` on afterward (unchanged from the legacy split).
|
||||
*/
|
||||
export interface ReservationJoinRow extends ReservationAllColumnsRow {
|
||||
day_number: number | null;
|
||||
place_name: string | null;
|
||||
accommodation_place_id: number | null;
|
||||
accommodation_name: string | null;
|
||||
accommodation_start_day_id: number | null;
|
||||
accommodation_end_day_id: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kysely typing for the RS18/RR1 join (`joinedQuery` below) — `reservations
|
||||
* .accommodation_id` is a bare `p.text().nullable()` column with no FK to
|
||||
* `day_accommodations` (§18.1 of the inventory), so the QueryBuilder's
|
||||
* relation-path `.join()` cannot express `LEFT JOIN day_accommodations ap ON
|
||||
* r.accommodation_id = ap.id` at all — the same escape hatch
|
||||
* `DayAssignmentsRepository.effectiveStart`/`TripsRepository.tripSelectQuery`
|
||||
* use. The `id`/`trip_id` the callers pass stay `number | string` (raw-bind,
|
||||
* D4's T5 seam) and are cast to the column type only at the bind, so this
|
||||
* join keeps the legacy statement's exact raw-bind flexibility.
|
||||
*/
|
||||
type ReservationJoinKyselyDB = Pick<DB, 'reservations' | 'days' | 'places' | 'day_accommodations'>;
|
||||
|
||||
/**
|
||||
* `reservations` as the two aliases below bind it: `accommodation_id` is a
|
||||
* TEXT column, widened to `string | number | null` so the plain `number`
|
||||
@@ -380,21 +349,7 @@ type FlightsMissingEndpointsKyselyDB = Pick<DB, 'reservations' | 'reservation_en
|
||||
|
||||
export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
private joinedQuery() {
|
||||
return this.kysely<ReservationJoinKyselyDB>()
|
||||
.selectFrom('reservations as r')
|
||||
.leftJoin('days as d', 'd.id', 'r.day_id')
|
||||
.leftJoin('places as p', 'p.id', 'r.place_id')
|
||||
.leftJoin('day_accommodations as ap', 'ap.id', 'r.accommodation_id')
|
||||
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
|
||||
.selectAll('r')
|
||||
.select([
|
||||
'd.day_number as day_number',
|
||||
'p.name as place_name',
|
||||
'ap.place_id as accommodation_place_id',
|
||||
'acc_p.name as accommodation_name',
|
||||
'ap.start_day_id as accommodation_start_day_id',
|
||||
'ap.end_day_id as accommodation_end_day_id',
|
||||
]);
|
||||
return selectReservationsWithJoins(this.kysely<ReservationJoinKyselyDB>(), this.getEntityManager().getPlatform());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -890,10 +845,13 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
|
||||
/** CL2 — see {@link CalendarReservationRow}'s docstring. */
|
||||
async listForCalendar(trip_id: number | string): Promise<CalendarReservationRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.kysely<CalendarReservationKyselyDB>()
|
||||
.selectFrom('reservations as r')
|
||||
.leftJoin('places as pl', 'pl.id', 'r.place_id')
|
||||
.leftJoin('day_accommodations as a', 'a.id', 'r.accommodation_id')
|
||||
.leftJoin('day_accommodations as a', (join) =>
|
||||
join.on((eb) => eb(castIntegerKysely(platform, eb, 'r.accommodation_id'), '=', eb.ref('a.id'))),
|
||||
)
|
||||
.leftJoin('days as sd', 'sd.id', 'a.start_day_id')
|
||||
.leftJoin('days as ed', 'ed.id', 'a.end_day_id')
|
||||
.leftJoin('days as rd', 'rd.id', 'r.day_id')
|
||||
@@ -909,7 +867,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
eb
|
||||
.selectFrom('reservations as r2')
|
||||
.select((eb2) => eb2.fn.min<number | null>('r2.id').as('c'))
|
||||
.whereRef('r2.accommodation_id', '=', 'a.id')
|
||||
.where((eb2) => eb2(castIntegerKysely(platform, eb2, 'r2.accommodation_id'), '=', eb2.ref('a.id')))
|
||||
.as('stay_first_reservation_id'),
|
||||
'rd.date as day_date',
|
||||
'red.date as end_day_date',
|
||||
@@ -947,6 +905,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
|
||||
/** CL7 — see {@link CalendarStayRow}'s docstring. */
|
||||
async listPublicStaysForCalendar(trip_id: number | string): Promise<CalendarStayRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.kysely<CalendarStayKyselyDB>()
|
||||
.selectFrom('day_accommodations as a')
|
||||
.where('a.trip_id', '=', trip_id as number)
|
||||
@@ -968,7 +927,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
eb
|
||||
.selectFrom('reservations as r')
|
||||
.select('r.title')
|
||||
.whereRef('r.accommodation_id', '=', 'a.id')
|
||||
.where((eb2) => eb2(castIntegerKysely(platform, eb2, 'r.accommodation_id'), '=', eb2.ref('a.id')))
|
||||
.where((eb2) => publicReservationExpr(eb2, 'r.ingest_state'))
|
||||
.orderBy('r.id', 'asc')
|
||||
.limit(1)
|
||||
|
||||
@@ -81,11 +81,13 @@ export class RouteUsageDailyRepository extends TrekRepository<RouteUsageDaily> {
|
||||
.insertInto('route_usage_daily')
|
||||
.values(entry)
|
||||
.onConflict((oc) =>
|
||||
// The target row's columns are qualified: Postgres reads a bare name
|
||||
// as ambiguous between it and `excluded` (42702).
|
||||
oc.columns(['day', 'profile', 'surface', 'self_hosted']).doUpdateSet({
|
||||
requests: (eb) => eb('requests', '+', eb.ref('excluded.requests')),
|
||||
waypoints: (eb) => eb('waypoints', '+', eb.ref('excluded.waypoints')),
|
||||
km: (eb) => eb('km', '+', eb.ref('excluded.km')),
|
||||
failed: (eb) => eb('failed', '+', eb.ref('excluded.failed')),
|
||||
requests: (eb) => eb(eb.ref('route_usage_daily.requests'), '+', eb.ref('excluded.requests')),
|
||||
waypoints: (eb) => eb(eb.ref('route_usage_daily.waypoints'), '+', eb.ref('excluded.waypoints')),
|
||||
km: (eb) => eb(eb.ref('route_usage_daily.km'), '+', eb.ref('excluded.km')),
|
||||
failed: (eb) => eb(eb.ref('route_usage_daily.failed'), '+', eb.ref('excluded.failed')),
|
||||
}),
|
||||
)
|
||||
.execute();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* RS18/RR1's joined read of reservations: the row shape, the Kysely tables it
|
||||
* binds and the statement. It lives beside the reservations repository so
|
||||
* that file stays readable; the repository re-exports the row type, so
|
||||
* callers keep importing it from there.
|
||||
*/
|
||||
import { castIntegerKysely } from '../dialect/kysely-functions';
|
||||
import type { DB } from '../kysely/db';
|
||||
import type { ReservationAllColumnsRow } from './Reservations.repository';
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
|
||||
import type { Kysely } from 'kysely';
|
||||
|
||||
/**
|
||||
* RS18/RR1's shared joined projection — `SELECT r.*, d.day_number, p.name as
|
||||
* place_name, r.assignment_id, ap.place_id as accommodation_place_id,
|
||||
* acc_p.name as accommodation_name, ap.start_day_id as
|
||||
* accommodation_start_day_id, ap.end_day_id as accommodation_end_day_id FROM
|
||||
* reservations r LEFT JOIN days d ON r.day_id = d.id LEFT JOIN places p ON
|
||||
* r.place_id = p.id LEFT JOIN day_accommodations ap ON r.accommodation_id =
|
||||
* ap.id LEFT JOIN places acc_p ON ap.place_id = acc_p.id`. The service
|
||||
* folds `accommodation_id` (`Math.trunc(Number(x))`), `day_positions`,
|
||||
* `endpoints` and `travelers` on afterward (unchanged from the legacy split).
|
||||
*/
|
||||
export interface ReservationJoinRow extends ReservationAllColumnsRow {
|
||||
day_number: number | null;
|
||||
place_name: string | null;
|
||||
accommodation_place_id: number | null;
|
||||
accommodation_name: string | null;
|
||||
accommodation_start_day_id: number | null;
|
||||
accommodation_end_day_id: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kysely typing for the RS18/RR1 join — `reservations.accommodation_id` is a
|
||||
* bare `p.text().nullable()` column with no FK to `day_accommodations` (§18.1
|
||||
* of the inventory), so the QueryBuilder's relation-path `.join()` cannot
|
||||
* express `LEFT JOIN day_accommodations ap ON r.accommodation_id = ap.id` at
|
||||
* all — the same escape hatch `DayAssignmentsRepository.effectiveStart`/
|
||||
* `TripsRepository.tripSelectQuery` use. The `id`/`trip_id` the callers pass
|
||||
* stay `number | string` (raw-bind, D4's T5 seam) and are cast to the column
|
||||
* type only at the bind, so this join keeps the legacy statement's exact
|
||||
* raw-bind flexibility.
|
||||
*/
|
||||
export type ReservationJoinKyselyDB = Pick<DB, 'reservations' | 'days' | 'places' | 'day_accommodations'>;
|
||||
|
||||
/**
|
||||
* The joined projection, without a WHERE or ORDER BY: each caller adds its
|
||||
* own. `accommodation_id` is TEXT and `ap.id` INTEGER, so the text side is
|
||||
* cast for the join (SQLite coerces the bare comparison, Postgres refuses it
|
||||
* with 42883).
|
||||
*/
|
||||
export function selectReservationsWithJoins(db: Kysely<ReservationJoinKyselyDB>, platform: Platform) {
|
||||
return db
|
||||
.selectFrom('reservations as r')
|
||||
.leftJoin('days as d', 'd.id', 'r.day_id')
|
||||
.leftJoin('places as p', 'p.id', 'r.place_id')
|
||||
.leftJoin('day_accommodations as ap', (join) =>
|
||||
join.on((eb) => eb(castIntegerKysely(platform, eb, 'r.accommodation_id'), '=', eb.ref('ap.id'))),
|
||||
)
|
||||
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
|
||||
.selectAll('r')
|
||||
.select([
|
||||
'd.day_number as day_number',
|
||||
'p.name as place_name',
|
||||
'ap.place_id as accommodation_place_id',
|
||||
'acc_p.name as accommodation_name',
|
||||
'ap.start_day_id as accommodation_start_day_id',
|
||||
'ap.end_day_id as accommodation_end_day_id',
|
||||
]);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
|
||||
import { SqliteMaintenance } from '../../db/engine/sqlite/sqlite-maintenance';
|
||||
import { logInfo, logWarn } from '../audit/audit-log.logger';
|
||||
import {
|
||||
DatabaseConnectionLostError,
|
||||
@@ -35,7 +35,7 @@ export class SqliteDatabaseBackup implements DatabaseBackupStrategy {
|
||||
|
||||
constructor(
|
||||
private readonly lifecycle: DatabaseLifecycle,
|
||||
private readonly maintenance: MaintenanceRepository,
|
||||
private readonly maintenance: SqliteMaintenance,
|
||||
) {}
|
||||
|
||||
location(): string {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { SqliteMaintenance } from '../../db/engine/sqlite/sqlite-maintenance';
|
||||
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Provides `MaintenanceRepository`, the home of the few whole-database
|
||||
* statements no entity can express (the readiness ping, the WAL checkpoint,
|
||||
* `VACUUM INTO`, the plugin-table erasure).
|
||||
* statements no entity can express (the readiness ping, the plugin-table
|
||||
* erasure), and `SqliteMaintenance`, the SQLite file's own (the WAL
|
||||
* checkpoint, `VACUUM INTO`).
|
||||
*
|
||||
* A factory over the context-resolving global `EntityManager`, the same one
|
||||
* Nest injects into every service, so the repository resolves the request or
|
||||
* Factories over the context-resolving global `EntityManager`, the same one
|
||||
* Nest injects into every service, so each resolves the request or
|
||||
* transaction fork that is active when a method runs. The class itself stays
|
||||
* free of Nest, like every other file under `db/`.
|
||||
*/
|
||||
@@ -19,7 +21,12 @@ import { Module } from '@nestjs/common';
|
||||
useFactory: (em: EntityManager) => new MaintenanceRepository(em),
|
||||
inject: [EntityManager],
|
||||
},
|
||||
{
|
||||
provide: SqliteMaintenance,
|
||||
useFactory: (em: EntityManager) => new SqliteMaintenance(em),
|
||||
inject: [EntityManager],
|
||||
},
|
||||
],
|
||||
exports: [MaintenanceRepository],
|
||||
exports: [MaintenanceRepository, SqliteMaintenance],
|
||||
})
|
||||
export class MaintenanceModule {}
|
||||
|
||||
@@ -251,12 +251,10 @@ export class PlacesService {
|
||||
// the coercion stays here (the service), the repository binds the
|
||||
// already-built pattern verbatim (PL3).
|
||||
const searchPattern = filters.search ? `%${escapeLikePattern(filters.search)}%` : undefined;
|
||||
const places: PlaceListRow[] = await this.placesRepo.listForTrip(tripId, {
|
||||
searchPattern,
|
||||
category: filters.category,
|
||||
tag: filters.tag,
|
||||
assignment: filters.assignment,
|
||||
});
|
||||
// A category or tag that is no canonical id (toRowId) matches nothing; bound as text, Postgres would refuse it.
|
||||
const [category, tag] = [filters.category, filters.tag].map((id) => (id ? toRowId(id) : undefined));
|
||||
if (category === null || tag === null) return [];
|
||||
const places: PlaceListRow[] = await this.placesRepo.listForTrip(tripId, { searchPattern, category, tag, assignment: filters.assignment });
|
||||
|
||||
const placeIds = places.map(p => p.id);
|
||||
const tagsByPlaceId = await this.queryHelpers.loadTagsByPlaceIds(placeIds);
|
||||
|
||||
Reference in New Issue
Block a user