#!/usr/bin/env python3 """统一初始化数据导入脚本(模块 init/data.json -> pipeline 库)。 读取各模块 init/data.json 的字典数据(appcodes / appcodes_kv / organization), 导入 pipeline 库对应表。幂等:已存在则跳过。 用法: py3/bin/python scripts/import_init.py """ import sys, os, json, asyncio SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(SCRIPT_DIR) sys.path.insert(0, os.path.join(ROOT_DIR, 'py3', 'lib', 'python3.10', 'site-packages')) sys.path.insert(0, ROOT_DIR) from sqlor.dbpools import DBPools from appPublic.jsonConfig import getConfig from appPublic.folderUtils import ProgramPath from appPublic.uniqueID import getID from ahserver.serverenv import ServerEnv from ahserver.globalEnv import initEnv # 各模块的 init 数据(模块名 -> 相对 ROOT_DIR 的 init/data.json 路径) INIT_MODULES = [ ('product_management', 'pkgs/product_management/init/data.json'), ('discount', 'pkgs/discount/init/data.json'), ] async def main(): config = getConfig(ROOT_DIR, NS={'workdir': ROOT_DIR, 'ProgramPath': ProgramPath()}) DBPools(config.databases) initEnv() env = ServerEnv() env.get_module_dbname = lambda m: 'pipeline' if 'pipeline' in m else 'sage' total = {'appcodes': 0, 'appcodes_kv': 0, 'organization': 0} async with DBPools().sqlorContext('pipeline') as sor: for mod, rel in INIT_MODULES: f = os.path.join(ROOT_DIR, rel) if not os.path.exists(f): print(f' skip {mod}: {rel} not found') continue data = json.load(open(f, encoding='utf-8')) for ac in data.get('appcodes', []): recs = await sor.R('appcodes', {'id': ac['id']}) if not recs: await sor.C('appcodes', { 'id': ac['id'], 'name': ac.get('name', ''), 'hierarchy_flg': ac.get('hierarchy_flg', '0'), }) total['appcodes'] += 1 for kv in data.get('appcodes_kv', []): recs = await sor.R('appcodes_kv', {'id': kv['id']}) if not recs: await sor.C('appcodes_kv', { 'id': kv['id'], 'parentid': kv.get('parentid', ''), 'k': kv.get('k', ''), 'v': kv.get('v', ''), }) total['appcodes_kv'] += 1 for org in data.get('organization', []): recs = await sor.R('organization', {'id': org['id']}) if not recs: await sor.C('organization', { 'id': org['id'], 'orgname': org.get('orgname', ''), }) total['organization'] += 1 print(f'import_init: appcodes {total["appcodes"]}, appcodes_kv {total["appcodes_kv"]}, organization {total["organization"]}') if __name__ == '__main__': asyncio.run(main())