text2sql.py 14.5 KB
"""数据问答接口:数据源 / 建模 / 问答(SSE) / 执行 / 沉淀库 / 审计。"""
from __future__ import annotations
import logging

from fastapi import APIRouter, HTTPException, Request
from sse_starlette.sse import EventSourceResponse

from ..core import db, llm
from ..jobs.queue import runner
from ..schemas import (
    AskRequest, ColumnUpdate, DataSourceCreate, DataSourceUpdate, DescribeRequest,
    EnableModelsRequest, InstructionUpsert, ModelUpdate, PairUpsert,
    ExplainRequest, RelationUpsert, RunSqlRequest, SummarizeRequest,
)
from ..text2sql import crypto, describe, executor, introspect, library, prompts, semantic
from ..text2sql.connectors import registry
from ..text2sql.connectors.base import ConnectionFailed
from ..text2sql.pipeline import run_ask
from . import deps

log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/sql", tags=["text2sql"])


def _need_ds(ds_id: int) -> dict:
    ds = semantic.get_datasource(ds_id)
    if ds is None:
        raise HTTPException(404, "数据源不存在")
    return ds


def _need_crypto() -> None:
    if not crypto.available():
        raise HTTPException(400, "未配置 SECRET_KEY,无法安全保存数据源口令。"
                                 "请在 .env 里设置一个足够长的随机串后重启服务。")


# ---------------- 元信息 ----------------
@router.get("/meta")
async def meta():
    return {"supported_types": registry.supported_types(),
            "crypto_ready": crypto.available(),
            "row_limit": executor.limits()[0],
            "timeout_ms": executor.limits()[1]}


# ---------------- 数据源 ----------------
@router.get("/datasources")
async def list_datasources():
    return semantic.list_datasources()


@router.post("/datasources")
async def create_datasource(payload: DataSourceCreate):
    _need_crypto()
    ds_id = semantic.create_datasource(**payload.model_dump())
    return semantic.get_datasource(ds_id)


@router.get("/datasources/{ds_id}")
async def get_datasource(ds_id: int):
    return _need_ds(ds_id)


@router.put("/datasources/{ds_id}")
async def update_datasource(ds_id: int, payload: DataSourceUpdate):
    _need_ds(ds_id)
    fields = payload.model_dump(exclude_unset=True)
    if "password" in fields:
        _need_crypto()
    semantic.update_datasource(ds_id, **fields)
    return semantic.get_datasource(ds_id)


@router.delete("/datasources/{ds_id}")
async def delete_datasource(ds_id: int):
    _need_ds(ds_id)
    semantic.delete_datasource(ds_id)
    return {"ok": True}


@router.post("/datasources/{ds_id}/test")
async def test_datasource(ds_id: int):
    _need_ds(ds_id)
    try:
        # 用 fresh 连接器:坏配置不该进连接池缓存
        info = semantic.connector_for(ds_id, fresh=True).test()
    except ConnectionFailed as e:
        semantic.mark_datasource(ds_id, "error", str(e))
        raise HTTPException(400, f"连接失败:{e}") from e
    except Exception as e:  # noqa: BLE001
        semantic.mark_datasource(ds_id, "error", str(e))
        raise HTTPException(400, str(e)[:500]) from e
    semantic.mark_datasource(ds_id, "ok", "")
    if info.get("account_writable"):
        info["warning"] = "这个账号有写权限。生成的 SQL 有只读校验兜底,但仍建议改用只读账号。"
    return info


@router.post("/datasources/{ds_id}/introspect")
async def start_introspect(ds_id: int, resample: bool = False):
    _need_ds(ds_id)
    job_id = db.create_job(0, job_type="introspect")
    ok = runner.submit(job_id, lambda: introspect.run_introspection(ds_id, resample))
    return {"job_id": job_id, "queued": ok, "queue_depth": runner.queue_depth()}


