Просмотр исходного кода

feat(data-platform): 交付通用 ODBC、来源预检与隔离测算

整理 1.2.4、1.2.5 的实现及验证,并更新一期进度表。Web 2.4.428,server 1.0.614。
YY968XX 5 часов назад
Родитель
Сommit
7953612a53
30 измененных файлов с 1706 добавлено и 189 удалено
  1. 1 1
      Web/package.json
  2. 138 0
      Web/src/views/aidop/data-platform/components/RelationalCapacityPanel.vue
  3. 68 0
      Web/src/views/aidop/data-platform/components/RelationalPreflightReport.vue
  4. 66 3
      Web/src/views/aidop/data-platform/components/RelationalTrialPanel.vue
  5. BIN
      doc/plan/系统集成/数据中台/Ai-DOP数据中台一期项目进度管理.xlsx
  6. 3 3
      server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj
  7. 4 1
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/IRelationalSourceDriver.cs
  8. 32 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalCapacityEstimate.cs
  9. 23 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalCatalogAdvice.cs
  10. 2 2
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalConnectorRuntime.cs
  11. 86 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalPreflight.cs
  12. 3 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/Admin.NET.Plugin.AiDOP.DataPlatform.Relational.csproj
  13. 108 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeReadSession.CatalogAdvice.cs
  14. 168 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeReadSession.Inspection.cs
  15. 208 33
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeReadSession.cs
  16. 58 11
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeRelationalDriver.cs
  17. 54 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeSourceSql.cs
  18. 47 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/OdbcRelationalDriver.cs
  19. 15 1
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/README.md
  20. 63 11
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpNativeRelationalDriverTests.cs
  21. 55 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpRelationalCapacityTests.cs
  22. 23 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpRelationalCatalogTests.cs
  23. 29 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpRelationalPreflightTests.cs
  24. 2 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetReleaseController.cs
  25. 108 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetSandbox.Capacity.cs
  26. 31 16
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetSandbox.cs
  27. 36 28
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs
  28. 58 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalCapacityController.cs
  29. 124 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalSource.cs
  30. 93 79
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalTrialController.cs

+ 1 - 1
Web/package.json

