/** * 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 { 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(); } }); });