增加日志

This commit is contained in:
2026-07-15 16:01:06 +08:00
parent d34dd82bd5
commit 727f5434b2
11 changed files with 461 additions and 192 deletions

View File

@@ -2,6 +2,36 @@
数据库初始化
"""
from lib.db import execute_update, execute_query
from lib.logger import log_info, log_error, log_warning
def _column_exists(table_name, column_name):
"""检查字段是否存在(通过 information_schema 查询)"""
try:
result = execute_query("""
SELECT COUNT(*) as cnt
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = %s
AND column_name = %s
""", (table_name, column_name))
return result and result[0]['cnt'] > 0
except Exception:
return False
def _add_column_if_not_exists(table_name, column_def_sql, column_name):
"""安全地添加字段:先检查是否存在,不存在再添加"""
if _column_exists(table_name, column_name):
log_info(f"[数据库] 字段 {table_name}.{column_name} 已存在,跳过", 'db_init')
return True
try:
execute_update(f"ALTER TABLE {table_name} ADD COLUMN {column_def_sql}")
log_info(f"[数据库] 新增字段 {table_name}.{column_name} 成功", 'db_init')
return True
except Exception as e:
log_warning(f"[数据库] 新增字段 {table_name}.{column_name} 失败: {e}", 'db_init')
return False
def init_database_tables():
@@ -34,7 +64,7 @@ def init_database_tables():
PROPERTIES("replication_num" = "1")
"""
execute_update(create_config_table)
print("[数据库] t_daily_report_config 表已就绪")
log_info("[数据库] t_daily_report_config 表已就绪", 'db_init')
# 创建历史表
create_history_table = """
@@ -60,16 +90,14 @@ def init_database_tables():
PROPERTIES("replication_num" = "1")
"""
execute_update(create_history_table)
print("[数据库] t_daily_report_history 表已就绪")
log_info("[数据库] t_daily_report_history 表已就绪", 'db_init')
# 为已存在的表添加 config_name 字段(如果不存在)
try:
execute_update("""
ALTER TABLE t_daily_report_history
ADD COLUMN IF NOT EXISTS config_name VARCHAR(200) NULL COMMENT '配置名称'
""")
except Exception as e:
print(f"[数据库] 添加 config_name 字段时出错(可能已存在): {e}")
_add_column_if_not_exists(
't_daily_report_history',
"config_name VARCHAR(200) NULL COMMENT '配置名称'",
'config_name'
)
# 创建求和数据表
create_sum_data_table = """
@@ -96,56 +124,35 @@ def init_database_tables():
PROPERTIES("replication_num" = "1")
"""
execute_update(create_sum_data_table)
print("[数据库] t_daily_report_sum_data 表已就绪")
log_info("[数据库] t_daily_report_sum_data 表已就绪", 'db_init')
# 给配置表增加 show_monthly_total 字段
try:
execute_update(
"ALTER TABLE t_daily_report_config ADD COLUMN show_monthly_total TINYINT NULL COMMENT '是否显示当月充电量总计' "
)
print("[数据库] 配置表新增 show_monthly_total 字段成功")
except Exception as e:
# 字段已存在会报错,忽略
if "Duplicate" in str(e) or "duplicate" in str(e) or "Exists" in str(e) or "exists" in str(e):
pass
else:
print(f"[数据库] 新增 show_monthly_total 字段时出错(可能已存在): {e}")
_add_column_if_not_exists(
't_daily_report_config',
"show_monthly_total TINYINT NULL COMMENT '是否显示当月充电量总计'",
'show_monthly_total'
)
# 给求和数据表增加 sort_order 字段
try:
execute_update(
"ALTER TABLE t_daily_report_sum_data ADD COLUMN sort_order INT NULL COMMENT '配置排序号' "
)
print("[数据库] 求和数据表新增 sort_order 字段成功")
except Exception as e:
if "Duplicate" in str(e) or "duplicate" in str(e) or "Exists" in str(e) or "exists" in str(e):
pass
else:
print(f"[数据库] 新增 sort_order 字段时出错(可能已存在): {e}")
_add_column_if_not_exists(
't_daily_report_sum_data',
"sort_order INT NULL COMMENT '配置排序号'",
'sort_order'
)
# 给配置表增加 custom_service_fee_price 字段(自定义服务费单价)
try:
execute_update(
"ALTER TABLE t_daily_report_config ADD COLUMN custom_service_fee_price DECIMAL(10,4) NULL COMMENT '自定义服务费单价(元/kWh)' "
)
print("[数据库] 配置表新增 custom_service_fee_price 字段成功")
except Exception as e:
if "Duplicate" in str(e) or "duplicate" in str(e) or "Exists" in str(e) or "exists" in str(e):
pass
else:
print(f"[数据库] 新增 custom_service_fee_price 字段时出错(可能已存在): {e}")
_add_column_if_not_exists(
't_daily_report_config',
"custom_service_fee_price DECIMAL(10,4) NULL COMMENT '自定义服务费单价(元/kWh)'",
'custom_service_fee_price'
)
# 给配置表增加 custom_service_fee_name 字段(自定义服务费表头名称)
try:
execute_update(
"ALTER TABLE t_daily_report_config ADD COLUMN custom_service_fee_name VARCHAR(100) NULL COMMENT '自定义服务费报表表头名称' "
)
print("[数据库] 配置表新增 custom_service_fee_name 字段成功")
except Exception as e:
if "Duplicate" in str(e) or "duplicate" in str(e) or "Exists" in str(e) or "exists" in str(e):
pass
else:
print(f"[数据库] 新增 custom_service_fee_name 字段时出错(可能已存在): {e}")
_add_column_if_not_exists(
't_daily_report_config',
"custom_service_fee_name VARCHAR(100) NULL COMMENT '自定义服务费报表表头名称'",
'custom_service_fee_name'
)
# 数据迁移:给 sort_order 为 NULL 的配置记录按 id 顺序赋值
try:
@@ -153,7 +160,7 @@ def init_database_tables():
"SELECT COUNT(*) as cnt FROM t_daily_report_config WHERE sort_order IS NULL"
)
if null_count and null_count[0]['cnt'] > 0:
print(f"[数据库] 检测到 {null_count[0]['cnt']} 条配置 sort_order 为空,开始初始化排序...")
log_info(f"[数据库] 检测到 {null_count[0]['cnt']} 条配置 sort_order 为空,开始初始化排序...", 'db_init')
all_configs = execute_query(
"SELECT id FROM t_daily_report_config ORDER BY id ASC"
)
@@ -162,11 +169,12 @@ def init_database_tables():
"UPDATE t_daily_report_config SET sort_order = %s WHERE id = %s",
(idx + 1, cfg['id'])
)
print("[数据库] 配置 sort_order 初始化完成")
log_info("[数据库] 配置 sort_order 初始化完成", 'db_init')
except Exception as e:
print(f"[数据库] 初始化 sort_order 时出错: {e}")
log_warning(f"[数据库] 初始化 sort_order 时出错: {e}", 'db_init')
log_info("[数据库] 初始化完成", 'db_init')
return True
except Exception as e:
print(f"[数据库] 初始化失败: {e}")
log_error(f"[数据库] 初始化失败: {e}", 'db_init')
return False