@@ -1,7 +1,7 @@
 {
 	"name": "admin.net",
 	"type": "module",
-	"version": "2.4.427",
+	"version": "2.4.428",
 	"packageManager": "pnpm@10.32.1",
 	"lastBuildTime": "2026.03.15",
 	"description": "Admin.NET 站在巨人肩膀上的 .NET 通用权限开发框架",

+ 138 - 0
Web/src/views/aidop/data-platform/components/RelationalCapacityPanel.vue

@@ -0,0 +1,138 @@
+<script setup lang="ts">
+import { computed, shallowRef } from 'vue';
+import service from '/@/utils/request';
+
+type ApiInteger = number | string;
+
+interface CapacityResult {
+	sample: {
+		estimate: {
+			sourceRows: ApiInteger | null;
+			sourceRowsBasis: 'sample' | 'catalog' | 'sample-floor' | 'unknown';
+			sampleRows: number;
+			sampleBatches: number;
+			sampleRawBytes: ApiInteger;
+			rawBytesPerRow: number | null;
+			fullRawBytes: ApiInteger | null;
+			fullSecondsLow: number | null;
+			fullSecondsHigh: number | null;
+		};
+		isolatedRows: number;
+		setupMs: number;
+		sourceMs: number;
+		rawMs: number;
+		cleanMs: number;
+		handoffMs: number;
+		reconcileMs: number;
+	};
+	history: {
+		increments: { recordedDays: number; dailyIncrementRows: number | null };
+		full: { sourceRows: ApiInteger; pageCount: number; completedUtc: string; elapsedMs: number } | null;
+		rawBytes?: ApiInteger | null;
+		rawToCleanMs?: number | null;
+	} | null;
+}
+
+const props = defineProps<{ endpoint: string; factoryId: string; active: boolean }>();
+const busy = shallowRef(false);
+const result = shallowRef<CapacityResult>();
+const retentionDays = shallowRef<number | undefined>(30);
+const dailyOverride = shallowRef<number>();
+const historicalDaily = computed(() => {
+	const increments = result.value?.history?.increments;
+	return increments && increments.recordedDays >= 2 ? increments.dailyIncrementRows : null;
+});
+const forecast = computed(() => {
+	const estimate = result.value?.sample.estimate;
+	const dailyRows = dailyOverride.value ?? historicalDaily.value;
+	const days = retentionDays.value;
+	if (!estimate?.sampleRows || dailyRows == null || !days) return null;
+	const perRow = Number(estimate.sampleRawBytes) / estimate.sampleRows;
+	const daily = Math.ceil(perRow * dailyRows);
+	const incremental = Math.ceil(perRow * dailyRows * days);
+	const total = estimate.fullRawBytes == null ? null : Number(estimate.fullRawBytes) + incremental;
+	return { daily, incremental, total };
+});
+
+const number = new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 3 });
+const amount = (value: ApiInteger | null | undefined) => value == null ? '待估算' : number.format(Number(value));
+const bytes = (value: ApiInteger | null | undefined) => {
+	if (value == null) return '待估算';
+	const units = ['字节', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
+	let size = Number(value);
+	let index = 0;
+	while (size >= 1024 && index < units.length - 1) {
+		size /= 1024;
+		index++;
+	}
+	return `${number.format(size)} ${units[index]}`;
+};
+const elapsed = (value: number | null | undefined) => value == null ? '未记录' : `${number.format(value)} 毫秒`;
+const rowCountBasis = {
+	sample: '本次已读到来源末尾,采用本次读取行数',
+	catalog: '行数采用源目录统计',
+	'sample-floor': '源目录低于已读行数,当前以样本行数为估算下限',
+	unknown: '源目录没有行数统计',
+};
+const forecastTime = computed(() => {
+	const estimate = result.value?.sample.estimate;
+	const low = estimate?.fullSecondsLow;
+	const high = estimate?.fullSecondsHigh;
+	if (low == null || high == null) return '待估算';
+	return low === high ? `约 ${amount(low)} 秒` : `${amount(low)}–${amount(high)} 秒`;
+});
+
+async function measure() {
+	if (!props.active || busy.value) return;
+	busy.value = true;
+	try {
+		const response = await service.post<CapacityResult>(props.endpoint, {}, {
+			params: { factoryId: props.factoryId },
+			timeout: 40000,
+		});
+		result.value = response.data;
+	} finally {
+		busy.value = false;
+	}
+}
+</script>
+
+<template>
+	<section class="relational-capacity">
+		<h4>同步耗时和保留容量</h4>
+		<el-button :loading="busy" :disabled="!active" @click="measure">运行隔离测算</el-button>
+		<p v-if="!active">启用已审批的来源版本后可以运行测算。</p>
+		<div v-if="result" role="status">
+			<p>样本 {{ result.sample.estimate.sampleRows }} 行 · {{ result.sample.estimate.sampleBatches }} 批 · Raw {{ bytes(result.sample.estimate.sampleRawBytes) }} · 隔离 {{ result.sample.isolatedRows }} 行</p>
+			<p v-if="!result.sample.estimate.sampleRows">来源没有可用样本,耗时及每行容量待估算。</p>
+			<p v-else-if="result.sample.estimate.sourceRows == null">源目录没有行数统计,首次全量待估算。</p>
+			<p v-if="result.sample.isolatedRows">样本出现隔离。请复核来源字段和映射,再用于投产评估。</p>
+			<template v-if="result.sample.estimate.sampleRows">
+				<p>沙箱准备 {{ elapsed(result.sample.setupMs) }} · 源库读取 {{ elapsed(result.sample.sourceMs) }} · Raw 入库 {{ elapsed(result.sample.rawMs) }}</p>
+				<p>清洗 {{ elapsed(result.sample.cleanMs) }} · 贴源及标准层 {{ elapsed(result.sample.handoffMs) }} · 对账 {{ elapsed(result.sample.reconcileMs) }}</p>
+			</template>
+			<p>首次全量预计 {{ amount(result.sample.estimate.sourceRows) }} 行 · {{ forecastTime }} · Raw {{ bytes(result.sample.estimate.fullRawBytes) }}</p>
+			<p v-if="result.sample.estimate.sampleRows">{{ rowCountBasis[result.sample.estimate.sourceRowsBasis] }}。每行 Raw {{ bytes(result.sample.estimate.rawBytesPerRow) }},耗时按样本批次速度推算。队列等待见实际运行。</p>
+			<div class="capacity-inputs">
+				<label>保留天数 <el-input-number v-model="retentionDays" :min="1" :max="3650" :precision="0" aria-label="保留天数" /></label>
+				<label>日均增量假设 <el-input-number v-model="dailyOverride" :min="0" :max="1000000000" :precision="0" placeholder="沿用历史" aria-label="日均增量假设" /></label>
+			</div>
+			<p v-if="dailyOverride != null">使用手填假设,每日 {{ amount(dailyOverride) }} 行。</p>
+			<p v-else-if="historicalDaily != null">取近 14 天内 {{ result.history?.increments.recordedDays }} 个有对账记录的完整 UTC 日,日均 {{ amount(historicalDaily) }} 行,含增量窗口的重叠数据。</p>
+			<p v-else>日均增量待估算。历史记录不足时可填写假设值。</p>
+			<p>每日 Raw {{ bytes(forecast?.daily) }} · 保留期增量 Raw {{ bytes(forecast?.incremental) }} · 含首次全量 {{ bytes(forecast?.total) }}</p>
+			<p>容量按 Raw 原文计算,索引及贴源、标准层各自占用空间。</p>
+			<template v-if="result.history?.full">
+				<p>最近一次已对账全量 {{ result.history.full.sourceRows }} 行 · {{ result.history.full.pageCount }} 批 · Raw {{ bytes(result.history.rawBytes) }}</p>
+				<p>实际全程 {{ elapsed(result.history.full.elapsedMs) }},含排队和对账等待。每批 Raw 入库至清洗完成平均 {{ elapsed(result.history.rawToCleanMs) }},含 Worker 排队。</p>
+			</template>
+			<p v-else>当前配置暂无已对账全量可供比较。</p>
+		</div>
+	</section>
+</template>
+
+<style scoped>
+.relational-capacity { margin: 14px 0; }
+.capacity-inputs { display: flex; flex-wrap: wrap; gap: 12px 20px; }
+.capacity-inputs label { display: inline-flex; align-items: center; gap: 8px; }
+</style>

+ 68 - 0
Web/src/views/aidop/data-platform/components/RelationalPreflightReport.vue

@@ -0,0 +1,68 @@
+<script setup lang="ts">
+export interface RelationalPreflightReport {
+	schema: string;
+	objectName: string;
+	businessKey: string;
+	objects: { name: string; kind: string }[];
+	columns: { name: string; type: string; nullable: boolean | null; length: number | null; precision: number | null; scale: number | null; encoding: string | null; default: string | null }[];
+	sample: { name: string; sampled: number; missing: number; distinct: number }[];
+	minimumGrant: string | null;
+	advice?: {
+		keys: { name: string; primary: boolean; columns: string[] }[];
+		timeIndex: string | null;
+		estimatedRows: number | null;
+		estimatedRawBytes: number | null;
+		estimatedReadSeconds: number | null;
+	};
+	checks: { code: string; severity: 'pass' | 'warning' | 'block'; message: string }[];
+}
+
+defineProps<{ report: RelationalPreflightReport }>();
+const emit = defineEmits<{ object: [name: string] }>();
+const severity = { pass: '通过', warning: '警告', block: '阻断' } as const;
+</script>
+
+<template>
+	<div>
+		<p>{{ report.schema }}.{{ report.objectName }}<template v-if="report.businessKey"> · 业务键 {{ report.businessKey }}</template></p>
+		<ul aria-label="来源预检">
+			<li v-for="check in report.checks" :key="check.code">{{ severity[check.severity] }} · {{ check.message }}</li>
+		</ul>
+		<el-collapse>
+			<el-collapse-item v-if="report.advice" title="候选业务键、索引和容量估算">
+				<p v-for="key in report.advice.keys" :key="key.name">{{ key.primary ? '主键' : '非空唯一索引' }} {{ key.name }}({{ key.columns.join('、') }})</p>
+				<p v-if="!report.advice.keys.length">源目录未提供已证实的非空唯一键</p>
+				<p v-if="report.advice.timeIndex">时间分页索引 {{ report.advice.timeIndex }}</p>
+				<p>源端目录估计 {{ report.advice.estimatedRows ?? '未知' }} 行 · Raw {{ report.advice.estimatedRawBytes ?? '未知' }} 字节 · 源端读取 {{ report.advice.estimatedReadSeconds ?? '未知' }} 秒</p>
+			</el-collapse-item>
+			<el-collapse-item title="授权架构中的表和视图">
+				<el-table :data="report.objects" max-height="220">
+					<el-table-column label="对象"><template #default="{ row }"><el-button link @click="emit('object', row.name)">{{ row.name }}</el-button></template></el-table-column>
+					<el-table-column prop="kind" label="类型" />
+				</el-table>
+			</el-collapse-item>
+			<el-collapse-item title="当前对象字段和类型">
+				<el-table :data="report.columns" max-height="240">
+					<el-table-column prop="name" label="字段" />
+					<el-table-column prop="type" label="类型" />
+					<el-table-column label="可空"><template #default="{ row }">{{ row.nullable ? '是' : '否' }}</template></el-table-column>
+					<el-table-column prop="length" label="长度" />
+					<el-table-column prop="precision" label="精度" />
+					<el-table-column prop="scale" label="小数位" />
+					<el-table-column prop="encoding" label="字符集" />
+				</el-table>
+			</el-collapse-item>
+			<el-collapse-item v-if="report.sample.length" title="样本统计">
+				<el-table :data="report.sample">
+					<el-table-column prop="name" label="字段" />
+					<el-table-column prop="sampled" label="抽样行数" />
+					<el-table-column prop="missing" label="空值" />
+					<el-table-column prop="distinct" label="非空不同值" />
+				</el-table>
+			</el-collapse-item>
+			<el-collapse-item v-if="report.minimumGrant" title="对象最小读取权限示例">
+				<pre>{{ report.minimumGrant }}</pre>
+			</el-collapse-item>
+		</el-collapse>
+	</div>
+</template>

+ 66 - 3
Web/src/views/aidop/data-platform/components/RelationalTrialPanel.vue

@@ -1,24 +1,76 @@
 <script setup lang="ts">
-import { onMounted, ref } from 'vue';
+import { computed, onMounted, ref, watch } from 'vue';
 import { ElMessageBox } from 'element-plus';
 import service from '/@/utils/request';
+import RelationalCapacityPanel from './RelationalCapacityPanel.vue';
+import RelationalPreflightReportPanel, { type RelationalPreflightReport } from './RelationalPreflightReport.vue';
 
 const props = defineProps<{ datasetId: string; factoryId: string; active: boolean }>();
 const profiles = ref<{ id: string; name: string; driver: string }[]>([]);
 const selected = ref('');
 const busy = ref(false);
+const inspection = ref<RelationalPreflightReport>();
+const canMeasureCapacity = ref(false);
+const probe = ref<{ supported: boolean; reason: string | null }>();
 const result = ref<{ driver: string; position: string | null; complete: boolean; receipts: { batchId: string; acceptedRecordCount: number }[] }>();
 const endpoint = '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/relational-trials';
 const options = { params: { factoryId: props.factoryId } };
+const driver = computed(() => profiles.value.find((profile) => profile.id === selected.value)?.driver);
+const requiresProbe = computed(() => ['mdp.postgresql', 'mdp.oracle', 'mdp.odbc'].includes(driver.value ?? ''));
+const canRun = computed(() => props.active && !!selected.value && (probe.value?.supported ?? !requiresProbe.value));
+const labels: Record<string, string> = {
+	'read-only-permission-unverified': '源库账号的只读权限未通过检查。',
+	'stable-key-unverified': '未能确认配置表有可用于分页的单列整数主键。',
+	'projection-unverified': '配置字段不存在或源库账号无权读取。',
+	'parameterized-paging-unverified': '驱动的参数化分页未通过检查。',
+	'driver-family-unverified': 'ODBC 已连接,实际驱动的读取能力尚未确认。',
+	'identifier-unverified': '配置的库表标识超出驱动可验证范围。',
+	'database-scope-mismatch': '实际连接库与来源配置不一致。',
+	'driver-configuration-invalid': '数据库驱动配置未通过检查。',
+	'source-unavailable': '无法打开来源,请核对源库与驱动配置。',
+};
+const probeMessage = computed(() => probe.value?.supported ? '只读权限和分页能力检查通过。'
+	: labels[probe.value?.reason ?? ''] ?? '读取能力未通过检查。');
 
 onMounted(async () => {
 	profiles.value = (await service.get(endpoint, options)).data;
 	selected.value = profiles.value[0]?.id ?? '';
 });
 
-async function run() {
+watch(selected, () => {
+	inspection.value = undefined;
+	probe.value = undefined;
+	result.value = undefined;
+});
+
+async function inspect(objectName?: string) {
+	if (busy.value || !selected.value) return;
+	busy.value = true;
+	inspection.value = undefined;
+	try {
+		const response = await service.get(endpoint + '/' + encodeURIComponent(selected.value) + '/catalog', { params: { ...options.params, objectName } });
+		inspection.value = response.data.report;
+		canMeasureCapacity.value = response.data.canMeasureCapacity === true;
+	} finally {
+		busy.value = false;
+	}
+}
+
+async function checkRead() {
 	if (busy.value || !selected.value || !props.active) return;
 	busy.value = true;
+	probe.value = undefined;
+	result.value = undefined;
+	try {
+		probe.value = (await service.get(endpoint + '/' + encodeURIComponent(selected.value) + '/probe', options)).data;
+	} finally {
+		busy.value = false;
+	}
+}
+
+async function run() {
+	if (busy.value || !canRun.value) return;
+	busy.value = true;
 	try {
 		await ElMessageBox.confirm('试跑会读取已配置的只读表,并将批次提交到当前接收数据集。', '确认数据库试跑');
 		result.value = undefined;
@@ -37,8 +89,19 @@ async function run() {
 		<el-select v-model="selected" aria-label="试跑数据库" :disabled="busy" style="width: 230px">
 			<el-option v-for="profile in profiles" :key="profile.id" :label="profile.name" :value="profile.id" />
 		</el-select>
-		<el-button :loading="busy" :disabled="!active || !selected" @click="run">读取并接收试跑批次</el-button>
+		<el-button :disabled="busy || !selected" @click="inspect()">查看结构和来源预检</el-button>
+		<el-button :disabled="busy || !active || !selected" @click="checkRead">检查读取能力</el-button>
+		<el-button :loading="busy" :disabled="!canRun" @click="run">读取并接收试跑批次</el-button>
 		<p v-if="!active">启用已审批的采购接收版本后,可提交试跑批次。</p>
+		<p v-if="probe" role="status">{{ probeMessage }}</p>
+		<RelationalPreflightReportPanel v-if="inspection" :report="inspection" @object="inspect" />
+		<RelationalCapacityPanel
+			v-if="inspection && canMeasureCapacity"
+			:key="selected"
+			:endpoint="endpoint + '/' + encodeURIComponent(selected) + '/capacity-sample'"
+			:factory-id="factoryId"
+			:active="active"
+		/>
 		<template v-if="result">
 			<p>{{ result.complete ? '读取完成' : '已达到本次试跑页数上限' }} · 已确认位置 {{ result.position ?? '无' }}</p>
 			<ul>

BIN
doc/plan/系统集成/数据中台/Ai-DOP数据中台一期项目进度管理.xlsx


+ 3 - 3
server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj

@@ -11,9 +11,9 @@
     <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
     <Copyright>Admin.NET</Copyright>
     <Description>Admin.NET 通用权限开发平台</Description>
-    <AssemblyVersion>1.0.613</AssemblyVersion>
-    <FileVersion>1.0.613</FileVersion>
-    <Version>1.0.613</Version>
+    <AssemblyVersion>1.0.614</AssemblyVersion>
+    <FileVersion>1.0.614</FileVersion>
+    <Version>1.0.614</Version>
   </PropertyGroup>
 
   <ItemGroup>

+ 4 - 1
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/IRelationalSourceDriver.cs

@@ -23,6 +23,9 @@ public interface IRelationalReadSession : IAsyncDisposable
     Task<ConnectorBatchCandidate?> ReadPageAsync(ConnectorReadRequest request, CancellationToken cancellationToken);
 }
 
-public sealed record RelationalReadCapabilities(bool ReadOnly, bool Full, bool Incremental);
+public sealed record RelationalReadCapabilities(bool ReadOnly, bool Full, bool Incremental)
+{
+    public string? Reason { get; init; }
+}
 
 public sealed record RelationalReadBatch(ConnectorFrozenBatch Batch, bool HasMore);

+ 32 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalCapacityEstimate.cs

@@ -0,0 +1,32 @@
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+public sealed record RelationalCapacityBatch(int Rows, long RawBytes, decimal SourceMs,
+    decimal RawMs, decimal CleanMs, decimal HandoffMs, decimal ReconcileMs)
+{
+    public decimal TotalMs => SourceMs + RawMs + CleanMs + HandoffMs + ReconcileMs;
+}
+
+public sealed record RelationalCapacityEstimate(long? SourceRows, string SourceRowsBasis, int SampleRows, int SampleBatches,
+    long SampleRawBytes, decimal? RawBytesPerRow, long? FullRawBytes, decimal? FullSecondsLow, decimal? FullSecondsHigh)
+{
+    public static RelationalCapacityEstimate FromSamples(long? catalogRows, IReadOnlyList<RelationalCapacityBatch> batches,
+        bool reachedEnd = false)
+    {
+        var valid = batches.Where(batch => batch.Rows > 0 && batch.RawBytes > 0).ToArray();
+        var rows = valid.Sum(batch => batch.Rows);
+        var bytes = valid.Sum(batch => batch.RawBytes);
+        long? sourceRows = reachedEnd ? rows : catalogRows.HasValue ? Math.Max(catalogRows.Value, rows) : null;
+        var basis = reachedEnd ? "sample" : catalogRows is null ? "unknown" : catalogRows < rows ? "sample-floor" : "catalog";
+        if (rows == 0)
+            return new(sourceRows, basis, 0, 0, 0, null, sourceRows == 0 ? 0 : null, null, null);
+
+        var bytesPerRow = (decimal)bytes / rows;
+        var projectedBytes = decimal.Ceiling(bytesPerRow * sourceRows.GetValueOrDefault());
+        var measuredRates = valid.Where(batch => batch.TotalMs > 0).Select(batch => batch.TotalMs / batch.Rows).ToArray();
+        decimal? Forecast(decimal rate) => sourceRows.HasValue ? decimal.Round(rate * sourceRows.Value / 1000, 3) : null;
+        return new(sourceRows, basis, rows, valid.Length, bytes, decimal.Round(bytesPerRow, 2),
+            sourceRows.HasValue && projectedBytes <= long.MaxValue ? (long)projectedBytes : null,
+            measuredRates.Length > 0 ? Forecast(measuredRates.Min()) : null,
+            measuredRates.Length > 0 ? Forecast(measuredRates.Max()) : null);
+    }
+}

+ 23 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalCatalogAdvice.cs

@@ -0,0 +1,23 @@
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+public sealed record RelationalIndex(string Name, bool Unique, bool Primary, IReadOnlyList<string> Columns);
+
+public sealed record RelationalCatalogAdvice(IReadOnlyList<RelationalIndex> Keys, string? TimeIndex,
+    long? EstimatedRows, long? EstimatedRawBytes, double? EstimatedReadSeconds)
+{
+    public static RelationalCatalogAdvice Analyze(IReadOnlyList<RelationalColumn> columns,
+        IReadOnlyList<RelationalIndex> indexes, string? time, string key, long? rows, int sampled, long bytes, double seconds)
+    {
+        var nonNull = columns.Where(c => c.Nullable == false).Select(c => c.Name).ToHashSet(StringComparer.Ordinal);
+        var keys = indexes.Where(i => i.Unique && i.Columns.Count > 0 && i.Columns.All(nonNull.Contains))
+            .OrderByDescending(i => i.Primary).ThenBy(i => i.Columns.Count).ThenBy(i => i.Name, StringComparer.Ordinal).ToArray();
+        var timeIndex = string.IsNullOrEmpty(time) ? null : indexes.FirstOrDefault(i => i.Columns.Count >= 2
+            && i.Columns[0] == time && i.Columns[1] == key)?.Name;
+        if (rows is null || sampled <= 0 || bytes <= 0 || seconds <= 0)
+            return new(keys, timeIndex, rows, null, null);
+
+        var estimate = decimal.Ceiling((decimal)bytes * rows.Value / sampled);
+        return new(keys, timeIndex, rows, estimate <= long.MaxValue ? (long)estimate : null,
+            Math.Round(seconds * rows.Value / sampled, 2));
+    }
+}

+ 2 - 2
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalConnectorRuntime.cs

@@ -42,10 +42,10 @@ public sealed class RelationalConnectorRuntime
             {
                 var actual = await session.ProbeAsync(token);
                 if (!actual.ReadOnly)
-                    return new ConnectorProbeResult(false, "read-only-permission-unverified");
+                    return new ConnectorProbeResult(false, actual.Reason ?? "read-only-permission-unverified");
                 var declared = manifest.Capabilities[ConnectorManifest.Database];
                 var supported = (declared.Full && actual.Full) || (declared.Incremental && actual.Incremental);
-                return new ConnectorProbeResult(supported, supported ? null : "no-supported-read-mode");
+                return new ConnectorProbeResult(supported, supported ? null : actual.Reason ?? "no-supported-read-mode");
             }, token);
 
         public Task<ConnectorBatchCandidate?> ReadAsync(

+ 86 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/RelationalPreflight.cs

@@ -0,0 +1,86 @@
+using System.Text.Json.Serialization;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+public sealed record RelationalPreflightOptions(string? TimeZone, string? Encoding, string? DeletePolicy,
+    string? DeleteField, string? IncrementalStrategy, string? IncrementalField,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? ChangeVersionField = null,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] long? SourceGeneration = null,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] int? MaxCommitDelaySeconds = null,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] int? LookbackSeconds = null,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] int? RetentionSeconds = null,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SnapshotFenceTable = null,
+    [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SnapshotFenceColumn = null);
+
+public sealed record RelationalCheck(string Code, string Severity, string Message);
+public sealed record RelationalObject(string Name, string Kind);
+public sealed record RelationalColumn(string Name, string Type, bool? Nullable, long? Length,
+    int? Precision, int? Scale, string? Encoding, string? Default);
+public sealed record RelationalSampleStat(string Name, int Sampled, int Missing, int Distinct);
+public sealed record RelationalInspection(string Schema, string ObjectName, string BusinessKey,
+    IReadOnlyList<RelationalObject> Objects, IReadOnlyList<RelationalColumn> Columns,
+    IReadOnlyList<RelationalSampleStat> Sample, IReadOnlyList<RelationalCheck> Checks, string? MinimumGrant, RelationalCatalogAdvice? Advice = null);
+
+public interface IRelationalSourceInspection
+{
+    Task<RelationalInspection> InspectAsync(RelationalPreflightOptions options, CancellationToken token, string? catalogObject = null);
+}
+
+public static class RelationalPreflight
+{
+    public static IReadOnlyList<RelationalCheck> Evaluate(RelationalReadCapabilities capabilities,
+        RelationalPreflightOptions options, IReadOnlyCollection<string> columns)
+    {
+        var checks = new List<RelationalCheck>
+        {
+            new("connection", "pass", "已连接来源"),
+            Gate("read-only", capabilities.ReadOnly, "专用只读权限通过", "无法确认来源只读权限"),
+            Gate("stable-key", capabilities.Full, "业务键、字段投影及稳定分页通过", "无法确认稳定主键、投影或分页"),
+        };
+        if (capabilities.Reason is { } reason)
+            checks.Add(new(reason, "block", "驱动读取能力未通过"));
+
+        checks.Add(options.TimeZone is null
+            ? new("time-zone", "warning", "尚未声明源端时区")
+            : Gate("time-zone", ValidTimeZone(options.TimeZone), "已识别源端时区", "源端时区无效"));
+        checks.Add(options.Encoding is null
+            ? new("encoding", "warning", "驱动负责解码字符字段,请核对源端字符集")
+            : Gate("encoding", options.Encoding is "utf-8" or "utf8" or "utf8mb4" or "al32utf8" or "gbk" or "gb18030" or "big5",
+                "已声明受支持的字符集", "字符集未获支持或声明有误"));
+        checks.Add(options.DeletePolicy switch
+        {
+            "soft-delete" when !HasField(options.DeleteField, columns)
+                => new("delete-field", "block", "缺少软删标记字段"),
+            "soft-delete" => Gate("delete-policy", capabilities.Incremental && options.SourceGeneration > 0
+                && HasField(options.ChangeVersionField, columns), "已配置版本化软删", "软删缺少已验证的版本化增量"),
+            "snapshot-difference" => Gate("delete-policy", capabilities.Incremental && options.SourceGeneration > 0
+                && HasField(options.ChangeVersionField, columns)
+                && !string.IsNullOrWhiteSpace(options.SnapshotFenceTable) && !string.IsNullOrWhiteSpace(options.SnapshotFenceColumn),
+                "全量差异使用同一来源代次的完整键集和提交边界", "差异删除缺少经核验的完整快照或提交边界"),
+            "delete-log" => Gate("delete-policy", capabilities.Incremental && options.SourceGeneration > 0
+                && HasField(options.DeleteField, columns) && HasField(options.ChangeVersionField, columns)
+                && options.IncrementalStrategy == "ordered-change-log", "已配置版本化删除日志", "缺少已验证的顺序、删除标记或来源版本"),
+            "unsupported" => new("delete-policy", "warning", "该配置不传播删除"),
+            _ => new("delete-policy", "block", "请声明删除策略"),
+        });
+        if (options.IncrementalStrategy != "full")
+        {
+            var hasField = HasField(options.IncrementalField, columns);
+            checks.Add(Gate("incremental-field", hasField, "已找到配置的增量字段", "缺少增量字段"));
+            checks.Add(Gate("incremental-order", capabilities.Incremental, "源端增量顺序通过", "增量字段的顺序、索引及覆盖范围尚未核实"));
+        }
+        return checks;
+    }
+
+    private static bool HasField(string? name, IReadOnlyCollection<string> columns) =>
+        name is not null && columns.Contains(name, StringComparer.Ordinal);
+
+    private static RelationalCheck Gate(string code, bool pass, string passed, string blocked) =>
+        new(code, pass ? "pass" : "block", pass ? passed : blocked);
+
+    private static bool ValidTimeZone(string zone)
+    {
+        try { return TimeZoneInfo.TryFindSystemTimeZoneById(zone, out _); }
+        catch (InvalidTimeZoneException) { return false; }
+    }
+}

+ 3 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/Admin.NET.Plugin.AiDOP.DataPlatform.Relational.csproj

@@ -8,5 +8,8 @@
     <ProjectReference Include="../Admin.NET.Plugin.AiDOP.DataPlatform.Core/Admin.NET.Plugin.AiDOP.DataPlatform.Core.csproj" />
     <PackageReference Include="MySqlConnector" Version="2.2.5" />
     <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.2" />
+    <PackageReference Include="Npgsql" Version="8.0.9" />
+    <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="23.26.400" />
+    <PackageReference Include="System.Data.Odbc" Version="10.0.15" />
   </ItemGroup>
 </Project>

+ 108 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeReadSession.CatalogAdvice.cs

@@ -0,0 +1,108 @@
+using System.Data;
+using System.Data.Common;
+using System.Globalization;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
+
+internal sealed partial class NativeReadSession
+{
+    private async Task<IReadOnlyList<RelationalIndex>> ReadIndexes(string name, CancellationToken token)
+    {
+        var schema = Marker("@schema", ":schema", 1);
+        var table = Marker("@table", ":source_table", 2);
+        await using var query = CreateCommand();
+        query.CommandText = dialect switch
+        {
+            SourceDialect.MySql => $"""
+                SELECT INDEX_NAME,CASE WHEN NON_UNIQUE=0 THEN 1 ELSE 0 END,
+                    CASE WHEN INDEX_NAME='PRIMARY' THEN 1 ELSE 0 END,COLUMN_NAME
+                FROM information_schema.statistics
+                WHERE TABLE_SCHEMA={schema} AND TABLE_NAME={table} AND INDEX_TYPE='BTREE'
+                ORDER BY INDEX_NAME,SEQ_IN_INDEX
+                """,
+            SourceDialect.SqlServer => $"""
+                SELECT i.name,CAST(i.is_unique AS int),CAST(i.is_primary_key AS int),c.name
+                FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id
+                JOIN sys.indexes i ON i.object_id=t.object_id
+                JOIN sys.index_columns k ON k.object_id=i.object_id AND k.index_id=i.index_id AND k.key_ordinal>0
+                JOIN sys.columns c ON c.object_id=k.object_id AND c.column_id=k.column_id
+                WHERE s.name={schema} AND t.name={table} AND i.type IN (1,2)
+                  AND i.has_filter=0 AND i.is_disabled=0 AND i.is_hypothetical=0
+                ORDER BY i.name,k.key_ordinal
+                """,
+            SourceDialect.PostgreSql => $"""
+                SELECT z.relname,CASE WHEN i.indisunique THEN 1 ELSE 0 END,
+                    CASE WHEN i.indisprimary THEN 1 ELSE 0 END,a.attname
+                FROM pg_catalog.pg_class t JOIN pg_catalog.pg_namespace n ON n.oid=t.relnamespace
+                JOIN pg_catalog.pg_index i ON i.indrelid=t.oid
+                JOIN pg_catalog.pg_class z ON z.oid=i.indexrelid
+                JOIN pg_catalog.pg_am m ON m.oid=z.relam
+                CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum,pos)
+                JOIN pg_catalog.pg_attribute a ON a.attrelid=t.oid AND a.attnum=k.attnum
+                WHERE n.nspname={schema} AND t.relname={table} AND m.amname='btree'
+                  AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL AND k.pos<=i.indnkeyatts
+                ORDER BY z.relname,k.pos
+                """,
+            _ => $"""
+                SELECT i.INDEX_NAME,CASE WHEN i.UNIQUENESS='UNIQUE' THEN 1 ELSE 0 END,
+                    CASE WHEN p.CONSTRAINT_NAME IS NULL THEN 0 ELSE 1 END,c.COLUMN_NAME
+                FROM SYS.ALL_INDEXES i
+                JOIN SYS.ALL_IND_COLUMNS c ON c.INDEX_OWNER=i.OWNER AND c.INDEX_NAME=i.INDEX_NAME
+                LEFT JOIN SYS.ALL_CONSTRAINTS p ON p.INDEX_OWNER=i.OWNER AND p.INDEX_NAME=i.INDEX_NAME
+                  AND p.CONSTRAINT_TYPE='P'
+                WHERE i.TABLE_OWNER={schema} AND i.TABLE_NAME={table} AND i.INDEX_TYPE='NORMAL' AND i.STATUS='VALID'
+                ORDER BY i.INDEX_NAME,c.COLUMN_POSITION
+                """,
+        };
+        BindCatalogTarget(query, name);
+        using var cancel = CancelOdbc(query, token);
+        await using var reader = await query.ExecuteReaderAsync(token);
+        var fields = new List<(string Index, bool Unique, bool Primary, string? Column)>();
+        while (await reader.ReadAsync(token))
+            fields.Add((reader.GetString(0), Integer(reader, 1) == 1, Integer(reader, 2) == 1,
+                reader.IsDBNull(3) ? null : reader.GetString(3)));
+        return fields.GroupBy(c => new { c.Index, c.Unique, c.Primary })
+            .Where(g => g.All(c => c.Column != null))
+            .Select(g => new RelationalIndex(g.Key.Index, g.Key.Unique, g.Key.Primary, g.Select(c => c.Column!).ToArray()))
+            .ToArray();
+    }
+
+    private async Task<long?> EstimateRows(string name, CancellationToken token)
+    {
+        var schema = Marker("@schema", ":schema", 1);
+        var table = Marker("@table", ":source_table", 2);
+        await using var query = CreateCommand();
+        query.CommandText = dialect switch
+        {
+            SourceDialect.MySql => $"SELECT table_rows FROM information_schema.tables WHERE table_schema={schema} AND table_name={table}",
+            SourceDialect.Oracle => $"SELECT NUM_ROWS FROM SYS.ALL_TABLES WHERE OWNER={schema} AND TABLE_NAME={table}",
+            SourceDialect.PostgreSql => $"""
+                SELECT CAST(c.reltuples AS bigint)
+                FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
+                WHERE n.nspname={schema} AND c.relname={table} AND c.relkind IN ('r','m')
+                """,
+            _ => $"""
+                SELECT SUM(CAST(p.rows AS bigint))
+                FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id
+                JOIN sys.partitions p ON p.object_id=t.object_id AND p.index_id IN (0,1)
+                WHERE s.name={schema} AND t.name={table}
+                """,
+        };
+        BindCatalogTarget(query, name);
+        using var cancel = CancelOdbc(query, token);
+        var result = await query.ExecuteScalarAsync(token);
+        if (result is null or DBNull) return null;
+        var rows = Convert.ToInt64(result, CultureInfo.InvariantCulture);
+        return rows >= 0 ? rows : null;
+    }
+
+    private void BindCatalogTarget(DbCommand command, string name)
+    {
+        Add(command, "schema", DbType.String, mapping.Schema);
+        Add(command, dialect == SourceDialect.Oracle ? "source_table" : "table", DbType.String, name);
+    }
+
+    private static long Integer(DbDataReader reader, int ordinal) =>
+        Convert.ToInt64(reader.GetValue(ordinal), CultureInfo.InvariantCulture);
+}

+ 168 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeReadSession.Inspection.cs

@@ -0,0 +1,168 @@
+using System.Data;
+using System.Diagnostics;
+using System.Globalization;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
+
+internal sealed partial class NativeReadSession
+{
+    public async Task<RelationalInspection> InspectAsync(RelationalPreflightOptions options, CancellationToken token, string? catalogObject = null)
+    {
+        var capabilities = await ProbeAsync(token);
+        var requested = string.IsNullOrEmpty(catalogObject) ? mapping.Table : catalogObject;
+        var browseOnly = !string.Equals(requested, mapping.Table, StringComparison.Ordinal);
+        var objects = new List<RelationalObject>();
+        var columns = new List<RelationalColumn>();
+        var sample = new List<RelationalSampleStat>();
+        var diagnostics = new List<RelationalCheck>();
+        if (capabilities.ReadOnly)
+        {
+            try
+            {
+                await using var catalog = CreateCommand();
+                var marker = Marker("@schema", ":schema", 1);
+                catalog.CommandText = dialect switch
+                {
+                    SourceDialect.Oracle => $"""
+                        SELECT OBJECT_NAME, OBJECT_TYPE FROM SYS.ALL_OBJECTS
+                        WHERE OWNER={marker} AND OBJECT_TYPE IN ('TABLE','VIEW')
+                        ORDER BY OBJECT_NAME FETCH NEXT 201 ROWS ONLY
+                        """,
+                    SourceDialect.SqlServer => $"""
+                        SELECT TOP (201) TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES
+                        WHERE TABLE_SCHEMA={marker} ORDER BY TABLE_NAME
+                        """,
+                    _ => $"""
+                        SELECT TABLE_NAME, TABLE_TYPE FROM information_schema.tables
+                        WHERE TABLE_SCHEMA={marker} ORDER BY TABLE_NAME LIMIT 201
+                        """,
+                };
+                Add(catalog, "schema", DbType.String, mapping.Schema);
+                using var cancel = CancelOdbc(catalog, token);
+                await using var reader = await catalog.ExecuteReaderAsync(token);
+                while (await reader.ReadAsync(token))
+                    objects.Add(new(reader.GetString(0), reader.GetString(1)));
+                if (objects.Count > 200)
+                {
+                    objects.RemoveAt(200);
+                    diagnostics.Add(new("catalog-limit", "warning", "目录展示前 200 个可见对象"));
+                }
+            }
+            catch (System.Data.Common.DbException) when (!token.IsCancellationRequested)
+            {
+                diagnostics.Add(new("catalog", "warning", "驱动未能返回表和视图目录"));
+            }
+
+            if (browseOnly && !objects.Any(item => item.Name == requested))
+                throw new ConnectorContractException(ConnectorError.ScopeMismatch);
+            try
+            {
+                await using var fields = CreateCommand();
+                var schema = Marker("@schema", ":schema", 1);
+                var table = Marker("@table", ":source_table", 2);
+                fields.CommandText = dialect == SourceDialect.Oracle
+                    ? $"""
+                        SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, CHAR_LENGTH, DATA_PRECISION, DATA_SCALE,
+                            CHARACTER_SET_NAME, NULL
+                        FROM SYS.ALL_TAB_COLUMNS WHERE OWNER={schema} AND TABLE_NAME={table} ORDER BY COLUMN_ID
+                        """
+                    : $"""
+                        SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, CHARACTER_MAXIMUM_LENGTH,
+                            NUMERIC_PRECISION, NUMERIC_SCALE, CHARACTER_SET_NAME, COLUMN_DEFAULT
+                        FROM information_schema.columns WHERE TABLE_SCHEMA={schema} AND TABLE_NAME={table}
+                        ORDER BY ORDINAL_POSITION
+                        """;
+                Add(fields, "schema", DbType.String, mapping.Schema);
+                Add(fields, dialect == SourceDialect.Oracle ? "source_table" : "table", DbType.String, requested);
+                using var cancel = CancelOdbc(fields, token);
+                await using var reader = await fields.ExecuteReaderAsync(token);
+                while (await reader.ReadAsync(token))
+                {
+                    long? Number(int i) => reader.IsDBNull(i) ? null : Convert.ToInt64(reader.GetValue(i), CultureInfo.InvariantCulture);
+                    columns.Add(new(reader.GetString(0), reader.GetString(1), reader.GetString(2) is "Y" or "YES",
+                        Number(3), (int?)Number(4), (int?)Number(5), reader.IsDBNull(6) ? null : reader.GetString(6),
+                        reader.IsDBNull(7) ? null : "已设置"));
+                }
+            }
+            catch (System.Data.Common.DbException) when (!token.IsCancellationRequested)
+            {
+                diagnostics.Add(new("metadata", "warning", "驱动未能返回完整字段类型"));
+            }
+        }
+        var sampled = 0;
+        var bytesRead = 0;
+        var sampling = Stopwatch.StartNew();
+        if (capabilities.Full && !browseOnly)
+        {
+            try
+            {
+                var page = await ReadPageAsync(new(null, 20), token);
+                if (page is not null)
+                {
+                    using var payload = JsonDocument.Parse(page.Payload);
+                    var rows = payload.RootElement.GetProperty("data").GetProperty("list").EnumerateArray().ToArray();
+                    bytesRead = page.Payload.Length;
+                    sampled = rows.Length;
+                    foreach (var name in mapping.Columns)
+                    {
+                        var values = rows.Select(row => row.GetProperty(name)).Where(v => v.ValueKind != JsonValueKind.Null).ToArray();
+                        sample.Add(new(name, rows.Length, rows.Length - values.Length, values.Select(v => v.GetRawText()).Distinct().Count()));
+                    }
+                }
+            }
+            catch (Exception error) when (!token.IsCancellationRequested && error is ConnectorContractException or System.Data.Common.DbException or OverflowException)
+            {
+                diagnostics.Add(new("sample", "warning", "源字段转换预检有异常,请校验类型和数值范围"));
+            }
+        }
+
+        sampling.Stop();
+        RelationalCatalogAdvice? advice = null;
+        if (capabilities.ReadOnly)
+        {
+            IReadOnlyList<RelationalIndex> indexes = [];
+            long? rows = null;
+            try { indexes = await ReadIndexes(requested, token); }
+            catch (System.Data.Common.DbException) when (!token.IsCancellationRequested)
+            {
+                diagnostics.Add(new("index-metadata", "warning", "驱动未能核实索引目录"));
+            }
+            try { rows = await EstimateRows(requested, token); }
+            catch (System.Data.Common.DbException) when (!token.IsCancellationRequested) { }
+            if (rows is null)
+                diagnostics.Add(new("estimate", "warning", "源目录暂无可用统计,更新统计后可重新估算"));
+
+            advice = RelationalCatalogAdvice.Analyze(columns, indexes, options.IncrementalField, mapping.PositionColumn,
+                rows, sampled, bytesRead, sampling.Elapsed.TotalSeconds);
+        }
+        var grant = capabilities.ReadOnly ? MinimumGrant(requested) : null;
+        if (browseOnly)
+        {
+            if (!capabilities.ReadOnly)
+                throw new ConnectorContractException(ConnectorError.ScopeMismatch);
+            diagnostics.Add(new("catalog-only", "warning", "仅查看对象结构,正式预检使用来源配置中的对象"));
+            return new(mapping.Schema, requested, "", objects, columns, sample, diagnostics, grant, advice);
+        }
+        diagnostics.AddRange(RelationalPreflight.Evaluate(capabilities, options, columns.Select(x => x.Name).ToArray()));
+        if (columns.Any(c => c.Scale is not null && c.Precision > 28 &&
+            (c.Type.Equals("decimal", StringComparison.OrdinalIgnoreCase) ||
+             c.Type.Equals("numeric", StringComparison.OrdinalIgnoreCase) || c.Type == "NUMBER")))
+            diagnostics.Add(new("precision", "warning", "源字段精度可能超出接收范围,需按目标映射验证"));
+        return new(mapping.Schema, mapping.Table, mapping.PositionColumn, objects, columns, sample, diagnostics, grant, advice);
+    }
+
+    private string? MinimumGrant(string objectName)
+    {
+        var target = Quote(mapping.Schema) + "." + Quote(objectName);
+        return dialect switch
+        {
+            SourceDialect.PostgreSql => $"GRANT USAGE ON SCHEMA {Quote(mapping.Schema)} TO mdp_reader;\nGRANT SELECT ON {target} TO mdp_reader;",
+            SourceDialect.Oracle => $"GRANT SELECT ON {target} TO MDP_READER;",
+            SourceDialect.SqlServer => $"GRANT SELECT ON OBJECT::{target} TO [mdp_reader];",
+            SourceDialect.MySql => $"GRANT SELECT ON {target} TO 'mdp_reader'@'approved-host';",
+            _ => null,
+        };
+    }
+}

+ 208 - 33
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeReadSession.cs

@@ -1,49 +1,130 @@
 using DbType = System.Data.DbType;
 using System.Data.Common;
+using System.Data.Odbc;
 using System.Globalization;
+using System.Text;
 using System.Text.Json;
 using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Npgsql;
+using Oracle.ManagedDataAccess.Client;
+using Oracle.ManagedDataAccess.Types;
 
 namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
 
-internal sealed class NativeReadSession(DbConnection connection, RelationalSourceMapping mapping) : IRelationalReadSession
+internal enum SourceDialect { Unknown, MySql, SqlServer, PostgreSql, Oracle }
+
+internal sealed partial class NativeReadSession(DbConnection connection, RelationalSourceMapping mapping, SourceDialect dialect, bool odbc)
+    : IRelationalReadSession, IRelationalSourceInspection
 {
     private bool _verified;
-    private bool IsMySql => mapping.Execution.ConnectorId == NativeRelationalDriver.MySqlId;
-    private string Quote(string name) => IsMySql ? "`" + name.Replace("`", "``") + "`" : "[" + name.Replace("]", "]]") + "]";
+    private string Quote(string name) => dialect switch
+    {
+        SourceDialect.MySql => "`" + name.Replace("`", "``") + "`",
+        SourceDialect.SqlServer => "[" + name.Replace("]", "]]") + "]",
+        _ => "\"" + name.Replace("\"", "\"\"") + "\"",
+    };
     private string Table => Quote(mapping.Schema) + "." + Quote(mapping.Table);
     private string Columns => string.Join(", ", mapping.Columns.Select(Quote));
-
     public async Task<RelationalReadCapabilities> ProbeAsync(CancellationToken token)
     {
         _verified = false;
-        var readOnly = await HasReadOnlyGrantsAsync(token);
-        if (!readOnly)
-            return new(false, false, false);
-
-        await using var key = connection.CreateCommand();
-        key.CommandText = IsMySql ? NativeSourceSql.MySqlKey : NativeSourceSql.SqlServerKey;
-        Add(key, "@schema", DbType.String, mapping.Schema);
-        Add(key, "@table", DbType.String, mapping.Table);
-        Add(key, "@key", DbType.String, mapping.PositionColumn);
-        if (Convert.ToInt32(await key.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) != 1)
-            return new(true, false, false);
+        if (dialect == SourceDialect.Unknown)
+            return Blocked("driver-family-unverified");
+
+        if (dialect == SourceDialect.PostgreSql)
+        {
+            if (mapping.Columns.Append(mapping.Schema).Append(mapping.Table).Append(mapping.PositionColumn)
+                .Any(name => Encoding.UTF8.GetByteCount(name) > 63))
+                return Blocked("identifier-unverified");
+            await using var searchPath = CreateCommand();
+            searchPath.CommandText = "SET search_path TO pg_catalog";
+            using var cancel = CancelOdbc(searchPath, token);
+            await searchPath.ExecuteNonQueryAsync(token);
+        }
+
+        if (!await HasReadOnlyGrantsAsync(token))
+            return Blocked("read-only-permission-unverified");
+
+        try
+        {
+            await using var key = CreateCommand();
+            key.CommandText = dialect switch
+            {
+                SourceDialect.MySql => NativeSourceSql.MySqlKey,
+                SourceDialect.SqlServer when odbc => NativeSourceSql.SqlServerKey
+                    .Replace("@schema", "?").Replace("@table", "?").Replace("@key", "?"),
+                SourceDialect.SqlServer => NativeSourceSql.SqlServerKey,
+                SourceDialect.PostgreSql => PostgreSqlSql(NativeSourceSql.PostgreSqlKey),
+                _ => NativeSourceSql.OracleKey,
+            };
+            BindTarget(key, includeKey: true);
+            using var cancel = CancelOdbc(key, token);
+            if (Convert.ToInt32(await key.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) != 1)
+                return Blocked("stable-key-unverified", readOnly: true);
+        }
+        catch (DbException) when (!token.IsCancellationRequested)
+        {
+            return Blocked("stable-key-unverified", readOnly: true);
+        }
 
         // Validate access to the actual projection too (column-level grants are possible).
-        await using var projection = connection.CreateCommand();
-        projection.CommandText = $"SELECT {Quote(mapping.PositionColumn)}, {Columns} FROM {Table} WHERE 1=0";
-        await using var reader = await projection.ExecuteReaderAsync(token);
+        try
+        {
+            await using var projection = CreateCommand();
+            projection.CommandText = $"SELECT {Quote(mapping.PositionColumn)}, {Columns} FROM {Table} WHERE 1=0";
+            using var cancel = CancelOdbc(projection, token);
+            await using var reader = await projection.ExecuteReaderAsync(token);
+        }
+        catch (DbException) when (!token.IsCancellationRequested)
+        {
+            return Blocked("projection-unverified", readOnly: true);
+        }
+
+        if (odbc || dialect is SourceDialect.PostgreSql or SourceDialect.Oracle)
+        {
+            try
+            {
+                // Exercises both bound markers, including resumed reads. No sample is submitted.
+                await using var paging = CreatePageCommand(long.MinValue, 1);
+                using var cancel = CancelOdbc(paging, token);
+                await using var reader = await paging.ExecuteReaderAsync(token);
+                if (await reader.ReadAsync(token))
+                    _ = reader.GetDecimal(0);
+            }
+            catch (Exception error) when (!token.IsCancellationRequested && error is DbException or InvalidCastException or OverflowException)
+            {
+                return Blocked("parameterized-paging-unverified", readOnly: true);
+            }
+        }
         _verified = true;
         return new(true, true, false);
     }
 
+    private static RelationalReadCapabilities Blocked(string reason, bool readOnly = false) =>
+        new(readOnly, false, false) { Reason = reason };
+
     private async Task<bool> HasReadOnlyGrantsAsync(CancellationToken token)
     {
-        await using var command = connection.CreateCommand();
-        if (!IsMySql)
+        await using var command = CreateCommand();
+        using var cancel = CancelOdbc(command, token);
+        if (dialect != SourceDialect.MySql)
         {
-            command.CommandText = NativeSourceSql.SqlServerReadOnly;
-            return Convert.ToInt32(await command.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) == 1;
+            command.CommandText = dialect switch
+            {
+                SourceDialect.SqlServer => NativeSourceSql.SqlServerReadOnly,
+                SourceDialect.PostgreSql => PostgreSqlSql(NativeSourceSql.PostgreSqlReadOnly),
+                _ => NativeSourceSql.OracleReadOnly,
+            };
+            if (dialect != SourceDialect.SqlServer)
+                BindTarget(command, includeKey: false);
+            try
+            {
+                return Convert.ToInt32(await command.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) == 1;
+            }
+            catch (DbException) when (!token.IsCancellationRequested)
+            {
+                return false;
+            }
         }
 
         command.CommandText = "SHOW GRANTS";
@@ -68,24 +149,18 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
         if (request.BatchSize < 1 || request.BatchSize == int.MaxValue)
             throw new ConnectorContractException(ConnectorError.InvalidBatch);
 
-        await using var command = connection.CreateCommand();
-        var key = Quote(mapping.PositionColumn);
-        var where = "";
         decimal? previous = null;
         if (request.LastCommittedCheckpoint is { } checkpoint)
         {
             if (!decimal.TryParse(checkpoint, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var after)
                 || after.ToString(CultureInfo.InvariantCulture) != checkpoint
-                || after < long.MinValue || after > (IsMySql ? (decimal)ulong.MaxValue : long.MaxValue))
+                || !FitsPosition(after))
                 throw new ConnectorContractException(ConnectorError.InvalidBatch);
             previous = after;
-            where = $" WHERE {key} > @after";
-            Add(command, "@after", DbType.Decimal, after);
         }
 
-        Add(command, "@take", DbType.Int32, request.BatchSize + 1);
-        var projection = $"CAST({key} AS DECIMAL(20,0)), {Columns} FROM {Table}{where} ORDER BY {key}";
-        command.CommandText = IsMySql ? $"SELECT {projection} LIMIT @take" : $"SELECT TOP (@take) {projection}";
+        await using var command = CreatePageCommand(previous, request.BatchSize + 1);
+        using var cancel = CancelOdbc(command, token);
         await using var reader = await command.ExecuteReaderAsync(token);
         using var buffer = new MemoryStream();
         using var json = new Utf8JsonWriter(buffer);
@@ -98,6 +173,8 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
         while (count < request.BatchSize && await reader.ReadAsync(token))
         {
             var position = reader.GetDecimal(0);
+            if (!FitsPosition(position))
+                throw new ConnectorContractException(ConnectorError.InvalidBatch);
             if (previous.HasValue && position <= previous.Value)
                 throw new ConnectorContractException(ConnectorError.InvalidBatch);
             previous = position;
@@ -108,7 +185,7 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
                 if (reader.IsDBNull(i + 1))
                     json.WriteNullValue();
                 else
-                    JsonSerializer.Serialize(json, reader.GetValue(i + 1));
+                    WriteValue(json, reader, i + 1);
             }
             json.WriteEndObject();
             count++;
@@ -126,14 +203,112 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
         return new(batchId, batchId, buffer.ToArray(), next, next, more);
     }
 
+    private bool FitsPosition(decimal position) => dialect switch
+    {
+        SourceDialect.MySql => position >= long.MinValue && position <= ulong.MaxValue,
+        SourceDialect.Oracle => position >= -9999999999999999999m && position <= 9999999999999999999m,
+        _ => position >= long.MinValue && position <= long.MaxValue,
+    };
+
+    private DbCommand CreateCommand()
+    {
+        var command = connection.CreateCommand();
+        if (odbc || dialect is SourceDialect.PostgreSql or SourceDialect.Oracle)
+            command.CommandTimeout = 8;
+        if (command is OracleCommand oracle)
+            oracle.BindByName = true;
+        return command;
+    }
+
+    private DbCommand CreatePageCommand(decimal? after, int take)
+    {
+        var command = CreateCommand();
+        var position = Quote(mapping.PositionColumn);
+        var afterParameter = Marker("@after", ":after", 1);
+        var takeParameter = Marker("@take", ":take", after.HasValue ? 2 : 1);
+        var filter = after.HasValue ? $" WHERE {position} > {afterParameter}" : "";
+        var ordered = $"CAST({position} AS DECIMAL(20,0)), {Columns} FROM {Table} src{filter} ORDER BY src.{position}";
+        command.CommandText = dialect switch
+        {
+            SourceDialect.SqlServer => $"SELECT TOP ({takeParameter}) {ordered}",
+            SourceDialect.Oracle => $"SELECT {ordered} FETCH NEXT {takeParameter} ROWS ONLY",
+            _ => $"SELECT {ordered} LIMIT {takeParameter}",
+        };
+
+        // With ODBC, TOP appears before WHERE. LIMIT uses the opposite parameter order.
+        var topFirst = odbc && dialect == SourceDialect.SqlServer;
+        if (topFirst) Add(command, "take", DbType.Int32, take);
+        if (after is { } value)
+        {
+            if (dialect == SourceDialect.PostgreSql)
+                Add(command, "after", DbType.Int64, (long)value);
+            else
+                Add(command, "after", DbType.Decimal, value);
+        }
+        if (!topFirst) Add(command, "take", DbType.Int32, take);
+        return command;
+    }
+
+    private string Marker(string named, string oracle, int position) =>
+        odbc ? "?" : dialect switch
+        {
+            SourceDialect.Oracle => oracle,
+            SourceDialect.PostgreSql => "$" + position.ToString(CultureInfo.InvariantCulture),
+            _ => named,
+        };
+
+    private string PostgreSqlSql(string format) => string.Format(CultureInfo.InvariantCulture, format,
+        Marker("", "", 1), Marker("", "", 2), Marker("", "", 3));
+
+    private void BindTarget(DbCommand command, bool includeKey)
+    {
+        var oracle = dialect == SourceDialect.Oracle;
+        Add(command, "schema", DbType.String, mapping.Schema);
+        Add(command, oracle ? "source_table" : "table", DbType.String, mapping.Table);
+        if (includeKey) Add(command, oracle ? "source_key" : "key", DbType.String, mapping.PositionColumn);
+    }
+
+    private static void WriteValue(Utf8JsonWriter json, DbDataReader reader, int index)
+    {
+        if (reader is OracleDataReader oracle && oracle.GetDataTypeName(index) == "NUMBER")
+        {
+            try
+            {
+                var number = oracle.GetOracleDecimal(index);
+                var value = number.Value;
+                if (new OracleDecimal(value).CompareTo(number) != 0)
+                    throw new ConnectorContractException(ConnectorError.InvalidBatch);
+                json.WriteNumberValue(value);
+            }
+            catch (Exception error) when (error is OverflowException or InvalidCastException)
+            {
+                throw new ConnectorContractException(ConnectorError.InvalidBatch);
+            }
+        }
+        else
+            JsonSerializer.Serialize(json, reader.GetValue(index));
+    }
+
     private static void Add(DbCommand command, string name, DbType type, object value)
     {
         var parameter = command.CreateParameter();
-        parameter.ParameterName = name;
+        parameter.ParameterName = command switch
+        {
+            NpgsqlCommand => "",
+            OracleCommand => name,
+            _ => "@" + name,
+        };
         parameter.DbType = type;
         parameter.Value = value;
         command.Parameters.Add(parameter);
     }
 
+    private static CancellationTokenRegistration CancelOdbc(DbCommand command, CancellationToken token) =>
+        command is OdbcCommand ? token.UnsafeRegister(static state =>
+        {
+            try { ((OdbcCommand)state!).Cancel(); }
+            catch (Exception error) when (error is DbException or InvalidOperationException or NotSupportedException) { }
+        }, command) : default;
+
     public ValueTask DisposeAsync() => connection.DisposeAsync();
 }

