Commit 2b6a700b by 林冲

步骤二拆分为两个脚本

1 parent 17468153
# merchant_goods_code 补齐脚本拆分说明
## 概述
为了提高执行效率和灵活性,将原来的 `main_merchant_goods_code.py` 拆分为两个独立的脚本:
- `main_merchant_goods_code_finance.py` - 处理财务规则(rule_type=1)
- `main_merchant_goods_code_reconciliation.py` - 处理对账规则(rule_type=3)
## 拆分原因
1. **并行执行**:两个脚本可以同时运行,提高处理速度
2. **独立管理**:财务规则和对账规则的数据量、处理逻辑可以独立优化
3. **故障隔离**:一个脚本失败不影响另一个脚本的执行
4. **灵活调度**:可以根据业务需要单独执行某一类规则的补数
5. **临时表隔离**:使用不同的临时表名,避免并行执行时的冲突
## 核心修改
### 1. MerchantGoodsCodeProcessor 类修改
**新增 rule_type 参数:**
```python
def __init__(self, db_helper, test_mode=False, rule_type=None):
"""
Args:
rule_type: 规则类型(1=财务,3=对账),用于区分临时表名
"""
```
**临时表名根据 rule_type 自动区分:**
- `rule_type=1`(财务规则):
- `tmp_goods_relation_context_finance`
- `tmp_merchant_goods_code_detail_finance`
- `tmp_merchant_goods_code_exception_finance`
- `rule_type=3`(对账规则):
- `tmp_goods_relation_context_reconciliation`
- `tmp_merchant_goods_code_detail_reconciliation`
- `tmp_merchant_goods_code_exception_reconciliation`
**round1_fill_from_merchant_goods 方法修改:**
```python
def round1_fill_from_merchant_goods(self, context_table=None):
"""
Args:
context_table: 指定要处理的上下文表名,如果不指定则使用 self.context_table
"""
```
### 2. SQL 注入修复
**_batch_insert_copy_records 方法改为参数化查询:**
**修改前(字符串拼接):**
```python
values_parts.append(f"""(
{rule_type}, {goods_type_group_rule_id}, {category_type}, {upgrade_goods_id},
'{new_code}', {goods_type if goods_type else 'NULL'},
...
)""")
```
**修改后(参数化查询):**
```python
values_list.append((
rule_type,
goods_type_group_rule_id,
category_type,
upgrade_goods_id,
new_code,
goods_type,
...
))
insert_sql = """
INSERT INTO dj_car_life_goods_type_group_relation
(...) VALUES (%s, %s, %s, %s, %s, %s, ...)
"""
self.db.execute_batch(insert_sql, values_list)
```
## 并行执行
**现在两个脚本可以安全地同时运行:**
```bash
# 在两个终端窗口中分别执行
# 终端1:
python main_merchant_goods_code_finance.py prod
# 终端2:
python main_merchant_goods_code_reconciliation.py prod
```
## 临时表说明
两个脚本使用完全独立的临时表:
| 脚本类型 | 上下文表 | 明细表 | 异常表 |
|---------|---------|--------|--------|
| 财务规则 | tmp_goods_relation_context_finance | tmp_merchant_goods_code_detail_finance | tmp_merchant_goods_code_exception_finance |
| 对账规则 | tmp_goods_relation_context_reconciliation | tmp_merchant_goods_code_detail_reconciliation | tmp_merchant_goods_code_exception_reconciliation |
## 使用示例
```bash
# 测试环境
python main_merchant_goods_code_finance.py test
python main_merchant_goods_code_reconciliation.py test
# 生产环境
python main_merchant_goods_code_finance.py prod
python main_merchant_goods_code_reconciliation.py prod
```
## 监控和验证
```sql
-- 检查财务规则补齐情况
SELECT COUNT(*) FROM dj_car_life_goods_type_group_relation
WHERE rule_type = 1 AND category_type = 2
AND (merchant_goods_code IS NULL OR merchant_goods_code = '');
-- 检查对账规则补齐情况
SELECT COUNT(*) FROM dj_car_life_goods_type_group_relation
WHERE rule_type = 3 AND category_type = 2
AND (merchant_goods_code IS NULL OR merchant_goods_code = '');
```
......@@ -18,11 +18,18 @@
# db: "dj_smartcarlife_scene_test_0506_done_copy"
# charset: "utf8mb4"
#test_smartcarlife_db:
# host: "192.168.1.228"
# port: 3307
# user: "wechat_user"
# password: "b4WRTkl"
# db: "dj_smartcarlife"
# charset: "utf8mb4"
test_smartcarlife_db:
host: "192.168.1.228"
port: 3307
user: "wechat_user"
password: "b4WRTkl"
db: "dj_smartcarlife"
db: "dj_smartcarlife_deal0515"
charset: "utf8mb4"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
merchant_goods_code 补齐主程序入口 - 财务规则(rule_type=1)
专门处理财务规则的 merchant_goods_code 补齐
"""
import sys
import logging
from datetime import datetime
from db_helper import get_db_helper
from merchant_goods_code_processor import MerchantGoodsCodeProcessor
def setup_logging(log_file='merchant_goods_code_fill_finance.log'):
"""配置日志"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[
logging.FileHandler(log_file, encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
)
def main(env='test', test_mode=False):
"""
主函数 - 财务规则
Args:
env: 环境 (test/prod),默认 test
test_mode: 是否为测试模式,默认 False(正式模式)
"""
logger = logging.getLogger(__name__)
print("=" * 80)
print("merchant_goods_code 补齐程序 - 财务规则(rule_type=1)")
print("=" * 80)
# 1. 验证环境参数
if env not in ['test', 'prod']:
print(f"错误:环境只能是 test 或 prod,当前值: {env}")
return
# 2. 显示运行模式
if test_mode:
print("\n【测试模式】将处理少量数据用于验证")
else:
print("\n【正式模式】将处理所有数据")
# 3. 配置日志
log_file = f'merchant_goods_code_fill_finance_{env}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
setup_logging(log_file)
logger.info("=" * 80)
logger.info(f"merchant_goods_code 补齐程序启动 - 财务规则(rule_type=1)")
logger.info(f"环境: {env}")
logger.info(f"模式: {'测试模式' if test_mode else '正式模式'}")
logger.info(f"日志文件: {log_file}")
logger.info("=" * 80)
# 4. 初始化数据库连接
db = None
try:
logger.info("初始化数据库连接...")
db = get_db_helper(env)
logger.info("数据库连接成功")
# 5. 初始化处理器(指定 rule_type=1)
processor = MerchantGoodsCodeProcessor(db, test_mode=test_mode, rule_type=1)
# 6. 加载商品数据到内存
logger.info("\n步骤1:加载商品数据到内存")
processor.load_merchant_goods_cache()
# 7. 创建临时表
logger.info("\n步骤2:创建临时表")
processor.create_temp_tables()
# 8. 构造财务规则上下文(只处理 rule_type=1)
logger.info("\n步骤3:构造财务规则上下文(rule_type=1)")
processor._build_finance_context()
# 统计上下文记录数
count_sql = f"SELECT COUNT(*) FROM {processor.context_table};"
result = db.execute_query_one(count_sql)
total_count = result[0] if result else 0
logger.info(f"财务规则上下文构造完成,共 {total_count} 条记录")
# 9. 第一轮补数:从商品上架数据补齐
logger.info("\n步骤4:第一轮补数(从商品上架数据)")
processor.round1_fill_from_merchant_goods(context_table=processor.context_table)
# 10. 验证结果
logger.info("\n步骤5:验证补数结果")
processor.validate_results()
# 11. 导出异常报告
exception_file = f'merchant_goods_code_exceptions_finance_{env}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
logger.info(f"\n步骤6:导出异常报告")
processor.export_exception_report(exception_file)
# 12. 默认保留临时表(不再询问)
logger.info("临时表已保留,可用于后续分析")
logger.info("=" * 80)
logger.info("merchant_goods_code 补齐程序执行完成 - 财务规则")
logger.info(f"日志文件: {log_file}")
if exception_file:
logger.info(f"异常报告: {exception_file}")
logger.info("=" * 80)
print("\n" + "=" * 80)
print("执行完成!")
print(f"日志文件: {log_file}")
print(f"异常报告: {exception_file}")
print("=" * 80)
except Exception as e:
logger.error(f"执行失败: {e}", exc_info=True)
print(f"\n执行失败: {e}")
print(f"详细信息请查看日志文件: {log_file}")
sys.exit(1)
finally:
if db:
db.close()
logger.info("数据库连接已关闭")
def show_help():
"""显示帮助信息"""
help_text = """
merchant_goods_code 补齐程序使用说明 - 财务规则(rule_type=1)
================================================================
功能:
专门处理财务规则(rule_type=1)的 merchant_goods_code 补齐。
对 dj_car_life_goods_type_group_relation 表中 rule_type=1、
category_type=2 且 merchant_goods_code 为空的记录进行补齐。
处理流程:
1. 加载商品数据到内存
2. 创建临时表(上下文表、明细表、异常表)
3. 构造财务规则上下文(只处理 rule_type=1)
4. 第一轮补数:从内存缓存中查询商品编码
5. 验证结果
6. 导出异常报告
补数规则:
- 匹配到1个 merchant_goods_code:更新原记录
- 匹配到多个 merchant_goods_code:原记录更新第一个,其余复制插入新记录
- 复制插入前检查是否已存在相同记录,避免重复
- 所有新记录标记 created_by='DATA_MIGRATION2', updated_by='DATA_MIGRATION2'
临时表说明:
- tmp_goods_relation_context: 规则上下文表(只包含财务规则)
- tmp_merchant_goods_code_detail: 补数明细表
- tmp_merchant_goods_code_exception: 异常清单表
运行模式:
- 测试模式:处理少量数据,用于验证逻辑
- 正式模式:处理所有数据
环境选择:
- test: 测试环境
- prod: 生产环境
输出文件:
- merchant_goods_code_fill_finance_<env>_<timestamp>.log: 执行日志
- merchant_goods_code_exceptions_finance_<env>_<timestamp>.csv: 异常报告
注意事项:
1. 执行前请确保已完成场景拆分(第1-13步)
2. 建议先在测试环境验证
3. 正式执行前请备份相关表
4. 临时表默认保留,可用于后续分析
5. 异常记录需要人工确认处理
6. 可以与对账规则脚本并行执行
使用示例:
# 默认:测试环境 + 正式模式
python main_merchant_goods_code_finance.py
# 指定环境:生产环境 + 正式模式
python main_merchant_goods_code_finance.py prod
# 指定环境和模式:测试环境 + 测试模式
python main_merchant_goods_code_finance.py test true
# 显示帮助
python main_merchant_goods_code_finance.py --help
"""
print(help_text)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help', 'help']:
show_help()
else:
# 从命令行参数获取环境和模式
env = 'test' # 默认测试环境
test_mode = False # 默认正式模式
if len(sys.argv) > 1:
env = sys.argv[1].lower()
if len(sys.argv) > 2:
test_mode = sys.argv[2].lower() in ['true', '1', 'yes']
main(env=env, test_mode=test_mode)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
merchant_goods_code 补齐主程序入口 - 对账规则(rule_type=3)
专门处理对账规则的 merchant_goods_code 补齐
"""
import sys
import logging
from datetime import datetime
from db_helper import get_db_helper
from merchant_goods_code_processor import MerchantGoodsCodeProcessor
def setup_logging(log_file='merchant_goods_code_fill_reconciliation.log'):
"""配置日志"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[
logging.FileHandler(log_file, encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
)
def main(env='test', test_mode=False):
"""
主函数 - 对账规则
Args:
env: 环境 (test/prod),默认 test
test_mode: 是否为测试模式,默认 False(正式模式)
"""
logger = logging.getLogger(__name__)
print("=" * 80)
print("merchant_goods_code 补齐程序 - 对账规则(rule_type=3)")
print("=" * 80)
# 1. 验证环境参数
if env not in ['test', 'prod']:
print(f"错误:环境只能是 test 或 prod,当前值: {env}")
return
# 2. 显示运行模式
if test_mode:
print("\n【测试模式】将处理少量数据用于验证")
else:
print("\n【正式模式】将处理所有数据")
# 3. 配置日志
log_file = f'merchant_goods_code_fill_reconciliation_{env}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
setup_logging(log_file)
logger.info("=" * 80)
logger.info(f"merchant_goods_code 补齐程序启动 - 对账规则(rule_type=3)")
logger.info(f"环境: {env}")
logger.info(f"模式: {'测试模式' if test_mode else '正式模式'}")
logger.info(f"日志文件: {log_file}")
logger.info("=" * 80)
# 4. 初始化数据库连接
db = None
try:
logger.info("初始化数据库连接...")
db = get_db_helper(env)
logger.info("数据库连接成功")
# 5. 初始化处理器(指定 rule_type=3)
processor = MerchantGoodsCodeProcessor(db, test_mode=test_mode, rule_type=3)
# 6. 加载商品数据到内存
logger.info("\n步骤1:加载商品数据到内存")
processor.load_merchant_goods_cache()
# 7. 创建临时表
logger.info("\n步骤2:创建临时表")
processor.create_temp_tables()
# 8. 构造对账规则上下文(只处理 rule_type=3)
logger.info("\n步骤3:构造对账规则上下文(rule_type=3)")
processor._build_reconciliation_context()
# 统计上下文记录数
count_sql = f"SELECT COUNT(*) FROM {processor.context_table};"
result = db.execute_query_one(count_sql)
total_count = result[0] if result else 0
logger.info(f"对账规则上下文构造完成,共 {total_count} 条记录")
# 9. 第一轮补数:从商品上架数据补齐
logger.info("\n步骤4:第一轮补数(从商品上架数据)")
processor.round1_fill_from_merchant_goods(context_table=processor.context_table)
# 10. 验证结果
logger.info("\n步骤5:验证补数结果")
processor.validate_results()
# 11. 导出异常报告
exception_file = f'merchant_goods_code_exceptions_reconciliation_{env}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
logger.info(f"\n步骤6:导出异常报告")
processor.export_exception_report(exception_file)
# 12. 默认保留临时表(不再询问)
logger.info("临时表已保留,可用于后续分析")
logger.info("=" * 80)
logger.info("merchant_goods_code 补齐程序执行完成 - 对账规则")
logger.info(f"日志文件: {log_file}")
if exception_file:
logger.info(f"异常报告: {exception_file}")
logger.info("=" * 80)
print("\n" + "=" * 80)
print("执行完成!")
print(f"日志文件: {log_file}")
print(f"异常报告: {exception_file}")
print("=" * 80)
except Exception as e:
logger.error(f"执行失败: {e}", exc_info=True)
print(f"\n执行失败: {e}")
print(f"详细信息请查看日志文件: {log_file}")
sys.exit(1)
finally:
if db:
db.close()
logger.info("数据库连接已关闭")
def show_help():
"""显示帮助信息"""
help_text = """
merchant_goods_code 补齐程序使用说明 - 对账规则(rule_type=3)
================================================================
功能:
专门处理对账规则(rule_type=3)的 merchant_goods_code 补齐。
对 dj_car_life_goods_type_group_relation 表中 rule_type=3、
category_type=2 且 merchant_goods_code 为空的记录进行补齐。
处理流程:
1. 加载商品数据到内存
2. 创建临时表(上下文表、明细表、异常表)
3. 构造对账规则上下文(只处理 rule_type=3)
4. 第一轮补数:从内存缓存中查询商品编码
5. 验证结果
6. 导出异常报告
补数规则:
- 匹配到1个 merchant_goods_code:更新原记录
- 匹配到多个 merchant_goods_code:原记录更新第一个,其余复制插入新记录
- 复制插入前检查是否已存在相同记录,避免重复
- 所有新记录标记 created_by='DATA_MIGRATION2', updated_by='DATA_MIGRATION2'
临时表说明:
- tmp_goods_relation_context: 规则上下文表(只包含对账规则)
- tmp_merchant_goods_code_detail: 补数明细表
- tmp_merchant_goods_code_exception: 异常清单表
运行模式:
- 测试模式:处理少量数据,用于验证逻辑
- 正式模式:处理所有数据
环境选择:
- test: 测试环境
- prod: 生产环境
输出文件:
- merchant_goods_code_fill_reconciliation_<env>_<timestamp>.log: 执行日志
- merchant_goods_code_exceptions_reconciliation_<env>_<timestamp>.csv: 异常报告
注意事项:
1. 执行前请确保已完成场景拆分(第1-13步)
2. 建议先在测试环境验证
3. 正式执行前请备份相关表
4. 临时表默认保留,可用于后续分析
5. 异常记录需要人工确认处理
6. 可以与财务规则脚本并行执行
使用示例:
# 默认:测试环境 + 正式模式
python main_merchant_goods_code_reconciliation.py
# 指定环境:生产环境 + 正式模式
python main_merchant_goods_code_reconciliation.py prod
# 指定环境和模式:测试环境 + 测试模式
python main_merchant_goods_code_reconciliation.py test true
# 显示帮助
python main_merchant_goods_code_reconciliation.py --help
"""
print(help_text)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help', 'help']:
show_help()
else:
# 从命令行参数获取环境和模式
env = 'test' # 默认测试环境
test_mode = False # 默认正式模式
if len(sys.argv) > 1:
env = sys.argv[1].lower()
if len(sys.argv) > 2:
test_mode = sys.argv[2].lower() in ['true', '1', 'yes']
main(env=env, test_mode=test_mode)
......@@ -301,6 +301,47 @@ def main():
logger.info("\n" + "=" * 100)
logger.info("场景拆分数据处理完成!")
logger.info("=" * 100)
# 调用 main_merchant_goods_code.py 补齐 merchant_goods_code
logger.info("\n" + "=" * 100)
logger.info("开始执行 merchant_goods_code 补齐程序")
logger.info("=" * 100)
try:
import subprocess
# 构造命令:使用相同的环境参数,正式模式
cmd = [sys.executable, 'main_merchant_goods_code.py', args.env, 'false']
logger.info(f"执行命令: {' '.join(cmd)}")
# 执行脚本
result = subprocess.run(
cmd,
cwd=os.path.dirname(os.path.abspath(__file__)),
capture_output=True,
text=True,
encoding='utf-8'
)
# 输出执行结果
if result.stdout:
logger.info("merchant_goods_code 补齐程序输出:")
for line in result.stdout.splitlines():
logger.info(f" {line}")
if result.stderr:
logger.warning("merchant_goods_code 补齐程序错误输出:")
for line in result.stderr.splitlines():
logger.warning(f" {line}")
if result.returncode == 0:
logger.info("merchant_goods_code 补齐程序执行成功")
else:
logger.error(f"merchant_goods_code 补齐程序执行失败,返回码: {result.returncode}")
except Exception as e:
logger.error(f"调用 merchant_goods_code 补齐程序失败: {e}", exc_info=True)
return 0
else:
logger.error("\n" + "=" * 100)
......
......@@ -825,6 +825,7 @@ class SceneSplitProcessor:
"""
批量更新表2(dj_car_life_merchant_goods_type_group_settle_rule)中的 goods_type_group_id
使用临时表关联更新,优化大数据量场景性能
优化:使用 TEMPORARY TABLE + TRUNCATE 减少 DDL 开销
"""
self.logger.info(" 开始批量更新表2中的 goods_type_group_id...")
settle_rule_table = 'dj_car_life_merchant_goods_type_group_settle_rule'
......@@ -835,9 +836,9 @@ class SceneSplitProcessor:
self.logger.info(f" 待更新数据量: {total_count} 条")
try:
# 1. 创建临时表
# 1. 创建临时表(如果不存在)
create_temp_sql = f"""
CREATE TABLE {temp_table} (
CREATE TEMPORARY TABLE IF NOT EXISTS {temp_table} (
old_id BIGINT NOT NULL COMMENT '原goods_type_group的ID',
base_scene_code VARCHAR(20) NOT NULL COMMENT '场景编码',
new_settle_rule_group_id BIGINT NOT NULL COMMENT '新的settle_rule记录ID',
......@@ -846,9 +847,13 @@ class SceneSplitProcessor:
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4 COMMENT='临时表:用于批量更新settle_rule的goods_type_group_id';
"""
self.db.execute_update(create_temp_sql)
self.logger.info(f" 临时表 {temp_table} 创建成功")
# 2. 分批插入临时表(每批1万条,避免SQL过长)
# 2. 清空临时表(如果之前有数据)
truncate_sql = f"TRUNCATE TABLE {temp_table};"
self.db.execute_update(truncate_sql)
self.logger.info(f" 临时表 {temp_table} 已准备就绪")
# 3. 分批插入临时表(每批2万条,避免SQL过长)
insert_batch_size = 20000
total_batches = (total_count + insert_batch_size - 1) // insert_batch_size
self.logger.info(f" 开始插入临时表,共 {total_batches} 个批次")
......@@ -874,7 +879,7 @@ class SceneSplitProcessor:
self.db.execute_update(insert_sql)
self.logger.info(f" 临时表插入进度: {batch_idx + 1}/{total_batches},本批 {len(batch)} 条")
# 3. 一次性关联更新(核心优化:避免大量OR条件和CASE WHEN)
# 4. 一次性关联更新(核心优化:避免大量OR条件和CASE WHEN)
update_sql = f"""
UPDATE {settle_rule_table} sr
INNER JOIN {temp_table} tmp ON sr.id = tmp.new_settle_rule_group_id
......@@ -895,13 +900,13 @@ class SceneSplitProcessor:
self.logger.error(f" 批量更新表2失败: {e}")
raise
finally:
# 4. 清理临时表
# 5. 清空临时表(为下次使用做准备)
try:
drop_sql = f"DROP TEMPORARY TABLE IF EXISTS {temp_table};"
self.db.execute_update(drop_sql)
self.logger.info(f" 临时表 {temp_table} 已清理")
truncate_sql = f"TRUNCATE TABLE {temp_table};"
self.db.execute_update(truncate_sql)
self.logger.info(f" 临时表 {temp_table} 已清空")
except Exception as e:
self.logger.warning(f" 清理临时表失败: {e}")
self.logger.warning(f" 清空临时表失败: {e}")
def _update_division_rule_group_goods_type_group_id(self):
"""
......
......@@ -8,8 +8,9 @@ python main_scene_split.py --env test
## 第二步:merchantGoodsCode数据补全(依赖第一步刷规则做baseSceneCode更新和scene=0的拆分以及订单-善天、商品数据补全-诗林)
python main_merchant_goods_code.py test
> python main_merchant_goods_code.py test 废弃,改为下面两个脚本分别跑加快速度
python main_merchant_goods_code_finance.py test
python main_merchant_goods_code_reconciliation.py test
## 第三步:将刷好的表替换到生产库
- dj_car_life_merchant_settle_account_rule
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!