import type { Kysely } from "kysely"; import { Migrator, type Migration, type MigrationProvider } from "kysely/migration"; import type { Db } from "./db.ts"; import { migrations } from "./migrations/index.ts"; class StaticMigrationProvider implements MigrationProvider { constructor(private readonly all: Record) {} async getMigrations(): Promise> { return this.all; } } /** Apply every pending migration; throws on the first failure. A no-op when there are none. */ export async function migrateToLatest(db: Db): Promise { const migrator = new Migrator({ db: db.k as Kysely, provider: new StaticMigrationProvider(migrations), }); const { error, results } = await migrator.migrateToLatest(); if (error) { const failed = results?.find((r) => r.status === "Error")?.migrationName; throw new Error(`Migration ${failed ?? "(unknown)"} failed: ${String(error)}`, { cause: error }); } }