feat: SQLite 数据库初始化及模板 CRUD

This commit is contained in:
MikiVL 2026-05-05 13:34:46 +08:00
parent 68f90f4e4c
commit d92e39c936
2 changed files with 88 additions and 0 deletions

41
electron/db/init.js Normal file
View File

@ -0,0 +1,41 @@
const Database = require("better-sqlite3");
const path = require("path");
const { app } = require("electron");
const fs = require("fs");
const DB_DIR = path.join(app.getPath("userData"), "excel-batch-editor");
fs.mkdirSync(DB_DIR, { recursive: true });
const DB_PATH = path.join(DB_DIR, "app.db");
const db = new Database(DB_PATH);
db.exec(`
CREATE TABLE IF NOT EXISTS templates (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
grp TEXT DEFAULT '',
file_path TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS fields (
id TEXT PRIMARY KEY,
template_id TEXT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL,
sheet TEXT NOT NULL,
cell TEXT NOT NULL,
FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS generation_records (
id TEXT PRIMARY KEY,
template_id TEXT NOT NULL,
created_at TEXT NOT NULL,
output_dir TEXT NOT NULL,
row_count INTEGER NOT NULL
);
`);
module.exports = db;

47
electron/db/templateDb.js Normal file
View File

@ -0,0 +1,47 @@
const db = require("./init");
const { randomUUID } = require("crypto");
function listTemplates() {
const templates = db.prepare("SELECT * FROM templates ORDER BY updated_at DESC").all();
return templates.map((t) => ({
...t,
fields: db.prepare("SELECT * FROM fields WHERE template_id = ?").all(t.id),
}));
}
function saveTemplate({ name, grp = "", file_path, fields = [] }) {
const id = randomUUID();
const now = new Date().toISOString();
db.prepare(
"INSERT INTO templates (id, name, grp, file_path, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
).run(id, name, grp, file_path, now, now);
_saveFields(id, fields);
return id;
}
function updateTemplate(id, { name, grp, fields }) {
const now = new Date().toISOString();
if (name !== undefined || grp !== undefined) {
db.prepare("UPDATE templates SET name = COALESCE(?, name), grp = COALESCE(?, grp), updated_at = ? WHERE id = ?")
.run(name ?? null, grp ?? null, now, id);
}
if (fields !== undefined) {
db.prepare("DELETE FROM fields WHERE template_id = ?").run(id);
_saveFields(id, fields);
}
}
function deleteTemplate(id) {
db.prepare("DELETE FROM templates WHERE id = ?").run(id);
}
function _saveFields(templateId, fields) {
const stmt = db.prepare(
"INSERT INTO fields (id, template_id, name, type, sheet, cell) VALUES (?, ?, ?, ?, ?, ?)"
);
for (const f of fields) {
stmt.run(randomUUID(), templateId, f.name, f.type, f.sheet, f.cell);
}
}
module.exports = { listTemplates, saveTemplate, updateTemplate, deleteTemplate };