Files
admin d8a9d16d2c feat: JNPF 7.0 通用资产包独立分发,示例数据与官方 init SQL 对齐
- 新增 pack-jnpf-assets.sh:web 构建产物 + 示例数据库种子按 JNPF 版本单独出包,
  与 sspf 版本、OS/CPU、工具链解耦;manifest 声明版本绑定,SHA256SUMS 可逐项校验。
- demo_seed.sql 以官方 jnpf_dbnull_init.sql 为真源:58 表 / 14242 行,
  补齐行政区划、国际化、地图三张表,DDL 幂等可重复启动。
- 新增 SSW_ASSETS_DIR / SSW_DEMO_SEED_FILE 外置加载,编译期内嵌为兜底;
  换 JNPF 版本的演示数据无需重编二进制;release.sh 以资产包为 web/ 唯一真源,
  并加 --no-web 剥离选项。
- 修 SSW_STATIC_DIR 相对路径在 PGlite chdir 后失效;补 14 张官方图标并加
  /api/file/Image 精确白名单,其它 /api/** 仍保持信封 404。
- 新增 65 页 A/B 走查报告与 CHANGELOG v0.5.0 条目:UI/路由/接口形状与
  init SQL 基础数据页已 1:1,运行时业务数据页差异源于参考库额外演示数据。
2026-11-06 15:50:15 +08:00

323 lines
15 KiB
Python
Raw Permalink 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.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""gen-demo-seed.py —— 从官方 JNPF 7.0 init SQL 裁剪出「示例数据」资源文件。
用途
----
生成 `src/backend/db/demo_seed.sql`(**编译期内嵌进二进制** ⇒ 随版本包分发)
⇒ 空库启动就有官方示例数据,与官方「用示例数据初始化」出来的库**长得一样**。
为什么需要这把尺子
------------------
本仓的种子(`sspf_core::seed`)只种「**结构**」(系统 / 角色 / 菜单 / admin / 几本字典)
⇒ 官方前端的**列表页全是空的**(实测:官方 65 个可比页面里 31 个「数据少」、
23 个端点「官方有数据、ssw 空」)⇒ 空库启动和官方**长得完全不一样**。
用法
----
python3 scripts/gen-demo-seed.py # 用默认官方路径
python3 scripts/gen-demo-seed.py --src <init.sql> # 指定官方初始库
退出码:0 正常 / 2 前置错误(找不到官方初始库)
规则:
1. 引号感知切分(与 Rust `split_sql_statements` 同款)⇒ 字符串内的 `;` 不切错。
2. 排除 5 张纯大表(占原文 88% 体积)+ 7 张本仓自管表(撞复合主键)。
3. 补齐 13 张「示例系统专用表」的 DDL(官方原文里有,本仓 schema 里没有)。
4. 列裁剪:3 张 `ext_*` 表本仓形状与官方不同 ⇒ 只保留两边都有的列(**列与值同步裁**)。
5. 部分保留:`base_province` / `base_language` / `base_province_atlas`
官方有数据但体积大 ⇒ 裁列 + `base_province` 再裁掉街道级(见 `PARTIAL`)。
6. 幂等化:每条 INSERT 加 `ON CONFLICT DO NOTHING`。
"""
import re, os, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCHEMA = os.path.join(ROOT, 'src/backend/db/schema.sql')
DST = os.path.join(ROOT, 'src/backend/db/demo_seed.sql')
# 🔴 官方初始库路径:可用 `--src` 覆盖(默认是本机官方源码树的位置)。
DEFAULT_SRC = '/Users/xs/Desktop/workspace/jnpf/7.0/database/PostgreSQL/jnpf_dbnull_init.sql'
EXCLUDE = {
# 5 张纯大表:占原文 88% 体积(blade_visual_map 72.68MB / data_report / report_* )
# 🔴 这几张是「可视化设计器 / 报表」的数据源,本仓对应的页面另有数据源 ⇒ 不导。
'blade_visual_map',
'data_report', 'report_charts', 'report_user', 'report_department',
# 7 张本仓自管表:由 seed.rs / menus.rs 负责,灌入会撞复合主键
'base_module', 'base_system', 'base_user', 'base_role',
'base_organize', 'base_position', 'base_standing',
}
CROP = {
'ext_customer': {'f_contact_tel', 'f_en_code', 'f_full_name'},
'ext_document': {'f_upload_url'},
'ext_table_example': {
'f_cost_amount', 'f_customer_name', 'f_interaction_date', 'f_jack_stands',
'f_postil_count', 'f_principal', 'f_project_code', 'f_project_name',
'f_project_phase', 'f_project_type', 'f_projected_income',
'f_register_date', 'f_registrant', 'f_tunes_amount',
},
}
# 🔴 **三张「裁列 + 裁行」的表** —— 官方 init SQL 里有数据,但本仓只要用得上的部分。
#
# 背景(实测 A/B 走查 v4,官方 web@30093 vs ssw 静态包@30010):
# `/api/system/Area/-1` 官方 34 行 / ssw 0 行 ⇒ 行政区划页空
# `/api/system/BaseLang` 官方 20 行 / ssw 0 行 ⇒ 国际化页空
# `/api/system/atlas` 官方有 / ssw 空 ⇒ 地图页空
#
# | 表 | 官方全量 | 本仓保留 | 理由 |
# |---|---|---|---|
# | `base_province` | 45411 行 / 12.0 MB | **f_type ≤ 3**(4061 行 / 1.06 MB) | 省级(34)+市(369)+区(3658) 三级;街道(41350) 用不到,砍掉省 90% 体积 |
# | `base_language` | 4614 行 / 1.27 MB | 全量(裁列后) | 翻译标记,本仓 schema 有这张表 |
# | `base_province_atlas` | 3210 行 / 1.07 MB | 全量(裁列后) | 地图省市区 + 中心点坐标 |
#
# 🔴 **裁列**:只留「列表页真的在读」的列,去掉 4 个审计列(`f_creator_time` 等)+
# `f_description`(长文本)⇒ 体积省 ~40%,语义不变。
#
# 🔴 **裁行**:`base_province` 用 `f_type`(层级序号 1/2/3/4)切前三级。
PARTIAL = {
'base_province': {
'keep': ['f_id', 'f_parent_id', 'f_en_code', 'f_full_name', 'f_quick_query',
'f_type', 'f_sort_code', 'f_enabled_mark', 'f_delete_mark', 'f_tenant_id'],
'row_filter': lambda vals, idx: vals[idx['f_type']] in ("'1'", "'2'", "'3'"),
},
'base_language': {
'keep': ['f_id', 'f_group_id', 'f_en_code', 'f_full_name', 'f_language',
'f_type', 'f_enabled_mark', 'f_sort_code', 'f_delete_mark', 'f_tenant_id'],
},
'base_province_atlas': {
'keep': ['f_id', 'f_parent_id', 'f_en_code', 'f_full_name', 'f_quick_query',
'f_type', 'f_division_code', 'f_atlas_center', 'f_enabled_mark',
'f_sort_code', 'f_delete_mark', 'f_tenant_id'],
},
}
def split_sql(text):
"""与 Rust `sspf_store::db::split_sql_statements` 同款切分。"""
out = []; cur = []; i = 0; n = len(text)
while i < n:
c = text[i]
if c == '-' and i + 1 < n and text[i+1] == '-':
cur.append(' '); i += 2
while i < n and text[i] != '\n': i += 1
continue
if c == '/' and i + 1 < n and text[i+1] == '*':
cur.append(' '); depth = 1; i += 2
while i < n:
if text[i] == '/' and i+1 < n and text[i+1] == '*': depth += 1; i += 2; continue
if text[i] == '*' and i+1 < n and text[i+1] == '/':
depth -= 1; i += 2
if depth == 0: break
continue
if text[i] == '\n': cur.append('\n')
i += 1
continue
if c == "'":
cur.append("'"); i += 1
while i < n:
ch = text[i]
if ch == "'":
if i+1 < n and text[i+1] == "'": cur.append("''"); i += 2; continue
cur.append("'"); i += 1; break
cur.append(ch); i += 1
continue
if c == '"':
cur.append('"'); i += 1
while i < n:
if text[i] == '"':
if i+1 < n and text[i+1] == '"': cur.append('""'); i += 2; continue
cur.append('"'); i += 1; break
cur.append(text[i]); i += 1
continue
if c == ';':
s = ''.join(cur).strip()
if s: out.append(s)
cur = []; i += 1; continue
cur.append(c); i += 1
s = ''.join(cur).strip()
if s: out.append(s)
return out
def split_values(body):
"""按逗号切 VALUES 里的值(尊重单引号串,'' 为转义)。"""
vals = []; buf = []; q = False; i = 0; n = len(body)
while i < n:
c = body[i]
if q:
if c == "'":
if i+1 < n and body[i+1] == "'": buf.append("''"); i += 2; continue
q = False; buf.append("'"); i += 1; continue
buf.append(c); i += 1; continue
if c == "'": q = True; buf.append("'"); i += 1; continue
if c == ',': vals.append(''.join(buf).strip()); buf = []; i += 1; continue
buf.append(c); i += 1
vals.append(''.join(buf).strip())
return vals
def parse_cols(block):
cols = []
for line in block.split('\n'):
line = line.strip().rstrip(',')
if not line or line.upper().startswith(
('PRIMARY KEY', 'CONSTRAINT', 'UNIQUE', 'FOREIGN KEY', 'INDEX', 'CHECK', '--')):
continue
m = re.match(r'"?([a-z_0-9]+)"?\s+[A-Za-z]', line)
if m: cols.append(m.group(1).lower())
return cols
def main():
src_path = DEFAULT_SRC
if len(sys.argv) > 2 and sys.argv[1] == '--src':
src_path = sys.argv[2]
if not os.path.isfile(src_path):
print(f'❌ 找不到官方初始库: {src_path}\n'
f' 用法: python3 scripts/gen-demo-seed.py [--src <jnpf_dbnull_init.sql>]',
file=sys.stderr)
sys.exit(2)
sql = open(src_path, encoding='utf-8', errors='replace').read()
schema = open(SCHEMA, encoding='utf-8').read()
schema_tables = {}
for m in re.finditer(
r'CREATE TABLE\s+(?:IF NOT EXISTS\s+)?(?:public\.)?"?([a-z_0-9]+)"?\s*\((.*?)\n\)',
schema, re.S | re.I):
schema_tables[m.group(1).lower()] = parse_cols(m.group(2))
stmts = split_sql(sql)
ddls = {}
rows_by_table = {} # 表名 → [(cols, vals)]
for s in stmts:
m = re.match(r'CREATE TABLE\s+(?:IF NOT EXISTS\s+)?(?:public\.)?"?([a-z_0-9]+)"?\s*\((.*?)\n\)',
s, re.S | re.I)
if m:
ddls.setdefault(m.group(1).lower(), s)
continue
m = re.match(r'INSERT INTO\s+([a-z_0-9]+)\s*\(([^)]*)\)\s*VALUES\s*\((.*)\)\s*$',
s, re.S | re.I)
if not m:
continue
t = m.group(1).lower()
cols = [c.strip() for c in m.group(2).split(',')]
vals = split_values(m.group(3))
if len(cols) != len(vals):
print(f'⚠️ {t}: 列 {len(cols)} ≠ 值 {len(vals)} ⇒ 跳过', file=sys.stderr)
continue
rows_by_table.setdefault(t, []).append((cols, vals))
total_ins = sum(len(v) for v in rows_by_table.values())
print(f'切分: {len(stmts)} 条语句 / {total_ins} 条 INSERT / {len(ddls)} 张表的 DDL',
file=sys.stderr)
# ---- 逐表过滤 + 列裁剪(列与值同步裁)----
kept = {} # 表名 → {'cols': [...], 'rows': [(vals)]}
need_ddl = set()
for t, rows in rows_by_table.items():
if t in EXCLUDE:
continue
if t in PARTIAL:
# 🔴 **部分保留**:官方形状但裁列(+ 可选裁行)。
spec = PARTIAL[t]
keep_cols = list(spec['keep'])
col_idx = {c.lower(): i for i, c in enumerate(rows[0][0])}
missing = [c for c in keep_cols if c not in col_idx]
if missing:
print(f'⚠️ {t}: 官方表无此列 {missing} ⇒ 整表跳过', file=sys.stderr)
continue
keep_idx = [col_idx[c] for c in keep_cols]
# 本仓 schema 必须有这些列(否则插不进去)。
if t in schema_tables:
unknown = [c for c in keep_cols if c not in schema_tables[t]]
if unknown:
print(f'⚠️ {t}: 本仓 schema 无此列 {unknown} ⇒ 整表跳过', file=sys.stderr)
continue
row_filter = spec.get('row_filter')
if row_filter:
rows = [(c, v) for c, v in rows if row_filter(v, col_idx)]
kept[t] = {'cols': keep_cols, 'rows': [[v[i] for i in keep_idx] for _, v in rows]}
continue
if t not in schema_tables:
# 本仓 schema 没有 ⇒ 用官方 DDL 建表 ⇒ 列**不裁**(官方形状照搬)
need_ddl.add(t)
keep_idx = list(range(len(rows[0][0])))
keep_cols = list(rows[0][0])
else:
drop = CROP.get(t, set())
keep_idx = [i for i, c in enumerate(rows[0][0]) if c.lower() not in drop]
keep_cols = [rows[0][0][i] for i in keep_idx]
unknown = [c for c in keep_cols if c.lower() not in schema_tables[t]]
if unknown:
print(f'⚠️ {t}: 本仓 schema 无此列 {unknown} ⇒ 整表跳过', file=sys.stderr)
continue
kept[t] = {'cols': keep_cols, 'rows': [[v[i] for i in keep_idx] for _, v in rows]}
print(f'保留: {len(kept)} 张表 / {sum(len(v["rows"]) for v in kept.values())} 条行', file=sys.stderr)
print(f'需补 DDL: {len(need_ddl)} 张 ⇒ {sorted(need_ddl)}', file=sys.stderr)
# ---- 生成输出 ----
out = []
out.append('-- ============================================================================')
out.append('-- JNPF 7.0 官方示例数据(裁剪版)')
out.append('-- ============================================================================')
out.append('--')
out.append('-- 真源:jnpf/7.0/database/PostgreSQL/jnpf_dbnull_init.sql(官方 7.0 初始库)')
out.append('-- 生成:scripts/gen-demo-seed.py(引号感知切分 ⇒ 字符串内的 `;` 不切错)')
out.append('--')
out.append(f'-- 保留 {len(kept)} 张表 / {sum(len(v["rows"]) for v in kept.values())} 条示例行。')
out.append('--')
out.append('-- 排除 5 张纯大表(占原文 88% 体积):blade_visual_map / data_report /')
out.append('-- report_charts / report_user / report_department')
out.append('-- 排除 7 张本仓自管表(撞复合主键,由 seed.rs / menus.rs 负责):')
out.append('-- base_module / base_system / base_user / base_role /')
out.append('-- base_organize / base_position / base_standing')
out.append('-- 部分保留(裁列 + 裁行,见 scripts/gen-demo-seed.py 的 PARTIAL):')
out.append('-- base_province(只留 f_type<=3 的省/市/区,砍掉街道级)/')
out.append('-- base_language / base_province_atlas')
out.append('--')
out.append('-- 🔴 每条 INSERT 都带 `ON CONFLICT DO NOTHING` ⇒ **幂等**:')
out.append('-- 重复启动不炸、不覆盖人工改动(官方 id 是雪花 id,不与已有行相撞)。')
out.append('')
need_ddl = sorted(need_ddl & set(ddls))
if need_ddl:
out.append('-- ---------------------------------------------------------------------------')
out.append('-- 【DDL】示例系统专用表(本仓 schema 里没有 ⇒ 先建表)')
out.append('-- ---------------------------------------------------------------------------')
for t in need_ddl:
out.append('')
# 🔴 **幂等**:示例 DDL 每次启动都会执行(ensure_demo_data 每次启动跑),
# 第二次启动时表已存在 ⇒ 普通 CREATE TABLE 会报「表已存在」把 stderr 刷满。
# 一律归一化为 `CREATE TABLE IF NOT EXISTS`(剥离官方原文里可能有的 IF NOT EXISTS)。
ddl = re.sub(
r'^CREATE TABLE\s+(?:IF NOT EXISTS\s+)?',
'CREATE TABLE IF NOT EXISTS ',
ddls[t].strip(),
count=1,
flags=re.I,
)
out.append(ddl + ';')
out.append('')
out.append('-- ---------------------------------------------------------------------------')
out.append('-- 【DATA】示例数据')
out.append('-- ---------------------------------------------------------------------------')
for t in sorted(kept):
info = kept[t]
out.append('')
out.append(f'-- {t}({len(info["rows"])} 行)')
cols_sql = ', '.join(info['cols'])
for v in info['rows']:
out.append(f'INSERT INTO {t} ({cols_sql}) VALUES (')
out.append(' ' + ', '.join(v))
out.append(') ON CONFLICT DO NOTHING;')
open(DST, 'w', encoding='utf-8').write('\n'.join(out) + '\n')
print(f'写出 {DST}({os.path.getsize(DST)} bytes)', file=sys.stderr)
if __name__ == '__main__':
main()