示例工程 38-schema-migrations-concurrency

38-schema-migrations-concurrency/demo-01-migration-runner/migrations.ts

typescript · 3.4 KB

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";

type Migration = {
  version: number;
  name: string;
  up: (db: DatabaseSync) => void;
};

function version(db: DatabaseSync): number {
  const row = db.prepare("PRAGMA user_version").get() as {
    user_version?: number;
  };
  return Number(row.user_version ?? 0);
}

function migrations(): Migration[] {
  return [
    {
      version: 1,
      name: "create-notes",
      up(db) {
        db.exec(
          "CREATE TABLE notes (id TEXT PRIMARY KEY, body TEXT NOT NULL);",
        );
      },
    },
    {
      version: 2,
      name: "add-title",
      up(db) {
        db.exec("ALTER TABLE notes ADD COLUMN title TEXT NOT NULL DEFAULT '';");
        db.exec("UPDATE notes SET title = substr(body, 1, 20);");
      },
    },
  ];
}

function run(db: DatabaseSync, target: number, list: Migration[]) {
  db.exec(
    "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);",
  );
  const from = version(db);
  const steps: Array<{ version: number; applied: boolean; error: string }> = [];
  for (const item of list
    .filter((m) => m.version > from && m.version <= target)
    .sort((a, b) => a.version - b.version)) {
    try {
      db.exec("BEGIN IMMEDIATE;");
      item.up(db);
      db.exec(`PRAGMA user_version = ${item.version};`);
      db.prepare(
        "INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
      ).run(item.version, item.name, new Date().toISOString());
      db.exec("COMMIT;");
      steps.push({ version: item.version, applied: true, error: "" });
    } catch (error) {
      db.exec("ROLLBACK;");
      steps.push({
        version: item.version,
        applied: false,
        error: error instanceof Error ? error.message : String(error),
      });
      break;
    }
  }
  return { from, to: version(db), steps };
}

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "migration-demo-"));
const db = new DatabaseSync(path.join(dir, "ok.sqlite"));
const applied = run(db, 2, migrations());
const history = db
  .prepare("SELECT COUNT(*) AS n FROM schema_migrations")
  .get() as { n: number };
const columns = (
  db.prepare("PRAGMA table_info(notes)").all() as Array<{ name: string }>
).map((row) => row.name);
db.close();

const failDb = new DatabaseSync(path.join(dir, "fail.sqlite"));
run(failDb, 1, migrations());
const broken = migrations();
broken[1] = {
  version: 2,
  name: "broken-add-title",
  up(database) {
    database.exec(
      "ALTER TABLE notes ADD COLUMN title TEXT NOT NULL DEFAULT '';",
    );
    database.exec(
      "ALTER TABLE notes ADD COLUMN title TEXT NOT NULL DEFAULT '';",
    );
  },
};
const failed = run(failDb, 2, broken);
const failColumns = (
  failDb.prepare("PRAGMA table_info(notes)").all() as Array<{ name: string }>
).map((row) => row.name);
failDb.close();

const ok =
  applied.from === 0 &&
  applied.to === 2 &&
  applied.steps.length === 2 &&
  history.n === 2 &&
  columns.includes("title") &&
  failed.from === 1 &&
  failed.to === 1 &&
  failed.steps[0]?.applied === false &&
  failed.steps[0]?.error.includes("duplicate column") === true &&
  !failColumns.includes("title");

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    applied,
    history: history.n,
    columns,
    failed,
    failColumns,
  }),
);

fs.rmSync(dir, { recursive: true, force: true });