示例工程 38-schema-migrations-concurrency
38-schema-migrations-concurrency/app/.tsc/shared/contention.js
import { DatabaseSync } from "node:sqlite";
import { performance } from "node:perf_hooks";
import { removeDbFiles } from "./db";
function message(error) {
return error instanceof Error ? error.message : String(error);
}
export function probeContention(file) {
removeDbFiles(file);
const a = new DatabaseSync(file);
a.exec("PRAGMA journal_mode = WAL;");
a.exec("CREATE TABLE probe (id INTEGER PRIMARY KEY, v TEXT NOT NULL);");
const b = new DatabaseSync(file);
b.exec("PRAGMA busy_timeout = 0;");
let busyMessage = "";
let busyCode = "";
let retryOk = false;
a.exec("BEGIN IMMEDIATE;");
a.prepare("INSERT INTO probe (v) VALUES (?)").run("a");
const started = performance.now();
try {
b.prepare("INSERT INTO probe (v) VALUES (?)").run("b");
}
catch (error) {
busyMessage = message(error);
busyCode = String(error.code ?? "");
}
const waitedMs = performance.now() - started;
a.exec("ROLLBACK;");
try {
b.prepare("INSERT INTO probe (v) VALUES (?)").run("retry");
retryOk = true;
}
catch {
retryOk = false;
}
a.close();
b.close();
removeDbFiles(file);
return {
busyMessage,
busyCode,
waitedMs: Number(waitedMs.toFixed(2)),
retryOk,
at: Date.now(),
};
}
//# sourceMappingURL=contention.js.map