fix(backup): a restore that migrates no longer breaks the request it runs in

Restoring a backup whose database was behind the running version migrated it inside the admin's HTTP request. A MikroORM migration's getEntityManager() pins the migration's transaction on the EntityManager of the context it runs in, which was the request's. Once the migrations committed, every later read on that request failed with "Transaction is already committed": the storage registry reload kept the pre-restore config (uploads, including the archive's own, went to the old backend), and the restore's audit row was lost.

Both engines now run their migrations in a request context of their own (runSchemaBootstrap on SQLite, bootstrapPostgresSchema on Postgres), so the transaction stays on a throwaway EntityManager, at boot and on restore alike. RESTORE-002 restores a file six migrations behind head inside a request and reads on through that request's EntityManager.

Closes #3264
This commit is contained in:
Maurice
2026-11-29 12:00:08 +01:00
parent f89ebf6882
commit 67049c1065
3 changed files with 54 additions and 7 deletions
@@ -1,4 +1,5 @@
import type { DbEngineSettings } from '../../../app-config/db-settings';
import { withRequestContext } from '../../../nest/database/request-context';
import { NO_SAFETY_NET } from '../../legacy-baseline';
import { finishSchemaBootstrap, type AnyOrm } from '../../orm';
import type { DatabaseEngine } from '../engine';
@@ -74,7 +75,12 @@ export class PostgresEngine implements DatabaseEngine {
/** `snapshot: false` (a restore, whose archive is the copy) migrates without a pg_dump first. */
async schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
const deps = this.bootstrapDeps(this.settings.url);
await bootstrapPostgresSchema(orm, options.snapshot ? deps : { ...deps, safetyNet: NO_SAFETY_NET });
// Migrated in a request context of its own, so the migrations' transaction
// never lands on a caller's EntityManager (a restore's request, #3264; see
// runSchemaBootstrap).
await withRequestContext(orm, () =>
bootstrapPostgresSchema(orm, options.snapshot ? deps : { ...deps, safetyNet: NO_SAFETY_NET }),
);
await finishSchemaBootstrap(orm);
}