343 lines
8.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* SQLite 通用轻量存储工具
*
* 特性:
* - 自动创建 DB 文件在应用数据目录(开发态在项目根,打包态在 ProgramData/printServer)
* - WAL 模式,支持并发读写
* - 同步 API,简单直接
* - 表辅助器(TableHelper):insert / update / delete / find / count
*
* 用法:
* import db from '../utils/db.js';
* db.exec('CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT, ts INTEGER)');
* db.table('logs').insert({ msg: 'hello', ts: Date.now() });
* const rows = db.table('logs').where({ msg: 'hello' }).orderBy('ts', 'desc').limit(10).find();
*/
import Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { getAppDataDir, isElectronRuntime } from './runtime.js';
let _instance = null;
class DB {
constructor() {
if (_instance) return _instance;
_instance = this;
this._db = null;
this._stmtCache = new Map();
this._open();
}
// ─── 生命周期 ───
_open() {
const dir = getAppDataDir();
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const dbPath = path.join(dir, 'printserver.db');
this._db = new Database(dbPath);
this._db.pragma('journal_mode = WAL');
this._db.pragma('foreign_keys = ON');
console.log('[DB] 已打开:', dbPath);
}
/**
* 关闭数据库(进程退出前调用)
*/
close() {
if (this._db) {
this._stmtCache.clear();
this._db.close();
this._db = null;
_instance = null;
console.log('[DB] 已关闭');
}
}
/**
* 获取底层 better-sqlite3 实例(高级用法)
*/
raw() {
return this._db;
}
// ─── 原生 SQL ───
/**
* 执行一条或多条 SQL(不返回行)
*/
exec(sql) {
return this._db.exec(sql);
}
/**
* 执行 INSERT / UPDATE / DELETE / DDL
* @returns {{ changes: number, lastInsertRowid: number|bigint }}
*/
run(sql, ...params) {
const stmt = this._prepare(sql);
return stmt.run(...params);
}
/**
* 查询单行
* @returns {object|undefined}
*/
get(sql, ...params) {
const stmt = this._prepare(sql);
return stmt.get(...params);
}
/**
* 查询多行
* @returns {object[]}
*/
all(sql, ...params) {
const stmt = this._prepare(sql);
return stmt.all(...params);
}
/**
* 迭代查询(大数据集)
*/
iterate(sql, ...params) {
const stmt = this._prepare(sql);
return stmt.iterate(...params);
}
/**
* 事务包装
*/
transaction(fn) {
const txn = this._db.transaction(fn);
return txn();
}
// ─── 表辅助器 ───
/**
* 获取表辅助器,提供链式 CRUD
* @param {string} tableName
* @returns {TableHelper}
*/
table(tableName) {
return new TableHelper(this, tableName);
}
// ─── 内部 ───
_prepare(sql) {
let stmt = this._stmtCache.get(sql);
if (!stmt) {
stmt = this._db.prepare(sql);
this._stmtCache.set(sql, stmt);
}
return stmt;
}
}
// ─── 表辅助器 ───
class TableHelper {
constructor(db, tableName) {
this._db = db;
this._table = tableName;
this._where = [];
this._whereParams = [];
this._order = '';
this._limitVal = null;
this._offsetVal = null;
this._selectCols = '*';
}
/**
* 等值条件:.where({ name: 'foo', status: 1 })
*/
where(conditions) {
for (const [key, value] of Object.entries(conditions)) {
this._where.push(`${key} = ?`);
this._whereParams.push(value);
}
return this;
}
/**
* 自定义条件:.whereRaw('age > ? AND name LIKE ?', 18, '%张%')
*/
whereRaw(clause, ...params) {
this._where.push(clause);
this._whereParams.push(...params);
return this;
}
/**
* 排序:.orderBy('id', 'desc') 或 .orderBy('name')
*/
orderBy(column, direction = 'asc') {
const dir = direction.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
this._order = `ORDER BY ${column} ${dir}`;
return this;
}
/**
* 限制行数
*/
limit(n) {
this._limitVal = n;
return this;
}
/**
* 偏移
*/
offset(n) {
this._offsetVal = n;
return this;
}
/**
* 指定查询列:.select('id, name')
*/
select(cols) {
this._selectCols = cols;
return this;
}
// ─── 查询方法 ───
/**
* 查询多行
*/
find() {
const { sql, params } = this._buildSelect();
return this._db.all(sql, ...params);
}
/**
* 查询单行
*/
first() {
this._limitVal = 1;
const rows = this.find();
return rows[0] || null;
}
/**
* 计数
*/
count() {
let whereClause = '';
const params = [...this._whereParams];
if (this._where.length > 0) {
whereClause = 'WHERE ' + this._where.join(' AND ');
}
const sql = `SELECT COUNT(*) as cnt FROM ${this._table} ${whereClause}`;
const row = this._db.get(sql, ...params);
return row ? row.cnt : 0;
}
/**
* 是否存在
*/
exists() {
return this.count() > 0;
}
// ─── 写入方法 ───
/**
* 插入一行
* @returns {{ changes: number, lastInsertRowid: number|bigint }}
*/
insert(data) {
const keys = Object.keys(data);
const values = Object.values(data);
const placeholders = keys.map(() => '?').join(', ');
const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})`;
return this._db.run(sql, ...values);
}
/**
* 批量插入
*/
insertMany(rows) {
if (rows.length === 0) return 0;
const keys = Object.keys(rows[0]);
const placeholders = keys.map(() => '?').join(', ');
const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})`;
const stmt = this._db._prepare(sql);
const insertAll = this._db.raw().transaction((items) => {
for (const row of items) {
stmt.run(...keys.map(k => row[k]));
}
});
insertAll(rows);
return rows.length;
}
/**
* 更新满足条件的行
*/
update(data) {
const setClauses = Object.keys(data).map(k => `${k} = ?`);
const setParams = Object.values(data);
const whereClause = this._where.length > 0 ? 'WHERE ' + this._where.join(' AND ') : '';
const sql = `UPDATE ${this._table} SET ${setClauses.join(', ')} ${whereClause}`;
return this._db.run(sql, ...setParams, ...this._whereParams);
}
/**
* 删除满足条件的行
*/
delete() {
const whereClause = this._where.length > 0 ? 'WHERE ' + this._where.join(' AND ') : '';
const sql = `DELETE FROM ${this._table} ${whereClause}`;
return this._db.run(sql, ...this._whereParams);
}
/**
* UPSERT:存在则更新,不存在则插入
* 需要表有 UNIQUE 约束
*/
upsert(data, conflictColumns) {
const keys = Object.keys(data);
const values = Object.values(data);
const placeholders = keys.map(() => '?').join(', ');
const updates = keys.map(k => `${k} = excluded.${k}`).join(', ');
const conflict = conflictColumns ? conflictColumns.join(', ') : keys[0];
const sql = `INSERT INTO ${this._table} (${keys.join(', ')}) VALUES (${placeholders})
ON CONFLICT(${conflict}) DO UPDATE SET ${updates}`;
return this._db.run(sql, ...values);
}
// ─── 内部 ───
_buildSelect() {
let sql = `SELECT ${this._selectCols} FROM ${this._table}`;
const params = [...this._whereParams];
if (this._where.length > 0) {
sql += ' WHERE ' + this._where.join(' AND ');
}
if (this._order) {
sql += ' ' + this._order;
}
if (this._limitVal !== null) {
sql += ' LIMIT ?';
params.push(this._limitVal);
}
if (this._offsetVal !== null) {
sql += ' OFFSET ?';
params.push(this._offsetVal);
}
return { sql, params };
}
}
export default new DB();