test_huitong_db_write.py
1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import pandas as pd
from sqlalchemy import create_engine, text
import sys
import os
# 将 project 目录加入路径以导入配置
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'project', '2-report_generation'))
from device_detail_processor import get_db_engine_config, to_sql_native
import numpy as np
def test_huitong_db_logic():
# 1. 初始化引擎 (从项目配置获取)
engine = create_engine(get_db_engine_config('device_detail_db'))
test_table = "d_es_huitong_raw_data_test"
# 2. 准备模拟数据 (包含 NaN 以测试 fix)
df = pd.DataFrame([
{
'settlement_time': '2026-01-01',
'financial_time': '2026-01-16',
'hardware_without_tax': 100.50
},
{
'settlement_time': '2026-01-02',
'financial_time': '2026-01-17',
'hardware_without_tax': np.nan # 测试 NaN 写入
}
])
print(f"--- 开始测试表 {test_table} 的写入逻辑 ---")
# 3. 模拟删除逻辑
min_time, max_time = '2026-01-01', '2026-01-31'
delete_sql = f"delete from {test_table} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
try:
print(f"执行删除 SQL: {delete_sql}")
with engine.begin() as con:
con.execute(text(delete_sql))
print("✅ 删除逻辑执行成功")
# 4. 模拟写入逻辑 (使用 to_sql_native)
print(f"执行 to_sql_native 写入 (包含 NaN 值)...")
to_sql_native(df, test_table, engine, if_exists="append")
print("✅ to_sql_native 写入逻辑执行成功 (NaN 已处理)")
except Exception as e:
print(f"❌ 测试失败: {e}")
finally:
print("--- 测试结束 ---")
if __name__ == "__main__":
test_huitong_db_logic()