"""运行可由 Cron 或任务平台调用的 NL2SQL 运维任务。""" from __future__ import annotations import argparse import asyncio import json import sys from datetime import datetime, timedelta, timezone from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from config.deps import get_redis from nl2sql.jobs import run_consistency_check, run_history_cleanup, run_metadata_sync, run_vector_cleanup async def run(task: str) -> dict: redis = next(get_redis()) if task == "metadata_sync": result = await run_metadata_sync(redis=redis) elif task == "vector_cleanup": result = await run_vector_cleanup(redis=redis) elif task == "consistency_check": from scripts.check_nl2sql_consistency import collect_consistency result = await run_consistency_check(redis=redis, worker=collect_consistency) elif task == "history_cleanup": from config.database.mysql import get_session_factory async with get_session_factory()() as db: result = await run_history_cleanup( db, datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(days=180), redis=redis, ) else: raise ValueError("不支持的 NL2SQL 运维任务") return { "name": result.name, "status": result.status, "attempts": result.attempts, "detail": result.detail, "error_type": result.error_type, } def main() -> None: parser = argparse.ArgumentParser(description="NL2SQL 运维任务") parser.add_argument( "task", choices=["metadata_sync", "vector_cleanup", "consistency_check", "history_cleanup"], ) args = parser.parse_args() print(json.dumps(asyncio.run(run(args.task)), ensure_ascii=False)) if __name__ == "__main__": main()