← 中文资源

简体中文版本

幂等的版本化迁移运行器

按版本顺序执行迁移并记录到状态表:已应用的版本直接跳过,因此重复运行是幂等的;首次应用 3 条、二次应用 0 条可以直观验证。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

first run applied: 3
second run applied: 0
versions recorded: 1,2,3

实现说明

活动部件是函数 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(","));