ops-pg.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. 'use strict';
  2. /**
  3. * ops 存储 · PostgreSQL 驱动
  4. * ----------------------------------------------------------------------------
  5. * 与 SQLite 驱动同接口。`pg` 为可选依赖(本期不安装):未安装时 health() 返回明确原因,
  6. * 只有「店铺运营」功能不可用,服务与其它功能不受影响。
  7. *
  8. * 上线切换步骤见设计文档 §5.6:改 config.storage.driver = "postgres" + 填连接串 + npm i pg。
  9. */
  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 timestamptz NOT NULL,
  22. year integer NOT NULL,
  23. parser_kind text NOT NULL,
  24. parser_version integer NOT NULL,
  25. report jsonb NOT NULL DEFAULT '{}'::jsonb,
  26. content bytea 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 timestamptz NOT NULL,
  37. last_seen timestamptz NOT NULL
  38. )`,
  39. `CREATE TABLE IF NOT EXISTS ops_row (
  40. date char(8) 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 numeric(14,2),
  49. exposure integer,
  50. click_rate numeric(8,6),
  51. raw jsonb NOT NULL DEFAULT '{}'::jsonb,
  52. quality text[] NOT NULL DEFAULT '{}',
  53. updated_at timestamptz 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 char(8) 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 jsonb NOT NULL DEFAULT '{}'::jsonb,
  64. updated_at timestamptz 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: String(row.date || '').trim(),
  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 == null ? null : Number(row.order_cnt),
  79. revenue: row.revenue == null ? null : Number(row.revenue),
  80. exposure: row.exposure == null ? null : Number(row.exposure),
  81. click_rate: row.click_rate == null ? null : Number(row.click_rate),
  82. raw: row.raw || {},
  83. quality: row.quality || [],
  84. uploadId: row.upload_id,
  85. updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : row.updated_at,
  86. };
  87. }
  88. function createPgStore({ connectionString, ssl = true, max = 5, schema = 'public', connectTimeoutMs = 10000 }) {
  89. let pool = null;
  90. let initPromise = null;
  91. function getPool() {
  92. if (pool) return pool;
  93. let pg;
  94. try {
  95. pg = require('pg');
  96. } catch {
  97. const err = new Error('未安装 pg(npm i pg)');
  98. err.reason = 'pg-not-installed';
  99. throw err;
  100. }
  101. pool = new pg.Pool({
  102. connectionString,
  103. max: Number(max) || 5,
  104. ssl: ssl ? { rejectUnauthorized: false } : false,
  105. connectionTimeoutMillis: Number(connectTimeoutMs) || 10000,
  106. options: `-c search_path=${schema || 'public'}`,
  107. });
  108. return pool;
  109. }
  110. async function init() {
  111. if (!initPromise) {
  112. initPromise = (async () => {
  113. const client = await getPool().connect();
  114. try {
  115. for (const sql of DDL) await client.query(sql);
  116. await client.query(
  117. 'INSERT INTO ops_meta (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value',
  118. ['schema_version', SCHEMA_VERSION],
  119. );
  120. } finally {
  121. client.release();
  122. }
  123. return true;
  124. })().catch((e) => {
  125. initPromise = null;
  126. throw e;
  127. });
  128. }
  129. return initPromise;
  130. }
  131. async function health() {
  132. try {
  133. await getPool().query('SELECT 1 AS ok');
  134. return { ok: true, kind: 'postgres', detail: (schema || 'public') };
  135. } catch (e) {
  136. return { ok: false, kind: 'postgres', detail: e.message || String(e) };
  137. }
  138. }
  139. async function withTransaction(fn) {
  140. const client = await getPool().connect();
  141. try {
  142. await client.query('BEGIN');
  143. const result = await fn(makeTx(client));
  144. await client.query('COMMIT');
  145. return result;
  146. } catch (e) {
  147. try { await client.query('ROLLBACK'); } catch { /* 已结束 */ }
  148. throw e;
  149. } finally {
  150. client.release();
  151. }
  152. }
  153. function makeTx(client) {
  154. return {
  155. async insertUpload(upload) {
  156. await client.query(
  157. `INSERT INTO ops_upload (id, original_name, sha256, size_bytes, uploaded_at, year,
  158. parser_kind, parser_version, report, content)
  159. VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
  160. [upload.id, upload.originalName, upload.sha256, upload.sizeBytes, upload.uploadedAt,
  161. upload.year, upload.parserKind, upload.parserVersion, JSON.stringify(upload.report || {}), upload.content],
  162. );
  163. },
  164. async upsertRows(rows) {
  165. const now = new Date().toISOString();
  166. for (const r of rows) {
  167. await client.query(
  168. `INSERT INTO ops_row (date, shop_key, upload_id, shop_id, shop_name, school, status,
  169. order_cnt, revenue, exposure, click_rate, raw, quality, updated_at)
  170. VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
  171. ON CONFLICT (date, shop_key) DO UPDATE SET
  172. upload_id = EXCLUDED.upload_id, shop_id = EXCLUDED.shop_id, shop_name = EXCLUDED.shop_name,
  173. school = EXCLUDED.school, status = EXCLUDED.status, order_cnt = EXCLUDED.order_cnt,
  174. revenue = EXCLUDED.revenue, exposure = EXCLUDED.exposure, click_rate = EXCLUDED.click_rate,
  175. raw = EXCLUDED.raw, quality = EXCLUDED.quality, updated_at = EXCLUDED.updated_at`,
  176. [r.date, r.shopKey, r.uploadId, r.shopId || null, r.shopName, r.school, r.status || null,
  177. r.order_cnt, r.revenue, r.exposure, r.click_rate,
  178. JSON.stringify(r.raw || {}), r.quality || [], now],
  179. );
  180. }
  181. },
  182. async upsertShops(shops) {
  183. const now = new Date().toISOString();
  184. for (const s of shops) {
  185. await client.query(
  186. `INSERT INTO ops_shop (key, shop_id, shop_name, school, status, last_upload_id, first_seen, last_seen)
  187. VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
  188. ON CONFLICT (key) DO UPDATE SET
  189. shop_id = EXCLUDED.shop_id, shop_name = EXCLUDED.shop_name, school = EXCLUDED.school,
  190. status = EXCLUDED.status, last_upload_id = EXCLUDED.last_upload_id, last_seen = EXCLUDED.last_seen`,
  191. [s.key, s.shopId || null, s.shopName, s.school, s.status || null, s.lastUploadId || null, now, now],
  192. );
  193. }
  194. },
  195. async deleteRowsByUpload(uploadId) {
  196. await client.query('DELETE FROM ops_row WHERE upload_id = $1', [uploadId]);
  197. },
  198. async upsertPlatformRows(rows) {
  199. const now = new Date().toISOString();
  200. for (const r of rows) {
  201. await client.query(
  202. `INSERT INTO ops_platform_row (date, shop_id, upload_id, school, shop_name, data, updated_at)
  203. VALUES ($1,$2,$3,$4,$5,$6,$7)
  204. ON CONFLICT (date, shop_id) DO UPDATE SET
  205. upload_id = EXCLUDED.upload_id, school = EXCLUDED.school,
  206. shop_name = EXCLUDED.shop_name, data = EXCLUDED.data, updated_at = EXCLUDED.updated_at`,
  207. [r.date, r.shopId, r.uploadId, r.school || '', r.shopName || '', JSON.stringify(r.data || {}), now],
  208. );
  209. }
  210. },
  211. async deletePlatformRowsByUpload(uploadId) {
  212. await client.query('DELETE FROM ops_platform_row WHERE upload_id = $1', [uploadId]);
  213. },
  214. async deletePlatformRowsBySha(sha256) {
  215. await client.query('DELETE FROM ops_platform_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = $1)', [sha256]);
  216. },
  217. async deleteRowsBySha(sha256) {
  218. await client.query('DELETE FROM ops_row WHERE upload_id IN (SELECT id FROM ops_upload WHERE sha256 = $1)', [sha256]);
  219. },
  220. async pruneOrphanShops() {
  221. await client.query('DELETE FROM ops_shop s WHERE NOT EXISTS (SELECT 1 FROM ops_row r WHERE r.shop_key = s.key)');
  222. },
  223. async updateReport(id, report) {
  224. await client.query('UPDATE ops_upload SET report = $1 WHERE id = $2', [JSON.stringify(report || {}), id]);
  225. },
  226. };
  227. }
  228. async function findUploadBySha(sha256) {
  229. const r = await getPool().query('SELECT id FROM ops_upload WHERE sha256 = $1 ORDER BY uploaded_at DESC LIMIT 1', [sha256]);
  230. return r.rows.length ? r.rows[0].id : null;
  231. }
  232. function uploadRowToApi(row) {
  233. if (!row) return null;
  234. const report = row.report || {};
  235. return {
  236. id: row.id,
  237. originalName: row.original_name,
  238. sha256: row.sha256,
  239. sizeBytes: row.size_bytes,
  240. uploadedAt: row.uploaded_at instanceof Date ? row.uploaded_at.toISOString() : row.uploaded_at,
  241. year: row.year,
  242. parserKind: row.parser_kind,
  243. parserVersion: row.parser_version,
  244. report,
  245. rows: report.rows || 0,
  246. shops: report.shops || 0,
  247. warningCount: report.warningCount || 0,
  248. };
  249. }
  250. async function listUploads() {
  251. const r = await getPool().query(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  252. parser_kind, parser_version, report FROM ops_upload ORDER BY uploaded_at DESC`);
  253. return r.rows.map(uploadRowToApi);
  254. }
  255. async function getUpload(id) {
  256. const r = await getPool().query(`SELECT id, original_name, sha256, size_bytes, uploaded_at, year,
  257. parser_kind, parser_version, report FROM ops_upload WHERE id = $1`, [id]);
  258. return uploadRowToApi(r.rows[0]);
  259. }
  260. async function getContent(id) {
  261. const r = await getPool().query('SELECT content, original_name FROM ops_upload WHERE id = $1', [id]);
  262. if (!r.rows.length) return null;
  263. return { content: r.rows[0].content, originalName: r.rows[0].original_name };
  264. }
  265. async function queryRows({ from, to, schools, shops } = {}) {
  266. const where = [];
  267. const params = [];
  268. if (from) { params.push(String(from)); where.push(`date >= $${params.length}`); }
  269. if (to) { params.push(String(to)); where.push(`date <= $${params.length}`); }
  270. if (Array.isArray(schools) && schools.length) { params.push(schools.map(String)); where.push(`school = ANY($${params.length})`); }
  271. if (Array.isArray(shops) && shops.length) { params.push(shops.map(String)); where.push(`shop_key = ANY($${params.length})`); }
  272. const sql = `SELECT * FROM ops_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''}
  273. ORDER BY school ASC, shop_name ASC, date ASC`;
  274. const r = await getPool().query(sql, params);
  275. return r.rows.map(rowToApi);
  276. }
  277. async function queryPlatformRows({ from, to } = {}) {
  278. const where = [];
  279. const params = [];
  280. if (from) { params.push(String(from)); where.push(`date >= ${params.length}`); }
  281. if (to) { params.push(String(to)); where.push(`date <= ${params.length}`); }
  282. const sql = `SELECT * FROM ops_platform_row ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY date ASC, shop_id ASC`;
  283. const r = await getPool().query(sql, params);
  284. return r.rows.map((row) => ({
  285. date: String(row.date).trim(),
  286. shopId: row.shop_id,
  287. uploadId: row.upload_id,
  288. school: row.school,
  289. shopName: row.shop_name,
  290. data: row.data || {},
  291. updatedAt: row.updated_at instanceof Date ? row.updated_at.toISOString() : row.updated_at,
  292. }));
  293. }
  294. async function summary() {
  295. const poolRef = getPool();
  296. const [uploadCount, rowCount, platformRowCount, range, matrix, schools, shops, last] = await Promise.all([
  297. poolRef.query('SELECT COUNT(*)::int AS c FROM ops_upload'),
  298. poolRef.query('SELECT COUNT(*)::int AS c FROM ops_row'),
  299. poolRef.query('SELECT COUNT(*)::int AS c FROM ops_platform_row'),
  300. poolRef.query(`SELECT MIN(d) AS f, MAX(d) AS t FROM (
  301. SELECT date AS d FROM ops_row UNION SELECT date AS d FROM ops_platform_row)`),
  302. poolRef.query(`SELECT COUNT(*)::int AS c FROM (
  303. SELECT date, shop_key FROM ops_row UNION SELECT date, shop_id FROM ops_platform_row)`),
  304. poolRef.query(`SELECT school, COUNT(DISTINCT shop)::int AS c FROM (
  305. SELECT school, shop_id AS shop FROM ops_platform_row WHERE school <> ''
  306. UNION SELECT school, shop_key AS shop FROM ops_row WHERE school <> ''
  307. UNION SELECT school, key AS shop FROM ops_shop WHERE school <> ''
  308. ) AS t GROUP BY school ORDER BY school ASC`),
  309. poolRef.query(`SELECT key, MAX(shop_id) AS shop_id, MAX(shop_name) AS shop_name,
  310. MAX(school) AS school, MAX(status) AS status FROM (
  311. SELECT key, shop_id, shop_name, school, status FROM ops_shop
  312. UNION ALL
  313. SELECT shop_id AS key, shop_id, shop_name, school, NULL AS status FROM ops_platform_row
  314. ) AS t GROUP BY key ORDER BY school ASC, shop_name ASC`),
  315. poolRef.query('SELECT id, original_name, uploaded_at, report FROM ops_upload ORDER BY uploaded_at DESC LIMIT 1'),
  316. ]);
  317. return {
  318. schools: schools.rows.map((r) => ({ name: r.school, shopCount: r.c })),
  319. shops: shops.rows.map((r) => ({ key: r.key, shopId: r.shop_id, shopName: r.shop_name, school: r.school, status: r.status })),
  320. uploadCount: uploadCount.rows[0].c,
  321. rowCount: rowCount.rows[0].c,
  322. platformRowCount: platformRowCount.rows[0].c,
  323. matrixRowCount: matrix.rows[0].c,
  324. coverage: range.rows[0] && range.rows[0].f ? { from: String(range.rows[0].f).replace(/-/g, ''), to: String(range.rows[0].t).replace(/-/g, '') } : null,
  325. lastUpload: last.rows.length ? {
  326. id: last.rows[0].id,
  327. at: last.rows[0].uploaded_at instanceof Date ? last.rows[0].uploaded_at.toISOString() : last.rows[0].uploaded_at,
  328. originalName: last.rows[0].original_name,
  329. rows: (last.rows[0].report || {}).rows || 0,
  330. warningCount: (last.rows[0].report || {}).warningCount || 0,
  331. } : null,
  332. };
  333. }
  334. async function close() {
  335. if (pool) {
  336. try { await pool.end(); } catch { /* ignore */ }
  337. pool = null;
  338. initPromise = null;
  339. }
  340. }
  341. return {
  342. kind: 'postgres',
  343. init,
  344. health,
  345. withTransaction,
  346. findUploadBySha,
  347. queryPlatformRows,
  348. listUploads,
  349. getUpload,
  350. getContent,
  351. queryRows,
  352. summary,
  353. close,
  354. };
  355. }
  356. module.exports = { createPgStore };