feat: 自动提交 - 周一 2025/09/22 14:40:25.43
This commit is contained in:
142
init_database.py
142
init_database.py
@@ -64,13 +64,13 @@ class DatabaseInitializer:
|
|||||||
print(f"⏰ 初始化时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
print(f"⏰ 初始化时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||||
print("=" * 80)
|
print("=" * 80)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# 设置日志
|
# 设置日志
|
||||||
setup_logging(Config.LOG_LEVEL, Config.LOG_FILE)
|
setup_logging(Config.LOG_LEVEL, Config.LOG_FILE)
|
||||||
|
|
||||||
# 测试数据库连接
|
# 测试数据库连接
|
||||||
if not self._test_connection():
|
if not self._test_connection():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 检查是否需要重置数据库
|
# 检查是否需要重置数据库
|
||||||
if force_reset:
|
if force_reset:
|
||||||
@@ -85,7 +85,7 @@ class DatabaseInitializer:
|
|||||||
if not self._run_migrations():
|
if not self._run_migrations():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 插入初始数据
|
# 插入初始数据
|
||||||
if not self._insert_initial_data():
|
if not self._insert_initial_data():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -99,9 +99,9 @@ class DatabaseInitializer:
|
|||||||
print("\n" + "=" * 80)
|
print("\n" + "=" * 80)
|
||||||
print("🎉 数据库初始化完成!")
|
print("🎉 数据库初始化完成!")
|
||||||
print("=" * 80)
|
print("=" * 80)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"\n❌ 数据库初始化失败: {e}")
|
print(f"\n❌ 数据库初始化失败: {e}")
|
||||||
self.logger.error(f"数据库初始化失败: {e}", exc_info=True)
|
self.logger.error(f"数据库初始化失败: {e}", exc_info=True)
|
||||||
return False
|
return False
|
||||||
@@ -154,7 +154,7 @@ class DatabaseInitializer:
|
|||||||
|
|
||||||
if created_tables:
|
if created_tables:
|
||||||
print(f"✅ 新创建表: {', '.join(created_tables)}")
|
print(f"✅ 新创建表: {', '.join(created_tables)}")
|
||||||
else:
|
else:
|
||||||
print("✅ 所有表已存在")
|
print("✅ 所有表已存在")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
@@ -220,17 +220,17 @@ class DatabaseInitializer:
|
|||||||
# 检查表是否存在
|
# 检查表是否存在
|
||||||
inspector = inspect(db_manager.engine)
|
inspector = inspect(db_manager.engine)
|
||||||
if 'vehicle_data' not in inspector.get_table_names():
|
if 'vehicle_data' not in inspector.get_table_names():
|
||||||
print(" ➕ 创建vehicle_data表...")
|
print(" ➕ 创建vehicle_data表...")
|
||||||
VehicleData.__table__.create(session.bind, checkfirst=True)
|
VehicleData.__table__.create(session.bind, checkfirst=True)
|
||||||
print(" ✅ vehicle_data表创建成功")
|
print(" ✅ vehicle_data表创建成功")
|
||||||
else:
|
else:
|
||||||
print(" ✅ vehicle_data表已存在")
|
print(" ✅ vehicle_data表已存在")
|
||||||
|
|
||||||
session.commit()
|
session.commit()
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" ❌ 车辆数据表迁移失败: {e}")
|
print(f" ❌ 车辆数据表迁移失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _migrate_conversation_enhancements(self) -> bool:
|
def _migrate_conversation_enhancements(self) -> bool:
|
||||||
"""迁移对话增强字段"""
|
"""迁移对话增强字段"""
|
||||||
@@ -357,9 +357,9 @@ class DatabaseInitializer:
|
|||||||
else:
|
else:
|
||||||
print(f" 📊 所有字段都已存在,跳过 {skipped_count} 个字段")
|
print(f" 📊 所有字段都已存在,跳过 {skipped_count} 个字段")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" ❌ 添加字段过程失败: {e}")
|
print(f" ❌ 添加字段过程失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -391,15 +391,15 @@ class DatabaseInitializer:
|
|||||||
|
|
||||||
return result[0] > 0
|
return result[0] > 0
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _insert_initial_data(self) -> bool:
|
def _insert_initial_data(self) -> bool:
|
||||||
"""插入初始数据"""
|
"""插入初始数据"""
|
||||||
print("\n📊 插入初始数据...")
|
print("\n📊 插入初始数据...")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with db_manager.get_session() as session:
|
with db_manager.get_session() as session:
|
||||||
# 检查是否已有数据
|
# 检查是否已有数据
|
||||||
existing_count = session.query(KnowledgeEntry).count()
|
existing_count = session.query(KnowledgeEntry).count()
|
||||||
if existing_count > 0:
|
if existing_count > 0:
|
||||||
print(f" ✅ 数据库中已有 {existing_count} 条知识库条目,跳过初始数据插入")
|
print(f" ✅ 数据库中已有 {existing_count} 条知识库条目,跳过初始数据插入")
|
||||||
@@ -541,53 +541,53 @@ class DatabaseInitializer:
|
|||||||
]
|
]
|
||||||
|
|
||||||
def _add_sample_vehicle_data(self) -> bool:
|
def _add_sample_vehicle_data(self) -> bool:
|
||||||
"""添加示例车辆数据"""
|
"""添加示例车辆数据"""
|
||||||
try:
|
try:
|
||||||
from src.vehicle.vehicle_data_manager import VehicleDataManager
|
from src.vehicle.vehicle_data_manager import VehicleDataManager
|
||||||
|
|
||||||
vehicle_manager = VehicleDataManager()
|
vehicle_manager = VehicleDataManager()
|
||||||
success = vehicle_manager.add_sample_vehicle_data()
|
success = vehicle_manager.add_sample_vehicle_data()
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
print(" ✅ 示例车辆数据添加成功")
|
print(" ✅ 示例车辆数据添加成功")
|
||||||
else:
|
else:
|
||||||
print(" ❌ 示例车辆数据添加失败")
|
print(" ❌ 示例车辆数据添加失败")
|
||||||
|
|
||||||
return success
|
return success
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" ❌ 添加示例车辆数据失败: {e}")
|
print(f" ❌ 添加示例车辆数据失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _verify_existing_knowledge(self) -> bool:
|
def _verify_existing_knowledge(self) -> bool:
|
||||||
"""验证现有的知识库条目"""
|
"""验证现有的知识库条目"""
|
||||||
try:
|
try:
|
||||||
with db_manager.get_session() as session:
|
with db_manager.get_session() as session:
|
||||||
# 获取所有未验证的知识库条目
|
# 获取所有未验证的知识库条目
|
||||||
unverified_entries = session.query(KnowledgeEntry).filter(
|
unverified_entries = session.query(KnowledgeEntry).filter(
|
||||||
KnowledgeEntry.is_verified == False
|
KnowledgeEntry.is_verified == False
|
||||||
).all()
|
).all()
|
||||||
|
|
||||||
if unverified_entries:
|
if unverified_entries:
|
||||||
print(f" 📝 发现 {len(unverified_entries)} 条未验证的知识库条目")
|
print(f" 📝 发现 {len(unverified_entries)} 条未验证的知识库条目")
|
||||||
|
|
||||||
# 将现有的知识库条目标记为已验证
|
# 将现有的知识库条目标记为已验证
|
||||||
for entry in unverified_entries:
|
for entry in unverified_entries:
|
||||||
entry.is_verified = True
|
entry.is_verified = True
|
||||||
entry.verified_by = "system_init"
|
entry.verified_by = "system_init"
|
||||||
entry.verified_at = datetime.now()
|
entry.verified_at = datetime.now()
|
||||||
if not hasattr(entry, 'search_frequency'):
|
if not hasattr(entry, 'search_frequency'):
|
||||||
entry.search_frequency = 0
|
entry.search_frequency = 0
|
||||||
if not hasattr(entry, 'relevance_score'):
|
if not hasattr(entry, 'relevance_score'):
|
||||||
entry.relevance_score = 0.7
|
entry.relevance_score = 0.7
|
||||||
|
|
||||||
session.commit()
|
session.commit()
|
||||||
print(f" ✅ 成功验证 {len(unverified_entries)} 条知识库条目")
|
print(f" ✅ 成功验证 {len(unverified_entries)} 条知识库条目")
|
||||||
else:
|
else:
|
||||||
print(" ✅ 所有知识库条目已验证")
|
print(" ✅ 所有知识库条目已验证")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f" ❌ 验证知识库条目失败: {e}")
|
print(f" ❌ 验证知识库条目失败: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _verify_database_integrity(self) -> bool:
|
def _verify_database_integrity(self) -> bool:
|
||||||
@@ -676,14 +676,14 @@ class DatabaseInitializer:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
def check_database_status(self) -> Dict[str, Any]:
|
def check_database_status(self) -> Dict[str, Any]:
|
||||||
"""检查数据库状态"""
|
"""检查数据库状态"""
|
||||||
print("\n" + "=" * 80)
|
print("\n" + "=" * 80)
|
||||||
print("📊 数据库状态检查")
|
print("📊 数据库状态检查")
|
||||||
print("=" * 80)
|
print("=" * 80)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with db_manager.get_session() as session:
|
with db_manager.get_session() as session:
|
||||||
# 检查各表的记录数
|
# 检查各表的记录数
|
||||||
tables_info = {
|
tables_info = {
|
||||||
'work_orders': WorkOrder,
|
'work_orders': WorkOrder,
|
||||||
'conversations': Conversation,
|
'conversations': Conversation,
|
||||||
@@ -711,19 +711,19 @@ class DatabaseInitializer:
|
|||||||
status["tables"][table_name] = f"错误: {e}"
|
status["tables"][table_name] = f"错误: {e}"
|
||||||
print(f"⚠️ {table_name}: 检查失败 - {e}")
|
print(f"⚠️ {table_name}: 检查失败 - {e}")
|
||||||
|
|
||||||
# 检查车辆数据详情
|
# 检查车辆数据详情
|
||||||
if 'vehicle_data' in status["tables"] and isinstance(status["tables"]['vehicle_data'], int):
|
if 'vehicle_data' in status["tables"] and isinstance(status["tables"]['vehicle_data'], int):
|
||||||
vehicle_count = status["tables"]['vehicle_data']
|
vehicle_count = status["tables"]['vehicle_data']
|
||||||
if vehicle_count > 0:
|
if vehicle_count > 0:
|
||||||
vehicle_ids = session.query(VehicleData.vehicle_id).distinct().all()
|
vehicle_ids = session.query(VehicleData.vehicle_id).distinct().all()
|
||||||
print(f" - 车辆数量: {len(vehicle_ids)}")
|
print(f" - 车辆数量: {len(vehicle_ids)}")
|
||||||
status["vehicle_count"] = len(vehicle_ids)
|
status["vehicle_count"] = len(vehicle_ids)
|
||||||
|
|
||||||
for vehicle_id in vehicle_ids[:3]: # 显示前3个车辆
|
for vehicle_id in vehicle_ids[:3]: # 显示前3个车辆
|
||||||
vehicle_data_types = session.query(VehicleData.data_type).filter(
|
vehicle_data_types = session.query(VehicleData.data_type).filter(
|
||||||
VehicleData.vehicle_id == vehicle_id[0]
|
VehicleData.vehicle_id == vehicle_id[0]
|
||||||
).distinct().all()
|
).distinct().all()
|
||||||
print(f" - 车辆 {vehicle_id[0]}: {len(vehicle_data_types)} 种数据类型")
|
print(f" - 车辆 {vehicle_id[0]}: {len(vehicle_data_types)} 种数据类型")
|
||||||
|
|
||||||
# 检查知识库验证状态
|
# 检查知识库验证状态
|
||||||
if 'knowledge_entries' in status["tables"] and isinstance(status["tables"]['knowledge_entries'], int):
|
if 'knowledge_entries' in status["tables"] and isinstance(status["tables"]['knowledge_entries'], int):
|
||||||
@@ -737,12 +737,12 @@ class DatabaseInitializer:
|
|||||||
}
|
}
|
||||||
|
|
||||||
print(f"\n📊 总记录数: {status['total_records']}")
|
print(f"\n📊 总记录数: {status['total_records']}")
|
||||||
print("\n✅ 数据库状态检查完成")
|
print("\n✅ 数据库状态检查完成")
|
||||||
|
|
||||||
return status
|
return status
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ 数据库状态检查失败: {e}")
|
print(f"❌ 数据库状态检查失败: {e}")
|
||||||
return {"error": str(e)}
|
return {"error": str(e)}
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|||||||
Reference in New Issue
Block a user