69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
# 导入数据库工具
|
|
from db_utils import get_db_connection, close_db_connection
|
|
|
|
# 验证数据库结构是否完整
|
|
def verify_database_structure():
|
|
try:
|
|
# 连接数据库
|
|
conn = get_db_connection()
|
|
cursor = conn.cursor()
|
|
|
|
# 需要检查的表
|
|
tables_to_check = ['users', 'query_records']
|
|
verification_results = []
|
|
|
|
for table in tables_to_check:
|
|
# 检查表是否存在
|
|
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
|
|
table_exists = cursor.fetchone() is not None
|
|
|
|
if table_exists:
|
|
# 检查表的列结构
|
|
cursor.execute(f"PRAGMA table_info({table})")
|
|
columns = cursor.fetchall()
|
|
column_names = [col[1] for col in columns]
|
|
|
|
verification_results.append({
|
|
"table": table,
|
|
"exists": True,
|
|
"column_count": len(columns),
|
|
"columns": column_names
|
|
})
|
|
else:
|
|
verification_results.append({
|
|
"table": table,
|
|
"exists": False,
|
|
"column_count": 0,
|
|
"columns": []
|
|
})
|
|
|
|
# 关闭数据库连接
|
|
close_db_connection(conn)
|
|
|
|
# 构造返回结果
|
|
all_tables_exist = all(result['exists'] for result in verification_results)
|
|
|
|
return {
|
|
"success": all_tables_exist,
|
|
"results": verification_results
|
|
}
|
|
except Exception as e:
|
|
# 确保在异常情况下也关闭连接
|
|
if 'conn' in locals() and conn:
|
|
close_db_connection(conn)
|
|
|
|
return {
|
|
"success": False,
|
|
"error": str(e)
|
|
}
|
|
|
|
# 如果直接运行此脚本,则执行验证操作
|
|
if __name__ == "__main__":
|
|
result = verify_database_structure()
|
|
print(f"数据库结构验证: {'通过' if result['success'] else '失败'}")
|
|
if result['success']:
|
|
print("验证详情:")
|
|
for table_result in result['results']:
|
|
print(f" - 表 {table_result['table']}: 存在,包含 {table_result['column_count']} 个字段")
|
|
else:
|
|
print(f"错误信息: {result['error']}") |