示例工程 38-schema-migrations-concurrency
38-schema-migrations-concurrency/app/shared/db.ts
import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import { ensureMeta } from "./migrations";
export function openLabDb(file: string): DatabaseSync {
fs.mkdirSync(path.dirname(file), { recursive: true });
const db = new DatabaseSync(file);
db.exec("PRAGMA journal_mode = WAL;");
db.exec("PRAGMA synchronous = NORMAL;");
db.exec("PRAGMA busy_timeout = 3000;");
ensureMeta(db);
return db;
}
export function tableNames(db: DatabaseSync): string[] {
const rows = db
.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
)
.all() as Array<{ name: string }>;
return rows.map((row) => row.name);
}
export function columnNames(db: DatabaseSync, table: string): string[] {
if (!["notes", "events", "schema_migrations"].includes(table)) return [];
const rows = db.prepare(`PRAGMA table_info(${table});`).all() as Array<{
name: string;
}>;
return rows.map((row) => row.name);
}
export function countRows(db: DatabaseSync, table: string): number {
if (!["notes", "events", "schema_migrations"].includes(table)) return 0;
const row = db.prepare(`SELECT COUNT(*) AS n FROM ${table};`).get() as
{ n?: number | bigint } | undefined;
return Number(row?.n ?? 0);
}
export function seedNotes(db: DatabaseSync): number {
const existing = countRows(db, "notes");
if (existing > 0) return 0;
const insert = db.prepare(
"INSERT INTO notes (id, body, created_at, title) VALUES (?, ?, ?, ?)",
);
const notes: Array<[string, string, string, string]> = [
[
"seed-1",
"迁移前先备份,迁移后先验证。",
"2026-11-26T08:00:00.000Z",
"迁移原则",
],
[
"seed-2",
"每个版本一个事务,失败整体回滚。",
"2026-11-26T08:01:00.000Z",
"事务边界",
],
[
"seed-3",
"单写者队列把并发写变成顺序写。",
"2026-11-26T08:02:00.000Z",
"单写者",
],
[
"seed-4",
"PRAGMA user_version 是迁移游标。",
"2026-11-26T08:03:00.000Z",
"版本游标",
],
[
"seed-5",
"WAL + busy_timeout 只是缓冲,不是并发方案。",
"2026-11-26T08:04:00.000Z",
"锁竞争",
],
];
db.exec("BEGIN IMMEDIATE;");
try {
for (const [id, body, createdAt, title] of notes) {
insert.run(id, body, createdAt, title);
}
db.exec("COMMIT;");
return notes.length;
} catch (error) {
db.exec("ROLLBACK;");
throw error;
}
}
export function removeDbFiles(file: string): void {
for (const candidate of [file, `${file}-wal`, `${file}-shm`]) {
try {
fs.rmSync(candidate, { force: true });
} catch {
// 文件不存在或被占用。
}
}
}