Files
STTracker/packages/db/src/migrate.ts
T

25 lines
975 B
TypeScript

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<string, Migration>) {}
async getMigrations(): Promise<Record<string, Migration>> {
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<void> {
const migrator = new Migrator({
db: db.k as Kysely<any>,
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 });
}
}