ops-sqlite.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. const { DatabaseSync } = require('node:sqlite');
  93. db = new DatabaseSync(dbFile);
  94. db.exec('PRAGMA journal_mode = WAL');
  95. db.exec('PRAGMA busy_timeout = 5000');
  96. db.exec('PRAGMA foreign_keys = ON');
  97. return db;
  98. }
  99. async function init() {
  100. if (!initPromise) {
  101. initPromise = (async () => {
  102. const handle = open();
  103. for (const sql of DDL) handle.exec(sql);
  104. handle.prepare('INSERT INTO ops_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
  105. .run('schema_version', SCHEMA_VERSION);
  106. return true;
  107. })().catch((e) => {
  108. initPromise = null; // 允许下次重试
  109. throw e;
  110. });
  111. }
  112. return initPromise;
  113. }
  114. async function health() {
  115. try {
  116. open().prepare('SELECT 1 AS ok').get();
  117. return { ok: true, kind: 'sqlite', detail: dbFile };
  118. } catch (e) {
  119. return { ok: false, kind: 'sqlite', detail: e.message || String(e) };
  120. }
  121. }
  122. function insertUpload(upload) {
  123. open().prepare(`INSERT INTO ops_upload
  124. (id, original_name, sha256, size_bytes, uploaded_at, year, parser_kind, parser_version, report, content)
  125. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
  126. upload.id,
  127. upload.originalName,
  128. upload.sha256,
  129. upload.sizeBytes,
  130. upload.uploadedAt,
  131. upload.year,
  132. upload.parserKind,
  133. upload.parserVersion,
  134. JSON.stringify(upload.report || {}),
  135. upload.content,
  136. );
  137. }
  138. function upsertRows(rows) {
  139. const stmt = open().prepare(`INSERT INTO ops_row
  140. (date, shop_key, upload_id, shop_id, shop_name, school, status,
  141. order_cnt, revenue, exposure, click_rate, raw, quality, updated_at)
  142. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  143. ON CONFLICT(date, shop_key) DO UPDATE SET
  144. upload_id = excluded.upload_id,
  145. shop_id = excluded.shop_id,
  146. shop_name = excluded.shop_name,
  147. school = excluded.school,
  148. status = excluded.status,
  149. order_cnt = excluded.order_cnt,
  150. revenue = excluded.revenue,
  151. exposure = excluded.exposure,
  152. click_rate = excluded.click_rate,
  153. raw = excluded.raw,
  154. quality = excluded.quality,
  155. updated_at = excluded.updated_at`);
  156. const now = new Date().toISOString();
  157. for (const r of rows) {
  158. stmt.run(
  159. r.date, r.shopKey, r.uploadId, r.shopId || null, r.shopName, r.school,
  160. r.status || null, r.order_cnt, r.revenue, r.exposure, r.click_rate,
  161. JSON.stringify(r.raw || {}), JSON.stringify(r.quality || []), now,
  162. );
  163. }
  164. }
  165. function upsertShops(shops) {
  166. const stmt = open().prepare(`INSERT INTO ops_shop
  167. (key, shop_id, shop_name, school, status, last_upload_id, first_seen, last_seen)
  168. VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  169. ON CONFLICT(key) DO UPDATE SET
  170. shop_id = excluded.shop_id,
  171. shop_name = excluded.shop_name,
  172. school = excluded.school,
  173. status = excluded.status,
  174. last_upload_id = excluded.last_upload_id,
  175. last_seen = excluded.last_seen`);
  176. const now = new Date().toISOString();
  177. for (const s of shops) {
  178. stmt.run(s.key, s.shopId || null, s.shopName, s.school, s.status || null, s.lastUploadId || null, now, now);
  179. }
  180. }
  181. function deleteRowsByUpload(uploadId) {
  182. open().prepare('DELETE FROM ops_row WHERE upload_id = ?').run(uploadId);
  183. }
  184. function updateReport(id, report) {
  185. open().prepare('UPDATE ops_upload SET report = ? WHERE id = ?').run(JSON.stringify(report || {}), id);
  186. }
  187. async function withTransaction(fn) {
  188. const handle = open();
  189. handle.exec('BEGIN IMMEDIATE');
  190. try {
  191. const result = await fn({ insertUpload, upsertRows, upsertShops, deleteRowsByUpload, updateReport });
  192. handle.exec('COMMIT');
  193. // 写事务结束后做一次 checkpoint:让 data/ops.db 自包含,备份时不必关心 -wal
  194. try { handle.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* 有读事务时跳过 */ }
  195. return result;
  196. } catch (e) {
  197. try { handle.exec('ROLLBACK'); } catch { /* 事务可能已结束 */ }
  198. throw e;
  199. }
  200. }
  201. async function findUploadBySha(sha256) {
  202. const row = open().prepare('SELECT id FROM ops_upload WHERE sha256 = ? ORDER BY uploaded_at DESC LIMIT 1').get(sha256);
  203. return row ? row.id : null;
  204. }
  205. function uploadRowToApi(row) {
  206. if (!row) return null;
  207. const report = safeJson(row.report, {});
  208. return {
  209. id: row.id,
  210. originalName: row.original_name,
  211. sha256: row.sha256,
  212. sizeBytes: row.size_bytes,
  213. uploadedAt: row.uploaded_at,
  214. year: row.year,
  215. parserKind: row.parser_kind,
  216. parserVersion: row.parser_version,
  217. report,
  218. rows: report.rows || 0,
  219. shops: report.shops || 0,
  220. warningCount: report.warningCount || 0,
  221. };
  222. }
  223. async function listUploads() {
  224. return open().prepare(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  225. parser_kind, parser_version, report FROM ops_upload ORDER BY uploaded_at DESC`).all().map(uploadRowToApi);
  226. }
  227. async function getUpload(id) {
  228. const row = open().prepare(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  229. parser_kind, parser_version, report FROM ops_upload WHERE id = ?`).get(id);
  230. return uploadRowToApi(row);
  231. }
  232. async function getContent(id) {
  233. const row = open().prepare('SELECT content, original_name FROM ops_upload WHERE id = ?').get(id);
  234. if (!row) return null;
  235. return { content: Buffer.from(row.content), originalName: row.original_name };
  236. }
  237. async function queryRows({ from, to, schools, shops } = {}) {
  238. const where = [];
  239. const params = [];
  240. if (from) { where.push('date >= ?'); params.push(String(from)); }
  241. if (to) { where.push('date <= ?'); params.push(String(to)); }
  242. if (Array.isArray(schools) && schools.length) {
  243. where.push(`school IN (${schools.map(() => '?').join(',')})`);
  244. params.push(...schools.map(String));
  245. }
  246. if (Array.isArray(shops) && shops.length) {
  247. where.push(`shop_key IN (${shops.map(() => '?').join(',')})`);
  248. params.push(...shops.map(String));
  249. }
  250. const sql = `SELECT * FROM ops_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
  251. ORDER BY school ASC, shop_name ASC, date ASC`;
  252. return open().prepare(sql).all(...params).map(rowToApi);
  253. }
  254. async function summary() {
  255. const handle = open();
  256. const uploadCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_upload').get().c;
  257. const rowCount = handle.prepare('SELECT COUNT(*) AS c FROM ops_row').get().c;
  258. const range = handle.prepare('SELECT MIN(date) AS f, MAX(date) AS t FROM ops_row').get();
  259. const schools = handle.prepare('SELECT school, COUNT(*) AS c FROM ops_shop GROUP BY school ORDER BY school ASC')
  260. .all().map((r) => ({ name: r.school, shopCount: r.c }));
  261. const shops = handle.prepare('SELECT key, shop_id, shop_name, school, status FROM ops_shop ORDER BY school ASC, shop_name ASC')
  262. .all().map((r) => ({ key: r.key, shopId: r.shop_id, shopName: r.shop_name, school: r.school, status: r.status }));
  263. const last = handle.prepare(`SELECT id, original_name, uploaded_at, report FROM ops_upload
  264. ORDER BY uploaded_at DESC LIMIT 1`).get();
  265. return {
  266. schools,
  267. shops,
  268. uploadCount,
  269. rowCount,
  270. coverage: range && range.f ? { from: range.f, to: range.t } : null,
  271. lastUpload: last ? {
  272. id: last.id,
  273. at: last.uploaded_at,
  274. originalName: last.original_name,
  275. rows: (safeJson(last.report, {}) || {}).rows || 0,
  276. warningCount: (safeJson(last.report, {}) || {}).warningCount || 0,
  277. } : null,
  278. };
  279. }
  280. async function close() {
  281. if (db) {
  282. try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch { /* ignore */ }
  283. try { db.close(); } catch { /* ignore */ }
  284. db = null;
  285. initPromise = null;
  286. }
  287. }
  288. return {
  289. kind: 'sqlite',
  290. file: dbFile,
  291. init,
  292. health,
  293. withTransaction,
  294. insertUpload,
  295. upsertRows,
  296. upsertShops,
  297. deleteRowsByUpload,
  298. updateReport,
  299. findUploadBySha,
  300. listUploads,
  301. getUpload,
  302. getContent,
  303. queryRows,
  304. summary,
  305. close,
  306. };
  307. }
  308. module.exports = { createSqliteStore };