#!/usr/bin/env python3 """Core → jinrong_agent.customer_advisor_rel 同步。""" from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT)) from sqlalchemy import create_engine, text from app.config.settings import settings def db_url(database: str) -> str: pwd = settings.mysql_password auth = f"{settings.mysql_user}:{pwd}" if pwd else settings.mysql_user return ( f"mysql+pymysql://{auth}@{settings.mysql_host}:{settings.mysql_port}" f"/{database}?charset=utf8mb4" ) def main() -> None: core = create_engine(db_url(settings.mysql_core_database), pool_pre_ping=True) agent = create_engine(db_url(settings.mysql_database), pool_pre_ping=True) with core.connect() as cconn: rows = cconn.execute( text( """ SELECT customer_id, advisor_id, rel_status, effective_from, effective_to FROM core_customer_advisor WHERE rel_status = 'active' """ ) ).mappings().all() upsert_sql = text( """ INSERT INTO customer_advisor_rel (customer_id, advisor_id, rel_status, effective_from, effective_to, synced_at) VALUES (:customer_id, :advisor_id, :rel_status, :effective_from, :effective_to, NOW(3)) ON DUPLICATE KEY UPDATE rel_status = VALUES(rel_status), effective_to = VALUES(effective_to), synced_at = NOW(3) """ ) with agent.begin() as aconn: for row in rows: aconn.execute(upsert_sql, dict(row)) print(f"sync_advisor_rel: upserted {len(rows)} rows → {settings.mysql_database}.customer_advisor_rel") if __name__ == "__main__": main()