import fs from "node:fs"; import path from "node:path"; import { DatabaseSync } from "node:sqlite"; import type { Note } from "./json-store"; export type SqliteInfo = { available: boolean; error: string; }; export function openStore(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;"); 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: DatabaseSync): number { const row = db.prepare("SELECT COUNT(*) AS n FROM notes").get() as { n?: number | bigint } | undefined; return Number(row?.n ?? 0); } export function insertNote(db: DatabaseSync, note: Note): void { 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: DatabaseSync, limit = 5): Note[] { const rows = db .prepare( "SELECT id, title, body, tags, updated_at FROM notes ORDER BY updated_at DESC LIMIT ?", ) .all(limit) as Array<{ id: string; title: string; body: string; tags: string; updated_at: string; }>; return rows.map((row) => ({ id: row.id, title: row.title, body: row.body, tags: parseTags(row.tags), updatedAt: row.updated_at, })); } function parseTags(text: string): string[] { try { const value: unknown = JSON.parse(text); return Array.isArray(value) ? value.filter((tag): tag is string => typeof tag === "string") : []; } catch { return []; } } export function journalMode(db: DatabaseSync): string { const row = db.prepare("PRAGMA journal_mode;").get() as { journal_mode?: string } | undefined; return row?.journal_mode ?? ""; } export function seedIfEmpty(db: DatabaseSync, notes: Note[]): number { 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: string): number { 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: DatabaseSync | null): void { try { db?.close(); } catch { // 已关闭。 } }