59 lines
1.8 KiB
Python
59 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
修复 users 表:添加缺失的列(role、is_active、created_at)。
|
||
用法(在项目根目录):
|
||
python deploy/scripts/fix_users_table.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, inspect
|
||
|
||
DATABASE_URL_SYNC = os.getenv(
|
||
"DATABASE_URL_SYNC",
|
||
"postgresql://wecom:wecom_secret@localhost:5432/wecom_ai",
|
||
)
|
||
|
||
|
||
def main():
|
||
engine = create_engine(DATABASE_URL_SYNC)
|
||
inspector = inspect(engine)
|
||
|
||
if not inspector.has_table("users"):
|
||
print("users 表不存在,请先执行迁移。")
|
||
sys.exit(1)
|
||
|
||
columns = [c["name"] for c in inspector.get_columns("users")]
|
||
print(f"当前 users 表的列: {columns}")
|
||
|
||
with engine.connect() as conn:
|
||
if "role" not in columns:
|
||
print("添加 role 列...")
|
||
conn.execute(text("ALTER TABLE users ADD COLUMN IF NOT EXISTS role VARCHAR(32) NOT NULL DEFAULT 'admin'"))
|
||
conn.commit()
|
||
print("✓ role 已添加")
|
||
|
||
if "is_active" not in columns:
|
||
print("添加 is_active 列...")
|
||
conn.execute(text("ALTER TABLE users ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true"))
|
||
conn.commit()
|
||
print("✓ is_active 已添加")
|
||
|
||
if "created_at" not in columns:
|
||
print("添加 created_at 列...")
|
||
conn.execute(text("ALTER TABLE users ADD COLUMN IF NOT EXISTS created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()"))
|
||
conn.commit()
|
||
print("✓ created_at 已添加")
|
||
|
||
print("修复完成。")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|