+ 58 - 11
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeRelationalDriver.cs

@@ -2,6 +2,8 @@ using System.Data.Common;
 using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
 using Microsoft.Data.SqlClient;
 using MySqlConnector;
+using Npgsql;
+using Oracle.ManagedDataAccess.Client;
 
 namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
 
@@ -18,30 +20,45 @@ public sealed class NativeRelationalDriver : IRelationalSourceDriver
 {
     public const string MySqlId = "mdp.mysql";
     public const string SqlServerId = "mdp.sqlserver";
+    public const string PostgreSqlId = "mdp.postgresql";
+    public const string OracleId = "mdp.oracle";
     public const string Version = "1.0.0";
     private readonly RelationalSourceMapping _mapping;
     private readonly Func<ConnectorBinding, string, CancellationToken, Task<string>> _resolve;
 
     public NativeRelationalDriver(RelationalSourceMapping mapping,
         Func<ConnectorBinding, string, CancellationToken, Task<string>> resolve)
+        : this(mapping, resolve, false)
+    {
+    }
+
+    private readonly bool _odbc;
+
+    // The ODBC driver delegates only the shared binding and session lifecycle here.
+    internal NativeRelationalDriver(RelationalSourceMapping mapping,
+        Func<ConnectorBinding, string, CancellationToken, Task<string>> resolve, bool odbc)
     {
         var id = mapping.Execution.ConnectorId;
-        if (id is not (MySqlId or SqlServerId) || mapping.Execution.ConnectorVersion != Version)
+        if ((odbc ? id != OdbcRelationalDriver.Id : id is not (MySqlId or SqlServerId or PostgreSqlId or OracleId))
+            || mapping.Execution.ConnectorVersion != Version)
             throw new ConnectorContractException(ConnectorError.UnsupportedVersion);
         if (mapping.Execution.Mode != ConnectorManifest.Database)
             throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
 
         var columns = mapping.Columns?.ToArray() ?? [];
-        var limit = id == MySqlId ? 64 : 128;
+        var limit = id == PostgreSqlId ? 63 : id == MySqlId ? 64 : 128;
         if (string.IsNullOrWhiteSpace(mapping.SecretRef) || columns.Length == 0
             || columns.Distinct(StringComparer.OrdinalIgnoreCase).Count() != columns.Length
             || columns.Concat(new[] { mapping.Database, mapping.Schema, mapping.Table, mapping.PositionColumn })
                 .Any(name => string.IsNullOrWhiteSpace(name) || name.Length > limit || name.Any(char.IsControl))
-            || (id == MySqlId && mapping.Database != mapping.Schema))
+            || (id == MySqlId && mapping.Database != mapping.Schema)
+            || (id == PostgreSqlId && new[] { mapping.Schema, mapping.Table, mapping.PositionColumn }
+                .Concat(columns).Any(name => System.Text.Encoding.UTF8.GetByteCount(name) > 63)))
             throw new ConnectorContractException(ConnectorError.InvalidManifest);
 
         _mapping = mapping with { Columns = columns };
         _resolve = resolve ?? throw new ArgumentNullException(nameof(resolve));
+        _odbc = odbc;
     }
 
     public string ConnectorId => _mapping.Execution.ConnectorId;
