53 lines
1.8 KiB
Python
53 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
修复 alembic_version 表:如果数据库里记录了不存在的版本号(如 002),
|
||
将其重置为当前最新的迁移版本(如 001)。
|
||
用法(在项目根目录):
|
||
python deploy/scripts/fix_alembic_version.py
|
||
"""
|
||
import os
|
||
import sys
|
||
|
||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "backend"))
|
||
|
||
from dotenv import load_dotenv
|
||
|
||
load_dotenv(os.path.join(os.path.dirname(__file__), "..", "..", ".env"))
|
||
|
||
from sqlalchemy import create_engine, text
|
||
|
||
DATABASE_URL_SYNC = os.getenv(
|
||
"DATABASE_URL_SYNC",
|
||
"postgresql://wecom:wecom_secret@localhost:5432/wecom_ai",
|
||
)
|
||
|
||
|
||
def main():
|
||
engine = create_engine(DATABASE_URL_SYNC)
|
||
with engine.connect() as conn:
|
||
# 检查 alembic_version 表
|
||
try:
|
||
r = conn.execute(text("SELECT version_num FROM alembic_version"))
|
||
current = r.scalar_one_or_none()
|
||
if current:
|
||
print(f"当前数据库版本: {current}")
|
||
if current == "002":
|
||
print("检测到版本 002,但本地只有 001。重置为 001...")
|
||
conn.execute(text("UPDATE alembic_version SET version_num = '001'"))
|
||
conn.commit()
|
||
print("已重置为 001。")
|
||
else:
|
||
print(f"版本 {current} 正常,无需修复。")
|
||
else:
|
||
print("alembic_version 表为空,无需修复。")
|
||
except Exception as e:
|
||
if "does not exist" in str(e) or "relation" in str(e).lower():
|
||
print("alembic_version 表不存在,这是首次迁移前的状态,正常。")
|
||
else:
|
||
print(f"错误: {e}")
|
||
sys.exit(1)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|