# -*- coding: utf-8 -*-
"""
修复 test_zqyy_app 的 FDW：
1. 为 local-Python 添加 user mapping（IMPORT 需要当前用户有映射）
2. 重新 IMPORT FOREIGN SCHEMA
"""
import psycopg2

CONN = dict(host="100.64.0.4", port=5432, user="local-Python", password="Neo-local-1991125")

conn = psycopg2.connect(**CONN, dbname="test_zqyy_app")
conn.autocommit = True
cur = conn.cursor()

steps = [
    # 为执行用户添加 user mapping（用超级用户身份连远程库）
    (
        "CREATE USER MAPPING IF NOT EXISTS FOR \"local-Python\" "
        "SERVER test_etl_feiqiu_server "
        "OPTIONS (user 'local-Python', password 'Neo-local-1991125')",
        "添加 local-Python user mapping"
    ),
    # 导入外部表
    (
        "IMPORT FOREIGN SCHEMA app FROM SERVER test_etl_feiqiu_server INTO fdw_etl",
        "导入 test_etl_feiqiu.app 外部表"
    ),
]

for sql, label in steps:
    try:
        cur.execute(sql)
        print(f"[OK] {label}")
    except Exception as e:
        conn.rollback()
        msg = str(e).strip().split("\n")[0]
        print(f"[FAIL] {label}: {msg}")

# 验证
cur.execute(
    "SELECT count(*) FROM information_schema.tables "
    "WHERE table_schema = 'fdw_etl'"
)
count = cur.fetchone()[0]
print(f"\n验证: fdw_etl 外部表数 = {count}")

# 同时给 zqyy_app 也加上 local-Python mapping（方便调试）
conn.close()
conn = psycopg2.connect(**CONN, dbname="zqyy_app")
conn.autocommit = True
cur = conn.cursor()
try:
    cur.execute(
        "CREATE USER MAPPING IF NOT EXISTS FOR \"local-Python\" "
        "SERVER etl_feiqiu_server "
        "OPTIONS (user 'local-Python', password 'Neo-local-1991125')"
    )
    print("[OK] zqyy_app: 添加 local-Python user mapping")
except Exception as e:
    msg = str(e).strip().split("\n")[0]
    print(f"[SKIP] zqyy_app: {msg}")

conn.close()
print("\n完成!")
