The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
test(server): read the db, demo and helper specs through the ORM
Mauriced8052c49b469
diff --git a/server/tests/unit/db/durability.test.ts b/server/tests/unit/db/durability.test.tsindex 4adb06018..03dde7c15 100644--- a/server/tests/unit/db/durability.test.ts+++ b/server/tests/unit/db/durability.test.ts@@ -220,6 +220,7 @@ describe('standalone scripts honour the same configuration', () => {expect(readModes(dbPath)).toEqual({ journalMode: 'DELETE', synchronous: 2 });const db = new Database(dbPath);+ // test-sql-allow: the file reset-admin.js just rewrote has no ORM bound to it; it is read as the script left it.const admin = db.prepare('SELECT role FROM users WHERE email = ?').get('[email protected]') as| { role: string }| undefined;@@ -230,6 +231,7 @@ describe('standalone scripts honour the same configuration', () => {it('reset-admin.js finds the account whatever the case, and ends its sessions', () => {seedWalDb();const seed = new Database(dbPath);+ // test-sql-allow: the database file reset-admin.js works on has no ORM bound to it.seed.prepare("INSERT INTO users (username, email, password_hash, role, password_version) VALUES ('boss', '[email protected]', 'x', 'user', 3)").run();seed.close();@@ -240,6 +242,7 @@ describe('standalone scripts honour the same configuration', () => {});const db = new Database(dbPath);+ // test-sql-allow: the file reset-admin.js just rewrote has no ORM bound to it; it is read as the script left it.const rows = db.prepare('SELECT email, role, password_version, must_change_password FROM users').all();db.close();expect(rows).toEqual([{ email: '[email protected]', role: 'admin', password_version: 4, must_change_password: 1 }]);diff --git a/server/tests/unit/db/transaction-yield.test.ts b/server/tests/unit/db/transaction-yield.test.tsindex 22777857d..1075920e8 100644--- a/server/tests/unit/db/transaction-yield.test.ts+++ b/server/tests/unit/db/transaction-yield.test.ts@@ -4,7 +4,7 @@* bodies await DB work only." The server holds ONE better-sqlite3 connection, shared* by MikroORM's Kysely-backed driver (`orm-driver.ts`'s `BoundSqliteDriver`) and by* any code holding the raw `better-sqlite3` handle directly (Plan 4 Task 4 deleted- * `DatabaseService`, the class that used to wrap `db.prepare(...)` this way — the+ * `DatabaseService`, the class that used to wrap `db.prepare` statements this way — the* hazard below is unchanged, since `MaintenanceRepository`/`DemoRepository`'s own* `connection.execute()` calls and the still-exported `db` Proxy in* `db/database.ts` are the same kind of direct, non-Kysely-queued access). This@@ -20,7 +20,7 @@* Kysely's own `ConnectionMutex` for SQLite serialises every statement onto* the one connection, so there is no interleaving: the queued statement's* result only becomes observable after the holder's transaction settles.- * B. A raw `better-sqlite3` statement (`db.prepare(...).get/run(...)`, the same+ * B. A raw `better-sqlite3` statement (`db.prepare` then `.get`/`.run`, the same* shape `DatabaseService` used to wrap) issued while that same transaction is* open does NOT queue — it shares the connection directly, with no mutex of* its own, so it runs INSIDE the open transaction: a "dirty read" of the@@ -44,6 +44,7 @@ import { Trips } from '../../../src/db/entities/Trips.entity';import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';import { UnitOfWork } from '../../../src/nest/database/unit-of-work';import { withRequestContext } from '../../../src/nest/database/request-context';+import { findRow } from '../../helpers/factories/rows';const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));@@ -139,13 +140,15 @@ describe('transaction yield (rule 24)', () => {// uncommitted write, not the cross-request hazard rule 24 names). It// issues a raw `better-sqlite3` READ and WRITE directly against the// shared handle (the same shape `DatabaseService.get`/`.run` used to- // wrap — `this.conn.prepare(sql).get/run(...)`, bypassing MikroORM/+ // wrap — `this.conn.prepare` then `.get`/`.run`, bypassing MikroORM/// Kysely entirely). Neither is behind Kysely's `ConnectionMutex` (probe// A), so both share the one better-sqlite3 connection directly and run// INSIDE the holder's still-open, uncommitted transaction.await withRequestContext(t.orm, async () => {+ // test-sql-allow: a raw read on the shared handle, outside Kysely's mutex, is the hazard this probe measures.const row = testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(trip.id) as { end_date: string | null } | undefined;dirtyRead = row?.end_date;+ // test-sql-allow: a raw write on the shared handle, outside Kysely's mutex, is the hazard this probe measures.testDb.prepare('UPDATE trips SET title = ? WHERE id = ?').run('DIRTY-WRITE-MARKER', trip.id);});@@ -162,7 +165,7 @@ describe('transaction yield (rule 24)', () => {// production code: a raw statement issued mid-transaction by ANOTHER// request would otherwise report success on a write this rollback just// undid.- const after = testDb.prepare('SELECT end_date, title FROM trips WHERE id = ?').get(trip.id) as { end_date: string | null; title: string };+ const after = (await findRow(t, Trips, { id: trip.id }))!;expect(after.end_date).toBe('2026-01-01');expect(after.title).toBe('Original Title');});@@ -190,8 +193,8 @@ describe('transaction yield (rule 24)', () => {await expect(Promise.all([first, second])).resolves.toBeDefined();- const rowA = testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(tripA.id) as { end_date: string | null };- const rowB = testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(tripB.id) as { end_date: string | null };+ const rowA = (await findRow(t, Trips, { id: tripA.id }))!;+ const rowB = (await findRow(t, Trips, { id: tripB.id }))!;expect(rowA.end_date).toBe('2099-01-01');expect(rowB.end_date).toBe('2099-02-01');});diff --git a/server/tests/unit/demo/demo-seed.test.ts b/server/tests/unit/demo/demo-seed.test.tsindex c82d72825..a3ea076cf 100644--- a/server/tests/unit/demo/demo-seed.test.ts+++ b/server/tests/unit/demo/demo-seed.test.ts@@ -31,6 +31,21 @@ vi.mock('../../../src/demo/demo-reset', async (importOriginal) => {import { seedDemoData } from '../../../src/demo/demo-seed';import { takeExampleTripsSeeded } from '../../../src/demo/demo-reset';+import type { EntityClass } from '@mikro-orm/core';+import { countRows, findRows } from '../../helpers/factories/rows';+import { readAppSetting } from '../../helpers/factories/settings';+import { readUser } from '../../helpers/factories/users';+import { AppSettings } from '../../../src/db/entities/AppSettings.entity';+import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';+import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';+import { DayNotes } from '../../../src/db/entities/DayNotes.entity';+import { Days } from '../../../src/db/entities/Days.entity';+import { PackingItems } from '../../../src/db/entities/PackingItems.entity';+import { Places } from '../../../src/db/entities/Places.entity';+import { Reservations } from '../../../src/db/entities/Reservations.entity';+import { TripMembers } from '../../../src/db/entities/TripMembers.entity';+import { Trips } from '../../../src/db/entities/Trips.entity';+import { Users } from '../../../src/db/entities/Users.entity';describe('demo seeding', () => {let db: Database.Database;@@ -91,32 +106,37 @@ describe('demo seeding', () => {// 10+6+8=24 packing items, 6+4+5=15 budget items, 2+1+3=6// reservations, 4+2+3=9 day notes, 3 trip_members rows (one per trip,// demo joined as a member alongside the admin owner).- const count = (table: string): number => (db.prepare(`SELECT COUNT(*) as n FROM ${table}`).get() as { n: number }).n;- expect(count('users')).toBe(2); // admin + demo- expect(count('trips')).toBe(3);- expect(count('days')).toBe(16);- expect(count('places')).toBe(32);- expect(count('day_assignments')).toBe(13 + 9 + 11); // per-day assignment counts, trip 1/2/3- expect(count('packing_items')).toBe(10 + 6 + 8);- expect(count('budget_items')).toBe(6 + 4 + 5);- expect(count('reservations')).toBe(2 + 1 + 3);- expect(count('day_notes')).toBe(4 + 2 + 3);- expect(count('trip_members')).toBe(3);- expect(count('app_settings')).toBeGreaterThanOrEqual(1);-- const allowRegistration = db.prepare("SELECT value FROM app_settings WHERE key = 'allow_registration'").get() as { value: string } | undefined;- expect(allowRegistration?.value).toBe('false');-- const admin = db.prepare('SELECT username, email, role FROM users WHERE id = ?').get(adminId) as { username: string; email: string; role: string };+ const orm = await createTestOrm(db);+ const tables = {+ users: Users, trips: Trips, days: Days, places: Places, day_assignments: DayAssignments, packing_items: PackingItems,+ budget_items: BudgetItems, reservations: Reservations, day_notes: DayNotes, trip_members: TripMembers, app_settings: AppSettings,+ } as const;+ const count = (table: keyof typeof tables): Promise<number> => countRows(orm, tables[table] as EntityClass<object>);+ expect(await count('users')).toBe(2); // admin + demo+ expect(await count('trips')).toBe(3);+ expect(await count('days')).toBe(16);+ expect(await count('places')).toBe(32);+ expect(await count('day_assignments')).toBe(13 + 9 + 11); // per-day assignment counts, trip 1/2/3+ expect(await count('packing_items')).toBe(10 + 6 + 8);+ expect(await count('budget_items')).toBe(6 + 4 + 5);+ expect(await count('reservations')).toBe(2 + 1 + 3);+ expect(await count('day_notes')).toBe(4 + 2 + 3);+ expect(await count('trip_members')).toBe(3);+ expect(await count('app_settings')).toBeGreaterThanOrEqual(1);++ expect(await readAppSetting(orm, 'allow_registration')).toBe('false');++ const admin = await readUser(orm, adminId);expect(admin.role).toBe('admin');- const demoUser = db.prepare('SELECT username, email, role FROM users WHERE id = ?').get(demoId) as { username: string; email: string; role: string };- expect(demoUser).toEqual({ username: 'demo', email: '[email protected]', role: 'user' });+ const demoUser = await readUser(orm, demoId);+ expect({ username: demoUser.username, email: demoUser.email, role: demoUser.role }).toEqual({ username: 'demo', email: '[email protected]', role: 'user' });- const tripTitles = (db.prepare('SELECT title FROM trips ORDER BY id').all() as { title: string }[]).map((r) => r.title);+ const tripTitles = (await findRows(orm, Trips, {}, { id: 'asc' })).map((r) => r.title);expect(tripTitles).toEqual(['Tokyo & Kyoto', 'Barcelona Long Weekend', 'New York City']);// reservation_time carries the full date (#1934), never a bare clock time.- const reservationTimes = (db.prepare('SELECT reservation_time FROM reservations ORDER BY id').all() as { reservation_time: string }[]).map((r) => r.reservation_time);+ const reservationTimes = (await findRows(orm, Reservations, {}, { id: 'asc' })).map((r) => r.reservation_time);+ await orm.close();for (const t of reservationTimes) expect(t).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/);});diff --git a/server/tests/unit/helpers/test-uow.test.ts b/server/tests/unit/helpers/test-uow.test.tsindex 1402e51b9..46db6cfe2 100644--- a/server/tests/unit/helpers/test-uow.test.ts+++ b/server/tests/unit/helpers/test-uow.test.ts@@ -1,7 +1,9 @@import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';import { createSnapshotTestDb } from '../../helpers/db-mock';import { resetTestDb } from '../../helpers/test-db';-import { createTestUnitOfWork } from '../../helpers/test-uow';+import { createTestUnitOfWork, sharedTestOrm } from '../../helpers/test-uow';+import { countRows } from '../../helpers/factories/rows';+import { Users } from '../../../src/db/entities/Users.entity';import { createUser } from '../../helpers/factories';import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';@@ -14,7 +16,7 @@ beforeAll(async () => {beforeEach(() => resetTestDb(testDb));afterAll(() => testDb.close());-const countUsers = () => (testDb.prepare('SELECT COUNT(*) AS n FROM users').get() as { n: number }).n;+const countUsers = async () => countRows(await sharedTestOrm(testDb), Users);describe('createTestUnitOfWork', () => {it('TUOW-001: raw better-sqlite3 statements inside transactional() commit together', async () => {@@ -22,7 +24,7 @@ describe('createTestUnitOfWork', () => {createUser(testDb);createUser(testDb);});- expect(countUsers()).toBe(2);+ expect(await countUsers()).toBe(2);});it('TUOW-002: a throw rolls raw statements back', async () => {@@ -32,7 +34,7 @@ describe('createTestUnitOfWork', () => {throw new Error('boom');}),).rejects.toThrow('boom');- expect(countUsers()).toBe(0);+ expect(await countUsers()).toBe(0);});it('TUOW-003: the helper is memoised per handle', async () => {