# ---------------- 建模 ----------------
@router.get("/datasources/{ds_id}/models")
async def list_models(ds_id: int, enabled_only: bool = False):
    _need_ds(ds_id)
    return semantic.models_with_columns(ds_id, enabled_only=enabled_only)


@router.put("/models/{model_id}")
async def update_model(model_id: int, payload: ModelUpdate):
    fields = payload.model_dump(exclude_unset=True)
    if "enabled" in fields:
        fields["enabled"] = 1 if fields["enabled"] else 0
    semantic.update_model(model_id, **fields)
    return {"ok": True}


@router.put("/columns/{column_id}")
async def update_column(column_id: int, payload: ColumnUpdate):
    fields = payload.model_dump(exclude_unset=True)
    for k in ("is_dimension", "is_measure", "enabled"):
        if k in fields:
            fields[k] = 1 if fields[k] else 0
    semantic.update_column(column_id, **fields)
    return {"ok": True}


@router.post("/datasources/{ds_id}/models/enable")
async def enable_models(ds_id: int, payload: EnableModelsRequest):
    _need_ds(ds_id)
    n = semantic.set_models_enabled(ds_id, payload.ids, payload.enabled)
    return {"ok": True, "changed": n}


@router.get("/datasources/{ds_id}/relations")
async def list_relations(ds_id: int):
    _need_ds(ds_id)
    return semantic.list_relations(ds_id)


@router.post("/datasources/{ds_id}/relations")
async def upsert_relation(ds_id: int, payload: RelationUpsert):
    _need_ds(ds_id)
    fields = payload.model_dump()
    fields["enabled"] = 1 if fields.pop("enabled", True) else 0
    models = {m["id"]: m for m in semantic.list_models(ds_id)}
    fm, tm = models.get(fields["from_model_id"]), models.get(fields["to_model_id"])
    if not fm or not tm:
        raise HTTPException(400, "关系两端必须是这个数据源下已存在的表")
    ft = fm["physical_table"] or fm["name"]
    tt = tm["physical_table"] or tm["name"]
    fields["condition_sql"] = f"{ft}.{fields['from_column']} = {tt}.{fields['to_column']}"
    if not fields.get("name"):
        fields["name"] = f"{ft}_{tt}"
    rel_id = semantic.upsert_relation(ds_id, **fields)
    return {"ok": True, "id": rel_id}


@router.delete("/relations/{rel_id}")
async def delete_relation(rel_id: int):
    semantic.delete_relation(rel_id)
    return {"ok": True}


@router.post("/datasources/{ds_id}/describe")
async def start_describe(ds_id: int, payload: DescribeRequest):
    """让大模型给已启用的表批量补描述与同义词(后台任务)。

    同义词是召回能不能命中的关键:物理列叫 sum_ax_package,
    业务同事说的是「会员服务卖了多少」,中间这层映射得补上。
    """
    _need_ds(ds_id)
    job_id = db.create_job(0, job_type="describe")
    ok = runner.submit(job_id, lambda: describe.run_describe(
        ds_id, overwrite=payload.overwrite, model_ids=payload.model_ids or None))
    return {"job_id": job_id, "queued": ok, "queue_depth": runner.queue_depth()}


@router.get("/datasources/{ds_id}/relations/recommend")
async def recommend_relations(ds_id: int):
    """这个库没有外键,靠列名 + 真实取值重叠率推关联路径。"""
    _need_ds(ds_id)
    return semantic.recommend_relations(ds_id)


# ---------------- 指标(只读:来自本体里绑定到这个数据源的聚合函数) ----------------
@router.get("/datasources/{ds_id}/metrics")
async def list_metrics(ds_id: int, enabled_only: bool = False):
    _need_ds(ds_id)
    return semantic.list_metrics(ds_id, enabled_only=enabled_only)


