sql_utils.py
5.73 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import pandas as pd
import pymysql
import yaml
import os
def get_db_config():
"""从 config.yaml 获取数据库配置"""
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config_path = os.path.join(base_dir, "config.yaml")
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
return config.get("database", {}).get("dijia_db")
def execute_sql_file(sql_file_path, progress_callback=None, params=None):
"""
读取并执行 SQL 文件,返回每个查询的结果列表
progress_callback: 回调函数,接收 (current_index, total_count, title)
params: 变量替换字典,例如 {"year": 2025},SQL 中使用 {year} 占位
"""
db_config = get_db_config()
if not db_config:
raise ValueError("未找到 dijia_db 数据库配置")
conn = pymysql.connect(
host=db_config['host'],
port=db_config['port'],
user=db_config['user'],
password=db_config['password'],
db=db_config['db_name'],
charset=db_config['charset'],
cursorclass=pymysql.cursors.DictCursor
)
try:
with open(sql_file_path, "r", encoding="utf-8") as f:
full_sql = f.read()
# 如果提供了参数,进行变量替换
if params:
try:
full_sql = full_sql.format(**params)
except KeyError as e:
# 如果 SQL 中包含花括号但不是为了替换(如 JSON 或其他语法),可能会报错
# 简单处理:如果替换失败,保持原样或打印警告
pass
# 按分号分割多个 SQL 语句
commands = [cmd.strip() for cmd in full_sql.split(';') if cmd.strip()]
total_commands = len(commands)
results = []
with conn.cursor() as cursor:
for i, cmd in enumerate(commands):
# 预处理:过滤掉纯注释行并提取标题
lines = cmd.split('\n')
non_comment_lines = []
title = f"查询 {i+1}"
for line in lines:
stripped_line = line.strip()
if not stripped_line:
continue
if stripped_line.startswith('--') or stripped_line.startswith('##'):
# 提取第一行注释作为标题
if title == f"查询 {i+1}":
title = stripped_line.lstrip('-#').strip()
continue
non_comment_lines.append(line)
clean_command = "\n".join(non_comment_lines).strip()
if not clean_command:
continue
# 进度回调
if progress_callback:
progress_callback(i + 1, total_commands, title)
# 执行查询
cursor.execute(clean_command)
# 获取结果
data = cursor.fetchall()
if data:
df = pd.DataFrame(data)
results.append({"title": title, "data": df})
return results
finally:
conn.close()
def get_dijia_stats(year, month_str):
"""
获取指定月份在数据库中的数据量统计
year: 年份 (int)
month_str: 月份字符串 (如 "8" 或 "08")
"""
db_config = get_db_config()
if not db_config:
return None
conn = pymysql.connect(
host=db_config['host'],
port=db_config['port'],
user=db_config['user'],
password=db_config['password'],
db=db_config['db_name'],
charset=db_config['charset'],
cursorclass=pymysql.cursors.DictCursor
)
try:
# 补全月份格式
if month_str.isdigit():
target_month = f"{year}-{int(month_str):02d}"
else:
# 尝试从 "8月份" 这种字符串中提取数字
import re
match = re.search(r'(\d+)', month_str)
if match:
target_month = f"{year}-{int(match.group(1)):02d}"
else:
return {"error": f"无法从批次名称 '{month_str}' 中提取月份"}
stats = {"finance_count": 0, "order_count": 0}
with conn.cursor() as cursor:
# 1. 统计财务表
table_finance = f"dj_{year}_settlment_order_finance"
try:
cursor.execute(f"SELECT COUNT(*) as count FROM {table_finance} WHERE DATE_FORMAT(finance_time, '%%Y-%%m') = %s", (target_month,))
res_fin = cursor.fetchone()
stats['finance_count'] = res_fin['count'] if res_fin else 0
except pymysql.err.ProgrammingError as e:
if e.args[0] == 1146: # Table doesn't exist
return {"error": f"数据库表 {table_finance} 不存在,请检查数据库结构或年份配置。"}
raise e
# 2. 统计商务表
table_order = f"dj_{year}_settlment_order"
try:
cursor.execute(f"SELECT COUNT(*) as count FROM {table_order} WHERE DATE_FORMAT(finance_time, '%%Y-%%m') = %s", (target_month,))
res_ord = cursor.fetchone()
stats['order_count'] = res_ord['count'] if res_ord else 0
except pymysql.err.ProgrammingError as e:
if e.args[0] == 1146: # Table doesn't exist
return {"error": f"数据库表 {table_order} 不存在,请检查数据库结构或年份配置。"}
raise e
return stats
except Exception as e:
print(f"查询统计失败: {e}")
return {"error": f"查询统计失败: {str(e)}"}
finally:
conn.close()