"""一次性迁移：admin_users 表新增 roles 字段。"""
import os
import sys
from pathlib import Path

from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parents[2] / ".env")

dsn = os.environ.get("TEST_APP_DB_DSN") or os.environ.get("APP_DB_DSN", "").replace("zqyy_app", "test_zqyy_app")
if not dsn:
    print("ERROR: 无法获取测试库 DSN", file=sys.stderr)
    sys.exit(1)

import psycopg2

conn = psycopg2.connect(dsn)
try:
    with conn.cursor() as cur:
        cur.execute("""
            ALTER TABLE admin_users
                ADD COLUMN IF NOT EXISTS roles text[] NOT NULL DEFAULT '{site_admin}';
        """)
        cur.execute("COMMENT ON COLUMN admin_users.roles IS '用户角色列表，如 site_admin / tenant_admin';")
    conn.commit()
    print("OK: admin_users.roles 列已添加")

    # 验证
    with conn.cursor() as cur:
        cur.execute("SELECT id, username, roles FROM admin_users LIMIT 5;")
        for row in cur.fetchall():
            print(f"  id={row[0]} username={row[1]} roles={row[2]}")
finally:
    conn.close()