@@ -57,23 +74,53 @@ public sealed class NativeRelationalDriver : IRelationalSourceDriver
         return new MySqlConnection(options.ConnectionString);
     }
 
-    public async Task<IRelationalReadSession> OpenReadOnlyAsync(
-        ConnectorExecution execution, string secretRef, CancellationToken cancellationToken)
+    public Task<IRelationalReadSession> OpenReadOnlyAsync(
+        ConnectorExecution execution, string secretRef, CancellationToken cancellationToken) =>
+        OpenReadOnlyAsync(execution, secretRef, null, cancellationToken);
+
+    internal async Task<IRelationalReadSession> OpenReadOnlyAsync(
+        ConnectorExecution execution, string secretRef, string? odbcFamily, CancellationToken cancellationToken)
     {
         if (execution != _mapping.Execution || secretRef != _mapping.SecretRef)
             throw new ConnectorContractException(ConnectorError.ScopeMismatch);
 
         cancellationToken.ThrowIfCancellationRequested();
         var connectionString = await _resolve(execution.Binding, secretRef, cancellationToken);
-        DbConnection connection = ConnectorId == MySqlId
-            ? CreateMySqlConnection(connectionString)
-            : new SqlConnection(connectionString);
+        DbConnection connection = ConnectorId switch
+        {
+            MySqlId => CreateMySqlConnection(connectionString),
+            SqlServerId => new SqlConnection(connectionString),
+            PostgreSqlId => new NpgsqlConnection(connectionString),
+            OracleId => new OracleConnection(connectionString),
+            _ => OdbcRelationalDriver.CreateConnection(connectionString),
+        };
         try
         {
-            await connection.OpenAsync(cancellationToken);
-            if (!string.Equals(connection.Database, _mapping.Database, StringComparison.Ordinal))
+            // System.Data.Odbc uses synchronous I/O even for its async-shaped methods.
+            if (_odbc)
+                await Task.Run(connection.Open, cancellationToken);
+            else
+                await connection.OpenAsync(cancellationToken);
+            cancellationToken.ThrowIfCancellationRequested();
+            var dialect = ConnectorId switch
+            {
+                MySqlId => SourceDialect.MySql,
+                SqlServerId => SourceDialect.SqlServer,
+                PostgreSqlId => SourceDialect.PostgreSql,
+                OracleId => SourceDialect.Oracle,
+                _ => OdbcRelationalDriver.GetDialect((System.Data.Odbc.OdbcConnection)connection, odbcFamily),
+            };
+            var database = connection.Database;
+            if (dialect == SourceDialect.Oracle)
+            {
+                await using var identity = connection.CreateCommand();
+                identity.CommandTimeout = 8;
+                identity.CommandText = "SELECT SYS_CONTEXT('USERENV', 'CON_NAME') FROM DUAL";
+                database = (string?)await identity.ExecuteScalarAsync(cancellationToken);
+            }
+            if (dialect != SourceDialect.Unknown && !string.Equals(database, _mapping.Database, StringComparison.Ordinal))
                 throw new ConnectorContractException(ConnectorError.ScopeMismatch);
-            return new NativeReadSession(connection, _mapping);
+            return new NativeReadSession(connection, _mapping, dialect, _odbc);
         }
         catch
         {

+ 54 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/NativeSourceSql.cs

@@ -45,4 +45,58 @@ internal static class NativeSourceSql
                        AND NOT (p.class=1 AND p.major_id<0 AND u.name='public'))
           THEN 0 ELSE 1 END
         """;
+
+    internal const string PostgreSqlReadOnly = """
+        SELECT CASE WHEN EXISTS (
+            SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
+            WHERE n.nspname={0} AND c.relname={1} AND c.relkind IN ('r','p')
+              AND NOT EXISTS (
+                  SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'MEMBER')
+                    AND (r.rolsuper OR pg_has_role(r.oid, c.relowner, 'USAGE')
+                         OR pg_has_role(r.oid, n.nspowner, 'USAGE')
+                         OR has_table_privilege(r.oid, c.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, TRIGGER')
+                         OR has_any_column_privilege(r.oid, c.oid, 'INSERT, UPDATE'))
+              )
+        ) THEN 1 ELSE 0 END
+        """;
+
+    internal const string PostgreSqlKey = """
+        SELECT COUNT(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
+        JOIN pg_constraint p ON p.conrelid=c.oid AND p.contype='p' AND p.convalidated
+        JOIN pg_attribute k ON k.attrelid=c.oid AND k.attnum=p.conkey[1]
+        WHERE n.nspname={0} AND c.relname={1} AND k.attname={2}
+          AND (c.relkind='p' OR (c.relkind='r' AND NOT c.relhassubclass))
+          AND cardinality(p.conkey)=1 AND k.attnotnull AND NOT k.attisdropped
+          AND k.atttypid IN ('int2'::regtype,'int4'::regtype,'int8'::regtype)
+        """;
+
+    internal const string OracleReadOnly = """
+        WITH target AS (SELECT :schema AS owner, :source_table AS table_name FROM SYS.DUAL)
+        SELECT CASE WHEN USER IN ('SYS','SYSTEM') OR USER=(SELECT owner FROM target)
+          OR EXISTS (SELECT 1 FROM SYS.SESSION_PRIVS WHERE PRIVILEGE <> 'CREATE SESSION')
+          OR EXISTS (
+            SELECT 1 FROM SYS.ALL_TAB_PRIVS p JOIN target t
+              ON p.TABLE_SCHEMA=t.owner AND p.TABLE_NAME=t.table_name
+            WHERE (p.GRANTEE IN (USER,'PUBLIC') OR p.GRANTEE IN (SELECT ROLE FROM SYS.SESSION_ROLES))
+              AND (p.PRIVILEGE NOT IN ('SELECT','READ') OR p.GRANTABLE='YES')
+          )
+          OR EXISTS (
+            SELECT 1 FROM SYS.ALL_COL_PRIVS p JOIN target t
+              ON p.TABLE_SCHEMA=t.owner AND p.TABLE_NAME=t.table_name
+            WHERE p.GRANTEE IN (USER,'PUBLIC') OR p.GRANTEE IN (SELECT ROLE FROM SYS.SESSION_ROLES)
+          )
+          THEN 0 ELSE 1 END FROM SYS.DUAL
+        """;
+
+    internal const string OracleKey = """
+        SELECT COUNT(*) FROM SYS.ALL_TABLES t
+        JOIN SYS.ALL_CONSTRAINTS p ON p.OWNER=t.OWNER AND p.TABLE_NAME=t.TABLE_NAME
+        JOIN SYS.ALL_CONS_COLUMNS k ON k.OWNER=p.OWNER AND k.CONSTRAINT_NAME=p.CONSTRAINT_NAME
+        JOIN SYS.ALL_TAB_COLUMNS c ON c.OWNER=t.OWNER AND c.TABLE_NAME=t.TABLE_NAME AND c.COLUMN_NAME=k.COLUMN_NAME
+        WHERE t.OWNER=:schema AND t.TABLE_NAME=:source_table AND k.COLUMN_NAME=:source_key
+          AND p.CONSTRAINT_TYPE='P' AND p.STATUS='ENABLED' AND p.VALIDATED='VALIDATED' AND k.POSITION=1
+          AND c.DATA_TYPE='NUMBER' AND c.DATA_PRECISION BETWEEN 1 AND 19 AND c.DATA_SCALE=0 AND c.NULLABLE='N'
+          AND NOT EXISTS (SELECT 1 FROM SYS.ALL_CONS_COLUMNS x
+                          WHERE x.OWNER=p.OWNER AND x.CONSTRAINT_NAME=p.CONSTRAINT_NAME AND x.POSITION>1)
+        """;
 }

+ 47 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/OdbcRelationalDriver.cs

@@ -0,0 +1,47 @@
+using System.Data.Odbc;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
+
+public sealed class OdbcRelationalDriver : IRelationalSourceDriver
+{
+    public const string Id = "mdp.odbc";
+    private readonly NativeRelationalDriver _driver;
+    private readonly string _family;
+
+    public OdbcRelationalDriver(RelationalSourceMapping mapping, string family,
+        Func<ConnectorBinding, string, CancellationToken, Task<string>> resolve)
+    {
+        _family = family;
+        _driver = new NativeRelationalDriver(mapping, resolve, true);
+    }
+
+    public string ConnectorId => Id;
+    public string ConnectorVersion => _driver.ConnectorVersion;
+
+    public Task<IRelationalReadSession> OpenReadOnlyAsync(ConnectorExecution execution,
+        string secretRef, CancellationToken cancellationToken) =>
+        _driver.OpenReadOnlyAsync(execution, secretRef, _family, cancellationToken);
+
+    internal static OdbcConnection CreateConnection(string connectionString)
+    {
+        var settings = new OdbcConnectionStringBuilder(connectionString);
+        if (string.IsNullOrWhiteSpace(settings.Dsn) || !string.IsNullOrEmpty(settings.Driver)
+            || settings.Keys.Cast<string>().Any(key => key.ToUpperInvariant() is not ("DSN" or "DRIVER" or "UID" or "PWD")))
+            throw new ConnectorContractException(ConnectorError.InvalidManifest);
+        return new OdbcConnection(settings.ConnectionString) { ConnectionTimeout = 5 };
+    }
+
+    internal static SourceDialect GetDialect(OdbcConnection connection, string? family)
+    {
+        var driver = Path.GetFileName(connection.Driver.Replace('\\', '/')).ToLowerInvariant();
+        return family switch
+        {
+            "postgresql" when driver is "psqlodbcw.dll" or "psqlodbcw.so" => SourceDialect.PostgreSql,
+            "sqlserver" when driver is "msodbcsql17.dll" or "msodbcsql18.dll"
+                || driver.StartsWith("libmsodbcsql-17.", StringComparison.Ordinal)
+                || driver.StartsWith("libmsodbcsql-18.", StringComparison.Ordinal) => SourceDialect.SqlServer,
+            _ => SourceDialect.Unknown,
+        };
+    }
+}

+ 15 - 1
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Relational/README.md

@@ -2,7 +2,7 @@
 
 数据源管理中打开「接收数据集 → 版本与审批」。运维为授权的数据集配置来源后,有试跑权限的维护人员可选择来源,点击「读取并接收试跑批次」。数据集须绑定启用的来源和已审批发布的采购接收版本。
 
-将 `MDP_RELATIONAL_TRIALS_FILE` 指向只有服务身份可读的 JSON 数组,单个配置如下。配置及凭据文件存放于版本库外。MySQL 和 MariaDB 使用 `mdp.mysql`,SQL Server 使用 `mdp.sqlserver`。
+将 `MDP_RELATIONAL_TRIALS_FILE` 指向只有服务身份可读的 JSON 数组,单个配置如下。配置及凭据文件存放于版本库外。MySQL 和 MariaDB 使用 `mdp.mysql`,SQL Server 使用 `mdp.sqlserver`,PostgreSQL 使用 `mdp.postgresql`,Oracle 使用 `mdp.oracle`。
 
 ```json
 [
@@ -27,3 +27,17 @@
 ```
 
 源表使用单列整数主键。凭据文件包含页面签发的 `accessKey` 及 Base64 签名密钥 `secret`,授权范围须与来源和数据集一致。接收地址填写本机回环上的应用地址。每次试跑最多五页、每页两行。从持久接收回执确认位置,同一来源配置、版本、位置和报文重试时沿用原批次。批次进入统一接收待办,后续按现有 Worker 和采购交接配置处理。该入口是手动试跑,正式定时同步和增量水位由后续同步工作包交付。
+
+PostgreSQL 使用 `smallint`、`integer` 或 `bigint` 主键。Oracle 的 `database` 填实际连接的容器名,例如 `FREEPDB1`,`schema` 填对象所有者。Oracle 的主键为精度不超过 19 且小数位为 0 的 `NUMBER`。两者均以源端目录核验专用只读账号和所配置的主键及列。
+
+ODBC 使用 `driver: "mdp.odbc"` 和 `odbcFamily: "postgresql"` 或 `"sqlserver"`,分别匹配 PostgreSQL Unicode 或 Microsoft ODBC Driver 17/18 的实际驱动。后端环境安装驱动管理器和相应的 64 位驱动并登记专用 DSN。连接串仅接受 `DSN`、`UID` 和 `PWD`。TLS、库名和主机配置于服务端 DSN,驱动的只读声明还需通过数据库实际授权检查。驱动族、只读、主键、投影或参数化分页无法核实时,页面显示具体原因并阻止批次提交。PostgreSQL、Oracle 和 ODBC 先点「检查读取能力」,再提交试跑批次。提交时后端会重新检查。
+
+受控实库测试使用配对的 `MDP_TEST_<引擎>_READ`、`MDP_TEST_<引擎>_WRITE`,其中引擎为 `POSTGRESQL`、`ORACLE`、`ODBC_POSTGRESQL` 或 `ODBC_SQLSERVER`。测试表配置见 `MdpNativeRelationalDriverTests`。在部署目标使用真实 DSN、驱动版本和数据库组合重新执行。
+
+## 来源预检与隔离测算
+
+有试跑权限的维护人员可在面板选择数据集绑定的来源,查看源端表、视图、字段类型、候选键、索引、样本统计和风险。浏览同一 Schema 中其他可见对象只展示结构。配置来源表的读权、主键和参数化分页决定能否试跑。
+
+来源配置可加 `"preflight": {"timeZone":"UTC","encoding":"utf-8","deletePolicy":"unsupported","incrementalStrategy":"full"}`。已启用预检的匹配来源在试跑、候选预检及发布时检查阻断项。删除语义和增量策略如需使用,应由具有相应运行能力的同步版本验证。
+
+隔离测算复用 `MDP_INGEST_SANDBOX_MYSQL`,使用当前连接的临时表和经审批的采购映射。最多抽样 3 批,每批最多 50 行,测量源端读取、Raw 入库、清洗、贴源/标准层和对账耗时,并按读取结果或目录统计估算全量。保留容量可输入日均增量和保留天数,仅统计 Raw 原文,由已经对账的持久同步运行补充历史耗时和日均增量。

+ 63 - 11
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpNativeRelationalDriverTests.cs

@@ -33,20 +33,46 @@ public sealed class MdpNativeRelationalDriverTests
     [NativeSourceFact("SQLSERVER")]
     public Task SqlServerNative() => ExerciseEngine("SQLSERVER", NativeRelationalDriver.SqlServerId, "dbo");
 
+    [NativeSourceFact("POSTGRESQL")]
+    public Task PostgreSqlNative() => ExerciseEngine("POSTGRESQL", NativeRelationalDriver.PostgreSqlId, "mdp_fixture");
+
+    [NativeSourceFact("ORACLE")]
+    public Task OracleNative() => ExerciseEngine("ORACLE", NativeRelationalDriver.OracleId, "MDP_FIXTURE", "FREEPDB1");
+
+    [NativeSourceFact("ODBC_POSTGRESQL")]
+    public Task PostgreSqlOdbc() => ExerciseEngine("ODBC_POSTGRESQL", OdbcRelationalDriver.Id, "mdp_fixture", family: "postgresql");
+
+    [NativeSourceFact("ODBC_SQLSERVER")]
+    public Task SqlServerOdbc() => ExerciseEngine("ODBC_SQLSERVER", OdbcRelationalDriver.Id, "dbo", family: "sqlserver");
+
     [Theory]
     [InlineData(NativeRelationalDriver.MySqlId)]
     [InlineData(NativeRelationalDriver.SqlServerId)]
+    [InlineData(NativeRelationalDriver.PostgreSqlId)]
+    [InlineData(NativeRelationalDriver.OracleId)]
+    [InlineData(OdbcRelationalDriver.Id)]
     public async Task RejectsWrongScopeOrSecretBeforeResolving(string id)
     {
         var mapping = Mapping(id, "mdp_fixture");
-        var driver = new NativeRelationalDriver(mapping, (_, _, _) => throw new InvalidOperationException("unexpected resolution"));
+        var driver = Driver(mapping, (_, _, _) => throw new InvalidOperationException("unexpected resolution"), "postgresql");
         var wrong = mapping.Execution with { Binding = Binding with { Identity = Binding.Identity with { TenantId = 555 } } };
         Assert.Equal(ConnectorError.ScopeMismatch, (await Assert.ThrowsAsync<ConnectorContractException>(
             () => driver.OpenReadOnlyAsync(wrong, mapping.SecretRef, default))).Code);
         Assert.Equal(ConnectorError.ScopeMismatch, (await Assert.ThrowsAsync<ConnectorContractException>(
             () => driver.OpenReadOnlyAsync(mapping.Execution, "different", default))).Code);
-        Assert.Throws<ConnectorContractException>(() => new NativeRelationalDriver(
-            mapping with { Columns = new[] { "PoNo", "pono" } }, (_, _, _) => throw new InvalidOperationException()));
+        Assert.Throws<ConnectorContractException>(() => Driver(
+            mapping with { Columns = new[] { "PoNo", "pono" } }, (_, _, _) => throw new InvalidOperationException(), "postgresql"));
+    }
+
+    [Fact]
+    public async Task OdbcRejectsUnapprovedConnectionAttributesBeforeOpening()
+    {
+        var mapping = Mapping(OdbcRelationalDriver.Id, "mdp_fixture");
+        var driver = new OdbcRelationalDriver(mapping, "postgresql", (_, _, _) =>
+            Task.FromResult("DSN=fixture;Driver=unapproved"));
+        var error = await Assert.ThrowsAsync<ConnectorContractException>(() =>
+            driver.OpenReadOnlyAsync(mapping.Execution, mapping.SecretRef, default));
+        Assert.Equal(ConnectorError.InvalidManifest, error.Code);
     }
 
     [Fact]
@@ -64,28 +90,47 @@ public sealed class MdpNativeRelationalDriverTests
         new(new(Binding, id, NativeRelationalDriver.Version, ConnectorManifest.CloudDirect, ConnectorManifest.Database),
             "lab.read", "mdp_fixture", schema, "order", "rowid", new[] { "PoNo", "OrderQty", "ItemCode" });
 
-    private static async Task ExerciseEngine(string engine, string id, string schema)
+    private static IRelationalSourceDriver Driver(RelationalSourceMapping mapping,
+        Func<ConnectorBinding, string, CancellationToken, Task<string>> resolve, string family) =>
+        mapping.Execution.ConnectorId == OdbcRelationalDriver.Id
+            ? new OdbcRelationalDriver(mapping, family, resolve)
+            : new NativeRelationalDriver(mapping, resolve);
+
+    private static async Task ExerciseEngine(string engine, string id, string schema,
+        string database = "mdp_fixture", string family = "")
     {
-        var mapping = Mapping(id, schema);
+        var mapping = Mapping(id, schema) with { Database = database };
         var manifest = new ConnectorManifest(ConnectorManifest.FormatVersion, id, NativeRelationalDriver.Version,
             ConnectorManifest.SdkVersion, Binding.Identity.DatasetKey, Binding.SourceSchemaVersion,
             new[] { ConnectorManifest.CloudDirect }, new(mapping.SecretRef),
             new Dictionary<string, ConnectorCapability> { [ConnectorManifest.Database] = new("integer-primary-key", Full: true) },
             new("controlled-source", "under-test", Array.Empty<string>()));
         var schemas = new PurchaseOrderSchemaRegistry();
-        RelationalConnectorRuntime Runtime(RelationalSourceMapping source, string access)
+        RelationalConnectorRuntime Runtime(RelationalSourceMapping source, string access, string? driverFamily = null)
         {
-            var driver = new NativeRelationalDriver(source, (binding, reference, _) =>
+            var driver = Driver(source, (binding, reference, _) =>
             {
                 Assert.Equal(Binding, binding);
                 Assert.Equal(source.SecretRef, reference);
                 return Task.FromResult(Environment.GetEnvironmentVariable($"MDP_TEST_{engine}_{access}"));
-            });
+            }, driverFamily ?? family);
             return new(new[] { driver }, manifest, source.Execution, schemas);
         }
 
+        var inspectionDriver = Driver(mapping, (_, _, _) =>
+            Task.FromResult(Environment.GetEnvironmentVariable($"MDP_TEST_{engine}_READ")), family);
+        await using (var session = await inspectionDriver.OpenReadOnlyAsync(mapping.Execution, mapping.SecretRef, default))
+        {
+            var inspection = await Assert.IsAssignableFrom<IRelationalSourceInspection>(session)
+                .InspectAsync(new("UTC", "utf-8", "unsupported", null, "full", null), default);
+            Assert.Contains(inspection.Objects, x => x.Name == "order");
+            Assert.Contains(inspection.Columns, x => x.Name == "OrderQty" && x.Precision == 12 && x.Scale == 3);
+            Assert.Contains(inspection.Sample, x => x.Name == "ItemCode" && x.Sampled == 3 && x.Missing == 1);
+        }
+
         var runtime = Runtime(mapping, "READ");
-        Assert.True((await runtime.ProbeAsync(default)).Supported);
+        var probe = await runtime.ProbeAsync(default);
+        Assert.True(probe.Supported, probe.Reason);
         var first = await runtime.ReadAsync(new(null, 2), default);
         Assert.True(first.HasMore);
         Assert.Equal("0", first.Batch.Pending.NextCheckpoint);
@@ -108,8 +153,15 @@ public sealed class MdpNativeRelationalDriverTests
         Assert.Equal("P3", last.RootElement.GetProperty("data").GetProperty("list")[0].GetProperty("PoNo").GetString());
         Assert.Null(await runtime.ReadAsync(new("7", 2), default));
         await Assert.ThrowsAsync<ConnectorContractException>(() => runtime.ReadAsync(new("not-a-position", 2), default));
-        Assert.False((await Runtime(mapping with { Table = "no_key", Columns = new[] { "PoNo" } }, "READ")
-            .ProbeAsync(default)).Supported);
+        var noKey = await Runtime(mapping with { Table = "no_key", Columns = new[] { "PoNo" } }, "READ").ProbeAsync(default);
+        Assert.False(noKey.Supported);
+        if (id == OdbcRelationalDriver.Id)
+        {
+            Assert.Equal("stable-key-unverified", noKey.Reason);
+            var degraded = Runtime(mapping, "READ", "unrecognized");
+            Assert.Equal("driver-family-unverified", (await degraded.ProbeAsync(default)).Reason);
+            await Assert.ThrowsAsync<ConnectorContractException>(() => degraded.ReadAsync(new(null, 2), default));
+        }
         var writable = Runtime(mapping, "WRITE");
         Assert.False((await writable.ProbeAsync(default)).Supported);
         await Assert.ThrowsAsync<ConnectorContractException>(() => writable.ReadAsync(new(null, 2), default));

+ 55 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpRelationalCapacityTests.cs

@@ -0,0 +1,55 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpRelationalCapacityTests
+{
+    [Fact]
+    public void ExtrapolatesObservedBatchRangeAndKeepsRawBytesPerRow()
+    {
+        var estimate = RelationalCapacityEstimate.FromSamples(100, [
+            new(10, 500, 100, 50, 100, 200, 50),
+            new(20, 1500, 400, 100, 100, 700, 100)
+        ]);
+
+        Assert.Equal(30, estimate.SampleRows);
+        Assert.Equal(66.67m, estimate.RawBytesPerRow);
+        Assert.Equal(6667, estimate.FullRawBytes);
+        Assert.Equal(5m, estimate.FullSecondsLow);
+        Assert.Equal(7m, estimate.FullSecondsHigh);
+    }
+
+    [Fact]
+    public void PreservesUnknownScaleAndSingleBatchEvidence()
+    {
+        Assert.Null(RelationalCapacityEstimate.FromSamples(100, []).RawBytesPerRow);
+        var estimate = RelationalCapacityEstimate.FromSamples(null, [new(2, 100, 10, 20, 10, 50, 10)]);
+        Assert.Equal(1, estimate.SampleBatches);
+        Assert.Equal(50m, estimate.RawBytesPerRow);
+        Assert.Null(estimate.FullSecondsLow);
+        Assert.Null(estimate.FullRawBytes);
+    }
+
+    [Fact]
+    public void DistinguishesAnEmptySourceFromMissingSourceStatistics()
+    {
+        var estimate = RelationalCapacityEstimate.FromSamples(0, []);
+        Assert.Equal(0, estimate.FullRawBytes);
+        Assert.Null(estimate.FullSecondsLow);
+    }
+
+    [Fact]
+    public void ObservedRowsTakePrecedenceWhenCatalogStatisticsLag()
+    {
+        RelationalCapacityBatch[] batches = [new(4, 1060, 20, 250, 10, 800, 250)];
+        var allRows = RelationalCapacityEstimate.FromSamples(3, batches, reachedEnd: true);
+        Assert.Equal(4, allRows.SourceRows);
+        Assert.Equal("sample", allRows.SourceRowsBasis);
+        Assert.Equal(1060, allRows.FullRawBytes);
+
+        var incomplete = RelationalCapacityEstimate.FromSamples(3, batches);
+        Assert.Equal(4, incomplete.SourceRows);
+        Assert.Equal("sample-floor", incomplete.SourceRowsBasis);
+    }
+}

+ 23 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpRelationalCatalogTests.cs

@@ -0,0 +1,23 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpRelationalCatalogTests
+{
+    [Fact]
+    public void OnlyCompleteNonNullableUniqueKeysAreRecommended()
+    {
+        var ids = new[] { new RelationalColumn("id", "bigint", false, null, 64, 0, null, null),
+            new RelationalColumn("changed", "timestamp", false, null, null, null, null, null),
+            new RelationalColumn("optional", "varchar", true, 100, null, null, null, null) };
+        var indexes = new[] { new RelationalIndex("pk", true, true, ["id"]),
+            new RelationalIndex("ix", false, false, ["changed", "id"]),
+            new RelationalIndex("uk_nullable", true, false, ["optional"]) };
+        var report = RelationalCatalogAdvice.Analyze(ids, indexes, "changed", "id", 1000, 10, 500, 0.25);
+        Assert.Equal("pk", Assert.Single(report.Keys).Name);
+        Assert.Equal("ix", report.TimeIndex);
+        Assert.Equal(50_000, report.EstimatedRawBytes);
+        Assert.Equal(25, report.EstimatedReadSeconds);
+    }
+}

+ 29 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpRelationalPreflightTests.cs

@@ -0,0 +1,29 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpRelationalPreflightTests
+{
+    [Fact]
+    public void ReadingAndReleaseAreSeparateGates()
+    {
+        var result = RelationalPreflight.Evaluate(new(true, true, false),
+            new("unknown-timezone", "invalid-encoding", "soft-delete", null, "timestamp", "updated_at"),
+            ["rowid"]);
+        Assert.Equal("pass", result.Single(x => x.Code == "read-only").Severity);
+        Assert.Equal("block", result.Single(x => x.Code == "incremental-field").Severity);
+        Assert.Equal("block", result.Single(x => x.Code == "delete-field").Severity);
+        Assert.Equal("block", result.Single(x => x.Code == "time-zone").Severity);
+        Assert.Equal("block", result.Single(x => x.Code == "encoding").Severity);
+    }
+
+    [Fact]
+    public void FullOnlyDeclaresItsBoundary()
+    {
+        var result = RelationalPreflight.Evaluate(new(true, true, false),
+            new("UTC", "utf-8", "unsupported", null, "full", null), ["rowid"]);
+        Assert.DoesNotContain(result, x => x.Severity == "block");
+        Assert.Contains(result, x => x.Code == "delete-policy" && x.Severity == "warning");
+    }
+}

+ 2 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetReleaseController.cs

@@ -198,6 +198,7 @@ public sealed partial class MdpIngestDatasetController
             case "precheck":
                 Require(row.State == "DRAFT", "只有草稿可以预检");
                 await CheckReceiver(dataset, source!, row);
+                await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted);
                 next = "PREFLIGHT";
                 break;
             case "trial":
@@ -257,6 +258,7 @@ public sealed partial class MdpIngestDatasetController
                 Require(approved?.Status == FlowInstanceStatusEnum.Approved &&
                     await HasFactoryApproval(approved.Id, scope), "尚未取得人工审批通过记录");
                 await CheckReceiver(dataset, source!, row);
+                await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted);
                 await Publish(dataset, row);
                 next = "PUBLISHED";
                 break;

+ 108 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetSandbox.Capacity.cs

@@ -0,0 +1,108 @@
+using System.Diagnostics;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Microsoft.Extensions.Configuration;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+internal static partial class MdpDatasetSandbox
+{
+    internal static async Task<object> MeasureCapacityAsync(IConfiguration settings, RelationalConnectorRuntime runtime,
+        ConnectorBinding binding, PurchaseVersionConfiguration configuration, int pageSize,
+        long? sourceRows, CancellationToken token)
+    {
+        var batches = new List<RelationalCapacityBatch>();
+        var isolatedRows = 0;
+        var readMs = 0m;
+        var reachedEnd = false;
+        var clock = Stopwatch.StartNew();
+        using var sandbox = OpenSandbox(settings, token);
+        sandbox.Ado.Open();
+        await CreateSandboxTables(sandbox, token, "mdp_ingest_raw_batch", "mdp_ingest_raw_event",
+            "mdp_stg_purchase_order", "mdp_std_purchase_order");
+        var connectionId = await sandbox.Ado.GetLongAsync("SELECT CONNECTION_ID()");
+        var setupMs = ElapsedMs(clock);
+        var prepare = new IngestBatchPreparer(configuration);
+        string? cursor = null;
+        for (var page = 0; page < 3; page++)
+        {
+            clock.Restart();
+            var read = await runtime.ReadAsync(new(cursor, pageSize), token);
+            var sourceMs = ElapsedMs(clock);
+            readMs += sourceMs;
+            if (read is null)
+            {
+                reachedEnd = true;
+                break;
+            }
+
+            clock.Restart();
+            var payload = read.Batch.Payload.ToArray();
+            var prepared = prepare.Prepare(binding.Identity, binding.SourceSchemaVersion, payload, MdpIngestProtocol.Limits);
+            await sandbox.Ado.BeginTranAsync();
+            try
+            {
+                if (connectionId != await sandbox.Ado.GetLongAsync("SELECT CONNECTION_ID()"))
+                    throw new InvalidOperationException("隔离测算连接已更换,请重新运行");
+                var batch = prepared.Batch;
+                var batchId = batch.BatchId.ToString("D");
+                await MdpIngestReceiveService.PersistRawAsync(sandbox, batch, prepared.Events, payload,
+                    batch.BatchId.ToByteArray(), batch.ReceivedAt, token);
+                var rawMs = ElapsedMs(clock);
+
+                clock.Restart();
+                var result = PurchaseBatchProcessor.Process(prepared, "");
+                var cleanMs = ElapsedMs(clock);
+                var stageRows = new HashSet<long>();
+                var standardRows = new HashSet<long>();
+                var conflicts = 0;
+
+                clock.Restart();
+                foreach (var line in result.Package.Items.OrderBy(line => line.PoNo, StringComparer.Ordinal)
+                    .ThenBy(line => line.PoLine, StringComparer.Ordinal))
+                {
+                    token.ThrowIfCancellationRequested();
+                    var written = await MdpPurchaseHandoffService.WriteLineAsync(sandbox, result.Package, batchId, line);
+                    if (written.Status == "CONFLICT") conflicts++;
+                    if (written.Status != "WRITTEN") continue;
+                    stageRows.Add(written.StageId!.Value);
+                    standardRows.Add(written.StandardId!.Value);
+                }
+                var handoffMs = ElapsedMs(clock);
+
+                clock.Restart();
+                var rawBytes = await sandbox.Ado.GetLongAsync("""
+                    SELECT OCTET_LENGTH(payload) FROM mdp_ingest_raw_batch WHERE batch_id=@batchId
+                    """, new { batchId });
+                var indexed = await sandbox.Ado.GetIntAsync("SELECT COUNT(*) FROM mdp_ingest_raw_event WHERE batch_id=@batchId", new { batchId });
+                var staged = await sandbox.Ado.GetIntAsync("SELECT COUNT(*) FROM mdp_stg_purchase_order WHERE sync_batch_id=@batchId", new { batchId });
+                var standard = await sandbox.Ado.GetIntAsync("SELECT COUNT(*) FROM mdp_std_purchase_order WHERE sync_batch_id=@batchId", new { batchId });
+                if (rawBytes != payload.Length || indexed != prepared.Events.Count || staged != stageRows.Count || standard != standardRows.Count
+                    || result.Package.Items.Count + result.Quarantines.Count != indexed)
+                    throw new InvalidOperationException("隔离测算的批次对账不一致");
+                await sandbox.Ado.CommitTranAsync();
+
+                batches.Add(new(indexed, rawBytes, sourceMs, rawMs, cleanMs, handoffMs, ElapsedMs(clock)));
+                isolatedRows += result.Quarantines.Count + conflicts;
+            }
+            catch
+            {
+                await sandbox.Ado.RollbackTranAsync();
+                throw;
+            }
+            if (!read.HasMore)
+            {
+                reachedEnd = true;
+                break;
+            }
+            cursor = read.Batch.Pending.NextCheckpoint;
+        }
+
+        var estimate = RelationalCapacityEstimate.FromSamples(sourceRows, batches, reachedEnd);
+        return new { estimate, isolatedRows, setupMs, sourceMs = readMs,
+            rawMs = batches.Sum(batch => batch.RawMs), cleanMs = batches.Sum(batch => batch.CleanMs),
+            handoffMs = batches.Sum(batch => batch.HandoffMs), reconcileMs = batches.Sum(batch => batch.ReconcileMs) };
+    }
+
+    private static decimal ElapsedMs(Stopwatch timer) => decimal.Round((decimal)timer.Elapsed.TotalMilliseconds, 3);
+}

+ 31 - 16
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetSandbox.cs

@@ -10,7 +10,7 @@ public sealed record MdpTrialEvidence(Guid BatchId, string Digest, int Received,
     int Staged, decimal StagedQuantity, int Standard, decimal StandardQuantity, bool Matched,
     IReadOnlyList<PurchaseQuarantine> Quarantines, int ExpectedValid, int ExpectedIsolated, decimal ExpectedQuantity);
 
-internal static class MdpDatasetSandbox
+internal static partial class MdpDatasetSandbox
 {
     public static async Task<(MdpTrialEvidence Evidence, PreparedIngestBatch Prepared)> Run(IConfiguration settings, IngestDatasetIdentity scope,
         string version, PurchaseVersionConfiguration config, MdpTrialInput input, CancellationToken token)
@@ -19,22 +19,9 @@ internal static class MdpDatasetSandbox
             throw new ArgumentException("试跑样本不能为空或超过 1 MiB");
         var prepared = new IngestBatchPreparer(config).Prepare(scope, version, Encoding.UTF8.GetBytes(input.Sample), MdpIngestProtocol.Limits);
         var converted = PurchaseBatchProcessor.Process(prepared, "");
-        var connection = settings["MDP_INGEST_SANDBOX_MYSQL"];
-        if (string.IsNullOrWhiteSpace(connection)) throw new InvalidOperationException("请先配置数据中台隔离试跑库");
-        // Disable pooling so temporary relations cannot survive a trial. Business writes start only after both exist.
-        var builder = new MySqlConnectionStringBuilder(connection) { Pooling = false };
-        using var sandbox = new SqlSugarClient(new ConnectionConfig
-        {
-            DbType = SqlSugar.DbType.MySql,
-            ConnectionString = builder.ConnectionString,
-            IsAutoCloseConnection = false
-        });
+        using var sandbox = OpenSandbox(settings, token);
         sandbox.Ado.Open();
-        sandbox.Ado.CancellationToken = token;
-        await sandbox.Ado.ExecuteCommandAsync("CREATE TEMPORARY TABLE trial_stg_template LIKE mdp_stg_purchase_order");
-        await sandbox.Ado.ExecuteCommandAsync("CREATE TEMPORARY TABLE mdp_stg_purchase_order LIKE trial_stg_template");
-        await sandbox.Ado.ExecuteCommandAsync("CREATE TEMPORARY TABLE trial_std_template LIKE mdp_std_purchase_order");
-        await sandbox.Ado.ExecuteCommandAsync("CREATE TEMPORARY TABLE mdp_std_purchase_order LIKE trial_std_template");
+        await CreateSandboxTables(sandbox, token, "mdp_stg_purchase_order", "mdp_std_purchase_order");
         var batchId = prepared.Batch.BatchId.ToString("D");
         foreach (var line in converted.Package.Items)
         {
@@ -59,5 +46,33 @@ internal static class MdpDatasetSandbox
             input.ExpectedValid, input.ExpectedIsolated, input.ExpectedQuantity), prepared);
     }
 
+    private static SqlSugarClient OpenSandbox(IConfiguration settings, CancellationToken token)
+    {
+        token.ThrowIfCancellationRequested();
+        var connection = settings["MDP_INGEST_SANDBOX_MYSQL"];
+        if (string.IsNullOrWhiteSpace(connection)) throw new InvalidOperationException("请先配置数据中台隔离试跑库");
+        // Disable pooling so temporary relations cannot survive a trial. Business writes start only after both exist.
+        var builder = new MySqlConnectionStringBuilder(connection) { Pooling = false };
+        var sandbox = new SqlSugarClient(new ConnectionConfig
+        {
+            DbType = SqlSugar.DbType.MySql,
+            ConnectionString = builder.ConnectionString,
+            IsAutoCloseConnection = false
+        });
+        sandbox.Ado.CancellationToken = token;
+        return sandbox;
+    }
+
+    private static async Task CreateSandboxTables(ISqlSugarClient sandbox, CancellationToken token, params string[] tables)
+    {
+        foreach (var table in tables)
+        {
+            token.ThrowIfCancellationRequested();
+            // Names come from the internal sandbox call sites. The clone shadows the business table for this connection only.
+            await sandbox.Ado.ExecuteCommandAsync($"CREATE TEMPORARY TABLE trial_{table} LIKE {table}");
+            await sandbox.Ado.ExecuteCommandAsync($"CREATE TEMPORARY TABLE {table} LIKE trial_{table}");
+        }
+    }
+
     private sealed class Total { public int RowsWritten { get; set; } public decimal Quantity { get; set; } }
 }

+ 36 - 28
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs

@@ -144,34 +144,7 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
                 reservation.TenantId, reservation.FactoryId, reservation.SourceId, reservation.DatasetId,
                 reservation.KeySha256, ReceivedAt = receivedAt.UtcDateTime
             });
-        await db.Ado.ExecuteCommandAsync(
-            """
-            INSERT INTO mdp_ingest_raw_batch
-                (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key,
-                 payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at)
-            VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey,
-                    @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt)
-            """, new
-            {
-                BatchId = batchId,
-                batch.Identity.TenantId,
-                batch.Identity.FactoryId,
-                batch.Identity.SourceId,
-                batch.Identity.DatasetId,
-                batch.Identity.SourceCode,
-                batch.Identity.DatasetKey,
-                IdempotencyKey = idempotencyKey,
-                submission.Payload,
-                batch.PayloadSha256,
-                AcceptedRecordCount = batch.AcceptedRowCount,
-                SchemaVersion = batch.Versions.SourceSchema.Version,
-                VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions),
-                SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions),
-                ReceivedAt = receivedAt.UtcDateTime
-            });
-
-        cancellationToken.ThrowIfCancellationRequested();
-        await InsertEventsAsync(db, batchId, prepared.Events);
+        await PersistRawAsync(db, batch, prepared.Events, submission.Payload, idempotencyKey, receivedAt, cancellationToken);
 
         // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
         await db.Ado.ExecuteCommandAsync("""
@@ -203,6 +176,41 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
         return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt);
     }
 
