feat: 采集可以按字段名称查找对应的数据表
This commit is contained in:
+32
-1
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(), " "))
|
||||
@@ -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<number | null>(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);
|
||||
<n-modal v-model:show="show" class="app-dialog app-dialog-collect" preset="card" :show-icon="false" title="采集">
|
||||
<div class="collect-form">
|
||||
<div class="form-row"><label>名称</label><n-input v-model:value="name" /></div>
|
||||
<div class="form-row form-row-find">
|
||||
<label>按字段找表</label>
|
||||
<div class="field-find">
|
||||
<div class="field-find-bar">
|
||||
<n-input v-model:value="fieldQuery" placeholder="输入字段名称" clearable @keydown.enter.prevent="searchTables" />
|
||||
<n-button type="primary" :loading="fieldSearchLoading" @click="searchTables">查找</n-button>
|
||||
</div>
|
||||
<p v-if="fieldSearched" class="time-hint">{{ fieldHits.length ? `找到 ${fieldHits.length} 张表` : "没有找到包含这个字段的表" }}</p>
|
||||
<div v-if="fieldHits.length" class="find-list">
|
||||
<div v-for="table in fieldHits" :key="table.tablename" class="find-row">
|
||||
<div class="find-copy">
|
||||
<strong>{{ table.name }}</strong>
|
||||
<span :title="matchedText(table.fields)">{{ matchedText(table.fields) }}</span>
|
||||
</div>
|
||||
<n-button size="small" :disabled="picked.includes(table.tablename)" @click="addFound(table)">
|
||||
{{ picked.includes(table.tablename) ? "已选" : "选用" }}
|
||||
</n-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>数据表</label>
|
||||
<div class="table-picker">
|
||||
@@ -507,6 +575,31 @@ onMounted(load);
|
||||
|
||||
<style scoped>
|
||||
.collect-form { display: grid; gap: 12px; min-width: 0; }
|
||||
.form-row-find { align-items: start; }
|
||||
.form-row-find > label { padding-top: 6px; }
|
||||
.field-find { display: grid; gap: 8px; min-width: 0; }
|
||||
.field-find-bar { display: flex; gap: 8px; min-width: 0; }
|
||||
.field-find-bar .n-button { flex: none; }
|
||||
.find-list {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
max-height: 180px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.find-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.find-row:last-child { border-bottom: 0; }
|
||||
.find-copy { min-width: 0; }
|
||||
.find-copy strong, .find-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.find-copy span { color: var(--muted); font-size: 12px; }
|
||||
.table-picker { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.table-select { flex: 1; min-width: 0; }
|
||||
.picked-link { flex: none; }
|
||||
|
||||
Reference in New Issue
Block a user