@router.get("/datasources/{ds_id}/metrics/issues")
async def metric_issues(ds_id: int):
    """指标自检:表达式引用的列是不是都还可用。有问题的指标不会进提示词。"""
    _need_ds(ds_id)
    return semantic.metric_issues(ds_id)


@router.post("/datasources/{ds_id}/categorize")
async def categorize(ds_id: int):
    """给还没分类的规则补一个分类。只填空,不动人工改过的。"""
    _need_ds(ds_id)
    return {"ok": True, **semantic.autocategorize(ds_id)}


# ---------------- 业务规则(指令)----------------
@router.get("/instructions")
async def list_instructions(ds_id: int = 0, scope: str = "sql"):
    return semantic.list_instructions(ds_id, scope=scope, enabled_only=False)


@router.post("/instructions")
async def upsert_instruction(payload: InstructionUpsert):
    fields = payload.model_dump()
    ds_id = fields.pop("ds_id", 0)
    fields["is_default"] = 1 if fields.pop("is_default", True) else 0
    fields["enabled"] = 1 if fields.pop("enabled", True) else 0
    return {"ok": True, "id": semantic.upsert_instruction(ds_id, **fields)}


@router.delete("/instructions/{ins_id}")
async def delete_instruction(ins_id: int):
    semantic.delete_instruction(ins_id)
    return {"ok": True}


@router.get("/datasources/{ds_id}/mdl")
async def export_mdl(ds_id: int):
    _need_ds(ds_id)
    return semantic.export_mdl(ds_id)


@router.post("/datasources/{ds_id}/snapshot")
async def take_snapshot(ds_id: int, note: str = ""):
    _need_ds(ds_id)
    return {"ok": True, "id": semantic.snapshot(ds_id, note)}


# ---------------- 问答 ----------------
@router.post("/ask")
async def ask(payload: AskRequest, request: Request):
    _need_ds(payload.ds_id)
    gen = run_ask(payload.ds_id, payload.question.strip(), history=payload.history,
                  overrides=payload.overrides, thread_id=payload.thread_id,
                  approved_plan=payload.approved_plan)
    return EventSourceResponse(deps.sse(gen, request))


@router.post("/validate")
async def validate_sql(payload: RunSqlRequest):
    """只校验不执行。SQL 编辑器里边打边给反馈用。"""
    _need_ds(payload.ds_id)
    ds = semantic.get_datasource(payload.ds_id)
    return executor.validate(payload.ds_id, payload.sql, ds["ds_type"]).as_dict()


@router.post("/run")
async def run_sql(payload: RunSqlRequest):
    """执行用户手改过的 SQL。和管线走同一套 guard —— 不能有第二条绕过校验的路径。"""
    ds = _need_ds(payload.ds_id)
    outcome = executor.execute(payload.ds_id, payload.sql, ds["ds_type"])
    if not outcome.ok:
        run_id = executor.log_run(
            payload.ds_id, payload.question, payload.sql, payload.sql,
            "invalid" if outcome.error_kind == "guard" else "error",
            thread_id=payload.thread_id, error=outcome.error)
        raise HTTPException(400, detail=outcome.error)

    r = outcome.result
    run_id = executor.log_run(
        payload.ds_id, payload.question, payload.origin_sql or payload.sql,
        outcome.guard.sql, "ok", thread_id=payload.thread_id,
        row_count=r.row_count, duration_ms=r.duration_ms)

    pair_id = 0
    if payload.question.strip():
        # 用户改过 SQL 再跑通,是最值钱的信号:它直接标出了模型的系统性偏差。
        edited = bool(payload.origin_sql and payload.origin_sql.strip() != payload.sql.strip())
        try:
            pair_id = library.capture(
                payload.ds_id, payload.question, outcome.guard.sql,
                source="user_edited" if edited else "auto", run_id=run_id,
                models_used=outcome.guard.tables,
                sql_before=payload.origin_sql if edited else "")
        except Exception:  # noqa: BLE001
            log.exception("沉淀问答对失败")

    return {"ok": True, "run_id": run_id, "pair_id": pair_id,
            "columns": r.columns, "rows": r.rows, "row_count": r.row_count,
            "duration_ms": r.duration_ms, "truncated": r.truncated,
            "sql": outcome.guard.sql, "limited": outcome.guard.limited,
            "issues": [i.as_dict() for i in outcome.guard.issues]}


