From 7b28067d0cc47d5520fb13b8e8c26b643be000b0 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Tue, 10 Nov 2026 16:35:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=87=87=E9=9B=86=E5=8F=AF=E4=BB=A5?= =?UTF-8?q?=E6=8C=89=E5=AD=97=E6=AE=B5=E5=90=8D=E7=A7=B0=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=AF=B9=E5=BA=94=E7=9A=84=E6=95=B0=E6=8D=AE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/http.py | 33 ++++++++- backend/app/nqi/adhoc.py | 36 ++++++++++ backend/tests/test_field_search.py | 59 ++++++++++++++++ web/src/features/admin/SourcesView.vue | 93 ++++++++++++++++++++++++++ 4 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 backend/tests/test_field_search.py diff --git a/backend/app/api/http.py b/backend/app/api/http.py index 3285339..199d30b 100644 --- a/backend/app/api/http.py +++ b/backend/app/api/http.py @@ -17,7 +17,7 @@ from app.install import InstallError, perform_install from app.db import get_session, session_scope from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow from app.collect.schedule import next_run_at, parse_schedule -from app.nqi.adhoc import TIME_MODES, catalog_tree, categories, table_fields, tables, time_window +from app.nqi.adhoc import TIME_MODES, catalog_tree, categories, search_by_field, table_fields, tables, time_window from app.nqi.client import NqiAuthError, NqiClient, NqiError from app.nqi.flows import drop, purge, remember, take from app.security import hash_password, issue_token, verify_password @@ -561,6 +561,37 @@ def nqi_catalog(code: int | None = None, tree: bool = False, actor: Actor = Depe raise _bad(str(exc)) from exc +@router.get("/admin/nqi/search") +def nqi_search(key: str, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: + require_admin(actor) + try: + keyword = key.strip() + if not keyword or len(keyword) > 80 or any(ord(char) < 32 for char in keyword): + raise ValueError + except ValueError: + raise _bad("请输入字段名称") from None + cookies = _pool_cookies(session) + + async def run() -> dict: + client = NqiClient() + try: + client.import_cookies(cookies) + await client.current_user() + try: + return {"tables": await search_by_field(client, keyword)} + except NqiAuthError as exc: + raise NqiError("门户登录还在,但进入即席查询没有接上,请用这个大数据账号重新登录一次") from exc + finally: + await client.aclose() + + try: + return asyncio.run(run()) + except NqiAuthError as exc: + raise _bad("账号池凭证已失效") from exc + except NqiError as exc: + raise _bad(str(exc)) from exc + + @router.get("/admin/nqi/columns") def nqi_columns(tablename: str, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict: require_admin(actor) diff --git a/backend/app/nqi/adhoc.py b/backend/app/nqi/adhoc.py index 351b9b6..d744557 100644 --- a/backend/app/nqi/adhoc.py +++ b/backend/app/nqi/adhoc.py @@ -247,6 +247,42 @@ def _column_form(columns: list[dict]) -> dict: return form +async def search_by_field(client: NqiClient, keyword: str) -> list[dict]: + """按字段中文名、英文名或字段分类,找出包含它的表。""" + text = keyword.strip() + if not text or len(text) > 80 or any(ord(char) < 32 for char in text): + raise ValueError("请输入字段名称") + await ensure_session(client) + payload = await _post_json( + client, + f"{PAGE}/search", + {"key": text, "field": ["columnname_cn", "columnname", "fieldtype"]}, + ) + rows = payload.get("CFG_ADHOC_CONF_SEARCH") if isinstance(payload, dict) else None + if not isinstance(rows, list): + raise NqiError("没有查到相关的表") + grouped: dict[str, dict] = {} + order: list[str] = [] + for row in rows: + if not isinstance(row, dict): + continue + tablename = str(row.get("tablename") or "").strip() + field_name = str(row.get("columnname_cn") or row.get("columnname") or "").strip() + if not tablename or not field_name: + continue + item = grouped.get(tablename) + if item is None: + title = str(row.get("tablename_cn") or tablename).strip() or tablename + item = {"tablename": tablename, "name": title, "fields": []} + grouped[tablename] = item + order.append(tablename) + column = str(row.get("columnname") or "").strip() + if any(existing["column"] == column and existing["name"] == field_name for existing in item["fields"]): + continue + item["fields"].append({"name": field_name, "column": column, "type": str(row.get("datatype") or "").strip()}) + return [grouped[name] for name in order] + + async def table_fields(client: NqiClient, tablename: str) -> list[dict]: await ensure_session(client) rows = await _columns(client, tablename) diff --git a/backend/tests/test_field_search.py b/backend/tests/test_field_search.py new file mode 100644 index 0000000..8965b0a --- /dev/null +++ b/backend/tests/test_field_search.py @@ -0,0 +1,59 @@ +import asyncio + +import pytest + +from app.nqi.adhoc import search_by_field + + +def test_field_search_groups_hits_by_table(monkeypatch): + seen = {} + + async def fake_session(client): + seen["session"] = True + + async def fake_post(client, url, form): + seen["url"] = url + seen["form"] = form + return { + "CFG_ADHOC_CONF_SEARCH": [ + { + "tablename": "appdbv3.a_common_pm_lte", + "tablename_cn": "4G小区性能KPI报表", + "columnname": "uplastttioctdl", + "columnname_cn": "用户面下行尾包字节数", + "datatype": "character varying", + "fieldtype": "公共信息(小区级粒度)", + }, + { + "tablename": "appdbv3.a_common_pm_lte", + "tablename_cn": "4G小区性能KPI报表", + "columnname": "uplastttioctdl", + "columnname_cn": "用户面下行尾包字节数", + "datatype": "character varying", + }, + { + "tablename": "appdbv3.a_other", + "tablename_cn": "另一张表", + "columnname": "cgi", + "columnname_cn": "CGI", + "datatype": "character varying", + }, + {"tablename": "", "columnname_cn": "丢弃"}, + ] + } + + monkeypatch.setattr("app.nqi.adhoc.ensure_session", fake_session) + monkeypatch.setattr("app.nqi.adhoc._post_json", fake_post) + tables = asyncio.run(search_by_field(object(), " 尾包字节 ")) + assert seen["session"] is True + assert seen["url"].endswith("/pro-adhoc/adhocquery/search") + assert seen["form"]["key"] == "尾包字节" + assert seen["form"]["field"] == ["columnname_cn", "columnname", "fieldtype"] + assert [item["tablename"] for item in tables] == ["appdbv3.a_common_pm_lte", "appdbv3.a_other"] + assert tables[0]["fields"] == [{"name": "用户面下行尾包字节数", "column": "uplastttioctdl", "type": "character varying"}] + assert tables[1]["name"] == "另一张表" + + +def test_field_search_rejects_a_blank_keyword(): + with pytest.raises(ValueError): + asyncio.run(search_by_field(object(), " ")) diff --git a/web/src/features/admin/SourcesView.vue b/web/src/features/admin/SourcesView.vue index 9ecdfe7..1ebf4ef 100644 --- a/web/src/features/admin/SourcesView.vue +++ b/web/src/features/admin/SourcesView.vue @@ -59,6 +59,10 @@ const weekday = ref(1); const monthDay = ref(1); const clock = ref("08:00"); const catalogLoading = ref(false); +const fieldQuery = ref(""); +const fieldHits = ref<{ tablename: string; name: string; fields: { name: string; column: string; type: string }[] }[]>([]); +const fieldSearched = ref(false); +const fieldSearchLoading = ref(false); const runningId = ref(null); const dialog = useDialog(); const toast = useToast(); @@ -235,6 +239,9 @@ function reset(source?: Source) { weekday.value = Number(schedule?.weekday || 1); monthDay.value = Number(schedule?.monthDay || 1); clock.value = schedule?.time || "08:00"; + fieldQuery.value = ""; + fieldHits.value = []; + fieldSearched.value = false; show.value = true; if (!groups.value.length) void loadCatalog(); } @@ -275,6 +282,46 @@ function removeTable(tablename: string) { chosen.value = chosen.value.filter((item) => item.tablename !== tablename); } +function matchedText(fields: { name: string }[]) { + return fields.map((field) => field.name).filter(Boolean).join("、"); +} + +function addFound(table: { tablename: string; name: string }) { + if (chosen.value.some((item) => item.tablename === table.tablename)) return; + const known = lookup(table.tablename); + const item = known ?? { + code: 0, + category: "", + tablename: table.tablename, + name: table.name || table.tablename, + }; + const wasEmpty = chosen.value.length === 0; + chosen.value = [...chosen.value, item]; + if (wasEmpty && !name.value.trim()) name.value = item.name; +} + +async function searchTables() { + const key = fieldQuery.value.trim(); + if (!key) { + toast.error("请输入字段名称"); + return; + } + fieldSearchLoading.value = true; + try { + const result = await api<{ tables: { tablename: string; name: string; fields: { name: string; column: string; type: string }[] }[] }>( + `/api/admin/nqi/search?key=${encodeURIComponent(key)}`, + ); + fieldHits.value = result.tables; + fieldSearched.value = true; + } catch (error) { + fieldHits.value = []; + fieldSearched.value = false; + toast.error(error instanceof Error ? error.message : "没有查到相关的表"); + } finally { + fieldSearchLoading.value = false; + } +} + async function save() { if (!name.value.trim()) { toast.error("请填写名称"); @@ -420,6 +467,27 @@ onMounted(load);
+
+ +
+
+ + 查找 +
+

{{ fieldHits.length ? `找到 ${fieldHits.length} 张表` : "没有找到包含这个字段的表" }}

+
+
+
+ {{ table.name }} + {{ matchedText(table.fields) }} +
+ + {{ picked.includes(table.tablename) ? "已选" : "选用" }} + +
+
+
+
@@ -507,6 +575,31 @@ onMounted(load);