+    internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch,
+        IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
+    {
+        token.ThrowIfCancellationRequested();
+        var batchId = batch.BatchId.ToString("D");
+        await db.Ado.ExecuteCommandAsync(
+            """
+            INSERT INTO mdp_ingest_raw_batch
+                (batch_id, tenant_id, factory_id, source_id, dataset_id, source_code, dataset_key, idempotency_key,
+                 payload, payload_sha256, accepted_record_count, source_schema_version, version_snapshot, source_window, received_at)
+            VALUES (@BatchId, @TenantId, @FactoryId, @SourceId, @DatasetId, @SourceCode, @DatasetKey, @IdempotencyKey,
+                    @Payload, @PayloadSha256, @AcceptedRecordCount, @SchemaVersion, @VersionSnapshot, @SourceWindow, @ReceivedAt)
+            """, new
+            {
+                BatchId = batchId,
+                batch.Identity.TenantId,
+                batch.Identity.FactoryId,
+                batch.Identity.SourceId,
+                batch.Identity.DatasetId,
+                batch.Identity.SourceCode,
+                batch.Identity.DatasetKey,
+                IdempotencyKey = idempotencyKey,
+                Payload = payload,
+                batch.PayloadSha256,
+                AcceptedRecordCount = batch.AcceptedRowCount,
+                SchemaVersion = batch.Versions.SourceSchema.Version,
+                VersionSnapshot = JsonSerializer.Serialize(batch.Versions, SnapshotOptions),
+                SourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Serialize(batch.SourceWindow, SnapshotOptions),
+                ReceivedAt = receivedAt.UtcDateTime
+            });
+
+        token.ThrowIfCancellationRequested();
+        await InsertEventsAsync(db, batchId, events);
+    }
+
     private static Task<int> InsertEventsAsync(ISqlSugarClient db, string batchId, IReadOnlyList<RawIngestEvent> events)
     {
         const int parametersPerEvent = 9;

+ 58 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalCapacityController.cs

@@ -0,0 +1,58 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed partial class MdpIngestDatasetController
+{
+    [HttpPost("{id:long}/relational-trials/{profileId}/capacity-sample")]
+    public Task<IActionResult> MeasureRelationalCapacity(long id, string profileId, long? factoryId, CancellationToken token) =>
+        WithScope(factoryId, async scope =>
+        {
+            if (!await Can(TrialPermission)) return Forbid();
+            var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
+            if (dataset is null) return NotFound();
+            using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
+            deadline.CancelAfter(TimeSpan.FromSeconds(35));
+            var work = deadline.Token;
+            try
+            {
+                var profile = (await TrialProfiles(scope, id, work)).SingleOrDefault(p => p.Id == profileId);
+                if (profile is null) return NotFound();
+                var source = await BoundSource(dataset, profile.SourceId);
+                if (source is null || !dataset.Enabled || dataset.ActiveSchemaVersion is null || await Lifecycle(id) != "ACTIVE")
+                    return Conflict(new { message = "请先启用该来源已审批的采购接收版本" });
+
+                var (runtime, binding, configuration) = await CreateRelationalTrial(db, profile, dataset, source);
+                var report = await InspectProfile(profile, binding, work);
+                var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
+                if (blocked is not null) return Conflict(new { message = blocked.Message, code = blocked.Code });
+
+                var sample = await MdpDatasetSandbox.MeasureCapacityAsync(Settings, runtime, binding, configuration,
+                    Math.Clamp(profile.SyncPageSize, 1, 50), report.Advice?.EstimatedRows, work);
+                return Ok(new { sample, history = (object?)null });
+            }
+            catch (OperationCanceledException) when (!token.IsCancellationRequested)
+            {
+                return StatusCode(504, new { message = "估算试跑超时,请核对来源读取和沙箱响应时间" });
+            }
+            catch (MdpIngestHttpException error)
+            {
+                return StatusCode(error.StatusCode, new { message = "估算配置未通过接收校验", code = error.Code });
+            }
+            catch (ConnectorContractException error)
+            {
+                return Conflict(new { message = "来源未通过估算读取检查", code = error.Code.ToString() });
+            }
+            catch (IngestContractException error)
+            {
+                return Conflict(new { message = "估算样本未通过采购接收校验", code = error.Code.ToString() });
+            }
+            catch (Exception error) when (error is System.Data.Common.DbException or SqlSugarException or IOException
+                or System.Text.Json.JsonException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
+            {
+                return StatusCode(503, new { message = "请核对来源与隔离试跑库,或查看样本对账结果" });
+            }
+        });
+}

+ 124 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalSource.cs

@@ -0,0 +1,124 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Http.Json;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
+using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+internal sealed record RelationalTrialProfile(string Id, string Name, long TenantId, long FactoryId, long DatasetId,
+        long SourceId, string Driver, string ConnectionString, string Database, string Schema, string Table,
+        string PositionColumn, string[] Columns, string CredentialFile, string ReceiverBase, string? OdbcFamily,
+        RelationalPreflightOptions? Preflight, bool SyncEnabled = false, int SyncPageSize = 100);
+internal sealed record RelationalTrialKey(string AccessKey, string Secret);
+internal static class MdpRelationalSource
+{
+    internal static readonly JsonSerializerOptions RelationalTrialJson = new(JsonSerializerDefaults.Web);
+    internal static readonly HttpClient RelationalTrialHttp = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false });
+
+    internal static async Task<RelationalTrialProfile[]> ReadProfiles(string? path, CancellationToken token)
+    {
+        if (string.IsNullOrWhiteSpace(path)) return [];
+        using var file = File.OpenRead(path);
+        return await JsonSerializer.DeserializeAsync<RelationalTrialProfile[]>(file, RelationalTrialJson, token) ?? [];
+    }
+
+    internal static async Task<(RelationalConnectorRuntime Runtime, ConnectorBinding Binding, PurchaseVersionConfiguration Configuration)> CreateRelationalTrial(
+        ISqlSugarClient db, RelationalTrialProfile profile, MdpIngestDataset dataset, MdpSource source)
+    {
+        var version = dataset.ActiveSchemaVersion!;
+        var registry = new MdpIngestDatasetRegistry(db);
+        var active = await registry.ResolveActiveBindingAsync(profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey);
+        if (active is null || active.DatasetId != dataset.Id || active.SourceSchemaVersion != version)
+            throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
+        var mapping = await registry.ReadPublishedMapping(active) ?? throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
+        var schemas = new PurchaseVersionConfiguration(dataset.DatasetKey, version, mapping);
+        var contract = schemas.Find(dataset.DatasetKey, version)!;
+        var binding = new ConnectorBinding(new(profile.TenantId, profile.FactoryId, source.Id, dataset.Id,
+            source.SourceCode, dataset.DatasetKey), version, contract.ConfigVersion);
+        var execution = TrialExecution(profile, binding);
+        var manifest = new ConnectorManifest(ConnectorManifest.FormatVersion, profile.Driver, NativeRelationalDriver.Version,
+            ConnectorManifest.SdkVersion, dataset.DatasetKey, version, [ConnectorManifest.CloudDirect], new(profile.Id),
+            new Dictionary<string, ConnectorCapability> { [ConnectorManifest.Database] = new("primary-key", Full: true) },
+            new("configured-trial", "trial", []));
+        return (new RelationalConnectorRuntime([TrialDriver(profile, execution)], manifest, execution, schemas), binding, schemas);
+    }
+
+    internal static ConnectorExecution TrialExecution(RelationalTrialProfile profile, ConnectorBinding binding) =>
+        new(binding, profile.Driver, NativeRelationalDriver.Version, ConnectorManifest.CloudDirect, ConnectorManifest.Database);
+
+    internal static IRelationalSourceDriver TrialDriver(RelationalTrialProfile profile, ConnectorExecution execution)
+    {
+        var sourceMapping = new RelationalSourceMapping(execution, profile.Id, profile.Database, profile.Schema, profile.Table,
+            profile.PositionColumn, profile.Columns)
+        { IncludeFactoryInEnvelope = true };
+        Task<string> Resolve(ConnectorBinding _, string __, CancellationToken ___) => Task.FromResult(profile.ConnectionString);
+        return profile.Driver == OdbcRelationalDriver.Id
+            ? new OdbcRelationalDriver(sourceMapping, profile.OdbcFamily ?? "", Resolve)
+            : new NativeRelationalDriver(sourceMapping, Resolve);
+    }
+
+    internal static async Task<RelationalInspection> InspectProfile(RelationalTrialProfile profile, ConnectorBinding binding, CancellationToken token, string? objectName = null)
+    {
+        var execution = TrialExecution(profile, binding);
+        var driver = TrialDriver(profile, execution);
+        await using var session = await driver.OpenReadOnlyAsync(execution, profile.Id, token);
+        if (session is not IRelationalSourceInspection inspection)
+            throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+        return await inspection.InspectAsync(profile.Preflight ?? new(null, null, "unsupported", null, "full", null), token, objectName);
+    }
+
+    internal static async Task<(Uri Address, RelationalTrialKey Key)> LoadRelationalReceiver(
+        ISqlSugarClient db, RelationalTrialProfile profile, MdpIngestDataset dataset, CancellationToken token)
+    {
+        if (!Uri.TryCreate(profile.ReceiverBase, UriKind.Absolute, out var address)
+            || !IPAddress.TryParse(address.Host, out var ip) || !IPAddress.IsLoopback(ip)
+            || address.Scheme is not ("http" or "https") || !string.IsNullOrEmpty(address.UserInfo)
+            || address.AbsolutePath != "/" || !string.IsNullOrEmpty(address.Query) || !string.IsNullOrEmpty(address.Fragment))
+            throw new ArgumentException("Receipt host must be a loopback origin.");
+
+        using var credFile = System.IO.File.OpenRead(profile.CredentialFile);
+        var key = await JsonSerializer.DeserializeAsync<RelationalTrialKey>(credFile, RelationalTrialJson, token)
+            ?? throw new ArgumentException("Missing receipt credentials.");
+        var hash = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(key.AccessKey))).ToLowerInvariant();
+        var authorized = await db.Ado.GetIntAsync("""
+            SELECT COUNT(*) FROM mdp_ingest_access_grant
+            WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId
+                AND dataset_key=@DatasetKey AND access_key_hash=@hash AND use_batch_factory=1 AND enabled=1
+            """, new { profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey, hash });
+        if (authorized != 1) throw new MdpIngestHttpException(409, "TRIAL_GRANT_MISMATCH");
+        return (address, key);
+    }
+
+    internal static async Task<MdpIngestReceipt> SubmitRelationalTrial(Uri address, string datasetKey,
+        ConnectorFrozenBatch batch, RelationalTrialKey key, CancellationToken token)
+    {
+        var endpoint = new Uri(address, "/api/v1/ingest/" + Uri.EscapeDataString(datasetKey));
+        var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
+        var nonce = Guid.NewGuid().ToString("N");
+        var id = batch.Pending.Id;
+        var canonical = string.Join('&', "POST", endpoint.AbsolutePath, key.AccessKey, timestamp, nonce, id.PayloadSha256, id.IdempotencyKey);
+        var bytes = Convert.FromBase64String(key.Secret);
+        string signature;
+        try { signature = Convert.ToBase64String(HMACSHA256.HashData(bytes, Encoding.UTF8.GetBytes(canonical))); }
+        finally { CryptographicOperations.ZeroMemory(bytes); }
+        using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new ByteArrayContent(batch.Payload.ToArray()) };
+        request.Content.Headers.ContentType = new("application/json");
+        request.Headers.Add("X-Access-Key", key.AccessKey);
+        request.Headers.Add("X-Timestamp", timestamp);
+        request.Headers.Add("X-Nonce", nonce);
+        request.Headers.Add("X-Signature", signature);
+        request.Headers.Add("X-Content-SHA256", id.PayloadSha256);
+        request.Headers.Add("Idempotency-Key", id.IdempotencyKey);
+        using var response = await RelationalTrialHttp.SendAsync(request, token);
+        if (response.StatusCode != HttpStatusCode.Accepted)
+            throw new MdpIngestHttpException(response.IsSuccessStatusCode ? 502 : (int)response.StatusCode, "INGEST_NOT_CONFIRMED");
+        return await response.Content.ReadFromJsonAsync<MdpIngestReceipt>(RelationalTrialJson, token)
+            ?? throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
+    }
+}

