mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 13:23:04 +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:
@@ -8,7 +8,7 @@
|
||||
* on another install. The run now goes through backupService.createBackup(),
|
||||
* which snapshots the DB with VACUUM INTO and bundles the key.
|
||||
*/
|
||||
import type { MaintenanceRepository } from '../../src/db/repositories/MaintenanceRepository';
|
||||
import type { SqliteMaintenance } from '../../src/db/engine/sqlite/sqlite-maintenance';
|
||||
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
|
||||
import { createBackup } from '../../src/nest/backup/backup.impl';
|
||||
import type { BackupService } from '../../src/nest/backup/backup.service';
|
||||
@@ -78,7 +78,7 @@ const liveDb = path.join(__dirname, '../../data', 'travel.db');
|
||||
/** The backup port BackupService injects: the real SQLite one over stubs. */
|
||||
const database = new SqliteDatabaseBackup(
|
||||
{ file: liveDb, close: vi.fn(), reopen: vi.fn() } as unknown as DatabaseLifecycle,
|
||||
maintenanceStub as unknown as MaintenanceRepository,
|
||||
maintenanceStub as unknown as SqliteMaintenance,
|
||||
);
|
||||
|
||||
// createBackup receives StorageService and the database port as parameters
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* cases assert is which file each step names.
|
||||
*
|
||||
* The port is the real `SqliteDatabaseBackup` over a lifecycle stand-in (the
|
||||
* file, close, reopen) and a MaintenanceRepository stand-in (checkpoint,
|
||||
* file, close, reopen) and a SqliteMaintenance stand-in (checkpoint,
|
||||
* VACUUM INTO). The file system is spied rather than written to, because the
|
||||
* baseline path is fixed at data/travel-baseline.db and a developer running a
|
||||
* demo instance has a real one sitting there.
|
||||
@@ -21,7 +21,7 @@
|
||||
* `withRequestContext` over a real (empty) test database: the reads find
|
||||
* nothing and the restore-writes are skipped.
|
||||
*/
|
||||
import type { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
|
||||
import type { SqliteMaintenance } from '../../../src/db/engine/sqlite/sqlite-maintenance';
|
||||
import { resetDemoUser, saveBaseline } from '../../../src/demo/demo-reset';
|
||||
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
|
||||
import { DatabaseConnectionLostError } from '../../../src/nest/database/database-backup.interface';
|
||||
@@ -65,7 +65,7 @@ describe('demo-reset DB path', () => {
|
||||
maintenance = { walCheckpoint: vi.fn(async () => {}), vacuumInto: vi.fn(async () => {}) };
|
||||
database = new SqliteDatabaseBackup(
|
||||
lifecycle as unknown as DatabaseLifecycle,
|
||||
maintenance as unknown as MaintenanceRepository,
|
||||
maintenance as unknown as SqliteMaintenance,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ declare const repo: { run(sql: string, params?: unknown[]): Promise<unknown>; ge
|
||||
// text slipping in under the exemption, a lower one means the pin (and at 0
|
||||
// the ignores entry) has to follow.
|
||||
const EXEMPT_SQL_STRINGS: Record<string, number> = {
|
||||
'src/db/repositories/MaintenanceRepository.ts': 4,
|
||||
'src/db/repositories/MaintenanceRepository.ts': 2,
|
||||
'src/db/seeders/AdminSeeder.ts': 2,
|
||||
'src/db/seeders/CategorySeeder.ts': 2,
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Unit tests for backupService.
|
||||
* Covers BACKUP-031 to BACKUP-060.
|
||||
*/
|
||||
import type { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
|
||||
import type { SqliteMaintenance } from '../../../src/db/engine/sqlite/sqlite-maintenance';
|
||||
import {
|
||||
formatSize,
|
||||
parseIntField,
|
||||
@@ -78,9 +78,9 @@ const dbMock = vi.hoisted(() => ({
|
||||
}));
|
||||
|
||||
// The database port's SQLite implementation is built for real below with this
|
||||
// stand-in for the MaintenanceRepository Nest injects into it: the WAL
|
||||
// stand-in for the SqliteMaintenance Nest injects into it: the WAL
|
||||
// checkpoint and the VACUUM INTO snapshot are what a backup and a restore ask
|
||||
// of it. The real statements are MaintenanceRepository.test.ts's coverage.
|
||||
// of it. The real statements are sqlite-maintenance.test.ts's coverage.
|
||||
const maintenanceRepoMock = vi.hoisted(() => ({
|
||||
walCheckpoint: vi.fn().mockResolvedValue(undefined),
|
||||
vacuumInto: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -121,7 +121,7 @@ const lifecycleStub = {
|
||||
function deps(storage: StorageService) {
|
||||
return {
|
||||
storage,
|
||||
database: new SqliteDatabaseBackup(lifecycleStub, maintenanceRepoMock as unknown as MaintenanceRepository),
|
||||
database: new SqliteDatabaseBackup(lifecycleStub, maintenanceRepoMock as unknown as SqliteMaintenance),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
* SqliteDatabaseBackup: the database backup port for a SQLite file.
|
||||
*
|
||||
* The snapshot and the swap run for real here, against a database file in a
|
||||
* temp directory: a VACUUM INTO through the real MaintenanceRepository, and the
|
||||
* temp directory: a VACUUM INTO through the real SqliteMaintenance, and the
|
||||
* copy, sidecar removal and rename of a restore. Only the connection lifecycle
|
||||
* is a stand-in, because closing and reopening the process's own connection is
|
||||
* DatabaseLifecycle's business (tests/unit/nest/database/).
|
||||
*/
|
||||
import { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
|
||||
import { SqliteMaintenance } from '../../../src/db/engine/sqlite/sqlite-maintenance';
|
||||
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
|
||||
import { DatabaseConnectionLostError } from '../../../src/nest/database/database-backup.interface';
|
||||
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
|
||||
@@ -40,7 +40,7 @@ function maintenanceStub() {
|
||||
function portWith(maintenance: { walCheckpoint: unknown; vacuumInto: unknown }): SqliteDatabaseBackup {
|
||||
return new SqliteDatabaseBackup(
|
||||
lifecycle as unknown as DatabaseLifecycle,
|
||||
maintenance as unknown as MaintenanceRepository,
|
||||
maintenance as unknown as SqliteMaintenance,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ describe('SqliteDatabaseBackup', () => {
|
||||
// test-sql-allow: the marker table is a bare fixture no entity maps; the write has to land in the WAL of this file.
|
||||
live.prepare('UPDATE marker SET label = ?').run('after');
|
||||
const target = path.join(dir, 'copy.db');
|
||||
const port = portWith(new MaintenanceRepository(orm.em));
|
||||
const port = portWith(new SqliteMaintenance(orm.em));
|
||||
|
||||
await withRequestContext(orm.orm, () => port.snapshot(target));
|
||||
|
||||
@@ -125,7 +125,7 @@ describe('SqliteDatabaseBackup', () => {
|
||||
|
||||
it('SQLBK-005: a VACUUM INTO that fails rejects and leaves nothing at the target', async () => {
|
||||
const target = path.join(dir, 'missing-dir', 'copy.db');
|
||||
const port = portWith(new MaintenanceRepository(orm.em));
|
||||
const port = portWith(new SqliteMaintenance(orm.em));
|
||||
|
||||
await expect(withRequestContext(orm.orm, () => port.snapshot(target))).rejects.toThrow();
|
||||
|
||||
|
||||
@@ -128,6 +128,8 @@ describe('dialect-lint.mjs', () => {
|
||||
it('DIALECT-006: PRAGMA is allowed in the src/db lifecycle files, not in a repository or a domain', () => {
|
||||
const pragma = "export const p = 'PRAGMA wal_checkpoint(TRUNCATE)';\n";
|
||||
expect(run(serverRoot({ 'src/db/durability.ts': pragma })).status).toBe(0);
|
||||
expect(run(serverRoot({ 'src/db/engine/sqlite/sqlite-maintenance.ts': pragma })).status).toBe(0);
|
||||
expect(run(serverRoot({ 'src/db/engine/postgres/maintenance.ts': pragma })).status).toBe(1);
|
||||
expect(run(serverRoot({ [REPO]: pragma })).status).toBe(1);
|
||||
expect(run(serverRoot({ 'src/nest/backup/probe.ts': pragma })).status).toBe(1);
|
||||
});
|
||||
|
||||
@@ -47,6 +47,7 @@ export class ThingsRepository {
|
||||
async record(r: Record<string, number>): Promise<void> {}
|
||||
async literals(n: bigint, flag: true): Promise<void> {}
|
||||
async destructured({ id, label }: { id: number; label: string }): Promise<void> {}
|
||||
async presence(write: { name?: readonly [present: boolean, value: string]; flag?: readonly [boolean, number] }): Promise<void> {}
|
||||
}
|
||||
export abstract class AbstractRepository {
|
||||
async skipped(): Promise<void> {}
|
||||
@@ -102,6 +103,7 @@ describe('pg-probe argument samples', () => {
|
||||
'literals',
|
||||
'nullable',
|
||||
'optionalCallback',
|
||||
'presence',
|
||||
'record',
|
||||
'rest',
|
||||
'tuple',
|
||||
@@ -145,6 +147,13 @@ describe('pg-probe argument samples', () => {
|
||||
expect(argsOf('collections')).toEqual([new Set([1]), new Map([['1', 1]])]);
|
||||
});
|
||||
|
||||
it('PGPROBE-037: a presence pair is present, so a patch built from it reaches its SQL', () => {
|
||||
// The repositories' partial updates take `[present: boolean, value]` pairs
|
||||
// and send nothing when no pair is present; a false flag would leave the
|
||||
// method unmeasured. Only the element labelled `present` turns true.
|
||||
expect(argsOf('presence')).toEqual([{ name: [true, 'probe'], flag: [false, 1] }]);
|
||||
});
|
||||
|
||||
it('PGPROBE-035: a required callback makes the method unprobeable, an optional one is left off', () => {
|
||||
expect(planOf('withCallback')).toMatchObject({ unprobeable: 'fn: a function parameter' });
|
||||
expect(argsOf('optionalCallback')).toEqual([1]);
|
||||
|
||||
@@ -130,11 +130,13 @@ describe('pg-probe baseline', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('PGPROBE-010: only syntax and feature errors count toward the ratchet, not data errors from the sample values', () => {
|
||||
for (const code of ['42601', '42883', '42804', '42P01', '42703', '0A000'])
|
||||
it('PGPROBE-010: syntax, feature and data errors count toward the ratchet; constraints and timeouts do not', () => {
|
||||
// A data exception (class 22) is a value of the wrong type reaching a
|
||||
// column: a string the SQLite comparison let through where Postgres
|
||||
// refuses it, so it counts once the sampler sends the declared types.
|
||||
for (const code of ['42601', '42883', '42804', '42P01', '42703', '0A000', '22P02', '22007', '22008'])
|
||||
expect(countsTowardRatchet(code)).toBe(true);
|
||||
for (const code of ['22P02', '22007', '22008', '23505', '57014', 'NOSQLSTATE'])
|
||||
expect(countsTowardRatchet(code)).toBe(false);
|
||||
for (const code of ['23505', '23514', '57014', 'NOSQLSTATE']) expect(countsTowardRatchet(code)).toBe(false);
|
||||
});
|
||||
|
||||
it('PGPROBE-008: the checked-in baseline parses and formats back to itself', () => {
|
||||
|
||||
@@ -47,7 +47,7 @@ const RESULTS: MethodResult[] = [
|
||||
{ key: 'F.thrower', statements: [], threw: 'no trip 1' },
|
||||
{
|
||||
key: 'G.sampled',
|
||||
statements: [refused('select $1::date', '22007', 'invalid input syntax for type date: "probe"'), ok('select 5')],
|
||||
statements: [refused('insert into t values ($1)', '23514', 'violates check constraint "t_check"'), ok('select 5')],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -84,26 +84,30 @@ describe('pg-probe report', () => {
|
||||
new Map([
|
||||
['42883', 1],
|
||||
['42601', 1],
|
||||
['22007', 1],
|
||||
['23514', 1],
|
||||
]),
|
||||
);
|
||||
expect(summary.failedStatements.map((f) => `${f.method} ${f.code} ${f.counted}`)).toEqual([
|
||||
'B.broken 42883 true',
|
||||
'B.broken 42601 true',
|
||||
'G.sampled 22007 false',
|
||||
'G.sampled 23514 false',
|
||||
]);
|
||||
});
|
||||
|
||||
it('PGPROBE-068: a data error from a sample value is reported but not held to the baseline', () => {
|
||||
it('PGPROBE-068: a data error is held to the baseline, a constraint over a sample value is only reported', () => {
|
||||
const summary = summarize([
|
||||
{
|
||||
key: 'G.sampled',
|
||||
statements: [refused('select $1::date', '22P02', 'bad'), refused('select x', '0A000', 'nope')],
|
||||
statements: [
|
||||
refused('select $1::date', '22P02', 'bad'),
|
||||
refused('select x', '0A000', 'nope'),
|
||||
refused('insert into t values ($1)', '23514', 'check'),
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(summary.failingByMethod.get('G.sampled')).toBe(1);
|
||||
expect(splitRefusals(summary).counted.map((f) => f.code)).toEqual(['0A000']);
|
||||
expect(splitRefusals(summary).reported.map((f) => f.code)).toEqual(['22P02']);
|
||||
expect(summary.failingByMethod.get('G.sampled')).toBe(2);
|
||||
expect(splitRefusals(summary).counted.map((f) => f.code)).toEqual(['22P02', '0A000']);
|
||||
expect(splitRefusals(summary).reported.map((f) => f.code)).toEqual(['23514']);
|
||||
});
|
||||
|
||||
it('PGPROBE-069: names every method whose SQL the probe did not see, and why', () => {
|
||||
@@ -187,9 +191,9 @@ describe('pg-probe report', () => {
|
||||
expect(text).toContain('FAIL [postgres] dateOf: expected 1, got 2');
|
||||
expect(text).toContain('collation "NOCASE" does not exist');
|
||||
expect(text).toContain(
|
||||
'Statements: 8 distinct, 3 refused by Postgres (2 as SQL, held to the baseline; 1 over a sample value',
|
||||
"Statements: 8 distinct, 3 refused by Postgres (2 as SQL or over a value's type, held to the baseline; 1 over a constraint",
|
||||
);
|
||||
expect(text).toContain(' 22007: 1 (not held)');
|
||||
expect(text).toContain(' 23514: 1 (not held)');
|
||||
expect(text).toContain(' F.thrower: threw before any statement: no trip 1');
|
||||
expect(text).toContain(
|
||||
'FAIL F.thrower threw before any statement: no trip 1, and the baseline does not list it as uncovered.',
|
||||
@@ -217,9 +221,9 @@ describe('pg-probe report', () => {
|
||||
expect(md).toContain("| postgres | a\\|b | got 'x' |");
|
||||
expect(md).toContain('| 42883 | 1 |');
|
||||
expect(md).toContain('| E.skipped | could not be called: fn: a function parameter |');
|
||||
expect(md).toContain('| Refused by Postgres as SQL (held) | 2 |');
|
||||
expect(md).toContain('| Refused over a sample value or the empty tables (reported only) | 1 |');
|
||||
expect(md).toContain('| G.sampled | 22007 | no | invalid input syntax for type date: "probe" |');
|
||||
expect(md).toContain("| Refused by Postgres as SQL or over a value's type (held) | 2 |");
|
||||
expect(md).toContain('| Refused over a constraint, a timeout or the empty tables (reported only) | 1 |');
|
||||
expect(md).toContain('| G.sampled | 23514 | no | violates check constraint "t_check" |');
|
||||
const ratchet = formatMarkdown(
|
||||
input({ verdict: { ...CLEAN, newlyUncovered: ['C.silent'], nowCovered: ['Z.gone'] } }),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user