56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
from sqlalchemy import create_engine, text
|
|
import json
|
|
import os
|
|
|
|
# 数据库连接配置
|
|
DATABASE_URL = "sqlite:///./cpy_admin.db" # 修改为正确的数据库文件名
|
|
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
|
|
|
|
def backup_data():
|
|
"""备份现有数据"""
|
|
if not os.path.exists("cpy_admin.db"): # 检查数据库文件是否存在
|
|
print("数据库文件不存在,跳过备份")
|
|
return []
|
|
|
|
with engine.connect() as conn:
|
|
result = conn.execute(text("SELECT id FROM devices"))
|
|
devices = []
|
|
for row in result:
|
|
devices.append({"id": row[0]})
|
|
return devices
|
|
|
|
def migrate():
|
|
"""执行迁移"""
|
|
try:
|
|
# 备份现有数据
|
|
devices = backup_data()
|
|
|
|
with engine.connect() as conn:
|
|
try:
|
|
# 添加 enabled 列
|
|
conn.execute(text("ALTER TABLE devices ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT 1"))
|
|
conn.commit()
|
|
print("已添加 enabled 字段")
|
|
|
|
# 恢复数据
|
|
for device in devices:
|
|
conn.execute(
|
|
text("UPDATE devices SET enabled = :enabled WHERE id = :id"),
|
|
{"enabled": True, "id": device['id']}
|
|
)
|
|
conn.commit()
|
|
print("已更新现有设备的 enabled 状态")
|
|
|
|
except Exception as e:
|
|
if "duplicate column name" in str(e).lower():
|
|
print("enabled 字段已存在,跳过添加")
|
|
else:
|
|
raise e
|
|
|
|
except Exception as e:
|
|
print(f"迁移过程中出错: {str(e)}")
|
|
return
|
|
|
|
if __name__ == "__main__":
|
|
migrate()
|
|
print("迁移完成") |