+ 93 - 79
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpRelationalTrialController.cs

@@ -1,3 +1,4 @@
+using static Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress.MdpRelationalSource;
 using System.Globalization;
 using System.Net;
 using System.Net.Http.Json;
@@ -13,23 +14,11 @@ namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
 
 public sealed partial class MdpIngestDatasetController
 {
-    private sealed record RelationalTrialProfile(string Id, string Name, long TenantId, long FactoryId, long DatasetId,
-        long SourceId, string Driver, string ConnectionString, string Database, string Schema, string Table,
-        string PositionColumn, string[] Columns, string CredentialFile, string ReceiverBase);
-    private sealed record RelationalTrialKey(string AccessKey, string Secret);
-    private static readonly JsonSerializerOptions RelationalTrialJson = new(JsonSerializerDefaults.Web);
-    private static readonly HttpClient RelationalTrialHttp = new(new HttpClientHandler { AllowAutoRedirect = false, UseProxy = false });
     private const int RelationalTrialPages = 5;
 
-    private async Task<RelationalTrialProfile[]> TrialProfiles(DatasetScope scope, long id, CancellationToken token)
-    {
-        var path = Settings["MDP_RELATIONAL_TRIALS_FILE"];
-        if (string.IsNullOrWhiteSpace(path)) return [];
-        using var file = System.IO.File.OpenRead(path);
-        var profiles = await JsonSerializer.DeserializeAsync<RelationalTrialProfile[]>(file, RelationalTrialJson, token) ?? [];
-        return profiles.Where(profile => profile.TenantId == scope.TenantId && profile.FactoryId == scope.FactoryId
-            && profile.DatasetId == id).ToArray();
-    }
+    private async Task<RelationalTrialProfile[]> TrialProfiles(DatasetScope scope, long id, CancellationToken token) =>
+        (await ReadProfiles(Settings["MDP_RELATIONAL_TRIALS_FILE"], token)).Where(profile =>
+            profile.TenantId == scope.TenantId && profile.FactoryId == scope.FactoryId && profile.DatasetId == id).ToArray();
 
     [HttpGet("{id:long}/relational-trials")]
     public Task<IActionResult> ListRelationalTrials(long id, long? factoryId, CancellationToken token) =>
@@ -47,8 +36,48 @@ public sealed partial class MdpIngestDatasetController
             }
         });
 
