From 771dab7c35d4b02a1d0089b219651646c7489089 Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 18 Nov 2026 15:22:36 +0100 Subject: [PATCH] feat(db): name the tables and columns the database lacks on every start After the migrations, both engines compare the declared entities with the live schema in one catalog statement and log a warning naming each table or column that is missing, what fails because of it, and that it should be reported. It never refuses a start, not even when the check itself fails, and says nothing on a database the migrations built; a Postgres lane suite holds that on a real server. --- server/src/db/dialect/catalog.ts | 16 +++ server/src/db/orm.ts | 6 +- server/src/db/schema-gaps.ts | 101 +++++++++++++++++++ server/tests/postgres/schema-gaps.test.ts | 47 +++++++++ server/tests/unit/db/dialect/catalog.test.ts | 12 ++- server/tests/unit/db/schema-gaps.test.ts | 93 +++++++++++++++++ 6 files changed, 273 insertions(+), 2 deletions(-) create mode 100644 server/src/db/schema-gaps.ts create mode 100644 server/tests/postgres/schema-gaps.test.ts create mode 100644 server/tests/unit/db/schema-gaps.test.ts diff --git a/server/src/db/dialect/catalog.ts b/server/src/db/dialect/catalog.ts index 79964b936..7657daa2d 100644 --- a/server/src/db/dialect/catalog.ts +++ b/server/src/db/dialect/catalog.ts @@ -35,3 +35,19 @@ export function tableExistsSql(platform: Platform): string { */ export const CURRENT_SCHEMA_TABLES_SQL = 'select table_name from information_schema.tables where table_schema = current_schema() order by table_name'; + +/** + * Every column of every table, one `table_name` and `name` per row: the + * whole schema in one statement, for the boot's check that each column the + * entities map exists (`db/schema-gaps.ts`). Postgres reads the current + * schema only, as above. + */ +export function tableColumnsSql(platform: Platform): string { + if (isSqlite(platform)) { + return "select m.name as table_name, p.name as name from sqlite_master m join pragma_table_info(m.name) p where m.type = 'table'"; + } + if (isPostgres(platform)) { + return 'select table_name, column_name as name from information_schema.columns where table_schema = current_schema()'; + } + return unsupported(platform); +} diff --git a/server/src/db/orm.ts b/server/src/db/orm.ts index efb0fa622..cc21a6e7f 100644 --- a/server/src/db/orm.ts +++ b/server/src/db/orm.ts @@ -3,6 +3,7 @@ import { runDemoSeed } from './database'; import { ensureEmailCaseIndex } from './email-case-index'; import { migrateToHead, NO_SAFETY_NET } from './legacy-baseline'; import { preMigrateSnapshot } from './pre-migrate-snapshot'; +import { warnAboutSchemaGaps } from './schema-gaps'; import type { AnyEntity, EntityClass, EntityManager, EntitySchema, IDatabaseDriver, MikroORM } from '@mikro-orm/core'; import type { Migrator } from '@mikro-orm/migrations'; @@ -51,11 +52,14 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot }: { snapshot: /** * What every engine does once its schema is at head: the deferred index, the - * seeders, the demo seed. Idempotent, like the migration step before it. + * check for tables and columns the history left out, the seeders, the demo + * seed. Idempotent, like the migration step before it. */ export async function finishSchemaBootstrap(orm: AnyOrm): Promise { // The one index a migration may have had to defer (see email-case-index.ts). await ensureEmailCaseIndex(orm.em.getConnection()); + // Names what the entities map and the database lacks (see schema-gaps.ts). + await warnAboutSchemaGaps(orm); const defaultSeeder = orm.config.get('seeder').defaultSeeder; if (defaultSeeder) await orm.seeder.seedString(defaultSeeder); diff --git a/server/src/db/schema-gaps.ts b/server/src/db/schema-gaps.ts new file mode 100644 index 000000000..a0aa76a24 --- /dev/null +++ b/server/src/db/schema-gaps.ts @@ -0,0 +1,101 @@ +import { tableColumnsSql } from './dialect/catalog'; +import { ALL_ENTITIES } from './entities'; +import type { AnyOrm } from './orm'; +import { ReferenceKind, type EntityProperty } from '@mikro-orm/core'; +import { Logger } from '@nestjs/common'; + +/** + * What the entities map that the database lacks, named on every boot. + * + * The migrations are the only schema source, and on a healthy database the + * entities describe exactly what they built (`entity-schema-parity.test.ts`, + * PARITY-PG). An install the retired positional runner upgraded can still + * lack a column its `schema_version` claims, because the legacy baseline + * records those steps without running them: the migration that adds every + * such column it can (`Migration20200101046460_...`) closes the known gaps, + * and this names whatever is left, so it surfaces at the start instead of as + * a failed request in one feature, or as a refused move to Postgres. + * + * It warns and does not refuse the start, not even when the check itself + * fails: everything else keeps working, and no setting or command of the + * operator's adds a column. + */ + +const logger = new Logger('DB'); + +/** How many missing tables and columns the warning names before it counts the rest. */ +const MAX_NAMED = 20; + +interface ColumnRow { + table_name: string; + name: string; +} + +/** Whether `prop` is stored in columns of its own entity's table. */ +function ownsColumns(prop: EntityProperty): boolean { + if (prop.persist === false) return false; + if (prop.kind === ReferenceKind.ONE_TO_MANY || prop.kind === ReferenceKind.MANY_TO_MANY) return false; + if (prop.kind === ReferenceKind.EMBEDDED) return false; + return !(prop.kind === ReferenceKind.ONE_TO_ONE && !prop.owner); +} + +/** + * Every table and column an entity maps that the database does not have, as + * `the table ` or `.`. Empty on a + * database the migrations built. + */ +export async function schemaGaps(orm: AnyOrm): Promise { + const connection = orm.em.getConnection(); + const rows: ColumnRow[] = await connection.execute(tableColumnsSql(connection.getPlatform())); + const present = new Map>(); + for (const row of rows) { + const columns = present.get(row.table_name); + if (columns) columns.add(row.name); + else present.set(row.table_name, new Set([row.name])); + } + + // The declared entities only: MikroORM also registers a pivot of its own for + // a bare many-to-many, which its owning relation already covers. + const declared = new Set(ALL_ENTITIES.map((schema) => schema.meta.className)); + const gaps: string[] = []; + for (const meta of orm.getMetadata().getAll().values()) { + if (!declared.has(meta.className) || meta.virtual || meta.embeddable || meta.abstract) continue; + const columns = present.get(meta.tableName); + if (!columns) { + gaps.push(`the table ${meta.tableName}`); + continue; + } + for (const prop of meta.props) { + if (!ownsColumns(prop)) continue; + for (const field of prop.fieldNames) if (!columns.has(field)) gaps.push(`${meta.tableName}.${field}`); + } + } + return gaps; +} + +/** + * Logs what `schemaGaps` finds, once per start; says nothing on a healthy + * database. A check that cannot run is logged too and never fails the start: + * it only adds a diagnosis. + */ +export async function warnAboutSchemaGaps(orm: AnyOrm): Promise { + let gaps: string[]; + try { + gaps = await schemaGaps(orm); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + logger.warn( + `Could not check the database for tables and columns this TREK version uses (${reason}); ` + + 'the start goes on without that check.', + ); + return; + } + if (gaps.length === 0) return; + const named = gaps.slice(0, MAX_NAMED).join(', '); + const more = gaps.length > MAX_NAMED ? ` and ${gaps.length - MAX_NAMED} more` : ''; + logger.warn( + `The database lacks ${gaps.length} table(s) or column(s) this TREK version uses: ${named}${more}. ` + + 'Its upgrade history skipped them and no migration of this version can add them, so the features that use ' + + 'them fail, and a move to Postgres refuses the file. This is a bug in TREK: please report it with this message.', + ); +} diff --git a/server/tests/postgres/schema-gaps.test.ts b/server/tests/postgres/schema-gaps.test.ts new file mode 100644 index 000000000..b3568f4aa --- /dev/null +++ b/server/tests/postgres/schema-gaps.test.ts @@ -0,0 +1,47 @@ +/** + * PGGAP-001..002: the boot's check for tables and columns the entities map + * (src/db/schema-gaps.ts) on the lane's real Postgres database. Every + * Postgres start runs it, so a catalog that reads differently from the + * entities would warn about a healthy install on every start; the SQLite + * suite (tests/unit/db/schema-gaps.test.ts) cannot see that. + */ +import { buildApp } from '../../src/bootstrap'; +import { schemaGaps } from '../../src/db/schema-gaps'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { MikroORM } from '@mikro-orm/core'; +import { Logger, type INestApplication } from '@nestjs/common'; + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +let app: INestApplication; +let orm: MikroORM; +let bootWarnings: string[]; + +beforeAll(async () => { + const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + try { + app = await buildApp(); + } finally { + bootWarnings = warn.mock.calls.map(([line]) => String(line)); + warn.mockRestore(); + } + orm = app.get(MikroORM); +}, 60_000); + +afterAll(async () => { + await app?.close(); +}); + +describe('the schema gap check on Postgres', () => { + it('PGGAP-001: a bootstrapped database lacks nothing, and the start says nothing about it', async () => { + expect(await withRequestContext(orm, () => schemaGaps(orm))).toEqual([]); + expect(bootWarnings.filter((line) => line.includes('this TREK version uses'))).toEqual([]); + }); + + it('PGGAP-002: a column the database lacks is named by table and column', async () => { + await withRequestContext(orm, () => + orm.em.getConnection().execute('alter table users drop column mfa_backup_codes'), + ); + expect(await withRequestContext(orm, () => schemaGaps(orm))).toEqual(['users.mfa_backup_codes']); + }); +}); diff --git a/server/tests/unit/db/dialect/catalog.test.ts b/server/tests/unit/db/dialect/catalog.test.ts index 448453c2a..5eec10655 100644 --- a/server/tests/unit/db/dialect/catalog.test.ts +++ b/server/tests/unit/db/dialect/catalog.test.ts @@ -3,7 +3,7 @@ * helpers built on it (src/db/migration-utils.ts), so a migration after the * Postgres baseline's cut can ask what exists on either engine. */ -import { columnNamesSql, tableExistsSql } from '../../../../src/db/dialect/catalog'; +import { columnNamesSql, tableColumnsSql, tableExistsSql } from '../../../../src/db/dialect/catalog'; import { addColumnIfMissing, columnNames, @@ -33,10 +33,20 @@ describe('catalog statements', () => { ); }); + it('CATALOG-003: every column of every table in one statement, on both engines', () => { + expect(tableColumnsSql(sqlite)).toBe( + "select m.name as table_name, p.name as name from sqlite_master m join pragma_table_info(m.name) p where m.type = 'table'", + ); + expect(tableColumnsSql(postgres)).toBe( + 'select table_name, column_name as name from information_schema.columns where table_schema = current_schema()', + ); + }); + it('CATALOG-002: any other engine is refused', () => { class OtherPlatform extends Platform {} expect(() => columnNamesSql(new OtherPlatform())).toThrow(); expect(() => tableExistsSql(new OtherPlatform())).toThrow(); + expect(() => tableColumnsSql(new OtherPlatform())).toThrow(); }); }); diff --git a/server/tests/unit/db/schema-gaps.test.ts b/server/tests/unit/db/schema-gaps.test.ts new file mode 100644 index 000000000..623772d6f --- /dev/null +++ b/server/tests/unit/db/schema-gaps.test.ts @@ -0,0 +1,93 @@ +/** + * SCHEMAGAP: the boot's check that every table and column the entities map + * exists (src/db/schema-gaps.ts). Silent on a database the migrations built, + * so it never troubles a healthy install; on one an old upgrade left without + * a column, it names the column once per start and lets the start go on. + */ +import { schemaGaps, warnAboutSchemaGaps } from '../../../src/db/schema-gaps'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; +import { Logger } from '@nestjs/common'; + +import type Database from 'better-sqlite3'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +let db: Database.Database; +let t: TestOrm; + +beforeEach(async () => { + db = createSnapshotTestDb(); + t = await createTestOrm(db); +}); + +afterEach(async () => { + await t.close(); + db.close(); + vi.restoreAllMocks(); +}); + +describe('schemaGaps', () => { + it('SCHEMAGAP-001: finds nothing on a database the migrations built, and says nothing', async () => { + const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + expect(await schemaGaps(t.orm)).toEqual([]); + await warnAboutSchemaGaps(t.orm); + expect(warn).not.toHaveBeenCalled(); + }); + + it('SCHEMAGAP-002: names a missing column by table and column, and a missing table as a whole', async () => { + db.exec('ALTER TABLE users DROP COLUMN mfa_backup_codes'); + db.exec('ALTER TABLE users DROP COLUMN immich_access_token'); + db.exec('PRAGMA foreign_keys = OFF'); + db.exec('DROP TABLE bucket_list'); + expect(await schemaGaps(t.orm)).toEqual( + expect.arrayContaining(['users.mfa_backup_codes', 'users.immich_access_token', 'the table bucket_list']), + ); + expect(await schemaGaps(t.orm)).toHaveLength(3); + }); + + it('SCHEMAGAP-003: the warning names what is missing, says what fails, and asks for a report', async () => { + const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + db.exec('ALTER TABLE users DROP COLUMN mfa_backup_codes'); + await warnAboutSchemaGaps(t.orm); + expect(warn).toHaveBeenCalledTimes(1); + const [line] = warn.mock.calls[0] as [string]; + expect(line).toMatch( + /^The database lacks 1 table\(s\) or column\(s\) this TREK version uses: users\.mfa_backup_codes\. /, + ); + expect(line).toContain('a move to Postgres refuses the file'); + expect(line).toContain('please report it with this message'); + }); + + it('SCHEMAGAP-004: past twenty it names the first twenty and counts the rest', async () => { + const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + const optional: Array<{ name: string }> = await t.em + .getConnection() + .execute(`SELECT name FROM pragma_table_info('users') WHERE pk = 0 AND "notnull" = 0`); + let dropped = 0; + for (const { name } of optional) { + try { + db.exec(`ALTER TABLE users DROP COLUMN "${name}"`); + dropped++; + } catch { + // indexed or referenced columns stay + } + if (dropped === 22) break; + } + expect(dropped).toBe(22); + await warnAboutSchemaGaps(t.orm); + expect(warn.mock.calls[0]?.[0]).toMatch(/lacks 22 table\(s\) or column\(s\) .* and 2 more\. /); + }); + + it('SCHEMAGAP-005: a check that cannot run is logged and the start goes on', async () => { + const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {}); + const connection = t.orm.em.getConnection(); + vi.spyOn(connection, 'execute').mockRejectedValueOnce(new Error('no such module: fts5')); + vi.spyOn(t.orm.em, 'getConnection').mockReturnValue(connection); + await expect(warnAboutSchemaGaps(t.orm)).resolves.toBeUndefined(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toBe( + 'Could not check the database for tables and columns this TREK version uses (no such module: fts5); ' + + 'the start goes on without that check.', + ); + }); +});