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(xugu): support native Xugu-to-Xugu table transfer

Elias0c95c816b5e7
diff --git a/apps/desktop/src/components/transfer/DataTransferDialog.vue b/apps/desktop/src/components/transfer/DataTransferDialog.vue
index 91ce01ea4b..808918c5ac 100644
--- a/apps/desktop/src/components/transfer/DataTransferDialog.vue
+++ b/apps/desktop/src/components/transfer/DataTransferDialog.vue
@@ -31,7 +31,7 @@ import { ensureReadOnlyWriteAccess } from "@/lib/database/readOnlyWriteAccess";
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
import * as api from "@/lib/backend/api";
import type { TransferContent, TransferObjectKind, TransferTableNameCase } from "@/lib/backend/api";
-import { crossFamilyTransferableKinds, isSameTransferFamily, transferObjectKindsForDatabase } from "@/lib/database/transferObjectKinds";
+import { crossFamilyTransferableKinds, isSameTransferFamily, isTransferPairSupported, transferObjectKindsForDatabase } from "@/lib/database/transferObjectKinds";
import ObjectSelectionTree from "@/components/transfer/ObjectSelectionTree.vue";
import TransferTaskTree from "@/components/transfer/TransferTaskTree.vue";
import DataTransferProgressDialog from "@/components/transfer/DataTransferProgressDialog.vue";
@@ -87,6 +87,14 @@ const transferDialogStyle = {
const store = useConnectionStore();
const sqlConnections = computed(() => store.connections.filter((c) => supportsTransfer(transferDatabaseTypeForConnection(c))));
+const sourceConnections = computed(() => {
+ const targetType = transferDatabaseTypeForConnection(store.getConfig(targetConnectionId.value));
+ return sqlConnections.value.filter((connection) => isTransferPairSupported(transferDatabaseTypeForConnection(connection), targetType));
+});
+const targetConnections = computed(() => {
+ const sourceType = transferDatabaseTypeForConnection(store.getConfig(sourceConnectionId.value));
+ return sqlConnections.value.filter((connection) => isTransferPairSupported(sourceType, transferDatabaseTypeForConnection(connection)));
+});
// Source state
const sourceConnectionId = ref("");
@@ -270,14 +278,32 @@ function requestedTableFilters(): Record<string, string> | undefined {
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
}
+const sourceTransferType = computed(() => transferDatabaseTypeForConnection(store.getConfig(sourceConnectionId.value)));
+const targetTransferType = computed(() => transferDatabaseTypeForConnection(store.getConfig(targetConnectionId.value)));
+const isXuguTransferPair = computed(() => sourceTransferType.value === "xugu" && targetTransferType.value === "xugu");
+// The table-name-case selector is hidden for Xugu pairs; reset any earlier choice so the
+// blocking xuguPreserveTableNames hint cannot strand the user without a visible control.
+watch(isXuguTransferPair, (isXuguPair) => {
+ if (isXuguPair) targetTableNameCase.value = "preserve";
+});
+const targetStrategyType = computed(() => (targetTransferType.value === "xugu" ? "xugu" : connectionType(targetConnectionId.value)));
+const xuguTransferHint = computed(() => {
+ if (sourceTransferType.value === "xugu" || targetTransferType.value === "xugu") {
+ if (!isTransferPairSupported(sourceTransferType.value, targetTransferType.value)) return t("transfer.xuguPairOnly");
+ if (targetTableStrategy.value === "upsert" || targetTableStrategy.value === "rebuild") return t("transfer.xuguAppendOverwriteOnly");
+ if (transferContent.value !== "dataOnly" && targetTableNameCase.value !== "preserve") return t("transfer.xuguPreserveTableNames");
+ }
+ return "";
+});
+
function isMongoConnection(id: string): boolean {
return connectionType(id) === "mongodb";
}
const showTargetColumnQuoteOption = computed(() => ["gaussdb", "opengauss"].includes(connectionType(targetConnectionId.value) ?? ""));
-const rebuildDisabledReason = computed(() => rebuildUnavailableReason(transferContent.value, connectionType(targetConnectionId.value)));
-const upsertSupported = computed(() => supportsTransferUpsert(connectionType(targetConnectionId.value)));
+const rebuildDisabledReason = computed(() => rebuildUnavailableReason(transferContent.value, targetStrategyType.value));
+const upsertSupported = computed(() => supportsTransferUpsert(targetStrategyType.value));
const rebuildDisabledHint = computed(() => {
if (rebuildDisabledReason.value === "dataOnly") return t("transfer.rebuildDataOnlyDisabled");
if (rebuildDisabledReason.value === "unsupported") return t("transfer.rebuildUnsupportedDisabled");
@@ -317,6 +343,8 @@ const canStart = computed(() => {
const sameSourceAndTarget = sameCatalogAndDatabase && effectiveSourceSchema === effectiveTargetSchema;
return (
!!sourceConnectionId.value &&
+ isTransferPairSupported(sourceTransferType.value, targetTransferType.value) &&
+ !xuguTransferHint.value &&
isTransferDatabaseSelected(sourceDatabase.value) &&
!!targetConnectionId.value &&
isTransferDatabaseSelected(targetDatabase.value) &&
@@ -1339,7 +1367,7 @@ async function saveConfigTask() {
<Label class="text-xs">{{ t("transfer.sourceConnection") }}</Label>
<ConnectionTreeSelect
v-model="sourceConnectionId"
- :connections="sqlConnections"
+ :connections="sourceConnections"
:layout="store.sidebarLayout"
:placeholder="t('transfer.selectConnection')"
:search-placeholder="t('transfer.searchConnection')"
@@ -1412,7 +1440,7 @@ async function saveConfigTask() {
<Label class="text-xs">{{ t("transfer.targetConnection") }}</Label>
<ConnectionTreeSelect
v-model="targetConnectionId"
- :connections="sqlConnections"
+ :connections="targetConnections"
:layout="store.sidebarLayout"
:placeholder="t('transfer.selectConnection')"
:search-placeholder="t('transfer.searchConnection')"
@@ -1547,7 +1575,8 @@ async function saveConfigTask() {
</Select>
</div>
<p v-if="rebuildDisabledHint" class="text-xs text-muted-foreground">{{ rebuildDisabledHint }}</p>
- <div class="flex items-center gap-3">
+ <p v-if="xuguTransferHint" class="text-xs text-amber-600">{{ xuguTransferHint }}</p>
+ <div v-if="!isXuguTransferPair" class="flex items-center gap-3">
<Label class="text-xs shrink-0">{{ t("transfer.targetTableNameCase") }}</Label>
<Select v-model="targetTableNameCase">
<SelectTrigger class="h-7 text-xs">
diff --git a/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts b/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts
index 484515521f..7bfc78fbae 100644
--- a/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts
+++ b/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts
@@ -70,12 +70,13 @@ describe("transfer strategies", () => {
expect(resolveTransferStrategy({})).toBe("append");
});
- it("does not expose unimplemented DB2 upsert or rebuild strategies", () => {
+ it("does not expose unimplemented DB2 or Xugu upsert or rebuild strategies", () => {
expect(supportsTransferUpsert("db2")).toBe(false);
expect(rebuildUnavailableReason("structureAndData", "db2")).toBe("unsupported");
expect(rebuildUnavailableReason("structureOnly", "db2")).toBe("unsupported");
expect(supportsTransferUpsert("postgres")).toBe(true);
expect(supportsTransferUpsert("mysql")).toBe(true);
+ expect(supportsTransferUpsert("xugu")).toBe(false);
expect(supportsTransferUpsert(undefined)).toBe(true);
});
diff --git a/apps/desktop/src/components/transfer/transferStrategy.ts b/apps/desktop/src/components/transfer/transferStrategy.ts
index 0ec48ee28a..3e54297ce8 100644
--- a/apps/desktop/src/components/transfer/transferStrategy.ts
+++ b/apps/desktop/src/components/transfer/transferStrategy.ts
@@ -19,7 +19,7 @@ export function transferStrategyOptions(strategy: TransferStrategy): Pick<Transf
const REBUILD_TARGET_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlserver", "kingbase", "gaussdb", "opengauss", "kwdb", "goldendb", "sqlite", "duckdb", "cloudflare-d1"]);
export function supportsTransferUpsert(targetType: DatabaseType | undefined): boolean {
- return targetType !== "db2" && targetType !== "iris";
+ return targetType !== "db2" && targetType !== "iris" && targetType !== "xugu";
}
export function rebuildUnavailableReason(content: TransferContent, targetType: DatabaseType | undefined): "dataOnly" | "unsupported" | undefined {
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index e6bf50e5ca..bad6f7c4ac 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -6948,6 +6948,9 @@ export default {
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)",
+ xuguPairOnly: "Xugu transfer currently supports Xugu-to-Xugu only. Select Xugu connections for both source and target.",
+ xuguAppendOverwriteOnly: "The first Xugu transfer phase supports append and overwrite only; upsert and rebuild are not supported yet.",
+ xuguPreserveTableNames: "Xugu structure transfer currently requires preserving source table-name casing to avoid mismatched foreign-key references.",
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)",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 2026d0d970..e3f985b6f9 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -6324,6 +6324,9 @@ export default withEnglishFallback({
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)",
+ xuguPairOnly: "La transferencia de Xugu solo admite conexiones de Xugu a Xugu. Selecciona una conexión Xugu tanto para el origen como para el destino.",
+ xuguAppendOverwriteOnly: "La primera fase de transferencia de Xugu solo admite agregar y sobrescribir; aún no admite upsert ni reconstrucción.",
+ xuguPreserveTableNames: "La transferencia de estructura de Xugu requiere conservar las mayúsculas y minúsculas de los nombres de las tablas de origen para evitar referencias incorrectas en las claves foráneas.",
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",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index b633cf2895..4c8271b460 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -6137,6 +6137,9 @@ export default withEnglishFallback({
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)",
+ xuguPairOnly: "Il trasferimento Xugu supporta attualmente solo connessioni da Xugu a Xugu. Seleziona connessioni Xugu sia per l'origine sia per la destinazione.",
+ xuguAppendOverwriteOnly: "La prima fase del trasferimento Xugu supporta solo l'aggiunta e la sovrascrittura; upsert e ricostruzione non sono ancora supportati.",
+ xuguPreserveTableNames: "Il trasferimento della struttura Xugu richiede di mantenere maiuscole e minuscole dei nomi delle tabelle di origine per evitare riferimenti errati alle chiavi esterne.",
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",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 02e589b68e..b6bdf4bf9b 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -6158,6 +6158,9 @@ export default withEnglishFallback({
objectTypeEvent: "イベント",
objectDataOnlyDisabled: "データのみモードではテーブル以外のオブジェクトは転送されません",
objectCrossFamilyDisabled: "データベース間転送はシーケンスのみサポートします(単純なDDL。ビューの本文は翻訳されません)",
+ xuguPairOnly: "Xugu の転送は現在、Xugu から Xugu への接続のみをサポートしています。ソースとターゲットの両方に Xugu 接続を選択してください。",
+ xuguAppendOverwriteOnly: "Xugu 転送の第 1 段階では追加と上書きのみをサポートしています。upsert と再構築はまだサポートされていません。",
+ xuguPreserveTableNames: "外部キー参照の不一致を防ぐため、Xugu の構造転送ではソーステーブル名の大文字・小文字を保持する必要があります。",
crossFamilyViewHint: "データベース間ビュー転送:ビューが依存するテーブルも選択するか、ターゲットDBに既に存在することを確認してください",
objectUnsupportedDisabled: "現在のデータベースは、このオブジェクトタイプの転送をサポートしていません",
skippedExistingObjects: "既存のオブジェクト {count} 件をスキップしました",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index d75f06a348..b8048f5cfc 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -5931,6 +5931,9 @@ export default withEnglishFallback({
objectTypeEvent: "이벤트",
objectDataOnlyDisabled: "데이터 전용 모드에서는 테이블이 아닌 개체는 전송되지 않습니다",
objectCrossFamilyDisabled: "데이터베이스 간 전송은 시퀀스만 지원합니다(단순 DDL, 뷰 본문은 변환되지 않음)",
+ xuguPairOnly: "현재 Xugu 전송은 Xugu 간 연결만 지원합니다. 원본과 대상 모두 Xugu 연결을 선택하세요.",
+ xuguAppendOverwriteOnly: "Xugu 전송 1단계에서는 추가와 덮어쓰기만 지원하며, upsert와 재구성은 아직 지원하지 않습니다.",
+ xuguPreserveTableNames: "외래 키 참조가 잘못되는 것을 방지하려면 Xugu 구조 전송 시 원본 테이블 이름의 대소문자를 유지해야 합니다.",
crossFamilyViewHint: "데이터베이스 간 뷰 전송: 뷰가 의존하는 테이블도 선택하거나 대상 DB에 이미 존재하는지 확인하세요",
objectUnsupportedDisabled: "현재 데이터베이스는 이 개체 유형의 전송을 지원하지 않습니다",
skippedExistingObjects: "기존 개체 {count}개 건너뜀",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 2dcf69c99d..9a2e04527d 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -6138,6 +6138,9 @@ export default withEnglishFallback({
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)",
+ xuguPairOnly: "No momento, a transferência do Xugu aceita apenas conexões de Xugu para Xugu. Selecione conexões Xugu para a origem e o destino.",
+ xuguAppendOverwriteOnly: "A primeira fase da transferência do Xugu aceita apenas inclusão e sobrescrita; upsert e reconstrução ainda não são compatíveis.",
+ xuguPreserveTableNames: "A transferência de estrutura do Xugu exige preservar maiúsculas e minúsculas nos nomes das tabelas de origem para evitar referências incorretas de chaves estrangeiras.",
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)",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 0ee68d8608..e247bd74b0 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -7314,6 +7314,9 @@ export default withEnglishFallback({
objectTypeEvent: "События",
objectDataOnlyDisabled: "Объекты, не являющиеся таблицами, не переносятся в режиме «только данные»",
objectCrossFamilyDisabled: "Межбазовый перенос поддерживает только последовательности (обычный DDL; тела запросов представлений не могут быть преобразованы)",
+ xuguPairOnly: "Перенос Xugu пока поддерживает только соединения Xugu → Xugu. Выберите соединения Xugu для источника и назначения.",
+ xuguAppendOverwriteOnly: "На первом этапе переноса Xugu поддерживаются только добавление и перезапись; upsert и перестроение пока не поддерживаются.",
+ xuguPreserveTableNames: "При переносе структуры Xugu необходимо сохранять регистр символов в именах исходных таблиц, чтобы избежать ошибок во внешних ключах.",
crossFamilyViewHint: "Межбазовый перенос представлений: выберите также таблицы, от которых зависит представление, или убедитесь, что они уже существуют в целевой базе данных",
objectUnsupportedDisabled: "Эта база данных не поддерживает перенос объектов этого типа",
skippedExistingObjects: "Пропущено существующих объектов: {count}",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 299854f0b2..10be6c64e1 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -6934,6 +6934,9 @@ export default withEnglishFallback({
objectTypeEvent: "事件",
objectDataOnlyDisabled: "仅数据模式不传输非表对象",
objectCrossFamilyDisabled: "跨库仅支持序列传输(纯DDL;视图查询体无法翻译)",
+ xuguPairOnly: "虚谷数据传输当前仅支持虚谷到虚谷,请为源端和目标端都选择虚谷连接。",
+ xuguAppendOverwriteOnly: "虚谷一期仅支持追加或覆盖;暂不支持更新插入和重建。",
+ xuguPreserveTableNames: "虚谷结构传输暂要求保留源表名大小写,以避免外键引用错位。",
crossFamilyViewHint: "跨库视图传输:请同时选择视图依赖的表,或确保目标库已存在这些表",
objectUnsupportedDisabled: "当前数据库不支持该对象类型传输",
skippedExistingObjects: "跳过 {count} 个已存在对象",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 5f620df1fe..24e3975dec 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -5474,6 +5474,9 @@ export default withEnglishFallback({
objectTypeEvent: "事件",
objectDataOnlyDisabled: "僅資料模式不傳輸非表物件",
objectCrossFamilyDisabled: "跨庫僅支援序列傳輸(純DDL;檢視查詢體無法翻譯)",
+ xuguPairOnly: "虛谷資料傳輸目前僅支援虛谷到虛谷,請為來源端和目標端都選擇虛谷連線。",
+ xuguAppendOverwriteOnly: "虛谷第一階段僅支援追加或覆蓋;暫不支援更新插入和重建。",
+ xuguPreserveTableNames: "虛谷結構傳輸目前要求保留來源資料表名稱大小寫,以避免外鍵引用錯位。",
crossFamilyViewHint: "跨庫檢視傳輸:請同時選擇檢視依賴的表,或確保目標庫已存在這些表",
objectUnsupportedDisabled: "目前資料庫不支援該物件類型傳輸",
skippedExistingObjects: "跳過 {count} 個已存在物件",
diff --git a/apps/desktop/src/lib/__tests__/database/databaseDriverManifest.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseDriverManifest.spec.ts
index b898aa0cd6..150a219afb 100644
--- a/apps/desktop/src/lib/__tests__/database/databaseDriverManifest.spec.ts
+++ b/apps/desktop/src/lib/__tests__/database/databaseDriverManifest.spec.ts
@@ -13,7 +13,7 @@ describe("databaseDriverManifest", () => {
tableDataEdit: true,
tableStructureEdit: true,
tableImport: true,
- dataTransfer: false,
+ dataTransfer: true,
sqlFileExecution: true,
databaseCreate: false,
fieldLineage: false,
diff --git a/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts b/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts
index cbaffe2e40..1efd3575d8 100644
--- a/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts
+++ b/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts
@@ -1,10 +1,10 @@
import { describe, expect, it } from "vitest";
-import { transferObjectFamily, transferObjectKindsForDatabase, isSameTransferFamily, crossFamilyTransferableKinds, TransferObjectFamily } from "@/lib/database/transferObjectKinds";
+import { transferObjectFamily, transferObjectKindsForDatabase, isSameTransferFamily, crossFamilyTransferableKinds, isTransferPairSupported, TransferObjectFamily } from "@/lib/database/transferObjectKinds";
import { manifestDatabaseTypes } from "@/lib/database/databaseDriverManifest";
import { supportsTransfer } from "@/lib/database/databaseFeatureSupport";
import type { DatabaseType } from "@/types/database";
-const TABLE_ONLY_TRANSFER_DATABASES: DatabaseType[] = ["sqlite", "rqlite", "turso", "cloudflare-d1", "duckdb", "clickhouse", "mongodb", "highgo", "vastbase", "goldendb", "yashandb", "questdb", "h2", "hive", "argo", "transwarp", "kyuubi", "impala", "db2", "iris", "spark"];
+const TABLE_ONLY_TRANSFER_DATABASES: DatabaseType[] = ["sqlite", "rqlite", "turso", "cloudflare-d1", "duckdb", "clickhouse", "mongodb", "highgo", "vastbase", "goldendb", "yashandb", "questdb", "h2", "hive", "argo", "transwarp", "kyuubi", "impala", "db2", "iris", "spark", "xugu"];
describe("transferObjectKinds", () => {
it("groups databases into transfer families", () => {
@@ -27,7 +27,8 @@ describe("transferObjectKinds", () => {
});
it("covers every transfer-capable database outside the richer object families", () => {
- expect(manifestDatabaseTypes().filter((dbType) => supportsTransfer(dbType) && !transferObjectFamily(dbType))).toEqual(TABLE_ONLY_TRANSFER_DATABASES);
+ const manifestTypes = manifestDatabaseTypes().filter((dbType) => supportsTransfer(dbType) && !transferObjectFamily(dbType));
+ expect([...manifestTypes].sort()).toEqual([...TABLE_ONLY_TRANSFER_DATABASES].sort());
});
it("does not expose objects for databases without transfer support", () => {
@@ -44,6 +45,14 @@ describe("transferObjectKinds", () => {
expect(isSameTransferFamily("sqlserver", "mysql")).toBe(false);
});
+ it("allows Xugu transfer only between two Xugu connections", () => {
+ expect(isTransferPairSupported("xugu", "xugu")).toBe(true);
+ expect(isTransferPairSupported("xugu", "postgres")).toBe(false);
+ expect(isTransferPairSupported("mysql", "xugu")).toBe(false);
+ expect(isTransferPairSupported("mysql", "postgres")).toBe(true);
+ expect(isTransferPairSupported(undefined, "xugu")).toBe(true);
+ });
+
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
diff --git a/apps/desktop/src/lib/database/transferObjectKinds.ts b/apps/desktop/src/lib/database/transferObjectKinds.ts
index 22b02658fd..fc3c71b25c 100644
--- a/apps/desktop/src/lib/database/transferObjectKinds.ts
+++ b/apps/desktop/src/lib/database/transferObjectKinds.ts
@@ -39,6 +39,13 @@ export function isSameTransferFamily(a?: DatabaseType, b?: DatabaseType): boolea
return !!fa && fa === fb;
}
+/** Xugu's initial transfer implementation is deliberately limited to Xugu → Xugu. */
+export function isTransferPairSupported(source?: DatabaseType, target?: DatabaseType): boolean {
+ if (!source || !target) return true;
+ if (source === "xugu" || target === "xugu") return source === "xugu" && target === "xugu";
+ return true;
+}
+
export function transferObjectKindsForDatabase(dbType?: DatabaseType): TransferObjectKind[] {
switch (transferObjectFamily(dbType)) {
case TransferObjectFamily.Mysql:
diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.json
index f4270c8d73..bffabc6ca2 100644
--- a/crates/dbx-core/assets/database-drivers.manifest.json
+++ b/crates/dbx-core/assets/database-drivers.manifest.json
@@ -2537,7 +2537,7 @@
"tableDataEdit": true,
"tableStructureEdit": true,
"tableImport": true,
- "dataTransfer": false,
+ "dataTransfer": true,
"sqlFileExecution": true,
"databaseCreate": false,
"fieldLineage": false,
diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rs
index 51fa73ade9..a402283364 100644
--- a/crates/dbx-core/src/data/transfer.rs
+++ b/crates/dbx-core/src/data/transfer.rs
@@ -1025,6 +1025,35 @@ pub fn validate_transfer_request(request: &TransferRequest) -> Result<(), String
Ok(())
}
+/// Validate the deliberately narrow first-phase Xugu transfer contract. The
+/// generic transfer engine remains available to every other database pair;
+/// Xugu is only admitted when both endpoints use its native driver path.
+pub fn validate_transfer_database_pair(
+ request: &TransferRequest,
+ source_db_type: &DatabaseType,
+ target_db_type: &DatabaseType,
+) -> Result<(), String> {
+ if !matches!(source_db_type, DatabaseType::Xugu) && !matches!(target_db_type, DatabaseType::Xugu) {
+ return Ok(());
+ }
+ if !matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu)) {
+ return Err("虚谷数据传输当前仅支持虚谷到虚谷".to_string());
+ }
+ if request.objects.as_ref().is_some_and(|objects| !objects.is_empty()) {
+ return Err("虚谷数据传输当前仅支持表对象".to_string());
+ }
+ if request.mode == TransferMode::Upsert || request.drop_target_before_create {
+ return Err("虚谷数据传输当前仅支持追加或覆盖,暂不支持更新插入或重建".to_string());
+ }
+ if request.create_table
+ && !matches!(request.content, TransferContent::DataOnly)
+ && request.target_table_name_case != TransferTableNameCase::Preserve
+ {
+ return Err("虚谷结构传输当前要求保留源表名大小写,以避免外键引用错位".to_string());
+ }
+ Ok(())
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
struct ResolvedTransferTargetTable {
name: String,
@@ -1834,6 +1863,19 @@ fn is_sqlserver_non_insertable_transfer_column(
&& is_sqlserver_rowversion_type(&column.data_type)
}
+fn is_xugu_rowversion_type(data_type: &str) -> bool {
+ normalize_xugu_type_name(data_type) == "ROWVERSION"
+}
+
+fn is_xugu_non_insertable_transfer_column(
+ column: &db::ColumnInfo,
+ source_db_type: &DatabaseType,
+ target_db_type: &DatabaseType,
+) -> bool {
+ matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu))
+ && is_xugu_rowversion_type(&column.data_type)
+}
+
fn is_mysql_non_insertable_transfer_column(column: &db::ColumnInfo, source_db_type: &DatabaseType) -> bool {
*source_db_type == DatabaseType::Mysql && is_mysql_generated_column_extra(column.extra.as_deref())
}
@@ -1847,6 +1889,7 @@ fn writable_transfer_columns(
.iter()
.filter(|column| {
!is_sqlserver_non_insertable_transfer_column(column, source_db_type, target_db_type)
+ && !is_xugu_non_insertable_transfer_column(column, source_db_type, target_db_type)
&& !is_mysql_non_insertable_transfer_column(column, source_db_type)
})
.cloned()
@@ -1863,6 +1906,16 @@ fn mysql_generated_only_transfer(
&& columns.iter().all(|column| is_mysql_generated_column_extra(column.extra.as_deref()))
}
+fn xugu_rowversion_only_transfer(
+ columns: &[db::ColumnInfo],
+ source_db_type: &DatabaseType,
+ target_db_type: &DatabaseType,
+) -> bool {
+ matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu))
+ && !columns.is_empty()
+ && columns.iter().all(|column| is_xugu_rowversion_type(&column.data_type))
+}
+
fn transfer_column_names_match(
target_db_type: &DatabaseType,
quote_target_column_names: bool,
@@ -2785,6 +2838,149 @@ fn generate_postgres_sequence_sync_sql(columns: &[db::ColumnInfo], table: &str,
.collect()
}
+/// Explicit identity values do not advance Xugu's backing sequence. Resolve the
+/// sequence through SERIAL_ID rather than relying on its generated name, which
+/// belongs to SYSDBA even when the table lives in another schema.
+fn xugu_identity_sequences_sql(schema: &str, table: &str) -> String {
+ xugu_identity_sequences_query(schema, table, true)
+}
+
+/// Case-insensitive fallback used only after the exact catalog spelling misses.
+/// Extra columns identify the matched table so two differently cased objects
+/// are not both advanced.
+fn xugu_identity_sequences_sql_case_insensitive(schema: &str, table: &str) -> String {
+ xugu_identity_sequences_query(schema, table, false)
+}
+
+fn xugu_identity_sequences_query(schema: &str, table: &str, exact: bool) -> String {
+ let (schema_predicate, table_predicate) = if exact {
+ (
+ format!("s.SCHEMA_NAME={}", quote_string_literal(schema)),
+ format!("t.TABLE_NAME={}", quote_string_literal(table)),
+ )
+ } else {
+ (
+ format!("UPPER(s.SCHEMA_NAME)=UPPER({})", quote_string_literal(schema)),
+ format!("UPPER(t.TABLE_NAME)=UPPER({})", quote_string_literal(table)),
+ )
+ };
+ format!(
+ "SELECT c.COL_NAME, q.SEQ_NAME, ss.SCHEMA_NAME, q.STEP_VAL, s.SCHEMA_NAME, t.TABLE_NAME \
+ FROM ALL_COLUMNS c \
+ JOIN ALL_TABLES t ON c.DB_ID=t.DB_ID AND c.TABLE_ID=t.TABLE_ID \
+ JOIN ALL_SCHEMAS s ON t.DB_ID=s.DB_ID AND t.SCHEMA_ID=s.SCHEMA_ID \
+ JOIN ALL_SEQUENCES q ON c.DB_ID=q.DB_ID AND c.SERIAL_ID=q.SEQ_ID \
+ JOIN ALL_SCHEMAS ss ON q.DB_ID=ss.DB_ID AND q.SCHEMA_ID=ss.SCHEMA_ID \
+ WHERE s.DB_ID=CURRENT_DB_ID AND {schema_predicate} \
+ AND {table_predicate} AND c.IS_SERIAL=TRUE AND q.IS_SYS=TRUE"
+ )
+}
+
+/// Value passed to `ALTER SEQUENCE ... START WITH`.
+///
+/// `NEXTVAL` is the only reliable probe of an existing sequence: catalog
+/// `CURR_VAL` is a reserved cache boundary. That probe consumes one value, so
+/// when the sequence is already ahead of the imported rows the consumed value
+/// is put back. A new table, or a sequence that is still behind the imported
+/// maximum, restarts at `last + step`.
+fn xugu_identity_start_with(step: i64, last: i64, preexisting_probe: Option<i64>) -> Option<i64> {
+ if let Some(probe) = preexisting_probe {
+ if (step > 0 && probe > last) || (step < 0 && probe < last) {
+ return Some(probe);
+ }
+ }
+ last.checked_add(step)
+}
+
+async fn sync_xugu_identity_sequences(
+ state: &Arc<AppState>,
+ target_pool_key: &str,
+ table: &str,
+ schema: &str,
+ explicitly_written_columns: &[String],
+ target_table_preexisting: bool,
+) -> Result<(), String> {
+ let exact = execute_on_pool(state, target_pool_key, &xugu_identity_sequences_sql(schema, table))
+ .await
+ .map_err(|e| format!("Failed to inspect Xugu identity sequences for {schema}.{table}: {e}"))?;
+ let rows = if !exact.rows.is_empty() {
+ exact.rows
+ } else {
+ let folded =
+ execute_on_pool(state, target_pool_key, &xugu_identity_sequences_sql_case_insensitive(schema, table))
+ .await
+ .map_err(|e| format!("Failed to inspect Xugu identity sequences for {schema}.{table}: {e}"))?;
+ let mut matched_tables = std::collections::HashSet::new();
+ for row in &folded.rows {
+ if let (Some(matched_schema), Some(matched_table)) =
+ (row.get(4).and_then(json_scalar_to_string), row.get(5).and_then(json_scalar_to_string))
+ {
+ matched_tables.insert((matched_schema, matched_table));
+ }
+ }
+ if matched_tables.len() > 1 {
+ return Err(format!(
+ "虚谷标识列同步匹配到多个仅大小写不同的表 {schema}.{table},请使用数据字典中的模式名和表名"
+ ));
+ }
+ folded.rows
+ };
+ for row in rows {
+ let (Some(column), Some(sequence), Some(sequence_schema), Some(step)) = (
+ row.first().and_then(json_scalar_to_string),
+ row.get(1).and_then(json_scalar_to_string),
+ row.get(2).and_then(json_scalar_to_string),
+ row.get(3).and_then(json_scalar_to_string).and_then(|value| value.parse::<i64>().ok()),
+ ) else {
+ return Err(format!("Incomplete Xugu identity metadata for {schema}.{table}"));
+ };
+ if !explicitly_written_columns.iter().any(|name| name.eq_ignore_ascii_case(&column)) {
+ continue;
+ }
+ if step == 0 {
+ return Err(format!("Invalid Xugu identity step for {schema}.{table}.{column}"));
+ }
+ let table_name = qualified_table(table, schema, &DatabaseType::Xugu, None);
+ let column_name = quote_identifier(&column, &DatabaseType::Xugu);
+ let extremum = if step > 0 { "MAX" } else { "MIN" };
+ let value_sql = format!("SELECT {extremum}({column_name}) FROM {table_name}");
+ let value = execute_on_pool(state, target_pool_key, &value_sql)
+ .await
+ .map_err(|e| format!("Failed to inspect Xugu identity values for {schema}.{table}.{column}: {e}"))?
+ .rows
+ .first()
+ .and_then(|row| row.first())
+ .and_then(json_scalar_to_string);
+ let Some(value) = value else { continue };
+ let last: i64 =
+ value.parse().map_err(|_| format!("Invalid Xugu identity value for {schema}.{table}.{column}: {value}"))?;
+ let sequence_name = qualified_table(&sequence, &sequence_schema, &DatabaseType::Xugu, None);
+ let preexisting_probe = if target_table_preexisting {
+ let probe_sql = format!("SELECT {sequence_name}.NEXTVAL FROM DUAL");
+ let probe = execute_on_pool(state, target_pool_key, &probe_sql)
+ .await
+ .map_err(|e| format!("Failed to inspect Xugu identity next value for {schema}.{table}: {e}"))?
+ .rows
+ .first()
+ .and_then(|row| row.first())
+ .and_then(json_scalar_to_string)
+ .ok_or_else(|| format!("Missing Xugu identity next value for {schema}.{table}"))?;
+ let probe: i64 =
+ probe.parse().map_err(|_| format!("Invalid Xugu identity next value for {schema}.{table}: {probe}"))?;
+ Some(probe)
+ } else {
+ None
+ };
+ let next = xugu_identity_start_with(step, last, preexisting_probe)
+ .ok_or_else(|| format!("Xugu identity overflow for {schema}.{table}.{column}"))?;
+ let alter_sql = format!("ALTER SEQUENCE {sequence_name} START WITH {next}");
+ execute_on_pool(state, target_pool_key, &alter_sql)
+ .await
+ .map_err(|e| format!("Failed to sync Xugu identity for {schema}.{table}.{column}: {e}"))?;
+ }
+ Ok(())
+}
+
#[derive(Debug, Clone)]
struct PostgresOwnedSequence {
name: String,
@@ -3146,6 +3342,9 @@ pub fn escape_value_typed(val: &serde_json::Value, db_type: &DatabaseType, colum
if *db_type == DatabaseType::Db2 {
return db2::string_literal(s, column_type);
}
+ if let Some(xugu_literal) = format_xugu_typed_sql_literal(s, db_type, column_type) {
+ return xugu_literal;
+ }
if let Some(json_array_literal) = format_starrocks_json_array_sql_literal(s, db_type, column_type) {
return json_array_literal;
}
@@ -3350,11 +3549,200 @@ fn format_xugu_binary_sql_literal(value: &str, db_type: &DatabaseType, column_ty
}
let hex = value.strip_prefix("0x").or_else(|| value.strip_prefix("0X"))?;
- if hex.is_empty() || hex.len() % 2 != 0 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ if hex.len() % 2 != 0 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ return None;
+ }
+
+ // Xugu's SQL hex literal also represents an empty binary value as X''.
+ // Keeping binary bytes out of string literals avoids accidental charset
+ // conversion while transferring BINARY/BLOB columns through the Agent.
+ Some(format!("X'{hex}'"))
+}
+
+fn format_xugu_typed_sql_literal(value: &str, db_type: &DatabaseType, column_type: Option<&str>) -> Option<String> {
+ if !matches!(db_type, DatabaseType::Xugu) {
+ return None;
+ }
+ let column_type = column_type?;
+ let normalized = normalize_xugu_type_name(column_type);
+
+ if matches!(normalized.as_str(), "GEOMETRY" | "GEOGRAPHY" | "BOX2D" | "BOX3D") {
+ let hex = value.strip_prefix("0x").or_else(|| value.strip_prefix("0X"))?;
+ if hex.is_empty() || hex.len() % 2 != 0 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ return None;
+ }
+ // Source-side EWKB retains SRID and Z/M coordinates, unlike the
+ // driver's generic WKT decoding. BOX values travel as their geometry
+ // representation and are cast back to the original target type.
+ let geometry = format!("ST_GeomFromEWKB(HEXTORAW('{hex}'))");
+ return Some(if normalized == "GEOMETRY" { geometry } else { format!("CAST({geometry} AS {normalized})") });
+ }
+
+ if matches!(normalized.as_str(), "BIT" | "VARBIT" | "BIT VARYING") {
+ if value.bytes().all(|byte| matches!(byte, b'0' | b'1')) {
+ return Some(format!("B'{}'", value));
+ }
return None;
}
- Some(format!("HEXTORAW('{hex}')"))
+ if let Some(interval_type) = xugu_interval_literal_type(column_type) {
+ let interval_value = normalize_xugu_interval_literal_value(value, &normalized);
+ return Some(format!("INTERVAL {} {}", quote_string_literal(&interval_value), interval_type));
+ }
+
+ if normalized == "TIME" {
+ // Xugu accepts TIME input through an explicit cast, but does not
+ // accept the standard SQL `TIME '...'` literal form.
+ return Some(format!("CAST({} AS TIME)", quote_string_literal(value)));
+ }
+
+ // Unlike Oracle/PostgreSQL, Xugu does not accept SQL-standard typed
+ // literals for its timezone-aware temporal types. Its SQL layer accepts
+ // these values through ordinary string-to-column conversion (verified on
+ // Xugu 12.0); returning None lets the common formatter emit that string.
+ // Keep this fallback Xugu-only so other database dialects are unchanged.
+ None
+}
+
+fn normalize_xugu_type_name(column_type: &str) -> String {
+ let upper = column_type.trim().to_ascii_uppercase();
+ let upper = upper.strip_prefix("INTERVAL ").unwrap_or(&upper);
+ let mut normalized = String::with_capacity(upper.len());
+ let mut in_precision = false;
+ for character in upper.chars() {
+ match character {
+ '(' => in_precision = true,
+ ')' => in_precision = false,
+ _ if !in_precision => normalized.push(character),
+ _ => {}
+ }
+ }
+ normalized.split_whitespace().collect::<Vec<_>>().join(" ")
+}
+
+fn xugu_interval_literal_type(column_type: &str) -> Option<String> {
+ let upper = column_type.trim().to_ascii_uppercase();
+ let interval_type = upper.strip_prefix("INTERVAL ")?;
+ let normalized = normalize_xugu_type_name(column_type);
+ let supported = [
+ "YEAR",
+ "YEAR TO MONTH",
+ "MONTH",
+ "DAY",
+ "DAY TO HOUR",
+ "HOUR",
+ "DAY TO MINUTE",
+ "HOUR TO MINUTE",
+ "MINUTE",
+ "DAY TO SECOND",
+ "HOUR TO SECOND",
+ "MINUTE TO SECOND",
+ "SECOND",
+ ];
+ if !supported.contains(&normalized.as_str()) {
+ return None;
+ }
+ // Keep source precision clauses when present (for example SECOND(6) or
+ // DAY(3) TO SECOND(6)); the literal's leading and trailing fields must
+ // match the declared Xugu interval type.
+ Some(interval_type.to_string())
+}
+
+fn normalize_xugu_interval_literal_value(value: &str, interval_type: &str) -> String {
+ // Xugu CAST(... AS VARCHAR) expands intervals into year-month or
+ // hour-minute-second fields even for narrower qualifiers. Convert back
+ // to the declared literal form without dropping nonzero trailing fields.
+ let value = value.trim();
+ match interval_type {
+ "YEAR" => normalize_xugu_year_month_value(value, true).unwrap_or_else(|| value.to_string()),
+ "MONTH" => normalize_xugu_year_month_value(value, false).unwrap_or_else(|| value.to_string()),
+ "DAY" | "DAY TO HOUR" | "DAY TO MINUTE" | "DAY TO SECOND" => {
+ normalize_xugu_day_time_value(value, interval_type).unwrap_or_else(|| value.to_string())
+ }
+ "HOUR" | "HOUR TO MINUTE" | "HOUR TO SECOND" | "MINUTE" | "MINUTE TO SECOND" | "SECOND" => {
+ normalize_xugu_time_value(value, interval_type).unwrap_or_else(|| value.to_string())
+ }
+ _ => value.to_string(),
+ }
+}
+
+fn split_xugu_interval_sign(value: &str) -> (&str, &str) {
+ if let Some(value) = value.strip_prefix('-') {
+ ("-", value)
+ } else if let Some(value) = value.strip_prefix('+') {
+ ("+", value)
+ } else {
+ ("", value)
+ }
+}
+
+fn normalize_xugu_year_month_value(value: &str, year_only: bool) -> Option<String> {
+ let (sign, unsigned) = split_xugu_interval_sign(value);
+ let (years, months) = unsigned.split_once('-')?;
+ let years = years.parse::<u64>().ok()?;
+ let months = months.parse::<u64>().ok()?;
+ if year_only {
+ (months == 0).then(|| format!("{sign}{years}"))
+ } else {
+ Some(format!("{}{total_months}", sign, total_months = years.checked_mul(12)?.checked_add(months)?))
+ }
+}
+
+fn parse_xugu_interval_seconds(value: &str) -> Option<(u64, &str)> {
+ let (whole, fraction) = match value.split_once('.') {
+ Some((whole, fraction)) if !fraction.is_empty() && fraction.bytes().all(|byte| byte.is_ascii_digit()) => {
+ (whole, fraction)
+ }
+ Some(_) => return None,
+ None => (value, ""),
+ };
+ Some((whole.parse().ok()?, fraction))
+}
+
+fn parse_xugu_interval_hms(value: &str) -> Option<(u64, u64, u64, &str)> {
+ let mut fields = value.split(':');
+ let hours = fields.next()?.parse().ok()?;
+ let minutes = fields.next()?.parse().ok()?;
+ let (seconds, fraction) = parse_xugu_interval_seconds(fields.next()?)?;
+ fields.next().is_none().then_some((hours, minutes, seconds, fraction))
+}
+
+fn normalize_xugu_day_time_value(value: &str, interval_type: &str) -> Option<String> {
+ let (sign, unsigned) = split_xugu_interval_sign(value);
+ let (days, time) = unsigned.split_once(' ')?;
+ let days = days.parse::<u64>().ok()?;
+ let (hours, minutes, seconds, fraction) = parse_xugu_interval_hms(time)?;
+ match interval_type {
+ "DAY" if hours == 0 && minutes == 0 && seconds == 0 && fraction.is_empty() => Some(format!("{sign}{days}")),
+ "DAY TO HOUR" if minutes == 0 && seconds == 0 && fraction.is_empty() => Some(format!("{sign}{days} {hours}")),
+ "DAY TO MINUTE" if seconds == 0 && fraction.is_empty() => Some(format!("{sign}{days} {hours}:{minutes:02}")),
+ "DAY TO SECOND" => Some(value.to_string()),
+ _ => None,
+ }
+}
+
+fn normalize_xugu_time_value(value: &str, interval_type: &str) -> Option<String> {
+ let (sign, unsigned) = split_xugu_interval_sign(value);
+ let (hours, minutes, seconds, fraction) = parse_xugu_interval_hms(unsigned)?;
+ match interval_type {
+ "HOUR" if minutes == 0 && seconds == 0 && fraction.is_empty() => Some(format!("{sign}{hours}")),
+ "HOUR TO MINUTE" if seconds == 0 && fraction.is_empty() => Some(format!("{sign}{hours}:{minutes:02}")),
+ "HOUR TO SECOND" => Some(value.to_string()),
+ "MINUTE" if seconds == 0 && fraction.is_empty() => {
+ Some(format!("{sign}{}", hours.checked_mul(60)?.checked_add(minutes)?))
+ }
+ "MINUTE TO SECOND" => Some(format!(
+ "{sign}{}:{seconds:02}{fractional}",
+ hours.checked_mul(60)?.checked_add(minutes)?,
+ fractional = if fraction.is_empty() { String::new() } else { format!(".{fraction}") },
+ )),
+ "SECOND" => Some(format!(
+ "{sign}{total_seconds}{fractional}",
+ total_seconds = hours.checked_mul(3600)?.checked_add(minutes.checked_mul(60)?)?.checked_add(seconds)?,
+ fractional = if fraction.is_empty() { String::new() } else { format!(".{fraction}") },
+ )),
+ _ => None,
+ }
}
fn format_oracle_temporal_sql_literal(
@@ -4870,6 +5258,12 @@ fn rewrite_transfer_source_table_ddl(
} else {
rewrite_mysql_create_table_name(sql, target_table)
}
+ } else if matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu)) {
+ // Xugu's Agent DDL contains quoted schema-qualified CREATE/ALTER/INDEX
+ // statements. Rewrite only code spans so schema names inside comments
+ // and string literals remain untouched; table casing is validated as
+ // Preserve for structure transfers.
+ Some(rewrite_double_quoted_schema_qualifier(sql, source_schema, target_schema))
} else {
Some(sql.to_string())
}
@@ -5263,6 +5657,15 @@ fn generate_insert_typed_sql_batches_for_transfer(
return Ok(Vec::new());
}
+ if columns.is_empty() && *db_type == DatabaseType::Xugu {
+ // ROWVERSION is generated and immutable in XuguDB. A table containing
+ // only that column still needs one default row per source row; Xugu's
+ // `DEFAULT VALUES` form is single-row, so keep these statements
+ // separate instead of emitting invalid empty-column VALUES tuples.
+ let target = qualified_table(table, schema, db_type, catalog);
+ return Ok(rows.iter().map(|_| (format!("INSERT INTO {target} DEFAULT VALUES"), 1)).collect());
+ }
+
let value_rows = value_rows_sql(rows, column_types, db_type, mysql_spatial_markers);
generate_insert_sql_batches_from_value_rows(
columns,
@@ -6913,7 +7316,7 @@ fn transfer_ddl_statements(sql: &str, db_type: &DatabaseType) -> Vec<String> {
})
.collect()
}
- } else if matches!(db_type, DatabaseType::Dameng) {
+ } else if matches!(db_type, DatabaseType::Dameng | DatabaseType::Xugu) {
let statements = split_sql_statements_for_database(sql, *db_type);
if statements.is_empty() {
vec![sql.trim().to_string()]
@@ -9227,6 +9630,7 @@ pub async fn preview_transfer_ownership(
source_pool_key: &str,
target_pool_key: &str,
) -> Result<TransferOwnershipPreview, String> {
+ validate_transfer_database_pair(request, source_db_type, target_db_type)?;
// PostgreSQL-compatible transfers report role ownership gaps for the confirmation flow.
let (missing_owners, target_owner) =
if request.create_table && is_postgres_compat_transfer(source_db_type, target_db_type) {
@@ -9874,7 +10278,7 @@ where
}
#[derive(Default)]
-struct HiveServerTransferCursor {
+struct AgentTransferCursor {
started: bool,
session_id: Option<String>,
}
@@ -9930,8 +10334,142 @@ fn transfer_cursor_sql(
format!("SELECT {col_list} FROM {full_table}")
}
+const XUGU_SPATIAL_PROBE_SQL: &str = "SELECT ST_AsEWKB(ST_GeomFromText('POINT(0 0)')) FROM DUAL";
+
+fn is_xugu_spatial_column_type(data_type: &str) -> bool {
+ matches!(normalize_xugu_type_name(data_type).as_str(), "GEOMETRY" | "GEOGRAPHY" | "BOX2D" | "BOX3D")
+}
+
+fn xugu_columns_include_spatial(columns: &[db::ColumnInfo]) -> bool {
+ columns.iter().any(|column| is_xugu_spatial_column_type(&column.data_type))
+}
+
+/// Spatial Xugu can transfer geometry to spatial Xugu. A build without the
+/// spatial functions must fail before CREATE or INSERT rather than halfway
+/// through a mixed pair.
+async fn ensure_xugu_spatial_transfer_supported(
+ state: &AppState,
+ columns: &[db::ColumnInfo],
+ source_db_type: &DatabaseType,
+ target_db_type: &DatabaseType,
+ source_pool_key: &str,
+ target_pool_key: &str,
+ table: &str,
+) -> Result<(), String> {
+ if !matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu))
+ || !xugu_columns_include_spatial(columns)
+ {
+ return Ok(());
+ }
+ let source_error = execute_on_pool(state, source_pool_key, XUGU_SPATIAL_PROBE_SQL).await.err();
+ let target_error = if source_pool_key == target_pool_key {
+ source_error.clone()
+ } else {
+ execute_on_pool(state, target_pool_key, XUGU_SPATIAL_PROBE_SQL).await.err()
+ };
+ match (source_error, target_error) {
+ (None, None) => Ok(()),
+ (Some(error), None) => {
+ Err(format!("虚谷空间表 {table} 需要源库支持空间函数 ST_GeomFromText/ST_AsEWKB:{error}"))
+ }
+ (None, Some(error)) => {
+ Err(format!("虚谷空间表 {table} 需要目标库支持空间函数 ST_GeomFromText/ST_AsEWKB:{error}"))
+ }
+ (Some(source), Some(target)) => Err(format!(
+ "虚谷空间表 {table} 需要源和目标都支持空间函数 ST_GeomFromText/ST_AsEWKB。源:{source} 目标:{target}"
+ )),
+ }
+}
+
+/// A Xugu agent session has one server connection. Holding a read cursor open
+/// while writing through that same session blocks once the first page returns.
+/// Page with LIMIT/OFFSET instead; two connections keep the streaming cursor.
+fn xugu_transfer_shares_agent_session(
+ source_db_type: &DatabaseType,
+ source_pool_key: &str,
+ target_pool_key: &str,
+) -> bool {
+ *source_db_type == DatabaseType::Xugu && source_pool_key == target_pool_key
+}
+
+fn xugu_transfer_page_sql(
+ columns: &[db::ColumnInfo],
+ table: &str,
+ schema: &str,
+ catalog: Option<&str>,
+ primary_keys: &[String],
+ offset: u64,
+ limit: usize,
+) -> String {
+ // Re-running LIMIT/OFFSET pages is unstable for tables without a unique key
+ // (rows can be skipped or repeated), so order by the primary key when present.
+ let order = postgres_order_by_expression(primary_keys, &DatabaseType::Xugu)
+ .map(|expression| format!(" ORDER BY {expression}"))
+ .unwrap_or_default();
+ format!("{}{order} LIMIT {limit} OFFSET {offset}", xugu_transfer_cursor_sql(columns, table, schema, catalog))
+}
+
+/// Build a source-side projection for Xugu transfer rows whose wire values are
+/// not safely represented by the Go driver's generic `database/sql` values.
+/// This stays on the Xugu path only; the returned strings are still formatted
+/// against the original column metadata when INSERT statements are generated.
+fn xugu_transfer_cursor_sql(columns: &[db::ColumnInfo], table: &str, schema: &str, catalog: Option<&str>) -> String {
+ let db_type = DatabaseType::Xugu;
+ let full_table = qualified_table(table, schema, &db_type, catalog);
+ let projection = columns
+ .iter()
+ .map(|column| {
+ let identifier = quote_identifier(&column.name, &db_type);
+ let normalized = normalize_xugu_type_name(&column.data_type);
+ let expression = if matches!(normalized.as_str(), "GEOMETRY" | "GEOGRAPHY" | "BOX2D" | "BOX3D") {
+ let geometry = if normalized == "GEOMETRY" {
+ identifier.clone()
+ } else {
+ format!("CAST({identifier} AS GEOMETRY)")
+ };
+ // Hex text bypasses lossy WKT decoding and raw BOX bytes.
+ // Keep SQL NULL distinct from an empty geometry's EWKB.
+ format!("CASE WHEN {identifier} IS NULL THEN NULL ELSE '0x'||RAWTOHEX(ST_AsEWKB({geometry})) END")
+ } else if is_binary_transfer_column_type(&column.data_type) {
+ // Preserve NULL separately from an empty BLOB/BINARY value.
+ format!("CASE WHEN {identifier} IS NULL THEN NULL ELSE '0x'||RAWTOHEX({identifier}) END")
+ } else if matches!(normalized.as_str(), "BIT" | "VARBIT" | "BIT VARYING") {
+ let length = column.character_maximum_length.filter(|length| *length > 0).unwrap_or(32_767).min(32_767);
+ // Xugu pads BIT/VARBIT text casts to the declared bit width.
+ // Remove that padding so the B'...' target literal contains
+ // only the original 0/1 digits.
+ format!("RTRIM(CAST({identifier} AS VARCHAR({length})))")
+ } else if normalized == "TIME" {
+ // The Go driver materializes Xugu TIME as a timestamp-like
+ // value with a synthetic date. Project it as text so target
+ // inserts receive only the original time-of-day value.
+ format!("CAST({identifier} AS VARCHAR(64))")
+ } else if matches!(normalized.as_str(), "TIME WITH TIME ZONE" | "TIMEZONE" | "TIMETZ")
+ || matches!(
+ normalized.as_str(),
+ "DATETIME WITH TIME ZONE" | "DATETIME TIMEZONE" | "TIMESTAMP WITH TIME ZONE" | "TIMESTAMP_TZ"
+ )
+ || xugu_interval_literal_type(&column.data_type).is_some()
+ {
+ // The driver currently decodes TIMETZ into a time.Time without
+ // retaining the source offset. Intervals also need their exact
+ // Xugu text form for a typed target literal.
+ format!("CAST({identifier} AS VARCHAR(256))")
+ } else {
+ identifier.clone()
+ };
+ format!("{expression} AS {identifier}")
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!("SELECT {projection} FROM {full_table}")
+}
+
fn uses_agent_transfer_cursor(db_type: &DatabaseType) -> bool {
- matches!(db_type, DatabaseType::Kyuubi | DatabaseType::Impala | DatabaseType::Transwarp | DatabaseType::Db2)
+ matches!(
+ db_type,
+ DatabaseType::Kyuubi | DatabaseType::Impala | DatabaseType::Transwarp | DatabaseType::Db2 | DatabaseType::Xugu
+ )
}
fn transfer_upsert_falls_back_to_append(db_type: &DatabaseType) -> bool {
@@ -9956,13 +10494,13 @@ fn transfer_clear_table_sql(table: &str, schema: &str, db_type: &DatabaseType, c
}
}
-async fn fetch_hive_server_transfer_batch(
+async fn fetch_agent_transfer_batch(
state: &AppState,
pool_key: &str,
request: &TransferRequest,
sql: &str,
batch_size: usize,
- cursor: &mut HiveServerTransferCursor,
+ cursor: &mut AgentTransferCursor,
) -> Result<db::QueryResult, String> {
let query_timeout_secs = if cursor.started {
0
@@ -9979,7 +10517,7 @@ async fn fetch_hive_server_transfer_batch(
let mut client = client.lock().await;
let result = if cursor.started {
let session_id =
- cursor.session_id.as_deref().ok_or("Impala transfer cursor ended before the next page was requested")?;
+ cursor.session_id.as_deref().ok_or("Agent transfer cursor ended before the next page was requested")?;
client.fetch_table_read_page::<db::QueryResult>(session_id, batch_size).await?
} else {
cursor.started = true;
@@ -9999,7 +10537,7 @@ async fn fetch_hive_server_transfer_batch(
if result.has_more {
cursor.session_id = result.session_id.clone().or_else(|| cursor.session_id.clone());
if cursor.session_id.is_none() {
- return Err("Impala transfer cursor did not return a session id for additional rows".to_string());
+ return Err("Agent transfer cursor did not return a session id for additional rows".to_string());
}
} else {
cursor.session_id = None;
@@ -10007,7 +10545,7 @@ async fn fetch_hive_server_transfer_batch(
Ok(result)
}
-async fn close_hive_server_transfer_cursor(state: &AppState, pool_key: &str, cursor: &mut HiveServerTransferCursor) {
+async fn close_agent_transfer_cursor(state: &AppState, pool_key: &str, cursor: &mut AgentTransferCursor) {
let Some(session_id) = cursor.session_id.take() else {
return;
};
@@ -10018,7 +10556,7 @@ async fn close_hive_server_transfer_cursor(state: &AppState, pool_key: &str, cur
let client = client.clone();
let mut client = client.lock().await;
if let Err(error) = client.close_table_read_session::<bool>(&session_id).await {
- log::warn!("[transfer] failed to close Impala transfer cursor: {error}");
+ log::warn!("[transfer] failed to close Agent transfer cursor: {error}");
}
}
@@ -10719,9 +11257,20 @@ where
.is_some_and(|config| db::doris::is_native_profile(&config.db_type, config.driver_profile.as_deref()))
};
ensure_transfer_columns_supported(request, is_doris_source, table, &columns)?;
+ ensure_xugu_spatial_transfer_supported(
+ state,
+ &columns,
+ source_db_type,
+ target_db_type,
+ source_pool_key,
+ target_pool_key,
+ table,
+ )
+ .await?;
let writable_columns = writable_transfer_columns(&columns, source_db_type, target_db_type);
- let default_rows_only = mysql_generated_only_transfer(&columns, source_db_type, target_db_type);
+ let default_rows_only = mysql_generated_only_transfer(&columns, source_db_type, target_db_type)
+ || xugu_rowversion_only_transfer(&columns, source_db_type, target_db_type);
if writable_columns.is_empty() && !default_rows_only {
return Err(format!("No writable columns found for table {table}"));
}
@@ -10912,7 +11461,9 @@ where
// Empty-column INSERTs are safe only when the target also computes every
// value. Reject incompatible data-only targets before an overwrite truncates
// them; otherwise ordinary columns could silently receive defaults instead.
- if default_rows_only && !mysql_generated_only_transfer(&target_columns, target_db_type, target_db_type) {
+ let target_default_rows_only = mysql_generated_only_transfer(&target_columns, target_db_type, target_db_type)
+ || xugu_rowversion_only_transfer(&target_columns, target_db_type, target_db_type);
+ if default_rows_only && !target_default_rows_only {
return Err(format!(
"Target table '{target_table}' must contain only generated columns for default-row transfer"
));
@@ -11148,20 +11699,36 @@ where
transfer_keyset_column_indexes(&writable_columns, &primary_key_columns, source_db_type)
};
let mut keyset_cursor: Vec<serde_json::Value> = Vec::new();
- // A single Agent cursor keeps Hive-family rows in one query execution. Inceptor
- // rejects the generic LIMIT/OFFSET form, just like the other Agent cursor paths.
- // Re-running LIMIT/OFFSET pages is unstable for tables without a unique key.
- let use_hive_server_cursor = table_filter.is_none() && uses_agent_transfer_cursor(source_db_type);
- let hive_server_transfer_sql = use_hive_server_cursor.then(|| {
- transfer_cursor_sql(
- &col_names,
- table,
- &request.source_schema,
- source_db_type,
- request.source_catalog.as_deref(),
- )
+ // A single Agent cursor keeps Xugu/Hive-family rows in one query execution.
+ // Inceptor rejects the generic LIMIT/OFFSET form, and re-running LIMIT/OFFSET
+ // pages is unstable for tables without a unique key. A row filter stays on
+ // the filtered page SQL. The Xugu agent keeps that cursor on its only server
+ // connection, so a transfer inside one session pages instead of holding the
+ // cursor open across target writes.
+ let xugu_same_session = xugu_transfer_shares_agent_session(source_db_type, source_pool_key, target_pool_key);
+ let use_agent_cursor = table_filter.is_none()
+ && uses_agent_transfer_cursor(source_db_type)
+ && !default_rows_only
+ && !xugu_same_session;
+ let agent_transfer_sql = use_agent_cursor.then(|| {
+ if *source_db_type == DatabaseType::Xugu {
+ xugu_transfer_cursor_sql(
+ &writable_columns,
+ table,
+ &request.source_schema,
+ request.source_catalog.as_deref(),
+ )
+ } else {
+ transfer_cursor_sql(
+ &col_names,
+ table,
+ &request.source_schema,
+ source_db_type,
+ request.source_catalog.as_deref(),
+ )
+ }
});
- let mut hive_server_cursor = HiveServerTransferCursor::default();
+ let mut agent_cursor = AgentTransferCursor::default();
// Key-less PostgreSQL heaps page by `ctid` windows instead of OFFSET: an
// OFFSET page re-reads every row before it, so a ten-million-row table gets
// slower as it runs and never finishes. Tables with a usable key keep the
@@ -11206,19 +11773,23 @@ where
return Err("Cancelled".to_string());
}
- let (mut result, mysql_spatial_markers) = if let Some(sql) = hive_server_transfer_sql.as_deref() {
+ let (mut result, mysql_spatial_markers) = if let Some(sql) = agent_transfer_sql.as_deref() {
(
- fetch_hive_server_transfer_batch(
- state,
- source_pool_key,
- request,
- sql,
- batch_size,
- &mut hive_server_cursor,
- )
- .await?,
+ fetch_agent_transfer_batch(state, source_pool_key, request, sql, batch_size, &mut agent_cursor)
+ .await?,
false,
)
+ } else if xugu_same_session && !default_rows_only {
+ let sql = xugu_transfer_page_sql(
+ &writable_columns,
+ table,
+ &request.source_schema,
+ request.source_catalog.as_deref(),
+ &primary_key_columns,
+ offset,
+ batch_size,
+ );
+ (execute_on_pool_with_max_rows(state, source_pool_key, &sql, Some(batch_size)).await?, false)
} else if let Some(pager) = ctid_pager.as_ref() {
let sql = pager.page_sql(&col_names, table, &request.source_schema, batch_size);
(execute_on_pool_with_max_rows(state, source_pool_key, &sql, Some(batch_size)).await?, false)
@@ -11388,16 +11959,28 @@ where
if ctid_scan_finished == Some(true) {
break;
}
- } else if (use_hive_server_cursor && !has_more) || (!use_hive_server_cursor && row_count < batch_size) {
+ } else if (use_agent_cursor && !has_more) || (!use_agent_cursor && row_count < batch_size) {
break;
}
}
Ok(())
}
.await;
- close_hive_server_transfer_cursor(state, source_pool_key, &mut hive_server_cursor).await;
+ close_agent_transfer_cursor(state, source_pool_key, &mut agent_cursor).await;
transfer_result?;
+ if *target_db_type == DatabaseType::Xugu && total_transferred > 0 {
+ sync_xugu_identity_sequences(
+ state,
+ target_pool_key,
+ &target_table,
+ &request.target_schema,
+ &write_col_names,
+ target_table_preexisting,
+ )
+ .await?;
+ }
+
if pg_compat_transfer {
for statement in generate_postgres_sequence_sync_sql(&columns, &target_table, &request.target_schema) {
execute_on_pool(state, target_pool_key, &statement)
@@ -11774,6 +12357,7 @@ where
F: FnMut(TransferProgress),
C: FnMut(Option<u64>),
{
+ validate_transfer_database_pair(request, source_db_type, target_db_type)?;
let state = state.clone();
let request = request.clone();
let table = table.to_string();
@@ -13390,6 +13974,76 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
mod transfer_validation_tests {
use super::*;
+ fn base_request() -> TransferRequest {
+ TransferRequest {
+ transfer_id: "xugu-transfer-test".into(),
+ source_connection_id: "source".into(),
+ source_database: "SOURCE_DB".into(),
+ source_schema: "SOURCE_SCHEMA".into(),
+ source_catalog: None,
+ target_connection_id: "target".into(),
+ target_database: "TARGET_DB".into(),
+ target_schema: "TARGET_SCHEMA".into(),
+ target_catalog: None,
+ tables: vec!["ORDERS".into()],
+ create_table: true,
+ content: TransferContent::StructureAndData,
+ objects: None,
+ mode: TransferMode::Append,
+ target_table_name_case: TransferTableNameCase::Preserve,
+ quote_target_column_names: true,
+ ownership_policy: TransferOwnershipPolicy::Preserve,
+ batch_size: 1000,
+ table_filters: std::collections::HashMap::new(),
+ drop_target_before_create: false,
+ drop_target_confirmed: false,
+ }
+ }
+
+ #[test]
+ fn xugu_transfer_is_same_engine_table_only_and_append_or_overwrite() {
+ let request = base_request();
+ assert!(validate_transfer_database_pair(&request, &DatabaseType::Xugu, &DatabaseType::Xugu).is_ok());
+ // Existing non-Xugu transfer combinations retain their prior policy.
+ assert!(validate_transfer_database_pair(&request, &DatabaseType::Postgres, &DatabaseType::Mysql).is_ok());
+
+ let err =
+ validate_transfer_database_pair(&request, &DatabaseType::Xugu, &DatabaseType::Postgres).unwrap_err();
+ assert!(err.contains("虚谷到虚谷"), "{err}");
+ let err = validate_transfer_database_pair(&request, &DatabaseType::Mysql, &DatabaseType::Xugu).unwrap_err();
+ assert!(err.contains("虚谷到虚谷"), "{err}");
+
+ for mode in [TransferMode::Append, TransferMode::Overwrite] {
+ let request = TransferRequest { mode, ..request.clone() };
+ assert!(validate_transfer_database_pair(&request, &DatabaseType::Xugu, &DatabaseType::Xugu).is_ok());
+ }
+ let upsert = TransferRequest { mode: TransferMode::Upsert, ..request.clone() };
+ assert!(validate_transfer_database_pair(&upsert, &DatabaseType::Xugu, &DatabaseType::Xugu)
+ .unwrap_err()
+ .contains("追加或覆盖"));
+ let rebuild = TransferRequest { drop_target_before_create: true, ..request.clone() };
+ assert!(validate_transfer_database_pair(&rebuild, &DatabaseType::Xugu, &DatabaseType::Xugu).is_err());
+ }
+
+ #[test]
+ fn xugu_structure_transfer_rejects_renamed_tables_and_non_table_objects() {
+ let request = TransferRequest { target_table_name_case: TransferTableNameCase::Upper, ..base_request() };
+ assert!(validate_transfer_database_pair(&request, &DatabaseType::Xugu, &DatabaseType::Xugu)
+ .unwrap_err()
+ .contains("保留源表名"));
+
+ let request = TransferRequest {
+ objects: Some(vec![TransferObjectSelection {
+ object_type: TransferObjectKind::View,
+ names: vec!["V_ORDERS".into()],
+ }]),
+ ..base_request()
+ };
+ assert!(validate_transfer_database_pair(&request, &DatabaseType::Xugu, &DatabaseType::Xugu)
+ .unwrap_err()
+ .contains("仅支持表对象"));
+ }
+
#[test]
fn validates_content_and_object_rules() {
let base = TransferRequest {
@@ -14800,6 +15454,114 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
assert_eq!(writable.iter().map(|column| column.name.as_str()).collect::<Vec<_>>(), vec!["id", "name"]);
}
+ #[test]
+ fn xugu_writable_transfer_columns_regenerate_rowversion_values() {
+ let columns =
+ vec![test_column("ID", "INTEGER"), test_column("RV", "ROWVERSION"), test_column("NOTE", "VARCHAR(40)")];
+
+ let writable = writable_transfer_columns(&columns, &DatabaseType::Xugu, &DatabaseType::Xugu);
+
+ assert_eq!(writable.iter().map(|column| column.name.as_str()).collect::<Vec<_>>(), vec!["ID", "NOTE"]);
+ assert!(is_xugu_non_insertable_transfer_column(&columns[1], &DatabaseType::Xugu, &DatabaseType::Xugu));
+ assert!(!is_xugu_non_insertable_transfer_column(&columns[1], &DatabaseType::Xugu, &DatabaseType::Postgres));
+ assert!(xugu_rowversion_only_transfer(&[columns[1].clone()], &DatabaseType::Xugu, &DatabaseType::Xugu));
+ assert!(!xugu_rowversion_only_transfer(&columns, &DatabaseType::Xugu, &DatabaseType::Xugu));
+ }
+
+ #[test]
+ fn xugu_identity_lookup_uses_serial_id_and_scopes_the_target_database() {
+ let sql = xugu_identity_sequences_sql("GUE'ST", "T'1");
+ assert!(sql.contains("c.SERIAL_ID=q.SEQ_ID"));
+ assert!(sql.contains("s.DB_ID=CURRENT_DB_ID"));
+ assert!(sql.contains("s.SCHEMA_NAME='GUE''ST'"));
+ assert!(sql.contains("t.TABLE_NAME='T''1'"));
+ assert!(sql.contains("c.IS_SERIAL=TRUE AND q.IS_SYS=TRUE"));
+ assert!(!sql.contains("UPPER("));
+ }
+
+ #[test]
+ fn xugu_identity_lookup_folds_case_only_as_a_fallback() {
+ let sql = xugu_identity_sequences_sql_case_insensitive("App", "Items");
+ assert!(sql.contains("UPPER(s.SCHEMA_NAME)=UPPER('App')"));
+ assert!(sql.contains("UPPER(t.TABLE_NAME)=UPPER('Items')"));
+ assert!(sql.contains("s.SCHEMA_NAME, t.TABLE_NAME"));
+ }
+
+ #[test]
+ fn xugu_identity_restart_restores_a_consumed_nextval_when_the_sequence_is_ahead() {
+ assert_eq!(xugu_identity_start_with(1, 50, None), Some(51));
+ assert_eq!(xugu_identity_start_with(1, 50, Some(20)), Some(51));
+ assert_eq!(xugu_identity_start_with(1, 50, Some(50)), Some(51));
+ assert_eq!(xugu_identity_start_with(1, 50, Some(100)), Some(100));
+ assert_eq!(xugu_identity_start_with(10, 100, Some(105)), Some(105));
+ assert_eq!(xugu_identity_start_with(-1, -5, Some(-10)), Some(-10));
+ assert_eq!(xugu_identity_start_with(-1, -5, Some(-3)), Some(-6));
+ assert_eq!(xugu_identity_start_with(1, i64::MAX, None), None);
+ }
+
+ #[test]
+ fn xugu_spatial_columns_cover_geometry_modifiers_but_not_ordinary_types() {
+ assert!(is_xugu_spatial_column_type("GEOMETRY"));
+ assert!(is_xugu_spatial_column_type("geometry(PointZ,4326)"));
+ assert!(is_xugu_spatial_column_type("GEOGRAPHY"));
+ assert!(is_xugu_spatial_column_type("BOX2D"));
+ assert!(is_xugu_spatial_column_type("BOX3D"));
+ assert!(!is_xugu_spatial_column_type("VARCHAR(40)"));
+ assert!(!is_xugu_spatial_column_type("BLOB"));
+ let columns = vec![test_column("ID", "INTEGER"), test_column("G", "geometry(Point,3857)")];
+ assert!(xugu_columns_include_spatial(&columns));
+ assert!(!xugu_columns_include_spatial(&[test_column("ID", "INTEGER")]));
+ }
+
+ #[test]
+ fn xugu_same_session_pages_without_holding_the_agent_cursor() {
+ assert!(xugu_transfer_shares_agent_session(&DatabaseType::Xugu, "conn:SYSTEM", "conn:SYSTEM"));
+ assert!(!xugu_transfer_shares_agent_session(&DatabaseType::Xugu, "conn:SYSTEM", "conn:GIS"));
+ assert!(!xugu_transfer_shares_agent_session(&DatabaseType::Postgres, "conn", "conn"));
+ let sql = xugu_transfer_page_sql(&[test_column("G", "GEOMETRY")], "SHAPES", "APP", None, &[], 1000, 1000);
+ assert!(sql.contains("ST_AsEWKB(\"G\")"));
+ assert!(sql.ends_with("LIMIT 1000 OFFSET 1000"));
+
+ // A primary key makes LIMIT/OFFSET paging deterministic; without one the
+ // plain projection keeps the previous behavior.
+ let keyed = xugu_transfer_page_sql(
+ &[test_column("ID", "INTEGER"), test_column("G", "GEOMETRY")],
+ "SHAPES",
+ "APP",
+ None,
+ &["ID".to_string()],
+ 2000,
+ 1000,
+ );
+ assert!(keyed.contains(" ORDER BY \"ID\" LIMIT 1000 OFFSET 2000"));
+ }
+
+ #[test]
+ fn xugu_rowversion_only_transfer_inserts_default_rows() {
+ let batches = generate_insert_typed_sql_batches_for_transfer(
+ &[],
+ &[],
+ &[Vec::new(), Vec::new()],
+ "VERSIONS",
+ "APP",
+ &DatabaseType::Xugu,
+ None,
+ SqlBatchLimits { max_rows: 100, target_sql_bytes: 1024, hard_sql_bytes: None },
+ false,
+ false,
+ true,
+ )
+ .unwrap();
+
+ assert_eq!(
+ batches,
+ vec![
+ ("INSERT INTO \"APP\".\"VERSIONS\" DEFAULT VALUES".into(), 1),
+ ("INSERT INTO \"APP\".\"VERSIONS\" DEFAULT VALUES".into(), 1),
+ ]
+ );
+ }
+
#[test]
fn mysql_generated_only_transfer_requires_nonempty_same_engine_generated_metadata() {
let generated = vec![
@@ -15717,6 +16479,188 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
);
}
+ #[test]
+ fn xugu_transfer_ddl_splits_table_constraints_indexes_and_comments() {
+ let ddl = "CREATE TABLE \"APP\".\"ITEMS\" (\"ID\" INTEGER, \"NOTE\" VARCHAR(100));\n\
+ ALTER TABLE \"APP\".\"ITEMS\" ADD CONSTRAINT \"ITEMS_PK\" PRIMARY KEY (\"ID\");\n\
+ CREATE INDEX \"ITEMS_NOTE_IDX\" ON \"APP\".\"ITEMS\" (\"NOTE\");\n\
+ COMMENT ON TABLE \"APP\".\"ITEMS\" IS 'semi;colon';";
+ let statements = transfer_ddl_statements(ddl, &DatabaseType::Xugu);
+ assert_eq!(statements.len(), 4, "{statements:#?}");
+ assert!(statements[0].starts_with("CREATE TABLE"));
+ assert!(statements[1].starts_with("ALTER TABLE"));
+ assert!(statements[2].starts_with("CREATE INDEX"));
+ assert_eq!(statements[3], "COMMENT ON TABLE \"APP\".\"ITEMS\" IS 'semi;colon'");
+ }
+
+ #[test]
+ fn xugu_reused_ddl_rewrites_schema_only_in_code_spans() {
+ let ddl = "CREATE TABLE \"SRC\".\"ITEMS\" (\"NOTE\" VARCHAR(100) DEFAULT '\"SRC\".ITEMS');\n\
+ ALTER TABLE \"SRC\".\"ITEMS\" ADD CONSTRAINT \"ITEMS_PK\" PRIMARY KEY (\"ID\");\n\
+ CREATE INDEX \"ITEMS_NOTE_IDX\" ON \"SRC\".\"ITEMS\" (\"NOTE\");\n\
+ -- \"SRC\".\"ITEMS\" remains in this comment";
+ let rewritten = rewrite_transfer_source_table_ddl(
+ ddl,
+ "SRC",
+ "DST",
+ &DatabaseType::Xugu,
+ &DatabaseType::Xugu,
+ "ITEMS",
+ "ITEMS",
+ )
+ .unwrap();
+ assert!(rewritten.contains("CREATE TABLE \"DST\".\"ITEMS\""));
+ assert!(rewritten.contains("ALTER TABLE \"DST\".\"ITEMS\""));
+ assert!(rewritten.contains("ON \"DST\".\"ITEMS\""));
+ assert!(rewritten.contains("DEFAULT '\"SRC\".ITEMS'"));
+ assert!(rewritten.contains("-- \"SRC\".\"ITEMS\" remains in this comment"));
+ assert!(can_reuse_source_table_ddl(&DatabaseType::Xugu, &DatabaseType::Xugu, None, None, true));
+ assert!(!can_reuse_source_table_ddl(&DatabaseType::Xugu, &DatabaseType::Xugu, None, None, false));
+ }
+
+ #[test]
+ fn xugu_transfer_reads_source_rows_through_agent_cursor() {
+ assert!(uses_agent_transfer_cursor(&DatabaseType::Xugu));
+ assert!(!uses_agent_transfer_cursor(&DatabaseType::Postgres));
+ assert!(!uses_agent_transfer_cursor(&DatabaseType::Mysql));
+ }
+
+ #[test]
+ fn xugu_transfer_cursor_projects_lossy_driver_types_as_text_or_hex() {
+ let columns = vec![
+ test_column("ID", "INTEGER"),
+ test_column("BLOB_C", "BLOB"),
+ db::ColumnInfo { character_maximum_length: Some(8), ..test_column("BIT_C", "BIT(8)") },
+ test_column("VARBIT_C", "VARBIT"),
+ test_column("TIME_C", "TIME"),
+ test_column("TIME_TZ_C", "TIME WITH TIME ZONE"),
+ test_column("IV_YM_C", "INTERVAL YEAR TO MONTH"),
+ test_column("NOTE", "VARCHAR(40)"),
+ ];
+
+ assert_eq!(
+ xugu_transfer_cursor_sql(&columns, "ITEMS", "APP", None),
+ r#"SELECT "ID" AS "ID", CASE WHEN "BLOB_C" IS NULL THEN NULL ELSE '0x'||RAWTOHEX("BLOB_C") END AS "BLOB_C", RTRIM(CAST("BIT_C" AS VARCHAR(8))) AS "BIT_C", RTRIM(CAST("VARBIT_C" AS VARCHAR(32767))) AS "VARBIT_C", CAST("TIME_C" AS VARCHAR(64)) AS "TIME_C", CAST("TIME_TZ_C" AS VARCHAR(256)) AS "TIME_TZ_C", CAST("IV_YM_C" AS VARCHAR(256)) AS "IV_YM_C", "NOTE" AS "NOTE" FROM "APP"."ITEMS""#
+ );
+ }
+
+ #[test]
+ fn xugu_transfer_cursor_preserves_spatial_srid_dimensions_and_box_values() {
+ let columns = vec![
+ test_column("G", "geometry(PointZ,4326)"),
+ test_column("GG", "GEOGRAPHY"),
+ test_column("B2", "BOX2D"),
+ test_column("B3", "BOX3D"),
+ ];
+ assert_eq!(
+ xugu_transfer_cursor_sql(&columns, "SHAPES", "APP", None),
+ r#"SELECT CASE WHEN "G" IS NULL THEN NULL ELSE '0x'||RAWTOHEX(ST_AsEWKB("G")) END AS "G", CASE WHEN "GG" IS NULL THEN NULL ELSE '0x'||RAWTOHEX(ST_AsEWKB(CAST("GG" AS GEOMETRY))) END AS "GG", CASE WHEN "B2" IS NULL THEN NULL ELSE '0x'||RAWTOHEX(ST_AsEWKB(CAST("B2" AS GEOMETRY))) END AS "B2", CASE WHEN "B3" IS NULL THEN NULL ELSE '0x'||RAWTOHEX(ST_AsEWKB(CAST("B3" AS GEOMETRY))) END AS "B3" FROM "APP"."SHAPES""#
+ );
+ }
+
+ #[test]
+ fn xugu_spatial_insert_restores_ewkb_only_for_valid_typed_hex_values() {
+ let hex = "0101000020110F0000000000000000F03F0000000000000040";
+ let geometry = format!("ST_GeomFromEWKB(HEXTORAW('{hex}'))");
+ for column_type in ["GEOMETRY", "geometry(Point,3857)"] {
+ assert_eq!(
+ escape_value_typed(&json!(format!("0x{hex}")), &DatabaseType::Xugu, Some(column_type)),
+ geometry
+ );
+ }
+ for column_type in ["GEOGRAPHY", "BOX2D", "BOX3D"] {
+ assert_eq!(
+ escape_value_typed(&json!(format!("0X{hex}")), &DatabaseType::Xugu, Some(column_type)),
+ format!("CAST({geometry} AS {column_type})")
+ );
+ assert_eq!(escape_value_typed(&json!(null), &DatabaseType::Xugu, Some(column_type)), "NULL");
+ }
+ for value in ["0x", "0x123", "0xZZ", "0x00');DROP TABLE T;--", "POINT(1 2)"] {
+ assert_eq!(format_xugu_typed_sql_literal(value, &DatabaseType::Xugu, Some("GEOMETRY")), None);
+ }
+ assert_eq!(
+ escape_value_typed(&json!("0x00');DROP TABLE T;--"), &DatabaseType::Xugu, Some("BOX3D")),
+ "'0x00'');DROP TABLE T;--'"
+ );
+ // No spatial SQL specialization leaks into another database or a
+ // non-spatial Xugu column containing the same text.
+ assert_eq!(format_xugu_typed_sql_literal(&format!("0x{hex}"), &DatabaseType::Postgres, Some("GEOMETRY")), None);
+ assert_eq!(escape_value_typed(&json!("0x00"), &DatabaseType::Xugu, Some("VARCHAR(10)")), "'0x00'");
+ }
+
+ #[test]
+ fn xugu_insert_uses_typed_literals_only_for_bit_interval_and_plain_time_values() {
+ assert_eq!(escape_value_typed(&json!("10101010"), &DatabaseType::Xugu, Some("BIT(8)")), "B'10101010'");
+ assert_eq!(escape_value_typed(&json!("101101"), &DatabaseType::Xugu, Some("VARBIT")), "B'101101'");
+ assert_eq!(escape_value_typed(&json!(""), &DatabaseType::Xugu, Some("BIT VARYING")), "B''");
+ assert_eq!(
+ escape_value_typed(&json!("5-7"), &DatabaseType::Xugu, Some("INTERVAL YEAR TO MONTH")),
+ "INTERVAL '5-7' YEAR TO MONTH"
+ );
+ assert_eq!(
+ escape_value_typed(&json!("2 3:04:05.123"), &DatabaseType::Xugu, Some("INTERVAL DAY(3) TO SECOND(6)")),
+ "INTERVAL '2 3:04:05.123' DAY(3) TO SECOND(6)"
+ );
+ assert_eq!(
+ escape_value_typed(&json!("17:30:29+08:00"), &DatabaseType::Xugu, Some("TIME WITH TIME ZONE")),
+ "'17:30:29+08:00'"
+ );
+ assert_eq!(
+ escape_value_typed(&json!("23:59:59.123"), &DatabaseType::Xugu, Some("TIME")),
+ "CAST('23:59:59.123' AS TIME)"
+ );
+ assert_eq!(
+ escape_value_typed(
+ &json!("2026-10-08 17:30:29+08:00"),
+ &DatabaseType::Xugu,
+ Some("DATETIME WITH TIME ZONE")
+ ),
+ "'2026-10-08 17:30:29+08:00'"
+ );
+ assert_eq!(
+ escape_value_typed(&json!("2026-10-08 17:30:29"), &DatabaseType::Xugu, Some("DATETIME")),
+ "'2026-10-08 17:30:29'"
+ );
+ // These SQL literal specializations are intentionally Xugu-only.
+ assert_eq!(escape_value_typed(&json!("10101010"), &DatabaseType::Postgres, Some("BIT(8)")), "'10101010'");
+ assert_eq!(escape_value_typed(&json!("23:59:59.123"), &DatabaseType::Postgres, Some("TIME")), "'23:59:59.123'");
+ }
+
+ #[test]
+ fn xugu_interval_cast_values_are_normalized_to_the_declared_qualifier() {
+ let cases = [
+ ("5-0", "INTERVAL YEAR", "INTERVAL '5' YEAR"),
+ ("5-7", "INTERVAL YEAR TO MONTH", "INTERVAL '5-7' YEAR TO MONTH"),
+ ("0-8", "INTERVAL MONTH", "INTERVAL '8' MONTH"),
+ ("12 0:00:00", "INTERVAL DAY", "INTERVAL '12' DAY"),
+ ("1 2:00:00", "INTERVAL DAY TO HOUR", "INTERVAL '1 2' DAY TO HOUR"),
+ ("1 2:03:00", "INTERVAL DAY TO MINUTE", "INTERVAL '1 2:03' DAY TO MINUTE"),
+ ("1 02:03:04.123000", "INTERVAL DAY TO SECOND", "INTERVAL '1 02:03:04.123000' DAY TO SECOND"),
+ ("50:00:00", "INTERVAL HOUR", "INTERVAL '50' HOUR"),
+ ("50:03:00", "INTERVAL HOUR TO MINUTE", "INTERVAL '50:03' HOUR TO MINUTE"),
+ ("50:03:04.123000", "INTERVAL HOUR TO SECOND", "INTERVAL '50:03:04.123000' HOUR TO SECOND"),
+ ("1:40:00", "INTERVAL MINUTE", "INTERVAL '100' MINUTE"),
+ ("1:40:03.123000", "INTERVAL MINUTE TO SECOND", "INTERVAL '100:03.123000' MINUTE TO SECOND"),
+ ("0:00:45.123000", "INTERVAL SECOND", "INTERVAL '45.123000' SECOND"),
+ ("-5-0", "INTERVAL YEAR", "INTERVAL '-5' YEAR"),
+ ("-2-8", "INTERVAL MONTH", "INTERVAL '-32' MONTH"),
+ ("+0-0", "INTERVAL MONTH", "INTERVAL '+0' MONTH"),
+ ("-50:03:00", "INTERVAL MINUTE", "INTERVAL '-3003' MINUTE"),
+ ("-1:40:03.123000", "INTERVAL MINUTE TO SECOND", "INTERVAL '-100:03.123000' MINUTE TO SECOND"),
+ ("50:03:04.123000", "INTERVAL SECOND(6)", "INTERVAL '180184.123000' SECOND(6)"),
+ ("5-7", "INTERVAL YEAR", "INTERVAL '5-7' YEAR"),
+ ("1:40:03", "INTERVAL MINUTE", "INTERVAL '1:40:03' MINUTE"),
+ ];
+
+ for (value, column_type, expected) in cases {
+ assert_eq!(
+ escape_value_typed(&json!(value), &DatabaseType::Xugu, Some(column_type)),
+ expected,
+ "{column_type}"
+ );
+ }
+ }
+
#[test]
fn dameng_transfer_ddl_preserves_plsql_blocks_and_single_statements() {
let script = "BEGIN\n\
@@ -18266,14 +19210,21 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
#[test]
fn xugu_insert_formats_prefixed_hex_for_binary_and_blob() {
let sql = generate_insert_typed(
- &[String::from("id"), String::from("binary_payload"), String::from("blob_payload"), String::from("note")],
+ &[
+ String::from("id"),
+ String::from("binary_payload"),
+ String::from("blob_payload"),
+ String::from("empty_blob"),
+ String::from("note"),
+ ],
&[
Some(String::from("integer")),
Some(String::from("BINARY")),
Some(String::from("BLOB")),
+ Some(String::from("BLOB")),
Some(String::from("varchar(64)")),
],
- &[vec![json!(1), json!("0x0001ABff"), json!("0X1020"), json!("0x0001ABff")]],
+ &[vec![json!(1), json!("0x0001ABff"), json!("0X1020"), json!("0x"), json!("0x0001ABff")]],
"files",
"AppSchema",
&DatabaseType::Xugu,
@@ -18282,8 +19233,8 @@ PARTITION p_old VALUES LESS THAN (TO_DAYS('2026-01-01')))";
assert_eq!(
sql,
- r#"INSERT INTO "AppSchema"."files" ("id", "binary_payload", "blob_payload", "note") VALUES
-(1, HEXTORAW('0001ABff'), HEXTORAW('1020'), '0x0001ABff')"#
+ r#"INSERT INTO "AppSchema"."files" ("id", "binary_payload", "blob_payload", "empty_blob", "note") VALUES
+(1, X'0001ABff', X'1020', X'', '0x0001ABff')"#
);
}
diff --git a/crates/dbx-core/src/data/transfer/ddl_plan.rs b/crates/dbx-core/src/data/transfer/ddl_plan.rs
index 8700cf96d6..36e7de51f5 100644
--- a/crates/dbx-core/src/data/transfer/ddl_plan.rs
+++ b/crates/dbx-core/src/data/transfer/ddl_plan.rs
@@ -8,6 +8,10 @@
use super::*;
+fn xugu_table_ddl_is_unavailable(sql: &str) -> bool {
+ sql.trim().is_empty() || sql.contains("XuguDB did not expose enough metadata to reconstruct")
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(super) struct PreparedTableDdl {
pub ddl: String,
@@ -147,9 +151,21 @@ pub(super) async fn prepare_table_ddl(
)
.await
{
+ Ok(ddl)
+ if matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu))
+ && xugu_table_ddl_is_unavailable(&ddl) =>
+ {
+ return Err(format!(
+ "Cannot transfer Xugu table '{table}': the source Agent could not return complete table DDL. \
+ Check metadata privileges and retry; generating a reduced table definition could lose identity, \
+ constraints, indexes, or partitioning."
+ ));
+ }
Ok(ddl) => (ddl, true),
Err(e)
- if rebuild || matches!((source_db_type, target_db_type), (DatabaseType::H2, DatabaseType::H2)) =>
+ if rebuild
+ || matches!((source_db_type, target_db_type), (DatabaseType::H2, DatabaseType::H2))
+ || matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu)) =>
{
// Rebuilds and H2-to-H2 transfers must not silently discard source
// constraints or generated columns when native DDL cannot be read.
@@ -463,4 +479,13 @@ mod tests {
assert!(result.is_err(), "incomplete source metadata must fail before any target DDL: {result:?}");
}
}
+
+ #[test]
+ fn xugu_native_ddl_placeholder_or_empty_text_is_not_treated_as_a_valid_table_definition() {
+ assert!(xugu_table_ddl_is_unavailable(" "));
+ assert!(xugu_table_ddl_is_unavailable(
+ "-- XuguDB did not expose enough metadata to reconstruct APP.T.\n-- grant access"
+ ));
+ assert!(!xugu_table_ddl_is_unavailable("CREATE TABLE \"APP\".\"T\" (\"ID\" INTEGER)"));
+ }
}
diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rs
index 3cb21f1d0a..152d2bd4ac 100644
--- a/crates/dbx-web/src/routes/transfer.rs
+++ b/crates/dbx-web/src/routes/transfer.rs
@@ -95,11 +95,13 @@ pub async fn start_transfer(
)));
}
+ 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)?;
+ transfer::validate_transfer_database_pair(&req, &source_db_type, &target_db_type).map_err(AppError::from)?;
+
// `drop_target_before_create` rebuilds target tables. Gate it before responding so the
// caller sees the error code rather than a progress stream that fails later.
if req.drop_target_before_create {
- let target_db_type =
- transfer::get_db_type(&state.app, &req.target_connection_id).await.map_err(AppError::from)?;
dbx_core::transfer_rebuild::ensure_drop_target_allowed(
&state.app,
&req.target_connection_id,
@@ -135,23 +137,6 @@ pub async fn start_transfer(
let state_clone = state.clone();
tokio::spawn(async move {
- let source_db_type = match transfer::get_db_type(&app, &req.source_connection_id).await {
- Ok(t) => t,
- Err(e) => {
- send_transfer_progress(&progress_channel, &terminal_transfer_error(&req, e));
- finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;
- return;
- }
- };
- let target_db_type = match transfer::get_db_type(&app, &req.target_connection_id).await {
- Ok(t) => t,
- Err(e) => {
- send_transfer_progress(&progress_channel, &terminal_transfer_error(&req, e));
- finish_transfer_channel(&state_clone, &req.transfer_id, &progress_channel).await;
- return;
- }
- };
-
// 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
@@ -660,6 +645,7 @@ pub async fn preview_transfer_ownership(
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)?;
+ transfer::validate_transfer_database_pair(&req, &source_db_type, &target_db_type).map_err(AppError::from)?;
let source_pool_key = transfer::ensure_transfer_pool(
&state.app,
&req.source_connection_id,
diff --git a/plugins/connection-types/xugu.yaml b/plugins/connection-types/xugu.yaml
index afbd16c46b..53e5021e4d 100644
--- a/plugins/connection-types/xugu.yaml
+++ b/plugins/connection-types/xugu.yaml
@@ -27,7 +27,7 @@ capabilities:
tableDataEdit: true
tableStructureEdit: true
tableImport: true
- dataTransfer: false
+ dataTransfer: true
sqlFileExecution: true
databaseCreate: false
fieldLineage: false
diff --git a/src-tauri/src/commands/transfer.rs b/src-tauri/src/commands/transfer.rs
index 3fa47bab80..df554786fd 100644
--- a/src-tauri/src/commands/transfer.rs
+++ b/src-tauri/src/commands/transfer.rs
@@ -39,6 +39,7 @@ pub async fn start_transfer(
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_request(&request)?;
+ dbx_core::transfer::validate_transfer_database_pair(&request, &source_db_type, &target_db_type)?;
// `drop_target_before_create` rebuilds target tables; gate the dialect and require an
// explicit confirmation for production databases.
@@ -587,6 +588,7 @@ pub async fn preview_transfer_ownership(
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_request(&request)?;
+ dbx_core::transfer::validate_transfer_database_pair(&request, &source_db_type, &target_db_type)?;
let source_pool_key = dbx_core::transfer::ensure_transfer_pool(
&state,
&request.source_connection_id,