+    [HttpGet("{id:long}/relational-trials/{profileId}/probe")]
+    public Task<IActionResult> ProbeRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) =>
+        ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: true, token);
+
+    [HttpGet("{id:long}/relational-trials/{profileId}/catalog")]
+    public Task<IActionResult> InspectRelationalTrial(long id, string profileId, long? factoryId, string? objectName, CancellationToken token) =>
+        WithScope(factoryId, async scope =>
+        {
+            if (!await Can(TrialPermission)) return Forbid();
+            var dataset = await Datasets(scope).FirstAsync(d => d.Id == id);
+            if (dataset is null) return NotFound();
+            try
+            {
+                var profile = (await TrialProfiles(scope, id, token)).SingleOrDefault(p => p.Id == profileId);
+                if (profile is null) return NotFound();
+                var source = await BoundSource(dataset, profile.SourceId);
+                if (source is null) return NotFound();
+                var binding = new ConnectorBinding(new(scope.TenantId, scope.FactoryId, source.Id, id,
+                    source.SourceCode, dataset.DatasetKey), dataset.ActiveSchemaVersion ?? "draft",
+                    dataset.Revision.ToString(CultureInfo.InvariantCulture));
+                using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
+                deadline.CancelAfter(TimeSpan.FromSeconds(20));
+                var report = await InspectProfile(profile, binding, deadline.Token, objectName);
+                return Ok(new { dataset.Revision, report, canMeasureCapacity = string.IsNullOrWhiteSpace(objectName) || string.Equals(objectName, profile.Table, StringComparison.Ordinal) });
+            }
+            catch (OperationCanceledException) when (!token.IsCancellationRequested)
+            {
+                return StatusCode(504, new { message = "来源预检超时" });
+            }
+            catch (Exception error) when (error is ConnectorContractException or System.Data.Common.DbException or
+                IOException or JsonException or ArgumentException or InvalidOperationException or UnauthorizedAccessException)
+            {
+                return StatusCode(503, new { message = "请核对来源配置、连通性或只读授权" });
+            }
+        });
+
     [HttpPost("{id:long}/relational-trials/{profileId}")]
     public Task<IActionResult> RunRelationalTrial(long id, string profileId, long? factoryId, CancellationToken token) =>
