import { copyFileSync, cpSync, mkdtempSync, readFileSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { PostgreSqlContainer, type StartedPostgreSqlContainer, } from '@testcontainers/postgresql'; import { drizzle } from 'drizzle-orm/node-postgres'; import { migrate as drizzleMigrate } from 'drizzle-orm/node-postgres/migrator'; import { Pool } from 'pg'; import { afterAll, beforeAll, describe, expect, test } from 'vitest'; import { MIGRATIONS_SCHEMA, MIGRATIONS_TABLE, migrate, } from '../src/migrator.js'; /** * Upgrading a database that an earlier release set up must leave it with the * schema a fresh database gets. * * The 4.x release line shipped 0000-0010, then 0015 (4.3) and 0027 (4.4), so * its databases record migrations out of journal order. Drizzle's own migrator * applies only entries newer than the newest recorded one and skips the rest. */ const MIGRATIONS = fileURLToPath( new URL('../src/drizzle/migrations', import.meta.url) ); /** * The 0027 that 4.4 shipped. It converts only the tables 4.4 had, so it * predates `workflow_invocations` (0020) and `workflow_snapshots` (0025). */ const V4_4_0027 = fileURLToPath( new URL( './fixtures/migrations-4.4/0027_timestamps_with_time_zone.sql', import.meta.url ) ); interface JournalEntry { idx: number; when: number; tag: string; } const journal: JournalEntry[] = JSON.parse( readFileSync(join(MIGRATIONS, 'meta', '_journal.json'), 'utf8') ).entries; const entry = (prefix: string) => { const found = journal.find((e) => e.tag.startsWith(`${prefix}_`)); if (!found) throw new Error(`no migration ${prefix} in the journal`); return found; }; const tag = (prefix: string) => entry(prefix).tag; const V4_2 = journal.filter((e) => e.idx <= 10).map((e) => e.tag); const V4_3 = [...V4_2, tag('0015')]; const V4_4 = [...V4_3, tag('0027')]; /** 5.0-5.5, whose bootstrap still used drizzle's migrator. */ const V5_5 = journal .filter((e) => e.when < entry('0034').when) .map((e) => e.tag); /** * A migrations folder holding only `tags`, with their SQL files from this * release unless `replace` gives another file for a tag. */ function migrationsFolder( tags: string[], replace: Record = {} ): string { const dir = mkdtempSync(join(tmpdir(), 'world-postgres-migrator-')); cpSync(MIGRATIONS, dir, { recursive: true }); for (const [name, file] of Object.entries(replace)) { copyFileSync(file, join(dir, `${name}.sql`)); } const journalPath = join(dir, 'meta', '_journal.json'); const parsed = JSON.parse(readFileSync(journalPath, 'utf8')); parsed.entries = parsed.entries.filter((e: JournalEntry) => tags.includes(e.tag) ); writeFileSync(journalPath, JSON.stringify(parsed, null, 2)); return dir; } if (process.platform === 'win32') { // These tests rely on a docker container. test.skip('skipped on Windows since it relies on a docker container', () => {}); } else { describe('migrate', () => { let container: StartedPostgreSqlContainer; let databases = 0; let fresh: string; const pools: Pool[] = []; /** A new, empty database and a pool on it. */ async function createDatabase(): Promise<{ name: string; pool: Pool }> { const name = `migrator_${++databases}`; const admin = new Pool({ connectionString: container.getConnectionUri(), }); try { await admin.query(`CREATE DATABASE "${name}"`); } finally { await admin.end(); } const url = new URL(container.getConnectionUri()); url.pathname = `/${name}`; const pool = new Pool({ connectionString: url.toString(), max: 4 }); // Stopping the container terminates idle connections (57P01). pool.on('error', (error: Error & { code?: string }) => { if (error.code !== '57P01') throw error; }); pools.push(pool); return { name, pool }; } /** What a release whose bootstrap used drizzle's migrator left behind. */ async function drizzleBootstrap(pool: Pool, folder: string) { await drizzleMigrate(drizzle(pool), { migrationsFolder: folder, migrationsTable: MIGRATIONS_TABLE, migrationsSchema: MIGRATIONS_SCHEMA, }); } /** * The `workflow` schema as `pg_dump` prints it, one line per entry and * sorted, so two databases compare equal when they hold the same tables, * columns, types, defaults, constraints and indexes, whatever order the * columns were added in. */ async function schemaOf(database: string): Promise { const { output, exitCode } = await container.exec([ 'pg_dump', '--username', container.getUsername(), '--dbname', database, '--schema-only', '--schema=workflow', '--no-owner', ]); expect(exitCode).toBe(0); return output .split('\n') .filter( (line) => line.trim() !== '' && !line.startsWith('--') && !/^\\(un)?restrict /.test(line) ) .map((line) => line.replace(/,$/, '')) .sort(); } async function recorded(pool: Pool): Promise { const { rows } = await pool.query<{ created_at: string }>( `SELECT created_at FROM "${MIGRATIONS_SCHEMA}"."${MIGRATIONS_TABLE}" ORDER BY id` ); return rows.map((row) => Number(row.created_at)); } const byValue = (a: number, b: number) => a - b; const allWhens = journal.map((e) => e.when).sort(byValue); const missingFrom = (tags: string[]) => journal.map((e) => e.tag).filter((t) => !tags.includes(t)); beforeAll(async () => { container = await new PostgreSqlContainer('postgres:15-alpine').start(); const db = await createDatabase(); fresh = db.name; const { applied } = await migrate(db.pool, { migrationsFolder: MIGRATIONS, }); expect(applied).toEqual(journal.map((e) => e.tag)); }, 120_000); afterAll(async () => { await Promise.all(pools.map((pool) => pool.end())); await container?.stop(); }); test('upgrades a 5.5 database', async () => { const { name, pool } = await createDatabase(); await drizzleBootstrap(pool, migrationsFolder(V5_5)); const { applied } = await migrate(pool, { migrationsFolder: MIGRATIONS }); expect(applied).toEqual(missingFrom(V5_5)); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); test('applies nothing to a database that is up to date', async () => { const { name, pool } = await createDatabase(); await migrate(pool, { migrationsFolder: MIGRATIONS }); const before = await recorded(pool); expect(await migrate(pool, { migrationsFolder: MIGRATIONS })).toEqual({ applied: [], }); expect(await recorded(pool)).toEqual(before); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); test('upgrades a 4.2 database', async () => { const { name, pool } = await createDatabase(); await drizzleBootstrap(pool, migrationsFolder(V4_2)); const { applied } = await migrate(pool, { migrationsFolder: MIGRATIONS }); expect(applied).toEqual(missingFrom(V4_2)); expect((await recorded(pool)).sort(byValue)).toEqual(allWhens); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); test('upgrades a 4.3 database, which drizzle fails to upgrade', async () => { const v4 = migrationsFolder(V4_3); const skipped = await createDatabase(); await drizzleBootstrap(skipped.pool, v4); await expect( drizzleBootstrap(skipped.pool, migrationsFolder(V5_5)) ).rejects.toThrow(); const { name, pool } = await createDatabase(); await drizzleBootstrap(pool, v4); const { applied } = await migrate(pool, { migrationsFolder: MIGRATIONS }); expect(applied).toEqual(missingFrom(V4_3)); expect(applied).toContain(tag('0011')); expect((await recorded(pool)).sort(byValue)).toEqual(allWhens); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); test('upgrades a 4.4 database, which drizzle leaves incomplete', async () => { const v4 = migrationsFolder(V4_4, { [tag('0027')]: V4_4_0027 }); const skipped = await createDatabase(); await drizzleBootstrap(skipped.pool, v4); await drizzleBootstrap(skipped.pool, migrationsFolder(V5_5)); expect(await schemaOf(skipped.name)).not.toEqual(await schemaOf(fresh)); const { name, pool } = await createDatabase(); await drizzleBootstrap(pool, v4); const { applied } = await migrate(pool, { migrationsFolder: MIGRATIONS }); // 4.4 recorded its own 0027, which is not applied again. expect(applied).toEqual(missingFrom(V4_4)); expect((await recorded(pool)).sort(byValue)).toEqual(allWhens); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); test('repairs a 4.4 database that drizzle already upgraded', async () => { const { name, pool } = await createDatabase(); await drizzleBootstrap( pool, migrationsFolder(V4_4, { [tag('0027')]: V4_4_0027 }) ); await drizzleBootstrap(pool, migrationsFolder(V5_5)); const upgraded = await recorded(pool); const { applied } = await migrate(pool, { migrationsFolder: MIGRATIONS }); expect(applied.length).toBe(journal.length - upgraded.length); expect(applied).toContain(tag('0011')); expect((await recorded(pool)).sort(byValue)).toEqual(allWhens); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); test('applies each migration once when two callers race', async () => { const { name, pool } = await createDatabase(); await drizzleBootstrap(pool, migrationsFolder(V4_3)); const results = await Promise.all([ migrate(pool, { migrationsFolder: MIGRATIONS }), migrate(pool, { migrationsFolder: MIGRATIONS }), ]); expect(results.map((r) => r.applied.length).sort(byValue)).toEqual([ 0, missingFrom(V4_3).length, ]); expect((await recorded(pool)).sort(byValue)).toEqual(allWhens); expect(await schemaOf(name)).toEqual(await schemaOf(fresh)); }); }); }