import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { type MigrationMeta, readMigrationFiles } from 'drizzle-orm/migrator'; import type { Pool, PoolClient } from 'pg'; /** Where drizzle-kit and every earlier release recorded applied migrations. */ export const MIGRATIONS_SCHEMA = 'workflow_drizzle'; export const MIGRATIONS_TABLE = 'workflow_migrations'; export interface MigrateOptions { /** A drizzle-kit migrations folder: `meta/_journal.json` plus one SQL file per entry. */ migrationsFolder: string; } export interface MigrateResult { /** Tags of the migrations this call applied, in the order it applied them. */ applied: string[]; } /** * Applies every migration in the journal that the database has not recorded, * in journal order, in one transaction. * * A migration counts as applied when the migrations table has a row whose * `created_at` equals the journal entry's `when`, which is the value drizzle's * migrator records for it. Neither drizzle's own rule nor the hash identifies a * migration on every database this World has written: * * - Drizzle's `migrate()` applies only entries newer than the newest recorded * row. The 4.x release line shipped 0015 and 0027 without 0011-0014 and * 0016-0026, so on a database it set up those entries are older than the * newest row and drizzle never applies them: from a 4.3 database the upgrade * fails on the first migration that needs a skipped column, and from a 4.4 * database it succeeds without them. * - The hash is of the file's content, and shipped files have been edited * (0000, and 0027, whose 4.x version predates the tables of 0020 and 0025), * so matching on it would apply a migration a second time. * * Rows with a `created_at` the journal does not have (a migration a later * release added, or one an earlier release deleted) are left alone. * * A transaction-scoped advisory lock serializes concurrent callers, so a second * `bootstrap` started alongside the first waits for it and then finds nothing * left to apply. */ export async function migrate( pool: Pool, { migrationsFolder }: MigrateOptions ): Promise { const migrations = readMigrationFiles({ migrationsFolder }); const journal: { entries: { tag: string; when: number }[] } = JSON.parse( readFileSync(join(migrationsFolder, 'meta', '_journal.json'), 'utf8') ); const client = await pool.connect(); try { await client.query('BEGIN'); try { const recorded = await lockAndReadRecorded(client); const applied: string[] = []; for (const [index, migration] of migrations.entries()) { if (recorded.has(migration.folderMillis)) continue; const name = journal.entries[index]?.tag ?? String(migration.folderMillis); await apply(client, migration, name); recorded.add(migration.folderMillis); applied.push(name); } await client.query('COMMIT'); return { applied }; } catch (error) { await client.query('ROLLBACK').catch(() => {}); throw error; } } finally { client.release(); } } const TABLE = `"${MIGRATIONS_SCHEMA}"."${MIGRATIONS_TABLE}"`; /** * Takes the migration lock, creates the migrations table if this is a new * database, and returns the `created_at` of every recorded migration. */ async function lockAndReadRecorded(client: PoolClient): Promise> { await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [ `${MIGRATIONS_SCHEMA}.${MIGRATIONS_TABLE}`, ]); await client.query(`CREATE SCHEMA IF NOT EXISTS "${MIGRATIONS_SCHEMA}"`); await client.query( `CREATE TABLE IF NOT EXISTS ${TABLE} ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint )` ); const { rows } = await client.query<{ created_at: string | null }>( `SELECT created_at FROM ${TABLE}` ); return new Set(rows.map((row) => Number(row.created_at))); } /** Runs one migration's statements and records it the way drizzle does. */ async function apply( client: PoolClient, migration: MigrationMeta, name: string ): Promise { for (const statement of migration.sql) { if (statement.trim() === '') continue; try { await client.query(statement); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Migration ${name} failed: ${message}`, { cause: error, }); } } await client.query( `INSERT INTO ${TABLE} (hash, created_at) VALUES ($1, $2)`, [migration.hash, migration.folderMillis] ); }