feat(db): create and migrate the schema on a Postgres database

With TREK_DB_URL set, TREK now boots on Postgres; without it nothing changes.

- The database engine contract gains open, close, reopen and the schema
  bootstrap; DatabaseLifecycle delegates to the engine resolveEngine() picks.
- An empty Postgres database gets server/assets/postgres/baseline.sql
  (generated from the entities by gen:pg-baseline, with the reference rows
  the migrations up to its cut insert: tour types, provider catalogues,
  addons, app settings) and every migration up to its cut recorded as
  executed, in one transaction. A database holding tables
  without TREK's history is refused before anything is written; a migrated one
  runs the newer-database refusal and its pending migrations, which refuse
  without a copy unless TREK_DB_PRE_MIGRATE_SNAPSHOT=false.
- INTEGER columns are bigint on Postgres (SQLite's INTEGER is 64-bit: an
  epoch-millisecond column overflowed int4), and the engine's driver reads
  bigint and numeric back as numbers, refusing values past 2^53.
- The two SQLite triggers are ported to PL/pgSQL; check:pg-baseline fails
  while a SQLite trigger has no port, and while the baseline drifts from the
  entities before a later migration freezes it.
- Backups and restores on Postgres refuse until they can dump and load one.
- Migration helpers read the catalog per engine (dialect/catalog.ts), and
  the email case index no longer needs group_concat.
