feat(db): run TREK on PostgreSQL

TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
This commit is contained in:
Isaias Tavares
2026-11-05 01:15:21 -03:00
committed by Maurice
parent 17b47b38b9
commit 2e3762afe1
176 changed files with 6728 additions and 777 deletions
@@ -1,6 +1,7 @@
import { coalesceOverride, columnRef } from '../dialect/sql-functions';
import type { DayAccommodations } from '../entities/DayAccommodations.entity';
import type { DB } from '../kysely/db';
import { accommodationIdMatches } from './_shared/reservation-accommodation';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -249,10 +250,13 @@ 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')
.leftJoin('reservations as r', (join) =>
join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'a.id')),
)
.selectAll('a')
.select([
'p.name as place_name',
@@ -469,6 +473,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 +490,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) => accommodationIdMatches(platform, eb2, 'r.accommodation_id', 'a.id'))
.as('reservation_id'),
])
.where('a.trip_id', '=', trip_id)
@@ -43,7 +43,9 @@ 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) }))
// The target row's column is qualified: Postgres reads a bare name as
// ambiguous between it and `excluded` (42702).
.onConflict((oc) => oc.column('day').doUpdateSet({ calls: (eb) => eb(eb.ref('google_api_usage.calls'), '+', 1) }))
.execute();
}
@@ -1,27 +1,18 @@
import { isMissingTableError } from '../migration-utils';
import type { EntityManager } from '@mikro-orm/core';
/**
* Plan 3i Task 3 — R1's raw-connection exception, named ahead of this plan by
* the program brief's own rule 4 ("connection.execute() (only in
* 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.
* Raw-connection statements that run on every engine and that no entity can
* express: the readiness ping and the plugin-table erasure. Not a
* `TrekRepository<Entity>`, since it backs no entity. The SQLite file's own
* maintenance (`PRAGMA wal_checkpoint`, `VACUUM INTO`) lives in
* `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 +21,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 {
@@ -44,69 +35,27 @@ export class MaintenanceRepository {
}
/**
* `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
* (`plugin_user_config`/`plugin_oauth_tokens`/`plugin_oauth_state`). These
* are `nest/plugins`' own tables (Plan 3b Task 5's "stays raw" ruling,
* 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
* 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
* (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
* whole lifetime, and a bare `execute()` tries to check out that SAME
* connection fresh instead of reusing the held one — a checkout that only
* frees once the transaction (which is itself awaiting THIS call)
* completes. `em.getTransactionContext()` returns the open transaction's
* driver handle when called from inside one (resolved the same
* `TransactionContext`-async-local-storage way `getContext()` is, so
* `this.em` need not be the transactional fork itself) and `undefined`
* otherwise, so passing it through is correct both inside and outside a
* transaction. Each statement is independently best-effort: a
* slimmed-down test schema may not carry one or more of these tables at
* all, matching the legacy per-table try/catch exactly.
* The per-user erasure of the three plugin-held tables (`plugin_user_config`,
* `plugin_oauth_tokens`, `plugin_oauth_state`), called inside the erasure's
* own `UnitOfWork.transactional(...)`.
*
* A table that does not exist (a slimmed-down test schema) is skipped; any
* other failure propagates. Each statement runs in its own savepoint, since
* on Postgres a failed statement aborts the whole transaction it is in.
* `em.getTransactionContext()` hands the statement the open transaction's
* connection, which a bare `execute()` would wait on forever.
*/
async deletePluginUserData(userId: number): Promise<void> {
this.validateRequestContext();
const ctx = this.em.getTransactionContext();
for (const table of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state']) {
try {
await this.em.getConnection().execute(`DELETE FROM ${table} WHERE user_id = ?`, [userId], 'run', ctx);
} catch {
/* table absent (slim schema) */
await this.em.transactional((em) =>
em
.getConnection()
.execute(`DELETE FROM ${table} WHERE user_id = ?`, [userId], 'run', em.getTransactionContext()),
);
} catch (err: unknown) {
if (!isMissingTableError(err)) throw err;
}
}
}
@@ -1,6 +1,6 @@
import type { Places } from '../entities/Places.entity';
import { wrapOptionalLongitude } from '@trek/shared';
import { absDifference, coalesceParam, columnRef, currentTimestamp, lowerTrim } from '../dialect/sql-functions';
import { absDifference, coalesceParam, columnRef, currentTimestamp, ilike, lowerTrim } from '../dialect/sql-functions';
import { type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import { tourPlaceTextPatch, type TourPlaceWrite } from './tour-place-write';
@@ -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();
@@ -680,15 +680,13 @@ export class PlacesRepository extends TrekRepository<Places> {
.where('p.trip_id = ?', [trip_id]);
if (filters.searchPattern) {
qb.andWhere(
"(p.name LIKE ? ESCAPE '\\' OR p.address LIKE ? ESCAPE '\\' OR p.description LIKE ? ESCAPE '\\')",
[filters.searchPattern, filters.searchPattern, filters.searchPattern],
);
const fields = ['p.name', 'p.address', 'p.description'];
qb.andWhere(ilike(platform, fields), fields.map(() => 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();
}
}
@@ -2,7 +2,8 @@ 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 { castIntegerKysely, concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
import { concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
import { accommodationIdMatches } from './_shared/reservation-accommodation';
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';
import type { DayAssignmentRow } from './day-assignment-rows';
import { TrekRepository } from './_shared/trek-repository';
@@ -32,18 +33,6 @@ export type {
PublicApiUnscheduledReservationRow,
};
/**
* 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.
*/
/**
* `reservations` as the two aliases below bind it: `accommodation_id` is a
* TEXT column, widened to `string | number | null` so the plain `number`
@@ -364,7 +353,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
findPassContext(id: number, tripId: number) { return passContextQuery(this.kysely<PassContextDB>(), id, tripId); }
private joinedQuery() {
return joinedReservationQuery(this.kysely<ReservationJoinDB>());
return joinedReservationQuery(this.kysely<ReservationJoinDB>(), this.getEntityManager().getPlatform());
}
/**
@@ -875,10 +864,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) => accommodationIdMatches(platform, eb, 'r.accommodation_id', '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')
@@ -894,7 +886,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) => accommodationIdMatches(platform, eb2, 'r2.accommodation_id', 'a.id'))
.as('stay_first_reservation_id'),
'rd.date as day_date',
'red.date as end_day_date',
@@ -932,6 +924,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)
@@ -953,7 +946,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
eb
.selectFrom('reservations as r')
.select('r.title')
.whereRef('r.accommodation_id', '=', 'a.id')
.where((eb2) => accommodationIdMatches(platform, eb2, 'r.accommodation_id', 'a.id'))
.where((eb2) => publicReservationExpr(eb2, 'r.ingest_state'))
.orderBy('r.id', 'asc')
.limit(1)
@@ -1039,7 +1032,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
eb
.selectFrom('reservations as res')
.select('res.title')
.where((eb2) => eb2(castIntegerKysely(platform, eb2, 'res.accommodation_id'), '=', eb2.ref('a.id')))
.where((eb2) => accommodationIdMatches(platform, eb2, 'res.accommodation_id', 'a.id'))
.where('res.status', '!=', 'cancelled')
.orderBy('res.id', 'asc')
.limit(1),
@@ -1080,7 +1073,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
eb
.selectFrom('reservations as res')
.select('res.title')
.where((eb2) => eb2(castIntegerKysely(platform, eb2, 'res.accommodation_id'), '=', eb2.ref('a.id')))
.where((eb2) => accommodationIdMatches(platform, eb2, 'res.accommodation_id', 'a.id'))
.where('res.status', '!=', 'cancelled')
.orderBy('res.id', 'asc')
.limit(1),
@@ -80,12 +80,14 @@ export class RouteUsageDailyRepository extends TrekRepository<RouteUsageDaily> {
await this.kysely<RouteUsageDailyKyselyDB>()
.insertInto('route_usage_daily')
.values(entry)
// The target row's columns are qualified: Postgres reads a bare name as
// ambiguous between it and `excluded` (42702).
.onConflict((oc) =>
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();
@@ -1,6 +1,6 @@
import { QueryFlag } from '@mikro-orm/core';
import type { TTripsCostsMode, Trips } from '../entities/Trips.entity';
import { coalesceParam, currentTimestamp, nowDateOffset } from '../dialect/sql-functions';
import { coalesceParam, currentTimestamp, ilike, nowDateOffset } from '../dialect/sql-functions';
import type { AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
import { tripAccessExpr } from './_shared/trip-access';
@@ -175,7 +175,7 @@ export class TripsRepository extends TrekRepository<Trips> {
return await this.accessibleTripsQuery(user_id)
.join('t.places_collection', 'p')
.select(['p.trip', 'p.name'])
.andWhere("(p.name LIKE ? ESCAPE '\\' OR p.address LIKE ? ESCAPE '\\')", [likePattern, likePattern])
.andWhere(ilike(this.getEntityManager().getPlatform(), ['p.name', 'p.address']), [likePattern, likePattern])
.orderBy([{ 'p.trip': 'asc' }, { 'p.name': 'asc' }])
.limit(500)
// The limit is on the joined place rows, like the legacy statement's.
@@ -0,0 +1,22 @@
import { castIntegerKysely } from '../../dialect/kysely-functions';
import type { Platform } from '@mikro-orm/core';
import type { ExpressionBuilder, ExpressionWrapper, SqlBool, StringReference } from 'kysely';
/**
* The join condition between a reservation and the stay it is booked against.
*
* `reservations.accommodation_id` is TEXT with no foreign key, while
* `day_accommodations.id` is INTEGER, so the comparison is written as
* `CAST(<reservation ref> AS INTEGER) = <stay ref>`. SQLite coerces a bare
* text-to-integer comparison and Postgres refuses it (42883), so the cast is
* needed on both engines. A stored `'14.0'` casts to 14 on both.
*/
export function accommodationIdMatches<DB, TB extends keyof DB>(
platform: Platform,
eb: ExpressionBuilder<DB, TB>,
reservationAccommodationId: StringReference<DB, TB>,
stayId: StringReference<DB, TB>,
): ExpressionWrapper<DB, TB, SqlBool> {
return eb(castIntegerKysely(platform, eb, reservationAccommodationId), '=', eb.ref(stayId).$castTo<number>());
}
@@ -1,4 +1,6 @@
import type { DB } from '../../kysely/db';
import { accommodationIdMatches } from './reservation-accommodation';
import type { Platform } from '@mikro-orm/core';
import type { Kysely } from 'kysely';
@@ -9,14 +11,18 @@ export type ReservationJoinDB = Pick<DB, 'reservations' | 'days' | 'places' | 'd
* A booking with its day number, its place's name and its stay's place and
* times: the projection `ReservationsRepository.listForTrip` and
* `findWithJoins` narrow with their own `WHERE`. Kept out of the repository
* file, which is at its size baseline.
* file, which is at its size baseline. `accommodation_id` is TEXT and `ap.id`
* INTEGER, so the stay is matched through accommodationIdMatches: SQLite
* coerces the bare comparison, Postgres refuses it.
*/
export function joinedReservationQuery(kysely: Kysely<ReservationJoinDB>) {
export function joinedReservationQuery(kysely: Kysely<ReservationJoinDB>, platform: Platform) {
return kysely
.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('day_accommodations as ap', (join) =>
join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'ap.id')),
)
.leftJoin('places as acc_p', 'acc_p.id', 'ap.place_id')
.selectAll('r')
.select([