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(transfer): add tree-based object selection

GIWTO473ef910b601
diff --git a/apps/desktop/src/components/transfer/DataTransferDialog.vue b/apps/desktop/src/components/transfer/DataTransferDialog.vue
index e01a2bae4c..131d304e51 100644
--- a/apps/desktop/src/components/transfer/DataTransferDialog.vue
+++ b/apps/desktop/src/components/transfer/DataTransferDialog.vue
@@ -4,6 +4,7 @@ import { uuid } from "@/lib/common/utils";
import { useI18n } from "vue-i18n";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
+import { buildTransferObjectSelections } from "./transferSelections";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -13,7 +14,9 @@ import { useConnectionStore } from "@/stores/connectionStore";
import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";
import { connectionIconType } from "@/lib/connection/connectionPresentation";
import * as api from "@/lib/backend/api";
-import type { TransferMode, TransferTableNameCase } from "@/lib/backend/api";
+import type { TransferContent, TransferMode, TransferObjectKind, TransferTableNameCase } from "@/lib/backend/api";
+import { crossFamilyTransferableKinds, isSameTransferFamily, transferObjectKindsForDatabase } from "@/lib/database/transferObjectKinds";
+import ObjectSelectionTree from "@/components/transfer/ObjectSelectionTree.vue";
import type { DatabaseType } from "@/types/database";
import { isSchemaAware, supportsTransfer } from "@/lib/database/databaseCapabilities";
import { isDorisFamilyCatalogCapable } from "@/lib/database/databaseFeatureSupport";
@@ -21,7 +24,7 @@ import { isSameTransferDatabase, normalizeTransferCatalog } from "@/lib/database
import { databaseOptionsForConnection, fetchCatalogNamespaceOptions, fetchNamespaceOptionsForConnection, namespaceOptionsAreSchemas } from "@/composables/useDatabaseOptions";
import { useExportTracker } from "@/composables/useExportTracker";
import type { CatalogInfo } from "@/types/database";
-import { ArrowRightLeft, ArrowLeftRight, Loader2, Square, CheckSquare } from "@lucide/vue";
+import { ArrowRightLeft, ArrowLeftRight, Loader2 } from "@lucide/vue";
const { t } = useI18n();
const { startDataTransferTask } = useExportTracker();
@@ -50,10 +53,73 @@ const sourceDatabase = ref("");
const sourceDatabases = ref<string[]>([]);
const sourceSchemas = ref<string[]>([]);
const sourceSchema = ref("");
-const sourceTables = ref<string[]>([]);
-const selectedTables = ref<Set<string>>(new Set());
-const tableSearch = ref("");
-const loadingTables = ref(false);
+const objectGroups = ref<Partial<Record<TransferObjectKind, string[]>>>({});
+const selectedObjects = ref<Partial<Record<TransferObjectKind, Set<string>>>>({});
+const objectSearch = ref("");
+const loadingObjects = ref(false);
+const transferContent = ref<TransferContent>("structureAndData");
+
+const selectedTables = computed(() => new Set(selectedObjects.value.TABLE ?? []));
+
+const OBJECT_KIND_LABEL_KEY: Record<TransferObjectKind, string> = {
+ TABLE: "objectTypeTable",
+ VIEW: "objectTypeView",
+ MATERIALIZED_VIEW: "objectTypeMaterializedView",
+ PROCEDURE: "objectTypeProcedure",
+ FUNCTION: "objectTypeFunction",
+ TRIGGER: "objectTypeTrigger",
+ SEQUENCE: "objectTypeSequence",
+ EVENT: "objectTypeEvent",
+};
+
+const treeSelection = computed<Record<string, string[]>>({
+ get: () => Object.fromEntries(Object.entries(selectedObjects.value).map(([k, v]) => [k, [...(v ?? [])]])),
+ set: (value) => {
+ const next: Partial<Record<TransferObjectKind, Set<string>>> = {};
+ for (const [k, names] of Object.entries(value)) {
+ if (names.length > 0) next[k as TransferObjectKind] = new Set(names);
+ }
+ selectedObjects.value = next;
+ },
+});
+
+const treeGroups = computed(() =>
+ (Object.keys(objectGroups.value) as TransferObjectKind[]).map((kind) => ({
+ kind,
+ label: t(`transfer.${OBJECT_KIND_LABEL_KEY[kind]}`),
+ items: objectGroups.value[kind] ?? [],
+ })),
+);
+
+const treeDisabledGroups = computed<TransferObjectKind[]>(() => {
+ const presentKinds = Object.keys(objectGroups.value) as TransferObjectKind[];
+ if (transferContent.value === "dataOnly") {
+ return presentKinds.filter((k) => k !== "TABLE");
+ }
+ const sourceConfig = store.getConfig(sourceConnectionId.value);
+ const targetConfig = store.getConfig(targetConnectionId.value);
+ const allowed = crossFamilyTransferableKinds(sourceConfig?.db_type, targetConfig?.db_type);
+ return presentKinds.filter((k) => k !== "TABLE" && !allowed.includes(k));
+});
+
+const treeDisabledHints = computed<Record<string, string>>(() => {
+ const hints: Record<string, string> = {};
+ const dataOnly = transferContent.value === "dataOnly";
+ for (const kind of treeDisabledGroups.value) {
+ hints[kind] = dataOnly ? t("transfer.objectDataOnlyDisabled") : t("transfer.objectCrossFamilyDisabled");
+ }
+ return hints;
+});
+
+const showCrossFamilyViewHint = computed(() => {
+ const sourceConfig = store.getConfig(sourceConnectionId.value);
+ const targetConfig = store.getConfig(targetConnectionId.value);
+ if (transferContent.value === "dataOnly") return false;
+ if (!sourceConfig || !targetConfig) return false;
+ const allowed = crossFamilyTransferableKinds(sourceConfig.db_type, targetConfig.db_type);
+ if (!allowed.includes("VIEW")) return false;
+ return !isSameTransferFamily(sourceConfig.db_type, targetConfig.db_type) && (selectedObjects.value.VIEW?.size ?? 0) > 0;
+});
const pendingSourceSchemaPrefill = ref("");
const pendingSelectedTablesPrefill = ref<string[] | null>(null);
@@ -68,7 +134,6 @@ const targetSchema = ref("");
const pendingTargetSchemaPrefill = ref("");
// Options
-const createTable = ref(true);
const transferMode = ref<TransferMode>("append");
const targetTableNameCase = ref<TransferTableNameCase>("preserve");
const batchSize = ref(1000);
@@ -79,13 +144,6 @@ const ownershipTargetOwner = ref("");
const pendingOwnershipRequest = ref<api.TransferRequest | null>(null);
const pendingOwnershipRefresh = ref<{ shouldRefreshTargetTree: boolean } | null>(null);
-const filteredTables = computed(() => {
- const q = tableSearch.value.toLowerCase();
- return q ? sourceTables.value.filter((t) => t.toLowerCase().includes(q)) : sourceTables.value;
-});
-
-const allSelected = computed(() => filteredTables.value.length > 0 && filteredTables.value.every((t) => selectedTables.value.has(t)));
-
function connectionType(id: string): DatabaseType | undefined {
return store.connections.find((c) => c.id === id)?.db_type;
}
@@ -108,26 +166,17 @@ const canStart = computed(() => {
);
const sameSourceAndTarget = sameCatalogAndDatabase && effectiveSourceSchema === effectiveTargetSchema;
return (
- !!sourceConnectionId.value && !!sourceDatabase.value && !!targetConnectionId.value && !!targetDatabase.value && (sourceCatalogs.value.length <= 1 || !!sourceCatalog.value) && (targetCatalogs.value.length <= 1 || !!targetCatalog.value) && selectedTables.value.size > 0 && !sameSourceAndTarget
+ !!sourceConnectionId.value &&
+ !!sourceDatabase.value &&
+ !!targetConnectionId.value &&
+ !!targetDatabase.value &&
+ (sourceCatalogs.value.length <= 1 || !!sourceCatalog.value) &&
+ (targetCatalogs.value.length <= 1 || !!targetCatalog.value) &&
+ (selectedTables.value.size > 0 || Object.values(selectedObjects.value).some((names) => names.size > 0)) &&
+ !sameSourceAndTarget
);
});
-function toggleSelectAll() {
- if (allSelected.value) {
- filteredTables.value.forEach((t) => selectedTables.value.delete(t));
- } else {
- filteredTables.value.forEach((t) => selectedTables.value.add(t));
- }
-}
-
-function toggleTable(table: string) {
- if (selectedTables.value.has(table)) {
- selectedTables.value.delete(table);
- } else {
- selectedTables.value.add(table);
- }
-}
-
async function loadCatalogs(connectionId: string, side: "source" | "target") {
if (!connectionId || !isCatalogCapable(connectionId)) {
if (side === "source") {
@@ -234,19 +283,26 @@ async function loadSchemas(connectionId: string, database: string, side: "source
function applyPendingTableSelection() {
const pending = pendingSelectedTablesPrefill.value;
- selectedTables.value = pending ? new Set(sourceTables.value.filter((table) => pending.includes(table))) : new Set(sourceTables.value);
+ const tables = objectGroups.value.TABLE ?? [];
+ if (pending) {
+ const chosen = new Set(tables.filter((table) => pending.includes(table)));
+ if (chosen.size > 0) {
+ selectedObjects.value = { ...selectedObjects.value, TABLE: chosen };
+ }
+ }
pendingSelectedTablesPrefill.value = null;
}
-async function loadTables() {
+async function loadObjects() {
if (!sourceConnectionId.value || !sourceDatabase.value) {
- sourceTables.value = [];
+ objectGroups.value = {};
return;
}
- loadingTables.value = true;
+ loadingObjects.value = true;
try {
if (isMongoConnection(sourceConnectionId.value)) {
- sourceTables.value = (await api.mongoListCollections(sourceConnectionId.value, sourceDatabase.value)).map((c) => c.name);
+ const collections = await api.mongoListCollections(sourceConnectionId.value, sourceDatabase.value);
+ objectGroups.value = { TABLE: collections.map((c) => c.name) };
applyPendingTableSelection();
return;
}
@@ -254,13 +310,27 @@ async function loadTables() {
const needsSchema = isSchemaAware(config?.db_type);
const schema = needsSchema && sourceSchema.value ? sourceSchema.value : sourceDatabase.value;
const catalog = sourceCatalog.value || undefined;
- const tables = await api.listTables(sourceConnectionId.value, sourceDatabase.value, schema, undefined, undefined, undefined, undefined, catalog);
- sourceTables.value = tables.filter((t) => t.table_type === "TABLE" || t.table_type === "BASE TABLE").map((t) => t.name);
+ const kinds = transferObjectKindsForDatabase(config?.db_type);
+ const groups: Partial<Record<TransferObjectKind, string[]>> = {};
+ for (const kind of kinds) {
+ try {
+ if (kind === "TABLE") {
+ const tables = await api.listTables(sourceConnectionId.value, sourceDatabase.value, schema, undefined, undefined, undefined, undefined, catalog);
+ groups.TABLE = tables.filter((t) => t.table_type === "TABLE" || t.table_type === "BASE TABLE").map((t) => t.name);
+ } else {
+ const objects = await api.listObjects(sourceConnectionId.value, sourceDatabase.value, schema, [kind], undefined, undefined, undefined, catalog);
+ groups[kind] = objects.map((o) => o.name);
+ }
+ } catch {
+ groups[kind] = [];
+ }
+ }
+ objectGroups.value = groups;
applyPendingTableSelection();
} catch {
- sourceTables.value = [];
+ objectGroups.value = {};
} finally {
- loadingTables.value = false;
+ loadingObjects.value = false;
}
}
@@ -275,8 +345,8 @@ watch(sourceConnectionId, async (id) => {
sourceCatalog.value = "";
sourceCatalogs.value = [];
sourceDatabase.value = "";
- sourceTables.value = [];
- selectedTables.value.clear();
+ objectGroups.value = {};
+ selectedObjects.value = {};
pendingSourceSchemaPrefill.value = "";
pendingSelectedTablesPrefill.value = null;
if (isCatalogCapable(id)) {
@@ -292,8 +362,8 @@ watch(sourceConnectionId, async (id) => {
watch(sourceCatalog, async (catalog) => {
if (!sourceConnectionId.value) return;
sourceDatabase.value = "";
- sourceTables.value = [];
- selectedTables.value.clear();
+ objectGroups.value = {};
+ selectedObjects.value = {};
if (catalog) {
await loadDatabasesForCatalog(sourceConnectionId.value, catalog, "source");
}
@@ -316,7 +386,7 @@ watch(sourceDatabase, async (db) => {
}
});
-watch(sourceSchema, () => loadTables());
+watch(sourceSchema, () => loadObjects());
watch(targetConnectionId, async (id) => {
if (skipTargetWatch.value) {
@@ -414,11 +484,11 @@ function resetState() {
sourceDatabases.value = [];
sourceSchemas.value = [];
sourceSchema.value = "";
- sourceTables.value = [];
- selectedTables.value.clear();
+ objectGroups.value = {};
+ selectedObjects.value = {};
pendingSourceSchemaPrefill.value = "";
pendingSelectedTablesPrefill.value = null;
- tableSearch.value = "";
+ objectSearch.value = "";
targetConnectionId.value = "";
targetCatalog.value = "";
targetCatalogs.value = [];
@@ -427,7 +497,7 @@ function resetState() {
targetSchemas.value = [];
targetSchema.value = "";
pendingTargetSchemaPrefill.value = "";
- createTable.value = true;
+ transferContent.value = "structureAndData";
transferMode.value = "append";
targetTableNameCase.value = "preserve";
batchSize.value = 1000;
@@ -448,7 +518,7 @@ async function startTransfer() {
const sourceDatabaseName = sourceDatabase.value;
const targetConnection = targetConnectionId.value;
const targetDatabaseName = targetDatabase.value;
- const shouldRefreshTargetTree = createTable.value;
+ const shouldRefreshTargetTree = transferContent.value !== "dataOnly";
const request: api.TransferRequest = {
transferId: uuid(),
@@ -461,14 +531,16 @@ async function startTransfer() {
targetSchema: effectiveTargetSchema,
targetCatalog: normalizeTransferCatalog(targetCatalog.value, targetCatalogs.value) || undefined,
tables: [...selectedTables.value],
- createTable: createTable.value,
+ createTable: transferContent.value !== "dataOnly",
+ content: transferContent.value,
+ objects: buildTransferObjectSelections(selectedObjects.value, treeDisabledGroups.value),
mode: transferMode.value,
targetTableNameCase: targetTableNameCase.value,
ownershipPolicy: "preserve",
batchSize: batchSize.value,
};
- if (createTable.value) {
+ if (transferContent.value !== "dataOnly") {
try {
const preview = await api.previewTransferOwnership(request);
if (preview.missingOwners.length > 0) {
@@ -535,8 +607,8 @@ function getConnectionName(id: string) {
</DialogTitle>
</DialogHeader>
- <div class="min-h-0 flex-1 overflow-hidden">
- <div class="grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)_auto] gap-4 py-3">
+ <div class="min-h-0 flex-1 overflow-y-auto pr-1 scrollbar-thin">
+ <div class="flex flex-col gap-5 py-3">
<!-- Source / Target Side by Side -->
<div class="grid grid-cols-[1fr_auto_1fr] gap-4 items-start">
<!-- Source Section -->
@@ -693,48 +765,47 @@ function getConnectionName(id: string) {
</div>
</div>
- <!-- Tables Section -->
+ <!-- Objects Section -->
<div class="flex min-h-0 flex-col gap-2">
<div class="flex items-center justify-between">
<div class="text-xs font-medium text-muted-foreground uppercase tracking-wider">
- {{ t("transfer.tables") }}
- <span v-if="sourceTables.length" class="text-muted-foreground/60">({{ selectedTables.size }}/{{ sourceTables.length }})</span>
+ {{ t("transfer.objects") }}
+ <span v-if="objectGroups.TABLE?.length" class="text-muted-foreground/60">({{ selectedTables.size }}/{{ objectGroups.TABLE.length }})</span>
</div>
- <Button v-if="sourceTables.length" variant="ghost" size="sm" class="h-6 text-xs px-2" @click="toggleSelectAll">
- {{ allSelected ? t("transfer.deselectAll") : t("transfer.selectAll") }}
- </Button>
</div>
- <Input v-if="sourceTables.length > 5" v-model="tableSearch" :placeholder="t('transfer.searchTables')" class="h-7 text-xs" />
-
- <div v-if="loadingTables" class="flex items-center gap-2 text-xs text-muted-foreground py-4 justify-center">
- <Loader2 class="w-3.5 h-3.5 animate-spin" />
- {{ t("common.loading") }}
- </div>
- <div v-else-if="!sourceConnectionId || !sourceDatabase" class="text-xs text-muted-foreground py-4 text-center">
+ <div v-if="(!loadingObjects && !sourceConnectionId) || !sourceDatabase" class="text-xs text-muted-foreground py-4 text-center">
{{ t("transfer.selectSourceFirst") }}
</div>
- <div v-else-if="sourceTables.length === 0" class="text-xs text-muted-foreground py-4 text-center">
- {{ t("transfer.noTables") }}
- </div>
- <div v-else class="min-h-0 max-h-[200px] overflow-y-auto rounded-md border">
- <div v-for="table in filteredTables" :key="table" class="flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/50 cursor-pointer text-xs" @click="toggleTable(table)">
- <CheckSquare v-if="selectedTables.has(table)" class="w-3.5 h-3.5 text-primary shrink-0" />
- <Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
- <span class="truncate">{{ table }}</span>
- </div>
+ <ObjectSelectionTree v-model="treeSelection" :groups="treeGroups" :disabled-groups="treeDisabledGroups" :disabled-hints="treeDisabledHints" v-model:search="objectSearch" :loading="loadingObjects" class="min-h-0 flex-1" />
+ <div v-if="showCrossFamilyViewHint" class="mt-1.5 rounded-md border border-amber-300/40 bg-amber-50 px-2 py-1.5 text-xs text-amber-700">
+ {{ t("transfer.crossFamilyViewHint") }}
</div>
</div>
<!-- Options -->
<div class="space-y-2.5">
- <div class="flex items-center gap-2 cursor-pointer text-xs" @click="createTable = !createTable">
- <CheckSquare v-if="createTable" class="w-3.5 h-3.5 text-primary shrink-0" />
- <Square v-else class="w-3.5 h-3.5 text-muted-foreground/40 shrink-0" />
- {{ t("transfer.createTable") }}
+ <div class="space-y-1">
+ <Label class="text-xs">{{ t("transfer.content") }}</Label>
+ <div class="flex flex-col gap-1">
+ <label class="flex cursor-pointer items-center gap-2 text-xs">
+ <input type="radio" value="structureAndData" v-model="transferContent" class="h-3.5 w-3.5" />
+ {{ t("transfer.contentStructureAndData") }}
+ </label>
+ <label class="flex cursor-pointer items-center gap-2 text-xs">
+ <input type="radio" value="structureOnly" v-model="transferContent" class="h-3.5 w-3.5" />
+ {{ t("transfer.contentStructureOnly") }}
+ <span class="text-muted-foreground/70">{{ t("transfer.contentStructureOnlyHint") }}</span>
+ </label>
+ <label class="flex cursor-pointer items-center gap-2 text-xs">
+ <input type="radio" value="dataOnly" v-model="transferContent" class="h-3.5 w-3.5" />
+ {{ t("transfer.contentDataOnly") }}
+ <span class="text-muted-foreground/70">{{ t("transfer.contentDataOnlyHint") }}</span>
+ </label>
+ </div>
</div>
- <div class="flex items-center gap-3">
- <Label class="text-xs shrink-0">{{ t("transfer.transferMode") }}</Label>
+ <div v-if="transferContent !== 'structureOnly'" class="flex items-center gap-3">
+ <Label class="text-xs shrink-0">{{ t("transfer.dataWriteMode") }}</Label>
<Select v-model="transferMode">
<SelectTrigger class="h-7 text-xs">
<SelectValue />
diff --git a/apps/desktop/src/components/transfer/ObjectSelectionTree.vue b/apps/desktop/src/components/transfer/ObjectSelectionTree.vue
new file mode 100644
index 0000000000..4257023b04
--- /dev/null
+++ b/apps/desktop/src/components/transfer/ObjectSelectionTree.vue
@@ -0,0 +1,236 @@
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import type { TransferObjectKind } from "@/lib/backend/api";
+import { Square, CheckSquare, MinusSquare, Search, ChevronRight } from "@lucide/vue";
+
+const { t } = useI18n();
+
+export interface ObjectTreeGroup {
+ kind: TransferObjectKind;
+ label: string;
+ items: string[];
+}
+
+const props = defineProps<{
+ groups: ObjectTreeGroup[];
+ disabledGroups: TransferObjectKind[];
+ disabledHints: Record<string, string>;
+ modelValue: Record<string, string[]>;
+ search?: string;
+ loading?: boolean;
+}>();
+
+const emit = defineEmits<{
+ "update:modelValue": [value: Record<string, string[]>];
+ "update:search": [value: string];
+}>();
+
+const expanded = ref<Set<string>>(new Set(props.groups.map((g) => g.kind)));
+
+// Groups may arrive after the tree mounts (async object loading); keep newly
+// appearing groups expanded so search results are visible without a manual tap.
+watch(
+ () => props.groups.map((g) => g.kind),
+ (kinds) => {
+ let changed = false;
+ const next = new Set(expanded.value);
+ for (const kind of kinds) {
+ if (!next.has(kind)) {
+ next.add(kind);
+ changed = true;
+ }
+ }
+ if (changed) expanded.value = next;
+ },
+);
+
+// Local search state: the input edits this ref directly and changes are
+// forwarded up via update:search (v-model:search on the parent).
+const localSearch = ref(props.search ?? "");
+watch(
+ () => props.search,
+ (v) => {
+ if (v !== localSearch.value) localSearch.value = v ?? "";
+ },
+);
+watch(localSearch, (v) => {
+ if (v !== (props.search ?? "")) emit("update:search", v);
+});
+
+const searchQuery = computed(() => localSearch.value.trim().toLowerCase());
+
+function toggleGroup(kind: string) {
+ const next = new Set(expanded.value);
+ if (next.has(kind)) {
+ next.delete(kind);
+ } else {
+ next.add(kind);
+ }
+ expanded.value = next;
+}
+
+function isGroupDisabled(kind: TransferObjectKind): boolean {
+ return props.disabledGroups.includes(kind);
+}
+
+function selectedNames(kind: string): string[] {
+ return props.modelValue[kind] ?? [];
+}
+
+function updateSelection(kind: string, names: string[]) {
+ const next: Record<string, string[]> = { ...props.modelValue };
+ if (names.length === 0) {
+ delete next[kind];
+ } else {
+ next[kind] = names;
+ }
+ emit("update:modelValue", next);
+}
+
+function toggleItem(kind: string, item: string) {
+ const current = selectedNames(kind);
+ const next = current.includes(item) ? current.filter((n) => n !== item) : [...current, item];
+ updateSelection(kind, next);
+}
+
+function toggleGroupAll(kind: TransferObjectKind, items: string[]) {
+ const current = selectedNames(kind);
+ const allVisibleSelected = items.length > 0 && items.every((n) => current.includes(n));
+ if (allVisibleSelected) {
+ // uncheck only the visible items, keep selections hidden by the search
+ updateSelection(
+ kind,
+ current.filter((n) => !items.includes(n)),
+ );
+ } else {
+ // check the visible items, merging with existing (possibly hidden) ones
+ updateSelection(kind, [...new Set([...current, ...items])]);
+ }
+}
+
+const filteredGroups = computed<ObjectTreeGroup[]>(() => {
+ const query = searchQuery.value;
+ if (!query) {
+ return props.groups;
+ }
+ return props.groups.map((g) => ({
+ ...g,
+ items: g.items.filter((name) => name.toLowerCase().includes(query)),
+ }));
+});
+
+function selectAllEnabled() {
+ const next: Record<string, string[]> = { ...props.modelValue };
+ for (const group of filteredGroups.value) {
+ if (isGroupDisabled(group.kind)) continue;
+ next[group.kind] = [...new Set([...(next[group.kind] ?? []), ...group.items])];
+ }
+ emit("update:modelValue", next);
+}
+
+function deselectAll() {
+ // Clear only the visible, enabled selections; selections hidden by the
+ // current search and selections inside disabled groups are preserved so
+ // bulk actions never silently drop what the user cannot see.
+ const next: Record<string, string[]> = { ...props.modelValue };
+ for (const group of filteredGroups.value) {
+ if (isGroupDisabled(group.kind)) continue;
+ const kept = (next[group.kind] ?? []).filter((n) => !group.items.includes(n));
+ if (kept.length === 0) {
+ delete next[group.kind];
+ } else {
+ next[group.kind] = kept;
+ }
+ }
+ emit("update:modelValue", next);
+}
+
+// The bulk button flips between “select all” and “deselect all”. It shows
+// “deselect all” only when every visible, enabled item is already selected
+// (selecting more is then a no-op); otherwise “select all” is shown so the
+// user can fill the remaining visible items. Groups with no visible items
+// (fully filtered out by the search) and disabled groups are ignored.
+const allVisibleEnabledSelected = computed(() => {
+ const visibleEnabled = filteredGroups.value.filter((g) => !isGroupDisabled(g.kind) && g.items.length > 0);
+ return visibleEnabled.length > 0 && visibleEnabled.every((g) => g.items.every((item) => (props.modelValue[g.kind] ?? []).includes(item)));
+});
+
+// Tri-state header checkbox: "all" when every visible item of the group is
+// selected, "partial" when only some are, "none" otherwise. Mirrors
+// toggleGroupAll, which only ever touches the visible items.
+function groupSelectionState(kind: TransferObjectKind, items: string[]): "none" | "partial" | "all" {
+ if (items.length === 0) return "none";
+ const selected = props.modelValue[kind] ?? [];
+ const visibleSelected = items.filter((item) => selected.includes(item)).length;
+ if (visibleSelected === 0) return "none";
+ if (visibleSelected === items.length) return "all";
+ return "partial";
+}
+</script>
+
+<template>
+ <div class="flex flex-col flex-1 min-h-0 gap-2.5">
+ <!-- Sticky top bar: search input and action buttons -->
+ <div class="flex items-center gap-2 shrink-0">
+ <div class="relative flex-1 min-w-0">
+ <Search class="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/60 pointer-events-none" />
+ <input
+ data-test="search"
+ :placeholder="t('transfer.searchObjects')"
+ v-model="localSearch"
+ autocapitalize="off"
+ autocomplete="off"
+ autocorrect="off"
+ spellcheck="false"
+ class="pl-8 pr-2.5 h-8 w-full rounded-md border border-input bg-transparent text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:border-ring transition-colors placeholder:text-muted-foreground/70"
+ />
+ </div>
+ <Button v-if="allVisibleEnabledSelected" variant="outline" size="sm" @click="deselectAll">
+ {{ t("transfer.deselectAll") }}
+ </Button>
+ <Button v-else variant="outline" size="sm" @click="selectAllEnabled">
+ {{ t("transfer.selectAll") }}
+ </Button>
+ </div>
+
+ <div v-if="loading" class="py-4 text-center text-sm text-muted-foreground">
+ {{ t("common.loading") }}
+ </div>
+
+ <div v-else-if="groups.length === 0" class="py-4 text-center text-sm text-muted-foreground">
+ {{ t("transfer.noObjects") }}
+ </div>
+
+ <!-- Independent scroll area for tree groups -->
+ <div v-else class="flex-1 min-h-0 max-h-[240px] flex flex-col gap-1.5 overflow-y-auto rounded-md border border-border/80 bg-muted/10 p-1.5 scrollbar-thin scrollbar-thumb-muted-foreground/20">
+ <div v-for="group in filteredGroups" :key="group.kind" :data-test="`group-${group.kind}`" class="rounded-lg border border-border/60 bg-card/60 transition-all hover:bg-card flex flex-col p-1.5" :class="{ 'opacity-50 bg-muted/5 border-dashed border-muted': isGroupDisabled(group.kind) }">
+ <div class="flex items-center gap-2 px-1 py-0.5 select-none">
+ <button :data-test="'group-toggle'" :data-state="groupSelectionState(group.kind, group.items)" type="button" class="flex items-center gap-2 text-left shrink-0" :disabled="isGroupDisabled(group.kind)" @click="!isGroupDisabled(group.kind) && toggleGroupAll(group.kind, group.items)">
+ <CheckSquare v-if="groupSelectionState(group.kind, group.items) === 'all'" class="h-4 w-4 text-primary" />
+ <MinusSquare v-else-if="groupSelectionState(group.kind, group.items) === 'partial'" class="h-4 w-4 text-primary" />
+ <Square v-else class="h-4 w-4 text-muted-foreground" />
+ </button>
+ <span class="flex-1 text-xs font-semibold text-foreground/90 cursor-pointer" @click="toggleGroup(group.kind)">
+ {{ group.label }}
+ </span>
+ <span class="text-[10px] px-1 py-0.5 rounded-full bg-muted/60 text-muted-foreground font-mono shrink-0"> {{ (modelValue[group.kind] ?? []).length }}/{{ group.items.length }} </span>
+ <span v-if="disabledHints[group.kind]" class="rounded bg-amber-500/10 border border-amber-500/20 px-1.5 py-0.5 text-[10px] text-amber-700 font-medium shrink-0">
+ {{ disabledHints[group.kind] }}
+ </span>
+ <button type="button" class="text-muted-foreground hover:text-foreground shrink-0 p-0.5" @click="toggleGroup(group.kind)">
+ <ChevronRight class="h-3.5 w-3.5 text-muted-foreground/80 transition-transform duration-200" :class="{ 'rotate-90': expanded.has(group.kind) }" />
+ </button>
+ </div>
+
+ <div v-if="expanded.has(group.kind)" class="flex flex-col gap-0.5 pl-6 pr-1 mt-1">
+ <label v-for="item in group.items" :key="item" class="flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 text-xs hover:bg-muted/70 transition-colors" :class="{ 'pointer-events-none opacity-50': isGroupDisabled(group.kind) }" :data-test="`item-${group.kind}-${item}`">
+ <input type="checkbox" class="h-3.5 w-3.5" :checked="(modelValue[group.kind] ?? []).includes(item)" :disabled="isGroupDisabled(group.kind)" @change="toggleItem(group.kind, item)" />
+ <span class="truncate text-foreground/80">{{ item }}</span>
+ </label>
+ <div v-if="group.items.length === 0" class="px-1 py-1 text-xs text-muted-foreground">无匹配</div>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts b/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts
index 28e816f251..353e1363c8 100644
--- a/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts
+++ b/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts
@@ -7,17 +7,16 @@ describe("DataTransferDialog layout", () => {
it("keeps the header and footer outside the shrinking content region", () => {
expect(dialogSource).toContain('<DialogHeader class="shrink-0">');
expect(dialogSource).toContain('<DialogFooter class="shrink-0">');
- expect(dialogSource).toContain('class="min-h-0 flex-1 overflow-hidden"');
+ expect(dialogSource).toContain('class="min-h-0 flex-1 overflow-y-auto pr-1 scrollbar-thin"');
});
- it("shrinks the table row on short viewports without adding dialog scrolling", () => {
- expect(dialogSource).toContain('class="grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)_auto] gap-4 py-3"');
+ it("allows layout scrolling on short viewports to prevent content clipping", () => {
+ expect(dialogSource).toContain('class="flex flex-col gap-5 py-3"');
expect(dialogSource).toContain('class="flex min-h-0 flex-col gap-2"');
- expect(dialogSource).not.toContain('class="flex-1 min-h-0 overflow-auto"');
});
it("keeps long table lists independently scrollable", () => {
- expect(dialogSource).toContain('class="min-h-0 max-h-[200px] overflow-y-auto rounded-md border"');
+ expect(dialogSource).toContain('class="min-h-0 flex-1"');
});
});
@@ -32,7 +31,27 @@ describe("DataTransferDialog transfer prefill", () => {
it("keeps only copied tables selected after loading the source list", () => {
expect(dialogSource).toContain("function applyPendingTableSelection()");
- expect(dialogSource).toContain("new Set(sourceTables.value.filter((table) => pending.includes(table)))");
+ expect(dialogSource).toContain("new Set(tables.filter((table) => pending.includes(table)))");
+ });
+
+ it("sends content and objects in the transfer request", () => {
+ expect(dialogSource).toContain("buildTransferObjectSelections(selectedObjects.value, treeDisabledGroups.value)");
+ expect(dialogSource).toContain('import { buildTransferObjectSelections } from "./transferSelections"');
+ expect(dialogSource).toContain('createTable: transferContent.value !== "dataOnly"');
+ expect(dialogSource).toContain('createTable: transferContent.value !== "dataOnly"');
+ });
+
+ it("loads non-table object groups per source database kind", () => {
+ expect(dialogSource).toContain("transferObjectKindsForDatabase");
+ expect(dialogSource).toContain("api.listObjects(sourceConnectionId.value, sourceDatabase.value, schema, [kind]");
+ expect(dialogSource).toContain("groups[kind] = objects.map((o) => o.name)");
+ });
+
+ it("disables non-table groups for data-only and cross-family transfers", () => {
+ expect(dialogSource).toContain("treeDisabledGroups");
+ expect(dialogSource).toContain('transferContent.value === "dataOnly"');
+ expect(dialogSource).toContain("crossFamilyTransferableKinds");
+ expect(dialogSource).toContain("objectDataOnlyDisabled");
});
it("allows a transfer between different schemas in the same database", () => {
diff --git a/apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts b/apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts
new file mode 100644
index 0000000000..b681fcbaf0
--- /dev/null
+++ b/apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts
@@ -0,0 +1,272 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, reactive } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Component } from "vue";
+
+function passthrough(tag: string): Component {
+ return defineComponent({
+ inheritAttrs: false,
+ setup(_, { attrs, slots }) {
+ return () => h(tag, attrs, slots.default?.());
+ },
+ });
+}
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+vi.mock("@lucide/vue", () => {
+ const Icon = passthrough("span");
+ return {
+ Square: Icon,
+ CheckSquare: Icon,
+ MinusSquare: Icon,
+ Search: Icon,
+ ChevronRight: Icon,
+ };
+});
+vi.mock("@/components/ui/button", () => ({ Button: passthrough("button") }));
+
+import ObjectSelectionTree from "../ObjectSelectionTree.vue";
+
+type Kind = "TABLE" | "VIEW" | "FUNCTION";
+
+interface TreeGroup {
+ kind: Kind;
+ label: string;
+ items: string[];
+}
+
+const VIEWS: TreeGroup = { kind: "VIEW", label: "Views", items: ["v1", "v2", "v3"] };
+const FUNCTIONS: TreeGroup = { kind: "FUNCTION", label: "Fns", items: ["f1", "f2"] };
+const TABLES: TreeGroup = { kind: "TABLE", label: "Tables", items: ["t1", "t2"] };
+
+function mountTree(init: { groups?: TreeGroup[]; disabledGroups?: Kind[]; disabledHints?: Record<string, string>; selection?: Record<string, string[]>; search?: string }) {
+ const { groups = [VIEWS, FUNCTIONS], disabledGroups = [], disabledHints = {}, selection = {}, search = "" } = init;
+ const state = reactive({ selection, search });
+ const Wrapper = defineComponent({
+ setup() {
+ return () =>
+ h(ObjectSelectionTree, {
+ groups,
+ disabledGroups,
+ disabledHints,
+ modelValue: state.selection,
+ "onUpdate:modelValue": (v: Record<string, string[]>) => {
+ state.selection = v;
+ },
+ search: state.search,
+ "onUpdate:search": (v: string) => {
+ state.search = v;
+ },
+ });
+ },
+ });
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const app = createApp(Wrapper);
+ app.mount(container);
+ return { state, container, app };
+}
+
+function groupToggle(container: HTMLElement, index = 0): HTMLButtonElement {
+ return container.querySelectorAll<HTMLButtonElement>('button[data-test="group-toggle"]')[index];
+}
+
+function itemCheckbox(container: HTMLElement, kind: string, item: string): HTMLInputElement {
+ return container.querySelector<HTMLInputElement>(`label[data-test="item-${kind}-${item}"] input`)!;
+}
+
+function toolbarButton(container: HTMLElement, label: string): HTMLButtonElement | undefined {
+ return Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find((b) => b.textContent?.includes(label));
+}
+
+async function typeSearch(container: HTMLElement, value: string) {
+ const input = container.querySelector<HTMLInputElement>('input[data-test="search"]')!;
+ input.value = value;
+ input.dispatchEvent(new Event("input"));
+ await nextTick();
+}
+
+let cleanup: (() => void) | undefined;
+afterEach(() => {
+ cleanup?.();
+ cleanup = undefined;
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+describe("ObjectSelectionTree interaction", () => {
+ it("renders group headers, items and the search input", async () => {
+ const { container, app } = mountTree({});
+ cleanup = () => app.unmount();
+ expect(container.textContent).toContain("Views");
+ expect(container.querySelector('label[data-test="item-VIEW-v1"]')).not.toBeNull();
+ expect(container.querySelector('label[data-test="item-FUNCTION-f2"]')).not.toBeNull();
+ expect(container.querySelector('input[data-test="search"]')).not.toBeNull();
+ });
+
+ it("toggles all items of a group through the group header checkbox", async () => {
+ const { state, container, app } = mountTree({});
+ cleanup = () => app.unmount();
+ groupToggle(container).click();
+ await nextTick();
+ expect(state.selection.VIEW).toEqual(["v1", "v2", "v3"]);
+ // clicking again with every visible item selected unchecks them all
+ groupToggle(container).click();
+ await nextTick();
+ expect(state.selection.VIEW ?? []).toEqual([]);
+ });
+
+ it("group toggle under a search only touches the visible items", async () => {
+ const { state, container, app } = mountTree({ selection: { VIEW: ["v1", "v2", "v3"] } });
+ cleanup = () => app.unmount();
+ await typeSearch(container, "v2");
+ // all visible items (only v2) are selected -> toggle unchecks only v2
+ groupToggle(container).click();
+ await nextTick();
+ expect(state.selection.VIEW).toEqual(["v1", "v3"]);
+ });
+
+ it("deselect all only clears visible enabled selections, keeping hidden ones", async () => {
+ const { state, container, app } = mountTree({
+ selection: { VIEW: ["v1", "v2", "v3"], FUNCTION: ["f1", "f2"] },
+ });
+ cleanup = () => app.unmount();
+ await typeSearch(container, "v1");
+ toolbarButton(container, "transfer.deselectAll")!.click();
+ await nextTick();
+ expect(state.selection.VIEW).toEqual(["v2", "v3"]); // hidden selections survive
+ expect(state.selection.FUNCTION).toEqual(["f1", "f2"]);
+ });
+
+ it("deselect all skips disabled groups entirely", async () => {
+ const { state, container, app } = mountTree({
+ groups: [TABLES, VIEWS],
+ disabledGroups: ["VIEW"],
+ selection: { TABLE: ["t1", "t2"], VIEW: ["v1", "v2"] },
+ });
+ cleanup = () => app.unmount();
+ toolbarButton(container, "transfer.deselectAll")!.click();
+ await nextTick();
+ expect(state.selection.TABLE ?? []).toEqual([]);
+ expect(state.selection.VIEW).toEqual(["v1", "v2"]);
+ });
+
+ it("select all only selects visible enabled groups, merging hidden selections", async () => {
+ const { state, container, app } = mountTree({
+ selection: { VIEW: ["v1"], FUNCTION: [] },
+ });
+ cleanup = () => app.unmount();
+ await typeSearch(container, "v2");
+ // VIEW is the only group with visible items; FUNCTION items are filtered out
+ toolbarButton(container, "transfer.selectAll")!.click();
+ await nextTick();
+ expect(state.selection.VIEW).toEqual(["v1", "v2"]);
+ expect(state.selection.FUNCTION ?? []).toEqual([]);
+ });
+
+ it("select all skips disabled groups", async () => {
+ const { state, container, app } = mountTree({
+ groups: [TABLES, VIEWS],
+ disabledGroups: ["VIEW"],
+ });
+ cleanup = () => app.unmount();
+ toolbarButton(container, "transfer.selectAll")!.click();
+ await nextTick();
+ expect(state.selection.TABLE).toEqual(["t1", "t2"]);
+ expect(state.selection.VIEW ?? []).toEqual([]);
+ });
+
+ it("shows select-all while some visible enabled items are still unselected", async () => {
+ // user scenario: every TABLE selected but VIEW untouched -> select-all
+ const { container, app } = mountTree({
+ groups: [TABLES, VIEWS],
+ selection: { TABLE: ["t1", "t2"], VIEW: ["v1"] },
+ });
+ cleanup = () => app.unmount();
+ expect(toolbarButton(container, "transfer.selectAll")).toBeDefined();
+ expect(toolbarButton(container, "transfer.deselectAll")).toBeUndefined();
+ });
+
+ it("shows deselect-all only when every visible enabled item is selected", async () => {
+ const { state, container, app } = mountTree({
+ selection: { VIEW: ["v1", "v2", "v3"], FUNCTION: ["f1", "f2"] },
+ });
+ cleanup = () => app.unmount();
+ expect(toolbarButton(container, "transfer.deselectAll")).toBeDefined();
+ expect(toolbarButton(container, "transfer.selectAll")).toBeUndefined();
+ // deselecting everything flips the button back to select-all
+ toolbarButton(container, "transfer.deselectAll")!.click();
+ await nextTick();
+ expect(state.selection).toEqual({});
+ expect(toolbarButton(container, "transfer.selectAll")).toBeDefined();
+ });
+
+ it("search-filtered view: all visible items selected still shows deselect-all", async () => {
+ const { container, app } = mountTree({
+ selection: { VIEW: ["v1", "v2", "v3"], FUNCTION: ["f1"] },
+ });
+ cleanup = () => app.unmount();
+ // only v1 and f1 remain visible; both are selected -> deselect-all
+ await typeSearch(container, "1");
+ expect(toolbarButton(container, "transfer.deselectAll")).toBeDefined();
+ // filtering to nothing leaves only hidden selections -> select-all is shown again
+ await typeSearch(container, "zzz-no-match");
+ expect(toolbarButton(container, "transfer.selectAll")).toBeDefined();
+ expect(toolbarButton(container, "transfer.deselectAll")).toBeUndefined();
+ });
+
+ it("hidden selections in disabled groups do not surface the deselect button", async () => {
+ const { container, app } = mountTree({
+ groups: [TABLES, VIEWS],
+ disabledGroups: ["VIEW"],
+ selection: { VIEW: ["v1", "v2"] },
+ });
+ cleanup = () => app.unmount();
+ expect(toolbarButton(container, "transfer.selectAll")).toBeDefined();
+ expect(toolbarButton(container, "transfer.deselectAll")).toBeUndefined();
+ });
+
+ it("item checkbox toggles a single selection", async () => {
+ const { state, container, app } = mountTree({});
+ cleanup = () => app.unmount();
+ itemCheckbox(container, "VIEW", "v2").click();
+ await nextTick();
+ expect(state.selection.VIEW).toEqual(["v2"]);
+ itemCheckbox(container, "VIEW", "v2").click();
+ await nextTick();
+ expect(state.selection.VIEW ?? []).toEqual([]);
+ });
+
+ it("group header checkbox shows none / partial / all tri-state", async () => {
+ // none: no selection in the group
+ const none = mountTree({ groups: [VIEWS], selection: {} });
+ cleanup = () => none.app.unmount();
+ expect(groupToggle(none.container).dataset.state).toBe("none");
+ none.app.unmount();
+
+ // partial: only some visible items selected
+ const partial = mountTree({ groups: [VIEWS], selection: { VIEW: ["v1"] } });
+ cleanup = () => partial.app.unmount();
+ expect(groupToggle(partial.container).dataset.state).toBe("partial");
+ partial.app.unmount();
+
+ // all: every visible item selected
+ const all = mountTree({ groups: [VIEWS], selection: { VIEW: ["v1", "v2", "v3"] } });
+ cleanup = () => all.app.unmount();
+ expect(groupToggle(all.container).dataset.state).toBe("all");
+ all.app.unmount();
+ });
+
+ it("group header state is computed over visible items only", async () => {
+ // every item selected, but the search narrows the visible set to v1
+ const { container, app } = mountTree({ groups: [VIEWS], selection: { VIEW: ["v1", "v2", "v3"] } });
+ cleanup = () => app.unmount();
+ await typeSearch(container, "v1");
+ // v1 is the only visible item and it is selected -> all
+ expect(groupToggle(container).dataset.state).toBe("all");
+ // clearing the search shows every item selected again -> all
+ await typeSearch(container, "");
+ expect(groupToggle(container).dataset.state).toBe("all");
+ });
+});
diff --git a/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.ts b/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.ts
new file mode 100644
index 0000000000..e3fe4bdbdf
--- /dev/null
+++ b/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { buildTransferObjectSelections } from "../transferSelections";
+
+function setOf(names: string[]): Set<string> {
+ return new Set(names);
+}
+
+describe("buildTransferObjectSelections", () => {
+ it("serializes non-table selections in request order", () => {
+ const result = buildTransferObjectSelections(
+ {
+ VIEW: setOf(["v1", "v2"]),
+ SEQUENCE: setOf(["s1"]),
+ TABLE: setOf(["t1"]),
+ },
+ [],
+ );
+ expect(result).toEqual([
+ { objectType: "VIEW", names: ["v1", "v2"] },
+ { objectType: "SEQUENCE", names: ["s1"] },
+ ]);
+ });
+
+ it("drops TABLE selections (handled by the tables field)", () => {
+ const result = buildTransferObjectSelections({ TABLE: setOf(["t1", "t2"]) }, []);
+ expect(result).toEqual([]);
+ });
+
+ it("filters disabled object types even when stale selections remain", () => {
+ const result = buildTransferObjectSelections(
+ {
+ VIEW: setOf(["v1"]),
+ SEQUENCE: setOf(["s1"]),
+ PROCEDURE: setOf(["p1"]),
+ },
+ ["VIEW", "SEQUENCE"],
+ );
+ expect(result).toEqual([{ objectType: "PROCEDURE", names: ["p1"] }]);
+ });
+
+ it("returns an empty payload when nothing is selected", () => {
+ expect(buildTransferObjectSelections({}, [])).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/components/transfer/transferSelections.ts b/apps/desktop/src/components/transfer/transferSelections.ts
new file mode 100644
index 0000000000..93c89ef5a1
--- /dev/null
+++ b/apps/desktop/src/components/transfer/transferSelections.ts
@@ -0,0 +1,22 @@
+import type { TransferObjectKind } from "@/lib/backend/api";
+
+export interface TransferObjectSelectionPayload {
+ objectType: TransferObjectKind;
+ names: string[];
+}
+
+/**
+ * Builds the `objects` payload of a transfer request from the tree
+ * selection state. TABLE is handled by `tables`, and object types that
+ * are currently disabled for this transfer (data-only mode, or kinds the
+ * cross-family matrix does not allow) are dropped at the request boundary
+ * even if stale selections are still present in the tree.
+ */
+export function buildTransferObjectSelections(selectedObjects: Partial<Record<TransferObjectKind, Set<string>>>, disabledGroups: TransferObjectKind[]): TransferObjectSelectionPayload[] {
+ return (Object.keys(selectedObjects) as TransferObjectKind[])
+ .filter((kind) => kind !== "TABLE" && !disabledGroups.includes(kind))
+ .map((kind) => ({
+ objectType: kind,
+ names: [...(selectedObjects[kind] ?? [])],
+ }));
+}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 6e194bdfca..ee4bdc4629 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -3715,6 +3715,29 @@ export default {
},
transfer: {
title: "Data Transfer",
+ content: "Transfer content",
+ contentStructureAndData: "Structure and data",
+ contentStructureOnly: "Structure only",
+ contentDataOnly: "Data only",
+ contentStructureOnlyHint: "Create table and object structures only, no data",
+ contentDataOnlyHint: "Copy data only into existing target tables",
+ objects: "Objects",
+ searchObjects: "Search object names...",
+ noObjects: "No objects",
+ objectTypeTable: "Tables",
+ objectTypeView: "Views",
+ objectTypeMaterializedView: "Materialized views",
+ objectTypeProcedure: "Procedures",
+ objectTypeFunction: "Functions",
+ objectTypeTrigger: "Triggers",
+ objectTypeSequence: "Sequences",
+ objectTypeEvent: "Events",
+ objectDataOnlyDisabled: "Non-table objects are not transferred in data-only mode",
+ objectCrossFamilyDisabled: "Cross-database transfer supports sequences only (plain DDL; view query bodies cannot be translated)",
+ crossFamilyViewHint: "Cross-database view transfer: select the tables the view depends on as well, or make sure they already exist in the target database",
+ objectUnsupportedDisabled: "This database does not support transferring this object type",
+ skippedExistingObjects: "Skipped {count} existing object(s)",
+ dataWriteMode: "Data write mode",
source: "Source",
target: "Target",
sourceConnection: "Source Connection",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index dba6a51ab7..e36707763d 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -3529,6 +3529,29 @@ export default withEnglishFallback({
},
transfer: {
title: "Transferencia de datos",
+ content: "Modo de transferencia",
+ contentStructureAndData: "Estructura y datos",
+ contentStructureOnly: "Solo estructura",
+ contentDataOnly: "Solo datos",
+ contentStructureOnlyHint: "Crear solo las estructuras de tablas y objetos, sin copiar datos",
+ contentDataOnlyHint: "Copiar solo datos en las tablas de destino existentes",
+ objects: "Objetos",
+ searchObjects: "Buscar nombre de objeto...",
+ noObjects: "Sin objetos",
+ objectTypeTable: "Tablas",
+ objectTypeView: "Vistas",
+ objectTypeMaterializedView: "Vistas materializadas",
+ objectTypeProcedure: "Procedimientos",
+ objectTypeFunction: "Funciones",
+ objectTypeTrigger: "Disparadores",
+ objectTypeSequence: "Secuencias",
+ objectTypeEvent: "Eventos",
+ objectDataOnlyDisabled: "Los objetos que no son tablas no se transfieren en el modo de solo datos",
+ objectCrossFamilyDisabled: "La transferencia entre bases de datos solo admite secuencias (DDL simple; los cuerpos de las vistas no se traducen)",
+ crossFamilyViewHint: "Transferencia de vistas entre bases de datos: seleccione también las tablas de las que depende la vista o asegúrese de que ya existen en la base de datos de destino",
+ objectUnsupportedDisabled: "La base de datos actual no admite la transferencia de este tipo de objeto",
+ skippedExistingObjects: "Se omitieron {count} objetos existentes",
+ dataWriteMode: "Modo de escritura de datos",
source: "Origen",
target: "Destino",
sourceConnection: "Conexión de origen",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index c11b4a68eb..fd59aeaa3c 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -3527,6 +3527,29 @@ export default withEnglishFallback({
},
transfer: {
title: "Trasferimento Dati",
+ content: "Contenuto del trasferimento",
+ contentStructureAndData: "Struttura e dati",
+ contentStructureOnly: "Solo struttura",
+ contentDataOnly: "Solo dati",
+ contentStructureOnlyHint: "Crea solo la struttura di tabelle e oggetti, senza copiare dati",
+ contentDataOnlyHint: "Copia solo i dati nelle tabelle di destinazione esistenti",
+ objects: "Oggetti",
+ searchObjects: "Cerca nome oggetto...",
+ noObjects: "Nessun oggetto",
+ objectTypeTable: "Tabelle",
+ objectTypeView: "Viste",
+ objectTypeMaterializedView: "Viste materializzate",
+ objectTypeProcedure: "Procedure",
+ objectTypeFunction: "Funzioni",
+ objectTypeTrigger: "Trigger",
+ objectTypeSequence: "Sequenze",
+ objectTypeEvent: "Eventi",
+ objectDataOnlyDisabled: "Gli oggetti non di tabella non vengono trasferiti nella modalità solo dati",
+ objectCrossFamilyDisabled: "Il trasferimento tra database supporta solo sequenze (DDL semplice; i corpi delle viste non vengono tradotti)",
+ crossFamilyViewHint: "Trasferimento di viste tra database: selezionare anche le tabelle da cui la vista dipende, o assicurarsi che esistano già nel database di destinazione",
+ objectUnsupportedDisabled: "Il database corrente non supporta il trasferimento di questo tipo di oggetto",
+ skippedExistingObjects: "Saltati {count} oggetti esistenti",
+ dataWriteMode: "Modalità di scrittura dati",
source: "Sorgente",
target: "Destinazione",
sourceConnection: "Connessione Sorgente",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 7036f28ff8..59932d05d5 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -3559,6 +3559,29 @@ export default withEnglishFallback({
},
transfer: {
title: "データ転送",
+ content: "転送内容",
+ contentStructureAndData: "構造とデータ",
+ contentStructureOnly: "構造のみ",
+ contentDataOnly: "データのみ",
+ contentStructureOnlyHint: "テーブルとオブジェクトの構造のみを作成し、データはコピーしません",
+ contentDataOnlyHint: "既存のターゲットテーブルにデータのみをコピーします",
+ objects: "オブジェクト",
+ searchObjects: "オブジェクト名で検索...",
+ noObjects: "オブジェクトなし",
+ objectTypeTable: "テーブル",
+ objectTypeView: "ビュー",
+ objectTypeMaterializedView: "マテリアライズドビュー",
+ objectTypeProcedure: "プロシージャ",
+ objectTypeFunction: "関数",
+ objectTypeTrigger: "トリガー",
+ objectTypeSequence: "シーケンス",
+ objectTypeEvent: "イベント",
+ objectDataOnlyDisabled: "データのみモードではテーブル以外のオブジェクトは転送されません",
+ objectCrossFamilyDisabled: "データベース間転送はシーケンスのみサポートします(単純なDDL。ビューの本文は翻訳されません)",
+ crossFamilyViewHint: "データベース間ビュー転送:ビューが依存するテーブルも選択するか、ターゲットDBに既に存在することを確認してください",
+ objectUnsupportedDisabled: "現在のデータベースは、このオブジェクトタイプの転送をサポートしていません",
+ skippedExistingObjects: "既存のオブジェクト {count} 件をスキップしました",
+ dataWriteMode: "データ書き込みモード",
source: "ソース",
target: "対象",
sourceConnection: "ソース接続",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index b5846bd980..153069f63c 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -3461,6 +3461,29 @@ export default withEnglishFallback({
},
transfer: {
title: "데이터 이전",
+ content: "전송 콘텐츠",
+ contentStructureAndData: "구조 및 데이터",
+ contentStructureOnly: "구조만",
+ contentDataOnly: "데이터만",
+ contentStructureOnlyHint: "테이블 및 개체 구조만 생성하고 데이터는 복사하지 않습니다",
+ contentDataOnlyHint: "기존 대상 테이블에 데이터만 복사합니다",
+ objects: "개체",
+ searchObjects: "개체 이름 검색...",
+ noObjects: "개체 없음",
+ objectTypeTable: "테이블",
+ objectTypeView: "뷰",
+ objectTypeMaterializedView: "구체화된 뷰",
+ objectTypeProcedure: "프로시저",
+ objectTypeFunction: "함수",
+ objectTypeTrigger: "트리거",
+ objectTypeSequence: "시퀀스",
+ objectTypeEvent: "이벤트",
+ objectDataOnlyDisabled: "데이터 전용 모드에서는 테이블이 아닌 개체는 전송되지 않습니다",
+ objectCrossFamilyDisabled: "데이터베이스 간 전송은 시퀀스만 지원합니다(단순 DDL, 뷰 본문은 변환되지 않음)",
+ crossFamilyViewHint: "데이터베이스 간 뷰 전송: 뷰가 의존하는 테이블도 선택하거나 대상 DB에 이미 존재하는지 확인하세요",
+ objectUnsupportedDisabled: "현재 데이터베이스는 이 개체 유형의 전송을 지원하지 않습니다",
+ skippedExistingObjects: "기존 개체 {count}개 건너뜀",
+ dataWriteMode: "데이터 쓰기 모드",
source: "소스",
target: "대상",
sourceConnection: "소스 연결",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index e21f63d0c4..d982b32b07 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -3529,6 +3529,29 @@ export default withEnglishFallback({
},
transfer: {
title: "Transferência de Dados",
+ content: "Conteúdo de transferência",
+ contentStructureAndData: "Estrutura e dados",
+ contentStructureOnly: "Apenas estrutura",
+ contentDataOnly: "Apenas dados",
+ contentStructureOnlyHint: "Cria apenas a estrutura de tabelas e objetos, sem copiar dados",
+ contentDataOnlyHint: "Copia apenas os dados para tabelas de destino existentes",
+ objects: "Objetos",
+ searchObjects: "Buscar nome do objeto...",
+ noObjects: "Nenhum objeto",
+ objectTypeTable: "Tabelas",
+ objectTypeView: "Views",
+ objectTypeMaterializedView: "Views materializadas",
+ objectTypeProcedure: "Procedimentos",
+ objectTypeFunction: "Funções",
+ objectTypeTrigger: "Triggers",
+ objectTypeSequence: "Sequências",
+ objectTypeEvent: "Eventos",
+ objectDataOnlyDisabled: "Objetos que não são tabelas não são transferidos no modo apenas dados",
+ objectCrossFamilyDisabled: "A transferência entre bancos suporta apenas sequências (DDL simples; corpos de views não são traduzidos)",
+ crossFamilyViewHint: "Transferência de views entre bancos: selecione também as tabelas das quais a view depende ou garanta que elas já existam no banco de destino",
+ objectUnsupportedDisabled: "O banco de dados atual não suporta a transferência deste tipo de objeto",
+ skippedExistingObjects: "Ignorado {count} objeto(s) existente(s)",
+ dataWriteMode: "Modo de gravação de dados",
source: "Origem",
target: "Destino",
sourceConnection: "Conexão de origem",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 88a61b7724..221ea2e1fb 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -3715,6 +3715,29 @@ export default withEnglishFallback({
},
transfer: {
title: "数据传输",
+ content: "传输方式",
+ contentStructureAndData: "结构和数据",
+ contentStructureOnly: "仅结构",
+ contentDataOnly: "仅数据",
+ contentStructureOnlyHint: "仅创建表和对象结构,不复制数据",
+ contentDataOnlyHint: "仅复制数据到已存在的目标表",
+ objects: "传输对象",
+ searchObjects: "搜索对象名...",
+ noObjects: "暂无对象",
+ objectTypeTable: "表",
+ objectTypeView: "视图",
+ objectTypeMaterializedView: "物化视图",
+ objectTypeProcedure: "存储过程",
+ objectTypeFunction: "函数",
+ objectTypeTrigger: "触发器",
+ objectTypeSequence: "序列",
+ objectTypeEvent: "事件",
+ objectDataOnlyDisabled: "仅数据模式不传输非表对象",
+ objectCrossFamilyDisabled: "跨库仅支持序列传输(纯DDL;视图查询体无法翻译)",
+ crossFamilyViewHint: "跨库视图传输:请同时选择视图依赖的表,或确保目标库已存在这些表",
+ objectUnsupportedDisabled: "当前数据库不支持该对象类型传输",
+ skippedExistingObjects: "跳过 {count} 个已存在对象",
+ dataWriteMode: "数据写入方式",
source: "源",
target: "目标",
sourceConnection: "源连接",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 78c9b8a6c2..d3c063f050 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -2997,6 +2997,29 @@ export default withEnglishFallback({
},
transfer: {
title: "資料傳輸",
+ content: "傳輸方式",
+ contentStructureAndData: "結構和資料",
+ contentStructureOnly: "僅結構",
+ contentDataOnly: "僅資料",
+ contentStructureOnlyHint: "僅建立表和物件結構,不複製資料",
+ contentDataOnlyHint: "僅複製資料到已存在之目標表",
+ objects: "傳輸物件",
+ searchObjects: "搜尋物件名稱...",
+ noObjects: "暫無物件",
+ objectTypeTable: "表",
+ objectTypeView: "檢視",
+ objectTypeMaterializedView: "具體化檢視",
+ objectTypeProcedure: "預存程序",
+ objectTypeFunction: "函式",
+ objectTypeTrigger: "觸發程序",
+ objectTypeSequence: "序列",
+ objectTypeEvent: "事件",
+ objectDataOnlyDisabled: "僅資料模式不傳輸非表物件",
+ objectCrossFamilyDisabled: "跨庫僅支援序列傳輸(純DDL;檢視查詢體無法翻譯)",
+ crossFamilyViewHint: "跨庫檢視傳輸:請同時選擇檢視依賴的表,或確保目標庫已存在這些表",
+ objectUnsupportedDisabled: "目前資料庫不支援該物件類型傳輸",
+ skippedExistingObjects: "跳過 {count} 個已存在物件",
+ dataWriteMode: "資料寫入方式",
source: "來源",
target: "目標",
sourceConnection: "來源連線",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index d03a605076..1bc0b78a84 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -719,6 +719,9 @@ export type {
TransferRequest,
TransferProgress,
TransferMode,
+ TransferContent,
+ TransferObjectKind,
+ TransferObjectSelection,
TransferTableNameCase,
TransferOwnershipPolicy,
TransferOwnershipPreview,
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 971a9fcd39..17d27108de 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -692,7 +692,7 @@ export async function getTableComment(_connectionId: string, _database: string,
throw new Error("Table comment lookup is not available in the web backend");
}
-export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: SidebarObjectKind[], filter?: string, limit?: number, offset?: number, catalog?: string): Promise<ObjectInfo[]> {
+export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string): Promise<ObjectInfo[]> {
return get(
`/api/schema/objects?${qs({
connection_id: connectionId,
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index da66bdde27..ab53e0db4f 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -974,7 +974,7 @@ export async function getTableComment(connectionId: string, database: string, sc
});
}
-export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: SidebarObjectKind[], filter?: string, limit?: number, offset?: number, catalog?: string): Promise<ObjectInfo[]> {
+export async function listObjects(connectionId: string, database: string, schema: string, objectTypes?: (SidebarObjectKind | "EVENT")[], filter?: string, limit?: number, offset?: number, catalog?: string): Promise<ObjectInfo[]> {
return invoke("list_objects", {
connectionId,
database,
@@ -3301,6 +3301,13 @@ export async function listenSqlFileProgress(handler: (progress: SqlFileProgress)
export type TransferMode = "append" | "overwrite" | "upsert";
export type TransferTableNameCase = "preserve" | "lower" | "upper";
export type TransferOwnershipPolicy = "preserve" | "skip" | "reassignMissing";
+export type TransferContent = "structureAndData" | "structureOnly" | "dataOnly";
+export type TransferObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT";
+
+export interface TransferObjectSelection {
+ objectType: TransferObjectKind;
+ names: string[];
+}
export interface TransferRequest {
transferId: string;
@@ -3314,6 +3321,8 @@ export interface TransferRequest {
targetCatalog?: string;
tables: string[];
createTable: boolean;
+ content: TransferContent;
+ objects: TransferObjectSelection[];
mode: TransferMode;
targetTableNameCase: TransferTableNameCase;
ownershipPolicy?: TransferOwnershipPolicy;
diff --git a/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts b/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts
new file mode 100644
index 0000000000..3ae0e79dfc
--- /dev/null
+++ b/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { transferObjectFamily, transferObjectKindsForDatabase, isSameTransferFamily, crossFamilyTransferableKinds, TransferObjectFamily } from "@/lib/database/transferObjectKinds";
+
+describe("transferObjectKinds", () => {
+ it("groups databases into transfer families", () => {
+ expect(transferObjectFamily("mysql")).toBe(TransferObjectFamily.Mysql);
+ expect(transferObjectFamily("kingbase")).toBe(TransferObjectFamily.Postgres);
+ expect(transferObjectFamily("dameng")).toBe(TransferObjectFamily.Oracle);
+ expect(transferObjectFamily("sqlserver")).toBe(TransferObjectFamily.SqlServer);
+ expect(transferObjectFamily("sqlite")).toBeUndefined();
+ });
+
+ it("returns per-family object kinds", () => {
+ expect(transferObjectKindsForDatabase("mysql")).toEqual(["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT"]);
+ expect(transferObjectKindsForDatabase("postgres")).toContain("SEQUENCE");
+ expect(transferObjectKindsForDatabase("dameng")).toContain("TRIGGER");
+ expect(transferObjectKindsForDatabase("sqlserver")).toEqual(["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"]);
+ expect(transferObjectKindsForDatabase("sqlite")).toEqual([]);
+ });
+
+ it("detects same-family transfers", () => {
+ expect(isSameTransferFamily("mysql", "mysql")).toBe(true);
+ expect(isSameTransferFamily("mysql", "postgres")).toBe(false);
+ expect(isSameTransferFamily("oracle", "dameng")).toBe(true);
+ expect(isSameTransferFamily("postgres", "sqlite")).toBe(false);
+ expect(isSameTransferFamily("sqlserver", "sqlserver")).toBe(true);
+ expect(isSameTransferFamily("sqlserver", "mysql")).toBe(false);
+ });
+
+ it("limits cross-family transferable kinds to sequences only", () => {
+ // mysql participates: VIEW is disabled (query body not translated) and
+ // mysql has no sequences on either side
+ expect(crossFamilyTransferableKinds("mysql", "dameng")).toEqual([]);
+ expect(crossFamilyTransferableKinds("dameng", "mysql")).toEqual([]);
+ expect(crossFamilyTransferableKinds("mysql", "sqlserver")).toEqual([]);
+ // sqlserver <-> dameng: sequences only (plain DDL)
+ expect(crossFamilyTransferableKinds("sqlserver", "dameng")).toEqual(["SEQUENCE"]);
+ expect(crossFamilyTransferableKinds("dameng", "sqlserver")).toEqual(["SEQUENCE"]);
+ // same family: all source kinds
+ const same = crossFamilyTransferableKinds("mysql", "mysql");
+ expect(same).toContain("TRIGGER");
+ expect(same).toContain("EVENT");
+ // unsupported db
+ expect(crossFamilyTransferableKinds("sqlite", "mysql")).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/lib/database/transferObjectKinds.ts b/apps/desktop/src/lib/database/transferObjectKinds.ts
new file mode 100644
index 0000000000..e8812612ea
--- /dev/null
+++ b/apps/desktop/src/lib/database/transferObjectKinds.ts
@@ -0,0 +1,86 @@
+import type { DatabaseType } from "@/types/database";
+
+export enum TransferObjectFamily {
+ Mysql = "mysql",
+ Postgres = "postgres",
+ Oracle = "oracle",
+ SqlServer = "sqlserver",
+}
+
+export type TransferObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT";
+
+const MYSQL_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT"];
+const POSTGRES_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
+const ORACLE_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
+const SQLSERVER_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
+
+const FAMILY_BY_DB = new Map<DatabaseType, TransferObjectFamily>([
+ ["mysql", TransferObjectFamily.Mysql],
+ ["postgres", TransferObjectFamily.Postgres],
+ ["kingbase", TransferObjectFamily.Postgres],
+ ["gaussdb", TransferObjectFamily.Postgres],
+ ["kwdb", TransferObjectFamily.Postgres],
+ ["opengauss", TransferObjectFamily.Postgres],
+ ["oracle", TransferObjectFamily.Oracle],
+ ["dameng", TransferObjectFamily.Oracle],
+ ["oceanbase-oracle", TransferObjectFamily.Oracle],
+ ["sqlserver", TransferObjectFamily.SqlServer],
+]);
+
+export function transferObjectFamily(dbType?: DatabaseType): TransferObjectFamily | undefined {
+ return dbType ? FAMILY_BY_DB.get(dbType) : undefined;
+}
+
+export function isSameTransferFamily(a?: DatabaseType, b?: DatabaseType): boolean {
+ const fa = transferObjectFamily(a);
+ const fb = transferObjectFamily(b);
+ return !!fa && fa === fb;
+}
+
+export function transferObjectKindsForDatabase(dbType?: DatabaseType): TransferObjectKind[] {
+ switch (transferObjectFamily(dbType)) {
+ case TransferObjectFamily.Mysql:
+ return [...MYSQL_KINDS];
+ case TransferObjectFamily.Postgres:
+ return [...POSTGRES_KINDS];
+ case TransferObjectFamily.Oracle:
+ return [...ORACLE_KINDS];
+ case TransferObjectFamily.SqlServer:
+ return [...SQLSERVER_KINDS];
+ default:
+ return [];
+ }
+}
+
+/**
+ * Kinds selectable for a transfer between the two databases. Within one
+ * family every kind of the source is allowed; across families only
+ * sequences are allowed (plain DDL without a query body), and only when
+ * both sides support the type. Views are excluded: the backend rewrites
+ * only the DDL wrapper, quoting and schema qualifiers, not the view
+ * query body, so cross-family view bodies could run unchanged on an
+ * incompatible target.
+ */
+export function crossFamilyTransferableKinds(a?: DatabaseType, b?: DatabaseType): TransferObjectKind[] {
+ if (isSameTransferFamily(a, b)) {
+ return transferObjectKindsForDatabase(a);
+ }
+ const aFam = transferObjectFamily(a);
+ const bFam = transferObjectFamily(b);
+ // Cross-family DDL conversion is only implemented and validated for
+ // MySQL / SQL Server / Oracle families. Postgres-family sources or
+ // targets (postgres/kingbase/gaussdb/kwdb/opengauss) are not supported
+ // by the cross-family executor, so nothing is selectable there.
+ const supported = new Set([TransferObjectFamily.Mysql, TransferObjectFamily.SqlServer, TransferObjectFamily.Oracle]);
+ if (!aFam || !bFam || !supported.has(aFam) || !supported.has(bFam)) return [];
+ const aKinds = transferObjectKindsForDatabase(a);
+ const bKinds = transferObjectKindsForDatabase(b);
+ // Cross-family VIEW transfer is disabled: the backend only rewrites the
+ // DDL wrapper/quoting/schema qualifiers and cannot translate the view
+ // query body (IFNULL, TOP, GETDATE, … would run unchanged on an
+ // incompatible target). Sequences are plain DDL and remain transferable
+ // when both sides support them.
+ const allowed: TransferObjectKind[] = [];
+ if (aKinds.includes("SEQUENCE") && bKinds.includes("SEQUENCE")) allowed.push("SEQUENCE");
+ return allowed;
+}
diff --git a/crates/dbx-core/src/db/mysql.rs b/crates/dbx-core/src/db/mysql.rs
index b2217d04f7..5feffe0191 100644
--- a/crates/dbx-core/src/db/mysql.rs
+++ b/crates/dbx-core/src/db/mysql.rs
@@ -2798,6 +2798,14 @@ fn wants_routine_objects(object_types: Option<&[String]>) -> bool {
requested_object_type(object_types, "PROCEDURE") || requested_object_type(object_types, "FUNCTION")
}
+fn wants_trigger_objects(object_types: Option<&[String]>) -> bool {
+ requested_object_type(object_types, "TRIGGER")
+}
+
+fn wants_event_objects(object_types: Option<&[String]>) -> bool {
+ requested_object_type(object_types, "EVENT")
+}
+
fn sql_pagination(limit: Option<usize>, offset: Option<usize>) -> String {
limit.map_or_else(String::new, |limit| format!(" LIMIT {limit} OFFSET {}", offset.unwrap_or(0)))
}
@@ -2888,6 +2896,32 @@ fn row_to_object(row: &mysql_async::Row, database: &str) -> ObjectInfo {
}
}
+fn list_triggers_objects_sql(database: &str) -> String {
+ format!(
+ "SELECT TRIGGER_NAME AS object_name, 'TRIGGER' AS object_type, NULL AS object_comment, \
+ CREATED AS created_at, NULL AS updated_at, \
+ TRIGGER_SCHEMA AS parent_schema, EVENT_OBJECT_TABLE AS parent_name, \
+ 5 AS sort_order \
+ FROM information_schema.TRIGGERS \
+ WHERE TRIGGER_SCHEMA = {} \
+ ORDER BY object_name",
+ quote_value(database)
+ )
+}
+
+fn list_events_objects_sql(database: &str) -> String {
+ format!(
+ "SELECT EVENT_NAME AS object_name, 'EVENT' AS object_type, NULL AS object_comment, \
+ CREATED AS created_at, LAST_ALTERED AS updated_at, \
+ EVENT_SCHEMA AS parent_schema, NULL AS parent_name, \
+ 6 AS sort_order \
+ FROM information_schema.EVENTS \
+ WHERE EVENT_SCHEMA = {} \
+ ORDER BY object_name",
+ quote_value(database)
+ )
+}
+
pub struct PagedObjectList {
pub objects: Vec<ObjectInfo>,
pub paging_applied: bool,
@@ -2985,6 +3019,40 @@ pub async fn list_objects(
}
}
+ if wants_trigger_objects(object_types) {
+ let triggers_sql = list_triggers_objects_sql(database);
+ match conn.query_iter(&triggers_sql).await {
+ Ok(result) => match result.collect_and_drop::<mysql_async::Row>().await {
+ Ok(trigger_rows) => {
+ objects.extend(trigger_rows.iter().map(|row| row_to_object(row, database)));
+ }
+ Err(e) => {
+ log::warn!("Skipping triggers for database `{}` in object browser: {}", database, e);
+ }
+ },
+ Err(e) => {
+ log::warn!("Skipping triggers for database `{}` in object browser: {}", database, e);
+ }
+ }
+ }
+
+ if wants_event_objects(object_types) {
+ let events_sql = list_events_objects_sql(database);
+ match conn.query_iter(&events_sql).await {
+ Ok(result) => match result.collect_and_drop::<mysql_async::Row>().await {
+ Ok(event_rows) => {
+ objects.extend(event_rows.iter().map(|row| row_to_object(row, database)));
+ }
+ Err(e) => {
+ log::warn!("Skipping events for database `{}` in object browser: {}", database, e);
+ }
+ },
+ Err(e) => {
+ log::warn!("Skipping events for database `{}` in object browser: {}", database, e);
+ }
+ }
+ }
+
Ok(PagedObjectList { objects, paging_applied })
}
@@ -5179,6 +5247,19 @@ mod tests {
assert!(sql.contains("TRIGGER_SCHEMA = 'app'"));
}
+ #[test]
+ fn lists_triggers_and_events_via_information_schema() {
+ let sql = list_triggers_objects_sql("shop");
+ assert!(sql.contains("information_schema.TRIGGERS"));
+ assert!(sql.contains("TRIGGER_SCHEMA = 'shop'"));
+ let sql = list_events_objects_sql("shop");
+ assert!(sql.contains("information_schema.EVENTS"));
+ assert!(sql.contains("EVENT_SCHEMA = 'shop'"));
+ assert!(wants_trigger_objects(Some(&["TRIGGER".to_string()])));
+ assert!(!wants_trigger_objects(Some(&["TABLE".to_string()])));
+ assert!(wants_event_objects(Some(&["EVENT".to_string()])));
+ }
+
#[test]
fn mysql_completion_like_pattern_uses_prefix_by_default() {
assert_eq!(mysql_completion_like_pattern("Temp", Some(&CompletionAssistantMatchMode::Prefix)), "Temp%");
diff --git a/crates/dbx-core/src/transfer.rs b/crates/dbx-core/src/transfer.rs
index 03b9b30a9d..dde1f31dfd 100644
--- a/crates/dbx-core/src/transfer.rs
+++ b/crates/dbx-core/src/transfer.rs
@@ -75,6 +75,84 @@ pub enum TransferOwnershipPolicy {
ReassignMissing,
}
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum TransferContent {
+ #[default]
+ StructureAndData,
+ StructureOnly,
+ DataOnly,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum TransferObjectKind {
+ #[default]
+ Table,
+ View,
+ MaterializedView,
+ Procedure,
+ Function,
+ Trigger,
+ Sequence,
+ Event,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct TransferObjectSelection {
+ pub object_type: TransferObjectKind,
+ pub names: Vec<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TransferObjectFamily {
+ Mysql,
+ Postgres,
+ Oracle,
+ SqlServer,
+}
+
+pub fn transfer_object_family(db_type: &DatabaseType) -> Option<TransferObjectFamily> {
+ match db_type {
+ DatabaseType::Mysql => Some(TransferObjectFamily::Mysql),
+ DatabaseType::Postgres
+ | DatabaseType::Kingbase
+ | DatabaseType::Gaussdb
+ | DatabaseType::Kwdb
+ | DatabaseType::OpenGauss => Some(TransferObjectFamily::Postgres),
+ DatabaseType::Oracle | DatabaseType::Dameng | DatabaseType::OceanbaseOracle => {
+ Some(TransferObjectFamily::Oracle)
+ }
+ DatabaseType::SqlServer => Some(TransferObjectFamily::SqlServer),
+ _ => None,
+ }
+}
+
+pub fn is_same_transfer_family(a: &DatabaseType, b: &DatabaseType) -> bool {
+ match (transfer_object_family(a), transfer_object_family(b)) {
+ (Some(fa), Some(fb)) => fa == fb,
+ _ => false,
+ }
+}
+
+pub fn transfer_object_kinds_for_family(family: &TransferObjectFamily) -> Vec<TransferObjectKind> {
+ use TransferObjectKind::*;
+ match family {
+ TransferObjectFamily::Mysql => vec![Table, View, Procedure, Function, Trigger, Event],
+ TransferObjectFamily::Postgres => vec![Table, View, MaterializedView, Procedure, Function, Trigger, Sequence],
+ TransferObjectFamily::Oracle => vec![Table, View, MaterializedView, Procedure, Function, Trigger, Sequence],
+ TransferObjectFamily::SqlServer => vec![Table, View, Procedure, Function, Trigger, Sequence],
+ }
+}
+
+pub fn transfer_object_kinds(db_type: &DatabaseType) -> Vec<TransferObjectKind> {
+ match transfer_object_family(db_type) {
+ Some(family) => transfer_object_kinds_for_family(&family),
+ None => Vec::new(),
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferRequest {
@@ -90,6 +168,10 @@ pub struct TransferRequest {
pub tables: Vec<String>,
pub create_table: bool,
#[serde(default)]
+ pub content: TransferContent,
+ #[serde(default)]
+ pub objects: Vec<TransferObjectSelection>,
+ #[serde(default)]
pub mode: TransferMode,
#[serde(default)]
pub target_table_name_case: TransferTableNameCase,
@@ -257,6 +339,354 @@ pub fn validate_transfer_target_table_names(request: &TransferRequest) -> Result
Ok(())
}
+/// Kinds that may be transferred between different database families.
+/// Only DDL shapes that can be mechanically rewritten are allowed:
+/// views (CREATE ... VIEW ... AS SELECT) and sequences (CREATE SEQUENCE).
+/// Sequences additionally require both sides to support the type (MySQL does not).
+/// Cross-family transfer is only supported between the MySQL, SQL Server and
+/// Oracle/Dameng families; the Postgres family is not a validated source or
+/// target for the cross-family DDL pipeline (the executor rejects it).
+pub fn cross_family_transferable_object_kinds(source: &DatabaseType, target: &DatabaseType) -> Vec<TransferObjectKind> {
+ use TransferObjectKind::*;
+ if is_same_transfer_family(source, target) {
+ return transfer_object_kinds(source);
+ }
+ // Narrow the matrix to validated directions: MySQL, SQL Server and
+ // Oracle/Dameng may act as either side. Postgres (and anything else) is
+ // excluded — the executor rejects Postgres sources and no dialect-aware
+ // conversion is validated for it.
+ let family_supported = |db_type: &DatabaseType| {
+ matches!(
+ transfer_object_family(db_type),
+ Some(TransferObjectFamily::Mysql)
+ | Some(TransferObjectFamily::SqlServer)
+ | Some(TransferObjectFamily::Oracle)
+ )
+ };
+ if !family_supported(source) || !family_supported(target) {
+ return Vec::new();
+ }
+ // Cross-family VIEW transfer is disabled: convert_cross_family_object_ddl
+ // only rewrites the DDL wrapper, identifier quoting and schema qualifiers —
+ // it does not translate the view query body, so source-specific constructs
+ // (IFNULL, TOP, GETDATE, …) would execute unchanged on an incompatible
+ // target. Only sequences are allowed: their CREATE SEQUENCE statements are
+ // plain DDL (no query body) and the small set of dialect differences
+ // (AS <type>, NOCYCLE/NOCACHE) is converted and tested.
+ let source_kinds = transfer_object_kinds(source);
+ let target_kinds = transfer_object_kinds(target);
+ let mut allowed = Vec::new();
+ if source_kinds.contains(&Sequence) && target_kinds.contains(&Sequence) {
+ allowed.push(Sequence);
+ }
+ allowed
+}
+
+/// Rewrites a source DDL fragment to the target family's quoting style and
+/// schema qualifier. Prefix normalization (DEFINER/ALGORITHM/FORCE/WITH
+/// SCHEMABINDING/AS <type>) is applied per source family.
+pub fn convert_cross_family_object_ddl(
+ source_family: &TransferObjectFamily,
+ target_family: &TransferObjectFamily,
+ kind: &TransferObjectKind,
+ source_schema: &str,
+ target_schema: &str,
+ ddl: &str,
+) -> String {
+ let mut sql = ddl.trim().to_string();
+ match kind {
+ TransferObjectKind::View => match source_family {
+ TransferObjectFamily::Mysql => {
+ sql = strip_mysql_definer(&sql);
+ sql = strip_sql_view_prefix(&sql);
+ }
+ TransferObjectFamily::Oracle => {
+ sql = strip_sql_view_prefix(&sql);
+ }
+ TransferObjectFamily::SqlServer => {
+ sql = strip_sqlserver_view_with_clause(&sql);
+ }
+ _ => {}
+ },
+ TransferObjectKind::Sequence => match source_family {
+ TransferObjectFamily::SqlServer => {
+ sql = strip_sqlserver_sequence_as_type(&sql);
+ }
+ TransferObjectFamily::Oracle if target_family == &TransferObjectFamily::SqlServer => {
+ sql = sql.replace("NOCYCLE", "NO CYCLE").replace("NOCACHE", "NO CACHE");
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ // Mask string literals and comments before any identifier/schema
+ // rewrite, then restore them afterwards: regexes that re-quote
+ // identifiers must never touch text inside strings or comments. MySQL
+ // double-quoted text is a string literal (unless ANSI_QUOTES is on).
+ let (masked, restores) = protect_sql_literals(&sql, matches!(source_family, TransferObjectFamily::Mysql));
+ sql = rewrite_identifiers_to_target(&masked, target_family);
+ if !source_schema.is_empty() && !target_schema.is_empty() && !source_schema.eq_ignore_ascii_case(target_schema) {
+ sql = rewrite_cross_family_schema_qualifier(&sql, target_family, source_schema, target_schema);
+ }
+ if kind == &TransferObjectKind::View {
+ sql = qualify_cross_family_view_target(&sql, target_family, target_schema);
+ }
+ for (placeholder, original) in restores {
+ sql = sql.replace(&placeholder, &original);
+ }
+ sql
+}
+
+/// Locates string literals and comments in SQL: single-quoted strings
+/// (with `''` and backslash escapes), MySQL double-quoted strings when
+/// `double_quote_is_string` is set, `--`/`#` line comments and `/* */`
+/// block comments. Returns byte ranges `(start, end)` of those spans.
+fn sql_non_code_spans(sql: &str, double_quote_is_string: bool) -> Vec<(usize, usize)> {
+ let bytes = sql.as_bytes();
+ let mut spans = Vec::new();
+ let mut i = 0;
+ while i < bytes.len() {
+ let b = bytes[i];
+ let starts_non_code = match b {
+ b'\'' => true,
+ b'"' if double_quote_is_string => true,
+ b'-' if i + 1 < bytes.len() && bytes[i + 1] == b'-' => true,
+ b'#' => true, // MySQL line comment
+ b'/' if i + 1 < bytes.len() && bytes[i + 1] == b'*' => true,
+ _ => false,
+ };
+ if !starts_non_code {
+ i += 1;
+ continue;
+ }
+ let start = i;
+ i = match b {
+ b'\'' | b'"' => {
+ i += 1;
+ while i < bytes.len() {
+ if bytes[i] == b'\\' && i + 1 < bytes.len() {
+ i += 2; // backslash escape (MySQL style)
+ continue;
+ }
+ if bytes[i] == b && i + 1 < bytes.len() && bytes[i + 1] == b {
+ i += 2; // '' / "" doubled quote
+ continue;
+ }
+ if bytes[i] == b {
+ i += 1;
+ break;
+ }
+ i += 1;
+ }
+ i
+ }
+ b'-' | b'#' => {
+ while i < bytes.len() && bytes[i] != b'\n' {
+ i += 1;
+ }
+ i
+ }
+ _ => {
+ i += 2; // /* ... */
+ while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
+ i += 1;
+ }
+ (i + 2).min(bytes.len())
+ }
+ };
+ spans.push((start, i));
+ }
+ spans
+}
+
+/// Applies `f` to every code span of `sql`; string literals and comments
+/// (see `sql_non_code_spans`) pass through verbatim so rewrites never touch
+/// text inside them.
+fn map_sql_code_spans<F>(sql: &str, double_quote_is_string: bool, mut f: F) -> String
+where
+ F: FnMut(&str) -> String,
+{
+ let spans = sql_non_code_spans(sql, double_quote_is_string);
+ let mut out = String::with_capacity(sql.len());
+ let mut prev = 0;
+ for (start, end) in spans {
+ if start > prev {
+ out.push_str(&f(&sql[prev..start]));
+ }
+ out.push_str(&sql[start..end]);
+ prev = end;
+ }
+ if prev < sql.len() {
+ out.push_str(&f(&sql[prev..]));
+ }
+ out
+}
+
+/// Masks string literals and comments with placeholders so subsequent regex
+/// rewrites cannot touch them, and returns the restore map to swap the
+/// original text back afterwards.
+fn protect_sql_literals(sql: &str, double_quote_is_string: bool) -> (String, Vec<(String, String)>) {
+ let spans = sql_non_code_spans(sql, double_quote_is_string);
+ let mut out = String::with_capacity(sql.len());
+ let mut restores = Vec::new();
+ let mut prev = 0;
+ for (start, end) in spans {
+ if start > prev {
+ out.push_str(&sql[prev..start]);
+ }
+ let placeholder = format!("__DBX_LIT_{}__", restores.len());
+ out.push_str(&placeholder);
+ restores.push((placeholder, sql[start..end].to_string()));
+ prev = end;
+ }
+ if prev < sql.len() {
+ out.push_str(&sql[prev..]);
+ }
+ (out, restores)
+}
+
+/// Aligns a cross-family view DDL with the target schema: the `CREATE VIEW`
+/// target and bare table references in the body (`FROM`/`JOIN`/`INTO`/`UPDATE`)
+/// are qualified with the target schema, matching how table transfer creates
+/// tables (`"schema"."table"`). References that already carry a prefix are left
+/// untouched. String literals and comments are preserved verbatim (see
+/// `map_sql_code_spans`).
+fn qualify_cross_family_view_target(sql: &str, target_family: &TransferObjectFamily, target_schema: &str) -> String {
+ if target_schema.is_empty() {
+ return sql.to_string();
+ }
+ let (open, close) = match target_family {
+ TransferObjectFamily::Mysql => ("`", "`"),
+ TransferObjectFamily::SqlServer => ("[", "]"),
+ TransferObjectFamily::Oracle => ("\"", "\""),
+ _ => return sql.to_string(),
+ };
+ let qo = regex::escape(open);
+ let qc = regex::escape(close);
+ // Identifiers may contain any characters (including CJK) except the
+ // closing quote of the target dialect, since every identifier has been
+ // normalized to the target quoting style by this point.
+ let ident = match target_family {
+ TransferObjectFamily::Mysql => r#"[^`]+"#,
+ TransferObjectFamily::SqlServer => r#"[^\]]+"#,
+ TransferObjectFamily::Oracle => r#"[^"]+"#,
+ _ => "[A-Za-z_][A-Za-z0-9_]*",
+ };
+ let create_re = Regex::new(&format!(r"(?i)\bCREATE\s+VIEW\s+(?:{qo}({ident}){qc}\.)?{qo}({ident}){qc}")).unwrap();
+ let mut out = create_re
+ .replace_all(sql, |caps: &regex::Captures| {
+ let name = &caps[2];
+ if matches!(caps.get(1), Some(m) if !m.as_str().is_empty()) {
+ caps[0].to_string()
+ } else {
+ format!("CREATE VIEW {open}{target_schema}{close}.{open}{name}{close}")
+ }
+ })
+ .to_string();
+ // bare references after FROM/JOIN/INTO/UPDATE/TABLE get the schema prefix;
+ // already-prefixed references (group 1) stay as-is
+ let ref_re =
+ Regex::new(&format!(r"(?i)\b(from|join|into|update|table)\s+(?:{qo}({ident}){qc}\.)?{qo}({ident}){qc}"))
+ .unwrap();
+ out = ref_re
+ .replace_all(&out, |caps: &regex::Captures| {
+ let name = &caps[3];
+ if matches!(caps.get(2), Some(m) if !m.as_str().is_empty()) {
+ caps[0].to_string()
+ } else {
+ format!("{} {open}{target_schema}{close}.{open}{name}{close}", &caps[1])
+ }
+ })
+ .to_string();
+ out
+}
+
+/// Collapses `CREATE [ALGORITHM=..] [DEFINER=..] [SQL SECURITY ..] VIEW`,
+/// `CREATE OR REPLACE [FORCE] [NONEDITIONABLE] VIEW` and plain `CREATE VIEW`
+/// into a bare `CREATE VIEW` prefix usable on every target family.
+fn strip_sql_view_prefix(sql: &str) -> String {
+ if let Some(pos) = sql.find(" VIEW ") {
+ let head = &sql[..pos];
+ if head.trim_start().starts_with("CREATE") {
+ return format!("CREATE VIEW{}", &sql[pos + 5..]);
+ }
+ }
+ sql.to_string()
+}
+
+/// Removes `WITH SCHEMABINDING` between the view name and `AS` in SQL Server
+/// view definitions.
+fn strip_sqlserver_view_with_clause(sql: &str) -> String {
+ let re = Regex::new(r"(?i)\s+WITH\s+SCHEMABINDING\s+").unwrap();
+ map_sql_code_spans(sql, false, |code| re.replace_all(code, " ").to_string())
+}
+
+/// Removes the ` AS <type>` clause from a SQL Server CREATE SEQUENCE so the
+/// DDL fits Dameng/Oracle sequence syntax.
+fn strip_sqlserver_sequence_as_type(sql: &str) -> String {
+ let re =
+ Regex::new(r"(?i)\s+AS\s+(?:BIGINT|INT|SMALLINT|TINYINT|DECIMAL\s*\([^)]*\)|NUMERIC\s*\([^)]*\))\s+").unwrap();
+ map_sql_code_spans(sql, false, |code| re.replace_all(code, " ").to_string())
+}
+
+/// Rewrites backtick / double-quote / bracket identifier quoting to the
+/// target family's style. Only identifiers in code positions are rewritten:
+/// string literals and comments are preserved verbatim (see
+/// `map_sql_code_spans`). The source family decides whether double-quoted
+/// text is a string literal (MySQL, unless ANSI_QUOTES is on) or an
+/// identifier (SQL Server / Oracle).
+fn rewrite_identifiers_to_target(sql: &str, target: &TransferObjectFamily) -> String {
+ let (open, close, pattern) = match target {
+ TransferObjectFamily::Mysql => ("`", "`", r#""([^"]+)"|\[([^\]]+)\]"#),
+ TransferObjectFamily::SqlServer => ("[", "]", r#"`([^`]+)`|"([^"]+)""#),
+ TransferObjectFamily::Oracle => ("\"", "\"", r#"`([^`]+)`|\[([^\]]+)\]"#),
+ _ => return sql.to_string(),
+ };
+ let re = Regex::new(pattern).unwrap();
+ re.replace_all(sql, |caps: &regex::Captures| {
+ let name = caps.get(1).map(|m| m.as_str()).or_else(|| caps.get(2).map(|m| m.as_str())).unwrap_or("");
+ format!("{open}{name}{close}")
+ })
+ .to_string()
+}
+
+/// Rewrites `{quote}{source_schema}{quote}.` qualifiers to the target schema
+/// in the target family's quoting style.
+fn rewrite_cross_family_schema_qualifier(
+ sql: &str,
+ target: &TransferObjectFamily,
+ source_schema: &str,
+ target_schema: &str,
+) -> String {
+ let (open, close) = match target {
+ TransferObjectFamily::Mysql => ("`", "`"),
+ TransferObjectFamily::SqlServer => ("[", "]"),
+ TransferObjectFamily::Oracle => ("\"", "\""),
+ _ => return sql.to_string(),
+ };
+ let source = format!("{open}{}{close}.", regex::escape(source_schema));
+ let target = format!("{open}{target_schema}{close}.");
+ sql.replace(&source, &target)
+}
+
+pub fn validate_transfer_request(request: &TransferRequest) -> Result<(), String> {
+ validate_transfer_target_table_names(request)?;
+ if matches!(request.content, TransferContent::DataOnly) && !request.objects.is_empty() {
+ return Err("仅数据模式不传输非表对象".to_string());
+ }
+ for selection in &request.objects {
+ if selection.names.is_empty() {
+ return Err(format!("Object selection for {:?} is empty", selection.object_type));
+ }
+ for name in &selection.names {
+ if name.trim().is_empty() || name.contains('\0') {
+ return Err(format!("Invalid object name: {name:?}"));
+ }
+ }
+ }
+ Ok(())
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
struct ResolvedTransferTargetTable {
name: String,
@@ -383,6 +813,332 @@ fn quote_string_literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
+/// Returns a SQL statement selecting 1 row when `name` exists in `schema`
+/// on the target side; None-kind support per family mirrors
+/// `transfer_object_kinds`.
+pub fn target_object_exists_sql(
+ db_type: &DatabaseType,
+ schema: &str,
+ name: &str,
+ kind: &TransferObjectKind,
+) -> Result<String, String> {
+ let schema = quote_string_literal(schema);
+ let name = quote_string_literal(name);
+ let q = |literal: &str| literal.to_string();
+ let sql = match (transfer_object_family(db_type), kind) {
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Table | TransferObjectKind::View) => format!(
+ "SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = {schema} AND TABLE_NAME = {name} \
+ AND TABLE_TYPE {} 'VIEW'",
+ if matches!(kind, TransferObjectKind::View) { "=" } else { "<>" }
+ ),
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Procedure | TransferObjectKind::Function) => format!(
+ "SELECT 1 FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = {schema} AND ROUTINE_NAME = {name} \
+ AND ROUTINE_TYPE = {}",
+ q(if matches!(kind, TransferObjectKind::Procedure) { "'PROCEDURE'" } else { "'FUNCTION'" })
+ ),
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Trigger) => format!(
+ "SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = {schema} AND TRIGGER_NAME = {name}"
+ ),
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Event) => {
+ format!("SELECT 1 FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {schema} AND EVENT_NAME = {name}")
+ }
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::View | TransferObjectKind::MaterializedView) => {
+ format!(
+ "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind {}",
+ if matches!(kind, TransferObjectKind::MaterializedView) { "= 'm'" } else { "= 'v'" }
+ )
+ }
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Table) => format!(
+ "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind = 'r'"
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Procedure | TransferObjectKind::Function) => {
+ format!(
+ "SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
+ WHERE n.nspname = {schema} AND p.proname = {name}"
+ )
+ }
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Sequence) => format!(
+ "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind = 'S'"
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Trigger) => format!(
+ "SELECT 1 FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid \
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND t.tgname = {name} AND NOT t.tgisinternal"
+ ),
+ (
+ Some(TransferObjectFamily::Oracle),
+ TransferObjectKind::View
+ | TransferObjectKind::MaterializedView
+ | TransferObjectKind::Procedure
+ | TransferObjectKind::Function
+ | TransferObjectKind::Trigger
+ | TransferObjectKind::Sequence,
+ ) => format!(
+ "SELECT 1 FROM ALL_OBJECTS WHERE OWNER = {schema} AND OBJECT_NAME = {name} AND OBJECT_TYPE = {}",
+ q(match kind {
+ TransferObjectKind::View => "'VIEW'",
+ TransferObjectKind::MaterializedView => "'MATERIALIZED VIEW'",
+ TransferObjectKind::Procedure => "'PROCEDURE'",
+ TransferObjectKind::Function => "'FUNCTION'",
+ TransferObjectKind::Trigger => "'TRIGGER'",
+ _ => "'SEQUENCE'",
+ })
+ ),
+ (
+ Some(TransferObjectFamily::SqlServer),
+ TransferObjectKind::Table
+ | TransferObjectKind::View
+ | TransferObjectKind::Procedure
+ | TransferObjectKind::Function
+ | TransferObjectKind::Trigger
+ | TransferObjectKind::Sequence,
+ ) => format!(
+ "SELECT 1 FROM sys.objects o JOIN sys.schemas s ON s.schema_id = o.schema_id \
+ WHERE s.name = {schema} AND o.name = {name} AND o.type IN ({})",
+ q(match kind {
+ TransferObjectKind::Table => "'U'",
+ TransferObjectKind::View => "'V'",
+ TransferObjectKind::Procedure => "'P'",
+ TransferObjectKind::Function => "'FN','IF','TF','FS','FT'",
+ TransferObjectKind::Trigger => "'TR'",
+ _ => "'SO'",
+ })
+ ),
+ _ => return Err(format!("Object existence check not supported for {:?} {:?}", db_type, kind)),
+ };
+ Ok(sql)
+}
+
+/// Remove `DEFINER=`user`@`host`` tokens from MySQL DDL (they are not
+/// transferable and frequently reference accounts that don't exist on target).
+pub fn strip_mysql_definer(ddl: &str) -> String {
+ let re = Regex::new(r"(?i)\bDEFINER\s*=\s*`[^`]*`@`[^`]*`\s*").unwrap();
+ re.replace_all(ddl, "").to_string()
+}
+
+/// Rewrite backtick-qualified `schema`.`name` references from `source_schema`
+/// to `target_schema` in MySQL DDL.
+pub fn rewrite_mysql_schema_qualifier(ddl: &str, source_schema: &str, target_schema: &str) -> String {
+ if source_schema == target_schema || source_schema.is_empty() {
+ return ddl.to_string();
+ }
+ let re = Regex::new(&format!(r"`{}`\.", regex::escape(source_schema))).unwrap();
+ re.replace_all(ddl, &format!("`{}`.", target_schema)).to_string()
+}
+
+pub fn mysql_trigger_ddl(
+ schema: &str,
+ name: &str,
+ timing: &str,
+ manipulation: &str,
+ table: &str,
+ statement: &str,
+) -> String {
+ format!(
+ "CREATE TRIGGER `{name}` {timing} {manipulation} ON `{schema}`.`{table}` FOR EACH ROW {statement}",
+ name = name,
+ timing = timing,
+ manipulation = manipulation,
+ schema = schema,
+ table = table,
+ statement = statement.trim()
+ )
+}
+
+pub fn mysql_event_ddl(_schema: &str, name: &str, status: &str, schedule: &str, body: &str) -> String {
+ format!(
+ "CREATE EVENT `{name}` ON SCHEDULE {schedule} {status} DO {body}",
+ name = name,
+ schedule = schedule,
+ status = status,
+ body = body.trim()
+ )
+}
+
+/// Builds the query that fetches DDL for one MySQL object.
+/// - View/Procedure/Function → `SHOW CREATE ...`
+/// - Trigger → information_schema.TRIGGERS row (timing/manipulation/table/
+/// statement) via `mysql_trigger_ddl`.
+/// - Event → information_schema.EVENTS row via `mysql_event_ddl`.
+pub fn mysql_object_source_query(kind: &TransferObjectKind, database: &str, name: &str) -> Result<String, String> {
+ let db = quote_string_literal(database);
+ let n = quote_string_literal(name);
+ let ddl = match kind {
+ TransferObjectKind::View => format!("SHOW CREATE VIEW `{database}`.`{name}`"),
+ TransferObjectKind::Procedure => format!("SHOW CREATE PROCEDURE `{database}`.`{name}`"),
+ TransferObjectKind::Function => format!("SHOW CREATE FUNCTION `{database}`.`{name}`"),
+ TransferObjectKind::Trigger => format!(
+ "SELECT TRIGGER_NAME, ACTION_TIMING, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_STATEMENT \
+ FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = {db} AND TRIGGER_NAME = {n}"
+ ),
+ TransferObjectKind::Event => format!(
+ "SELECT EVENT_NAME, STATUS, EXECUTE_AT, INTERVAL_VALUE, INTERVAL_FIELD, EVENT_DEFINITION \
+ FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {db} AND EVENT_NAME = {n}"
+ ),
+ _ => return Err(format!("MySQL object source not supported for {:?}", kind)),
+ };
+ Ok(ddl)
+}
+
+/// Maps a MySQL DDL query result row to a single DDL string.
+/// SHOW CREATE column index: view=1, routine=2 (same convention as
+/// `schema::mysql_object_source_ddl_column_index`); triggers and events are
+/// assembled from information_schema cells.
+pub fn mysql_object_ddl_from_result(
+ kind: &TransferObjectKind,
+ database: &str,
+ rows: &[Vec<serde_json::Value>],
+) -> Result<String, String> {
+ let row = rows.first().ok_or_else(|| format!("No rows returned for MySQL {:?} DDL", kind))?;
+ let cell = |idx: usize| -> Result<&str, String> {
+ row.get(idx)
+ .and_then(|value| value.as_str())
+ .ok_or_else(|| format!("Missing column {idx} in MySQL {:?} DDL result", kind))
+ };
+ match kind {
+ TransferObjectKind::View => Ok(cell(1)?.to_string()),
+ TransferObjectKind::Procedure | TransferObjectKind::Function => Ok(cell(2)?.to_string()),
+ TransferObjectKind::Trigger => {
+ let name = cell(0)?;
+ let timing = cell(1)?;
+ let manipulation = cell(2)?;
+ let table = cell(3)?;
+ let statement = cell(4)?;
+ Ok(mysql_trigger_ddl(database, name, timing, manipulation, table, statement))
+ }
+ TransferObjectKind::Event => {
+ let name = cell(0)?;
+ let status = cell(1)?;
+ let execute_at = cell(2)?;
+ let interval_value = cell(3)?;
+ let interval_field = cell(4)?;
+ let body = cell(5)?;
+ let schedule = if interval_value.is_empty() && interval_field.is_empty() {
+ format!("AT {execute_at}")
+ } else {
+ format!("EVERY {interval_value} {interval_field}")
+ };
+ Ok(mysql_event_ddl(database, name, status, &schedule, body))
+ }
+ _ => Err(format!("MySQL object DDL extraction not supported for {:?}", kind)),
+ }
+}
+
+pub fn oracle_object_source_query(kind: &TransferObjectKind, schema: &str, name: &str) -> Result<String, String> {
+ let object_type = match kind {
+ TransferObjectKind::View => "VIEW",
+ TransferObjectKind::MaterializedView => "MATERIALIZED_VIEW",
+ TransferObjectKind::Procedure => "PROCEDURE",
+ TransferObjectKind::Function => "FUNCTION",
+ TransferObjectKind::Trigger => "TRIGGER",
+ TransferObjectKind::Sequence => "SEQUENCE",
+ _ => return Err(format!("Oracle object source not supported for {:?}", kind)),
+ };
+ let name_lit = quote_string_literal(name);
+ if schema.trim().is_empty() {
+ Ok(format!("SELECT DBMS_METADATA.GET_DDL({}, {}) FROM DUAL", quote_string_literal(object_type), name_lit))
+ } else {
+ Ok(format!(
+ "SELECT DBMS_METADATA.GET_DDL({}, {}, {}) FROM DUAL",
+ quote_string_literal(object_type),
+ name_lit,
+ quote_string_literal(schema)
+ ))
+ }
+}
+
+/// Rewrite `"SCHEMA"."NAME"` occurrences in Oracle/DM metadata DDL from
+/// source_schema to target_schema.
+pub fn sqlserver_object_source_query(kind: &TransferObjectKind, schema: &str, name: &str) -> Result<String, String> {
+ match kind {
+ TransferObjectKind::View
+ | TransferObjectKind::Procedure
+ | TransferObjectKind::Function
+ | TransferObjectKind::Trigger => {
+ let object_type = match kind {
+ TransferObjectKind::View => "'V'",
+ TransferObjectKind::Procedure => "'P'",
+ TransferObjectKind::Function => "'FN','IF','TF','FS','FT'",
+ _ => "'TR'",
+ };
+ Ok(format!(
+ "SELECT m.definition FROM sys.sql_modules m \
+ JOIN sys.objects o ON o.object_id = m.object_id \
+ JOIN sys.schemas s ON s.schema_id = o.schema_id \
+ WHERE s.name = {} AND o.name = {} AND o.type IN ({})",
+ quote_string_literal(schema),
+ quote_string_literal(name),
+ object_type
+ ))
+ }
+ TransferObjectKind::Sequence => Ok(format!(
+ "SELECT CAST(seq.start_value AS NVARCHAR(50)), \
+ CAST(seq.increment_value AS NVARCHAR(50)), \
+ CAST(seq.minimum_value AS NVARCHAR(50)), \
+ CAST(seq.maximum_value AS NVARCHAR(50)), \
+ CASE WHEN seq.is_cycling = 1 THEN 'CYCLE' ELSE 'NO CYCLE' END, \
+ CASE WHEN seq.is_cached = 1 THEN CAST(seq.cache_size AS NVARCHAR(50)) ELSE '0' END \
+ FROM sys.sequences seq JOIN sys.schemas s ON s.schema_id = seq.schema_id \
+ WHERE s.name = {} AND seq.name = {}",
+ quote_string_literal(schema),
+ quote_string_literal(name)
+ )),
+ _ => Err(format!("SQL Server object source not supported for {:?}", kind)),
+ }
+}
+
+pub fn sqlserver_object_ddl_from_result(
+ result: &db::QueryResult,
+ schema: &str,
+ name: &str,
+ kind: &TransferObjectKind,
+) -> Result<String, String> {
+ let Some(row) = result.rows.first() else {
+ return Err(format!("No DDL returned for SQL Server {kind:?} {name}"));
+ };
+ match kind {
+ TransferObjectKind::View
+ | TransferObjectKind::Procedure
+ | TransferObjectKind::Function
+ | TransferObjectKind::Trigger => row
+ .first()
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+ .ok_or_else(|| format!("No DDL returned for SQL Server {kind:?} {name}")),
+ TransferObjectKind::Sequence => {
+ let cell = |i: usize| row.get(i).and_then(|v| v.as_str()).unwrap_or("");
+ let start = cell(0);
+ let increment = cell(1);
+ let minimum = cell(2);
+ let maximum = cell(3);
+ let cycle = cell(4);
+ let cache = cell(5);
+ Ok(format!(
+ "CREATE SEQUENCE [{}].[{}] START WITH {} INCREMENT BY {} MINVALUE {} MAXVALUE {} {} {}",
+ schema,
+ name,
+ start,
+ increment,
+ minimum,
+ maximum,
+ cycle,
+ if cache == "0" { "NO CACHE".to_string() } else { format!("CACHE {cache}") }
+ ))
+ }
+ _ => Err(format!("SQL Server object DDL not supported for {:?}", kind)),
+ }
+}
+pub fn rewrite_oracle_schema_qualifier(ddl: &str, source_schema: &str, target_schema: &str) -> String {
+ if source_schema == target_schema || source_schema.is_empty() {
+ return ddl.to_string();
+ }
+ let re = Regex::new(&format!(r#""{}"\."#, regex::escape(source_schema))).unwrap();
+ re.replace_all(ddl, &format!("\"{target_schema}\".")).to_string()
+}
+
pub(crate) fn quote_postgres_string_literal(value: &str) -> String {
if !value.contains('\\') && !value.chars().any(|character| character.is_ascii_control()) {
return quote_string_literal(value);
@@ -1291,12 +2047,10 @@ pub fn escape_value_typed(val: &serde_json::Value, db_type: &DatabaseType, colum
} else {
"1".to_string()
}
+ } else if column_type.is_some_and(is_mysql_bit_type) {
+ "b'0'".to_string()
} else {
- if column_type.is_some_and(is_mysql_bit_type) {
- "b'0'".to_string()
- } else {
- "0".to_string()
- }
+ "0".to_string()
}
}
DatabaseType::SqlServer | DatabaseType::Dameng => {
@@ -3639,51 +4393,553 @@ async fn bind_postgres_owned_sequences_for_transfer(
Ok(())
}
-async fn get_postgres_schema_object_sources_for_transfer(
- state: &AppState,
- pool_key: &str,
- schema: &str,
-) -> Result<Vec<db::ObjectSource>, String> {
- let views_sql = format!(
- "SELECT c.relname, pg_get_viewdef(c.oid, true) \
- FROM pg_catalog.pg_class c \
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
- WHERE n.nspname = {} AND c.relkind = 'v' \
- ORDER BY c.relname",
- quote_string_literal(schema)
- );
- let routines_sql = format!(
- "SELECT p.proname, CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, pg_get_functiondef(p.oid) \
- FROM pg_catalog.pg_proc p \
- JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
- WHERE n.nspname = {} AND p.prokind IN ('p', 'f') \
- ORDER BY CASE p.prokind WHEN 'p' THEN 0 ELSE 1 END, p.proname, p.oid",
- quote_string_literal(schema)
- );
+pub fn ordered_transfer_object_kinds(kinds: Vec<TransferObjectKind>) -> Vec<TransferObjectKind> {
+ let rank = |kind: &TransferObjectKind| match kind {
+ TransferObjectKind::Table => 0,
+ TransferObjectKind::Sequence => 1,
+ TransferObjectKind::View => 2,
+ TransferObjectKind::MaterializedView => 2,
+ TransferObjectKind::Function => 3,
+ TransferObjectKind::Procedure => 4,
+ TransferObjectKind::Trigger => 5,
+ TransferObjectKind::Event => 6,
+ };
+ let mut kinds = kinds;
+ kinds.sort_by_key(rank);
+ kinds
+}
- let mut sources = Vec::new();
- for row in execute_on_pool(state, pool_key, &views_sql).await?.rows {
- let Some(name) = json_string_cell(&row, 0) else {
- continue;
- };
- let Some(source) = json_string_cell(&row, 1) else {
- continue;
- };
- sources.push(db::ObjectSource {
- name,
- object_type: db::ObjectSourceKind::View,
- schema: Some(schema.to_string()),
- source,
- editable: None,
- });
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransferObjectOutcome {
+ pub transferred: Vec<String>,
+ pub skipped: Vec<String>,
+ pub failed: Vec<String>,
+}
+
+pub fn selected_object_names(selections: &[TransferObjectSelection], kind: &TransferObjectKind) -> Vec<String> {
+ selections.iter().filter(|s| &s.object_type == kind).flat_map(|s| s.names.clone()).collect::<Vec<_>>()
+}
+
+/// Whether a kind participates in a transfer. An empty selection is the legacy
+/// PG→PG default: every kind participates (views, functions, triggers,
+/// materialized views are all transferred). Once the caller explicitly selects
+/// objects, only kinds with a non-empty selection participate.
+pub fn object_kind_selected_or_defaulted(selections: &[TransferObjectSelection], kind: &TransferObjectKind) -> bool {
+ selections.is_empty() || !selected_object_names(selections, kind).is_empty()
+}
+
+pub fn should_copy_data(content: &TransferContent) -> bool {
+ !matches!(content, TransferContent::StructureOnly)
+}
+
+fn transfer_kind_from_object_source_kind(kind: &db::ObjectSourceKind) -> Option<TransferObjectKind> {
+ use db::ObjectSourceKind as S;
+ Some(match kind {
+ S::View => TransferObjectKind::View,
+ S::MaterializedView => TransferObjectKind::MaterializedView,
+ S::Procedure => TransferObjectKind::Procedure,
+ S::Function => TransferObjectKind::Function,
+ S::Trigger => TransferObjectKind::Trigger,
+ S::Sequence => TransferObjectKind::Sequence,
+ _ => return None,
+ })
+}
+
+fn filter_object_sources_by_selection(
+ sources: Vec<db::ObjectSource>,
+ selections: &[TransferObjectSelection],
+) -> Vec<db::ObjectSource> {
+ // Empty selection is the legacy PG→PG default: transfer everything.
+ if selections.is_empty() {
+ return sources;
}
- for row in execute_on_pool(state, pool_key, &routines_sql).await?.rows {
- let Some(name) = json_string_cell(&row, 0) else {
- continue;
- };
- let kind = match json_string_cell(&row, 1).as_deref() {
- Some("PROCEDURE") => db::ObjectSourceKind::Procedure,
- _ => db::ObjectSourceKind::Function,
+ sources
+ .into_iter()
+ .filter(|source| {
+ let Some(kind) = transfer_kind_from_object_source_kind(&source.object_type) else {
+ return false;
+ };
+ selected_object_names(selections, &kind).contains(&source.name)
+ })
+ .collect()
+}
+
+/// Whether non-table schema-object transfer should run for a request.
+/// Data-only transfers never include schema objects. In structure modes,
+/// newer clients send an explicit `objects` selection; for those the answer
+/// is simply whether any object was selected. PG→PG keeps the legacy default:
+/// even an *empty* selection still transfers all views, functions, triggers,
+/// policies, ownership and grants (the old table-selection flow always did).
+pub fn should_transfer_schema_objects(
+ source_db_type: &DatabaseType,
+ target_db_type: &DatabaseType,
+ content: &TransferContent,
+ objects: &[TransferObjectSelection],
+) -> bool {
+ if matches!(content, TransferContent::DataOnly) {
+ return false;
+ }
+ if !objects.is_empty() {
+ return true;
+ }
+ transfer_object_family(source_db_type) == Some(TransferObjectFamily::Postgres)
+ && transfer_object_family(target_db_type) == Some(TransferObjectFamily::Postgres)
+}
+
+/// Transfers selected non-table objects from source to target.
+/// Skips objects that already exist on the target; counts them in the
+/// outcome. Executes in dependency order (sequence → view → function →
+/// procedure → trigger → event). Errors are collected per object and the
+/// transfer continues.
+pub async fn transfer_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ if matches!(request.content, TransferContent::DataOnly) {
+ return Ok(TransferObjectOutcome::default());
+ }
+ let source_db_type = get_db_type(state, &request.source_connection_id).await?;
+ let target_db_type = get_db_type(state, &request.target_connection_id).await?;
+ if !should_transfer_schema_objects(&source_db_type, &target_db_type, &request.content, &request.objects) {
+ return Ok(TransferObjectOutcome::default());
+ }
+ if !is_same_transfer_family(&source_db_type, &target_db_type) {
+ return transfer_cross_family_schema_objects(
+ state,
+ request,
+ source_pool_key,
+ target_pool_key,
+ progress_callback,
+ )
+ .await;
+ }
+ // Same-family path: drop selections whose object type is not transferable
+ // for the source family (defense in depth — the UI already filters disabled
+ // types at the request boundary, but requests can also arrive from older
+ // clients or be crafted directly).
+ let mut filtered_request = request.clone();
+ if let Some(family) = transfer_object_family(&source_db_type) {
+ let supported = transfer_object_kinds_for_family(&family);
+ filtered_request.objects =
+ request.objects.iter().filter(|sel| supported.contains(&sel.object_type)).cloned().collect();
+ }
+ match transfer_object_family(&source_db_type) {
+ Some(TransferObjectFamily::Postgres) => {
+ transfer_postgres_schema_objects(
+ state,
+ &filtered_request,
+ source_pool_key,
+ target_pool_key,
+ progress_callback,
+ )
+ .await
+ }
+ Some(TransferObjectFamily::Mysql) => {
+ transfer_mysql_schema_objects(state, &filtered_request, source_pool_key, target_pool_key, progress_callback)
+ .await
+ }
+ Some(TransferObjectFamily::Oracle) => {
+ transfer_oracle_schema_objects(
+ state,
+ &filtered_request,
+ source_pool_key,
+ target_pool_key,
+ progress_callback,
+ )
+ .await
+ }
+ Some(TransferObjectFamily::SqlServer) => {
+ transfer_sqlserver_schema_objects(
+ state,
+ &filtered_request,
+ source_pool_key,
+ target_pool_key,
+ progress_callback,
+ )
+ .await
+ }
+ None => Ok(TransferObjectOutcome::default()),
+ }
+}
+
+async fn transfer_mysql_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ mut progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ let mut outcome = TransferObjectOutcome::default();
+ let source_db = &request.source_database;
+ let target_db =
+ if request.target_database.trim().is_empty() { source_db.as_str() } else { request.target_database.as_str() };
+ let order = ordered_transfer_object_kinds(request.objects.iter().map(|s| s.object_type).collect());
+ for kind in order {
+ for name in selected_object_names(&request.objects, &kind) {
+ if is_cancelled(&request.transfer_id).await {
+ return Err("Cancelled".to_string());
+ }
+ let table = format!("schema object: {name}");
+ let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {
+ progress_callback(TransferProgress {
+ transfer_id: request.transfer_id.clone(),
+ table: table.clone(),
+ table_index: request.tables.len(),
+ total_tables: request.tables.len(),
+ rows_transferred: (outcome.transferred.len() + outcome.skipped.len()) as u64,
+ total_rows: None,
+ status,
+ error,
+ terminal: false,
+ });
+ };
+ // skip if the target already has it
+ let exists_sql = target_object_exists_sql(&DatabaseType::Mysql, target_db, &name, &kind)?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ continue;
+ }
+ let query = mysql_object_source_query(&kind, source_db, &name)?;
+ let result = execute_on_pool(state, source_pool_key, &query).await?;
+ let raw_ddl = mysql_object_ddl_from_result(&kind, source_db, &result.rows)?;
+ let ddl = strip_mysql_definer(&raw_ddl);
+ let ddl = rewrite_mysql_schema_qualifier(&ddl, source_db, target_db);
+ match execute_on_pool(state, target_pool_key, &ddl).await {
+ Ok(_) => {
+ outcome.transferred.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ }
+ Err(e) => {
+ outcome.failed.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Error, Some(e));
+ }
+ }
+ }
+ }
+ Ok(outcome)
+}
+
+fn resolve_oracle_schema(schema: &str, database: &str) -> String {
+ if schema.trim().is_empty() {
+ database.to_string()
+ } else {
+ schema.to_string()
+ }
+}
+
+async fn transfer_oracle_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ mut progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ let mut outcome = TransferObjectOutcome::default();
+ let source_schema = resolve_oracle_schema(&request.source_schema, &request.source_database);
+ let target_schema = resolve_oracle_schema(&request.target_schema, &request.target_database);
+ let order = ordered_transfer_object_kinds(request.objects.iter().map(|s| s.object_type).collect());
+ for kind in order {
+ for name in selected_object_names(&request.objects, &kind) {
+ if is_cancelled(&request.transfer_id).await {
+ return Err("Cancelled".to_string());
+ }
+ let table = format!("schema object: {name}");
+ let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {
+ progress_callback(TransferProgress {
+ transfer_id: request.transfer_id.clone(),
+ table: table.clone(),
+ table_index: request.tables.len(),
+ total_tables: request.tables.len(),
+ rows_transferred: (outcome.transferred.len() + outcome.skipped.len()) as u64,
+ total_rows: None,
+ status,
+ error,
+ terminal: false,
+ });
+ };
+ // skip if the target already has it (ALL_OBJECTS works for both Oracle and Dameng)
+ let exists_sql = target_object_exists_sql(&DatabaseType::Oracle, &target_schema, &name, &kind)?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ continue;
+ }
+ let query = oracle_object_source_query(&kind, &source_schema, &name)?;
+ let result = execute_on_pool(state, source_pool_key, &query).await?;
+ // DBMS_METADATA.GET_DDL resolves against the session's current
+ // schema; if the pool session is not the owner schema the query
+ // may return no row and the object is reported as failed (v1).
+ let ddl = result
+ .rows
+ .first()
+ .and_then(|row| row.first())
+ .and_then(|value| value.as_str())
+ .ok_or_else(|| format!("No DDL returned for Oracle {:?} {name}", kind))?
+ .to_string();
+ let ddl = rewrite_oracle_schema_qualifier(&ddl, &source_schema, &target_schema);
+ match execute_on_pool(state, target_pool_key, &ddl).await {
+ Ok(_) => {
+ outcome.transferred.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ }
+ Err(e) => {
+ outcome.failed.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Error, Some(e));
+ }
+ }
+ }
+ }
+ Ok(outcome)
+}
+
+async fn transfer_sqlserver_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ mut progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ let mut outcome = TransferObjectOutcome::default();
+ let source_schema =
+ if request.source_schema.trim().is_empty() { "dbo".to_string() } else { request.source_schema.clone() };
+ let target_schema =
+ if request.target_schema.trim().is_empty() { "dbo".to_string() } else { request.target_schema.clone() };
+ let order = ordered_transfer_object_kinds(request.objects.iter().map(|s| s.object_type).collect());
+ for kind in order {
+ for name in selected_object_names(&request.objects, &kind) {
+ if is_cancelled(&request.transfer_id).await {
+ return Err("Cancelled".to_string());
+ }
+ let table = format!("schema object: {name}");
+ let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {
+ progress_callback(TransferProgress {
+ transfer_id: request.transfer_id.clone(),
+ table: table.clone(),
+ table_index: request.tables.len(),
+ total_tables: request.tables.len(),
+ rows_transferred: (outcome.transferred.len() + outcome.skipped.len()) as u64,
+ total_rows: None,
+ status,
+ error,
+ terminal: false,
+ });
+ };
+ let exists_sql = target_object_exists_sql(&DatabaseType::SqlServer, &target_schema, &name, &kind)?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ continue;
+ }
+ let query = sqlserver_object_source_query(&kind, &source_schema, &name)?;
+ let result = execute_on_pool(state, source_pool_key, &query).await?;
+ let ddl = match sqlserver_object_ddl_from_result(&result, &source_schema, &name, &kind) {
+ Ok(ddl) => ddl,
+ Err(e) => {
+ outcome.failed.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Error, Some(e));
+ continue;
+ }
+ };
+ match execute_on_pool(state, target_pool_key, &ddl).await {
+ Ok(_) => {
+ outcome.transferred.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ }
+ Err(e) => {
+ outcome.failed.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Error, Some(e));
+ }
+ }
+ }
+ }
+ Ok(outcome)
+}
+
+/// Transfers non-table objects across different database families.
+/// Only mechanically rewriteable kinds (views, sequences) are allowed;
+/// anything else is rejected up front with a descriptive error.
+async fn transfer_cross_family_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ mut progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ let mut outcome = TransferObjectOutcome::default();
+ let source_db_type = get_db_type(state, &request.source_connection_id).await?;
+ let target_db_type = get_db_type(state, &request.target_connection_id).await?;
+ let allowed = cross_family_transferable_object_kinds(&source_db_type, &target_db_type);
+ let unsupported: Vec<String> = request
+ .objects
+ .iter()
+ .filter(|selection| !allowed.contains(&selection.object_type))
+ .map(|selection| format!("{:?}", selection.object_type))
+ .collect();
+ if !unsupported.is_empty() {
+ return Err(format!("跨库非表对象传输暂不支持该类型,不支持: {}", unsupported.join(", ")));
+ }
+ let source_family = transfer_object_family(&source_db_type).ok_or("unsupported source family")?;
+ let target_family = transfer_object_family(&target_db_type).ok_or("unsupported target family")?;
+ let resolve_schema = |schema: &str, database: &str, db_type: &DatabaseType| -> String {
+ if !schema.trim().is_empty() {
+ return schema.to_string();
+ }
+ match transfer_object_family(db_type) {
+ Some(TransferObjectFamily::SqlServer) => "dbo".to_string(),
+ _ => database.to_string(),
+ }
+ };
+ let source_schema = resolve_schema(&request.source_schema, &request.source_database, &source_db_type);
+ let target_schema = resolve_schema(&request.target_schema, &request.target_database, &target_db_type);
+ let order = ordered_transfer_object_kinds(request.objects.iter().map(|s| s.object_type).collect());
+ for kind in order {
+ for name in selected_object_names(&request.objects, &kind) {
+ if is_cancelled(&request.transfer_id).await {
+ return Err("Cancelled".to_string());
+ }
+ let table = format!("schema object: {name}");
+ let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {
+ progress_callback(TransferProgress {
+ transfer_id: request.transfer_id.clone(),
+ table: table.clone(),
+ table_index: request.tables.len(),
+ total_tables: request.tables.len(),
+ rows_transferred: (outcome.transferred.len() + outcome.skipped.len()) as u64,
+ total_rows: None,
+ status,
+ error,
+ terminal: false,
+ });
+ };
+ let exists_sql = target_object_exists_sql(&target_db_type, &target_schema, &name, &kind)?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ continue;
+ }
+ let query = match source_family {
+ TransferObjectFamily::Mysql => mysql_object_source_query(&kind, &source_schema, &name)?,
+ TransferObjectFamily::SqlServer => sqlserver_object_source_query(&kind, &source_schema, &name)?,
+ TransferObjectFamily::Oracle => oracle_object_source_query(&kind, &source_schema, &name)?,
+ TransferObjectFamily::Postgres => {
+ return Err(format!("跨库传输暂不支持 Postgres 源: {name}"));
+ }
+ };
+ let result = execute_on_pool(state, source_pool_key, &query).await?;
+ let raw_ddl = match source_family {
+ TransferObjectFamily::Mysql => mysql_object_ddl_from_result(&kind, &source_schema, &result.rows)?,
+ TransferObjectFamily::SqlServer => {
+ sqlserver_object_ddl_from_result(&result, &source_schema, &name, &kind)?
+ }
+ TransferObjectFamily::Oracle => result
+ .rows
+ .first()
+ .and_then(|row| row.first())
+ .and_then(|value| value.as_str())
+ .ok_or_else(|| format!("No DDL returned for Oracle {:?} {name}", kind))?
+ .to_string(),
+ TransferObjectFamily::Postgres => {
+ return Err(format!("跨库传输暂不支持 Postgres 源: {name}"));
+ }
+ };
+ let ddl = convert_cross_family_object_ddl(
+ &source_family,
+ &target_family,
+ &kind,
+ &source_schema,
+ &target_schema,
+ &raw_ddl,
+ );
+ match execute_on_pool(state, target_pool_key, &ddl).await {
+ Ok(_) => {
+ outcome.transferred.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ }
+ Err(e) => {
+ let e = if kind == TransferObjectKind::View
+ && (e.contains("无效的表或视图名") || e.contains("table or view does not exist"))
+ {
+ format!("{e}(视图引用的基表可能未在目标库中,请同时选择视图依赖的表或先传输这些表)")
+ } else {
+ e
+ };
+ outcome.failed.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Error, Some(e));
+ }
+ }
+ }
+ }
+ Ok(outcome)
+}
+async fn get_postgres_schema_object_sources_for_transfer(
+ state: &AppState,
+ pool_key: &str,
+ schema: &str,
+) -> Result<Vec<db::ObjectSource>, String> {
+ let views_sql = format!(
+ "SELECT c.relname, pg_get_viewdef(c.oid, true) \
+ FROM pg_catalog.pg_class c \
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {} AND c.relkind = 'v' \
+ ORDER BY c.relname",
+ quote_string_literal(schema)
+ );
+ let routines_sql = format!(
+ "SELECT p.proname, CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, pg_get_functiondef(p.oid) \
+ FROM pg_catalog.pg_proc p \
+ JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
+ WHERE n.nspname = {} AND p.prokind IN ('p', 'f') \
+ ORDER BY CASE p.prokind WHEN 'p' THEN 0 ELSE 1 END, p.proname, p.oid",
+ quote_string_literal(schema)
+ );
+
+ let mut sources = Vec::new();
+ for row in execute_on_pool(state, pool_key, &views_sql).await?.rows {
+ let Some(name) = json_string_cell(&row, 0) else {
+ continue;
+ };
+ let Some(source) = json_string_cell(&row, 1) else {
+ continue;
+ };
+ sources.push(db::ObjectSource {
+ name,
+ object_type: db::ObjectSourceKind::View,
+ schema: Some(schema.to_string()),
+ source,
+ editable: None,
+ });
+ }
+ for row in execute_on_pool(state, pool_key, &routines_sql).await?.rows {
+ let Some(name) = json_string_cell(&row, 0) else {
+ continue;
+ };
+ let kind = match json_string_cell(&row, 1).as_deref() {
+ Some("PROCEDURE") => db::ObjectSourceKind::Procedure,
+ _ => db::ObjectSourceKind::Function,
};
let Some(source) = json_string_cell(&row, 2) else {
continue;
@@ -4766,6 +6022,12 @@ where
}
}
+ // Structure-only transfer: DDL work (create table, indexes, comments) is
+ // done above; skip everything data-related.
+ if !should_copy_data(&request.content) {
+ return Ok(0);
+ }
+
// Truncate target if overwrite mode
if request.mode == TransferMode::Overwrite {
let full_table =
@@ -5057,23 +6319,41 @@ pub async fn transfer_postgres_schema_objects<F>(
source_pool_key: &str,
target_pool_key: &str,
mut progress_callback: F,
-) -> Result<(), String>
+) -> Result<TransferObjectOutcome, String>
where
F: FnMut(TransferProgress),
{
let source_db_type = get_db_type(state, &request.source_connection_id).await?;
let target_db_type = get_db_type(state, &request.target_connection_id).await?;
if !request.create_table || !is_postgres_compat_transfer(&source_db_type, &target_db_type) {
- return Ok(());
+ return Ok(TransferObjectOutcome::default());
}
- let object_sources =
- get_postgres_schema_object_sources_for_transfer(state, source_pool_key, &request.source_schema).await?;
+ let mut outcome = TransferObjectOutcome::default();
+ let object_sources = filter_object_sources_by_selection(
+ get_postgres_schema_object_sources_for_transfer(state, source_pool_key, &request.source_schema).await?,
+ &request.objects,
+ );
let materialized_views =
- get_postgres_materialized_view_sources_for_transfer(state, source_pool_key, &request.source_schema).await?;
+ get_postgres_materialized_view_sources_for_transfer(state, source_pool_key, &request.source_schema)
+ .await?
+ .into_iter()
+ .filter(|view| {
+ object_kind_selected_or_defaulted(&request.objects, &TransferObjectKind::MaterializedView)
+ && selected_object_names(&request.objects, &TransferObjectKind::MaterializedView)
+ .contains(&view.view_name)
+ })
+ .collect::<Vec<_>>();
let trigger_sources =
get_postgres_trigger_sources_for_transfer(state, source_pool_key, &request.source_schema, &request.tables)
- .await?;
+ .await?
+ .into_iter()
+ .filter(|trigger| {
+ object_kind_selected_or_defaulted(&request.objects, &TransferObjectKind::Trigger)
+ && selected_object_names(&request.objects, &TransferObjectKind::Trigger)
+ .contains(&trigger.trigger_name)
+ })
+ .collect::<Vec<_>>();
let policy_statements = get_postgres_policy_statements_for_transfer(
state,
source_pool_key,
@@ -5133,6 +6413,16 @@ where
if is_cancelled(&request.transfer_id).await {
return Err("Cancelled".to_string());
}
+ let Some(object_kind) = transfer_kind_from_object_source_kind(&object.object_type) else {
+ continue;
+ };
+ let exists_sql =
+ target_object_exists_sql(&DatabaseType::Postgres, &request.target_schema, &object.name, &object_kind)?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("{object_kind:?}:{}", object.name));
+ continue;
+ }
completed_steps += 1;
progress_callback(TransferProgress {
transfer_id: request.transfer_id.clone(),
@@ -5172,9 +6462,21 @@ where
.await
.map_err(|e| format!("Failed to create PostgreSQL {:?} {}: {e}", object.object_type, object.name))?;
}
+ outcome.transferred.push(format!("{object_kind:?}:{}", object.name));
}
for view in materialized_views {
+ let exists_sql = target_object_exists_sql(
+ &DatabaseType::Postgres,
+ &request.target_schema,
+ &view.view_name,
+ &TransferObjectKind::MaterializedView,
+ )?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("MaterializedView:{}", view.view_name));
+ continue;
+ }
for statement in generate_postgres_materialized_view_ddls(&view, &request.target_schema) {
if is_cancelled(&request.transfer_id).await {
return Err("Cancelled".to_string());
@@ -5195,12 +6497,24 @@ where
.await
.map_err(|e| format!("Failed to create PostgreSQL materialized view {}: {e}", view.view_name))?;
}
+ outcome.transferred.push(format!("MaterializedView:{}", view.view_name));
}
for trigger in trigger_sources {
if is_cancelled(&request.transfer_id).await {
return Err("Cancelled".to_string());
}
+ let exists_sql = target_object_exists_sql(
+ &DatabaseType::Postgres,
+ &request.target_schema,
+ &trigger.trigger_name,
+ &TransferObjectKind::Trigger,
+ )?;
+ let exists = !execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.is_empty();
+ if exists {
+ outcome.skipped.push(format!("Trigger:{}", trigger.trigger_name));
+ continue;
+ }
completed_steps += 1;
progress_callback(TransferProgress {
transfer_id: request.transfer_id.clone(),
@@ -5242,6 +6556,7 @@ where
execute_on_pool(state, target_pool_key, &create_sql)
.await
.map_err(|e| format!("Failed to create PostgreSQL trigger {}: {e}", trigger.trigger_name))?;
+ outcome.transferred.push(format!("Trigger:{}", trigger.trigger_name));
}
for statement in policy_statements {
@@ -5317,7 +6632,7 @@ where
.map_err(|e| format!("Failed to apply PostgreSQL grant statement: {e}"))?;
}
- Ok(())
+ Ok(outcome)
}
#[cfg(test)]
@@ -5412,6 +6727,783 @@ mod tests {
assert!(query_result_has_rows(&test_query_result(vec![vec![serde_json::json!(1)]])));
}
+ #[test]
+ fn transfer_content_defaults_to_structure_and_data() {
+ let request: TransferRequest = serde_json::from_value(serde_json::json!({
+ "transferId": "t1", "sourceConnectionId": "s", "sourceDatabase": "db",
+ "sourceSchema": "public", "targetConnectionId": "t", "targetDatabase": "db",
+ "targetSchema": "public", "tables": ["a"], "createTable": true,
+ "mode": "append", "targetTableNameCase": "preserve", "batchSize": 1000
+ }))
+ .unwrap();
+ assert_eq!(request.content, TransferContent::StructureAndData);
+ assert!(request.objects.is_empty());
+ }
+
+ #[test]
+ fn transfer_request_serializes_new_fields_camel_case() {
+ let request = TransferRequest {
+ transfer_id: "t1".to_string(),
+ source_connection_id: "s".to_string(),
+ source_database: "db".to_string(),
+ source_schema: "public".to_string(),
+ source_catalog: None,
+ target_connection_id: "t".to_string(),
+ target_database: "db".to_string(),
+ target_schema: "public".to_string(),
+ target_catalog: None,
+ tables: vec!["a".to_string()],
+ create_table: true,
+ content: TransferContent::StructureOnly,
+ objects: vec![TransferObjectSelection {
+ object_type: TransferObjectKind::View,
+ names: vec!["v1".to_string()],
+ }],
+ mode: TransferMode::Append,
+ target_table_name_case: TransferTableNameCase::Preserve,
+ ownership_policy: TransferOwnershipPolicy::Preserve,
+ batch_size: 1000,
+ };
+ let json = serde_json::to_value(&request).unwrap();
+ assert_eq!(json["content"], "structureOnly");
+ assert_eq!(json["objects"][0]["objectType"], "VIEW");
+ assert_eq!(json["objects"][0]["names"][0], "v1");
+ }
+
+ mod transfer_family_tests {
+ use super::*;
+
+ #[test]
+ fn same_family_matrix() {
+ // postgres family
+ assert!(is_same_transfer_family(&DatabaseType::Postgres, &DatabaseType::Kingbase));
+ assert!(is_same_transfer_family(&DatabaseType::Gaussdb, &DatabaseType::OpenGauss));
+ // oracle family
+ assert!(is_same_transfer_family(&DatabaseType::Oracle, &DatabaseType::Dameng));
+ assert!(is_same_transfer_family(&DatabaseType::OceanbaseOracle, &DatabaseType::Dameng));
+ // mysql
+ assert!(is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::Mysql));
+ // sqlserver
+ assert!(is_same_transfer_family(&DatabaseType::SqlServer, &DatabaseType::SqlServer));
+ // cross family
+ assert!(!is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::Postgres));
+ assert!(!is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::SqlServer));
+ }
+
+ #[test]
+ fn object_kinds_per_family() {
+ let mysql = transfer_object_kinds(&DatabaseType::Mysql);
+ assert!(mysql.contains(&TransferObjectKind::Event));
+ assert!(!mysql.contains(&TransferObjectKind::Sequence));
+ let pg = transfer_object_kinds(&DatabaseType::Postgres);
+ assert!(pg.contains(&TransferObjectKind::Sequence));
+ assert!(!pg.contains(&TransferObjectKind::Event));
+ let dm = transfer_object_kinds(&DatabaseType::Dameng);
+ assert!(dm.contains(&TransferObjectKind::Trigger));
+ assert!(dm.contains(&TransferObjectKind::Sequence));
+ let sqlserver = transfer_object_kinds(&DatabaseType::SqlServer);
+ assert!(sqlserver.contains(&TransferObjectKind::View));
+ assert!(sqlserver.contains(&TransferObjectKind::Procedure));
+ assert!(sqlserver.contains(&TransferObjectKind::Function));
+ assert!(sqlserver.contains(&TransferObjectKind::Trigger));
+ assert!(sqlserver.contains(&TransferObjectKind::Sequence));
+ assert!(!sqlserver.contains(&TransferObjectKind::Event));
+ assert!(!sqlserver.contains(&TransferObjectKind::MaterializedView));
+ assert!(transfer_object_kinds(&DatabaseType::Sqlite).is_empty());
+ }
+ }
+
+ mod transfer_validation_tests {
+ use super::*;
+
+ #[test]
+ fn validates_content_and_object_rules() {
+ let base = TransferRequest {
+ transfer_id: "t".into(),
+ source_connection_id: "s".into(),
+ source_database: "db".into(),
+ source_schema: "public".into(),
+ source_catalog: None,
+ target_connection_id: "t".into(),
+ target_database: "db".into(),
+ target_schema: "public".into(),
+ target_catalog: None,
+ tables: vec!["a".into()],
+ create_table: true,
+ mode: TransferMode::Append,
+ target_table_name_case: TransferTableNameCase::Preserve,
+ ownership_policy: TransferOwnershipPolicy::Preserve,
+ batch_size: 1000,
+ content: TransferContent::DataOnly,
+ objects: Vec::new(),
+ };
+ assert!(validate_transfer_request(&base).is_ok());
+
+ let with_objects = TransferRequest {
+ objects: vec![TransferObjectSelection {
+ object_type: TransferObjectKind::View,
+ names: vec!["v".into()],
+ }],
+ ..base.clone()
+ };
+ // DataOnly + objects → error
+ assert!(validate_transfer_request(&with_objects).is_err());
+
+ let structure_only = TransferRequest { content: TransferContent::StructureOnly, ..base.clone() };
+ assert!(validate_transfer_request(&structure_only).is_ok());
+ }
+ }
+
+ mod transfer_existence_tests {
+ use super::*;
+
+ #[test]
+ fn builds_target_existence_check_sql_per_family() {
+ let mysql =
+ target_object_exists_sql(&DatabaseType::Mysql, "shop", "v1", &TransferObjectKind::View).unwrap();
+ assert!(mysql.contains("information_schema.TABLES"));
+ assert!(mysql.contains("TABLE_TYPE = 'VIEW'"));
+ let mysql_ev =
+ target_object_exists_sql(&DatabaseType::Mysql, "shop", "e1", &TransferObjectKind::Event).unwrap();
+ assert!(mysql_ev.contains("information_schema.EVENTS"));
+ let mysql_tr =
+ target_object_exists_sql(&DatabaseType::Mysql, "shop", "t1", &TransferObjectKind::Trigger).unwrap();
+ assert!(mysql_tr.contains("information_schema.TRIGGERS"));
+ let pg =
+ target_object_exists_sql(&DatabaseType::Postgres, "public", "v1", &TransferObjectKind::View).unwrap();
+ assert!(pg.contains("pg_class"));
+ let orc =
+ target_object_exists_sql(&DatabaseType::Oracle, "HR", "SEQ1", &TransferObjectKind::Sequence).unwrap();
+ assert!(orc.contains("ALL_OBJECTS"));
+ assert!(target_object_exists_sql(&DatabaseType::Sqlite, "m", "x", &TransferObjectKind::View).is_err());
+ let ss_view =
+ target_object_exists_sql(&DatabaseType::SqlServer, "dbo", "v1", &TransferObjectKind::View).unwrap();
+ assert!(ss_view.contains("sys.objects"));
+ assert!(ss_view.contains("o.type IN ('V')"));
+ let ss_seq =
+ target_object_exists_sql(&DatabaseType::SqlServer, "dbo", "s1", &TransferObjectKind::Sequence).unwrap();
+ assert!(ss_seq.contains("o.type IN ('SO')"));
+ let ss_trg =
+ target_object_exists_sql(&DatabaseType::SqlServer, "dbo", "t1", &TransferObjectKind::Trigger).unwrap();
+ assert!(ss_trg.contains("o.type IN ('TR')"));
+ }
+ }
+
+ mod transfer_cross_family_tests {
+ use super::*;
+ use TransferObjectKind::*;
+
+ #[test]
+ fn cross_family_transferable_kinds_matrix() {
+ // cross-family VIEW transfer is disabled (the DDL conversion does
+ // not translate the view query body, so source-specific constructs
+ // could run unchanged on an incompatible target)
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Mysql, &DatabaseType::Dameng).is_empty());
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Dameng, &DatabaseType::Mysql).is_empty());
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Mysql, &DatabaseType::SqlServer).is_empty());
+ // sqlserver <-> dameng: sequences only (plain DDL, converted and tested)
+ assert_eq!(
+ cross_family_transferable_object_kinds(&DatabaseType::SqlServer, &DatabaseType::Dameng),
+ vec![Sequence]
+ );
+ assert_eq!(
+ cross_family_transferable_object_kinds(&DatabaseType::Dameng, &DatabaseType::SqlServer),
+ vec![Sequence]
+ );
+ // same family: all source kinds are transferable
+ let same = cross_family_transferable_object_kinds(&DatabaseType::Mysql, &DatabaseType::Mysql);
+ assert!(same.contains(&Trigger));
+ assert!(same.contains(&Event));
+ // unsupported databases
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Sqlite, &DatabaseType::Mysql).is_empty());
+ // postgres is not a validated cross-family source or target:
+ // the executor rejects postgres sources and no dialect-aware
+ // conversion exists for it (postgres <-> postgres stays same-family)
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Postgres, &DatabaseType::Mysql).is_empty());
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Mysql, &DatabaseType::Postgres).is_empty());
+ assert!(
+ cross_family_transferable_object_kinds(&DatabaseType::Postgres, &DatabaseType::SqlServer).is_empty()
+ );
+ assert!(cross_family_transferable_object_kinds(&DatabaseType::Postgres, &DatabaseType::Postgres)
+ .contains(&View));
+ }
+
+ #[test]
+ fn should_transfer_schema_objects_matrix() {
+ // DataOnly never transfers schema objects, even for PG-family pairs.
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Postgres,
+ &DatabaseType::Postgres,
+ &TransferContent::DataOnly,
+ &[]
+ ));
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Postgres,
+ &DatabaseType::Postgres,
+ &TransferContent::DataOnly,
+ &[TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] }]
+ ));
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Mysql,
+ &DatabaseType::Dameng,
+ &TransferContent::DataOnly,
+ &[TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] }]
+ ));
+ // Non-empty selections participate in structure modes.
+ assert!(should_transfer_schema_objects(
+ &DatabaseType::Postgres,
+ &DatabaseType::Mysql,
+ &TransferContent::StructureOnly,
+ &[TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] }]
+ ));
+ // Empty selection: PG→PG keeps the legacy transfer-everything default
+ // only when structure participates in the transfer.
+ assert!(should_transfer_schema_objects(
+ &DatabaseType::Postgres,
+ &DatabaseType::Postgres,
+ &TransferContent::StructureOnly,
+ &[]
+ ));
+ assert!(should_transfer_schema_objects(
+ &DatabaseType::Kingbase,
+ &DatabaseType::Postgres,
+ &TransferContent::StructureAndData,
+ &[]
+ ));
+ assert!(should_transfer_schema_objects(
+ &DatabaseType::Postgres,
+ &DatabaseType::OpenGauss,
+ &TransferContent::StructureOnly,
+ &[]
+ ));
+ // empty selection: every other combination transfers nothing
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Postgres,
+ &DatabaseType::Mysql,
+ &TransferContent::StructureOnly,
+ &[]
+ ));
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Mysql,
+ &DatabaseType::Mysql,
+ &TransferContent::StructureAndData,
+ &[]
+ ));
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Mysql,
+ &DatabaseType::Dameng,
+ &TransferContent::StructureOnly,
+ &[]
+ ));
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Dameng,
+ &DatabaseType::SqlServer,
+ &TransferContent::StructureAndData,
+ &[]
+ ));
+ assert!(!should_transfer_schema_objects(
+ &DatabaseType::Sqlite,
+ &DatabaseType::Sqlite,
+ &TransferContent::StructureOnly,
+ &[]
+ ));
+ }
+
+ #[test]
+ fn rewrites_cross_family_view_ddl() {
+ // mysql -> dameng
+ let mysql_view = "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `src`.`v` AS select `t`.`id` AS `id` from `src`.`t`";
+ let dm = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Mysql,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::View,
+ "src",
+ "TGT",
+ mysql_view,
+ );
+ assert!(dm.starts_with("CREATE VIEW \"TGT\".\"v\" AS"), "{dm}");
+ assert!(!dm.contains("DEFINER"));
+ assert!(!dm.contains("ALGORITHM"));
+ assert!(dm.contains("\"t\".\"id\""));
+ assert!(dm.contains("from \"TGT\".\"t\""));
+
+ // sqlserver -> mysql
+ let ss_view = "CREATE VIEW [dbo].[v] WITH SCHEMABINDING AS SELECT a.id, b.name FROM [dbo].[a] JOIN [dbo].[b] ON a.id = b.id";
+ let my = convert_cross_family_object_ddl(
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectFamily::Mysql,
+ &TransferObjectKind::View,
+ "dbo",
+ "tgt",
+ ss_view,
+ );
+ assert!(my.starts_with("CREATE VIEW `tgt`.`v` AS"), "{my}");
+ assert!(!my.contains("SCHEMABINDING"));
+ assert!(my.contains("`tgt`.`a`"));
+ assert!(!my.contains("["));
+
+ // dameng -> sqlserver
+ let dm_view = "CREATE OR REPLACE FORCE VIEW \"S\".\"V\" (\"ID\") AS SELECT \"ID\" FROM \"S\".\"T\"";
+ let ss = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Oracle,
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectKind::View,
+ "S",
+ "dbo",
+ dm_view,
+ );
+ assert!(ss.starts_with("CREATE VIEW [dbo].[V] ("), "{ss}");
+ assert!(!ss.contains("FORCE"));
+ assert!(ss.contains("[dbo].[T]"));
+
+ // dameng -> mysql
+ let my2 = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Oracle,
+ &TransferObjectFamily::Mysql,
+ &TransferObjectKind::View,
+ "S",
+ "tgt",
+ dm_view,
+ );
+ assert!(my2.starts_with("CREATE VIEW `tgt`.`V` ("), "{my2}");
+ assert!(my2.contains("`tgt`.`T`"));
+ }
+
+ #[test]
+ fn does_not_rewrite_identifiers_inside_strings_and_comments() {
+ // MySQL -> Dameng: string literals and comments must not have
+ // their content re-quoted or schema-qualified.
+ let mysql_view = concat!(
+ "CREATE DEFINER=`root`@`%` VIEW `v` AS ",
+ "-- from `hidden`.`table` join \"hidden\"\n",
+ "SELECT `t`.`id`, 'from \"lit\"', \"double\" ",
+ "/* join \"quoted\" */ FROM `src`.`t` ",
+ "WHERE `t`.`name` = 'join \"src\".\"t\"'",
+ );
+ let dm = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Mysql,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::View,
+ "src",
+ "TGT",
+ mysql_view,
+ );
+ assert!(dm.starts_with("CREATE VIEW \"TGT\".\"v\" AS"), "{dm}");
+ // code identifiers are rewritten and qualified
+ assert!(dm.contains("SELECT \"t\".\"id\""), "{dm}");
+ assert!(dm.contains("FROM \"TGT\".\"t\""), "{dm}");
+ // the comment is untouched
+ assert!(dm.contains("-- from `hidden`.`table` join \"hidden\""), "{dm}");
+ assert!(dm.contains("/* join \"quoted\" */"), "{dm}");
+ // the single-quoted string literal is untouched (including the
+ // fake qualifier inside it)
+ assert!(dm.contains("'join \"src\".\"t\"'"), "{dm}");
+ // MySQL double-quoted text is a string literal, not an identifier
+ assert!(dm.contains("\"double\""), "{dm}");
+
+ // SqlServer -> MySQL: brackets inside comments/strings stay put
+ let ss_view = concat!(
+ "CREATE VIEW [dbo].[v] AS ",
+ "-- SELECT [dbo].[x]\n",
+ "SELECT [a].[id], 'literal [dbo].[y]' FROM [dbo].[a]",
+ );
+ let my = convert_cross_family_object_ddl(
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectFamily::Mysql,
+ &TransferObjectKind::View,
+ "dbo",
+ "tgt",
+ ss_view,
+ );
+ assert!(my.starts_with("CREATE VIEW `tgt`.`v` AS"), "{my}");
+ assert!(my.contains("`tgt`.`a`"), "{my}");
+ assert!(my.contains("-- SELECT [dbo].[x]"), "{my}");
+ assert!(my.contains("'literal [dbo].[y]'"), "{my}");
+ }
+
+ #[test]
+ fn sequence_rewrite_keeps_strings_intact() {
+ // SqlServer -> Dameng: `AS BIGINT` stripping must not touch a
+ // string literal that merely contains the token.
+ let ss_seq = "CREATE SEQUENCE [dbo].[s] AS BIGINT START WITH 1 COMMENT 'AS BIGINT in comment'";
+ let dm = convert_cross_family_object_ddl(
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::Sequence,
+ "dbo",
+ "TGT",
+ ss_seq,
+ );
+ assert!(dm.starts_with("CREATE SEQUENCE \"TGT\".\"s\" START WITH 1"), "{dm}");
+ assert!(!dm.contains("\"s\" AS BIGINT"), "{dm}");
+ assert!(dm.contains("'AS BIGINT in comment'"), "{dm}");
+ }
+
+ #[test]
+ fn rewrites_cross_family_sequence_ddl() {
+ // sqlserver -> dameng: strip AS type
+ let ss_seq =
+ "CREATE SEQUENCE [dbo].[seq1] AS BIGINT START WITH 5 INCREMENT BY 2 MINVALUE 1 MAXVALUE 1000 CACHE 50";
+ let dm = convert_cross_family_object_ddl(
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::Sequence,
+ "dbo",
+ "TGT",
+ ss_seq,
+ );
+ assert!(dm.starts_with("CREATE SEQUENCE \"TGT\".\"seq1\" START WITH 5"), "{dm}");
+ assert!(!dm.contains("AS BIGINT"));
+ assert!(dm.contains("CACHE 50"));
+
+ // dameng -> sqlserver: NO CYCLE spacing
+ let dm_seq = "CREATE SEQUENCE \"S\".\"SEQ1\" START WITH 1 INCREMENT BY 1 MINVALUE 1 NOCYCLE NOCACHE";
+ let ss = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Oracle,
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectKind::Sequence,
+ "S",
+ "dbo",
+ dm_seq,
+ );
+ assert!(ss.starts_with("CREATE SEQUENCE [dbo].[SEQ1]"), "{ss}");
+ assert!(ss.contains("NO CYCLE"), "{ss}");
+ assert!(ss.contains("NO CACHE"), "{ss}");
+ }
+
+ #[test]
+ fn rejects_unsupported_cross_family_objects_in_executor() {
+ let kinds = cross_family_transferable_object_kinds(&DatabaseType::Mysql, &DatabaseType::SqlServer);
+ // VIEW is disabled cross-family: only the DDL wrapper/quoting is
+ // rewritten, the query body is not translated
+ assert!(!kinds.contains(&View));
+ // procedures/triggers are never cross-family transferable
+ assert!(!kinds.contains(&Procedure));
+ assert!(!kinds.contains(&Trigger));
+ assert!(!kinds.contains(&Event));
+ assert!(!kinds.contains(&Function));
+ }
+
+ #[test]
+ fn qualifies_cross_family_view_target_schema() {
+ // mysql -> dameng: bare refs get the target schema prefix, prefixed
+ // refs keep their (rewritten) prefix
+ let mysql_view = "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `v` AS select a.id from `exam_record` a join `exam`.`t2` t on t.id = a.id";
+ let dm = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Mysql,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::View,
+ "exam",
+ "DM",
+ mysql_view,
+ );
+ assert!(dm.starts_with("CREATE VIEW \"DM\".\"v\" AS"), "{dm}");
+ assert!(dm.contains("from \"DM\".\"exam_record\" a"), "{dm}");
+ assert!(dm.contains("join \"DM\".\"t2\" t"), "{dm}");
+
+ // dameng -> mysql: quoted prefix style switches to backticks
+ let dm_view =
+ "CREATE OR REPLACE FORCE NONEDITIONABLE VIEW \"DM\".\"v\" AS select id from \"DM\".\"exam_record\"";
+ let my = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Oracle,
+ &TransferObjectFamily::Mysql,
+ &TransferObjectKind::View,
+ "DM",
+ "exam",
+ dm_view,
+ );
+ assert!(my.starts_with("CREATE VIEW `exam`.`v` AS"), "{my}");
+ assert!(my.contains("from `exam`.`exam_record`"), "{my}");
+
+ // sqlserver -> dameng
+ let ss_view = "CREATE VIEW [dbo].[v] WITH SCHEMABINDING AS select id from [dbo].[exam_record]";
+ let dm2 = convert_cross_family_object_ddl(
+ &TransferObjectFamily::SqlServer,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::View,
+ "dbo",
+ "TGT",
+ ss_view,
+ );
+ assert!(dm2.starts_with("CREATE VIEW \"TGT\".\"v\" AS"), "{dm2}");
+ assert!(dm2.contains("from \"TGT\".\"exam_record\""), "{dm2}");
+ }
+
+ #[test]
+ fn qualifies_cross_family_view_with_cjk_identifiers() {
+ // mysql -> dameng with Chinese table/view names
+ let mysql_view = "CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `成绩排名` AS select a.id from `用户表` a join `exam`.`成绩明细` t on t.id = a.id";
+ let dm = convert_cross_family_object_ddl(
+ &TransferObjectFamily::Mysql,
+ &TransferObjectFamily::Oracle,
+ &TransferObjectKind::View,
+ "exam",
+ "DM",
+ mysql_view,
+ );
+ assert!(dm.starts_with("CREATE VIEW \"DM\".\"成绩排名\" AS"), "{dm}");
+ assert!(dm.contains("from \"DM\".\"用户表\" a"), "{dm}");
+ assert!(dm.contains("join \"DM\".\"成绩明细\" t"), "{dm}");
+ }
+ }
+ mod transfer_mysql_ddl_tests {
+ use super::*;
+
+ #[test]
+ fn strips_mysql_definer_clauses() {
+ assert_eq!(strip_mysql_definer("CREATE DEFINER=`u`@`%` VIEW v AS SELECT 1"), "CREATE VIEW v AS SELECT 1");
+ assert_eq!(
+ strip_mysql_definer("CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` VIEW v AS SELECT 1"),
+ "CREATE ALGORITHM=UNDEFINED VIEW v AS SELECT 1"
+ );
+ assert_eq!(strip_mysql_definer("CREATE PROCEDURE p() BEGIN END"), "CREATE PROCEDURE p() BEGIN END");
+ }
+
+ #[test]
+ fn rewrites_mysql_schema_qualifiers() {
+ assert_eq!(
+ rewrite_mysql_schema_qualifier("CREATE VIEW `src`.`v` AS SELECT 1 FROM `src`.`t`", "src", "dst"),
+ "CREATE VIEW `dst`.`v` AS SELECT 1 FROM `dst`.`t`"
+ );
+ }
+
+ #[test]
+ fn assembles_mysql_trigger_and_event_ddl() {
+ let trigger = mysql_trigger_ddl("shop", "trg1", "BEFORE", "INSERT", "users", "SET NEW.updated = NOW()");
+ assert_eq!(
+ trigger,
+ "CREATE TRIGGER `trg1` BEFORE INSERT ON `shop`.`users` FOR EACH ROW SET NEW.updated = NOW()"
+ );
+ let event = mysql_event_ddl("shop", "ev1", "ENABLE", "EVERY 1 DAY", "DELETE FROM logs");
+ assert_eq!(event, "CREATE EVENT `ev1` ON SCHEDULE EVERY 1 DAY ENABLE DO DELETE FROM logs");
+ }
+ }
+
+ mod transfer_sqlserver_source_tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn builds_sqlserver_object_source_queries() {
+ let view = sqlserver_object_source_query(&TransferObjectKind::View, "dbo", "v1").unwrap();
+ assert!(view.contains("sys.sql_modules"), "{view}");
+ assert!(view.contains("o.type IN ('V')"), "{view}");
+ let routine = sqlserver_object_source_query(&TransferObjectKind::Procedure, "dbo", "p1").unwrap();
+ assert!(routine.contains("o.type IN ('P')"), "{routine}");
+ let trigger = sqlserver_object_source_query(&TransferObjectKind::Trigger, "dbo", "t1").unwrap();
+ assert!(trigger.contains("o.type IN ('TR')"), "{trigger}");
+ let seq = sqlserver_object_source_query(&TransferObjectKind::Sequence, "dbo", "s1").unwrap();
+ assert!(seq.contains("sys.sequences"), "{seq}");
+ assert!(!seq.contains("sys.sql_modules"), "{seq}");
+ }
+
+ #[test]
+ fn extracts_sqlserver_object_ddl_from_result() {
+ let view_result = test_query_result(vec![vec![json!("CREATE VIEW [dbo].[v1] AS SELECT 1 AS x")]]);
+ let ddl = sqlserver_object_ddl_from_result(&view_result, "dbo", "v1", &TransferObjectKind::View).unwrap();
+ assert_eq!(ddl, "CREATE VIEW [dbo].[v1] AS SELECT 1 AS x");
+
+ // start, increment, min, max, cycle, cache
+ let seq_result = test_query_result(vec![vec![
+ json!("1"),
+ json!("2"),
+ json!("5"),
+ json!("1000"),
+ json!("NO CYCLE"),
+ json!("50"),
+ ]]);
+ let seq_ddl =
+ sqlserver_object_ddl_from_result(&seq_result, "dbo", "s1", &TransferObjectKind::Sequence).unwrap();
+ assert!(
+ seq_ddl.starts_with("CREATE SEQUENCE [dbo].[s1] START WITH 1 INCREMENT BY 2 MINVALUE 5 MAXVALUE 1000"),
+ "{seq_ddl}"
+ );
+ assert!(seq_ddl.contains("NO CYCLE"), "{seq_ddl}");
+ assert!(seq_ddl.contains("CACHE 50"), "{seq_ddl}");
+ }
+ }
+ mod transfer_mysql_source_tests {
+ use super::*;
+
+ #[test]
+ fn builds_mysql_object_source_queries() {
+ let sql = mysql_object_source_query(&TransferObjectKind::View, "shop", "v1").unwrap();
+ assert!(sql.contains("SHOW CREATE VIEW"));
+ let sql = mysql_object_source_query(&TransferObjectKind::Trigger, "shop", "trg1").unwrap();
+ assert!(sql.contains("information_schema.TRIGGERS"));
+ assert!(sql.contains("TRIGGER_NAME = 'trg1'"));
+ let sql = mysql_object_source_query(&TransferObjectKind::Event, "shop", "ev1").unwrap();
+ assert!(sql.contains("information_schema.EVENTS"));
+ assert!(sql.contains("EVENT_NAME = 'ev1'"));
+ }
+
+ #[test]
+ fn extracts_mysql_object_ddl_from_result() {
+ let view = mysql_object_ddl_from_result(
+ &TransferObjectKind::View,
+ "shop",
+ &[vec![serde_json::json!("v1"), serde_json::json!("CREATE VIEW `shop`.`v1` AS SELECT 1")]],
+ )
+ .unwrap();
+ assert_eq!(view, "CREATE VIEW `shop`.`v1` AS SELECT 1");
+
+ let routine = mysql_object_ddl_from_result(
+ &TransferObjectKind::Procedure,
+ "shop",
+ &[vec![
+ serde_json::json!("p"),
+ serde_json::json!("PROCEDURE"),
+ serde_json::json!("CREATE PROCEDURE p() BEGIN END"),
+ ]],
+ )
+ .unwrap();
+ assert_eq!(routine, "CREATE PROCEDURE p() BEGIN END");
+
+ let trigger = mysql_object_ddl_from_result(
+ &TransferObjectKind::Trigger,
+ "shop",
+ &[vec![
+ serde_json::json!("trg1"),
+ serde_json::json!("BEFORE"),
+ serde_json::json!("INSERT"),
+ serde_json::json!("users"),
+ serde_json::json!("SET NEW.updated = NOW()"),
+ ]],
+ )
+ .unwrap();
+ assert_eq!(
+ trigger,
+ "CREATE TRIGGER `trg1` BEFORE INSERT ON `shop`.`users` FOR EACH ROW SET NEW.updated = NOW()"
+ );
+
+ let event = mysql_object_ddl_from_result(
+ &TransferObjectKind::Event,
+ "shop",
+ &[vec![
+ serde_json::json!("ev1"),
+ serde_json::json!("ENABLE"),
+ serde_json::json!("2026-01-01"),
+ serde_json::json!("1"),
+ serde_json::json!("DAY"),
+ serde_json::json!("DELETE FROM logs"),
+ ]],
+ )
+ .unwrap();
+ assert_eq!(event, "CREATE EVENT `ev1` ON SCHEDULE EVERY 1 DAY ENABLE DO DELETE FROM logs");
+ }
+ }
+
+ mod transfer_oracle_source_tests {
+ use super::*;
+
+ #[test]
+ fn builds_oracle_object_source_query() {
+ let sql = oracle_object_source_query(&TransferObjectKind::Trigger, "HR", "TRG1").unwrap();
+ assert!(sql.contains("DBMS_METADATA.GET_DDL('TRIGGER', 'TRG1', 'HR')"));
+ let sql = oracle_object_source_query(&TransferObjectKind::Sequence, "HR", "SEQ1").unwrap();
+ assert!(sql.contains("DBMS_METADATA.GET_DDL('SEQUENCE', 'SEQ1', 'HR')"));
+ let sql = oracle_object_source_query(&TransferObjectKind::View, "", "V1").unwrap();
+ assert!(!sql.contains(",'"));
+ }
+
+ #[test]
+ fn rewrites_oracle_schema_qualifiers() {
+ let ddl = "CREATE OR REPLACE TRIGGER \"HR\".\"TRG1\" ...";
+ assert_eq!(
+ rewrite_oracle_schema_qualifier(ddl, "HR", "APP"),
+ "CREATE OR REPLACE TRIGGER \"APP\".\"TRG1\" ..."
+ );
+ }
+ }
+
+ mod transfer_executor_tests {
+ use super::*;
+
+ #[test]
+ fn orders_object_selections_by_dependency() {
+ let kinds = vec![
+ TransferObjectKind::Trigger,
+ TransferObjectKind::View,
+ TransferObjectKind::Sequence,
+ TransferObjectKind::Event,
+ TransferObjectKind::Procedure,
+ TransferObjectKind::Function,
+ ];
+ let ordered = ordered_transfer_object_kinds(kinds);
+ assert_eq!(ordered[0], TransferObjectKind::Sequence);
+ assert_eq!(ordered[1], TransferObjectKind::View);
+ assert_eq!(ordered[2], TransferObjectKind::Function);
+ assert_eq!(ordered[3], TransferObjectKind::Procedure);
+ assert_eq!(ordered[4], TransferObjectKind::Trigger);
+ assert_eq!(ordered[5], TransferObjectKind::Event);
+ }
+ }
+
+ mod transfer_mysql_executor_tests {
+ use super::*;
+
+ #[test]
+ fn extracts_selected_names_by_kind() {
+ let selections = vec![
+ TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] },
+ TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v2".into()] },
+ TransferObjectSelection { object_type: TransferObjectKind::Trigger, names: vec!["t1".into()] },
+ ];
+ let views = selected_object_names(&selections, &TransferObjectKind::View);
+ assert_eq!(views, vec!["v1", "v2"]);
+ assert!(selected_object_names(&selections, &TransferObjectKind::Event).is_empty());
+ }
+ }
+
+ mod transfer_oracle_executor_tests {
+ use super::*;
+
+ #[test]
+ fn resolves_oracle_family_source_schema() {
+ assert_eq!(resolve_oracle_schema("", "HR"), "HR");
+ assert_eq!(resolve_oracle_schema("HR", "db"), "HR");
+ }
+ }
+
+ mod transfer_postgres_executor_tests {
+ use super::*;
+
+ #[test]
+ fn filters_postgres_object_sources_by_selection() {
+ let sources = vec![
+ db::ObjectSource {
+ name: "v1".into(),
+ object_type: db::ObjectSourceKind::View,
+ schema: Some("public".into()),
+ source: "SELECT 1".into(),
+ editable: None,
+ },
+ db::ObjectSource {
+ name: "v2".into(),
+ object_type: db::ObjectSourceKind::View,
+ schema: Some("public".into()),
+ source: "SELECT 2".into(),
+ editable: None,
+ },
+ ];
+ let selection =
+ vec![TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] }];
+ let filtered = filter_object_sources_by_selection(sources, &selection);
+ assert_eq!(filtered.len(), 1);
+ assert_eq!(filtered[0].name, "v1");
+ }
+ }
+
+ mod transfer_content_mode_tests {
+ use super::*;
+
+ #[test]
+ fn structure_only_skips_data_steps() {
+ assert!(should_copy_data(&TransferContent::StructureAndData));
+ assert!(should_copy_data(&TransferContent::DataOnly));
+ assert!(!should_copy_data(&TransferContent::StructureOnly));
+ }
+ }
fn test_transfer_request(tables: Vec<&str>) -> TransferRequest {
TransferRequest {
transfer_id: "transfer-1".to_string(),
@@ -5425,6 +7517,8 @@ mod tests {
target_catalog: None,
tables: tables.into_iter().map(str::to_string).collect(),
create_table: true,
+ content: TransferContent::default(),
+ objects: Vec::new(),
mode: TransferMode::Append,
target_table_name_case: TransferTableNameCase::Preserve,
ownership_policy: TransferOwnershipPolicy::Preserve,
diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rs
index 321af5f0cd..0c622211b8 100644
--- a/crates/dbx-core/tests/live_postgres_transfer.rs
+++ b/crates/dbx-core/tests/live_postgres_transfer.rs
@@ -218,6 +218,8 @@ async fn live_postgres_transfer_preserves_data_and_schema_objects() {
target_catalog: None,
tables: vec!["users".to_string(), "audit_logs".to_string(), "files".to_string()],
create_table: true,
+ content: dbx_core::transfer::TransferContent::default(),
+ objects: Vec::new(),
mode: TransferMode::Append,
target_table_name_case: TransferTableNameCase::Preserve,
ownership_policy: TransferOwnershipPolicy::Preserve,
@@ -501,6 +503,8 @@ async fn live_postgres_transfer_skips_create_ddl_for_existing_target_table() {
target_catalog: None,
tables: vec!["items".to_string()],
create_table: true,
+ content: dbx_core::transfer::TransferContent::default(),
+ objects: Vec::new(),
mode: TransferMode::Append,
target_table_name_case: TransferTableNameCase::Preserve,
ownership_policy: TransferOwnershipPolicy::Preserve,
diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rs
index aeb0fb895b..ec45101de9 100644
--- a/crates/dbx-core/tests/live_sqlserver_completion.rs
+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs
@@ -1361,6 +1361,8 @@ async fn live_sqlserver_transfer_table_skips_rowversion_insert_column() {
target_catalog: None,
tables: vec![source_table.clone()],
create_table: true,
+ content: dbx_core::transfer::TransferContent::default(),
+ objects: Vec::new(),
mode: dbx_core::transfer::TransferMode::Append,
target_table_name_case: dbx_core::transfer::TransferTableNameCase::Upper,
ownership_policy: dbx_core::transfer::TransferOwnershipPolicy::Preserve,
diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rs
index c000bcf8ae..a89e5cce60 100644
--- a/crates/dbx-web/src/routes/transfer.rs
+++ b/crates/dbx-web/src/routes/transfer.rs
@@ -78,7 +78,7 @@ pub async fn start_transfer(
Json(body): Json<StartTransferRequest>,
) -> Result<Json<serde_json::Value>, AppError> {
let req = body.request;
- transfer::validate_transfer_target_table_names(&req).map_err(AppError::from)?;
+ transfer::validate_transfer_request(&req).map_err(AppError::from)?;
// Reject transfer early if the target connection is read-only
if let Some(name) = dbx_core::query::connection_readonly_name(&state.app, &req.target_connection_id).await {
@@ -116,6 +116,22 @@ pub async fn start_transfer(
}
};
+ // Cross-family object transfers are validated inside transfer_schema_objects:
+ // only mechanically rewriteable kinds (views, sequences) are allowed; any
+ // other selection fails with a descriptive error. Structure-only data
+ // transfer is unsupported for MongoDB.
+ if matches!(req.content, transfer::TransferContent::StructureOnly)
+ && (matches!(source_db_type, dbx_core::models::connection::DatabaseType::MongoDb)
+ || matches!(target_db_type, dbx_core::models::connection::DatabaseType::MongoDb))
+ {
+ send_transfer_progress(
+ &progress_channel,
+ &terminal_transfer_error(&req, "MongoDB 暂不支持仅结构传输".to_string()),
+ );
+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;
+ return;
+ }
+
// External Doris/StarRocks catalogs: pool is created with `catalog=` URL
// setup (SET catalog) and without USE <external-db>. See ensure_transfer_pool.
let source_pool_key = match transfer::ensure_transfer_pool(
@@ -321,57 +337,65 @@ pub async fn start_transfer(
}
}
- if matches!(source_db_type, dbx_core::models::connection::DatabaseType::Postgres)
- && matches!(target_db_type, dbx_core::models::connection::DatabaseType::Postgres)
+ // Transfer selected non-table objects (views, procedures, functions,
+ // triggers, sequences, events) after the per-table loop. The shared
+ // Core decision handles all content modes: DataOnly never
+ // transfers schema objects; PG→PG keeps the legacy empty-selection
+ // default only when structure participates in the transfer.
+ let mut object_outcome = transfer::TransferObjectOutcome::default();
+ let progress_channel_clone = progress_channel.clone();
+ match transfer::transfer_schema_objects(&app, &req, &source_pool_key, &target_pool_key, |progress| {
+ send_transfer_progress(&progress_channel_clone, &progress);
+ })
+ .await
{
- let progress_channel_clone = progress_channel.clone();
- match transfer::transfer_postgres_schema_objects(
- &app,
- &req,
- &source_pool_key,
- &target_pool_key,
- |progress| {
- send_transfer_progress(&progress_channel_clone, &progress);
- },
- )
- .await
- {
- Ok(()) => {}
- Err(e) if e == "Cancelled" => {
- let progress = transfer::TransferProgress {
- transfer_id: req.transfer_id.clone(),
- table: "schema objects".to_string(),
- table_index: tables.len(),
- total_tables: tables.len(),
- rows_transferred: 0,
- total_rows: None,
- status: TransferStatus::Cancelled,
- error: None,
- terminal: true,
- };
- send_transfer_progress(&progress_channel, &progress);
- finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;
- return;
- }
- Err(e) => {
- failed_tables.push("schema objects".to_string());
- let progress = transfer::TransferProgress {
- transfer_id: req.transfer_id.clone(),
- table: "schema objects".to_string(),
- table_index: tables.len(),
- total_tables: tables.len(),
- rows_transferred: 0,
- total_rows: None,
- status: TransferStatus::Error,
- error: Some(e),
- terminal: false,
- };
- send_transfer_progress(&progress_channel, &progress);
- }
+ Ok(outcome) => {
+ object_outcome = outcome;
+ }
+ Err(e) if e == "Cancelled" => {
+ let progress = transfer::TransferProgress {
+ transfer_id: req.transfer_id.clone(),
+ table: "schema objects".to_string(),
+ table_index: tables.len(),
+ total_tables: tables.len(),
+ rows_transferred: 0,
+ total_rows: None,
+ status: TransferStatus::Cancelled,
+ error: None,
+ terminal: true,
+ };
+ send_transfer_progress(&progress_channel, &progress);
+ finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;
+ return;
+ }
+ Err(e) => {
+ failed_tables.push("schema objects".to_string());
+ let progress = transfer::TransferProgress {
+ transfer_id: req.transfer_id.clone(),
+ table: "schema objects".to_string(),
+ table_index: tables.len(),
+ total_tables: tables.len(),
+ rows_transferred: 0,
+ total_rows: None,
+ status: TransferStatus::Error,
+ error: Some(e),
+ terminal: false,
+ };
+ send_transfer_progress(&progress_channel, &progress);
}
}
// Send done
+ if !object_outcome.failed.is_empty() {
+ failed_tables.push(format!("schema objects ({})", object_outcome.failed.len()));
+ }
+ let skip_suffix = if !object_outcome.skipped.is_empty() && failed_tables.is_empty() {
+ format!(",跳过 {} 个已存在对象", object_outcome.skipped.len())
+ } else if !object_outcome.skipped.is_empty() {
+ format!(";跳过 {} 个已存在对象", object_outcome.skipped.len())
+ } else {
+ String::new()
+ };
let done = transfer::TransferProgress {
transfer_id: req.transfer_id.clone(),
table: String::new(),
@@ -381,12 +405,17 @@ pub async fn start_transfer(
total_rows: None,
status: if failed_tables.is_empty() { TransferStatus::Done } else { TransferStatus::Error },
error: if failed_tables.is_empty() {
- None
+ if skip_suffix.is_empty() {
+ None
+ } else {
+ Some(skip_suffix.clone())
+ }
} else {
Some(format!(
- "{} table(s) failed: {}",
+ "{} table(s) failed: {}{}",
failed_tables.len(),
- failed_tables.iter().take(5).cloned().collect::<Vec<_>>().join(", ")
+ failed_tables.iter().take(5).cloned().collect::<Vec<_>>().join(", "),
+ skip_suffix
))
},
terminal: true,
@@ -403,7 +432,7 @@ pub async fn preview_transfer_ownership(
Json(body): Json<PreviewTransferOwnershipRequest>,
) -> Result<Json<dbx_core::transfer::TransferOwnershipPreview>, AppError> {
let req = body.request;
- transfer::validate_transfer_target_table_names(&req).map_err(AppError::from)?;
+ transfer::validate_transfer_request(&req).map_err(AppError::from)?;
let source_db_type = transfer::get_db_type(&state.app, &req.source_connection_id).await.map_err(AppError::from)?;
let target_db_type = transfer::get_db_type(&state.app, &req.target_connection_id).await.map_err(AppError::from)?;
let source_pool_key = transfer::ensure_transfer_pool(
@@ -480,3 +509,164 @@ pub async fn sort_tables_by_fk_dependency(
.map(Json)
.map_err(AppError::from)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::extract::State;
+ use axum::response::IntoResponse;
+ use dbx_core::connection::AppState;
+ use dbx_core::models::connection::{
+ default_connect_timeout_secs, default_idle_timeout_secs, default_keepalive_interval_secs,
+ default_query_timeout_secs, ConnectionConfig, DatabaseType,
+ };
+ use dbx_core::storage::Storage;
+ use dbx_core::transfer::{
+ TransferContent, TransferMode, TransferOwnershipPolicy, TransferRequest, TransferTableNameCase,
+ };
+
+ fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {
+ ConnectionConfig {
+ id: id.to_string(),
+ name: "SQLite".to_string(),
+ note: String::new(),
+ db_type: DatabaseType::Sqlite,
+ driver_profile: None,
+ driver_label: None,
+ url_params: None,
+ agent_java_options: Vec::new(),
+ host: path.to_string(),
+ port: 0,
+ username: String::new(),
+ password: String::new(),
+ database: None,
+ visible_databases: None,
+ visible_schemas: None,
+ show_system_schemas: false,
+ attached_databases: Vec::new(),
+ init_script: None,
+ color: None,
+ transport_layers: Vec::new(),
+ connect_timeout_secs: default_connect_timeout_secs(),
+ query_timeout_secs: default_query_timeout_secs(),
+ idle_timeout_secs: default_idle_timeout_secs(),
+ keepalive_interval_secs: default_keepalive_interval_secs(),
+ ssl: false,
+ ca_cert_path: String::new(),
+ client_cert_path: String::new(),
+ client_key_path: String::new(),
+ sysdba: false,
+ oracle_connection_type: None,
+ connection_string: None,
+ redis_connection_mode: None,
+ redis_sentinel_master: String::new(),
+ redis_sentinel_nodes: String::new(),
+ redis_sentinel_username: String::new(),
+ redis_sentinel_password: String::new(),
+ redis_sentinel_tls: false,
+ redis_cluster_nodes: String::new(),
+ redis_key_separator: dbx_core::models::connection::default_redis_key_separator(),
+ redis_scan_page_size: None,
+ redis_database_aliases: Default::default(),
+ etcd_endpoints: String::new(),
+ gbase_server: String::new(),
+ informix_server: String::new(),
+ external_config: None,
+ jdbc_driver_class: None,
+ jdbc_driver_paths: Vec::new(),
+ one_time: false,
+ read_only: false,
+ is_production: false,
+ production_databases: vec![],
+ database_info: None,
+ }
+ }
+
+ async fn test_web_state() -> (Arc<WebState>, std::path::PathBuf) {
+ let dir = std::env::temp_dir().join(format!("dbx-web-transfer-test-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();
+ let app = Arc::new(AppState::new_with_plugin_dir(storage, dir.join("plugins")));
+ let state = Arc::new(WebState::for_tests(app, dir.clone()));
+ (state, dir)
+ }
+
+ fn transfer_request(source: &str, target: &str, dir: &std::path::Path) -> TransferRequest {
+ let db = dir.join("main.db").to_string_lossy().to_string();
+ TransferRequest {
+ transfer_id: "transfer-entry-test".to_string(),
+ source_connection_id: source.to_string(),
+ source_database: db.clone(),
+ source_schema: "main".to_string(),
+ source_catalog: None,
+ target_connection_id: target.to_string(),
+ target_database: db,
+ target_schema: "main".to_string(),
+ target_catalog: None,
+ tables: Vec::new(),
+ create_table: false,
+ content: TransferContent::DataOnly,
+ objects: Vec::new(),
+ mode: TransferMode::Append,
+ target_table_name_case: TransferTableNameCase::Preserve,
+ ownership_policy: TransferOwnershipPolicy::Preserve,
+ batch_size: 1000,
+ }
+ }
+
+ #[tokio::test]
+ async fn data_only_empty_object_selection_completes_through_the_core_noop() {
+ let (state, dir) = test_web_state().await;
+ let src = sqlite_config("src", &dir.join("src.db").to_string_lossy());
+ let dst = sqlite_config("dst", &dir.join("dst.db").to_string_lossy());
+ // SQLite pools need the backing files to exist before connecting.
+ std::fs::write(dir.join("src.db"), b"").unwrap();
+ std::fs::write(dir.join("dst.db"), b"").unwrap();
+ std::fs::write(dir.join("main.db"), b"").unwrap();
+ state.app.configs.write().await.insert("src".to_string(), src);
+ state.app.configs.write().await.insert("dst".to_string(), dst);
+
+ let req = transfer_request("src", "dst", &dir);
+ let transfer_id = req.transfer_id.clone();
+ let response = start_transfer(State(state.clone()), Json(StartTransferRequest { request: req })).await.unwrap();
+ let _ = response.into_response();
+
+ // Both HTTP and Tauri call the same Core schema-object stage
+ // unconditionally. DataOnly must resolve there to a no-op without an
+ // object progress event or database-family fallback.
+ let channel = {
+ let channels = state.transfer_progress_channels.read().await;
+ channels.get(&transfer_id).cloned().expect("transfer channel registered")
+ };
+ let mut saw_terminal = false;
+ let mut saw_schema_objects = false;
+ let mut terminal_error: Option<String> = None;
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
+ while !saw_terminal {
+ if let Some(data) = channel.latest() {
+ let value: serde_json::Value = serde_json::from_str(&data).unwrap();
+ if value["table"].as_str() == Some("schema objects") {
+ saw_schema_objects = true;
+ }
+ if value["terminal"].as_bool() == Some(true) {
+ saw_terminal = true;
+ terminal_error = value["error"].as_str().map(|s| s.to_string());
+ }
+ }
+ if saw_terminal {
+ break;
+ }
+ if std::time::Instant::now() > deadline {
+ panic!("transfer did not reach a terminal event within 15s");
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert!(saw_terminal, "transfer must reach a terminal event");
+ assert!(!saw_schema_objects, "DataOnly must not transfer schema objects");
+ assert!(
+ terminal_error.is_none(),
+ "DataOnly must complete without a schema-object error, got: {terminal_error:?}"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/dbx-web/src/sse.rs b/crates/dbx-web/src/sse.rs
index 20f8988a2f..43373e7a94 100644
--- a/crates/dbx-web/src/sse.rs
+++ b/crates/dbx-web/src/sse.rs
@@ -67,6 +67,13 @@ impl TransferProgressChannel {
let _ = self.tx.send(data);
}
+ /// The most recently sent progress payload, if any. Used by tests to wait
+ /// for a terminal event without subscribing to the live stream.
+ #[cfg(test)]
+ pub fn latest(&self) -> Option<String> {
+ self.history.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).latest.clone()
+ }
+
fn subscribe(&self) -> (Vec<String>, usize, broadcast::Receiver<String>) {
// Subscribe while holding the history lock so an event is either in the
// replay snapshot or in the live receiver, with no gap between them.
diff --git a/docs/superpowers/plans/2026-08-01-data-transfer-tree-selection.md b/docs/superpowers/plans/2026-08-01-data-transfer-tree-selection.md
new file mode 100644
index 0000000000..9d1cfa7f60
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-01-data-transfer-tree-selection.md
@@ -0,0 +1,1620 @@
+# Data Transfer: Tree Object Selection and Transfer Modes — Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Turn the data transfer dialog's flat table picker into a type-grouped object tree (tables/views/procedures/functions/triggers/sequences/events) with three transfer modes (structure+data / structure only / data only), and copy non-table object DDL for PostgreSQL-family, MySQL, and Oracle/Dameng.
+
+**Architecture:** Backend `TransferRequest` gains `content` (TransferContent) and `objects` (Vec<TransferObjectSelection>); a new family-aware object transfer executor (`transfer_schema_objects`) runs after table data transfer, checking target existence per object (skip + count) and executing DDL in dependency order (sequences → views → functions → procedures → triggers → events). Frontend `DataTransferDialog.vue` swaps the flat list for an `ObjectSelectionTree` group component and a three-way content mode selector.
+
+**Tech Stack:** Rust (dbx-core, dbx-web), Vue 3 + TypeScript + Vitest (apps/desktop), i18n locales.
+
+**Branch:** create `feature/data-transfer-tree-selection` from current HEAD. The `docs/superpowers/` directory is git-ignored and never committed.
+
+**Spec:** `docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md` (local, untracked).
+
+---
+
+## Task 0: Branch setup
+
+- [ ] **Step 1: Create the feature branch**
+
+```bash
+cd /d/git-clone-project/dbx && git checkout -b feature/data-transfer-tree-selection
+```
+
+Expected: switched to new branch. Note: it will carry the committed dameng-drop-schema fix (75238cde3) forward.
+
+---
+
+## Task 1: Backend protocol — TransferContent / TransferObjectKind / TransferObjectSelection
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs` (after `TransferMode` definition, ~line 67; and `TransferRequest` struct at line 80)
+
+- [ ] **Step 1: Write the failing test** — add a `#[cfg(test)] mod protocol_tests` at the end of `transfer.rs` asserting serde round-trips and defaults:
+
+```rust
+#[cfg(test)]
+mod transfer_protocol_tests {
+ use super::*;
+
+ #[test]
+ fn transfer_content_defaults_to_structure_and_data() {
+ let request: TransferRequest = serde_json::from_value(serde_json::json!({
+ "transferId": "t1", "sourceConnectionId": "s", "sourceDatabase": "db",
+ "sourceSchema": "public", "targetConnectionId": "t", "targetDatabase": "db",
+ "targetSchema": "public", "tables": ["a"], "createTable": true,
+ "mode": "append", "targetTableNameCase": "preserve", "batchSize": 1000
+ })).unwrap();
+ assert_eq!(request.content, TransferContent::StructureAndData);
+ assert!(request.objects.is_empty());
+ }
+
+ #[test]
+ fn transfer_request_serializes_new_fields_camel_case() {
+ let request = TransferRequest {
+ transfer_id: "t1".into(), source_connection_id: "s".into(),
+ source_database: "db".into(), source_schema: "public".into(), source_catalog: None,
+ target_connection_id: "t".into(), target_database: "db".into(),
+ target_schema: "public".into(), target_catalog: None,
+ tables: vec!["a".into()], create_table: true,
+ mode: TransferMode::Append, target_table_name_case: TransferTableNameCase::Preserve,
+ ownership_policy: TransferOwnershipPolicy::Preserve, batch_size: 1000,
+ content: TransferContent::StructureOnly,
+ objects: vec![TransferObjectSelection {
+ object_type: TransferObjectKind::View,
+ names: vec!["v1".into()],
+ }],
+ };
+ let json = serde_json::to_value(&request).unwrap();
+ assert_eq!(json["content"], "structureOnly");
+ assert_eq!(json["objects"][0]["objectType"], "VIEW");
+ assert_eq!(json["objects"][0]["names"][0], "v1");
+ }
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core transfer_protocol_tests 2>&1 | tail -5`
+Expected: FAIL — `content`/`objects` fields and enums do not exist yet.
+
+- [ ] **Step 3: Implement the protocol types** — insert after the `TransferMode` enum (line ~67):
+
+```rust
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum TransferContent {
+ #[default]
+ StructureAndData,
+ StructureOnly,
+ DataOnly,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum TransferObjectKind {
+ Table,
+ View,
+ MaterializedView,
+ Procedure,
+ Function,
+ Trigger,
+ Sequence,
+ Event,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
+pub struct TransferObjectSelection {
+ pub object_type: TransferObjectKind,
+ pub names: Vec<String>,
+}
+```
+
+Add to `TransferRequest` (after `tables`, keeping `create_table` for wire compatibility):
+
+```rust
+ #[serde(default)]
+ pub content: TransferContent,
+ #[serde(default)]
+ pub objects: Vec<TransferObjectSelection>,
+```
+
+Note: `TransferRequest` is constructed in tests (`transfer.rs:5364` area uses `create_table: true`) and in `crates/dbx-core/tests/live_postgres_transfer.rs` — all construction sites need the two new fields added. Fix compile errors by adding `content: TransferContent::default(), objects: Vec::new(),` wherever a literal is built.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core transfer_protocol_tests 2>&1 | tail -5`
+Expected: PASS (2 tests).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): add content and object selection protocol fields"
+```
+
+---
+
+## Task 2: Transfer object families and per-family kind tables
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** (module `transfer_family_tests`):
+
+```rust
+#[test]
+fn same_family_matrix() {
+ // postgres family
+ assert!(is_same_transfer_family(&DatabaseType::Postgres, &DatabaseType::Kingbase));
+ assert!(is_same_transfer_family(&DatabaseType::Gaussdb, &DatabaseType::OpenGauss));
+ // oracle family
+ assert!(is_same_transfer_family(&DatabaseType::Oracle, &DatabaseType::Dameng));
+ assert!(is_same_transfer_family(&DatabaseType::OceanbaseOracle, &DatabaseType::Dameng));
+ // mysql
+ assert!(is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::Mysql));
+ // cross family
+ assert!(!is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::Postgres));
+ assert!(!is_same_transfer_family(&DatabaseType::Mysql, &DatabaseType::SqlServer));
+}
+
+#[test]
+fn object_kinds_per_family() {
+ let mysql = transfer_object_kinds(&DatabaseType::Mysql);
+ assert!(mysql.contains(&TransferObjectKind::Event));
+ assert!(!mysql.contains(&TransferObjectKind::Sequence));
+ let pg = transfer_object_kinds(&DatabaseType::Postgres);
+ assert!(pg.contains(&TransferObjectKind::Sequence));
+ assert!(!pg.contains(&TransferObjectKind::Event));
+ let dm = transfer_object_kinds(&DatabaseType::Dameng);
+ assert!(dm.contains(&TransferObjectKind::Trigger));
+ assert!(dm.contains(&TransferObjectKind::Sequence));
+ assert!(transfer_object_kinds(&DatabaseType::Sqlite).is_empty());
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core transfer_family_tests 2>&1 | tail -5`
+Expected: FAIL — functions undefined.
+
+- [ ] **Step 3: Implement** — add near the top of `transfer.rs`:
+
+```rust
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TransferObjectFamily { Mysql, Postgres, Oracle }
+
+pub fn transfer_object_family(db_type: &DatabaseType) -> Option<TransferObjectFamily> {
+ match db_type {
+ DatabaseType::Mysql => Some(TransferObjectFamily::Mysql),
+ DatabaseType::Postgres
+ | DatabaseType::Kingbase
+ | DatabaseType::Gaussdb
+ | DatabaseType::Kwdb
+ | DatabaseType::OpenGauss => Some(TransferObjectFamily::Postgres),
+ DatabaseType::Oracle | DatabaseType::Dameng | DatabaseType::OceanbaseOracle => {
+ Some(TransferObjectFamily::Oracle)
+ }
+ _ => None,
+ }
+}
+
+pub fn is_same_transfer_family(a: &DatabaseType, b: &DatabaseType) -> bool {
+ match (transfer_object_family(a), transfer_object_family(b)) {
+ (Some(fa), Some(fb)) => fa == fb,
+ _ => false,
+ }
+}
+
+pub fn transfer_object_kinds(db_type: &DatabaseType) -> Vec<TransferObjectKind> {
+ use TransferObjectKind::*;
+ match transfer_object_family(db_type) {
+ Some(TransferObjectFamily::Mysql) => {
+ vec![Table, View, Procedure, Function, Trigger, Event]
+ }
+ Some(TransferObjectFamily::Postgres) => {
+ vec![Table, View, MaterializedView, Procedure, Function, Trigger, Sequence]
+ }
+ Some(TransferObjectFamily::Oracle) => {
+ vec![Table, View, MaterializedView, Procedure, Function, Trigger, Sequence]
+ }
+ None => Vec::new(),
+ }
+}
+```
+
+Check `DatabaseType` variant names in `crates/dbx-core/src/models/connection.rs` (OceanbaseOracle may be `OceanbaseOracle` — verify; `Kwdb`/`Gaussdb` exist per `build_drop_schema_sql` match at line 583).
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core transfer_family_tests 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): add object transfer families and per-family kind tables"
+```
+
+---
+
+## Task 3: Request validation for content and objects
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs` (extend `validate_transfer_target_table_names` area — add a new `validate_transfer_request`)
+
+- [ ] **Step 1: Write the failing test**:
+
+```rust
+#[test]
+fn validates_content_and_object_rules() {
+ let base = TransferRequest {
+ transfer_id: "t".into(), source_connection_id: "s".into(), source_database: "db".into(),
+ source_schema: "public".into(), source_catalog: None, target_connection_id: "t".into(),
+ target_database: "db".into(), target_schema: "public".into(), target_catalog: None,
+ tables: vec!["a".into()], create_table: true, mode: TransferMode::Append,
+ target_table_name_case: TransferTableNameCase::Preserve,
+ ownership_policy: TransferOwnershipPolicy::Preserve, batch_size: 1000,
+ content: TransferContent::DataOnly, objects: Vec::new(),
+ };
+ assert!(validate_transfer_request(&base).is_ok());
+
+ let with_objects = TransferRequest {
+ objects: vec![TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v".into()] }],
+ ..base.clone()
+ };
+ // DataOnly + objects → error
+ assert!(validate_transfer_request(&with_objects).is_err());
+
+ let structure_only = TransferRequest { content: TransferContent::StructureOnly, ..base.clone() };
+ assert!(validate_transfer_request(&structure_only).is_ok());
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core validates_content_and_object_rules 2>&1 | tail -5`
+Expected: FAIL — function undefined.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+pub fn validate_transfer_request(request: &TransferRequest) -> Result<(), String> {
+ validate_transfer_target_table_names(request)?;
+ if matches!(request.content, TransferContent::DataOnly) && !request.objects.is_empty() {
+ return Err("仅数据模式不传输非表对象".to_string());
+ }
+ for selection in &request.objects {
+ if selection.names.is_empty() {
+ return Err(format!("Object selection for {:?} is empty", selection.object_type));
+ }
+ for name in &selection.names {
+ if name.trim().is_empty() || name.contains('\0') {
+ return Err(format!("Invalid object name: {name:?}"));
+ }
+ }
+ }
+ Ok(())
+}
+```
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core validates_content_and_object_rules 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): validate transfer content and object selections"
+```
+
+---
+
+## Task 4: Target-side object existence check SQL (per family)
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test**:
+
+```rust
+#[test]
+fn builds_target_existence_check_sql_per_family() {
+ let mysql = target_object_exists_sql(&DatabaseType::Mysql, "shop", "v1", &TransferObjectKind::View).unwrap();
+ assert!(mysql.contains("information_schema.TABLES"));
+ assert!(mysql.contains("TABLE_TYPE = 'VIEW'"));
+ let mysql_ev = target_object_exists_sql(&DatabaseType::Mysql, "shop", "e1", &TransferObjectKind::Event).unwrap();
+ assert!(mysql_ev.contains("information_schema.EVENTS"));
+ let mysql_tr = target_object_exists_sql(&DatabaseType::Mysql, "shop", "t1", &TransferObjectKind::Trigger).unwrap();
+ assert!(mysql_tr.contains("information_schema.TRIGGERS"));
+ let pg = target_object_exists_sql(&DatabaseType::Postgres, "public", "v1", &TransferObjectKind::View).unwrap();
+ assert!(pg.contains("pg_class"));
+ let orc = target_object_exists_sql(&DatabaseType::Oracle, "HR", "SEQ1", &TransferObjectKind::Sequence).unwrap();
+ assert!(orc.contains("ALL_OBJECTS"));
+ assert!(target_object_exists_sql(&DatabaseType::Sqlite, "m", "x", &TransferObjectKind::View).is_err());
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core builds_target_existence_check_sql 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+/// Returns a SQL statement selecting 1 row when `name` exists in `schema`
+/// on the target side; None-kind support per family mirrors
+/// `transfer_object_kinds`.
+pub fn target_object_exists_sql(
+ db_type: &DatabaseType,
+ schema: &str,
+ name: &str,
+ kind: &TransferObjectKind,
+) -> Result<String, String> {
+ let schema = quote_string_literal(schema);
+ let name = quote_string_literal(name);
+ let q = |literal: &str| literal.to_string();
+ let sql = match (transfer_object_family(db_type), kind) {
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Table | TransferObjectKind::View) => format!(
+ "SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = {schema} AND TABLE_NAME = {name} \
+ AND TABLE_TYPE {} 'VIEW'",
+ if matches!(kind, TransferObjectKind::View) { "=" } else { "<>" }
+ ),
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Procedure | TransferObjectKind::Function) => format!(
+ "SELECT 1 FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = {schema} AND ROUTINE_NAME = {name} \
+ AND ROUTINE_TYPE = {}",
+ q(if matches!(kind, TransferObjectKind::Procedure) { "'PROCEDURE'" } else { "'FUNCTION'" })
+ ),
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Trigger) => format!(
+ "SELECT 1 FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = {schema} AND TRIGGER_NAME = {name}"
+ ),
+ (Some(TransferObjectFamily::Mysql), TransferObjectKind::Event) => format!(
+ "SELECT 1 FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {schema} AND EVENT_NAME = {name}"
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::View | TransferObjectKind::MaterializedView) => format!(
+ "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind {}",
+ if matches!(kind, TransferObjectKind::MaterializedView) { "= 'm'" } else { "= 'v'" }
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Table) => format!(
+ "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind = 'r'"
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Procedure | TransferObjectKind::Function) => format!(
+ "SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace \
+ WHERE n.nspname = {schema} AND p.proname = {name}"
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Sequence) => format!(
+ "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND c.relname = {name} AND c.relkind = 'S'"
+ ),
+ (Some(TransferObjectFamily::Postgres), TransferObjectKind::Trigger) => format!(
+ "SELECT 1 FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid \
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
+ WHERE n.nspname = {schema} AND t.tgname = {name} AND NOT t.tgisinternal"
+ ),
+ (Some(TransferObjectFamily::Oracle), TransferObjectKind::View
+ | TransferObjectKind::MaterializedView
+ | TransferObjectKind::Procedure
+ | TransferObjectKind::Function
+ | TransferObjectKind::Trigger
+ | TransferObjectKind::Sequence) => format!(
+ "SELECT 1 FROM ALL_OBJECTS WHERE OWNER = {schema} AND OBJECT_NAME = {name} AND OBJECT_TYPE = {}",
+ q(match kind {
+ TransferObjectKind::View => "'VIEW'",
+ TransferObjectKind::MaterializedView => "'MATERIALIZED VIEW'",
+ TransferObjectKind::Procedure => "'PROCEDURE'",
+ TransferObjectKind::Function => "'FUNCTION'",
+ TransferObjectKind::Trigger => "'TRIGGER'",
+ _ => "'SEQUENCE'",
+ })
+ ),
+ _ => return Err(format!("Object existence check not supported for {:?} {:?}", db_type, kind)),
+ };
+ Ok(sql)
+}
+```
+
+Verify `quote_string_literal` exists in transfer.rs (used at line 3717) — yes.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core builds_target_existence_check_sql 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): target object existence check SQL per family"
+```
+
+---
+
+## Task 5: MySQL list_objects gains TRIGGER and EVENT
+
+**Files:**
+- Modify: `crates/dbx-core/src/db/mysql.rs` (`list_objects` at 2844, `wants_table_objects`/`wants_routine_objects` at 2722, `object_query_supports_paging` at 2825)
+
+- [ ] **Step 1: Write the failing test** — add to existing test module in mysql.rs (pattern: `assert!(sql.contains("information_schema.TRIGGERS"))` at 5004):
+
+```rust
+#[test]
+fn lists_triggers_and_events_via_information_schema() {
+ let sql = list_triggers_objects_sql("shop");
+ assert!(sql.contains("information_schema.TRIGGERS"));
+ assert!(sql.contains("TRIGGER_SCHEMA = 'shop'"));
+ let sql = list_events_objects_sql("shop");
+ assert!(sql.contains("information_schema.EVENTS"));
+ assert!(sql.contains("EVENT_SCHEMA = 'shop'"));
+ assert!(wants_trigger_objects(Some(&["TRIGGER".to_string()])));
+ assert!(!wants_trigger_objects(Some(&["TABLE".to_string()])));
+ assert!(wants_event_objects(Some(&["EVENT".to_string()])));
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core lists_triggers_and_events 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement** — add functions mirroring `list_completion_triggers_sql` (2791) and `list_routines_sql` (2763):
+
+```rust
+fn wants_trigger_objects(object_types: Option<&[String]>) -> bool {
+ requested_object_type(object_types, "TRIGGER")
+}
+fn wants_event_objects(object_types: Option<&[String]>) -> bool {
+ requested_object_type(object_types, "EVENT")
+}
+
+fn list_triggers_objects_sql(database: &str) -> String {
+ format!(
+ "SELECT TRIGGER_NAME AS object_name, 'TRIGGER' AS object_type, NULL AS object_comment, \
+ CREATED AS created_at, NULL AS updated_at, \
+ TRIGGER_SCHEMA AS parent_schema, EVENT_OBJECT_TABLE AS parent_name, \
+ 5 AS sort_order \
+ FROM information_schema.TRIGGERS \
+ WHERE TRIGGER_SCHEMA = {} \
+ ORDER BY object_name",
+ quote_value(database)
+ )
+}
+
+fn list_events_objects_sql(database: &str) -> String {
+ format!(
+ "SELECT EVENT_NAME AS object_name, 'EVENT' AS object_type, NULL AS object_comment, \
+ CREATED AS created_at, LAST_ALTERED AS updated_at, \
+ EVENT_SCHEMA AS parent_schema, NULL AS parent_name, \
+ 6 AS sort_order \
+ FROM information_schema.EVENTS \
+ WHERE EVENT_SCHEMA = {} \
+ ORDER BY object_name",
+ quote_value(database)
+ )
+}
+```
+
+Wire into `list_objects` (after the routines block): fetch both lists when `wants_trigger_objects`/`wants_event_objects` and extend `objects` with `row_to_object`. Verify `requested_object_type`/`quote_value`/`row_to_object` signatures and reuse them.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core lists_triggers_and_events 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/db/mysql.rs
+git commit -m "feat(mysql): list triggers and events for object browsing"
+```
+
+---
+
+## Task 6: MySQL object DDL assembly for transfer
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** (pure-string functions; no DB needed):
+
+```rust
+#[test]
+fn strips_mysql_definer_clauses() {
+ assert_eq!(
+ strip_mysql_definer("CREATE DEFINER=`u`@`%` VIEW v AS SELECT 1"),
+ "CREATE VIEW v AS SELECT 1"
+ );
+ assert_eq!(strip_mysql_definer("CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` VIEW v AS SELECT 1"),
+ "CREATE ALGORITHM=UNDEFINED VIEW v AS SELECT 1");
+ assert_eq!(strip_mysql_definer("CREATE PROCEDURE p() BEGIN END"), "CREATE PROCEDURE p() BEGIN END");
+}
+
+#[test]
+fn rewrites_mysql_schema_qualifiers() {
+ assert_eq!(
+ rewrite_mysql_schema_qualifier("CREATE VIEW `src`.`v` AS SELECT 1 FROM `src`.`t`", "src", "dst"),
+ "CREATE VIEW `dst`.`v` AS SELECT 1 FROM `dst`.`t`"
+ );
+}
+
+#[test]
+fn assembles_mysql_trigger_and_event_ddl() {
+ let trigger = mysql_trigger_ddl("shop", "trg1", "BEFORE", "INSERT", "users", "SET NEW.updated = NOW()");
+ assert_eq!(trigger, "CREATE TRIGGER `trg1` BEFORE INSERT ON `shop`.`users` FOR EACH ROW SET NEW.updated = NOW()");
+ let event = mysql_event_ddl("shop", "ev1", "ENABLE", "EVERY 1 DAY", "DELETE FROM logs");
+ assert_eq!(event, "CREATE EVENT `ev1` ON SCHEDULE EVERY 1 DAY ENABLE DO DELETE FROM logs");
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core strips_mysql_definer_clauses 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement** — pure functions in `transfer.rs`:
+
+```rust
+/// Remove `DEFINER=`user`@`host`` tokens from MySQL DDL (they are not
+/// transferable and frequently reference accounts that don't exist on target).
+pub fn strip_mysql_definer(ddl: &str) -> String {
+ let re = Regex::new(r"(?i)\bDEFINER\s*=\s*`[^`]*`@`[^`]*`\s*").unwrap();
+ re.replace_all(ddl, "").to_string()
+}
+
+/// Rewrite backtick-qualified `schema`.`name` references from `source_schema`
+/// to `target_schema` in MySQL DDL.
+pub fn rewrite_mysql_schema_qualifier(ddl: &str, source_schema: &str, target_schema: &str) -> String {
+ if source_schema == target_schema || source_schema.is_empty() {
+ return ddl.to_string();
+ }
+ let re = Regex::new(&format!(r"`{}`\.", regex::escape(source_schema))).unwrap();
+ re.replace_all(ddl, &format!("`{}`.", target_schema)).to_string()
+}
+
+pub fn mysql_trigger_ddl(schema: &str, name: &str, timing: &str, manipulation: &str, table: &str, statement: &str) -> String {
+ format!(
+ "CREATE TRIGGER `{name}` {timing} {manipulation} ON `{schema}`.`{table}` FOR EACH ROW {statement}",
+ name = name, timing = timing, manipulation = manipulation,
+ schema = schema, table = table, statement = statement.trim()
+ )
+}
+
+pub fn mysql_event_ddl(schema: &str, name: &str, status: &str, schedule: &str, body: &str) -> String {
+ format!(
+ "CREATE EVENT `{name}` ON SCHEDULE {schedule} {status} DO {body}",
+ name = name, schedule = schedule, status = status, body = body.trim()
+ )
+}
+```
+
+Note: `Regex` is already imported in transfer.rs (line 1).
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core strips_mysql_definer_clauses 2>&1 | tail -5`
+Expected: PASS (3 tests).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): mysql object DDL helpers (definer strip, schema rewrite, trigger/event assembly)"
+```
+
+---
+
+## Task 7: MySQL object source fetching for transfer
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** (SQL generation only):
+
+```rust
+#[test]
+fn builds_mysql_object_source_queries() {
+ let sql = mysql_object_source_query(&TransferObjectKind::View, "shop", "v1").unwrap();
+ assert!(sql.contains("SHOW CREATE VIEW"));
+ let sql = mysql_object_source_query(&TransferObjectKind::Trigger, "shop", "trg1").unwrap();
+ assert!(sql.contains("information_schema.TRIGGERS"));
+ assert!(sql.contains("TRIGGER_NAME = 'trg1'"));
+ let sql = mysql_object_source_query(&TransferObjectKind::Event, "shop", "ev1").unwrap();
+ assert!(sql.contains("information_schema.EVENTS"));
+ assert!(sql.contains("EVENT_NAME = 'ev1'"));
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core builds_mysql_object_source_queries 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+/// Builds the query that fetches DDL for one MySQL object.
+/// - View/Procedure/Function → `SHOW CREATE ...` (existing
+/// `schema::mysql_object_source_sql` shape; reuse it by importing the
+/// function or duplicating the format strings).
+/// - Trigger → information_schema.TRIGGERS row (timing/manipulation/table/
+/// statement) via `mysql_trigger_ddl`.
+/// - Event → information_schema.EVENTS row via `mysql_event_ddl`.
+pub fn mysql_object_source_query(
+ kind: &TransferObjectKind,
+ database: &str,
+ name: &str,
+) -> Result<String, String> {
+ let db = quote_string_literal(database);
+ let n = quote_string_literal(name);
+ let ddl = match kind {
+ TransferObjectKind::View => format!("SHOW CREATE VIEW `{database}`.`{name}`"),
+ TransferObjectKind::Procedure => format!("SHOW CREATE PROCEDURE `{database}`.`{name}`"),
+ TransferObjectKind::Function => format!("SHOW CREATE FUNCTION `{database}`.`{name}`"),
+ TransferObjectKind::Trigger => format!(
+ "SELECT TRIGGER_NAME, ACTION_TIMING, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_STATEMENT \
+ FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = {db} AND TRIGGER_NAME = {n}"
+ ),
+ TransferObjectKind::Event => format!(
+ "SELECT EVENT_NAME, STATUS, EXECUTE_AT, INTERVAL_VALUE, INTERVAL_FIELD, EVENT_DEFINITION \
+ FROM information_schema.EVENTS WHERE EVENT_SCHEMA = {db} AND EVENT_NAME = {n}"
+ ),
+ _ => return Err(format!("MySQL object source not supported for {:?}", kind)),
+ };
+ Ok(ddl)
+}
+```
+
+Also implement `mysql_object_ddl_from_result(kind, rows) -> Result<String, String>` mapping query rows to a single DDL string (SHOW CREATE column index: view=1, routine=2 — same convention as `schema::mysql_object_source_ddl_column_index`; trigger/event assembled from row cells). Add a unit test asserting the extraction for each kind with a fake `db::QueryResult`.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core mysql_object_source_query 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): mysql per-object DDL query and row extraction"
+```
+
+---
+
+## Task 8: Oracle/Dameng object DDL via DBMS_METADATA for transfer
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test**:
+
+```rust
+#[test]
+fn builds_oracle_object_source_query() {
+ let sql = oracle_object_source_query(&TransferObjectKind::Trigger, "HR", "TRG1").unwrap();
+ assert!(sql.contains("DBMS_METADATA.GET_DDL('TRIGGER', 'TRG1', 'HR')"));
+ let sql = oracle_object_source_query(&TransferObjectKind::Sequence, "HR", "SEQ1").unwrap();
+ assert!(sql.contains("DBMS_METADATA.GET_DDL('SEQUENCE', 'SEQ1', 'HR')"));
+ let sql = oracle_object_source_query(&TransferObjectKind::View, "", "V1").unwrap();
+ assert!(!sql.contains(",'"));
+}
+
+#[test]
+fn rewrites_oracle_schema_qualifiers() {
+ let ddl = "CREATE OR REPLACE TRIGGER \"HR\".\"TRG1\" ...";
+ assert_eq!(rewrite_oracle_schema_qualifier(ddl, "HR", "APP"), "CREATE OR REPLACE TRIGGER \"APP\".\"TRG1\" ...");
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core builds_oracle_object_source_query 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+pub fn oracle_object_source_query(kind: &TransferObjectKind, schema: &str, name: &str) -> Result<String, String> {
+ let object_type = match kind {
+ TransferObjectKind::View => "VIEW",
+ TransferObjectKind::MaterializedView => "MATERIALIZED_VIEW",
+ TransferObjectKind::Procedure => "PROCEDURE",
+ TransferObjectKind::Function => "FUNCTION",
+ TransferObjectKind::Trigger => "TRIGGER",
+ TransferObjectKind::Sequence => "SEQUENCE",
+ _ => return Err(format!("Oracle object source not supported for {:?}", kind)),
+ };
+ let name_lit = quote_string_literal(name);
+ if schema.trim().is_empty() {
+ Ok(format!("SELECT DBMS_METADATA.GET_DDL({}, {}) FROM DUAL", quote_string_literal(object_type), name_lit))
+ } else {
+ Ok(format!(
+ "SELECT DBMS_METADATA.GET_DDL({}, {}, {}) FROM DUAL",
+ quote_string_literal(object_type),
+ name_lit,
+ quote_string_literal(schema)
+ ))
+ }
+}
+
+/// Rewrite `"SCHEMA"."NAME"` occurrences in Oracle/DM metadata DDL from
+/// source_schema to target_schema.
+pub fn rewrite_oracle_schema_qualifier(ddl: &str, source_schema: &str, target_schema: &str) -> String {
+ if source_schema == target_schema || source_schema.is_empty() {
+ return ddl.to_string();
+ }
+ let re = Regex::new(&format!(r#""{}"\."# , regex::escape(source_schema))).unwrap();
+ re.replace_all(ddl, &format!("\"{target_schema}\".")).to_string()
+}
+```
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core builds_oracle_object_source_query 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): oracle/dameng object DDL helpers"
+```
+
+---
+
+## Task 9: Generic object transfer executor with skip-existing and ordering
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** (pure ordering helper):
+
+```rust
+#[test]
+fn orders_object_selections_by_dependency() {
+ let kinds = vec![
+ TransferObjectKind::Trigger, TransferObjectKind::View, TransferObjectKind::Sequence,
+ TransferObjectKind::Event, TransferObjectKind::Procedure, TransferObjectKind::Function,
+ ];
+ let ordered = ordered_transfer_object_kinds(kinds.iter().copied().collect());
+ // sequences → views → functions → procedures → triggers → events
+ assert_eq!(ordered[0], TransferObjectKind::Sequence);
+ assert_eq!(ordered[1], TransferObjectKind::View);
+ assert_eq!(ordered[2], TransferObjectKind::Function);
+ assert_eq!(ordered[3], TransferObjectKind::Procedure);
+ assert_eq!(ordered[4], TransferObjectKind::Trigger);
+ assert_eq!(ordered[5], TransferObjectKind::Event);
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core orders_object_selections 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement** — ordering + executor skeleton:
+
+```rust
+pub fn ordered_transfer_object_kinds(kinds: Vec<TransferObjectKind>) -> Vec<TransferObjectKind> {
+ let rank = |kind: &TransferObjectKind| match kind {
+ TransferObjectKind::Table => 0,
+ TransferObjectKind::Sequence => 1,
+ TransferObjectKind::View => 2,
+ TransferObjectKind::MaterializedView => 2,
+ TransferObjectKind::Function => 3,
+ TransferObjectKind::Procedure => 4,
+ TransferObjectKind::Trigger => 5,
+ TransferObjectKind::Event => 6,
+ };
+ let mut kinds = kinds;
+ kinds.sort_by_key(rank);
+ kinds
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransferObjectOutcome {
+ pub transferred: Vec<String>,
+ pub skipped: Vec<String>,
+ pub failed: Vec<String>,
+}
+```
+
+Then the executor (async, one function per family):
+
+```rust
+/// Transfers selected non-table objects from source to target.
+/// Skips objects that already exist on the target; counts them in the
+/// outcome. Executes in dependency order (sequence → view → function →
+/// procedure → trigger → event). Errors are collected per object and the
+/// transfer continues.
+pub async fn transfer_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ mut progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ if request.objects.is_empty() {
+ return Ok(TransferObjectOutcome::default());
+ }
+ let source_db_type = get_db_type(state, &request.source_connection_id).await?;
+ let target_db_type = get_db_type(state, &request.target_connection_id).await?;
+ if !is_same_transfer_family(&source_db_type, &target_db_type) {
+ return Err("跨库暂不支持非表对象传输".to_string());
+ }
+ match transfer_object_family(&source_db_type) {
+ Some(TransferObjectFamily::Postgres) => {
+ transfer_postgres_schema_objects(state, request, source_pool_key, target_pool_key, progress_callback)
+ .await
+ .map(|_| TransferObjectOutcome::default())
+ }
+ Some(TransferObjectFamily::Mysql) => {
+ transfer_mysql_schema_objects(state, request, source_pool_key, target_pool_key, progress_callback).await
+ }
+ Some(TransferObjectFamily::Oracle) => {
+ transfer_oracle_schema_objects(state, request, source_pool_key, target_pool_key, progress_callback).await
+ }
+ None => Ok(TransferObjectOutcome::default()),
+ }
+}
+```
+
+Note: this task lands the skeleton + ordering + outcome; per-family bodies are Tasks 10 (MySQL), 11 (Oracle), 12 (PG refactor). `transfer_mysql_schema_objects` and `transfer_oracle_schema_objects` are stubbed in this task (returning `Ok(TransferObjectOutcome::default())` guarded by a `todo!()`-free minimal implementation) so the crate compiles — they are filled in by Tasks 10/11.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core orders_object_selections 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): schema object transfer executor skeleton with ordering"
+```
+
+---
+
+## Task 10: MySQL schema object transfer body
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** (selection extraction helper):
+
+```rust
+#[test]
+fn extracts_selected_names_by_kind() {
+ let selections = vec![
+ TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] },
+ TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v2".into()] },
+ TransferObjectSelection { object_type: TransferObjectKind::Trigger, names: vec!["t1".into()] },
+ ];
+ let views = selected_object_names(&selections, &TransferObjectKind::View);
+ assert_eq!(views, vec!["v1", "v2"]);
+ assert!(selected_object_names(&selections, &TransferObjectKind::Event).is_empty());
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core extracts_selected_names 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+pub fn selected_object_names(selections: &[TransferObjectSelection], kind: &TransferObjectKind) -> Vec<String> {
+ selections
+ .iter()
+ .filter(|s| &s.object_type == kind)
+ .flat_map(|s| s.names.clone())
+ .collect::<Vec<_>>()
+}
+```
+
+Then `transfer_mysql_schema_objects`:
+
+```rust
+async fn transfer_mysql_schema_objects<F>(
+ state: &AppState,
+ request: &TransferRequest,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ mut progress_callback: F,
+) -> Result<TransferObjectOutcome, String>
+where
+ F: FnMut(TransferProgress),
+{
+ let mut outcome = TransferObjectOutcome::default();
+ let source_db = &request.source_database;
+ let target_db = if request.target_database.trim().is_empty() {
+ source_db.as_str()
+ } else {
+ request.target_database.as_str()
+ };
+ let order = ordered_transfer_object_kinds(
+ request.objects.iter().map(|s| s.object_type).collect(),
+ );
+ for kind in order {
+ for name in selected_object_names(&request.objects, &kind) {
+ if is_cancelled(&request.transfer_id).await {
+ return Err("Cancelled".to_string());
+ }
+ let table = format!("schema object: {name}");
+ let progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {
+ progress_callback(TransferProgress {
+ transfer_id: request.transfer_id.clone(),
+ table: table.clone(),
+ table_index: request.tables.len(),
+ total_tables: request.tables.len(),
+ rows_transferred: (outcome.transferred.len() + outcome.skipped.len()) as u64,
+ total_rows: None,
+ status,
+ error,
+ terminal: false,
+ });
+ };
+ // skip if target already has it
+ let exists_sql =
+ target_object_exists_sql(&DatabaseType::Mysql, target_db, &name, &kind).map_err(|e| e)?;
+ let exists = execute_on_pool(state, target_pool_key, &exists_sql).await?.rows.first().is_some();
+ if exists {
+ outcome.skipped.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ continue;
+ }
+ let query = mysql_object_source_query(&kind, source_db, &name)?;
+ let result = execute_on_pool(state, source_pool_key, &query).await?;
+ let raw_ddl = mysql_object_ddl_from_result(&kind, &result)?;
+ let ddl = strip_mysql_definer(&raw_ddl);
+ let ddl = rewrite_mysql_schema_qualifier(&ddl, source_db, target_db);
+ match execute_on_pool(state, target_pool_key, &ddl).await {
+ Ok(_) => {
+ outcome.transferred.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Running, None);
+ }
+ Err(e) => {
+ outcome.failed.push(format!("{kind:?}:{name}"));
+ progress(&mut outcome, TransferStatus::Error, Some(e));
+ }
+ }
+ }
+ }
+ Ok(outcome)
+}
+```
+
+Check `TransferStatus` variant names (Running/Error/TableDone/Done/Cancelled — see route usage). `is_cancelled` is in transfer.rs:4076.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core extracts_selected_names 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): mysql schema object transfer (skip existing, definer strip, schema rewrite)"
+```
+
+---
+
+## Task 11: Oracle/Dameng schema object transfer body
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** (schema resolution for DM, where database==schema):
+
+```rust
+#[test]
+fn resolves_oracle_family_source_schema() {
+ // For Oracle/Dameng the metadata lookup schema is the source_schema;
+ // when empty, fall back to the database (DM lists users as databases).
+ assert_eq!(resolve_oracle_schema("", "HR"), "HR");
+ assert_eq!(resolve_oracle_schema("HR", "db"), "HR");
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core resolves_oracle_family 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+fn resolve_oracle_schema(schema: &str, database: &str) -> String {
+ if schema.trim().is_empty() { database.to_string() } else { schema.to_string() }
+}
+```
+
+Then `transfer_oracle_schema_objects` mirroring the MySQL body: for each selected object, existence check via `target_object_exists_sql(&DatabaseType::Oracle, target_schema, name, kind)` (target_schema resolved the same way; for DM use the same ALL_OBJECTS query — Dameng supports `ALL_OBJECTS` view), DDL via `oracle_object_source_query` executed on the source pool with the source schema as query database, extract first cell, `rewrite_oracle_schema_qualifier(&ddl, source_schema, target_schema)`, execute on target. Oracle objects created through `build_executable_object_source_statements` are *not* needed here — DBMS_METADATA output is already executable; the body uses the MySQL loop shape with `execute_on_pool` and the same progress/outcome accounting.
+
+Note: `DBMS_METADATA.GET_DDL` requires a connection whose current schema is the owner schema; the agent executes the query with `database`/`schema` params (see `oracle_agent_object_source` at schema.rs:6566 which passes both). For transfers the pools execute plain SQL; if `GET_DDL` returns no row because the current schema differs, the object transfer reports it as a failed object (acceptable for v1; note in code comment).
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core resolves_oracle_family 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): oracle/dameng schema object transfer"
+```
+
+---
+
+## Task 12: PG object transfer — per-selection filtering + skip-existing
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs` (`transfer_postgres_schema_objects` at 5020)
+
+- [ ] **Step 1: Write the failing test** (filter helper for PG sources):
+
+```rust
+#[test]
+fn filters_postgres_object_sources_by_selection() {
+ let sources = vec![
+ db::ObjectSource { name: "v1".into(), object_type: db::ObjectSourceKind::View, schema: Some("public".into()), source: "SELECT 1".into(), editable: None },
+ db::ObjectSource { name: "v2".into(), object_type: db::ObjectSourceKind::View, schema: Some("public".into()), source: "SELECT 2".into(), editable: None },
+ ];
+ let selection = vec![TransferObjectSelection { object_type: TransferObjectKind::View, names: vec!["v1".into()] }];
+ let filtered = filter_object_sources_by_selection(sources, &selection);
+ assert_eq!(filtered.len(), 1);
+ assert_eq!(filtered[0].name, "v1");
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core filters_postgres_object_sources 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement** — in `transfer_postgres_schema_objects`:
+
+1. After fetching `object_sources`/`materialized_views`/`trigger_sources`, filter each by `selected_object_names(&request.objects, &kind)`:
+ - `object_sources` (View/Procedure/Function/Sequence/…) → filter by kind-specific name lists.
+ - `materialized_views` → filter by MaterializedView names.
+ - `trigger_sources` → filter by Trigger names; if no Trigger selection, skip the whole trigger step (current behavior transfers triggers of selected tables — replace it with explicit selection; when `objects` is empty the function returns early anyway).
+2. Skip-existing: before executing each object's DDL, run `target_object_exists_sql(&DatabaseType::Postgres, &request.target_schema, name, kind)` on the target pool; on hit, record in a `skipped` list and `continue` (no execution, no error).
+3. Return `Ok(TransferObjectOutcome)` with transferred/skipped/failed populated from the loops (rename the current function's return or add a new wrapper that the executor calls; simplest: change the signature to return `Result<TransferObjectOutcome, String>` and update the route call in Task 14).
+
+Helper `filter_object_sources_by_selection` maps `db::ObjectSourceKind` ↔ `TransferObjectKind`:
+
+```rust
+fn transfer_kind_from_object_source_kind(kind: &db::ObjectSourceKind) -> Option<TransferObjectKind> {
+ use db::ObjectSourceKind as S;
+ Some(match kind {
+ S::View => TransferObjectKind::View,
+ S::MaterializedView => TransferObjectKind::MaterializedView,
+ S::Procedure => TransferObjectKind::Procedure,
+ S::Function => TransferObjectKind::Function,
+ S::Trigger => TransferObjectKind::Trigger,
+ S::Sequence => TransferObjectKind::Sequence,
+ _ => return None,
+ })
+}
+```
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core filters_postgres_object_sources 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): postgres object transfer honors selection and skips existing"
+```
+
+---
+
+## Task 13: transfer_table honors StructureOnly (no data copy)
+
+**Files:**
+- Modify: `crates/dbx-core/src/transfer.rs` (`transfer_table` around line 4730, before the "Truncate target if overwrite mode" block)
+
+- [ ] **Step 1: Write the failing test** — no pure unit test is feasible (async + DB); instead assert via a new pure helper:
+
+```rust
+#[test]
+fn structure_only_skips_data_steps() {
+ assert!(should_copy_data(&TransferContent::StructureAndData));
+ assert!(should_copy_data(&TransferContent::DataOnly));
+ assert!(!should_copy_data(&TransferContent::StructureOnly));
+}
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `cargo test -p dbx-core structure_only_skips_data 2>&1 | tail -5`
+Expected: FAIL.
+
+- [ ] **Step 3: Implement**:
+
+```rust
+pub fn should_copy_data(content: &TransferContent) -> bool {
+ !matches!(content, TransferContent::StructureOnly)
+}
+```
+
+In `transfer_table`, immediately before the `// Truncate target if overwrite mode` block (line ~4730):
+
+```rust
+ // Structure-only transfer: DDL work (create table, indexes, comments) is
+ // done above; skip everything data-related.
+ if !should_copy_data(&request.content) {
+ return Ok(0);
+ }
+```
+
+Also apply the same early return at the top of the Mongo branch (`transfer_mongodb_table`): add a guard in the caller route instead — Task 14 rejects StructureOnly for Mongo sources/targets at validation time, so no change is needed inside the Mongo path. If Mongo `create_table` flow differs, validate in Task 14 tests.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `cargo test -p dbx-core structure_only_skips_data 2>&1 | tail -5`
+Expected: PASS.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): structure-only mode skips data copy"
+```
+
+---
+
+## Task 14: Route integration — validation, object step, summary counts
+
+**Files:**
+- Modify: `crates/dbx-web/src/routes/transfer.rs`
+
+- [ ] **Step 1: Write the failing test** — no unit test harness exists for routes; verification is compile + manual. Skip TDD here; the compile step below is the gate.
+
+- [ ] **Step 2: Wire validation**: replace `transfer::validate_transfer_target_table_names(&req)` (line ~63) with `transfer::validate_transfer_request(&req)`; after resolving `source_db_type`/`target_db_type` inside the spawned task, reject when `!request.objects.is_empty() && !transfer::is_same_transfer_family(&source_db_type, &target_db_type)` (terminal error via `terminal_transfer_error`), and reject `StructureOnly` when either side is Mongo (`matches!(source_db_type, DatabaseType::Mongodb) || matches!(target_db_type, ...)`).
+
+- [ ] **Step 3: Run object transfer step** — after the table loop, replace the PG-only `transfer_postgres_schema_objects` block (lines ~327-390) with:
+
+```rust
+ let object_outcome = match transfer::transfer_schema_objects(
+ &app,
+ &req,
+ &source_pool_key,
+ &target_pool_key,
+ |progress| {
+ send_transfer_progress(&progress_channel, &progress);
+ },
+ )
+ .await
+ {
+ Ok(outcome) => outcome,
+ Err(e) if e == "Cancelled" => { /* existing cancelled terminal block */ return; }
+ Err(e) => { /* existing error terminal block with table="schema objects" */ return; }
+ };
+```
+
+Keep the existing `transfer_postgres_schema_dependencies` block (enum/domain) in place — it runs before the table loop and stays PG-only.
+
+- [ ] **Step 4: Merge skip count into the final summary**: extend the final `done` progress error text when `!object_outcome.skipped.is_empty()`: append `format!(",跳过 {} 个已存在对象", object_outcome.skipped.len())` — only when no failures; when failures exist, append to the failure message as well. Also add `outcome.transferred.len()` failures: failed object names go into `failed_tables` (they are reported per-object already via progress events; keep the aggregate simple: append `"schema objects"` to `failed_tables` when `!object_outcome.failed.is_empty()`).
+
+- [ ] **Step 5: Compile check**
+
+Run: `cargo check -p dbx-web 2>&1 | tail -10`
+Expected: no errors.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add crates/dbx-web/src/routes/transfer.rs crates/dbx-core/src/transfer.rs
+git commit -m "feat(transfer): route integration for content modes and schema objects"
+```
+
+---
+
+## Task 15: Backend test sweep
+
+- [ ] **Step 1: Run all transfer-related unit tests**
+
+Run: `cargo test -p dbx-core transfer 2>&1 | tail -15`
+Expected: all transfer tests pass (protocol, family, validation, existence SQL, mysql DDL helpers, ordering, selections).
+
+- [ ] **Step 2: Run full dbx-core unit tests**
+
+Run: `cargo test -p dbx-core 2>&1 | tail -10`
+Expected: PASS (live-DB tests excluded by default; if any `#[ignore]`-less live tests fail, they are environment-dependent and were failing before this change).
+
+- [ ] **Step 3: Commit any stragglers**
+
+```bash
+git add -A && git commit -m "test(transfer): backfill transfer unit tests" --allow-empty
+```
+
+---
+
+## Task 16: Frontend types (tauri.ts) and transfer object capability helpers
+
+**Files:**
+- Modify: `apps/desktop/src/lib/backend/tauri.ts` (TransferRequest at 3279; types at 3275)
+- Create: `apps/desktop/src/lib/database/transferObjectKinds.ts`
+- Test: `apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts`
+
+- [ ] **Step 1: Write the failing test**:
+
+```ts
+import { describe, expect, it } from "vitest";
+import {
+ transferObjectFamily,
+ transferObjectKindsForDatabase,
+ isSameTransferFamily,
+ TransferObjectFamily,
+} from "@/lib/database/transferObjectKinds";
+
+describe("transferObjectKinds", () => {
+ it("groups databases into transfer families", () => {
+ expect(transferObjectFamily("mysql")).toBe(TransferObjectFamily.Mysql);
+ expect(transferObjectFamily("kingbase")).toBe(TransferObjectFamily.Postgres);
+ expect(transferObjectFamily("dameng")).toBe(TransferObjectFamily.Oracle);
+ expect(transferObjectFamily("sqlite")).toBeUndefined();
+ });
+
+ it("returns per-family object kinds", () => {
+ expect(transferObjectKindsForDatabase("mysql")).toEqual([
+ "TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT",
+ ]);
+ expect(transferObjectKindsForDatabase("postgres")).toContain("SEQUENCE");
+ expect(transferObjectKindsForDatabase("dameng")).toContain("TRIGGER");
+ expect(transferObjectKindsForDatabase("sqlite")).toEqual([]);
+ });
+
+ it("detects same-family transfers", () => {
+ expect(isSameTransferFamily("mysql", "mysql")).toBe(true);
+ expect(isSameTransferFamily("mysql", "postgres")).toBe(false);
+ expect(isSameTransferFamily("oracle", "dameng")).toBe(true);
+ expect(isSameTransferFamily("postgres", "sqlite")).toBe(false);
+ });
+});
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `pnpm --dir apps/desktop vitest run transferObjectKinds 2>&1 | tail -8`
+Expected: FAIL — module missing.
+
+- [ ] **Step 3: Implement** — `transferObjectKinds.ts` mirrors the Rust tables:
+
+```ts
+import type { DatabaseType } from "@/types/database";
+
+export enum TransferObjectFamily {
+ Mysql = "mysql",
+ Postgres = "postgres",
+ Oracle = "oracle",
+}
+
+export type TransferObjectKind =
+ | "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE"
+ | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT";
+
+const MYSQL_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT"];
+const POSTGRES_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
+const ORACLE_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];
+
+const FAMILY_BY_DB = new Map<DatabaseType, TransferObjectFamily>([
+ ["mysql", TransferObjectFamily.Mysql],
+ ["postgres", TransferObjectFamily.Postgres],
+ ["kingbase", TransferObjectFamily.Postgres],
+ ["gaussdb", TransferObjectFamily.Postgres],
+ ["kwdb", TransferObjectFamily.Postgres],
+ ["opengauss", TransferObjectFamily.Postgres],
+ ["oracle", TransferObjectFamily.Oracle],
+ ["dameng", TransferObjectFamily.Oracle],
+ ["oceanbase-oracle", TransferObjectFamily.Oracle],
+]);
+
+export function transferObjectFamily(dbType?: DatabaseType): TransferObjectFamily | undefined {
+ return dbType ? FAMILY_BY_DB.get(dbType) : undefined;
+}
+
+export function isSameTransferFamily(a?: DatabaseType, b?: DatabaseType): boolean {
+ const fa = transferObjectFamily(a);
+ const fb = transferObjectFamily(b);
+ return !!fa && fa === fb;
+}
+
+export function transferObjectKindsForDatabase(dbType?: DatabaseType): TransferObjectKind[] {
+ switch (transferObjectFamily(dbType)) {
+ case TransferObjectFamily.Mysql: return [...MYSQL_KINDS];
+ case TransferObjectFamily.Postgres: return [...POSTGRES_KINDS];
+ case TransferObjectFamily.Oracle: return [...ORACLE_KINDS];
+ default: return [];
+ }
+}
+```
+
+Verify `DatabaseType` union includes `"kwdb"` and `"oceanbase-oracle"` in `apps/desktop/src/types/database.ts` — adjust keys to match.
+
+- [ ] **Step 4: Extend tauri.ts types**:
+
+```ts
+export type TransferContent = "structureAndData" | "structureOnly" | "dataOnly";
+export type TransferObjectKind =
+ | "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE"
+ | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT";
+
+export interface TransferObjectSelection {
+ objectType: TransferObjectKind;
+ names: string[];
+}
+```
+
+Add to `TransferRequest`:
+```ts
+ content: TransferContent;
+ objects: TransferObjectSelection[];
+```
+
+(Keep `createTable` for wire compatibility; the dialog stops sending it — check http.ts `startDataTransferTask`/`api.TransferRequest` construction sites.)
+
+- [ ] **Step 5: Run the test to verify it passes**
+
+Run: `pnpm --dir apps/desktop vitest run transferObjectKinds 2>&1 | tail -8`
+Expected: PASS (3 tests).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add apps/desktop/src/lib/database/transferObjectKinds.ts apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts apps/desktop/src/lib/backend/tauri.ts
+git commit -m "feat(transfer): frontend transfer object kind helpers and request types"
+```
+
+---
+
+## Task 17: i18n keys
+
+**Files:**
+- Modify: all 9 locale files under `apps/desktop/src/i18n/locales/` (zh-CN, en, zh-TW, es, it, ja, ko, pt-BR, fallback) — `transfer:` namespace (~line 3712 in zh-CN)
+
+- [ ] **Step 1: Add keys to zh-CN.ts** (source of truth):
+
+```ts
+ content: "传输方式",
+ contentStructureAndData: "结构和数据",
+ contentStructureOnly: "仅结构",
+ contentDataOnly: "仅数据",
+ contentStructureOnlyHint: "仅创建表和对象结构,不复制数据",
+ contentDataOnlyHint: "仅复制数据到已存在的目标表",
+ objects: "传输对象",
+ searchObjects: "搜索对象名...",
+ noObjects: "暂无对象",
+ objectTypeTable: "表",
+ objectTypeView: "视图",
+ objectTypeMaterializedView: "物化视图",
+ objectTypeProcedure: "存储过程",
+ objectTypeFunction: "函数",
+ objectTypeTrigger: "触发器",
+ objectTypeSequence: "序列",
+ objectTypeEvent: "事件",
+ objectDataOnlyDisabled: "仅数据模式不传输非表对象",
+ objectCrossFamilyDisabled: "跨数据库类型暂不支持非表对象传输",
+ objectUnsupportedDisabled: "当前数据库不支持该对象类型传输",
+ skippedExistingObjects: "跳过 {count} 个已存在对象",
+ dataWriteMode: "数据写入方式",
+```
+
+- [ ] **Step 2: Mirror into the other 8 locales** — en: translate; zh-TW/es/it/ja/ko/pt-BR/fallback: use zh-CN text (existing project convention for untranslated keys is fallback; check how other new keys were added historically — `fallback.ts` contains zh-CN text; add the same keys there and to each locale with English or Chinese placeholder per convention).
+
+Verify by grep: `grep -c "contentStructureAndData" apps/desktop/src/i18n/locales/*.ts` → 9 files.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add apps/desktop/src/i18n/locales/
+git commit -m "feat(i18n): transfer tree and content mode keys"
+```
+
+---
+
+## Task 18: ObjectSelectionTree component
+
+**Files:**
+- Create: `apps/desktop/src/components/transfer/ObjectSelectionTree.vue`
+- Test: `apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts`
+
+- [ ] **Step 1: Write the failing test** — component-level logic via mounted stubs:
+
+```ts
+import { describe, expect, it } from "vitest";
+import { mount } from "@vue/test-utils";
+import ObjectSelectionTree from "@/components/transfer/ObjectSelectionTree.vue";
+
+const groups = [
+ { kind: "TABLE" as const, label: "表", items: ["a", "b"] },
+ { kind: "VIEW" as const, label: "视图", items: ["v1"] },
+];
+
+function make(props: Record<string, unknown> = {}) {
+ return mount(ObjectSelectionTree, {
+ props: {
+ groups,
+ disabledGroups: [],
+ modelValue: {},
+ ...props,
+ },
+ global: { stubs: { Input: true, Button: true } },
+ });
+}
+
+describe("ObjectSelectionTree", () => {
+ it("renders group headers and items", () => {
+ const wrapper = make();
+ expect(wrapper.text()).toContain("表");
+ expect(wrapper.text()).toContain("v1");
+ });
+
+ it("selects all items in a group when the header checkbox is toggled", async () => {
+ const wrapper = make();
+ await wrapper.findAll("[data-test='group-toggle']")[0].trigger("click");
+ expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([
+ { TABLE: ["a", "b"] },
+ ]);
+ });
+
+ it("filters items by search text", async () => {
+ const wrapper = make();
+ await wrapper.find("[data-test='search']").setValue("v1");
+ expect(wrapper.text()).toContain("v1");
+ expect(wrapper.text()).not.toContain("a");
+ });
+
+ it("renders disabled groups with a hint", () => {
+ const wrapper = make({ disabledGroups: ["VIEW"], disabledHints: { VIEW: "原因" } });
+ const group = wrapper.find("[data-test='group-VIEW']");
+ expect(group.classes()).toContain("opacity-50");
+ expect(group.text()).toContain("原因");
+ });
+});
+```
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `pnpm --dir apps/desktop vitest run ObjectSelectionTree 2>&1 | tail -8`
+Expected: FAIL — component missing.
+
+- [ ] **Step 3: Implement the component** — props:
+
+```ts
+interface ObjectTreeGroup {
+ kind: TransferObjectKind;
+ label: string;
+ items: string[];
+}
+
+props: {
+ groups: ObjectTreeGroup[];
+ disabledGroups: TransferObjectKind[]; // kinds rendered but greyed out
+ disabledHints: Record<string, string>; // kind → reason
+ modelValue: Record<string, string[]>; // kind → selected names
+ search: string;
+ loading: boolean;
+}
+```
+
+Template: per group — header row (CheckSquare/Square icon, label, count `(n/m)`, expand chevron) + collapsible item list (checkbox rows) with `data-test` attributes. Emits `update:modelValue` with the new selection object on every toggle (group header toggles all/none of the group's items). Search filter applies to item rows. Disabled groups render with `opacity-50` and the hint text; their checkboxes are disabled. A top-level select-all button operates across enabled groups.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `pnpm --dir apps/desktop vitest run ObjectSelectionTree 2>&1 | tail -8`
+Expected: PASS (4 tests).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add apps/desktop/src/components/transfer/ObjectSelectionTree.vue apps/desktop/src/components/transfer/__tests__/ObjectSelectionTree.spec.ts
+git commit -m "feat(transfer): object selection tree component"
+```
+
+---
+
+## Task 19: DataTransferDialog integration
+
+**Files:**
+- Modify: `apps/desktop/src/components/transfer/DataTransferDialog.vue`
+
+- [ ] **Step 1: Write the failing test** — extend `apps/desktop/src/components/transfer/__tests__/DataTransferDialog.spec.ts`:
+
+```ts
+it("sends content and objects in the transfer request", async () => {
+ // mount with a stub api.startDataTransferTask capturing the request
+ // select a table + a view via the tree, choose "structure only",
+ // assert request.content === "structureOnly",
+ // request.objects contains { objectType: "VIEW", names: ["v1"] }
+});
+```
+
+Check how the existing spec stubs `api` (`vi.mock("@/lib/backend/api")`? verify from the existing spec file) and follow the same pattern.
+
+- [ ] **Step 2: Run the test to verify it fails**
+
+Run: `pnpm --dir apps/desktop vitest run DataTransferDialog 2>&1 | tail -8`
+Expected: FAIL — request has no content/objects.
+
+- [ ] **Step 3: Implement** — in `DataTransferDialog.vue`:
+
+1. State: replace `sourceTables: string[]` + `selectedTables: Set<string>` with `objectGroups: Record<TransferObjectKind, string[]>` and `selectedObjects: Record<TransferObjectKind, Set<string>>` (keep a `selectedTables` computed derived from the TABLE group for minimal churn in the request builder and target-tree refresh logic).
+2. Data loading: `loadObjects()` calls `api.listObjects(sourceConnectionId, sourceDatabase, schema, [kind], undefined, undefined, undefined, catalog)` per kind from `transferObjectKindsForDatabase(sourceDbType)` and fills groups. Keep the existing `table_type` filtering for the TABLE group (`TABLE`/`BASE TABLE`).
+3. Mode: `transferContent = ref<api.TransferContent>("structureAndData")`; radio row with 3 options + hints (`contentStructureOnlyHint`/`contentDataOnlyHint`); when `dataOnly`, compute `disabledGroups = non-table kinds` with hint `objectDataOnlyDisabled`; when `!isSameTransferFamily(sourceDbType, targetDbType)`, all non-table kinds disabled with `objectCrossFamilyDisabled`; kinds missing from `transferObjectKindsForDatabase(source)` are not rendered.
+4. Request builder: `content: transferContent.value`, `objects: non-table kinds → { objectType, names: [...selected] }`, drop `createTable` (or send `createTable: transferContent.value !== "dataOnly"` for backward compat — check http.ts / tauri command signature; prefer sending both fields, frontend stays in control).
+5. Data-write-mode select (`transferMode`) visible only when content includes data (`structureAndData` or `dataOnly`); hidden for `structureOnly`.
+6. Ownership preview: only trigger when `content === "structureAndData"` (existing `createTable.value` condition at line ~471 becomes `transferContent.value !== "dataOnly"` — verify ownership applies to structure creation; keep current condition semantics: it ran when createTable was true, i.e. now `content !== "dataOnly"`).
+7. Remove the `createTable` checkbox row; remove `toggleSelectAll`/`filteredTables` table-only logic in favor of the tree.
+8. Keep `prefillTables` behavior: prefill maps into the TABLE group selection after load.
+9. `shouldRefreshTargetTree` (line ~451): refresh when `content !== "dataOnly"`.
+
+- [ ] **Step 4: Run the test to verify it passes**
+
+Run: `pnpm --dir apps/desktop vitest run DataTransferDialog 2>&1 | tail -8`
+Expected: PASS (old + new tests).
+
+- [ ] **Step 5: Typecheck**
+
+Run: `pnpm --dir apps/desktop typecheck 2>&1 | tail -10`
+Expected: no errors.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add apps/desktop/src/components/transfer/
+git commit -m "feat(transfer): dialog tree selection and transfer content modes"
+```
+
+---
+
+## Task 20: Final verification and review
+
+- [ ] **Step 1: Backend unit tests**
+
+Run: `cargo test -p dbx-core 2>&1 | tail -8`
+Expected: PASS.
+
+- [ ] **Step 2: Frontend tests**
+
+Run: `pnpm --dir apps/desktop vitest run 2>&1 | tail -8`
+Expected: PASS (including the pre-existing 30 tests from databaseCapabilities/databaseFeatureSupport).
+
+- [ ] **Step 3: Frontend typecheck**
+
+Run: `pnpm --dir apps/desktop typecheck 2>&1 | tail -8`
+Expected: no errors.
+
+- [ ] **Step 4: Manual smoke (optional, needs running app)**: open transfer dialog with MySQL source → tree shows 表/视图/存储过程/函数/触发器/事件; DM source → 表/视图/存储过程/函数/触发器/序列/物化视图; cross-family target → non-table groups disabled with hint; 仅数据 → non-table disabled; 仅结构 → data write mode hidden.
+
+- [ ] **Step 5: Verify git state**
+
+Run: `git status --short && git log --oneline -15`
+Expected: only feature commits; docs/superpowers untracked.
+
+---
+
+## Notes / Risks
+
+- `DatabaseType` variant names must be verified against `crates/dbx-core/src/models/connection.rs` (Gaussdb/Kwdb/OceanbaseOracle) and `apps/desktop/src/types/database.ts` (kwdb/oceanbase-oracle) before compiling Task 2 / Task 16.
+- `TransferRequest` literal construction sites: `transfer.rs` tests (~line 5364) and `crates/dbx-core/tests/live_postgres_transfer.rs` — add the two new fields at every site.
+- `transfer_postgres_schema_objects` signature change (return `TransferObjectOutcome`) touches the route call in Task 14; keep both in the same commit so the crate stays green between commits only if the route is updated in the same commit — if not, keep the old signature and add a wrapper.
+- MySQL `SHOW CREATE` DDL column index differs by kind (view=1, routine=2) — reuse `schema::mysql_object_source_ddl_column_index` semantics in `mysql_object_ddl_from_result`.
+- DM `ALL_OBJECTS` availability: Dameng 8 supports `ALL_OBJECTS`; if a customer version lacks it, fall back to `SYS.SYSOBJECTS` (flagged as a follow-up).
+- `docs/superpowers/` must never be committed (`git add -f` avoided; it is gitignored).
diff --git a/docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md b/docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md
new file mode 100644
index 0000000000..ff8601597e
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-01-data-transfer-tree-selection-design.md
@@ -0,0 +1,171 @@
+# Data Transfer: Tree Object Selection and Transfer Modes Design
+
+Date: 2026-08-01
+
+## Summary
+
+The data transfer dialog (`apps/desktop/src/components/transfer/DataTransferDialog.vue`) currently lets the user pick tables from a flat checkbox list and copy table **data** between connections. Non-table objects (views, stored procedures, functions, triggers, sequences, events) are only copied for PostgreSQL→PostgreSQL transfers, and then only as an all-or-nothing schema sweep performed after the table data copy.
+
+This change turns the table picker into a tree that groups selectable objects by type (tables, views, stored procedures, functions, triggers, sequences, events), and adds an explicit transfer mode: **structure and data** (default), **structure only**, and **data only**. Non-table object DDL copying is implemented for PostgreSQL and PG-family databases (Kingbase, GaussDB, KWDB, OpenGauss), MySQL, Dameng, and Oracle. Cross-database-family object DDL copy is out of scope for the first version.
+
+## Goals
+
+- Select transfer content via a tree grouped by object type, with per-group select-all and object-level checkboxes.
+- Support three transfer modes: structure and data, structure only, data only.
+- Copy non-table object DDL for PostgreSQL/PG-family, MySQL, Dameng, and Oracle, within the same database family.
+- Skip objects that already exist on the target side (by name), and report the skip count on completion.
+- Preserve the existing table data transfer behavior (append/overwrite/upsert write modes, FK dependency ordering, ownership preview, target-table-name case handling).
+
+## Non-goals
+
+- Cross-family non-table object DDL transfer (e.g., MySQL view → PostgreSQL view). The tree disables non-table groups with a hint in that case.
+- Object transfer for databases outside the supported family set (SQLite, ClickHouse, SQL Server, MongoDB, Hive, Spark, etc.).
+- Editing object DDL inside the transfer dialog (users use the object source editor for that).
+- Differential/sync behavior beyond "skip existing" (no replacement of changed objects).
+
+## Existing Design to Reuse
+
+- `crates/dbx-core/src/transfer.rs` — table data transfer core: `TransferRequest`, `transfer_table`, FK dependency sorting (`sort_tables_by_fk_dependency`), progress reporting (`TransferProgress`), DDL generation (`generate_create_table_ddl`), column type mapping (`map_column_type`).
+- `crates/dbx-core/src/transfer.rs:5020` — `transfer_postgres_schema_objects`: existing PostgreSQL schema object DDL copy (views, materialized views, procedures, functions, sequences, triggers, types, packages, synonyms + ownership/grants/policies). Reused and extended with per-object selection filtering.
+- `crates/dbx-core/src/object_source_sql.rs` — `build_executable_object_source_statements`, `ObjectSourceKind`, `EditableObjectSourceSqlInput`: per-database object source DDL machinery (already used by the PG object transfer).
+- `crates/dbx-web/src/routes/transfer.rs` — transfer orchestration route, progress channel, per-object failure handling.
+- `apps/desktop/src/lib/backend/api.ts` — `listObjects(connectionId, database, schema, objectTypes?, filter?, limit?, offset?, catalog?)` returning `ObjectInfo[]`; `TransferRequest` types.
+- `apps/desktop/src/lib/database/databaseObjectCapabilities.ts` — per-database sidebar object kind lists.
+
+## Design
+
+### 1. Backend protocol (`crates/dbx-core/src/transfer.rs`, `crates/dbx-web/src/routes/transfer.rs`)
+
+Extend `TransferRequest`:
+
+```rust
+#[serde(rename_all = "camelCase")]
+pub enum TransferContent {
+ #[default]
+ StructureAndData,
+ StructureOnly,
+ DataOnly,
+}
+
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")] // matches SidebarObjectKind conventions
+pub enum TransferObjectKind {
+ Table, View, MaterializedView, Procedure, Function, Trigger, Sequence, Event,
+}
+
+pub struct TransferObjectSelection {
+ pub object_type: TransferObjectKind,
+ pub names: Vec<String>,
+}
+```
+
+New fields on `TransferRequest`:
+
+- `content: TransferContent` — defaults to `StructureAndData`. Replaces the `create_table` boolean (`create_table == (content != DataOnly)`); the field is kept for wire compatibility but the frontend stops sending it.
+- `objects: Vec<TransferObjectSelection>` — non-table object selections. The table selection stays in the existing `tables: Vec<String>` field (also mirrored as a `TransferObjectKind::Table` entry when the tree sends it).
+
+Validation (in the route, before transfer starts):
+
+- `DataOnly` with non-empty `objects` → error "仅数据模式不传输非表对象".
+- `StructureOnly` with empty `tables` and empty `objects` → error (nothing to do).
+- Non-table objects are rejected when source and target database families differ (see family rules below).
+- Non-table object names are validated like table names (non-empty, no NUL bytes).
+
+`TransferMode` (append/overwrite/upsert) is unchanged; it only takes effect when the content includes data (`StructureAndData` or `DataOnly`).
+
+### 2. Database family rules
+
+| Family | Database types | Non-table object DDL support |
+|---|---|---|
+| mysql | mysql | yes (views, procedures, functions, triggers, events) |
+| postgres | postgres, kingbase, gaussdb, kwdb, opengauss | yes |
+| oracle | oracle, dameng, oceanbase-oracle | yes (views, procedures, functions, triggers, sequences) |
+| other | everything else | no — tree groups disabled, backend rejects |
+
+`is_same_transfer_family(source, target)` — a new pure function in `transfer.rs`, unit-tested. Cross-family transfers keep table data copy working exactly as today, with non-table groups disabled in the UI.
+
+Object type availability per family (drives which tree groups render):
+
+| Object kind | mysql | postgres family | oracle/dameng |
+|---|---|---|---|
+| TABLE | ✓ | ✓ | ✓ |
+| VIEW | ✓ | ✓ | ✓ |
+| MATERIALIZED_VIEW | ✗ | ✓ | ✓ |
+| PROCEDURE | ✓ | ✓ | ✓ |
+| FUNCTION | ✓ | ✓ | ✓ |
+| TRIGGER | ✓ | ✓ | ✓ |
+| SEQUENCE | ✗ (MariaDB only, first version: no) | ✓ | ✓ |
+| EVENT | ✓ | ✗ | ✗ |
+
+### 3. Object listing (backend)
+
+Extend the existing `listObjects` path (per-database object listing in `crates/dbx-core/src/schema.rs` and the agent-side listing) so the transfer tree can fetch objects grouped by type:
+
+- **PostgreSQL family**: already supported kinds (TABLE, VIEW, MATERIALIZED_VIEW, PROCEDURE, FUNCTION, SEQUENCE) via `pg_catalog`; add TRIGGER listing (`pg_trigger` join `pg_class`/`pg_namespace`, names of triggers in the schema).
+- **MySQL**: add TRIGGER (`information_schema.TRIGGERS` filtered by `EVENT_OBJECT_SCHEMA`) and EVENT (`information_schema.EVENTS`); VIEW/PROCEDURE/FUNCTION listing already exists.
+- **Oracle/Dameng**: add TRIGGER and SEQUENCE (`ALL_OBJECTS` filtered by `OBJECT_TYPE`); VIEW/PROCEDURE/FUNCTION listing already exists (Dameng already has `SYS.SYSOBJECTS`-based listing).
+
+The `Event` kind is transfer-only: it is added to the backend `ObjectSourceKind`/listing mapping but not to the sidebar object capability lists (the sidebar does not gain new node types in this change).
+
+### 4. Non-table object DDL copy (backend)
+
+New `transfer_objects` flow in `crates/dbx-core/src/transfer.rs`, invoked from the route after table data transfer and after the existing PG schema-dependency step. Execution order:
+
+1. tables (existing flow, FK sorted)
+2. sequences
+3. views, materialized views
+4. functions
+5. procedures
+6. triggers
+7. events
+
+DDL fetching per family:
+
+- **PostgreSQL family**: reuse `get_postgres_schema_object_sources_for_transfer` + `get_postgres_materialized_view_sources_for_transfer` + new `get_postgres_trigger_sources_for_transfer`-style queries, filtered by the selected names. Existing schema rewrite (`rewrite_postgres_routine_schema`) and `build_executable_object_source_statements` apply. The current "transfer everything in the schema" behavior becomes "transfer only selected objects"; when the request carries no object selection the step is skipped entirely (no behavior surprise for table-only transfers).
+- **MySQL**: VIEW/PROCEDURE/FUNCTION DDL via `SHOW CREATE` (existing `mysql_object_source_sql`); TRIGGER DDL assembled from `information_schema.TRIGGERS` (`CREATE TRIGGER` with ACTION_TIMING/EVENT_MANIPULATION/EVENT_OBJECT_TABLE/ACTION_STATEMENT — the per-table trigger query at `crates/dbx-core/src/db/mysql.rs:4239` is the basis); EVENT DDL assembled from `information_schema.EVENTS`; strip `DEFINER=` clauses; rewrite the schema qualifier from source schema to target schema when they differ.
+- **Oracle/Dameng**: fetch DDL via `DBMS_METADATA.GET_DDL('<TYPE>', '<name>')` (the existing object-source machinery already implements per-type metadata DDL for these databases; reuse those code paths where possible); rewrite schema qualifiers; execute per statement.
+
+Target-side existence check, per object, immediately before executing its DDL:
+
+- **PostgreSQL family**: `SELECT 1 FROM pg_class/pg_proc ...` by schema+name.
+- **MySQL**: `information_schema` lookups (VIEWS, ROUTINES, TRIGGERS, EVENTS).
+- **Oracle/Dameng**: `ALL_OBJECTS` (or `SYS.SYSOBJECTS` for Dameng) by schema+name.
+
+Existing objects are skipped and counted; the count is included in the final summary progress message ("skipped N existing objects"). Failed objects follow the existing pattern: recorded in the failure list, transfer continues, final status reflects the failures.
+
+Progress: reuse `TransferProgress` with `table = "schema object: <name>"` (already the convention used by the PG object transfer). The `DataOnly` mode skips the whole object-DDL step.
+
+### 5. Frontend (`apps/desktop/src/components/transfer/DataTransferDialog.vue`)
+
+- Replace the flat table list with a tree:
+ - Top-level groups rendered from the source database family capability table (tables, views, materialized views, procedures, functions, triggers, sequences, events as applicable).
+ - Group header checkbox = select all / clear group; per-object checkboxes; expand/collapse per group; a search filter box filters object names across groups.
+ - Groups that cannot be transferred (cross-family, unsupported kind, or `DataOnly` mode) are rendered disabled with a tooltip explaining why.
+ - Table selection stays in `tables`; non-table selections serialize into `objects`.
+- Transfer mode selector: 结构和数据 / 仅结构 / 仅数据 (i18n keys in the `transfer.*` namespace).
+ - `DataOnly`: non-table groups disabled ("仅数据模式不传输非表对象"); table group enabled.
+ - `StructureOnly`: data write mode (append/overwrite/upsert) selector hidden/disabled; ownership preview and target-table-name case options only apply when data is copied (ownership preview only relevant with `StructureAndData`; keep the existing behavior for that mode).
+ - The `createTable` checkbox is removed.
+- Load object lists per group from `listObjects` with the per-kind object type filter; loading states per group; error states surface inline.
+
+### 6. Error handling
+
+- Validation errors from the route are shown inline in the dialog (existing error display pattern).
+- Per-object DDL failures: existing `failed_tables` mechanism extended to carry object entries; final status `Error` with the failure list, transfer continues for remaining objects.
+- Cancellation: existing `transfer_id` cancellation checks are threaded through the object-DDL loop (mirroring the PG object transfer loop).
+
+### 7. Testing
+
+Backend unit tests (`crates/dbx-core/src/transfer.rs` test module + `crates/dbx-core/tests/live_postgres_transfer.rs`):
+
+- `is_same_transfer_family` matrix.
+- Request validation (DataOnly + objects, cross-family objects).
+- Per-family object DDL statement generation (MySQL `SHOW CREATE` handling with DEFINER stripping; schema rewriting).
+- Target existence check SQL per family.
+- Live PG transfer: object filtering by selection, skip-existing behavior, `StructureOnly` (no data rows copied), `DataOnly` (no DDL executed).
+
+Frontend tests (`apps/desktop/src/components/transfer/__tests__/`):
+
+- Tree group rendering per database family.
+- Group select-all, object toggle, search filtering.
+- Disable rules: `DataOnly` mode, cross-family, unsupported kinds.
+- Request serialization (`tables` + `objects` + `content`).
diff --git a/src-tauri/src/commands/transfer.rs b/src-tauri/src/commands/transfer.rs
index a69742f2d3..413555ef31 100644
--- a/src-tauri/src/commands/transfer.rs
+++ b/src-tauri/src/commands/transfer.rs
@@ -4,6 +4,7 @@ use tauri::{AppHandle, Emitter, State};
use crate::commands::connection::{ensure_connection_writable, AppState};
// Re-export types and functions used by other modules
+use dbx_core::models::connection::DatabaseType;
pub use dbx_core::transfer::{
get_db_type, TransferOwnershipPreview, TransferProgress, TransferRequest, TransferStatus,
};
@@ -27,7 +28,16 @@ pub async fn start_transfer(
// Validate connections exist
let source_db_type = get_db_type(&state, &request.source_connection_id).await?;
let target_db_type = get_db_type(&state, &request.target_connection_id).await?;
- dbx_core::transfer::validate_transfer_target_table_names(&request)?;
+ dbx_core::transfer::validate_transfer_request(&request)?;
+
+ // Cross-family object transfers are validated inside transfer_schema_objects:
+ // only mechanically rewriteable kinds (views, sequences) are allowed.
+ // Structure-only data transfer is unsupported for MongoDB.
+ if matches!(request.content, dbx_core::transfer::TransferContent::StructureOnly)
+ && (matches!(source_db_type, DatabaseType::MongoDb) || matches!(target_db_type, DatabaseType::MongoDb))
+ {
+ return Err("MongoDB 暂不支持仅结构传输".to_string());
+ }
// External Doris/StarRocks catalogs: pool is created with `catalog=` URL
// setup (SET catalog) and without USE <external-db>. See ensure_transfer_pool.
@@ -234,56 +244,70 @@ pub async fn start_transfer(
}
}
- if matches!(source_db_type, dbx_core::models::connection::DatabaseType::Postgres)
- && matches!(target_db_type, dbx_core::models::connection::DatabaseType::Postgres)
+ // Transfer selected non-table objects (views, procedures, functions,
+ // triggers, sequences, events) after the per-table loop. The shared
+ // Core decision handles all content modes: DataOnly never
+ // transfers schema objects; PG→PG keeps the legacy empty-selection
+ // default only when structure participates in the transfer.
+ let mut object_outcome = dbx_core::transfer::TransferObjectOutcome::default();
+ match dbx_core::transfer::transfer_schema_objects(
+ &state,
+ &request,
+ &source_pool_key,
+ &target_pool_key,
+ |progress| emit_progress(&app, progress),
+ )
+ .await
{
- match dbx_core::transfer::transfer_postgres_schema_objects(
- &state,
- &request,
- &source_pool_key,
- &target_pool_key,
- |progress| emit_progress(&app, progress),
- )
- .await
- {
- Ok(()) => {}
- Err(e) if e == "Cancelled" => {
- emit_progress(
- &app,
- TransferProgress {
- transfer_id: transfer_id.clone(),
- table: "schema objects".to_string(),
- table_index: total_tables,
- total_tables,
- rows_transferred: 0,
- total_rows: None,
- status: TransferStatus::Cancelled,
- error: None,
- terminal: true,
- },
- );
- dbx_core::transfer::clear_cancelled(&transfer_id).await;
- return;
- }
- Err(e) => {
- failed_tables.push("schema objects".to_string());
- emit_progress(
- &app,
- TransferProgress {
- transfer_id: transfer_id.clone(),
- table: "schema objects".to_string(),
- table_index: total_tables,
- total_tables,
- rows_transferred: 0,
- total_rows: None,
- status: TransferStatus::Error,
- error: Some(e),
- terminal: false,
- },
- );
- }
+ Ok(outcome) => {
+ object_outcome = outcome;
}
+ Err(e) if e == "Cancelled" => {
+ emit_progress(
+ &app,
+ TransferProgress {
+ transfer_id: transfer_id.clone(),
+ table: "schema objects".to_string(),
+ table_index: total_tables,
+ total_tables,
+ rows_transferred: 0,
+ total_rows: None,
+ status: TransferStatus::Cancelled,
+ error: None,
+ terminal: true,
+ },
+ );
+ dbx_core::transfer::clear_cancelled(&transfer_id).await;
+ return;
+ }
+ Err(e) => {
+ failed_tables.push("schema objects".to_string());
+ emit_progress(
+ &app,
+ TransferProgress {
+ transfer_id: transfer_id.clone(),
+ table: "schema objects".to_string(),
+ table_index: total_tables,
+ total_tables,
+ rows_transferred: 0,
+ total_rows: None,
+ status: TransferStatus::Error,
+ error: Some(e),
+ terminal: false,
+ },
+ );
+ }
+ }
+ if !object_outcome.failed.is_empty() {
+ failed_tables.push(format!("schema objects ({})", object_outcome.failed.len()));
}
+ let skip_suffix = if !object_outcome.skipped.is_empty() && failed_tables.is_empty() {
+ format!(",跳过 {} 个已存在对象", object_outcome.skipped.len())
+ } else if !object_outcome.skipped.is_empty() {
+ format!(";跳过 {} 个已存在对象", object_outcome.skipped.len())
+ } else {
+ String::new()
+ };
emit_progress(
&app,
@@ -296,12 +320,17 @@ pub async fn start_transfer(
total_rows: None,
status: if failed_tables.is_empty() { TransferStatus::Done } else { TransferStatus::Error },
error: if failed_tables.is_empty() {
- None
+ if skip_suffix.is_empty() {
+ None
+ } else {
+ Some(skip_suffix.clone())
+ }
} else {
Some(format!(
- "{} table(s) failed: {}",
+ "{} table(s) failed: {}{}",
failed_tables.len(),
- failed_tables.iter().take(5).cloned().collect::<Vec<_>>().join(", ")
+ failed_tables.iter().take(5).cloned().collect::<Vec<_>>().join(", "),
+ skip_suffix
))
},
terminal: true,
@@ -321,7 +350,7 @@ pub async fn preview_transfer_ownership(
let state = state.inner().clone();
let source_db_type = get_db_type(&state, &request.source_connection_id).await?;
let target_db_type = get_db_type(&state, &request.target_connection_id).await?;
- dbx_core::transfer::validate_transfer_target_table_names(&request)?;
+ dbx_core::transfer::validate_transfer_request(&request)?;
let source_pool_key = dbx_core::transfer::ensure_transfer_pool(
&state,
&request.source_connection_id,