实现说明
活动部件是函数 runMigrations。
这个文件只在 for (const migration of pending) 里循环。
使用要点
- 跑完文件,输出里会留下标记——
first run applied:、second run applied:、versions recorded:。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 runMigrations。
主要签名是 function runMigrations(state: Map<number, string>, pending: readonly Migration[])
核心语句
readonly up: (state: Map<number, string>) => void;
const schema = new Map<number, string>();
applied += 1;
代码示例
// Versioned migration runner: applied versions live in state, migrations
// run in order, and a re-run skips everything already applied
interface Migration {
readonly version: number;
readonly up: (state: Map<number, string>) => void;
}
const migrations: readonly Migration[] = [
{ version: 1, up: (state) => state.set(1, "created orders table") },
{ version: 2, up: (state) => state.set(2, "added orders.status column") },
{ version: 3, up: (state) => state.set(3, "created orders_status index") },
];
function runMigrations(state: Map<number, string>, pending: readonly Migration[]): number {
let applied = 0;
for (const migration of pending) {
if (state.has(migration.version)) continue; // idempotent: skip applied
migration.up(state);
applied += 1;
}
return applied;
}
const schema = new Map<number, string>();
console.log("first run applied:", runMigrations(schema, migrations));
console.log("second run applied:", runMigrations(schema, migrations));
console.log("versions recorded:", [...schema.keys()].sort().join(","));