


























@@ -0,0 +1,67 @@
1+import type { DatabaseSync } from "node:sqlite";
2+import { afterEach, describe, expect, it, vi } from "vitest";
3+import {
4+DEFAULT_SQLITE_WAL_AUTOCHECKPOINT_PAGES,
5+configureSqliteWalMaintenance,
6+} from "./sqlite-wal.js";
7+8+function createMockDb(): DatabaseSync {
9+return {
10+exec: vi.fn(),
11+} as unknown as DatabaseSync;
12+}
13+14+describe("sqlite WAL maintenance", () => {
15+afterEach(() => {
16+vi.useRealTimers();
17+});
18+19+it("enables WAL mode and explicit autocheckpointing", () => {
20+const db = createMockDb();
21+22+configureSqliteWalMaintenance(db, { checkpointIntervalMs: 0 });
23+24+expect(db.exec).toHaveBeenNthCalledWith(1, "PRAGMA journal_mode = WAL;");
25+expect(db.exec).toHaveBeenNthCalledWith(
26+2,
27+`PRAGMA wal_autocheckpoint = ${DEFAULT_SQLITE_WAL_AUTOCHECKPOINT_PAGES};`,
28+);
29+});
30+31+it("runs periodic TRUNCATE checkpoints and stops them on close", () => {
32+vi.useFakeTimers();
33+const db = createMockDb();
34+35+const maintenance = configureSqliteWalMaintenance(db, { checkpointIntervalMs: 100 });
36+expect(db.exec).toHaveBeenCalledTimes(2);
37+38+vi.advanceTimersByTime(100);
39+expect(db.exec).toHaveBeenLastCalledWith("PRAGMA wal_checkpoint(TRUNCATE);");
40+expect(db.exec).toHaveBeenCalledTimes(3);
41+42+expect(maintenance.close()).toBe(true);
43+expect(db.exec).toHaveBeenCalledTimes(4);
44+45+vi.advanceTimersByTime(200);
46+expect(db.exec).toHaveBeenCalledTimes(4);
47+});
48+49+it("reports checkpoint errors without throwing from background maintenance", () => {
50+const db = createMockDb();
51+const error = new Error("busy");
52+const onCheckpointError = vi.fn();
53+vi.mocked(db.exec).mockImplementation((sql) => {
54+if (sql.includes("wal_checkpoint")) {
55+throw error;
56+}
57+});
58+59+const maintenance = configureSqliteWalMaintenance(db, {
60+checkpointIntervalMs: 0,
61+ onCheckpointError,
62+});
63+64+expect(maintenance.checkpoint()).toBe(false);
65+expect(onCheckpointError).toHaveBeenCalledWith(error);
66+});
67+});
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。