示例工程 37-local-persistence

37-local-persistence/app/.tsc/shared/sqlite-store.js

javascript · 2.4 KB

import fs from "node:fs";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
export function openStore(file) {
    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;");
    db.exec(`
    CREATE TABLE IF NOT EXISTS notes (
      id TEXT PRIMARY KEY,
      title TEXT NOT NULL,
      body TEXT NOT NULL,
      tags TEXT NOT NULL,
      updated_at TEXT NOT NULL
    );
  `);
    return db;
}
export function countNotes(db) {
    const row = db.prepare("SELECT COUNT(*) AS n FROM notes").get();
    return Number(row?.n ?? 0);
}
export function insertNote(db, note) {
    db.prepare("INSERT OR REPLACE INTO notes (id, title, body, tags, updated_at) VALUES (?, ?, ?, ?, ?)").run(note.id, note.title, note.body, JSON.stringify(note.tags), note.updatedAt);
}
export function listNotes(db, limit = 5) {
    const rows = db
        .prepare("SELECT id, title, body, tags, updated_at FROM notes ORDER BY updated_at DESC LIMIT ?")
        .all(limit);
    return rows.map((row) => ({
        id: row.id,
        title: row.title,
        body: row.body,
        tags: parseTags(row.tags),
        updatedAt: row.updated_at,
    }));
}
function parseTags(text) {
    try {
        const value = JSON.parse(text);
        return Array.isArray(value)
            ? value.filter((tag) => typeof tag === "string")
            : [];
    }
    catch {
        return [];
    }
}
export function journalMode(db) {
    const row = db.prepare("PRAGMA journal_mode;").get();
    return row?.journal_mode ?? "";
}
export function seedIfEmpty(db, notes) {
    if (countNotes(db) > 0)
        return 0;
    db.exec("BEGIN;");
    try {
        for (const note of notes)
            insertNote(db, note);
        db.exec("COMMIT;");
        return notes.length;
    }
    catch (error) {
        db.exec("ROLLBACK;");
        throw error;
    }
}
export function sqliteSize(file) {
    let bytes = 0;
    for (const candidate of [file, `${file}-wal`, `${file}-shm`]) {
        try {
            bytes += fs.statSync(candidate).size;
        }
        catch {
            // 文件不存在。
        }
    }
    return bytes;
}
export function closeStore(db) {
    try {
        db?.close();
    }
    catch {
        // 已关闭。
    }
}
//# sourceMappingURL=sqlite-store.js.map