-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix_database.py
More file actions
79 lines (65 loc) · 2.63 KB
/
fix_database.py
File metadata and controls
79 lines (65 loc) · 2.63 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
# -*- coding: utf-8 -*-
# fix_database.py
"""
修复数据库:为 chat_history 表添加 username 字段
"""
from sqlalchemy import create_engine, text
# 【请修改】你的数据库配置(与 server.py 保持一致)
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:123456@localhost:3306/rag_db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
def fix_chat_history_table():
"""为 chat_history 表添加 username 字段"""
print("=" * 50)
print("🔧 正在修复数据库表结构...")
print("=" * 50)
try:
with engine.connect() as conn:
# 检查字段是否已存在
result = conn.execute(text("""
SELECT COUNT(*) as count
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'rag_db'
AND TABLE_NAME = 'chat_history'
AND COLUMN_NAME = 'username'
"""))
exists = result.fetchone()[0] > 0
if exists:
print("✅ username 字段已存在,无需修复")
else:
print("⚠️ 检测到缺少 username 字段,正在添加...")
# 添加 username 字段
conn.execute(text("""
ALTER TABLE chat_history
ADD COLUMN username VARCHAR(50) DEFAULT 'default' AFTER id
"""))
conn.commit()
print("✅ 已添加 username 字段")
# 添加索引以提升查询性能
try:
conn.execute(text("""
ALTER TABLE chat_history
ADD INDEX idx_username (username)
"""))
conn.commit()
print("✅ 已添加 username 索引")
except Exception as e:
print(f"⚠️ 索引可能已存在: {e}")
# 更新现有记录的 username 为 'default'
conn.execute(text("""
UPDATE chat_history
SET username = 'default'
WHERE username IS NULL OR username = ''
"""))
conn.commit()
print("✅ 已更新现有记录的 username")
print("\n" + "=" * 50)
print("✅ 数据库修复完成!")
print("=" * 50)
return True
except Exception as e:
print(f"\n❌ 修复失败: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
fix_chat_history_table()