feat: 选表时可以查看这张表的字段

This commit is contained in:
2026-11-10 09:21:43 +08:00
parent 2346d80f8e
commit 4a29a1ec1b
3 changed files with 106 additions and 3 deletions
+29 -1
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import base64
import re
from datetime import date, datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Request
@@ -16,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, tables, time_window
from app.nqi.adhoc import TIME_MODES, catalog_tree, categories, 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
@@ -560,6 +561,33 @@ def nqi_catalog(code: int | None = None, tree: bool = False, actor: Actor = Depe
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)
if not re.fullmatch(r"[A-Za-z0-9_.]{1,180}", tablename):
raise _bad("请选择要查看的表")
cookies = _pool_cookies(session)
async def run() -> dict:
client = NqiClient()
try:
client.import_cookies(cookies)
await client.current_user()
try:
return {"columns": await table_fields(client, tablename)}
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
def _pool_cookies(session: Session) -> list:
account = session.scalar(select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc()))
cookies = list(account.cookies or []) if account is not None else []
+12
View File
@@ -259,6 +259,18 @@ def _csv(columns: list[dict], rows: list[dict]) -> bytes:
return buffer.getvalue().encode("utf-8-sig")
async def table_fields(client: NqiClient, tablename: str) -> list[dict]:
await ensure_session(client)
rows = await _columns(client, tablename)
fields = []
for row in rows:
name = str(row.get("columnname_cn") or row.get("columnname") or "").strip()
if not name:
continue
fields.append({"name": name, "type": str(row.get("datatype") or "").strip()})
return fields
async def _columns(client: NqiClient, tablename: str) -> list[dict]:
payload = await _post_json(client, f"{PAGE}/getSelectTable", {"tablename": tablename})
rows = payload.get("CFG_ADHOC_CONF_TABLE") if isinstance(payload, dict) else None
+65 -2
View File
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { computed, h, onMounted, ref } from "vue";
import { NButton, NIcon, NInput, NInputNumber, NModal, NSelect, NSwitch, NTimePicker, NTooltip, useDialog } from "naive-ui";
import type { SelectRenderTag } from "naive-ui";
import { CreateOutline, TrashOutline } from "@vicons/ionicons5";
import type { SelectRenderLabel, SelectRenderTag } from "naive-ui";
import { CreateOutline, InformationCircleOutline, TrashOutline } from "@vicons/ionicons5";
import Shell from "../../shell/Shell.vue";
import { api } from "../../shared/http";
import { useToast } from "../../shared/toast";
@@ -35,6 +35,10 @@ interface Group {
const sources = ref<Source[]>([]);
const show = ref(false);
const details = ref(false);
const fieldsOpen = ref(false);
const fieldsLoading = ref(false);
const fieldsTitle = ref("");
const fields = ref<{ name: string; type: string }[]>([]);
const editing = ref<Source | null>(null);
const name = ref("");
const enabled = ref(true);
@@ -71,6 +75,48 @@ const tableOptions = computed(() => groups.value.map((group) => ({
const picked = computed(() => chosen.value.map((item) => item.tablename));
const pickedText = computed(() => chosen.value.map((item) => item.name).join("、"));
const renderTag: SelectRenderTag = () => h("span", { class: "picker-inline" }, pickedText.value);
const renderTableLabel: SelectRenderLabel = (option) => {
if (option.type === "group") return String(option.label ?? "");
const title = String(option.label ?? "");
const tablename = String(option.value ?? "");
return h("div", { style: "display:flex;align-items:center;gap:8px;width:100%;min-width:0" }, [
h("span", { style: "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" }, title),
h(NTooltip, null, {
trigger: () => h(NButton, {
size: "tiny",
quaternary: true,
circle: true,
ariaLabel: "字段",
onMousedown: (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
},
onClick: (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
void openFields(tablename, title);
},
}, { icon: () => h(NIcon, { component: InformationCircleOutline }) }),
default: () => "字段",
}),
]);
};
async function openFields(tablename: string, title: string) {
fieldsTitle.value = title || "字段";
fields.value = [];
fieldsOpen.value = true;
fieldsLoading.value = true;
try {
const result = await api<{ columns: { name: string; type: string }[] }>(`/api/admin/nqi/columns?tablename=${encodeURIComponent(tablename)}`);
fields.value = result.columns;
} catch (error) {
fieldsOpen.value = false;
toast.error(error instanceof Error ? error.message : "字段没有获取到");
} finally {
fieldsLoading.value = false;
}
}
function scheduleText(source: Source) {
const schedule = source.config.schedule;
@@ -267,6 +313,7 @@ onMounted(load);
:value="picked"
:options="tableOptions"
:loading="catalogLoading"
:render-label="renderTableLabel"
:render-tag="renderTag"
@update:value="setPicked"
/>
@@ -297,6 +344,19 @@ onMounted(load);
</div>
</template>
</n-modal>
<n-modal v-model:show="fieldsOpen" class="app-dialog" preset="card" :title="fieldsTitle || '字段'">
<p v-if="fieldsLoading" class="admin-status">正在读取字段</p>
<template v-else-if="fields.length">
<p class="admin-status">共 {{ fields.length }} 个字段</p>
<div class="field-list">
<div v-for="(field, index) in fields" :key="`${field.name}-${index}`" class="field-row">
<span>{{ field.name }}</span>
<span v-if="field.type" class="field-type">{{ field.type }}</span>
</div>
</div>
</template>
<p v-else class="admin-status">没有字段</p>
</n-modal>
<n-modal v-model:show="details" class="app-dialog" preset="card" title="已选表格">
<div v-if="chosen.length" class="picked-list">
<div v-for="item in chosen" :key="item.tablename" class="picked-row">
@@ -345,4 +405,7 @@ onMounted(load);
.picked-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.picked-row strong { display: block; }
.picked-row span { color: var(--muted); font-size: 12px; }
.field-list { display: grid; gap: 8px; margin-top: 8px; }
.field-row { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
.field-type { color: var(--muted); font-size: 12px; white-space: nowrap; }
</style>