@router.post("/explain")
async def explain(payload: ExplainRequest):
    """用业务语言解释一条 SQL。

    按需生成:这段话在界面上默认是折叠的,没人展开就不该为它多花一轮往返。
    管线里做完这件事再发 done,意味着用户看完结论还要等三五秒才能问下一句。
    """
    _need_ds(payload.ds_id)
    text = llm.chat(prompts.build_explain_messages(payload.question, payload.sql),
                    temperature=0.3)
    return {"ok": True, "text": text}


@router.post("/summarize")
async def summarize(payload: SummarizeRequest):
    """对一批结果重新出结论。

    用户在编辑器里改完 SQL 点重跑,数据换了,可上一轮的「结论」还挂在那儿 ——
    那是比没有结论更糟的东西:它看起来仍然在解释屏幕上的表格。
    重跑走的是 /run(不经管线,自然也没有结论),所以单独留这个出口补上。
    """
    _need_ds(payload.ds_id)
    text = llm.chat(prompts.build_summary_messages(
        payload.question, payload.columns, payload.rows,
        payload.row_count or len(payload.rows)), temperature=0.3)
    return {"ok": True, "text": text}


# ---------------- 审计 ----------------
@router.get("/runs")
async def list_runs(ds_id: int | None = None, limit: int = 30):
    return executor.list_runs(ds_id, limit)


@router.get("/runs/{run_id}")
async def get_run(run_id: int):
    r = executor.get_run(run_id)
    if not r:
        raise HTTPException(404, "记录不存在")
    return r


@router.post("/runs/{run_id}/rate")
async def rate_run(run_id: int, rating: int = 0):
    if not executor.get_run(run_id):
        raise HTTPException(404, "记录不存在")
    executor.rate_run(run_id, max(-1, min(1, rating)))
    return {"ok": True}


# ---------------- 沉淀库 ----------------
@router.get("/pairs")
async def list_pairs(ds_id: int | None = None, status: str | None = None,
                     keyword: str = "", limit: int = 100):
    return library.list_pairs(ds_id, status, keyword, limit)


@router.post("/pairs")
async def create_pair(payload: PairUpsert):
    if not payload.ds_id or not payload.question or not payload.sql:
        raise HTTPException(400, "ds_id、question、sql 都不能为空")
    _need_ds(payload.ds_id)
    pair_id = library.capture(payload.ds_id, payload.question, payload.sql,
                              source="user_saved", status=payload.status or "verified")
    if payload.status:
        library.set_status(pair_id, payload.status)
    return {"ok": True, "id": pair_id}


@router.put("/pairs/{pair_id}")
async def update_pair(pair_id: int, payload: PairUpsert):
    if not library.get_pair(pair_id):
        raise HTTPException(404, "记录不存在")
    fields = payload.model_dump(exclude_unset=True, exclude_none=True)
    fields.pop("ds_id", None)
    status = fields.pop("status", None)
    if fields:
        library.update_pair(pair_id, **fields)
    if status:
        library.set_status(pair_id, status)
    return library.get_pair(pair_id)


@router.post("/pairs/{pair_id}/adopt")
async def adopt_pair(pair_id: int):
    """把草稿升成已采纳。只有采纳过的才会进 few-shot。"""
    if not library.get_pair(pair_id):
        raise HTTPException(404, "记录不存在")
    library.set_status(pair_id, "verified")
    return library.get_pair(pair_id)


@router.delete("/pairs/{pair_id}")
async def delete_pair(pair_id: int):
    library.delete_pair(pair_id)
    return {"ok": True}