Files
liqa/server/test/migrations.spec.ts
T
ars9 9f341719ef feat(database): manage the schema with typeorm migrations
- replace synchronize with migrations, starting with a generated initial
  migration that adopts databases created by synchronize
- apply pending migrations in the docker container before the server,
  and refuse to start the server while migrations are pending
- share one entity list and data source between app, migration runner,
  typeorm cli and tests; tests run the real migrations
- add migration:run, migration:show and migration:generate scripts and
  a test that fails when entities and migrations differ
- exit with code 1 when startup fails
- bump version to 1.20.0
2026-09-30 21:45:42 +03:00

66 lines
2.4 KiB
TypeScript

/**
* The schema is managed by migrations. These tests fail when an entity
* changes without a matching migration, and cover adopting databases that
* were created by `synchronize` before migrations existed.
*/
import { DataSource } from "typeorm";
import { dataSourceOptions } from "../src/database/data-source";
import { MIGRATIONS } from "../src/database/migrations";
async function pendingSchemaChanges(dataSource: DataSource): Promise<string[]> {
const sql = await dataSource.driver.createSchemaBuilder().log();
return sql.upQueries.map((q) => q.query);
}
describe("Database migrations", () => {
it("migrations produce exactly the schema the entities describe", async () => {
const dataSource = new DataSource(dataSourceOptions(":memory:"));
await dataSource.initialize();
try {
await dataSource.runMigrations();
expect(await dataSource.showMigrations()).toBe(false);
// If this fails, generate a migration: see "Database migrations" in docs/development.md
expect(await pendingSchemaChanges(dataSource)).toEqual([]);
} finally {
await dataSource.destroy();
}
});
it("adopts a database created by synchronize", async () => {
const dataSource = new DataSource({
...dataSourceOptions(":memory:"),
synchronize: true,
});
await dataSource.initialize();
try {
await dataSource.query(
`INSERT INTO scenarios (id, name, version) VALUES ('11111111-1111-4111-8111-111111111111', 'kept', 1)`,
);
const applied = await dataSource.runMigrations();
expect(applied.map((m) => m.name)).toEqual(MIGRATIONS.map((m) => m.name));
expect(await dataSource.showMigrations()).toBe(false);
expect(await pendingSchemaChanges(dataSource)).toEqual([]);
const [row] = await dataSource.query(`SELECT name FROM scenarios`);
expect(row.name).toBe("kept");
} finally {
await dataSource.destroy();
}
});
it("can revert the initial migration", async () => {
const dataSource = new DataSource(dataSourceOptions(":memory:"));
await dataSource.initialize();
try {
await dataSource.runMigrations();
await dataSource.undoLastMigration();
const tables = await dataSource.query(
`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT IN ('migrations', 'sqlite_sequence')`,
);
expect(tables).toEqual([]);
} finally {
await dataSource.destroy();
}
});
});