+        ExecuteRelationalTrial(id, profileId, factoryId, probeOnly: false, token);
+
+    private Task<IActionResult> ExecuteRelationalTrial(long id, string profileId, long? factoryId, bool probeOnly,
+        CancellationToken token) =>
         WithScope(factoryId, async scope =>
         {
             if (!await Can(TrialPermission)) return Forbid();
@@ -63,10 +92,30 @@ public sealed partial class MdpIngestDatasetController
                     return Conflict(new { message = "请先启用已绑定来源的采购接收版本" });
                 using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
                 deadline.CancelAfter(TimeSpan.FromSeconds(25));
-                return Ok(await ReadRelationalTrial(profile, dataset, source, deadline.Token));
+                var (runtime, binding, _) = await CreateRelationalTrial(db, profile, dataset, source);
+                var probe = await runtime.ProbeAsync(deadline.Token);
+                if (probeOnly) return Ok(probe);
+                if (!probe.Supported)
+                    return Conflict(new { message = "数据库读取能力未通过检查", code = "UnsupportedCapability", probe.Reason });
+                if (profile.Preflight is not null || profile.SyncEnabled)
+                {
+                    var report = await InspectProfile(profile, binding, deadline.Token);
+                    var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
+                    if (blocked is not null)
+                        return Conflict(new { message = blocked.Message, code = blocked.Code });
+                }
+                return Ok(await ReadRelationalTrial(profile, dataset, runtime, binding, deadline.Token));
             }
             catch (ConnectorContractException error)
             {
+                if (probeOnly && error.Code is ConnectorError.SourceUnavailable or ConnectorError.ScopeMismatch
+                    or ConnectorError.InvalidManifest or ConnectorError.UnsupportedCapability or ConnectorError.UnsupportedVersion)
+                    return Ok(new ConnectorProbeResult(false, error.Code switch
+                    {
+                        ConnectorError.SourceUnavailable => "source-unavailable",
+                        ConnectorError.ScopeMismatch => "database-scope-mismatch",
+                        _ => "driver-configuration-invalid",
+                    }));
                 return Conflict(new { message = "数据库连接器校验失败", code = error.Code.ToString() });
             }
             catch (MdpIngestHttpException error)
@@ -83,45 +132,36 @@ public sealed partial class MdpIngestDatasetController
             }
         });
 
-    private async Task<object> ReadRelationalTrial(RelationalTrialProfile profile, MdpIngestDataset dataset, MdpSource source, CancellationToken token)
+    private async Task CheckConfiguredSourcePreflight(MdpIngestDataset dataset, MdpSource source, Release candidate, CancellationToken token)
     {
-        if (!Uri.TryCreate(profile.ReceiverBase, UriKind.Absolute, out var address)
-            || !IPAddress.TryParse(address.Host, out var ip) || !IPAddress.IsLoopback(ip)
-            || address.Scheme is not ("http" or "https") || !string.IsNullOrEmpty(address.UserInfo)
-            || address.AbsolutePath != "/" || !string.IsNullOrEmpty(address.Query) || !string.IsNullOrEmpty(address.Fragment))
-            throw new ArgumentException("Receipt host must be a loopback origin.");
-        var version = dataset.ActiveSchemaVersion!;
-        var registry = new MdpIngestDatasetRegistry(db);
-        var active = await registry.ResolveActiveBindingAsync(profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey);
-        if (active is null || active.DatasetId != dataset.Id || active.SourceSchemaVersion != version)
-            throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
-        var mapping = await registry.ReadPublishedMapping(active) ?? throw new MdpIngestHttpException(409, "DATASET_UNAVAILABLE");
-        var schemas = new PurchaseVersionConfiguration(dataset.DatasetKey, version, mapping);
-        var contract = schemas.Find(dataset.DatasetKey, version)!;
-        var binding = new ConnectorBinding(new(profile.TenantId, profile.FactoryId, source.Id, dataset.Id,
-            source.SourceCode, dataset.DatasetKey), version, contract.ConfigVersion);
-        var execution = new ConnectorExecution(binding, profile.Driver, NativeRelationalDriver.Version, ConnectorManifest.CloudDirect, ConnectorManifest.Database);
-        var manifest = new ConnectorManifest(ConnectorManifest.FormatVersion, profile.Driver, NativeRelationalDriver.Version,
-            ConnectorManifest.SdkVersion, dataset.DatasetKey, version, [ConnectorManifest.CloudDirect], new(profile.Id),
-            new Dictionary<string, ConnectorCapability> { [ConnectorManifest.Database] = new("primary-key", Full: true) },
-            new("configured-trial", "trial", []));
-        var sourceMapping = new RelationalSourceMapping(execution, profile.Id, profile.Database, profile.Schema, profile.Table,
-            profile.PositionColumn, profile.Columns) { IncludeFactoryInEnvelope = true };
-        var driver = new NativeRelationalDriver(sourceMapping, (_, _, _) => Task.FromResult(profile.ConnectionString));
-        var runtime = new RelationalConnectorRuntime([driver], manifest, execution, schemas);
-        var probe = await runtime.ProbeAsync(token);
-        if (!probe.Supported) throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+        var scope = new DatasetScope(dataset.TenantId, dataset.FactoryId, "");
+        var profiles = (await TrialProfiles(scope, dataset.Id, token))
+            .Where(p => p.SourceId == source.Id && (p.SyncEnabled || p.Preflight is not null)).ToArray();
+        if (profiles.Length == 0) return;
+        using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
+        deadline.CancelAfter(TimeSpan.FromSeconds(20));
+        var binding = new ConnectorBinding(new(dataset.TenantId, dataset.FactoryId, source.Id, dataset.Id,
+            source.SourceCode, dataset.DatasetKey), candidate.Version, dataset.Revision.ToString(CultureInfo.InvariantCulture));
+        try
+        {
+            foreach (var profile in profiles)
+            {
+                var report = await InspectProfile(profile, binding, deadline.Token);
+                var blocked = report.Checks.FirstOrDefault(check => check.Severity == "block");
+                Require(blocked is null, blocked?.Message ?? "来源预检通过");
+            }
+        }
+        catch (Exception error) when (!token.IsCancellationRequested && error is System.Data.Common.DbException or ConnectorContractException or OperationCanceledException)
+        {
+            Require(false, "数据库来源预检未通过,请核对连通性、驱动与只读授权");
+        }
+    }
 
-        using var credFile = System.IO.File.OpenRead(profile.CredentialFile);
-        var key = await JsonSerializer.DeserializeAsync<RelationalTrialKey>(credFile, RelationalTrialJson, token)
-            ?? throw new ArgumentException("Missing receipt credentials.");
-        var hash = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(key.AccessKey))).ToLowerInvariant();
-        var authorized = await db.Ado.GetIntAsync("""
-            SELECT COUNT(*) FROM mdp_ingest_access_grant
-            WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_id=@SourceId
-                AND dataset_key=@DatasetKey AND access_key_hash=@hash AND use_batch_factory=1 AND enabled=1
-            """, new { profile.TenantId, profile.FactoryId, profile.SourceId, dataset.DatasetKey, hash });
-        if (authorized != 1) throw new MdpIngestHttpException(409, "TRIAL_GRANT_MISMATCH");
+    private async Task<object> ReadRelationalTrial(RelationalTrialProfile profile, MdpIngestDataset dataset,
+        RelationalConnectorRuntime runtime, ConnectorBinding binding, CancellationToken token)
+    {
+        var (address, key) = await LoadRelationalReceiver(db, profile, dataset, token);
+        var version = binding.SourceSchemaVersion;
         string? position = null;
         var receipts = new List<MdpIngestReceipt>();
         var complete = false;
@@ -150,30 +190,4 @@ public sealed partial class MdpIngestDatasetController
         return new { profile.Driver, position, complete, receipts };
     }
 
-    private static async Task<MdpIngestReceipt> SubmitRelationalTrial(Uri address, string datasetKey,
-        ConnectorFrozenBatch batch, RelationalTrialKey key, CancellationToken token)
-    {
-        var endpoint = new Uri(address, "/api/v1/ingest/" + Uri.EscapeDataString(datasetKey));
-        var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
-        var nonce = Guid.NewGuid().ToString("N");
-        var id = batch.Pending.Id;
-        var canonical = string.Join('&', "POST", endpoint.AbsolutePath, key.AccessKey, timestamp, nonce, id.PayloadSha256, id.IdempotencyKey);
-        var bytes = Convert.FromBase64String(key.Secret);
-        string signature;
-        try { signature = Convert.ToBase64String(HMACSHA256.HashData(bytes, Encoding.UTF8.GetBytes(canonical))); }
-        finally { CryptographicOperations.ZeroMemory(bytes); }
-        using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new ByteArrayContent(batch.Payload.ToArray()) };
-        request.Content.Headers.ContentType = new("application/json");
-        request.Headers.Add("X-Access-Key", key.AccessKey);
-        request.Headers.Add("X-Timestamp", timestamp);
-        request.Headers.Add("X-Nonce", nonce);
-        request.Headers.Add("X-Signature", signature);
-        request.Headers.Add("X-Content-SHA256", id.PayloadSha256);
-        request.Headers.Add("Idempotency-Key", id.IdempotencyKey);
-        using var response = await RelationalTrialHttp.SendAsync(request, token);
-        if (response.StatusCode != HttpStatusCode.Accepted)
-            throw new MdpIngestHttpException(response.IsSuccessStatusCode ? 502 : (int)response.StatusCode, "INGEST_NOT_CONFIRMED");
-        return await response.Content.ReadFromJsonAsync<MdpIngestReceipt>(RelationalTrialJson, token)
-            ?? throw new MdpIngestHttpException(502, "INVALID_RECEIPT");
-    }
 }