mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +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,109 @@
|
||||
import { SqliteMaintenance } from '../../../../../src/db/engine/sqlite/sqlite-maintenance';
|
||||
import { createSnapshotTestDb } from '../../../../helpers/db-mock';
|
||||
import { createTestOrm, type TestOrm } from '../../../../helpers/test-orm';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let maintenance: SqliteMaintenance;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
maintenance = new SqliteMaintenance(t.em);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* The first SQL text handed to the connection after the spy is set (the ORM
|
||||
* may read its own metadata on the same connection afterwards).
|
||||
*/
|
||||
function spyOnExecute(): { first: () => string; restore: () => void } {
|
||||
const connection = t.em.getConnection();
|
||||
const spy = vi.spyOn(connection, 'execute');
|
||||
return {
|
||||
first: () => String(spy.mock.calls[0]?.[0]),
|
||||
restore: () => spy.mockRestore(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether the SQLite file at `file` holds a table named `table`. */
|
||||
function holdsTable(file: string, table: string): boolean {
|
||||
const snap = new Database(file, { readonly: true });
|
||||
try {
|
||||
return (snap.pragma(`table_info(${table})`) as unknown[]).length > 0;
|
||||
} finally {
|
||||
snap.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe('SqliteMaintenance', () => {
|
||||
it('SQLMAINT-001: walCheckpoint sends PRAGMA wal_checkpoint(TRUNCATE)', async () => {
|
||||
const execute = spyOnExecute();
|
||||
try {
|
||||
await expect(maintenance.walCheckpoint()).resolves.toBeUndefined();
|
||||
expect(execute.first()).toBe('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
} finally {
|
||||
execute.restore();
|
||||
}
|
||||
});
|
||||
|
||||
describe('vacuumInto', () => {
|
||||
let scratchDir: string;
|
||||
|
||||
afterEach(() => {
|
||||
if (scratchDir) fs.rmSync(scratchDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("SQLMAINT-002: sends `VACUUM INTO '<path>'` and leaves a readable copy at the path", async () => {
|
||||
scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sqlite-maint-'));
|
||||
const target = path.join(scratchDir, 'snap.db');
|
||||
const execute = spyOnExecute();
|
||||
try {
|
||||
await maintenance.vacuumInto(target);
|
||||
expect(execute.first()).toBe(`VACUUM INTO '${target}'`);
|
||||
} finally {
|
||||
execute.restore();
|
||||
}
|
||||
expect(holdsTable(target, 'users')).toBe(true);
|
||||
});
|
||||
|
||||
it('SQLMAINT-003: doubles single quotes in the path', async () => {
|
||||
scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), "sqlite-maint-o'brien-"));
|
||||
const target = path.join(scratchDir, 'snap.db');
|
||||
const execute = spyOnExecute();
|
||||
try {
|
||||
await maintenance.vacuumInto(target);
|
||||
expect(execute.first()).toBe(`VACUUM INTO '${target.replaceAll("'", "''")}'`);
|
||||
} finally {
|
||||
execute.restore();
|
||||
}
|
||||
expect(holdsTable(target, 'users')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('SQLMAINT-004: both methods throw outside a request context (fail closed, as TrekRepository)', async () => {
|
||||
const { MikroORM } = await import('@mikro-orm/core');
|
||||
const fresh = await MikroORM.init({
|
||||
entities: [],
|
||||
driver: (await import('../../../../../src/db/orm-driver')).createBoundSqliteDriver(() => testDb),
|
||||
dbName: ':memory:',
|
||||
allowGlobalContext: false,
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
});
|
||||
try {
|
||||
const unwrapped = new SqliteMaintenance(fresh.em);
|
||||
await expect(unwrapped.walCheckpoint()).rejects.toThrow();
|
||||
await expect(unwrapped.vacuumInto(path.join(os.tmpdir(), 'never.db'))).rejects.toThrow();
|
||||
} finally {
|
||||
await fresh.close(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,11 +2,7 @@ import { MaintenanceRepository } from '../../../../src/db/repositories/Maintenan
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
@@ -22,61 +18,18 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
describe('MaintenanceRepository', () => {
|
||||
it('MAINTREPO-001: walCheckpoint renders PRAGMA wal_checkpoint(TRUNCATE) — pinned text, equivalent to the legacy raw call', async () => {
|
||||
// Rendered-SQL-equivalence: the exact text a direct statement on the
|
||||
// handle executes without throwing, string-for-string what the legacy
|
||||
// `db.exec('PRAGMA wal_checkpoint(TRUNCATE)')` issued.
|
||||
const RENDERED = 'PRAGMA wal_checkpoint(TRUNCATE)';
|
||||
// test-sql-allow: the pragma text itself is under test, run as the raw statement it renders to.
|
||||
expect(() => testDb.prepare(RENDERED).run()).not.toThrow();
|
||||
await expect(maintenance.walCheckpoint()).resolves.toBeUndefined();
|
||||
it('MAINTREPO-001: ping sends SELECT 1 and resolves while the database answers', async () => {
|
||||
const spy = vi.spyOn(t.em.getConnection(), 'execute');
|
||||
try {
|
||||
await expect(maintenance.ping()).resolves.toBeUndefined();
|
||||
// The first statement sent; the ORM may read its own metadata afterwards.
|
||||
expect(spy.mock.calls[0]?.[0]).toBe('SELECT 1');
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
describe('vacuumInto', () => {
|
||||
let scratchPath: string;
|
||||
|
||||
afterEach(() => {
|
||||
if (scratchPath && fs.existsSync(scratchPath)) fs.rmSync(scratchPath, { force: true });
|
||||
});
|
||||
|
||||
it("MAINTREPO-002: vacuumInto renders `VACUUM INTO '<path>'` — pinned text, produces a readable snapshot at the given path", async () => {
|
||||
scratchPath = path.join(os.tmpdir(), `maintrepo-vacuum-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
await maintenance.vacuumInto(scratchPath);
|
||||
expect(fs.existsSync(scratchPath)).toBe(true);
|
||||
|
||||
const snap = new Database(scratchPath, { readonly: true });
|
||||
try {
|
||||
// test-sql-allow: a snapshot file no ORM is bound to, read through sqlite_master.
|
||||
const row = snap.prepare('SELECT name FROM sqlite_master WHERE type = ? AND name = ?').get('table', 'users');
|
||||
expect(row).toBeTruthy();
|
||||
} finally {
|
||||
snap.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('MAINTREPO-003: single quotes in the path are escaped by doubling, matching the legacy `dbSnap.replaceAll("\'", "\'\'")` shape', async () => {
|
||||
const dirWithQuote = path.join(os.tmpdir(), `maintrepo-o'brien-${Date.now()}`);
|
||||
fs.mkdirSync(dirWithQuote, { recursive: true });
|
||||
scratchPath = path.join(dirWithQuote, 'snap.db');
|
||||
try {
|
||||
await maintenance.vacuumInto(scratchPath);
|
||||
expect(fs.existsSync(scratchPath)).toBe(true);
|
||||
|
||||
// Rendered-SQL-equivalence: the SAME escaped text, run directly
|
||||
// against another target path, succeeds identically.
|
||||
const directPath = path.join(dirWithQuote, 'snap-direct.db');
|
||||
const escaped = directPath.replaceAll("'", "''");
|
||||
// test-sql-allow: the VACUUM INTO text itself is under test, run as the raw statement it renders to.
|
||||
expect(() => testDb.prepare(`VACUUM INTO '${escaped}'`).run()).not.toThrow();
|
||||
expect(fs.existsSync(directPath)).toBe(true);
|
||||
fs.rmSync(directPath, { force: true });
|
||||
} finally {
|
||||
fs.rmSync(dirWithQuote, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('MAINTREPO-004: both methods throw outside a request context (fail-closed, matching TrekRepository)', async () => {
|
||||
it('MAINTREPO-004: ping throws outside a request context (fail-closed, matching TrekRepository)', async () => {
|
||||
const { MikroORM } = await import('@mikro-orm/core');
|
||||
const fresh = await MikroORM.init({
|
||||
entities: [],
|
||||
@@ -87,7 +40,7 @@ describe('MaintenanceRepository', () => {
|
||||
});
|
||||
try {
|
||||
const unwrapped = new MaintenanceRepository(fresh.em);
|
||||
await expect(unwrapped.walCheckpoint()).rejects.toThrow();
|
||||
await expect(unwrapped.ping()).rejects.toThrow();
|
||||
} finally {
|
||||
await fresh.close(false);
|
||||
}
|
||||
|
||||
@@ -640,7 +640,7 @@ describe('PlacesRepository.listForTrip (PL3) — filter fragments', () => {
|
||||
const inCat = createPlace(testDb, trip.id, { category_id: cat.id });
|
||||
const outCat = createPlace(testDb, trip.id);
|
||||
await deleteRows(t.orm, Categories, { id: { $ne: cat.id } });
|
||||
const rows = await places.listForTrip(String(trip.id), { category: String(cat.id) });
|
||||
const rows = await places.listForTrip(String(trip.id), { category: cat.id });
|
||||
expect(rows.map((r) => r.id)).toEqual([inCat.id]);
|
||||
void outCat;
|
||||
});
|
||||
@@ -652,7 +652,7 @@ describe('PlacesRepository.listForTrip (PL3) — filter fragments', () => {
|
||||
const tagged = createPlace(testDb, trip.id, { name: 'Tagged' });
|
||||
const untagged = createPlace(testDb, trip.id, { name: 'Untagged' });
|
||||
await tagPlace(t.orm, tagged.id, [tag.id]);
|
||||
const rows = await places.listForTrip(String(trip.id), { tag: String(tag.id) });
|
||||
const rows = await places.listForTrip(String(trip.id), { tag: tag.id });
|
||||
expect(rows.map((r) => r.id)).toEqual([tagged.id]);
|
||||
void untagged;
|
||||
});
|
||||
@@ -684,7 +684,7 @@ describe('PlacesRepository.listForTrip (PL3) — filter fragments', () => {
|
||||
await tagPlace(t.orm, other.id, [tag.id]);
|
||||
// `other` is left unassigned, so `assignment: 'assigned'` alone should exclude it.
|
||||
const rows = await places.listForTrip(String(trip.id), {
|
||||
searchPattern: '%Central Park%', category: String(cat.id), tag: String(tag.id), assignment: 'assigned',
|
||||
searchPattern: '%Central Park%', category: cat.id, tag: tag.id, assignment: 'assigned',
|
||||
});
|
||||
expect(rows.map((r) => r.id)).toEqual([winner.id]);
|
||||
});
|
||||
@@ -703,7 +703,7 @@ describe('PlacesRepository.listForTrip (PL3) — filter fragments', () => {
|
||||
describe('PlacesRepository.listForTrip (PL3) — toEqual(legacy) over all 32 filter combinations', () => {
|
||||
function legacyListForTrip(
|
||||
tripId: string,
|
||||
filters: { searchPattern?: string; category?: string; tag?: string; assignment?: 'all' | 'unassigned' | 'assigned' },
|
||||
filters: { searchPattern?: string; category?: number | string; tag?: number | string; assignment?: 'all' | 'unassigned' | 'assigned' },
|
||||
): unknown[] {
|
||||
let query = `
|
||||
SELECT DISTINCT p.*, t.place_id AS tour_place_id, c.name as category_name, c.color as category_color, c.icon as category_icon,
|
||||
@@ -767,8 +767,8 @@ describe('PlacesRepository.listForTrip (PL3) — toEqual(legacy) over all 32 fil
|
||||
createPlace(testDb, otherTrip.id, { name: 'Central Perk' });
|
||||
|
||||
const searchOptions: (string | undefined)[] = [undefined, '%Central%'];
|
||||
const categoryOptions: (string | undefined)[] = [undefined, String(cat.id)];
|
||||
const tagOptions: (string | undefined)[] = [undefined, String(tag.id)];
|
||||
const categoryOptions: (number | undefined)[] = [undefined, cat.id];
|
||||
const tagOptions: (number | undefined)[] = [undefined, tag.id];
|
||||
const assignmentOptions: (('all' | 'unassigned' | 'assigned') | undefined)[] = [undefined, 'all', 'assigned', 'unassigned'];
|
||||
|
||||
let combinations = 0;
|
||||
|
||||
@@ -2,14 +2,15 @@
|
||||
* ReservationDayPositionsRepository — parity test (Plan 3d Task 7 whole-plan
|
||||
* review, item 9/"missing parity tests": this repository had no standalone
|
||||
* test file). ONE seeded world, one `toEqual(<legacy raw>)` test for the
|
||||
* read method (RS19); RS31 (`upsertScoped`, a write) already has coverage
|
||||
* through `reservations.service.test.ts`'s `updatePositions` cases.
|
||||
* read method (RS19); RS31 (`upsertScoped`, a write) has coverage through
|
||||
* `reservations.service.test.ts`'s `updatePositions` cases and, for the
|
||||
* overwrite and the trip scoping its ON CONFLICT clause holds, below.
|
||||
*/
|
||||
import { ReservationDayPositions } from '../../../../src/db/entities/ReservationDayPositions.entity';
|
||||
import type { ReservationDayPositionsRepository } from '../../../../src/db/repositories/ReservationDayPositions.repository';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { createDay, createReservation, createTrip, createUser } from '../../../helpers/factories';
|
||||
import { insertRow } from '../../../helpers/factories/rows';
|
||||
import { findRows, insertRow } from '../../../helpers/factories/rows';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
@@ -86,3 +87,30 @@ describe('ReservationDayPositionsRepository — fully seeded world', () => {
|
||||
expect(await repo.listForReservation(999999)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ReservationDayPositionsRepository.upsertScoped', () => {
|
||||
it('RDP-UPSERT-001: a second write to the same reservation and day overwrites its position', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const reservation = createReservation(testDb, trip.id, { day_id: day.id });
|
||||
|
||||
await repo.upsertScoped(trip.id, reservation.id, day.id, 1.5);
|
||||
await repo.upsertScoped(trip.id, reservation.id, day.id, 4);
|
||||
|
||||
const rows = await findRows(t.orm, ReservationDayPositions, { reservation_id: reservation.id });
|
||||
expect(rows.map((r) => [r.day_id, r.position])).toEqual([[day.id, 4]]);
|
||||
});
|
||||
|
||||
it('RDP-UPSERT-002: a reservation of another trip writes no row', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id);
|
||||
const otherTrip = createTrip(testDb, user.id);
|
||||
const day = createDay(testDb, trip.id);
|
||||
const foreign = createReservation(testDb, otherTrip.id);
|
||||
|
||||
await repo.upsertScoped(trip.id, foreign.id, day.id, 2);
|
||||
|
||||
expect(await findRows(t.orm, ReservationDayPositions, { reservation_id: foreign.id })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user