Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(import): default to position mapping when names do not match

lxk955bcf5313f3c0a
diff --git a/apps/desktop/src/components/import/TableImportDialog.vue b/apps/desktop/src/components/import/TableImportDialog.vue
index a7fee97c32..f462c24adf 100644
--- a/apps/desktop/src/components/import/TableImportDialog.vue
+++ b/apps/desktop/src/components/import/TableImportDialog.vue
@@ -547,7 +547,7 @@ function applyAutoMapping() {
return;
}
const headerless = titleRow.value === 0 && (isDelimitedFormat(sourceFormat.value) || sourceFormat.value === "excel");
- columnMapping.value = autoMapImportColumns(currentPreview.columns, targetColumnNames.value, headerless ? "position" : "name");
+ columnMapping.value = autoMapImportColumns(currentPreview.columns, targetColumnNames.value, headerless ? "position" : "auto");
}
function applySuggestedColumnDataTypes(currentPreview = preview.value) {
@@ -942,6 +942,24 @@ function updateMapping(sourceColumn: string, value: any) {
};
}
+function mapByPosition() {
+ const currentPreview = preview.value;
+ if (!currentPreview) return;
+ columnMapping.value = autoMapImportColumns(currentPreview.columns, targetColumnNames.value, "position");
+}
+
+function mapByName() {
+ const currentPreview = preview.value;
+ if (!currentPreview) return;
+ columnMapping.value = autoMapImportColumns(currentPreview.columns, targetColumnNames.value, "name");
+}
+
+function skipAllColumns() {
+ const currentPreview = preview.value;
+ if (!currentPreview) return;
+ columnMapping.value = Object.fromEntries(currentPreview.columns.map((source) => [source, ""]));
+}
+
function updateColumnDataType(sourceColumn: string, value: any) {
columnDataTypes.value = {
...columnDataTypes.value,
@@ -1294,13 +1312,23 @@ watch(
minimized.value = false;
backgroundMode.value = false;
dialogDragOffset.value = { x: 0, y: 0 };
+ if (previewReloadTimer) {
+ clearTimeout(previewReloadTimer);
+ previewReloadTimer = null;
+ }
if (!running.value) void releaseTableImportSources();
}
},
{ immediate: true },
);
-onBeforeUnmount(stopDialogDrag);
+onBeforeUnmount(() => {
+ stopDialogDrag();
+ if (previewReloadTimer) {
+ clearTimeout(previewReloadTimer);
+ previewReloadTimer = null;
+ }
+});
watch([sourceFormat, delimiter, titleRow, dataStartRow, lastDataRow, trimValues, emptyStringAsNull, selectedSheet, jsonShape, previewLimit], schedulePreviewReload);
watch([textEncoding, decimalSeparator], schedulePreviewReloadAfterEncodingChange);
@@ -1706,9 +1734,24 @@ watch(rawProgressPercent, (percent) => {
</div>
</div>
- <div v-if="preview" class="grid gap-3" :class="targetMode === 'create' ? 'grid-cols-[minmax(360px,460px)_1fr]' : 'grid-cols-[minmax(240px,300px)_1fr]'">
+ <div v-if="preview" class="grid gap-3" :class="targetMode === 'create' ? 'grid-cols-[minmax(360px,460px)_1fr]' : 'grid-cols-[minmax(280px,360px)_1fr]'">
<div class="rounded-md border">
- <div class="border-b px-3 py-2 text-xs font-medium">{{ t("tableImport.mapping") }}</div>
+ <div class="flex items-center justify-between border-b px-3 py-1.5 text-xs font-medium">
+ <span>{{ t("tableImport.mapping") }}</span>
+ <div v-if="targetMode === 'existing'" class="flex items-center gap-1.5 font-normal">
+ <button type="button" data-action="map-by-position" class="text-xs text-muted-foreground hover:text-foreground hover:underline" @click="mapByPosition">
+ {{ t("tableImport.mapByPosition") }}
+ </button>
+ <span class="text-muted-foreground/40">·</span>
+ <button type="button" data-action="map-by-name" class="text-xs text-muted-foreground hover:text-foreground hover:underline" @click="mapByName">
+ {{ t("tableImport.mapByName") }}
+ </button>
+ <span class="text-muted-foreground/40">·</span>
+ <button type="button" data-action="skip-all" class="text-xs text-muted-foreground hover:text-foreground hover:underline" @click="skipAllColumns">
+ {{ t("tableImport.skipAll") }}
+ </button>
+ </div>
+ </div>
<div class="max-h-[320px] overflow-auto p-2">
<div class="grid items-center gap-2 border-b px-1 pb-1 text-[11px] font-medium text-muted-foreground" :class="targetMode === 'create' ? 'grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(92px,120px)]' : 'grid-cols-[1fr_1fr]'">
<span>{{ t("tableImport.sourceColumn") }}</span>
diff --git a/apps/desktop/src/components/import/__tests__/TableImportDialog.existingTarget.spec.ts b/apps/desktop/src/components/import/__tests__/TableImportDialog.existingTarget.spec.ts
index 7186fa018c..047a35fa0c 100644
--- a/apps/desktop/src/components/import/__tests__/TableImportDialog.existingTarget.spec.ts
+++ b/apps/desktop/src/components/import/__tests__/TableImportDialog.existingTarget.spec.ts
@@ -578,4 +578,49 @@ describe("TableImportDialog existing targets", () => {
expect(document.body.textContent).toContain("SQLite / main / existing_target");
expect(document.body.textContent).not.toContain("main / main");
});
+
+ it("defaults to position mapping when source column names do not match target table columns, and supports mapping actions", async () => {
+ i18n.global.locale.value = "en";
+ mocks.previewTableImportFile.mockResolvedValue({
+ fileName: "unmatched.csv",
+ filePath: "/tmp/unmatched.csv",
+ fileType: "csv",
+ sizeBytes: 24,
+ columns: ["col_1", "col_2"],
+ rows: [["1", "Alice"]],
+ totalRows: 1,
+ sourceFingerprint: "unmatched",
+ });
+
+ await mountDialog({ prefillTable: "existing_target" });
+ await selectWorkbook("unmatched.csv");
+ await vi.waitFor(() => expect(buttonContaining("Next")?.disabled).toBe(false));
+
+ buttonContaining("Next")?.click();
+ await flushAsyncUpdates();
+
+ const selects = [...document.body.querySelectorAll<HTMLSelectElement>("select")];
+ expect(selects.map((s) => s.value)).toEqual(["id", "name"]);
+
+ const skipAllBtn = document.body.querySelector<HTMLButtonElement>('button[data-action="skip-all"]');
+ expect(skipAllBtn).toBeTruthy();
+ skipAllBtn?.click();
+ await flushAsyncUpdates();
+ const skippedSelects = [...document.body.querySelectorAll<HTMLSelectElement>("select")];
+ expect(skippedSelects.map((s) => s.value)).toEqual(["__skip__", "__skip__"]);
+
+ const mapByPositionBtn = document.body.querySelector<HTMLButtonElement>('button[data-action="map-by-position"]');
+ expect(mapByPositionBtn).toBeTruthy();
+ mapByPositionBtn?.click();
+ await flushAsyncUpdates();
+ const positionSelects = [...document.body.querySelectorAll<HTMLSelectElement>("select")];
+ expect(positionSelects.map((s) => s.value)).toEqual(["id", "name"]);
+
+ const mapByNameBtn = document.body.querySelector<HTMLButtonElement>('button[data-action="map-by-name"]');
+ expect(mapByNameBtn).toBeTruthy();
+ mapByNameBtn?.click();
+ await flushAsyncUpdates();
+ const nameSelects = [...document.body.querySelectorAll<HTMLSelectElement>("select")];
+ expect(nameSelects.map((s) => s.value)).toEqual(["__skip__", "__skip__"]);
+ });
});
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 5912f48d6b..660d49f0d1 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -7128,6 +7128,9 @@ export default {
targetDataType: "Type",
createColumns: "Columns to create",
skipColumn: "Skip",
+ mapByPosition: "Map by Position",
+ mapByName: "Map by Name",
+ skipAll: "Skip All",
preview: "Preview",
mode: "Import mode",
append: "Append data",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 8b71c8c3f3..281abf103d 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -6516,6 +6516,9 @@ export default withEnglishFallback({
targetColumnsTimeout: "Se agotó el tiempo de espera al cargar los campos de la tabla de destino. Compruebe la conexión e inténtelo de nuevo.",
retry: "Reintentar",
decimalSeparator: "Separador decimal",
+ mapByPosition: "Asignar por posición",
+ mapByName: "Asignar por nombre",
+ skipAll: "Omitir todo",
},
dataGenerate: {
title: "Generación de datos",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 39901ed28b..d413469aee 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -6308,6 +6308,9 @@ export default withEnglishFallback({
targetColumnsTimeout: "Timeout nel caricamento dei campi della tabella di destinazione. Controlla la connessione e riprova.",
retry: "Riprova",
decimalSeparator: "Separatore decimale",
+ mapByPosition: "Mappa per posizione",
+ mapByName: "Mappa per nome",
+ skipAll: "Salta tutto",
},
dataGenerate: {
title: "Generazione dati",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 44a350a903..f69d9f757b 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -6338,6 +6338,9 @@ export default withEnglishFallback({
targetColumnsTimeout: "ターゲットテーブルのフィールド読み込みがタイムアウトしました。接続を確認して再試行してください。",
retry: "再試行",
decimalSeparator: "小数点記号",
+ mapByPosition: "順番にマッピング",
+ mapByName: "名前でマッピング",
+ skipAll: "すべてスキップ",
},
dataGenerate: {
title: "データ生成",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 0a23b23f70..98fe929688 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -6105,6 +6105,9 @@ export default withEnglishFallback({
targetColumnsTimeout: "대상 테이블 필드를 로드하는 시간이 초과되었습니다. 연결을 확인한 후 다시 시도하십시오.",
retry: "재시도",
decimalSeparator: "소수점 구분 기호",
+ mapByPosition: "순서대로 매핑",
+ mapByName: "이름으로 매핑",
+ skipAll: "모두 건너뛰기",
},
dataGenerate: {
title: "데이터 생성",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 155396b962..b661dfb4ac 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -6309,6 +6309,9 @@ export default withEnglishFallback({
targetColumnsTimeout: "Tempo esgotado ao carregar os campos da tabela de destino. Verifique a conexão e tente novamente.",
retry: "Tentar novamente",
decimalSeparator: "Separador decimal",
+ mapByPosition: "Mapear por posição",
+ mapByName: "Mapear por nome",
+ skipAll: "Ignorar tudo",
},
dataGenerate: {
title: "Geração de dados",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index a2f7875e37..ed35ef4642 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -7497,6 +7497,9 @@ export default withEnglishFallback({
status_done: "Импорт завершён",
status_error: "Импорт не выполнен",
status_cancelled: "Импорт отменён",
+ mapByPosition: "Сопоставление по порядку",
+ mapByName: "Сопоставление по имени",
+ skipAll: "Пропустить все",
},
dataGenerate: {
title: "Генерация данных",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 7032ac4d47..b2dfbca831 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -7114,6 +7114,9 @@ export default withEnglishFallback({
targetDataType: "目标类型",
createColumns: "将创建的字段",
skipColumn: "跳过",
+ mapByPosition: "按顺序映射",
+ mapByName: "按名称映射",
+ skipAll: "全部跳过",
preview: "预览",
mode: "导入模式",
append: "追加数据",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 4aba5c56ef..e4273e31d6 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -5629,6 +5629,9 @@ export default withEnglishFallback({
targetDataType: "目標類型",
createColumns: "將建立的欄位",
skipColumn: "跳過",
+ mapByPosition: "依順序映射",
+ mapByName: "依名稱映射",
+ skipAll: "全部跳過",
preview: "預覽",
mode: "匯入模式",
append: "追加資料",
diff --git a/apps/desktop/src/lib/__tests__/table/tableImport.spec.ts b/apps/desktop/src/lib/__tests__/table/tableImport.spec.ts
index 2a1ed8b740..55492d5cae 100644
--- a/apps/desktop/src/lib/__tests__/table/tableImport.spec.ts
+++ b/apps/desktop/src/lib/__tests__/table/tableImport.spec.ts
@@ -99,6 +99,21 @@ describe("tableImport", () => {
expect(autoMapImportColumns(["column_1", "column_2"], ["column_2", "column_1"], "position")).toEqual({ column_1: "column_2", column_2: "column_1" });
});
+ it("falls back to position mapping in auto mode when no column names match", () => {
+ expect(autoMapImportColumns(["col_a", "col_b", "col_c"], ["id", "name"])).toEqual({
+ col_a: "id",
+ col_b: "name",
+ col_c: "",
+ });
+ });
+
+ it("keeps name-only matches when explicitly using name mode", () => {
+ expect(autoMapImportColumns(["col_a", "col_b"], ["id", "name"], "name")).toEqual({
+ col_a: "",
+ col_b: "",
+ });
+ });
+
it("skips excess source columns and leaves excess target columns unmapped", () => {
expect(autoMapImportColumns(["column_1", "column_2", "column_3"], ["id", "name"], "position")).toEqual({ column_1: "id", column_2: "name", column_3: "" });
expect(autoMapImportColumns(["column_1"], ["id", "name"], "position")).toEqual({ column_1: "id" });
diff --git a/apps/desktop/src/lib/table/tableImport.ts b/apps/desktop/src/lib/table/tableImport.ts
index e2be4036f9..3d92da2f91 100644
--- a/apps/desktop/src/lib/table/tableImport.ts
+++ b/apps/desktop/src/lib/table/tableImport.ts
@@ -136,14 +136,22 @@ export function normalizeImportColumnName(name: string): string {
return name.trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ");
}
-export function autoMapImportColumns(sourceColumns: string[], targetColumns: string[], mode: "name" | "position" = "name"): Record<string, string> {
+export function autoMapImportColumns(sourceColumns: string[], targetColumns: string[], mode: "name" | "position" | "auto" = "auto"): Record<string, string> {
if (mode === "position") {
return Object.fromEntries(sourceColumns.map((source, index) => [source, targetColumns[index] ?? IMPORT_SKIP_TARGET]));
}
const exactTargets = new Map(targetColumns.map((column) => [column, column]));
const normalizedTargets = new Map(targetColumns.map((column) => [normalizeImportColumnName(column), column]));
- return Object.fromEntries(sourceColumns.map((source) => [source, exactTargets.get(source) ?? normalizedTargets.get(normalizeImportColumnName(source)) ?? IMPORT_SKIP_TARGET]));
+ const byName = Object.fromEntries(sourceColumns.map((source) => [source, exactTargets.get(source) ?? normalizedTargets.get(normalizeImportColumnName(source)) ?? IMPORT_SKIP_TARGET]));
+ if (mode === "auto") {
+ const hasAnyMatched = Object.values(byName).some((target) => target !== IMPORT_SKIP_TARGET);
+ if (!hasAnyMatched && targetColumns.length > 0) {
+ return Object.fromEntries(sourceColumns.map((source, index) => [source, targetColumns[index] ?? IMPORT_SKIP_TARGET]));
+ }
+ }
+
+ return byName;
}
export function validateImportMappings(mappings: ImportColumnMappingLike[]): ImportMappingValidationResult {