修改 bug--20261202

这个提交包含在:
apple
2026-12-02 10:42:14 +08:00
父节点 17e80cef9c
当前提交 bd87d49778
共修改 28 个文件,包含 441 行新增和 15 行删除
@@ -65,6 +65,7 @@
</el-table-column>
<el-table-column width="300" class-name="dg-row-actions dg-row-actions-nowrap" label="操作" fixed="right" align="center">
<template #default="{ row }"><RowActions>
<el-button v-if="row.language === 'SQL'" v-hasPermi="['aixun:dataops:code-development:debug']" link type="primary" icon="VideoPlay" @click="openExecution(row)">立即执行</el-button>
<el-tooltip content="编辑" placement="top">
<el-button
v-hasPermi="['aixun:dataops:code-development:update']"
@@ -327,6 +328,10 @@
</el-table-column>
</el-table>
</el-tab-pane>
<el-tab-pane v-if="editorForm.language === 'SQL'" label="定时执行" name="schedule">
<p>为当前代码设置执行时间、参数和目标表,保存并发布调度后生效。</p>
<el-button v-hasPermi="['aixun:dataops:schedule:create']" type="primary" :disabled="editorForm.status !== 'ENABLED'" @click="scheduleCode">配置定时执行</el-button>
</el-tab-pane>
</el-tabs>
</el-drawer>
@@ -722,6 +727,19 @@ async function openEditor(row: CodeSummaryVO) {
await showDetail(response.data);
}
async function openExecution(value: unknown) {
const row = value as CodeSummaryVO;
await openEditor(row);
if (String(editorCodeId.value) === String(row.codeId)) editorTab.value = 'debug';
}
function scheduleCode() {
if (!editorCodeId.value) return;
void router.push({ path: '/datagov/dataops/scheduling/editor', query: {
sourceType: 'CODE_OBJECT', sourceId: String(editorCodeId.value), sourceName: editorForm.name
} });
}
async function showDetail(detail: CodeDetailVO) {
stopDebugConfirmation();
editorEpoch++;
@@ -235,7 +235,7 @@
<el-col :span="24"><el-form-item label="数据所在路径" prop="responseContentField"><el-input v-model="configForm.responseContentField" maxlength="255" placeholder="可选,例如 $.data[*]" /></el-form-item></el-col>
</el-row>
</el-collapse-item>
<el-collapse-item title="高级请求与认证" name="request">
<el-collapse-item title="请求头、认证与签名" name="request">
<el-row :gutter="16">
<el-col :span="12"><el-form-item label="认证方式"><el-select v-model="profileForm.authKind" class="w-full" @change="onApiAuthKindChanged"><el-option label="固定 Bearer" value="STATIC_BEARER" /><el-option label="动态 Token(客户端凭据)" value="CLIENT_CREDENTIALS" /><el-option label="动态 Token(账号密码)" value="PASSWORD_TOKEN" /><el-option label="API Key 请求头" value="API_KEY_HEADER" /><el-option label="仅请求签名" value="SIGN_ONLY" /></el-select></el-form-item></el-col>
<el-col :span="12"><el-form-item label="数据请求方法"><el-select v-model="profileForm.requestMethod" class="w-full"><el-option label="GET" value="GET" /><el-option label="POST" value="POST" /></el-select></el-form-item></el-col>
@@ -689,7 +689,7 @@ const resetConfig = () => {
Object.assign(profileForm, emptyApiProfile());
requestHeadersText.value = '{}';
requestQueryText.value = '{}';
advancedSections.value = [];
advancedSections.value = activeKind.value === 'api' ? ['request'] : [];
pollingEnabled.value = false;
originalPollingEnabled.value = false;
editingIntakeId.value = undefined;
@@ -719,7 +719,7 @@ const openEdit = async (row: FileIntakeVO, enablePolling = false) => {
resetConfig();
originalPollingEnabled.value = pollState?.enabled === true;
pollingEnabled.value = originalPollingEnabled.value || enablePolling;
if (enablePolling) advancedSections.value = ['api'];
if (enablePolling) advancedSections.value = ['api', 'request'];
editingIntakeId.value = detail.intakeId;
originalSourceType.value = detail.sourceType;
currentEndpointConfigured.value = detail.endpointConfigured;
@@ -398,6 +398,16 @@
</el-descriptions>
<el-tabs v-model="detailTab">
<el-tab-pane label="关联表" name="tables">
<el-alert v-if="layerTablesError" :title="layerTablesError" type="error" :closable="false" />
<el-table v-loading="layerTablesLoading" :data="layerTables" border empty-text="该分层暂无已登记表">
<el-table-column prop="name" label="表名称" min-width="180" />
<el-table-column prop="namespaceName" label="数据库" min-width="160" />
<el-table-column prop="engineType" label="引擎" width="100" />
<el-table-column label="登记状态" width="120"><template #default="{ row }">{{ row.executionState === 'CONFIRMED' ? '已确认' : row.executionState === 'REJECTED' ? '失败' : '待核实' }}</template></el-table-column>
</el-table>
<pagination v-if="layerTablesTotal > 0" v-model:page="layerTablesPage" v-model:limit="layerTablesPageSize" :total="layerTablesTotal" @pagination="loadLayerTables" />
</el-tab-pane>
<el-tab-pane label="分层准入" name="admission">
<el-descriptions :column="2" border>
<el-descriptions-item label="数据粒度">{{ detail.admission.granularity }}</el-descriptions-item>
@@ -471,6 +481,8 @@ import type {
StorageFormat
} from '@/api/datagov/lakehouse-layers/types';
import { extractErrorMessage } from '@/utils/request';
import { listTableFiles } from '@/api/datagov/table-files';
import type { TableFileVO } from '@/api/datagov/table-files/types';
const router = useRouter(), route = useRoute();
const canBindExisting = computed(() => ['view', 'create'].every(action => checkPermi([`aixun:dataops:table-file:${action}`])));
@@ -509,7 +521,25 @@ const initializingLayers = ref(false);
const initializationResult = ref<LayerInitializationVO>();
const admissionDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const detailTab = ref('admission');
const detailTab = ref('tables');
const layerTables = ref<TableFileVO[]>([]);
const layerTablesPage = ref(1), layerTablesPageSize = ref(20), layerTablesTotal = ref(0);
const layerTablesLoading = ref(false), layerTablesError = ref('');
let layerTablesSequence = 0;
async function loadLayerTables() {
const sequence = ++layerTablesSequence;
layerTables.value = []; layerTablesTotal.value = 0; layerTablesError.value = '';
if (!detail.value) return;
if (!checkPermi(['aixun:dataops:table-file:view'])) { layerTablesError.value = '暂无查看关联表的权限'; return; }
layerTablesLoading.value = true;
try {
const response = await listTableFiles({ layerId: detail.value.layer.layerId, pageNum: layerTablesPage.value, pageSize: layerTablesPageSize.value });
if (sequence !== layerTablesSequence) return;
layerTables.value = response.data.rows; layerTablesTotal.value = response.data.total;
} catch (error) {
if (sequence === layerTablesSequence) layerTablesError.value = (await extractErrorMessage(error)) || '关联表加载失败';
} finally { if (sequence === layerTablesSequence) layerTablesLoading.value = false; }
}
const detail = ref<LayerDetailVO>();
const editingLayerId = ref<LakehouseId>();
const admissionLayer = ref<LayerVO>();
@@ -992,6 +1022,9 @@ const saveAdmission = async () => {
};
const openDetail = async (row: LayerVO) => {
++layerTablesSequence;
layerTables.value = []; layerTablesTotal.value = 0; layerTablesPage.value = 1;
layerTablesError.value = ''; detailTab.value = 'tables';
detailDialogVisible.value = true;
detailLoading.value = true;
detailError.value = '';
@@ -999,6 +1032,7 @@ const openDetail = async (row: LayerVO) => {
try {
const response = await getLakehouseLayer(row.layerId);
detail.value = response.data;
await loadLayerTables();
} catch (error) {
detailError.value = (await extractErrorMessage(error)) || '湖仓分层详情加载失败';
} finally {
@@ -930,6 +930,13 @@ onMounted(async () => {
} else if (results[1].status === 'rejected') loadError.value = '布局读取失败,请重新打开,避免覆盖未知的已存布局。';
if (!positions.value.length) positions.value = arrangeSchedule(form.nodes, form.edges);
savedDefinition.value = JSON.stringify(requestDefinition()); savedLayout.value = layoutSignature();
if (!scheduleId.value && route.query.sourceType === 'CODE_OBJECT' && typeof route.query.sourceId === 'string' && /^\d+$/.test(route.query.sourceId)) {
const name = typeof route.query.sourceName === 'string' ? route.query.sourceName.slice(0, 100) : '代码执行';
form.name = `${name}定时执行`;
form.nodes = [{ ...emptyNode(), type: 'CODE_OBJECT', name, referenceId: route.query.sourceId }];
form.triggers = [emptyTrigger()];
positions.value = arrangeSchedule(form.nodes, form.edges);
}
loading.value = false; checkpoint();
});
onBeforeUnmount(() => { clearTimeout(historyTimer); window.removeEventListener('beforeunload', beforeUnload); });
@@ -184,6 +184,7 @@
:value="item.tableFileId"
/>
</el-select>
<el-button v-hasPermi="['aixun:dataops:table-file:create']" link type="primary" :loading="creatingOutput" :disabled="!form.sourceTableFileId || creatingOutput" @click="createOutputFromSource">按源表结构新建输出表</el-button>
</el-form-item>
</el-col>
</el-row>
@@ -279,6 +280,21 @@
</div>
<el-tabs v-model="activeRuleTab">
<el-tab-pane label="按字段配置" name="fields">
<el-empty v-if="!sourceFields.length" description="请先选择输入表" />
<el-collapse>
<el-collapse-item v-for="field in sourceFields" :key="field" :name="field" :title="`${field}(${form.rules.standardizationRules.filter(rule => rule.sourceField === field).length} 条标准化规则)`">
<div v-for="rule in form.rules.standardizationRules.filter(item => item.sourceField === field)" :key="rule.ruleCode" class="mb-3 flex gap-2">
<el-select v-model="rule.operation" :disabled="protectedMask(rule)" @change="resetStandardization(rule)"><el-option v-for="item in standardizationOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select>
<el-select v-if="rule.operation === 'TEXT_TRIM'" v-model="rule.parameters.trimMode"><el-option label="两端空格" value="BOTH" /><el-option label="左侧空格" value="LEADING" /><el-option label="右侧空格" value="TRAILING" /></el-select>
<el-select v-if="rule.operation === 'TEXT_CASE'" v-model="rule.parameters.caseMode"><el-option label="大写" value="UPPER" /><el-option label="小写" value="LOWER" /></el-select>
<el-button link type="danger" :disabled="protectedMask(rule)" @click="form.rules.standardizationRules.splice(form.rules.standardizationRules.indexOf(rule), 1)">删除</el-button>
</div>
<el-button plain :icon="Plus" @click="addFieldRule(field)">添加规则</el-button>
<el-text class="ml-3" type="info">按显示顺序执行;未配置规则的同名字段直接保留。</el-text>
</el-collapse-item>
</el-collapse>
</el-tab-pane>
<el-tab-pane label="字段映射图" name="mapping" lazy><TransformationMapping v-if="activeRuleTab === 'mapping'" :rules="form.rules" :scope-key="`transformation:${form.planId || 'draft'}:${form.version || 0}`" /></el-tab-pane>
<el-tab-pane :label="`标准化(${form.rules.standardizationRules.length})`" name="standardization">
<div v-for="(rule, index) in form.rules.standardizationRules" :key="index" class="mb-3">
@@ -652,7 +668,8 @@ import type {
TransformationPreviewVO,
TransformationRuleSet
} from '@/api/datagov/transformation-cleanings/types';
import { getTableFile, listTableFiles } from '@/api/datagov/table-files';
import { createTableFile, getTableFile, listTableFiles } from '@/api/datagov/table-files';
import { extractErrorMessage } from '@/utils/request';
import type { ColumnDefinition, TableFileVO } from '@/api/datagov/table-files/types';
interface DedupEditor extends Omit<DeduplicationRule, 'weights'> { weightsText: string }
@@ -728,6 +745,7 @@ async function openMapping(id: TransformationPlanId, isCurrent: () => boolean =
}
function closeMapping() { visualEpoch++; visualPlan.value = undefined; visualLoadingId.value = ''; }
const tableOptions = ref<TableFileVO[]>([]);
const creatingOutput = ref(false);
const publicationOptions = ref<ReferenceDataPublicationOption[]>([]);
const publicationSourceSystems = reactive<Record<string, string[]>>({});
const ruleTemplates = ref<RuleTemplateVO[]>([]);
@@ -746,7 +764,7 @@ const sourceFields = ref<string[]>([]);
const outputFields = ref<string[]>([]);
const sourceColumns = ref<ColumnDefinition[]>([]);
const outputColumns = ref<ColumnDefinition[]>([]);
const activeRuleTab = ref('standardization');
const activeRuleTab = ref('fields');
const queryFormRef = ref<FormInstance>();
const definitionFormRef = ref<FormInstance>();
const definitionDialog = reactive({ visible: false, title: '', mode: 'create' as 'create' | 'edit' | 'version' });
@@ -1110,6 +1128,36 @@ async function loadSourceFields(id: TransformationPlanId) {
sourceFields.value = sourceColumns.value.map((item) => item.name);
}
async function createOutputFromSource() {
if (!form.sourceTableFileId || creatingOutput.value) return;
creatingOutput.value = true;
try {
const sourceId = form.sourceTableFileId;
const source = (await getTableFile(sourceId)).data;
const answer = await ElMessageBox.prompt('在源表所在分层新建独立输出表,仅复制字段结构,原表不变。', '新建清洗输出表', {
inputValue: `${source.tableFile.name}_clean`, inputPattern: /^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/, inputErrorMessage: '请使用字母、数字和下划线,且不以数字开头'
});
if (String(form.sourceTableFileId) !== String(sourceId)) return;
if (answer.value.toLowerCase() === source.tableFile.name.toLowerCase()) throw new Error('输出表名不能与源表相同');
const response = await createTableFile({ name: answer.value, objectType: 'TABLE',
layerId: source.tableFile.layerId, storageResourceId: source.tableFile.storageResourceId,
storageSpaceId: source.tableFile.storageSpaceId, engineType: source.tableFile.engineType,
storageFormat: source.tableFile.storageFormat, catalogName: source.tableFile.catalogName,
namespaceName: source.tableFile.namespaceName, columns: source.columns,
partitionPolicy: source.partitionPolicy, comment: `清洗输出:${source.tableFile.name}` }, idempotencyKey());
const created = response.data?.result?.tableFile as TableFileVO | undefined;
if (!created || created.executionState !== 'CONFIRMED') {
ElMessage.warning('建表结果尚未确认,请到表文件页面核对,勿重复建表'); return;
}
if (String(form.sourceTableFileId) !== String(sourceId)) return;
tableOptions.value.push(created); form.outputTableFileId = created.tableFileId;
await loadOutputFields(created.tableFileId);
ElMessage.success('输出表已创建,已自动保留源表字段');
} catch (error) {
if (error !== 'cancel' && error !== 'close') ElMessage.error((await extractErrorMessage(error)) || '输出表创建失败');
} finally { creatingOutput.value = false; }
}
async function loadOutputFields(id: TransformationPlanId) {
outputColumns.value = id ? (await getTableFile(id)).data.columns : [];
outputFields.value = outputColumns.value.map((item) => item.name);
@@ -1124,7 +1172,7 @@ async function openCreate() {
outputFields.value = [];
sourceColumns.value = [];
outputColumns.value = [];
activeRuleTab.value = 'standardization';
activeRuleTab.value = 'fields';
definitionDialog.mode = 'create';
definitionDialog.title = '新增转换清洗计划';
definitionDialog.visible = true;
@@ -1201,6 +1249,11 @@ function addStandardization() {
});
}
function addFieldRule(field: string) {
form.rules.standardizationRules.push({ ruleCode: ruleIdentity('standard'), sourceField: field,
targetField: field, operation: 'TEXT_TRIM', parameters: { trimMode: 'BOTH' } });
}
function addDirectMapping(targetField: string) {
if (form.rules.standardizationRules.some((rule) =>
rule.operation === 'DIRECT_COPY' && rule.targetField.toLowerCase() === targetField.toLowerCase()
@@ -34,6 +34,7 @@
<el-table-column width="330" class-name="dg-row-actions dg-row-actions-nowrap" label="操作" align="center" fixed="right">
<template #default="{ row }"><RowActions>
<el-button icon="View" link type="primary" @click="openCollection(row)">详情</el-button>
<el-button v-if="canExecute" icon="VideoPlay" link type="primary" :disabled="Boolean(executingCollectionId) || !['SUCCEEDED', 'FAILED', 'CANCELED'].includes(row.status)" :loading="executingCollectionId === String(row.collectionId)" @click="executeCollection(row)">立即执行</el-button>
<el-button icon="CopyDocument" v-if="canCopy" link type="primary" :disabled="loading || copyDisabled || Boolean(refreshingCollectionId)"
@click="emit('copy-configuration', row.collectionId)">复制配置</el-button>
<el-button icon="View" v-if="canRefresh" link type="primary" :loading="refreshingCollectionId === String(row.collectionId)"
@@ -83,9 +84,9 @@
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, onBeforeUnmount, reactive, ref, watch } from 'vue';
import { getIngestionCollection, pageIngestionCollections, refreshIngestionCollection } from '@/api/datagov/unified-ingestion';
import { copyIngestionConfiguration, submitUnifiedIngestion, getIngestionCollection, pageIngestionCollections, refreshIngestionCollection } from '@/api/datagov/unified-ingestion';
import type {
CollectionDetailVO,
CollectionQuery,
@@ -104,6 +105,29 @@ const props = defineProps<{ copyDisabled?: boolean; currentResult?: CollectionDe
const emit = defineEmits<{ 'copy-configuration': [collectionId: Identifier]; 'view-mapping': [taskId: Identifier]; refreshed: [result: CollectionDetailVO] }>();
function viewMapping(taskId: Identifier) { detailDialog.value = false; emit('view-mapping', taskId); }
const canCopy = computed(() => ['view', 'create'].every(action => checkPermi([`aixun:dataops:batch-ingestion:${action}`])));
const canExecute = computed(() => ['view', 'create', 'update', 'submit'].every(action => checkPermi([`aixun:dataops:batch-ingestion:${action}`])));
const executingCollectionId = ref<string>();
const executionKeys = new Map<string, string>();
async function executeCollection(value: unknown) {
const row = value as CollectionSummaryVO;
if (!canExecute.value || executingCollectionId.value) return;
const id = String(row.collectionId);
executingCollectionId.value = id;
try {
await ElMessageBox.confirm(`按保存的配置再次执行“${row.name}”?将向原目标表采集数据。`, '立即执行', { type: 'warning' });
const copied = (await copyIngestionConfiguration(row.collectionId)).data.configuration;
const key = executionKeys.get(id) || `collection-repeat-${crypto.randomUUID()}`;
executionKeys.set(id, key);
const response = await submitUnifiedIngestion({ ...copied, items: copied.items.map(item => ({ ...item, createTarget: false })) }, key);
executionKeys.delete(id);
await loadRecords();
await openCollection({ collectionId: response.data.collectionId });
if (response.data.status === 'FAILED' || response.data.status === 'UNKNOWN') ElMessage.warning('采集未确认成功,请查看新记录中的结果说明');
else ElMessage.success('已提交新的采集记录,请查看执行结果');
} catch (error) {
if (error !== 'cancel' && error !== 'close') ElMessage.error((await extractErrorMessage(error)) || '执行结果未确认,请核对采集记录;配置变化时请复制配置后重新检查');
} finally { executingCollectionId.value = undefined; }
}
const query = reactive<CollectionQuery>({ keyword: undefined, status: undefined, pageNum: 1, pageSize: 20 });
const collections = ref<CollectionSummaryVO[]>([]);
const total = ref(0);
@@ -217,9 +217,9 @@ type CollectionDisplayResult = Omit<SubmitResult, 'items'> & {
items: (SubmitResult['items'][number] | CollectionDetailVO['items'][number])[];
};
const activeView = ref<'create' | 'records' | 'drafts' | 'mapping' | 'originals'>('create');
const activeView = ref<'create' | 'records' | 'drafts' | 'mapping' | 'originals'>('records');
const originalBusy = ref(false);
const recordsVisited = ref(false);
const recordsVisited = ref(true);
const mappingTaskId = ref<string | number>();
const mappingIsCurrent = ref<(() => boolean)>();
const mappingGeneration = ref(0);
@@ -24,7 +24,7 @@
<div class="toolbar-shell">
<div class="table-heading">
<h3>编码标识</h3>
<p>共 {{ (rows)?.length ?? 0 }} 条记录</p>
<p>编码规则用于生成统一标识;建立来源系统与业务主键映射后,主数据维护会自动取得该标识。</p>
</div>
<div class="toolbar-actions">
<el-button
@@ -96,6 +96,17 @@
</header>
<el-skeleton v-if="snapshotLoading" :rows="8" animated />
<el-tabs v-else-if="snapshot" v-model="activeTab">
<el-tab-pane label="来源与去向" name="relations">
<el-alert title="根据已记录的血缘关系展示当前表的来源与下游引用;未采集的关系不会推测生成。" type="info" :closable="false" class="mb-3" />
<h3>上游来源表</h3>
<el-table :data="relatedTables(snapshot.graph, true)" border empty-text="当前快照未记录上游来源表">
<el-table-column prop="name" label="表名称" min-width="160" /><el-table-column prop="fullyQualifiedName" label="完整位置" min-width="240" />
</el-table>
<h3>下游引用表</h3>
<el-table :data="relatedTables(snapshot.graph, false)" border empty-text="当前快照未记录下游引用表">
<el-table-column prop="name" label="表名称" min-width="160" /><el-table-column prop="fullyQualifiedName" label="完整位置" min-width="240" />
</el-table>
</el-tab-pane>
<el-tab-pane label="血缘图" name="graph">
<DgVisualWorkspace
v-if="activeTab === 'graph'"
@@ -344,6 +355,7 @@ import DgVisualEntry from '@/design-system/components/visualization/DgVisualEntr
import '@/design-system/styles/_visualization.scss';
import { defineAsyncComponent } from 'vue';
import { useLineage, entityTypes, nodeLabel, formatTime, entityTypeLabel } from './useLineage';
import { relatedTables } from './projection';
const DgVisualWorkspace = defineAsyncComponent(
() => import('@/design-system/components/visualization/DgVisualWorkspace.vue')
);
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { fieldEmphasis, projectLineage } from './projection';
import { fieldEmphasis, projectLineage, relatedTables } from './projection';
import type { CanvasGraph } from '@/design-system/components/visualization/types';
import type { MetadataLineageGraph } from '@/api/datagov/metadata-lineage/types';
@@ -14,6 +14,16 @@ const graph: CanvasGraph = {
]
};
describe('字段血缘路径', () => {
it('来源和去向沿有向关系穿过管道,不包含无关表或反向支路', () => {
const nodes = ['source', 'pipeline', 'current', 'target', 'unrelated'].map(externalId => ({ externalId, name: externalId,
fullyQualifiedName: externalId, entityType: externalId === 'pipeline' ? 'PIPELINE' as const : 'TABLE' as const }));
const input: MetadataLineageGraph = { root: nodes[2], nodes, upstreamEdges: [
{ fromExternalId: 'source', toExternalId: 'pipeline' }, { fromExternalId: 'pipeline', toExternalId: 'current' }
], downstreamEdges: [{ fromExternalId: 'current', toExternalId: 'target' }, { fromExternalId: 'unrelated', toExternalId: 'target' }],
fieldMappings: [], upstreamDepth: 2, downstreamDepth: 2, truncated: false };
expect(relatedTables(input, true).map(node => node.externalId)).toEqual(['source']);
expect(relatedTables(input, false).map(node => node.externalId)).toEqual(['target']);
});
it('追踪全部已知上下游,保留订单与退款字段隔离', () => {
expect(fieldEmphasis(graph, { nodeId: 'detail', fieldId: 'amount' }).edgeIds.toSorted()).toEqual(['o1', 'o2', 'o3']);
expect(fieldEmphasis(graph, { nodeId: 'refund', fieldId: 'refund' }).edgeIds.toSorted()).toEqual(['r1', 'r2']);
@@ -8,6 +8,19 @@ import type { CanvasGraph, CanvasNode, CanvasEdge } from '@/design-system/compon
import { validateGraph } from '@/design-system/components/visualization/types';
export type LineageView = 'tables' | 'fields';
export function relatedTables(graph: MetadataLineageGraph, upstream: boolean) {
const edges = [...graph.upstreamEdges, ...graph.downstreamEdges];
const visited = new Set<string>([graph.root.externalId]);
const queue = [graph.root.externalId];
for (let index = 0; index < queue.length; index++) {
for (const edge of edges) {
if ((upstream ? edge.toExternalId : edge.fromExternalId) !== queue[index]) continue;
const id = upstream ? edge.fromExternalId : edge.toExternalId;
if (!visited.has(id)) { visited.add(id); queue.push(id); }
}
}
return graph.nodes.filter(node => node.entityType === 'TABLE' && node.externalId !== graph.root.externalId && visited.has(node.externalId));
}
const entityTypeLabel = (value: string) =>
({ TABLE: '数据表', PIPELINE: '数据管道', DASHBOARD: '仪表盘' } as Readonly<Record<string, string>>)[value] || '未知类型';
export const tableEdgeId = (source: string, target: string) => JSON.stringify(['entity', source, target]);