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,12 +1,9 @@
import { MaintenanceRepository } from '../../../../src/db/repositories/MaintenanceRepository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { TableNotFoundException } from '@mikro-orm/core';
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 +19,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,9 +41,23 @@ 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);
}
});
it('MAINTREPO-005: deletePluginUserData skips an absent table and rethrows any other failure', async () => {
const spy = vi.spyOn(t.em.getConnection(), 'execute');
try {
// The first statement is the user_config delete, so the one-shot rejection lands on it.
spy.mockRejectedValueOnce(new TableNotFoundException(new Error('no such table: plugin_user_config')));
await expect(maintenance.deletePluginUserData(1)).resolves.toBeUndefined();
spy.mockRejectedValueOnce(new Error('connection lost'));
await expect(maintenance.deletePluginUserData(1)).rejects.toThrow('connection lost');
} finally {
spy.mockRestore();
}
});
});