- CI runs check:pg-baseline and boots the image on postgres:17 twice.
This commit is contained in:
Isaias Tavares
2026-11-02 14:25:34 -03:00
parent 25f5e34558
commit a77705984e
40 changed files with 2655 additions and 229 deletions
@@ -0,0 +1,145 @@
/**
* The committed Postgres baseline (server/assets/postgres/) and what keeps it
* honest: reading and writing it (src/db/engine/postgres/baseline.ts) and the
* generator's --check (scripts/generate-pg-baseline.ts).
*/
import { checkBaseline, rowStatements, triggerPortProblems } from '../../../../../scripts/generate-pg-baseline';
import {
baselineMatches,
readPostgresBaseline,
renderBaseline,
writePostgresBaseline,
type PostgresBaseline,
} from '../../../../../src/db/engine/postgres/baseline';
import { knownMigrationNames } from '../../../../../src/db/known-migrations';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
const A = 'Migration20200101000000_a';
const B = 'Migration20200101000100_b';
const C = 'Migration20200101000200_c';
const sample: PostgresBaseline = {
through: B,
migrations: [A, B],
statements: ['create table "t" ("note" text default \'x;y\')', 'create index "i" on "t" ("note")'],
};
let dir: string | undefined;
afterEach(() => {
if (dir) rmSync(dir, { recursive: true, force: true });
dir = undefined;
});
const scratch = () => (dir = mkdtempSync(path.join(tmpdir(), 'trek-pg-baseline-')));
describe('Postgres baseline files', () => {
it('PGBASE-001: what is written reads back the same, comment line and all', () => {
const target = scratch();
writePostgresBaseline(sample, target);
expect(readPostgresBaseline(target)).toEqual(sample);
expect(baselineMatches(sample, target)).toBe(true);
expect(baselineMatches({ ...sample, statements: [sample.statements[0]] }, target)).toBe(false);
expect(renderBaseline(sample).sql.startsWith('-- ')).toBe(true);
});
it('PGBASE-002: a manifest that does not list its own cut, or an empty SQL file, is refused', () => {
const target = scratch();
writePostgresBaseline(sample, target);
writeFileSync(path.join(target, 'baseline.json'), JSON.stringify({ through: C, migrations: [A, B] }));
expect(() => readPostgresBaseline(target)).toThrow(/must name "through"/);
writePostgresBaseline(sample, target);
writeFileSync(path.join(target, 'baseline.sql'), '-- nothing\n');
expect(() => readPostgresBaseline(target)).toThrow(/holds no statements/);
writeFileSync(path.join(target, 'baseline.sql'), 'create table "q" ("a" text default \'?\');\n');
expect(() => readPostgresBaseline(target)).toThrow(/holds a "\?"/);
expect(baselineMatches(sample, path.join(target, 'missing'))).toBe(false);
});
it('PGBASE-003: the committed baseline names every migration on disk up to its cut, and only those', () => {
const committed = readPostgresBaseline();
const known = [...knownMigrationNames()].sort();
expect(committed.migrations).toEqual(known.filter((name) => name <= committed.through));
expect(committed.statements.some((statement) => /^create table "users"/.test(statement))).toBe(true);
expect(committed.statements.join('\n')).not.toMatch(/\binteger\b/);
});
});
describe('checkBaseline', () => {
const generated = (through: string, migrations: string[]): PostgresBaseline => ({
through,
migrations,
statements: [],
});
it('PGBASE-010: at the newest migration the baseline must be exactly what the entities generate', () => {
expect(checkBaseline(sample, generated(B, [A, B]), true)).toEqual([]);
expect(checkBaseline(sample, generated(B, [A, B]), false)).toEqual([
'the entities generate a different schema; run npm run gen:pg-baseline',
]);
});
it('PGBASE-011: once a migration lands after the cut, the baseline is frozen and only its manifest is checked', () => {
expect(checkBaseline(sample, generated(C, [A, B, C]), false)).toEqual([]);
});
it('PGBASE-012: a manifest naming a migration that is gone, or missing one before its cut, is reported', () => {
expect(checkBaseline(sample, generated(C, [B, C]), true)).toEqual([
`the baseline names migrations that do not exist: ${A}`,
]);
const skipped = { ...sample, migrations: [B] };
expect(checkBaseline(skipped, generated(B, [A, B]), true)).toEqual([
`migrations up to ${B} are missing from it: ${A}`,
]);
});
});
describe('triggerPortProblems', () => {
it('PGBASE-020: every SQLite trigger needs a Postgres port, and a port without its trigger is stale', () => {
expect(triggerPortProblems(['a', 'b'], ['b', 'a'])).toEqual([]);
expect(triggerPortProblems(['a', 'b'], ['a', 'c'])).toEqual([
'SQLite triggers without a Postgres port in POSTGRES_TRIGGERS: b',
'POSTGRES_TRIGGERS ports triggers the migrations no longer create: c',
]);
});
it('PGBASE-021: the committed baseline carries every trigger port after the tables', () => {
const statements = readPostgresBaseline().statements;
const firstTrigger = statements.findIndex((statement) => statement.startsWith('CREATE FUNCTION'));
expect(firstTrigger).toBeGreaterThan(0);
expect(statements.slice(firstTrigger).every((statement) => /^CREATE (FUNCTION|TRIGGER) /.test(statement))).toBe(
true,
);
});
});
describe('rowStatements', () => {
it("PGBASE-030: a migration's rows go in as quoted literals the column casts, and a numeric id moves its sequence past them", () => {
expect(
rowStatements('photo_provider_fields', [
{ id: 1, provider_id: 'immich', label: "Server's URL", required: 1, hint: null },
{ id: 2, provider_id: 'immich', label: 'API key', required: 0, hint: 'x' },
]),
).toEqual([
'insert into "photo_provider_fields" ("id", "provider_id", "label", "required", "hint") values ' +
"('1', 'immich', 'Server''s URL', '1', NULL), ('2', 'immich', 'API key', '0', 'x')",
"select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('\"photo_provider_fields\"', 'id') as seq, " +
'max("id") as max_id from "photo_provider_fields") ids where seq is not null',
]);
});
it('PGBASE-031: a text key has no sequence to move, an empty table writes nothing, and binary data is refused', () => {
expect(rowStatements('addons', [{ id: 'mcp', enabled: 0 }])).toEqual([
'insert into "addons" ("id", "enabled") values (\'mcp\', \'0\')',
]);
expect(rowStatements('addons', [])).toEqual([]);
expect(() => rowStatements('blobs', [{ data: Buffer.from('x') }])).toThrow(/binary data/);
});
it('PGBASE-032: the committed baseline carries the reference rows the migrations insert', () => {
const sql = readPostgresBaseline().statements.join('\n');
expect(sql).toContain('insert into "tour_types"');
expect(sql).toContain('insert into "app_settings"');
});
});
@@ -0,0 +1,46 @@
/**
* The Postgres driver reads `bigint` as a number, on its own pool only
* (src/db/engine/postgres/postgres-driver.ts). Nothing here connects.
*/
import { parseInt8, parseNumeric, TrekPostgreSqlDriver } from '../../../../../src/db/engine/postgres/postgres-driver';
import { Configuration } from '@mikro-orm/core';
import type { PostgreSqlConnection } from '@mikro-orm/postgresql';
import { describe, expect, it } from 'vitest';
type Parsers = { getTypeParser(oid: number): (text: string) => unknown };
describe('postgres driver', () => {
it('PGDRIVER-001: a bigint is a number up to 2^53 and refused past it, never rounded', () => {
expect(parseInt8('0')).toBe(0);
expect(parseInt8('1793636850006')).toBe(1793636850006);
expect(parseInt8('-42')).toBe(-42);
expect(() => parseInt8('9007199254740993')).toThrow(/beyond what TREK reads exactly/);
});
it('PGDRIVER-003: a numeric (sum of a bigint, avg) is a number like SQLite answers, an integral one past 2^53 refused', () => {
expect(parseNumeric('4200')).toBe(4200);
expect(parseNumeric('2.5000000000000000')).toBe(2.5);
expect(parseNumeric('-7')).toBe(-7);
expect(() => parseNumeric('9007199254740993')).toThrow(/beyond what TREK reads exactly/);
expect(() => parseNumeric('NaN')).toThrow(/beyond what TREK reads exactly/);
});
it("PGDRIVER-002: the pool parses int8 as a number and keeps MikroORM's text dates", () => {
const config = new Configuration(
{
driver: TrekPostgreSqlDriver,
clientUrl: 'postgresql://u@localhost/trek',
entities: [],
discovery: { warnWhenNoEntities: false },
},
false,
);
const driver = new TrekPostgreSqlDriver(config);
const options = (driver.getConnection() as PostgreSqlConnection).mapOptions({});
const types = options.types as unknown as Parsers;
expect(types.getTypeParser(20)('12')).toBe(12);
expect(types.getTypeParser(1700)('12.5')).toBe(12.5);
expect(types.getTypeParser(1114)('2026-01-01 00:00:00')).toBe('2026-01-01 00:00:00');
});
});
@@ -0,0 +1,95 @@
/**
* How the entities' schema is written in Postgres
* (src/db/engine/postgres/schema-adjust.ts): SQLite-only defaults, TEXT timestamps, the
* NOCASE collation, and splitting the generated DDL so one refused statement
* does not take the rest with it.
*/
import {
adjustColumns,
NOCASE_COLLATION_SQL,
PG_NOW_TEXT_DEFAULT,
portableDefault,
POSTGRES_TRIGGERS,
splitStatements,
type ColumnMeta,
} from '../../../../../src/db/engine/postgres/schema-adjust';
import { describe, expect, it } from 'vitest';
class DbTimestampType {}
class TextType {}
describe('pg-probe schema', () => {
it('PGPROBE-040: maps the SQLite clock defaults and leaves every other default alone', () => {
expect(PG_NOW_TEXT_DEFAULT).toBe("to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS')");
expect(portableDefault('CURRENT_TIMESTAMP')).toBe(PG_NOW_TEXT_DEFAULT);
expect(portableDefault("(datetime('now'))")).toBe(PG_NOW_TEXT_DEFAULT);
expect(portableDefault("datetime( 'now' )")).toBe(PG_NOW_TEXT_DEFAULT);
expect(portableDefault("(strftime('%s','now'))")).toBe('CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)');
for (const kept of ['0', '1', 'NULL', "'none'", "'#10b981'", "'{}'"]) expect(portableDefault(kept)).toBe(kept);
});
it('PGPROBE-041: makes timestamp columns text, rewrites defaults and the NOCASE collation, and names what it changed', () => {
const columns: ColumnMeta[] = [
{
name: 'created_at',
customType: new DbTimestampType(),
columnTypes: ['timestamptz'],
defaultRaw: 'CURRENT_TIMESTAMP',
},
{ name: 'title', customType: new TextType(), columnTypes: ['text'], defaultRaw: "'x'" },
{ name: 'stamp', columnTypes: ['int'], defaultRaw: "(strftime('%s','now'))" },
{ name: 'region', columnTypes: ['text'], collation: 'NOCASE' },
{ name: 'body', columnTypes: ['text'] },
];
expect(adjustColumns(columns)).toEqual(['created_at', 'stamp', 'region']);
expect(columns[0]).toMatchObject({ columnTypes: ['text'], defaultRaw: PG_NOW_TEXT_DEFAULT });
expect(columns[1]).toMatchObject({ columnTypes: ['text'], defaultRaw: "'x'" });
expect(columns[2]).toMatchObject({
columnTypes: ['bigint'],
defaultRaw: 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)',
});
expect(columns[3]).toMatchObject({ collation: 'nocase' });
expect(NOCASE_COLLATION_SQL).toContain('CREATE COLLATION IF NOT EXISTS nocase');
});
it('PGPROBE-043: an integer column is bigint, as wide as SQLite INTEGER (epoch milliseconds overflow integer)', () => {
const columns: ColumnMeta[] = [
{ name: 'id', columnTypes: ['integer'] },
{ name: 'next_run_at', columnTypes: ['int'] },
{ name: 'enabled', columnTypes: ['boolean'] },
{ name: 'note', columnTypes: ['text'] },
];
expect(adjustColumns(columns)).toEqual(['id', 'next_run_at']);
expect(columns.map((column) => column.columnTypes)).toEqual([['bigint'], ['bigint'], ['boolean'], ['text']]);
});
it('PGPROBE-042: splits DDL on semicolons outside quotes and drops session settings', () => {
const ddl = [
"set names 'utf8';",
'create table "a" ("id" serial primary key, "note" text default \'a;b\');',
'create index "a_x" on "a" ("note") where "note" <> \';\';',
'',
'create table "b ;" ("id" int)',
].join('\n');
expect(splitStatements(ddl)).toEqual([
'create table "a" ("id" serial primary key, "note" text default \'a;b\')',
'create index "a_x" on "a" ("note") where "note" <> \';\'',
'create table "b ;" ("id" int)',
]);
expect(splitStatements(' ; ; ')).toEqual([]);
});
it('PGPROBE-044: a $$ body stays one statement, semicolons and all, and every trigger port splits into its two', () => {
const fn =
"CREATE FUNCTION f() RETURNS trigger LANGUAGE plpgsql AS $$\nBEGIN\n UPDATE t SET x = ';';\n RETURN NEW;\nEND\n$$";
expect(splitStatements(`${fn};\nCREATE TRIGGER g AFTER UPDATE ON t FOR EACH ROW EXECUTE FUNCTION f();`)).toEqual([
fn,
'CREATE TRIGGER g AFTER UPDATE ON t FOR EACH ROW EXECUTE FUNCTION f()',
]);
for (const [name, statements] of Object.entries(POSTGRES_TRIGGERS)) {
expect(splitStatements(statements.join(';\n')), name).toEqual([...statements]);
expect(statements.at(-1), name).toContain(`CREATE TRIGGER ${name} `);
}
});
});
@@ -0,0 +1,201 @@
/**
* How a Postgres database reaches the schema (src/db/engine/postgres/schema-bootstrap.ts):
* the three states the plan names (empty, foreign tables, TREK's own) and the
* safety net before pending migrations, over a fake migrator and connection.
*/
import type { AppEnv } from '../../../../../src/app-config';
import {
bootstrapPostgresSchema,
postgresSafetyNet,
type PostgresBootstrapDeps,
} from '../../../../../src/db/engine/postgres/schema-bootstrap';
import type { MigrationSafetyNet } from '../../../../../src/db/legacy-baseline';
import type { AnyOrm } from '../../../../../src/db/orm';
import { Logger } from '@nestjs/common';
import { afterEach, describe, expect, it, vi } from 'vitest';
const M1 = 'Migration20200101000000_baseline_schema';
const M2 = 'Migration20200101000100_second';
const M3 = 'Migration20200101000200_after_the_cut';
interface FakeDb {
executed: string[];
pending: string[];
tables: string[];
/** Whether mikro_orm_migrations exists: from the start when anything is recorded. */
history: boolean;
ensureTable: ReturnType<typeof vi.fn>;
sql: string[];
logged: string[];
inTransaction: boolean[];
up: ReturnType<typeof vi.fn>;
}
function fakeOrm(state: Pick<FakeDb, 'executed' | 'pending' | 'tables'> & { history?: boolean }): {
orm: AnyOrm;
db: FakeDb;
} {
const db: FakeDb = {
...state,
history: state.history ?? state.executed.length > 0,
ensureTable: vi.fn(async () => {
db.history = true;
}),
sql: [],
logged: [],
inTransaction: [],
up: vi.fn(async () => undefined),
};
const trx = { trx: true };
const connection = {
execute: vi.fn(async (sql: string, _params?: unknown[], _method?: string, ctx?: unknown) => {
if (sql.includes('information_schema.tables')) {
return [...db.tables, ...(db.history ? ['mikro_orm_migrations'] : [])].map((table_name) => ({ table_name }));
}
db.sql.push(sql);
db.inTransaction.push(ctx === trx);
return [];
}),
transactional: vi.fn(async (work: (ctx: unknown) => Promise<void>) => work(trx)),
};
const storage = {
ensureTable: db.ensureTable,
logMigration: vi.fn(async ({ name }: { name: string }, ctx?: unknown) => {
db.logged.push(name);
db.inTransaction.push(ctx === trx);
db.executed = [...db.executed, name];
db.pending = db.pending.filter((pending) => pending !== name);
}),
};
const migrator = {
getStorage: () => storage,
getExecuted: vi.fn(async () => db.executed.map((name) => ({ name }))),
getPending: vi.fn(async () => db.pending.map((name) => ({ name }))),
up: db.up,
};
const orm = {
config: { getExtension: () => migrator, get: () => ({}) },
em: { getConnection: () => connection },
} as unknown as AnyOrm;
return { orm, db };
}
function deps(
safetyNet: MigrationSafetyNet = { beforeMigrate: vi.fn(async () => undefined), restoreHint: async () => null },
) {
const value: PostgresBootstrapDeps = {
baseline: () => ({
through: M2,
migrations: [M1, M2],
statements: ['create table "a" ("id" bigserial)', 'create index "x" on "a" ("id")'],
}),
known: new Set([M1, M2, M3]),
safetyNet,
};
return value;
}
afterEach(() => vi.restoreAllMocks());
describe('bootstrapPostgresSchema', () => {
it('PGBOOT-001: an empty database gets the baseline and its migrations recorded, all in one transaction', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2], tables: [] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(db.sql).toEqual(['create table "a" ("id" bigserial);\ncreate index "x" on "a" ("id")']);
expect(db.logged).toEqual([M1, M2]);
expect(db.inTransaction.every(Boolean)).toBe(true);
expect(db.up).not.toHaveBeenCalled();
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
it('PGBOOT-002: a fresh database runs the migrations after the cut without the safety net (nothing to lose)', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2, M3], tables: [] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(db.logged).toEqual([M1, M2]);
expect(db.up).toHaveBeenCalledTimes(1);
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
it('PGBOOT-003: tables without TREK history are refused, named, and nothing is written', async () => {
const { orm, db } = fakeOrm({ executed: [], pending: [M1], tables: ['customers', 'orders'] });
await expect(bootstrapPostgresSchema(orm, deps())).rejects.toThrow(
/Refusing to boot: the database holds 2 table\(s\) \(customers, orders\) but no TREK migration history/,
);
expect(db.sql).toEqual([]);
expect(db.logged).toEqual([]);
expect(db.ensureTable).not.toHaveBeenCalled();
});
it('PGBOOT-008: an empty history table beside no other table is a fresh database (a first boot cut short)', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [], pending: [M1, M2], tables: [], history: true });
await bootstrapPostgresSchema(orm, deps());
expect(db.logged).toEqual([M1, M2]);
});
it('PGBOOT-004: a database a newer TREK migrated is refused before anything runs', async () => {
const { orm, db } = fakeOrm({ executed: [M1, 'Migration20990101000000_from_the_future'], pending: [], tables: [] });
await expect(bootstrapPostgresSchema(orm, deps())).rejects.toThrow(/migrated by a newer TREK/);
expect(db.up).not.toHaveBeenCalled();
});
it('PGBOOT-005: pending migrations on a database in use run after the safety net, labelled by the last one', async () => {
vi.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);
const { orm, db } = fakeOrm({ executed: [M2, M1], pending: [M3], tables: ['users'] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(net.safetyNet.beforeMigrate).toHaveBeenCalledWith('20200101000100');
expect(db.up).toHaveBeenCalledTimes(1);
expect(db.sql).toEqual([]);
});
it('PGBOOT-006: a refusing safety net stops the migration', async () => {
const { orm, db } = fakeOrm({ executed: [M1, M2], pending: [M3], tables: ['users'] });
const refusing = {
beforeMigrate: vi.fn(async () => Promise.reject(new Error('no copy'))),
restoreHint: async () => null,
};
await expect(bootstrapPostgresSchema(orm, deps(refusing))).rejects.toThrow('no copy');
expect(db.up).not.toHaveBeenCalled();
});
it('PGBOOT-007: a database at head does nothing', async () => {
const { orm, db } = fakeOrm({ executed: [M1, M2, M3], pending: [], tables: ['users'] });
const net = deps();
await bootstrapPostgresSchema(orm, net);
expect(db.sql).toEqual([]);
expect(db.up).not.toHaveBeenCalled();
expect(net.safetyNet.beforeMigrate).not.toHaveBeenCalled();
});
});
describe('postgresSafetyNet', () => {
const envWith = (preMigrateSnapshot: boolean | undefined, isTest: boolean) => () =>
({ db: { preMigrateSnapshot }, app: { isTest } }) as unknown as AppEnv;
it.each([undefined, true])(
'PGBOOT-010: refuses by default (setting %s), naming pg_dump and the switch, since this release cannot copy a Postgres database',
async (setting) => {
await expect(postgresSafetyNet(envWith(setting, false)).beforeMigrate('1')).rejects.toThrow(
/cannot copy a Postgres database.*pg_dump.*TREK_DB_PRE_MIGRATE_SNAPSHOT=false/,
);
},
);
it('PGBOOT-011: migrates without a copy when the operator turned it off, and says so', async () => {
const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
await expect(postgresSafetyNet(envWith(false, false)).beforeMigrate('1')).resolves.toBeUndefined();
expect(warn).toHaveBeenCalledWith(expect.stringContaining('without a copy'));
});
it('PGBOOT-012: stays out of the way under test unless a suite asks for it, and has no restore hint', async () => {
const net = postgresSafetyNet(envWith(undefined, true));
await expect(net.beforeMigrate('1')).resolves.toBeUndefined();
await expect(net.restoreHint('1')).resolves.toBeNull();
});
});