示例工程 37-local-persistence

37-local-persistence/demo-02-sqlite-bench/sqlite.ts

typescript · 2.3 KB

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

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sqlite-bench-"));
const file = path.join(dir, "bench.sqlite");
const count = 5000;

const db = new DatabaseSync(file);
db.exec("PRAGMA journal_mode = WAL;");
db.exec("PRAGMA synchronous = NORMAL;");
db.exec(`
  CREATE TABLE notes (
    id TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    tags TEXT NOT NULL,
    updated_at TEXT NOT NULL
  );
`);

const insert = db.prepare(
  "INSERT INTO notes (id, title, body, tags, updated_at) VALUES (?, ?, ?, ?, ?)",
);
const bodies = "SQLite 事务、WAL 与单写者基准。".repeat(6);

const writeStart = performance.now();
db.exec("BEGIN;");
try {
  for (let index = 0; index < count; index += 1) {
    insert.run(
      `note-${index}`,
      `记录 ${index}`,
      `${bodies} #${index}`,
      JSON.stringify(["bench"]),
      new Date(1_700_000_000_000 + index * 1000).toISOString(),
    );
  }
  db.exec("COMMIT;");
} catch (error) {
  db.exec("ROLLBACK;");
  throw error;
}
const writeMs = performance.now() - writeStart;

const readStart = performance.now();
const rows = db.prepare("SELECT * FROM notes").all();
const readMs = performance.now() - readStart;
const journal = db.prepare("PRAGMA journal_mode;").get() as
  { journal_mode?: string } | undefined;
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
db.close();

let bytes = 0;
for (const candidate of [file, `${file}-wal`, `${file}-shm`]) {
  try {
    bytes += fs.statSync(candidate).size;
  } catch {
    // 文件不存在。
  }
}

const reopened = new DatabaseSync(file);
const verified = reopened.prepare("SELECT COUNT(*) AS n FROM notes").get() as
  { n?: number } | undefined;
reopened.close();

const ok =
  rows.length === count &&
  Number(verified?.n ?? 0) === count &&
  journal?.journal_mode === "wal" &&
  bytes > 0;

console.log(
  JSON.stringify({
    evt: "smoke",
    ok,
    count,
    rows: rows.length,
    verified: Number(verified?.n ?? 0),
    journal: journal?.journal_mode ?? "",
    writeMs: Number(writeMs.toFixed(2)),
    readMs: Number(readMs.toFixed(2)),
    bytes,
  }),
);

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