ops-sqlite.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. `CREATE TABLE IF NOT EXISTS ops_platform_row (
  58. date TEXT NOT NULL,
  59. shop_id TEXT NOT NULL,
  60. upload_id TEXT NOT NULL REFERENCES ops_upload(id) ON DELETE CASCADE,
  61. school TEXT NOT NULL DEFAULT '',
  62. shop_name TEXT NOT NULL DEFAULT '',
  63. data TEXT NOT NULL DEFAULT '{}',
  64. updated_at TEXT NOT NULL,
  65. PRIMARY KEY (date, shop_id)
  66. )`,
  67. `CREATE INDEX IF NOT EXISTS ops_platform_row_date_idx ON ops_platform_row (date)`,
  68. ];
  69. function rowToApi(row) {
  70. if (!row) return null;
  71. return {
  72. date: row.date,
  73. shopKey: row.shop_key,
  74. shopId: row.shop_id,
  75. shopName: row.shop_name,
  76. school: row.school,
  77. status: row.status,
  78. order_cnt: row.order_cnt,
  79. revenue: row.revenue,
  80. exposure: row.exposure,
  81. click_rate: row.click_rate,
  82. raw: safeJson(row.raw, {}),
  83. quality: safeJson(row.quality, []),
  84. uploadId: row.upload_id,
  85. updatedAt: row.updated_at,
  86. };
  87. }
  88. function safeJson(text, fallback) {
  89. try {
  90. const value = JSON.parse(text);
  91. return value == null ? fallback : value;
  92. } catch {
  93. return fallback;
  94. }
  95. }
  96. function createSqliteStore({ file }) {
  97. const dbFile = path.resolve(String(file || 'data/ops.db'));
  98. let db = null;
  99. let initPromise = null;
  100. function open() {
  101. if (db) return db;
  102. fs.mkdirSync(path.dirname(dbFile), { recursive: true });
  103. let DatabaseSync;
  104. try {
  105. ({ DatabaseSync } = require('node:sqlite'));
  106. } catch (e) {
  107. // Node < 22.5 没有内置 sqlite:单独给一个可读原因,前端据此提示升级 Node
  108. const err = new Error(`当前 Node 版本不支持内置 SQLite(需要 22.5 及以上,当前 ${process.version})`);
  109. err.reason = 'sqlite-unavailable';
  110. err.cause = e;
  111. throw err;
  112. }
  113. db = new DatabaseSync(dbFile);
  114. db.exec('PRAGMA journal_mode = WAL');
  115. db.exec('PRAGMA busy_timeout = 5000');
  116. db.exec('PRAGMA foreign_keys = ON');
  117. return db;
  118. }
  119. async function init() {
  120. if (!initPromise) {
  121. initPromise = (async () => {
  122. const handle = open();
  123. for (const sql of DDL) handle.exec(sql);
  124. handle.prepare('INSERT INTO ops_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
  125. .run('schema_version', SCHEMA_VERSION);
  126. // 建表后 checkpoint:空库阶段 data/ops.db 也是自包含的
  127. try { handle.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* ignore */ }
  128. return true;
  129. })().catch((e) => {
  130. initPromise = null; // 允许下次重试
  131. throw e;
  132. });
  133. }
  134. return initPromise;
  135. }
  136. async function health() {
  137. try {
  138. open().prepare('SELECT 1 AS ok').get();
  139. return { ok: true, kind: 'sqlite', detail: dbFile };
  140. } catch (e) {
  141. return { ok: false, kind: 'sqlite', detail: e.message || String(e) };
  142. }
  143. }
  144. function insertUpload(upload) {
  145. open().prepare(`INSERT INTO ops_upload
  146. (id, original_name, sha256, size_bytes, uploaded_at, year, parser_kind, parser_version, report, content)
  147. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
  148. upload.id,
  149. upload.originalName,
  150. upload.sha256,
  151. upload.sizeBytes,
  152. upload.uploadedAt,
  153. upload.year,
  154. upload.parserKind,
  155. upload.parserVersion,
  156. JSON.stringify(upload.report || {}),
  157. upload.content,
  158. );
  159. }
  160. function upsertRows(rows) {
  161. const stmt = open().prepare(`INSERT INTO ops_row
  162. (date, shop_key, upload_id, shop_id, shop_name, school, status,
  163. order_cnt, revenue, exposure, click_rate, raw, quality, updated_at)
  164. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  165. ON CONFLICT(date, shop_key) DO UPDATE SET
  166. upload_id = excluded.upload_id,
  167. shop_id = excluded.shop_id,
  168. shop_name = excluded.shop_name,
  169. school = excluded.school,
  170. status = excluded.status,
  171. order_cnt = excluded.order_cnt,
  172. revenue = excluded.revenue,
  173. exposure = excluded.exposure,
  174. click_rate = excluded.click_rate,
  175. raw = excluded.raw,
  176. quality = excluded.quality,
  177. updated_at = excluded.updated_at`);
  178. const now = new Date().toISOString();
  179. for (const r of rows) {
  180. stmt.run(
  181. r.date, r.shopKey, r.uploadId, r.shopId || null, r.shopName, r.school,
  182. r.status || null, r.order_cnt, r.revenue, r.exposure, r.click_rate,
  183. JSON.stringify(r.raw || {}), JSON.stringify(r.quality || []), now,
  184. );
  185. }
  186. }
  187. function upsertShops(shops) {
  188. const stmt = open().prepare(`INSERT INTO ops_shop
  189. (key, shop_id, shop_name, school, status, last_upload_id, first_seen, last_seen)
  190. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  191. ON CONFLICT(key) DO UPDATE SET
  192. shop_id = excluded.shop_id,
  193. shop_name = excluded.shop_name,
  194. school = excluded.school,
  195. status = excluded.status,
  196. last_upload_id = excluded.last_upload_id,
  197. last_seen = excluded.last_seen`);
  198. const now = new Date().toISOString();
  199. for (const s of shops) {
  200. stmt.run(s.key, s.shopId || null, s.shopName, s.school, s.status || null, s.lastUploadId || null, now, now);
  201. }
  202. }
  203. function deleteRowsByUpload(uploadId) {
  204. open().prepare('DELETE FROM ops_row WHERE upload_id = ?').run(uploadId);
  205. }
  206. function upsertPlatformRows(rows) {
  207. const stmt = open().prepare(`INSERT INTO ops_platform_row
  208. (date, shop_id, upload_id, school, shop_name, data, updated_at)
  209. VALUES (?, ?, ?, ?, ?, ?, ?)
  210. ON CONFLICT(date, shop_id) DO UPDATE SET
  211. upload_id = excluded.upload_id,
  212. school = excluded.school,
  213. shop_name = excluded.shop_name,
  214. data = excluded.data,
  215. updated_at = excluded.updated_at`);
  216. const now = new Date().toISOString();
  217. for (const r of rows) {
  218. stmt.run(r.date, r.shopId, r.uploadId, r.school || '', r.shopName || '', JSON.stringify(r.data || {}), now);
  219. }
  220. }
  221. function deletePlatformRowsByUpload(uploadId) {
  222. open().prepare('DELETE FROM ops_platform_row WHERE upload_id = ?').run(uploadId);
  223. }
  224. function deletePlatformRowsBySha(sha256) {
  225. open().prepare('DELETE FROM ops_platform_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = ?)').run(sha256);
  226. }
  227. async function queryPlatformRows({ from, to } = {}) {
  228. const where = [];
  229. const params = [];
  230. if (from) { where.push('date >= ?'); params.push(String(from)); }
  231. if (to) { where.push('date <= ?'); params.push(String(to)); }
  232. const sql = `SELECT * FROM ops_platform_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY date ASC, shop_id ASC`;
  233. return open().prepare(sql).all(...params).map((row) => ({
  234. date: row.date,
  235. shopId: row.shop_id,
  236. uploadId: row.upload_id,
  237. school: row.school,
  238. shopName: row.shop_name,
  239. data: safeJson(row.data, {}),
  240. updatedAt: row.updated_at,
  241. }));
  242. }
  243. function deleteRowsBySha(sha256) {
  244. open().prepare('DELETE FROM ops_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = ?)').run(sha256);
  245. }
  246. function pruneOrphanShops() {
  247. open().prepare('DELETE FROM ops_shop WHERE key NOT IN (SELECT DISTINCT shop_key FROM ops_row)').run();
  248. }
  249. function updateReport(id, report) {
  250. open().prepare('UPDATE ops_upload SET report = ? WHERE id = ?').run(JSON.stringify(report || {}), id);
  251. }
  252. async function withTransaction(fn) {
  253. const handle = open();
  254. handle.exec('BEGIN IMMEDIATE');
  255. try {
  256. const result = await fn({ insertUpload, upsertRows, upsertShops, upsertPlatformRows, deleteRowsByUpload, deleteRowsBySha, deletePlatformRowsByUpload, deletePlatformRowsBySha, pruneOrphanShops, updateReport });
  257. handle.exec('COMMIT');
  258. // 写事务结束后做一次 checkpoint:让 data/ops.db 自包含,备份时不必关心 -wal
  259. try { handle.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* 有读事务时跳过 */ }
  260. return result;
  261. } catch (e) {
  262. try { handle.exec('ROLLBACK'); } catch { /* 事务可能已结束 */ }
  263. throw e;
  264. }
  265. }
  266. async function findUploadBySha(sha256) {
  267. const row = open().prepare('SELECT id FROM ops_upload WHERE sha256 = ? ORDER BY uploaded_at DESC LIMIT 1').get(sha256);
  268. return row ? row.id : null;
  269. }
  270. function uploadRowToApi(row) {
  271. if (!row) return null;
  272. const report = safeJson(row.report, {});
  273. return {
  274. id: row.id,
  275. originalName: row.original_name,
  276. sha256: row.sha256,
  277. sizeBytes: row.size_bytes,
  278. uploadedAt: row.uploaded_at,
  279. year: row.year,
  280. parserKind: row.parser_kind,
  281. parserVersion: row.parser_version,
  282. report,
  283. rows: report.rows || 0,
  284. shops: report.shops || 0,
  285. warningCount: report.warningCount || 0,
  286. };
  287. }
  288. async function listUploads() {
  289. return open().prepare(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  290. parser_kind, parser_version, report FROM ops_upload ORDER BY uploaded_at DESC`).all().map(uploadRowToApi);
  291. }
  292. async function getUpload(id) {
  293. const row = open().prepare(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  294. parser_kind, parser_version, report FROM ops_upload WHERE id = ?`).get(id);
  295. return uploadRowToApi(row);
  296. }
  297. async function getContent(id) {
  298. const row = open().prepare('SELECT content, original_name FROM ops_upload WHERE id = ?').get(id);
  299. if (!row) return null;
  300. return { content: Buffer.from(row.content), originalName: row.original_name };
  301. }
  302. async function queryRows({ from, to, schools, shops } = {}) {
  303. const where = [];
  304. const params = [];
  305. if (from) { where.push('date >= ?'); params.push(String(from)); }
  306. if (to) { where.push('date <= ?'); params.push(String(to)); }
  307. if (Array.isArray(schools) && schools.length) {
  308. where.push(`school IN (${schools.map(() => '?').join(',')})`);
  309. params.push(...schools.map(String));
  310. }
  311. if (Array.isArray(shops) && shops.length) {
  312. where.push(`shop_key IN (${shops.map(() => '?').join(',')})`);
  313. params.push(...shops.map(String));
  314. }
  315. const sql = `SELECT * FROM ops_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
  316. ORDER BY school ASC, shop_name ASC, date ASC`;
  317. return open().prepare(sql).all(...params).map(rowToApi);
  318. }
  319. async function summary() {
  320. const handle = open();
  321. const uploadCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_upload').get().c;
  322. const rowCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_row').get().c;
  323. const platformRowCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_platform_row').get().c;
  324. const range = handle.prepare(`SELECT MIN(d) AS f, MAX(d) AS t FROM (
  325. SELECT date AS d FROM ops_row UNION SELECT date AS d FROM ops_platform_row)`).get();
  326. const matrixRowCount = handle.prepare(`SELECT COUNT(*) AS c FROM (
  327. SELECT date, shop_key FROM ops_row UNION SELECT date, shop_id FROM ops_platform_row)`).get().c;
  328. const schools = handle.prepare(`SELECT school, COUNT(DISTINCT shop) AS c FROM (
  329. SELECT school, shop_id AS shop FROM ops_platform_row WHERE school <> ''
  330. UNION SELECT school, shop_key AS shop FROM ops_row WHERE school <> ''
  331. UNION SELECT school, key AS shop FROM ops_shop WHERE school <> ''
  332. ) GROUP BY school ORDER BY school ASC`)
  333. .all().map((r) => ({ name: r.school, shopCount: r.c }));
  334. const shops = handle.prepare(`SELECT key, MAX(shop_id) AS shop_id, MAX(shop_name) AS shop_name,
  335. MAX(school) AS school, MAX(status) AS status FROM (
  336. SELECT key, shop_id, shop_name, school, status FROM ops_shop
  337. UNION ALL
  338. SELECT shop_id AS key, shop_id, shop_name, school, NULL AS status FROM ops_platform_row
  339. ) GROUP BY key ORDER BY school ASC, shop_name ASC`)
  340. .all().map((r) => ({ key: r.key, shopId: r.shop_id, shopName: r.shop_name, school: r.school, status: r.status }));
  341. const last = handle.prepare(`SELECT id, original_name, uploaded_at, report FROM ops_upload
  342. ORDER BY uploaded_at DESC LIMIT 1`).get();
  343. return {
  344. schools,
  345. shops,
  346. uploadCount,
  347. rowCount,
  348. platformRowCount,
  349. matrixRowCount,
  350. coverage: range && range.f ? { from: range.f, to: range.t } : null,
  351. lastUpload: last ? {
  352. id: last.id,
  353. at: last.uploaded_at,
  354. originalName: last.original_name,
  355. rows: (safeJson(last.report, {}) || {}).rows || 0,
  356. warningCount: (safeJson(last.report, {}) || {}).warningCount || 0,
  357. } : null,
  358. };
  359. }
  360. async function close() {
  361. if (db) {
  362. try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* ignore */ }
  363. try { db.close(); } catch { /* ignore */ }
  364. db = null;
  365. initPromise = null;
  366. }
  367. }
  368. return {
  369. kind: 'sqlite',
  370. file: dbFile,
  371. init,
  372. health,
  373. withTransaction,
  374. insertUpload,
  375. upsertRows,
  376. upsertShops,
  377. deleteRowsByUpload,
  378. updateReport,
  379. findUploadBySha,
  380. queryPlatformRows,
  381. listUploads,
  382. getUpload,
  383. getContent,
  384. queryRows,
  385. summary,
  386. close,
  387. };
  388. }
  389. module.exports = { createSqliteStore };