Files
syops/backend/app/services/schedule/sql_preview_service.py
T

56 lines
2.2 KiB
Python

"""
backend/app/services/schedule/sql_preview_service.py
用途:排程抓取 SQL 预览(test-sql 业务编排)。
依赖:services/schedule、sql_config、srm_service。
逻辑:由 api/schedule/config.py 调用。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError, NotFoundError
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.serialization import safe_json_value
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id
def preview_fetch_sql(task_id: int, data: dict[str, Any]) -> dict[str, Any]:
"""
执行抓取 SQL 预览查询。
Args:
task_id: ScheduleTask 主键。
data: 可选 fetch_where_conditions、fetch_order_by、limit。
Returns:
total、showing、limit、sql、columns、rows。
Raises:
NotFoundError: 任务配置不存在。
AppError: SQL 执行失败。
"""
cfg = get_schedule_sql_config_by_task_id(task_id)
if not cfg:
raise NotFoundError(f'Config for task {task_id} not found')
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
limit = min(int(data.get('limit') or 10), 100)
base = cfg.base_fetch_sql or cfg.fetch_sql
sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base
try:
if cfg.data_source and (not cfg.data_source.is_empty()):
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, sql)
result_rows = [{k: safe_json_value(v) for k, v in r.items()} for r in rows[:limit]]
return {
'total': len(rows),
'showing': len(result_rows),
'limit': limit,
'sql': sql,
'columns': list(result_rows[0].keys()) if result_rows else [],
'rows': result_rows,
}
except Exception as exc:
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=400, details={'sql': sql})