ops-sqlite.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. 'use strict';
  2. /**
  3. * ops 存储 · SQLite 驱动(node:sqlite,零依赖)
  4. * ----------------------------------------------------------------------------
  5. * 只负责「表和读写」,不含业务判断。接口与 PG 驱动保持一致,路由层不感知方言。
  6. * 需要 Node >= 22.5(node:sqlite 内置模块)。
  7. */
  8. const fs = require('fs');
  9. const path = require('path');
  10. const SCHEMA_VERSION = '1';
  11. const DDL = [
  12. `CREATE TABLE IF NOT EXISTS ops_meta (
  13. key TEXT PRIMARY KEY,
  14. value TEXT NOT NULL
  15. )`,
  16. `CREATE TABLE IF NOT EXISTS ops_upload (
  17. id TEXT PRIMARY KEY,
  18. original_name TEXT NOT NULL,
  19. sha256 TEXT NOT NULL,
  20. size_bytes INTEGER NOT NULL,
  21. uploaded_at TEXT NOT NULL,
  22. year INTEGER NOT NULL,
  23. parser_kind TEXT NOT NULL,
  24. parser_version INTEGER NOT NULL,
  25. report TEXT NOT NULL DEFAULT '{}',
  26. content BLOB NOT NULL
  27. )`,
  28. `CREATE INDEX IF NOT EXISTS ops_upload_sha256_idx ON ops_upload (sha256, uploaded_at DESC)`,
  29. `CREATE TABLE IF NOT EXISTS ops_shop (
  30. key TEXT PRIMARY KEY,
  31. shop_id TEXT,
  32. shop_name TEXT NOT NULL,
  33. school TEXT NOT NULL,
  34. status TEXT,
  35. last_upload_id TEXT REFERENCES ops_upload(id) ON DELETE SET NULL,
  36. first_seen TEXT NOT NULL,
  37. last_seen TEXT NOT NULL
  38. )`,
  39. `CREATE TABLE IF NOT EXISTS ops_row (
  40. date TEXT NOT NULL,
  41. shop_key TEXT NOT NULL,
  42. upload_id TEXT NOT NULL REFERENCES ops_upload(id) ON DELETE CASCADE,
  43. shop_id TEXT,
  44. shop_name TEXT NOT NULL,
  45. school TEXT NOT NULL,
  46. status TEXT,
  47. order_cnt INTEGER,
  48. revenue REAL,
  49. exposure INTEGER,
  50. click_rate REAL,
  51. raw TEXT NOT NULL DEFAULT '{}',
  52. quality TEXT NOT NULL DEFAULT '[]',
  53. updated_at TEXT NOT NULL,
  54. PRIMARY KEY (date, shop_key)
  55. )`,
  56. `CREATE INDEX IF NOT EXISTS ops_row_school_date_idx ON ops_row (school, date)`,
  57. ];
  58. function rowToApi(row) {
  59. if (!row) return null;
  60. return {
  61. date: row.date,
  62. shopKey: row.shop_key,
  63. shopId: row.shop_id,
  64. shopName: row.shop_name,
  65. school: row.school,
  66. status: row.status,
  67. order_cnt: row.order_cnt,
  68. revenue: row.revenue,
  69. exposure: row.exposure,
  70. click_rate: row.click_rate,
  71. raw: safeJson(row.raw, {}),
  72. quality: safeJson(row.quality, []),
  73. uploadId: row.upload_id,
  74. updatedAt: row.updated_at,
  75. };
  76. }
  77. function safeJson(text, fallback) {
  78. try {
  79. const value = JSON.parse(text);
  80. return value == null ? fallback : value;
  81. } catch {
  82. return fallback;
  83. }
  84. }
  85. function createSqliteStore({ file }) {
  86. const dbFile = path.resolve(String(file || 'data/ops.db'));
  87. let db = null;
  88. let initPromise = null;
  89. function open() {
  90. if (db) return db;
  91. fs.mkdirSync(path.dirname(dbFile), { recursive: true });
  92. let DatabaseSync;
  93. try {
  94. ({ DatabaseSync } = require('node:sqlite'));
  95. } catch (e) {
  96. // Node < 22.5 没有内置 sqlite:单独给一个可读原因,前端据此提示升级 Node
  97. const err = new Error(`当前 Node 版本不支持内置 SQLite(需要 22.5 及以上,当前 ${process.version})`);
  98. err.reason = 'sqlite-unavailable';
  99. err.cause = e;
  100. throw err;
  101. }
  102. db = new DatabaseSync(dbFile);
  103. db.exec('PRAGMA journal_mode = WAL');
  104. db.exec('PRAGMA busy_timeout = 5000');
  105. db.exec('PRAGMA foreign_keys = ON');
  106. return db;
  107. }
  108. async function init() {
  109. if (!initPromise) {
  110. initPromise = (async () => {
  111. const handle = open();
  112. for (const sql of DDL) handle.exec(sql);
  113. handle.prepare('INSERT INTO ops_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
  114. .run('schema_version', SCHEMA_VERSION);
  115. // 建表后 checkpoint:空库阶段 data/ops.db 也是自包含的
  116. try { handle.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* ignore */ }
  117. return true;
  118. })().catch((e) => {
  119. initPromise = null; // 允许下次重试
  120. throw e;
  121. });
  122. }
  123. return initPromise;
  124. }
  125. async function health() {
  126. try {
  127. open().prepare('SELECT 1 AS ok').get();
  128. return { ok: true, kind: 'sqlite', detail: dbFile };
  129. } catch (e) {
  130. return { ok: false, kind: 'sqlite', detail: e.message || String(e) };
  131. }
  132. }
  133. function insertUpload(upload) {
  134. open().prepare(`INSERT INTO ops_upload
  135. (id, original_name, sha256, size_bytes, uploaded_at, year, parser_kind, parser_version, report, content)
  136. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
  137. upload.id,
  138. upload.originalName,
  139. upload.sha256,
  140. upload.sizeBytes,
  141. upload.uploadedAt,
  142. upload.year,
  143. upload.parserKind,
  144. upload.parserVersion,
  145. JSON.stringify(upload.report || {}),
  146. upload.content,
  147. );
  148. }
  149. function upsertRows(rows) {
  150. const stmt = open().prepare(`INSERT INTO ops_row
  151. (date, shop_key, upload_id, shop_id, shop_name, school, status,
  152. order_cnt, revenue, exposure, click_rate, raw, quality, updated_at)
  153. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  154. ON CONFLICT(date, shop_key) DO UPDATE SET
  155. upload_id = excluded.upload_id,
  156. shop_id = excluded.shop_id,
  157. shop_name = excluded.shop_name,
  158. school = excluded.school,
  159. status = excluded.status,
  160. order_cnt = excluded.order_cnt,
  161. revenue = excluded.revenue,
  162. exposure = excluded.exposure,
  163. click_rate = excluded.click_rate,
  164. raw = excluded.raw,
  165. quality = excluded.quality,
  166. updated_at = excluded.updated_at`);
  167. const now = new Date().toISOString();
  168. for (const r of rows) {
  169. stmt.run(
  170. r.date, r.shopKey, r.uploadId, r.shopId || null, r.shopName, r.school,
  171. r.status || null, r.order_cnt, r.revenue, r.exposure, r.click_rate,
  172. JSON.stringify(r.raw || {}), JSON.stringify(r.quality || []), now,
  173. );
  174. }
  175. }
  176. function upsertShops(shops) {
  177. const stmt = open().prepare(`INSERT INTO ops_shop
  178. (key, shop_id, shop_name, school, status, last_upload_id, first_seen, last_seen)
  179. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  180. ON CONFLICT(key) DO UPDATE SET
  181. shop_id = excluded.shop_id,
  182. shop_name = excluded.shop_name,
  183. school = excluded.school,
  184. status = excluded.status,
  185. last_upload_id = excluded.last_upload_id,
  186. last_seen = excluded.last_seen`);
  187. const now = new Date().toISOString();
  188. for (const s of shops) {
  189. stmt.run(s.key, s.shopId || null, s.shopName, s.school, s.status || null, s.lastUploadId || null, now, now);
  190. }
  191. }
  192. function deleteRowsByUpload(uploadId) {
  193. open().prepare('DELETE FROM ops_row WHERE upload_id = ?').run(uploadId);
  194. }
  195. function deleteRowsBySha(sha256) {
  196. open().prepare('DELETE FROM ops_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = ?)').run(sha256);
  197. }
  198. function pruneOrphanShops() {
  199. open().prepare('DELETE FROM ops_shop WHERE key NOT IN (SELECT DISTINCT shop_key FROM ops_row)').run();
  200. }
  201. function updateReport(id, report) {
  202. open().prepare('UPDATE ops_upload SET report = ? WHERE id = ?').run(JSON.stringify(report || {}), id);
  203. }
  204. async function withTransaction(fn) {
  205. const handle = open();
  206. handle.exec('BEGIN IMMEDIATE');
  207. try {
  208. const result = await fn({ insertUpload, upsertRows, upsertShops, deleteRowsByUpload, deleteRowsBySha, pruneOrphanShops, updateReport });
  209. handle.exec('COMMIT');
  210. // 写事务结束后做一次 checkpoint:让 data/ops.db 自包含,备份时不必关心 -wal
  211. try { handle.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* 有读事务时跳过 */ }
  212. return result;
  213. } catch (e) {
  214. try { handle.exec('ROLLBACK'); } catch { /* 事务可能已结束 */ }
  215. throw e;
  216. }
  217. }
  218. async function findUploadBySha(sha256) {
  219. const row = open().prepare('SELECT id FROM ops_upload WHERE sha256 = ? ORDER BY uploaded_at DESC LIMIT 1').get(sha256);
  220. return row ? row.id : null;
  221. }
  222. function uploadRowToApi(row) {
  223. if (!row) return null;
  224. const report = safeJson(row.report, {});
  225. return {
  226. id: row.id,
  227. originalName: row.original_name,
  228. sha256: row.sha256,
  229. sizeBytes: row.size_bytes,
  230. uploadedAt: row.uploaded_at,
  231. year: row.year,
  232. parserKind: row.parser_kind,
  233. parserVersion: row.parser_version,
  234. report,
  235. rows: report.rows || 0,
  236. shops: report.shops || 0,
  237. warningCount: report.warningCount || 0,
  238. };
  239. }
  240. async function listUploads() {
  241. return open().prepare(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  242. parser_kind, parser_version, report FROM ops_upload ORDER BY uploaded_at DESC`).all().map(uploadRowToApi);
  243. }
  244. async function getUpload(id) {
  245. const row = open().prepare(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  246. parser_kind, parser_version, report FROM ops_upload WHERE id = ?`).get(id);
  247. return uploadRowToApi(row);
  248. }
  249. async function getContent(id) {
  250. const row = open().prepare('SELECT content, original_name FROM ops_upload WHERE id = ?').get(id);
  251. if (!row) return null;
  252. return { content: Buffer.from(row.content), originalName: row.original_name };
  253. }
  254. async function queryRows({ from, to, schools, shops } = {}) {
  255. const where = [];
  256. const params = [];
  257. if (from) { where.push('date >= ?'); params.push(String(from)); }
  258. if (to) { where.push('date <= ?'); params.push(String(to)); }
  259. if (Array.isArray(schools) && schools.length) {
  260. where.push(`school IN (${schools.map(() => '?').join(',')})`);
  261. params.push(...schools.map(String));
  262. }
  263. if (Array.isArray(shops) && shops.length) {
  264. where.push(`shop_key IN (${shops.map(() => '?').join(',')})`);
  265. params.push(...shops.map(String));
  266. }
  267. const sql = `SELECT * FROM ops_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
  268. ORDER BY school ASC, shop_name ASC, date ASC`;
  269. return open().prepare(sql).all(...params).map(rowToApi);
  270. }
  271. async function summary() {
  272. const handle = open();
  273. const uploadCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_upload').get().c;
  274. const rowCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_row').get().c;
  275. const range = handle.prepare('SELECT MIN(date) AS f, MAX(date) AS t FROM ops_row').get();
  276. const schools = handle.prepare('SELECT school, COUNT(*) AS c FROM ops_shop GROUP BY school ORDER BY school ASC')
  277. .all().map((r) => ({ name: r.school, shopCount: r.c }));
  278. const shops = handle.prepare('SELECT key, shop_id, shop_name, school, status FROM ops_shop ORDER BY school ASC, shop_name ASC')
  279. .all().map((r) => ({ key: r.key, shopId: r.shop_id, shopName: r.shop_name, school: r.school, status: r.status }));
  280. const last = handle.prepare(`SELECT id, original_name, uploaded_at, report FROM ops_upload
  281. ORDER BY uploaded_at DESC LIMIT 1`).get();
  282. return {
  283. schools,
  284. shops,
  285. uploadCount,
  286. rowCount,
  287. coverage: range && range.f ? { from: range.f, to: range.t } : null,
  288. lastUpload: last ? {
  289. id: last.id,
  290. at: last.uploaded_at,
  291. originalName: last.original_name,
  292. rows: (safeJson(last.report, {}) || {}).rows || 0,
  293. warningCount: (safeJson(last.report, {}) || {}).warningCount || 0,
  294. } : null,
  295. };
  296. }
  297. async function close() {
  298. if (db) {
  299. try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* ignore */ }
  300. try { db.close(); } catch { /* ignore */ }
  301. db = null;
  302. initPromise = null;
  303. }
  304. }
  305. return {
  306. kind: 'sqlite',
  307. file: dbFile,
  308. init,
  309. health,
  310. withTransaction,
  311. insertUpload,
  312. upsertRows,
  313. upsertShops,
  314. deleteRowsByUpload,
  315. updateReport,
  316. findUploadBySha,
  317. listUploads,
  318. getUpload,
  319. getContent,
  320. queryRows,
  321. summary,
  322. close,
  323. };
  324. }
  325. module.exports = { createSqliteStore };