49 lines
1.2 KiB
Python
49 lines
1.2 KiB
Python
"""
|
|
数据库迁移:给 users 表添加微信登录字段
|
|
运行方式: python migrate_add_wx_fields.py
|
|
"""
|
|
import sqlite3
|
|
import os
|
|
|
|
DB_PATHS = [
|
|
"weibo_hotsign.db",
|
|
"backend/weibo_hotsign.db",
|
|
]
|
|
|
|
def migrate(db_path):
|
|
if not os.path.exists(db_path):
|
|
print(f" 跳过 {db_path}(文件不存在)")
|
|
return
|
|
|
|
conn = sqlite3.connect(db_path)
|
|
cursor = conn.cursor()
|
|
|
|
cursor.execute("PRAGMA table_info(users)")
|
|
columns = {row[1] for row in cursor.fetchall()}
|
|
|
|
added = []
|
|
for col in ["wx_openid", "wx_nickname", "wx_avatar"]:
|
|
if col not in columns:
|
|
cursor.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT")
|
|
added.append(col)
|
|
|
|
# 创建唯一索引
|
|
try:
|
|
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_wx_openid ON users(wx_openid)")
|
|
except Exception:
|
|
pass
|
|
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
if added:
|
|
print(f" ✅ {db_path}: 添加了 {', '.join(added)}")
|
|
else:
|
|
print(f" ✅ {db_path}: 字段已存在,无需迁移")
|
|
|
|
if __name__ == "__main__":
|
|
print("正在迁移数据库...")
|
|
for p in DB_PATHS:
|
|
migrate(p)
|
|
print("迁移完成!")
|