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
fix(db): say what a schema difference means when the move to Postgres refuses it
Maurice85b773420c85
diff --git a/server/CLAUDE.md b/server/CLAUDE.mdindex c77319f03..82ba178a8 100644--- a/server/CLAUDE.md+++ b/server/CLAUDE.md@@ -81,8 +81,8 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator**: it bypasses that gate. Every tick first takes the job's row in `scheduler_leases` (`SchedulerLeasesRepository.acquire`, one conditional upsert that decides the race), renews it while it runs and keeps it for a short settle window afterwards, so two processes on one database never run the same tick; a job needs nothing of its own for this. Claims on individual rows (the reminder jobs' `claimReminder`) stay where they are: the lease decides who runs a tick, the claim what a tick may send.- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL runs in one store per engine behind the `PluginDataStore` port (`src/db/engine/plugin-data.ts`), each in its engine's folder: `SqlitePluginDataStore` (`src/db/engine/sqlite/plugin-data-store.ts`) and `PostgresPluginDataStore` (`src/db/engine/postgres/plugin-data-store.ts`). Both hold it to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed), and refuse a call that breaks the contract with the same words, taken from `PLUGIN_DATA_ERRORS` beside the caps in `src/db/engine/plugin-data-contract.ts` (`tests/unit/db/engine/plugin-data-contract.test.ts` runs every such call on both stores and fails on one answered differently; a closed store refuses every call). Transaction control is refused in every statement of every call on both engines with one text, `PLUGIN_DATA_ERRORS.txControl` (`refuseTransactionControl` on SQLite and in the SDK, the guard on Postgres). The SDK's dev harness and mock host throw the same texts and hold the same caps from a byte-identical copy of that file, held by a parity test in `plugin-sdk/`. Where that data lives is the engine's: `PLUGIN_DATA` (`src/nest/plugins/host/plugin-data.backend.ts`) binds the SQLite file per plugin, or on Postgres a schema per plugin (`trek_plugin_<id>`) whose SQL is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types, the functions that look an object up by name, a read of a system column (`xmin`, `ctid`, ...; the name may still be given with AS), the `xid` types where the word stands for the type, a collation or access method beyond the ones every server has, and every function of `pg_catalog` outside the allowlist `assets/postgres/plugin-functions.txt`, read by `src/db/engine/postgres/plugin-sql-functions.ts` (its catalog list, `assets/postgres/catalog-functions.txt`, is held to `pg_proc` by PGPLUG-021, and PGPLUG-022 fails on an allowed function with an overload that takes or returns a `reg*` type or `aclitem`, which would turn a text argument into a catalog lookup, and on one that makes a transaction id out of other values); the settings that decide how values print and parse (time zone UTC, the locales `C`, the date style, ...), pinned with `SET LOCAL` in every plugin transaction (`src/db/engine/postgres/plugin-session.ts`; PGPLUG-023 fails on a client setting of those categories a new Postgres adds until it is pinned or named as harmless); the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; one statement per round trip over the extended query protocol, which the store sends on a pool client it checks out for each call and runs its transaction on directly; `pg_temp` last on the plugin's and on every pool connection's `search_path`, `session-search-path.ts`, with the store dropping its client's temporary tables and other session state before the client goes back to the pool; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). Plugin SQL, an argument or a migration id holding NUL is refused on both engines with one error (`refuseNulSql`/`refuseNulValues` in the same contract file, so the SDK refuses it too), since Postgres text cannot hold it and a plugin must answer the same on either; a NUL the plugin's SQLite SQL builds itself (`char(0)`) is not caught, and the move to Postgres refuses such a row; the plugin's SQL is never translated, and `db.engine` tells the plugin which dialect to write. Backups and restores carry the plugin schemas the role owns (`pg-tools.ts`). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly. Where the data lives (`data/`, `uploads/`, backups, logs, key files, the DB file) is resolved in one place, `src/app-config/data-paths.ts`; a provider that reads one injects `DataPathsService`, plain helper modules shared with code outside the container call `resolveDataPaths()` (the list is in `src/app-config/README.md`), and nothing anchors a data path on its own `__dirname` or on `process.cwd()`.-- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot. It refuses the boot when `schema_version` is not exactly one row holding an integer ≥ 1, or is above the last mapped step (258); a value from 1 to 258 is read as dev's steps of those numbers, so a pre-ORM feature-branch database whose steps differ is not detected (the Tours branch is the one case it cuts back). Recorded `mikro_orm_migrations` names this build does not ship refuse it too (`refuseNewerDatabase`), whether a newer release or a development build wrote them. 4.3.x and earlier have no such check and start on a database 5.x migrated. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).-- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, a role granted EXECUTE on a server file function (`lo_export`, `pg_read_file`, ...), from PostgreSQL 15 on a role granted ALTER SYSTEM or SET on a superuser-only setting, and before PostgreSQL 16 a member of a role with CREATEROLE, its own included, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18, each in three slices) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character in TREK's own text too, unless `--drop-nul` lets it drop each one and list it in the summary), copies each plugin's `plugin.db` into its schema after checking, before anything is written, that every plugin value comes back from the Postgres store with its type and bytes, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows, built from the SQLite values rather than the converted ones, before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade, and keep one: TREK holds rate limits, pending codes, the permission cache and the WebSocket connections in memory, so it runs as a single replica on either engine.+- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot. It refuses the boot when `schema_version` is not exactly one row holding an integer ≥ 1, or is above the last mapped step (258); a value from 1 to 258 is read as dev's steps of those numbers, so a pre-ORM feature-branch database whose steps differ is not detected (the Tours branch is the one case it cuts back). Recorded `mikro_orm_migrations` names this build does not ship refuse it too (`refuseNewerDatabase`), whether a newer release or a development build wrote them. 4.3.x and earlier have no such check and start on a database 5.x migrated. Recording a step is not running it, so a column the positional runner never added stays missing: a step inserted below a version a build had already shipped (step 53, `users.mfa_backup_codes`) or a column added to `createTables()` with no step (`users.immich_access_token`) left such gaps. `Migration20200101046460_an_upgraded_install_gets_the_columns_its_history_skipped` adds, where missing, every column the schema held at step 258 that head still holds and `ADD COLUMN` can add (declared as head declares it; a missing table is skipped), and `tests/unit/db/legacy-column-repair.test.ts` derives that list again from the migrations, the head schema and the Postgres baseline. On every boot, `db/schema-gaps.ts` (from `finishSchemaBootstrap`, both engines) compares the entities with the live schema and warns, naming each table or column that is still missing; it never refuses the boot, not even when its own catalog query fails, and says nothing on a database the migrations built (PGGAP in `tests/postgres/schema-gaps.test.ts` holds that on Postgres). Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).+- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, a role granted EXECUTE on a server file function (`lo_export`, `pg_read_file`, ...), from PostgreSQL 15 on a role granted ALTER SYSTEM or SET on a superuser-only setting, and before PostgreSQL 16 a member of a role with CREATEROLE, its own included, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18, each in three slices) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, one whose tables differ from the Postgres schema (`SCHEMA_DIFFERENCE_REMEDY` says what that means and what to do; a column of TREK's own schema the move cannot copy is named apart as a bug in TREK, `SCHEMA_BUG_REMEDY`), orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character in TREK's own text too, unless `--drop-nul` lets it drop each one and list it in the summary), copies each plugin's `plugin.db` into its schema after checking, before anything is written, that every plugin value comes back from the Postgres store with its type and bytes, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows, built from the SQLite values rather than the converted ones, before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade, and keep one: TREK holds rate limits, pending codes, the permission cache and the WebSocket connections in memory, so it runs as a single replica on either engine.## Rules for new codediff --git a/server/src/db/engine/postgres/sqlite-move/catalog.ts b/server/src/db/engine/postgres/sqlite-move/catalog.tsindex 94cabf20b..129d3427c 100644--- a/server/src/db/engine/postgres/sqlite-move/catalog.ts+++ b/server/src/db/engine/postgres/sqlite-move/catalog.ts@@ -135,22 +135,26 @@ interface TrekCopyPlan {/** The tables in the order they are filled. */specs: TableSpec[];sequences: CopiedSequence[];- /** Why the two schemas do not match; the move refuses when there is any. */+ /** The tables and columns only one of the two has; the move refuses when there is any. */+ differences: string[];+ /** What this TREK's own schema holds that the move cannot copy (a bug in TREK); the move refuses on any. */problems: string[];}/*** Pairs every table of the target with the SQLite table of the same name and- * puts them in foreign key order. Anything the two do not share, or a column- * type the move has no rule for, is a problem: copying around it would lose- * data or guess.+ * puts them in foreign key order. Anything the two do not share is a+ * difference, and a column type the move has no rule for, or a deferred+ * reference that cannot be NULL meanwhile, is a problem of the schema itself:+ * copying around either would lose data or guess.*/export function planTrekTables(target: TargetSchema, source: SourceTables): TrekCopyPlan {+ const differences: string[] = [];const problems: string[] = [];const tables = target.tables.filter((table) => table.name !== HISTORY_TABLE);const names = new Set(tables.map((table) => table.name));for (const name of source.keys()) {- if (name !== HISTORY_TABLE && !names.has(name)) problems.push(`the SQLite table ${name} has no Postgres table`);+ if (name !== HISTORY_TABLE && !names.has(name)) differences.push(`the SQLite table ${name} has no Postgres table`);}const plan = planCopyOrder(tables.map((table) => table.name),@@ -163,18 +167,18 @@ export function planTrekTables(target: TargetSchema, source: SourceTables): Trekconst sourceColumns = source.get(name);if (!table) continue;if (!sourceColumns) {- problems.push(`the Postgres table ${name} has no SQLite table`);+ differences.push(`the Postgres table ${name} has no SQLite table`);continue;}for (const column of sourceColumns) {if (!table.columns.some((candidate) => candidate.name === column)) {- problems.push(`the SQLite column ${name}.${column} has no Postgres column`);+ differences.push(`the SQLite column ${name}.${column} has no Postgres column`);}}const columns = table.columns.flatMap((column) => {const kind = columnKind(column.dataType);if (!sourceColumns.includes(column.name))- problems.push(`the Postgres column ${name}.${column.name} has no SQLite column`);+ differences.push(`the Postgres column ${name}.${column.name} has no SQLite column`);else if (kind === null)problems.push(`the Postgres column ${name}.${column.name} has the type ${column.dataType}, which the move does not know`,@@ -202,5 +206,5 @@ export function planTrekTables(target: TargetSchema, source: SourceTables): Trekconst sequences = target.sequences.filter((entry) => names.has(entry.table)).map((entry) => ({ ...entry, target: quoteIdentifier(entry.table) }));- return { specs, sequences, problems };+ return { specs, sequences, differences, problems };}diff --git a/server/src/db/engine/postgres/sqlite-move/move.ts b/server/src/db/engine/postgres/sqlite-move/move.tsindex b49faadbd..f642c46e9 100644--- a/server/src/db/engine/postgres/sqlite-move/move.ts+++ b/server/src/db/engine/postgres/sqlite-move/move.ts@@ -109,6 +109,49 @@ const PLUGIN_DATA_REMEDY ="that type. Change those values in the plugin's plugin.db (through the plugin, or with the sqlite3 tool while " +'TREK is stopped), or uninstall the plugin and remove its data directory, then run the move again.';+/**+ * What a difference between the two schemas means and what the operator can+ * do, for a file already at this build's migration level (the level is+ * checked first, so the start that brought it there ran every migration,+ * including the one that adds the columns an old upgrade skipped).+ */+export const SCHEMA_DIFFERENCE_REMEDY =+ "The SQLite file is at this TREK version's migration level, so its tables should match this schema exactly. " ++ 'A table or column only Postgres has is one the SQLite install never got: an install upgraded before 5.0 can ' ++ 'have skipped some, and the start that brought the file to this level added every column it could; TREK names ' ++ 'the rest in its start log ("[DB] The database lacks ..."). A table or column only the SQLite file has was ' ++ "added outside TREK's migrations, by hand or by a development build. TREK cannot correct either on its own: " ++ 'keep running TREK on SQLite, which still works, and please report this message, with that line of the start ' ++ 'log if there is one.';++/** What a column of this TREK's own Postgres schema that the move cannot copy means: the file is not at fault. */+export const SCHEMA_BUG_REMEDY =+ "These come from this TREK version's own Postgres schema, not from the SQLite file, so this is a bug in TREK. " ++ 'Keep running TREK on SQLite, which still works, and please report this message.';++/**+ * The refusal for a SQLite file whose tables do not pair with the schema, or+ * null when they do: the tables and columns only one side has, with what+ * that means, and apart from them what the schema itself holds that the move+ * cannot copy, which is TREK's own fault.+ */+export function schemaRefusal(differences: readonly string[], problems: readonly string[]): string | null {+ const parts: string[] = [];+ if (differences.length > 0) {+ parts.push(+ `The SQLite file and this TREK's Postgres schema differ; nothing was written:\n` ++ `${listLines(differences, differences.length)}\n${SCHEMA_DIFFERENCE_REMEDY}`,+ );+ }+ if (problems.length > 0) {+ parts.push(+ `This TREK's Postgres schema holds what the move cannot copy; nothing was written:\n` ++ `${listLines(problems, problems.length)}\n${SCHEMA_BUG_REMEDY}`,+ );+ }+ return parts.length > 0 ? parts.join('\n') : null;+}+/*** Why the SQLite file is not at this build's migration level, or null when it* is: it must have recorded exactly the migrations this build ships.@@ -211,11 +254,8 @@ async function copyAll(source.tables().map((table) => [table, source.columns(table).map((column) => column.name)]),);const plan = planTrekTables(await readTargetSchema(trx), sourceTables);- if (plan.problems.length > 0) {- throw new MoveRefusal(- `The SQLite file and this TREK's Postgres schema differ:\n${listLines(plan.problems, plan.problems.length)}`,- );- }+ const refusal = schemaRefusal(plan.differences, plan.problems);+ if (refusal) throw new MoveRefusal(refusal);// The bootstrap's own rows (default settings, addons, providers) give way to the file's.await run(trx, `truncate table ${plan.specs.map((spec) => spec.target).join(', ')}`);diff --git a/server/tests/unit/db/engine/postgres/sqlite-move/move.test.ts b/server/tests/unit/db/engine/postgres/sqlite-move/move.test.tsindex d74055e77..40ff0d042 100644--- a/server/tests/unit/db/engine/postgres/sqlite-move/move.test.ts+++ b/server/tests/unit/db/engine/postgres/sqlite-move/move.test.ts@@ -1,5 +1,5 @@/**- * MOVE-001..032: the move of a SQLite install into Postgres+ * MOVE-001..037: the move of a SQLite install into Postgres* (src/db/engine/postgres/sqlite-move/), over real SQLite files and a* stand-in for Postgres that keeps what it is sent (tests/helpers/fake-postgres-move.ts):* the refusals before anything is written, the copy in foreign key order with@@ -26,6 +26,9 @@ import {migrationLevelProblem,moveSqliteToPostgres,renderSummary,+ SCHEMA_BUG_REMEDY,+ SCHEMA_DIFFERENCE_REMEDY,+ schemaRefusal,type MoveOptions,type MoveSummary,} from '../../../../../../src/db/engine/postgres/sqlite-move/move';@@ -248,6 +251,44 @@ describe('moveSqliteToPostgres', () => {);});+ it('MOVE-036: a SQLite file whose tables differ from the schema is refused with what that means and what to do', async () => {+ sqlite(+ path.join(dir, 'travel.db'),+ 'alter table trips drop column score; alter table users add column nickname text;',+ );+ const failure = moveSqliteToPostgres(options());+ await expect(failure).rejects.toBeInstanceOf(MoveRefusal);+ await expect(failure).rejects.toThrow(+ "The SQLite file and this TREK's Postgres schema differ; nothing was written:\n" ++ ' - the SQLite column users.nickname has no Postgres column\n' ++ ' - the Postgres column trips.score has no SQLite column\n' ++ SCHEMA_DIFFERENCE_REMEDY,+ );+ expect(SCHEMA_DIFFERENCE_REMEDY).toContain('[DB] The database lacks');+ expect(SCHEMA_DIFFERENCE_REMEDY).toContain('keep running TREK on SQLite');+ expect(pg.statements.some((sql) => sql.startsWith('insert into'))).toBe(false);+ expect(pg.statements.at(-1)).toBe(CLEAR_SCHEMA_SQL);+ });++ it('MOVE-037: what the schema itself cannot copy is named apart, as a bug in TREK, not as the file lacking it', () => {+ const typeProblem = 'the Postgres column trips.when has the type interval, which the move does not know';+ expect(schemaRefusal([], [])).toBeNull();+ expect(schemaRefusal([], [typeProblem])).toBe(+ "This TREK's Postgres schema holds what the move cannot copy; nothing was written:\n" ++ ` - ${typeProblem}\n` ++ SCHEMA_BUG_REMEDY,+ );+ expect(schemaRefusal(['the Postgres column trips.score has no SQLite column'], [typeProblem])).toBe(+ "The SQLite file and this TREK's Postgres schema differ; nothing was written:\n" ++ ' - the Postgres column trips.score has no SQLite column\n' ++ `${SCHEMA_DIFFERENCE_REMEDY}\n` ++ "This TREK's Postgres schema holds what the move cannot copy; nothing was written:\n" ++ ` - ${typeProblem}\n` ++ SCHEMA_BUG_REMEDY,+ );+ expect(SCHEMA_BUG_REMEDY).not.toContain('[DB] The database lacks');+ });+it('MOVE-011: a plugin database goes into its schema with its migration record, ids and indexes', async () => {const pluginDir = path.join(dir, 'plugins-data', 'move-notes');fs.mkdirSync(pluginDir, { recursive: true });diff --git a/server/tests/unit/db/engine/postgres/sqlite-move/order.test.ts b/server/tests/unit/db/engine/postgres/sqlite-move/order.test.tsindex c063b736d..4b9e2ce3b 100644--- a/server/tests/unit/db/engine/postgres/sqlite-move/order.test.ts+++ b/server/tests/unit/db/engine/postgres/sqlite-move/order.test.ts@@ -101,6 +101,7 @@ describe('planTrekTables', () => {['users', ['id', 'avatar']],]),);+ expect(plan.differences).toEqual([]);expect(plan.problems).toEqual([]);expect(plan.specs.map((spec) => spec.target)).toEqual(['"messages"', '"users"']);expect(plan.specs[0]).toMatchObject({@@ -145,13 +146,16 @@ describe('planTrekTables', () => {['leftover', ['id']],]),);- expect(plan.problems).toEqual([+ expect(plan.differences).toEqual(['the SQLite table leftover has no Postgres table','the Postgres table extra has no SQLite table','the SQLite column messages.legacy has no Postgres column',+ 'the Postgres column users.avatar has no SQLite column',+ ]);+ // What the schema itself holds that the move cannot copy is kept apart from what the file lacks.+ expect(plan.problems).toEqual(['the Postgres column messages.sent_at has the type timestamp with time zone, which the move does not know','messages.reply_to refers back to a table filled later and cannot be NULL meanwhile',- 'the Postgres column users.avatar has no SQLite column',]);});});