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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(oracle): preserve column parameters and OceanBase table clones
efeireece909f2e1f4
diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.javaindex 7a8d6ba9af..38af2ddac4 100644--- a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java@@ -2075,6 +2075,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {yield len == null ? base : base + "(" + len + ")";}case "NUMBER" -> {+ if (numPrec == null && numScale != null) {+ yield base + "(*," + numScale + ")";+ }if (numPrec != null && numScale != null && numScale != 0) {yield base + "(" + numPrec + "," + numScale + ")";}@@ -2083,6 +2086,7 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}yield base;}+ case "FLOAT" -> numPrec != null && numPrec > 0 ? base + "(" + numPrec + ")" : base;case "RAW" -> dataLen == null ? "RAW" : "RAW(" + dataLen + ")";default -> base;};diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.javaindex 849bfb40be..382c9be49d 100644--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java@@ -1022,6 +1022,23 @@ class OceanBaseOracleAgentTest {Assertions.assertTrue(sql.get(0).contains("c.CHAR_USED"));}+ @Test+ void getColumnsPreservesFloatPrecisionAndNumberStarScale() {+ List<String> sql = new ArrayList<>();+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();+ TestSupport.setPrivateConnection(agent, preparedConnection(sql, columnResultSet(new Object[][]{+ {"F", "FLOAT", "Y", 63, null, 22, 0, null, null, 0, null},+ {"FU", "FLOAT", "Y", null, null, 22, 0, null, null, 0, null},+ {"NS", "NUMBER", "Y", null, 3, 22, 0, null, null, 0, null},+ {"NN", "NUMBER", "Y", null, -2, 22, 0, null, null, 0, null},+ {"NZ", "NUMBER", "Y", null, 0, 22, 0, null, null, 0, null},+ {"NU", "NUMBER", "Y", null, null, 22, 0, null, null, 0, null}+ })));+ List<ColumnInfo> columns = agent.getColumns("APP", "NUMERIC_COLUMNS");+ Assertions.assertEquals(List.of("FLOAT(63)", "FLOAT", "NUMBER(*,3)", "NUMBER(*,-2)", "NUMBER(*,0)", "NUMBER"),+ columns.stream().map(ColumnInfo::getData_type).toList());+ }+@Testvoid getColumnsResolvesTheCurrentSchemaWhenSchemaIsEmpty() {List<String> sql = new ArrayList<>();diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.goindex 4c126c75b2..d287429a06 100644--- a/agents/drivers/oracle-go/main.go+++ b/agents/drivers/oracle-go/main.go@@ -3644,6 +3644,9 @@ func oracleColumnTypeDDL(column columnInfo) string {return fmt.Sprintf("%s(%d)", dataType, *column.CharacterMaximumLength)}if dataType == "NUMBER" {+ if column.NumericPrecision == nil && column.NumericScale != nil {+ return fmt.Sprintf("NUMBER(*,%d)", *column.NumericScale)+ }if column.NumericPrecision != nil && *column.NumericPrecision > 0 {if column.NumericScale != nil && *column.NumericScale != 0 {return fmt.Sprintf("NUMBER(%d,%d)", *column.NumericPrecision, *column.NumericScale)@@ -3652,7 +3655,7 @@ func oracleColumnTypeDDL(column columnInfo) string {}return "NUMBER"}- if (dataType == "FLOAT" || dataType == "BINARY_FLOAT" || dataType == "BINARY_DOUBLE") &&+ if dataType == "FLOAT" &&column.NumericPrecision != nil && *column.NumericPrecision > 0 {return fmt.Sprintf("%s(%d)", dataType, *column.NumericPrecision)}diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.goindex 7b43abdb58..49e25321e9 100644--- a/agents/drivers/oracle-go/main_test.go+++ b/agents/drivers/oracle-go/main_test.go@@ -1311,6 +1311,7 @@ func TestOracleColumnTypeDDL(t *testing.T) {precision := 10scale := 2zeroScale := 0+ negativeScale := -2byteUnit := "B"charUnit := "C"@@ -1325,6 +1326,17 @@ func TestOracleColumnTypeDDL(t *testing.T) {{name: "national character type ignores unit", column: columnInfo{DataType: "NVARCHAR2", CharacterMaximumLength: &charLen, CharacterLengthUnit: &charUnit}, want: "NVARCHAR2(64)"},{name: "number scale", column: columnInfo{DataType: "NUMBER", NumericPrecision: &precision, NumericScale: &scale}, want: "NUMBER(10,2)"},{name: "number zero scale", column: columnInfo{DataType: "NUMBER", NumericPrecision: &precision, NumericScale: &zeroScale}, want: "NUMBER(10)"},+ {name: "number star scale", column: columnInfo{DataType: "NUMBER", NumericScale: &scale}, want: "NUMBER(*,2)"},+ {name: "number star negative scale", column: columnInfo{DataType: "NUMBER", NumericScale: &negativeScale}, want: "NUMBER(*,-2)"},+ {name: "number star zero scale", column: columnInfo{DataType: "NUMBER", NumericScale: &zeroScale}, want: "NUMBER(*,0)"},+ {name: "number unknown", column: columnInfo{DataType: "NUMBER"}, want: "NUMBER"},+ {name: "number negative scale", column: columnInfo{DataType: "NUMBER", NumericPrecision: &precision, NumericScale: &negativeScale}, want: "NUMBER(10,-2)"},+ {name: "explicit number parameters", column: columnInfo{DataType: "NUMBER(12,-2)", NumericPrecision: &precision, NumericScale: &scale}, want: "NUMBER(12,-2)"},+ {name: "explicit float parameters", column: columnInfo{DataType: "FLOAT(63)", NumericPrecision: &precision}, want: "FLOAT(63)"},+ {name: "float precision", column: columnInfo{DataType: "FLOAT", NumericPrecision: &precision}, want: "FLOAT(10)"},+ {name: "float unknown", column: columnInfo{DataType: "FLOAT"}, want: "FLOAT"},+ {name: "binary float fixed precision", column: columnInfo{DataType: "BINARY_FLOAT", NumericPrecision: &precision}, want: "BINARY_FLOAT"},+ {name: "binary double fixed precision", column: columnInfo{DataType: "BINARY_DOUBLE", NumericPrecision: &precision}, want: "BINARY_DOUBLE"},{name: "timestamp preserves precision", column: columnInfo{DataType: "TIMESTAMP(6)"}, want: "TIMESTAMP(6)"},}for _, tt := range tests {diff --git a/apps/desktop/src/components/editor/DangerConfirmDialog.vue b/apps/desktop/src/components/editor/DangerConfirmDialog.vueindex 7870c3f98a..03cb544cbb 100644--- a/apps/desktop/src/components/editor/DangerConfirmDialog.vue+++ b/apps/desktop/src/components/editor/DangerConfirmDialog.vue@@ -32,6 +32,8 @@ const props = withDefaults(message?: string;details?: string;detailsText?: string;+ detailsLabel?: string;+ showCancel?: boolean;confirmLabel?: string;showSuppressToggle?: boolean;suppressToggleLabel?: string;@@ -56,6 +58,8 @@ const props = withDefaults(message: "",details: "",detailsText: "",+ detailsLabel: "",+ showCancel: true,confirmLabel: "",showSuppressToggle: false,suppressToggleLabel: "",@@ -139,7 +143,8 @@ async function copyFullCode() {<p class="text-sm text-muted-foreground mb-3">{{ message || t("dangerDialog.message") }}</p><p v-if="detailsText" class="text-xs text-muted-foreground mb-3 whitespace-pre-line max-h-40 overflow-auto">{{ detailsText }}</p><slot name="options" />- <div v-if="code" data-testid="danger-code-container" class="min-w-0">+ <component :is="detailsLabel ? 'details' : 'div'" v-if="code" data-testid="danger-code-container" class="min-w-0">+ <summary v-if="detailsLabel" class="mb-2 cursor-pointer text-sm text-muted-foreground">{{ detailsLabel }}</summary><div data-testid="danger-code-actions" class="mb-1 flex items-center justify-end gap-0.5"><Button variant="ghost" size="icon-xs" class="h-6 w-6 text-muted-foreground" :title="t('dangerDialog.copyFullText')" @click="copyFullCode"><Check v-if="copied" class="h-3.5 w-3.5 text-emerald-600" />@@ -156,7 +161,7 @@ async function copyFullCode() {</div><pre v-if="preview.tail" class="font-inherit" :class="wrap ? 'w-full whitespace-pre-wrap break-all' : 'w-max min-w-full whitespace-pre'" v-html="highlightedTail" /></div>- </div>+ </component><div v-if="showSuppressToggle" class="mt-3 flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"><Label for="danger-confirm-suppress" class="text-sm leading-5">{{ suppressToggleLabel || t("dangerDialog.suppressFuturePrompts") }}</Label><Switch id="danger-confirm-suppress" v-model="suppressFuturePrompts" />@@ -168,7 +173,7 @@ async function copyFullCode() {<Loader2 v-if="cancelRunningLoading" class="h-3.5 w-3.5 animate-spin" />{{ t("dangerDialog.cancelRunning") }}</Button>- <Button v-else ref="cancelButtonRef" variant="outline" :disabled="loading" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>+ <Button v-else-if="showCancel" ref="cancelButtonRef" variant="outline" :disabled="loading" @click="open = false">{{ t("dangerDialog.cancel") }}</Button><Button ref="confirmButtonRef" variant="destructive" class="gap-1.5" :disabled="loading || confirmDisabled" @click="onConfirm"><Loader2 v-if="loading" class="h-3.5 w-3.5 animate-spin" />{{ confirmLabel || t("dangerDialog.confirm") }}diff --git a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.tsindex 9f2066a2ad..a54762d51b 100644--- a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts@@ -66,6 +66,30 @@ afterEach(() => {});describe("DangerConfirmDialog SQL preview", () => {+ it("starts optional details collapsed and keeps the complete SQL available to copy", async () => {+ const sql = "CREATE TABLE target (id NUMBER);";+ await mountDialog(sql, { detailsLabel: "View SQL" });+ const details = document.body.querySelector<HTMLDetailsElement>("details[data-testid='danger-code-container']");+ expect(details).not.toBeNull();+ expect(details!.open).toBe(false);+ expect(details!.querySelector("summary")?.textContent).toBe("View SQL");+ details!.open = true;+ details!.querySelector<HTMLButtonElement>('button[title="Copy full text"]')!.click();+ await nextTick();+ expect(copyToClipboard).toHaveBeenCalledWith(sql);+ });++ it("lets a result caller hide Cancel and settle confirmation before closing", async () => {+ const confirmed = vi.fn();+ await mountDialog("CREATE TABLE target (id NUMBER);", { showCancel: false, closeOnConfirm: false, confirmLabel: "Close result" }, { onConfirm: confirmed });+ const buttons = Array.from(document.body.querySelectorAll("button"));+ expect(buttons.some((button) => button.textContent?.trim() === "Cancel")).toBe(false);+ buttons.find((button) => button.textContent?.trim() === "Close result")!.click();+ await nextTick();+ expect(confirmed).toHaveBeenCalledOnce();+ expect(document.body.querySelector('[role="dialog"]')).not.toBeNull();+ });+it("wraps SQL by default, including long unbroken identifiers", async () => {await mountDialog(`UPDATE ${"very_long_identifier_".repeat(20)} SET value = 1;`);diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex a7d50d4bf5..fde85ffc20 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -99,6 +99,9 @@ import {supportsTruncateTableCascade,type TableAdminSqlOptions,} from "@/lib/database/dbAdminSql";+import type { DuplicateTableStructurePlan } from "@/lib/database/dbAdminSql";+import { executeOceanbaseTableClone, executeOceanbaseTableCloneData, oceanbaseCloneDataPreparationError, OceanbaseTableCloneError, type OceanbaseTableClone } from "@/lib/database/oceanbaseTableClone";+import { useOceanbaseCloneDialog } from "@/composables/useOceanbaseCloneDialog";import { useToast } from "@/composables/useToast";import { buildExecutableObjectSourceStatements, buildRoutineRenameObjectSourceStatements, executeObjectSourceSave, formatObjectSourceSaveError, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";import { buildRenameObjectSql, supportsObjectRename } from "@/lib/table/objectRenameSql";@@ -216,6 +219,8 @@ const emit = defineEmits<{}>();const { t } = useI18n();+const cloneDialog = useOceanbaseCloneDialog(t);+const { state: cloneDialogState, open: cloneDialogOpen } = cloneDialog;const { toast } = useToast();const { highlight } = useSqlHighlighter();const connectionStore = useConnectionStore();@@ -2673,39 +2678,77 @@ function requestDuplicateStructure(row: ObjectBrowserRow) {showDuplicateDialog.value = true;}-async function buildDuplicateStructurePlan(sourceName: string, targetName: string, schema: string | undefined, tableComment?: string | null, sourceColumns?: ColumnInfo[]) {- return buildSharedDuplicateTableStructurePlan({- connectionId: props.connection.id,+function captureTableCopyContext() {+ return {+ connection: { ...props.connection },database: props.database,catalog: props.catalog,+ schema: selectedSchema.value,databaseType: effectiveDatabaseType.value,+ identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connection.id),+ };+}++type TableCopyContext = ReturnType<typeof captureTableCopyContext>;++function reloadTableCopyContext(context: TableCopyContext) {+ if (props.connection.id === context.connection.id && props.database === context.database && props.catalog === context.catalog && selectedSchema.value === context.schema) return reload();+ return Promise.resolve();+}++async function buildDuplicateStructurePlan(context: TableCopyContext, sourceName: string, targetName: string, schema: string | undefined, tableComment?: string | null, sourceColumns?: ColumnInfo[]) {+ return buildSharedDuplicateTableStructurePlan({+ connectionId: context.connection.id,+ database: context.database,+ catalog: context.catalog,+ databaseType: context.databaseType,schema,sourceName,targetName,tableComment,sourceColumns,- identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connection.id),+ identifierQuote: context.identifierQuote,});}-function executeDuplicateStructurePlan(plan: { sql: string; executeAsScript: boolean }, schema: string | undefined) {- return plan.executeAsScript ? api.executeScript(props.connection.id, props.database, plan.sql, schema) : api.executeQuery(props.connection.id, props.database, plan.sql, schema);+function executeDuplicateStructurePlan(context: TableCopyContext, plan: DuplicateTableStructurePlan, schema: string | undefined) {+ if (plan.oceanbaseClone) return executeOceanbaseTableClone(plan.oceanbaseClone, (sql) => api.executeQuery(context.connection.id, context.database, sql, plan.oceanbaseClone!.targetSchema));+ return plan.executeAsScript ? api.executeScript(context.connection.id, context.database, plan.sql, schema) : api.executeQuery(context.connection.id, context.database, plan.sql, schema);}async function confirmDuplicateStructure() {+ return effectiveDatabaseType.value === "oceanbase-oracle" ? cloneDialog.run(confirmDuplicateStructureImpl) : confirmDuplicateStructureImpl();+}++async function confirmDuplicateStructureImpl() {const row = duplicateTarget.value;const newName = duplicateTableName.value.trim();if (!row || !newName) return;+ const context = captureTableCopyContext();showDuplicateDialog.value = false;try {- const schema = row.schema || selectedSchema.value;- const plan = await buildDuplicateStructurePlan(row.name, newName, schema, row.comment);- const executed = await executeObjectBrowserSqlWithProductionGuard(plan.sql, () => executeDuplicateStructurePlan(plan, schema));+ const schema = row.schema || context.schema;+ const plan = await buildDuplicateStructurePlan(context, row.name, newName, schema, row.comment);+ if (!(await cloneDialog.request([{ plan, scope: [context.connection.id, context.database, context.catalog || ""] }]))) return;+ const executed = await executeObjectBrowserSqlWithProductionGuard(plan.sql, () => executeDuplicateStructurePlan(context, plan, schema), context);if (!executed) return;toast(t("contextMenu.duplicateStructureSuccess", { name: newName }));- await reload();- await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, schema);+ await reloadTableCopyContext(context);+ await connectionStore.refreshObjectListTreeNode(context.connection.id, context.database, schema);} catch (e: any) {+ if (e instanceof OceanbaseTableCloneError) {+ const refreshed = await Promise.allSettled([reloadTableCopyContext(context), connectionStore.refreshObjectListTreeNode(context.connection.id, context.database, e.targetSchema)]);+ cloneDialog.showFailure(+ e,+ [],+ refreshed.flatMap((result) => (result.status === "rejected" ? [result.reason] : [])),+ );+ return;+ }+ if (context.databaseType === "oceanbase-oracle") {+ cloneDialog.showFailure(e);+ return;+ }toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);}}@@ -2863,8 +2906,13 @@ function onObjectBrowserKeydown(event: KeyboardEvent) {}async function confirmPasteTable() {- const entries = pasteTableEntries.value.filter((entry) => entry.targetName.trim());+ return effectiveDatabaseType.value === "oceanbase-oracle" ? cloneDialog.run(confirmPasteTableImpl) : confirmPasteTableImpl();+}++async function confirmPasteTableImpl() {+ const entries = pasteTableEntries.value.filter((entry) => entry.targetName.trim()).map((entry) => ({ ...entry }));if (entries.length === 0) return;+ const context = captureTableCopyContext();const clipboardAtPasteStart = connectionStore.treeClipboard;const mode = pasteTableMode.value;const copyData = pasteTableModeCopiesData(mode) && pasteTableDataCopySupported.value;@@ -2874,37 +2922,60 @@ async function confirmPasteTable() {let firstPasteError: unknown;let pasteCancelled = false;let hasMutatedTable = false;+ const preparedClones = new Map<(typeof entries)[number], DuplicateTableStructurePlan>();+ if (context.databaseType === "oceanbase-oracle" && mode !== "data-only") {+ try {+ for (const entry of entries) preparedClones.set(entry, await buildDuplicateStructurePlan(context, entry.sourceName, entry.targetName.trim(), entry.schema || context.schema, entry.tableComment));+ if (!(await cloneDialog.request([...preparedClones.values()].map((plan) => ({ plan, scope: [context.connection.id, context.database, context.catalog || ""] }))))) return;+ } catch (error) {+ cloneDialog.showFailure(+ error,+ entries.map((entry) => `${entry.schema || context.schema || ""}.${entry.targetName}`),+ );+ return;+ }+ }+ let cloneFailure: { error: unknown; remaining: string[]; refreshErrors: unknown[] } | undefined;+ const completedCloneTargets: string[] = [];for (const entry of entries) {- const targetName = entry.targetName.trim();- const schema = entry.schema || selectedSchema.value;+ let targetName = entry.targetName.trim();+ let schema = entry.schema || context.schema;+ let completedClone: OceanbaseTableClone | undefined;try {let sourceColumns: ColumnInfo[] | undefined;if (mode === "structure-and-data" || mode === "structure-only") {- const plan = await buildDuplicateStructurePlan(entry.sourceName, targetName, schema, entry.tableComment, sourceColumns);+ const plan = preparedClones.get(entry) || (await buildDuplicateStructurePlan(context, entry.sourceName, targetName, schema, entry.tableComment, sourceColumns));sourceColumns = plan.sourceColumns;- const executed = await executeObjectBrowserSqlWithProductionGuard(plan.sql, () => executeDuplicateStructurePlan(plan, schema));+ if (plan.oceanbaseClone) {+ targetName = plan.oceanbaseClone.targetName;+ schema = plan.oceanbaseClone.targetSchema;+ }+ const executed = await executeObjectBrowserSqlWithProductionGuard(plan.sql, () => executeDuplicateStructurePlan(context, plan, schema), context);if (!executed) {pasteCancelled = true;break;}hasMutatedTable = true;+ completedClone = plan.oceanbaseClone;}if (copyData) {- sourceColumns ??= await api.getColumns(props.connection.id, props.database, schema || "", entry.sourceName, props.catalog);- const dataCopyColumnOptions = tableDataCopyColumnOptions(effectiveDatabaseType.value, sourceColumns);+ sourceColumns ??= await api.getColumns(context.connection.id, context.database, schema || "", entry.sourceName, context.catalog);+ const dataCopyColumnOptions = tableDataCopyColumnOptions(context.databaseType, sourceColumns);if (dataCopyColumnOptions.columns.length === 0) {throw new Error("No writable columns available for table data copy.");}const dataSql = await buildCopyTableDataSql({- databaseType: effectiveDatabaseType.value,+ databaseType: context.databaseType,schema,sourceName: entry.sourceName,targetName,- normalizeNewTargetName: mode === "structure-and-data",- identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connection.id),+ normalizeNewTargetName: mode === "structure-and-data" && context.databaseType !== "oceanbase-oracle",+ identifierQuote: context.identifierQuote,...dataCopyColumnOptions,});- const executed = await executeObjectBrowserSqlWithProductionGuard(dataSql, () => api.executeQuery(props.connection.id, props.database, dataSql, schema, undefined, { timeoutSecs: 0 }));+ const clone = preparedClones.get(entry)?.oceanbaseClone;+ const execute = (sql: string) => api.executeQuery(context.connection.id, context.database, sql, schema, undefined, { timeoutSecs: 0 });+ const executed = await executeObjectBrowserSqlWithProductionGuard(dataSql, () => (clone ? executeOceanbaseTableCloneData(clone, dataSql, execute) : execute(dataSql)), context);if (!executed) {pasteCancelled = true;break;@@ -2912,17 +2983,35 @@ async function confirmPasteTable() {hasMutatedTable = true;}successCount++;+ if (preparedClones.has(entry)) completedCloneTargets.push(`${schema}.${targetName}`);} catch (e: any) {+ if (context.databaseType === "oceanbase-oracle" && preparedClones.size) {+ if (completedClone && !(e instanceof OceanbaseTableCloneError)) e = oceanbaseCloneDataPreparationError(completedClone, e);+ const refreshed = await Promise.allSettled([reloadTableCopyContext(context), connectionStore.refreshObjectListTreeNode(context.connection.id, context.database, schema)]);+ cloneFailure = {+ error: e,+ remaining: entries.slice(entries.indexOf(entry) + 1).map((pending) => {+ const clone = preparedClones.get(pending)!.oceanbaseClone!;+ return `${clone.targetSchema}.${clone.targetName}`;+ }),+ refreshErrors: refreshed.flatMap((result) => (result.status === "rejected" ? [result.reason] : [])),+ };+ break;+ }pasteFailCount++;firstPasteError ??= e;console.error(`Failed to paste table "${entry.sourceName}" -> "${targetName}":`, e);}}+ if (cloneFailure) {+ cloneDialog.showFailure(cloneFailure.error, cloneFailure.remaining, cloneFailure.refreshErrors, completedCloneTargets);+ return;+ }if (pasteCancelled) {if (hasMutatedTable) {try {- await reload();- await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value);+ await reloadTableCopyContext(context);+ await connectionStore.refreshObjectListTreeNode(context.connection.id, context.database, context.schema);toast(t("contextMenu.pasteTableCancelledAfterPartial"), 5000);} catch (e: any) {toast(t("contextMenu.pasteTableRefreshFailed", { message: translateBackendError(t, e) }), 5000);@@ -2939,8 +3028,8 @@ async function confirmPasteTable() {} else {toast(`${t("contextMenu.batchPastePartialFail", { success: pasteFeedback.successCount, failed: pasteFeedback.failedCount })}\n${t("contextMenu.tableOperationFailed", { message: translateBackendError(t, pasteFeedback.firstError) })}`, 5000);}- await reload();- await connectionStore.refreshObjectListTreeNode(props.connection.id, props.database, selectedSchema.value);+ await reloadTableCopyContext(context);+ await connectionStore.refreshObjectListTreeNode(context.connection.id, context.database, context.schema);}function tableAdminSqlOptions(row: ObjectBrowserRow, options?: { cascade?: boolean }): TableAdminSqlOptions {@@ -2960,10 +3049,10 @@ function tableAdminSqlOptions(row: ObjectBrowserRow, options?: { cascade?: boole* assessed before the callback runs so generated DDL cannot bypass protection* via executable comments, EXPLAIN ANALYZE, or qualified production targets.*/-async function executeObjectBrowserSqlWithProductionGuard<T>(sql: string, execute: () => Promise<T>): Promise<T | undefined> {+async function executeObjectBrowserSqlWithProductionGuard<T>(sql: string, execute: () => Promise<T>, context: Pick<TableCopyContext, "connection" | "database"> = props): Promise<T | undefined> {return executeWithProductionSqlGuard({- connection: props.connection,- database: props.database,+ connection: context.connection,+ database: context.database,sql,source: t("production.sourceObjectBrowser"),execute,@@ -3995,6 +4084,18 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {</script><template>+ <DangerConfirmDialog+ v-model:open="cloneDialogOpen"+ :title="t(cloneDialogState?.failure ? 'oceanbaseCloneDialog.failed' : 'oceanbaseCloneDialog.title')"+ :message="t(cloneDialogState?.failure ? 'oceanbaseCloneDialog.failedMessage' : 'oceanbaseCloneDialog.message')"+ :details-text="cloneDialogState?.summary"+ :details="cloneDialogState?.details"+ :details-label="t('oceanbaseCloneDialog.details')"+ :show-cancel="!cloneDialogState?.failure"+ :confirm-label="cloneDialogState?.failure ? t('oceanbaseCloneDialog.close') : undefined"+ :close-on-confirm="false"+ @confirm="cloneDialog.confirm"+ /><FirebirdObjectManager v-if="effectiveDatabaseType === 'firebird'" v-model:open="firebirdManagerOpen" :connection-id="connection.id" :database="database" /><div ref="rootRef" data-object-browser-root class="flex h-full min-h-0 min-w-0 flex-col bg-background outline-none" tabindex="0" @keydown="onObjectBrowserKeydown"><SidebarMenuPreferencesDialog v-if="sidebarMenuPreferences" v-model:open="sidebarMenuPreferencesOpen" :scope="sidebarMenuPreferences.scope" :items="sidebarMenuPreferences.items" />diff --git a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.tsnew file mode 100644index 0000000000..3d2cfd3544--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts@@ -0,0 +1,496 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, ref, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import i18n, { loadLocaleMessages } from "@/i18n";+import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";+import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";+import type { ConnectionConfig, TreeNode } from "@/types/database";+import * as api from "@/lib/backend/api";++const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), buildCreateTableSql: vi.fn(), buildCopyTableDataSql: vi.fn() }));+vi.mock("@/lib/backend/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),+ ...backend,+ listPlugins: vi.fn().mockResolvedValue([]),+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),+ loadSchemaCache: vi.fn().mockResolvedValue(null),+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),+ listSchemas: vi.fn().mockResolvedValue(["APP"]),+ listDatabases: vi.fn().mockResolvedValue(["APP"]),+ listObjects: vi.fn().mockResolvedValue([{ name: "SOURCE", object_type: "TABLE", schema: "APP" }]),+ listObjectStatistics: vi.fn().mockResolvedValue([]),+ getColumns: vi.fn().mockResolvedValue([{ name: "ID", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null }]),+ listConstraints: vi.fn().mockResolvedValue([]),+ listIndexes: vi.fn().mockResolvedValue([]),+ listTriggers: vi.fn().mockResolvedValue([]),+}));++const result = (rows: unknown[][] = []) => ({ columns: [], rows, affected_rows: 0, execution_time_ms: 0 });+const connection = { id: "ob-entry", name: "OB", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", host: "test", port: 2881, username: "APP", database: "APP" } as ConnectionConfig;+const source: TreeNode = { id: "ob-entry:APP:APP:table:SOURCE", type: "table", label: "SOURCE", connectionId: connection.id, database: "APP", schema: "APP" };+const mounted: App[] = [];+const auxiliaryRequests = new Set<string>();+const ddlCalls = () => backend.executeQuery.mock.calls.filter((call) => !String(call[2]).startsWith("SELECT "));++beforeEach(() => {+ vi.clearAllMocks();+ i18n.global.locale.value = "en";+ vi.mocked(api.listIndexes).mockResolvedValue([]);+ connection.is_production = false;+ invalidateObjectBrowserRowsCache({});+ vi.stubGlobal("confirm", vi.fn().mockReturnValue(true));+ vi.stubGlobal("alert", vi.fn());+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ auxiliaryRequests.add(String(input));+ throw new Error(`Unexpected HTTP request: ${input}`);+ }),+ );+ backend.buildCreateTableSql.mockImplementation(async ({ schema, tableName }) => ({ statements: [`CREATE TABLE "${schema}"."${tableName}" ("ID" NUMBER);`], warnings: [] }));+ backend.buildCopyTableDataSql.mockResolvedValue('INSERT INTO "APP"."MixedCopy" SELECT * FROM "APP"."SOURCE"');+ backend.executeQuery.mockImplementation(async (_id, _db, sql: string) => {+ if (sql.includes("ALL_TAB_COMMENTS")) return result([["source comment"]]);+ if (sql.includes("ALL_TABLES")) return result([["NO", "N"]]);+ return result();+ });+});++afterAll(() => expect([...auxiliaryRequests]).toEqual([]));++afterEach(() => {+ for (const app of mounted.splice(0)) app.unmount();+ document.body.innerHTML = "";+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ invalidateObjectBrowserRowsCache({});+});++async function mountEntry(surface: "sidebar" | "objects") {+ const pinia = createPinia();+ setActivePinia(pinia);+ const store = useConnectionStore();+ store.connections = [{ ...connection }];+ store.connectedIds.add(connection.id);+ store.treeNodes = [{ id: `${connection.id}:APP:APP`, type: "schema", label: "APP", connectionId: connection.id, database: "APP", schema: "APP", children: [], isExpanded: false }];+ const refresh = vi.spyOn(store, "refreshObjectListTreeNode");+ const component = ref<any>(null);+ const context = ref({ connection, database: "APP", schema: "APP" });+ let controller: any;+ const app = createApp({+ setup: () => () =>+ surface === "sidebar"+ ? h(SidebarTreeRuntimeHost, {+ ref: component,+ node: source,+ depth: 0,+ onOpenDialogController: (value: unknown) => {+ controller = value;+ },+ })+ : h(ObjectBrowser, { ref: component, ...context.value }),+ });+ app.use(pinia);+ app.use(i18n);+ const container = document.createElement("div");+ document.body.append(container);+ mounted.push(app);+ app.mount(container);+ await nextTick();+ if (surface === "sidebar") component.value.buildContextMenu(source);+ else controller = component.value.$.setupState;+ await nextTick();+ expect(controller).toBeDefined();+ controller.duplicateTableName = '"MixedCopy"';+ if (surface === "objects") controller.duplicateTarget = { name: "SOURCE", schema: "APP", object_type: "TABLE" };+ controller.pasteTableEntries = [{ sourceName: "SOURCE", targetName: '"MixedCopy"', connectionId: connection.id, database: "APP", schema: "APP" }];+ controller.pasteTableMode = "structure-and-data";+ return { controller, refresh, context, app };+}++async function acceptClone() {+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).not.toBeNull());+ const button = Array.from(document.querySelector('[role="dialog"]')!.querySelectorAll("button")).find((item) => item.textContent?.trim() === i18n.global.t("dangerDialog.confirm"));+ expect(button).toBeDefined();+ button!.click();+ await nextTick();+}++describe.each(["sidebar", "objects"] as const)("%s OceanBase clone entry points", (surface) => {+ it("keeps the captured Spanner identifier quote while data-copy metadata is pending", async () => {+ const { controller, context } = await mountEntry(surface);+ const store = useConnectionStore();+ const spanner = { ...connection, db_type: "spanner", driver_profile: "spanner", password: "fixture-only" } as ConnectionConfig;+ store.connections = [spanner];+ context.value = { connection: spanner, database: "APP", schema: "APP" };+ await nextTick();+ controller.pasteTableMode = "data-only";+ vi.spyOn(api, "connectDb").mockResolvedValue(connection.id);+ vi.spyOn(api, "connectionDatabaseInfo").mockResolvedValue(null);+ const quote = vi.spyOn(api, "connectionIdentifierQuote").mockResolvedValue('"');+ await store.connect(spanner);+ expect(store.connectionIdentifierQuote(connection.id)).toBe('"');+ let release!: () => void;+ const paused = new Promise<void>((resolve) => {+ release = resolve;+ });+ vi.mocked(api.getColumns).mockImplementationOnce(async () => {+ await paused;+ return [{ name: "ID", data_type: "NUMBER", is_nullable: true, is_primary_key: false, column_default: null }];+ });+ const pending = controller.confirmPasteTable();+ await vi.waitFor(() => expect(api.getColumns).toHaveBeenCalled());+ quote.mockResolvedValue("`");+ await store.connect(spanner);+ expect(store.connectionIdentifierQuote(connection.id)).toBe("`");+ release();+ await pending;+ expect(backend.buildCopyTableDataSql).toHaveBeenCalledWith(expect.objectContaining({ identifierQuote: '"' }));+ });++ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("does not replace the pending confirmation when a repeated %s would fail planning", async (action) => {+ const { controller } = await mountEntry(surface);+ const pending = controller[action]();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Confirm table copy"));+ backend.buildCreateTableSql.mockRejectedValue(new Error("second planning failed"));+ await controller[action]();+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Confirm table copy");+ expect(document.querySelector('[role="dialog"]')?.textContent).not.toContain("second planning failed");+ await acceptClone();+ await pending;+ expect(ddlCalls().filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);+ });++ it("retains committed structure and unexecuted data when the data SQL builder fails", async () => {+ const { controller } = await mountEntry(surface);+ backend.buildCopyTableDataSql.mockRejectedValueOnce(new Error("data builder unavailable"));+ const pending = controller.confirmPasteTable();+ await acceptClone();+ await pending;+ const dialog = document.querySelector('[role="dialog"]')?.textContent;+ expect(dialog).toContain("data builder unavailable");+ expect(dialog).toContain('Completed and committed: Table "APP"."MixedCopy"');+ expect(dialog).toContain('Not executed: Data "APP"."MixedCopy"');+ expect(ddlCalls().some((call) => String(call[2]).startsWith("INSERT"))).toBe(false);+ });++ it("localizes clone validation errors without losing quoted object names", async () => {+ await loadLocaleMessages("zh-CN");+ i18n.global.locale.value = "zh-CN";+ const { controller } = await mountEntry(surface);+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => (String(args[2]).includes("VIRTUAL_COLUMN") ? result([['Computed"Value']]) : read(...args)));+ await controller.confirmPasteTable();+ const dialog = document.querySelector('[role="dialog"]')?.textContent;+ expect(dialog).toContain('不支持克隆虚拟列:"Computed""Value"。未执行 DDL。');+ expect(dialog).not.toContain("virtualColumns");+ expect(ddlCalls()).toEqual([]);+ });++ it("renders the scope and failure ledger in the selected Chinese locale", async () => {+ await loadLocaleMessages("zh-CN");+ i18n.global.locale.value = "zh-CN";+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => (String(args[2]).startsWith("COMMENT ") ? { ...result(), execution_error: true, error: { detail: "ORA-01031" } } : read(...args)));+ const pending = controller.confirmPasteTable();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')?.textContent).toContain("确认复制表"));+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("不复制");+ await acceptClone();+ await pending;+ const dialog = document.querySelector('[role="dialog"]')?.textContent;+ expect(dialog).toContain("复制表已停止");+ expect(dialog).toContain("已完成并提交");+ expect(dialog).toContain("数据库已拒绝");+ expect(dialog).not.toContain("oceanbaseCloneDialog.");+ });++ it("confirms the whole batch once with collapsed SQL before any writes", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0], targetName: '"OtherCopy"' });+ const pending = controller.confirmPasteTable();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')?.textContent).toContain("OtherCopy"));+ expect(ddlCalls()).toEqual([]);+ const details = document.querySelector<HTMLDetailsElement>("details[data-testid='danger-code-container']");+ expect(details).not.toBeNull();+ expect(details!.open).toBe(false);+ await acceptClone();+ await pending;+ expect(ddlCalls().filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(2);+ expect(window.confirm).not.toHaveBeenCalled();+ });++ it("keeps the original confirmation when the same action is requested again", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ const pending = controller.confirmPasteTable();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).not.toBeNull());+ await controller.confirmPasteTable();+ expect(ddlCalls()).toEqual([]);+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ await acceptClone();+ await pending;+ expect(ddlCalls().filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);+ });++ it("does not execute an earlier planned target if a later target cannot be planned", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0], targetName: '"OtherCopy"' });+ backend.buildCreateTableSql.mockImplementationOnce(async ({ schema, tableName }) => ({ statements: [`CREATE TABLE "${schema}"."${tableName}" ("ID" NUMBER);`], warnings: [] })).mockRejectedValueOnce(new Error("metadata unavailable"));+ await controller.confirmPasteTable();+ expect(ddlCalls()).toEqual([]);+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("metadata unavailable");+ });++ it("rejects duplicate resolved batch targets without any writes", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0] });+ await controller.confirmPasteTable();+ expect(ddlCalls()).toEqual([]);+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Multiple copies target");+ expect(window.alert).not.toHaveBeenCalled();+ });++ it("keeps per-target production protection after the single batch scope confirmation", async () => {+ connection.is_production = true;+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0], targetName: '"OtherCopy"' });+ const pending = controller.confirmPasteTable();+ await acceptClone();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending?.sql).toContain('CREATE TABLE "APP"."MixedCopy"'));+ expect(ddlCalls()).toEqual([]);+ safety.confirm();+ await vi.waitFor(() => expect(safety.pending?.sql).toContain('CREATE TABLE "APP"."OtherCopy"'));+ expect(ddlCalls().filter((call) => String(call[2]).startsWith("CREATE TABLE"))).toHaveLength(1);+ safety.cancel();+ await pending;+ expect(ddlCalls().some((call) => String(call[2]).includes("OtherCopy"))).toBe(false);+ expect(window.confirm).not.toHaveBeenCalled();+ });++ it("keeps the database failure and ledger when the subsequent refresh also fails", async () => {+ const { controller, refresh } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ refresh.mockRejectedValue(new Error("refresh unavailable"));+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => (String(args[2]).startsWith("COMMENT ") ? { ...result(), execution_error: true, error: { detail: "ORA-01031" } } : read(...args)));+ const pending = controller.confirmPasteTable();+ await acceptClone();+ await pending;+ const dialog = document.querySelector('[role="dialog"]')?.textContent;+ expect(dialog).toContain("ORA-01031");+ expect(dialog).toContain("Completed and committed");+ expect(dialog).toContain("Refresh also failed");+ expect(dialog).toContain("refresh unavailable");+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ });++ it("rejects index-name collisions between distinct batch targets before writing", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries[0].targetName = `${"A".repeat(25)}ONE`;+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0], targetName: `${"A".repeat(25)}TWO` });+ vi.spyOn(api, "listIndexes").mockResolvedValue([{ name: "IX_SOURCE", columns: ["ID"], is_unique: false, is_primary: false, index_type: "NORMAL" }]);+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => {+ const sql = String(args[2]);+ if (sql.includes("ALL_IND_COLUMNS")) return result([["IX_SOURCE", "ID", 1, "ASC"]]);+ if (sql.includes("ALL_INDEXES")) return result([["IX_SOURCE", "VISIBLE"]]);+ return read(...args);+ });+ await controller.confirmPasteTable();+ expect(ddlCalls()).toEqual([]);+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("same index");+ });++ it("stops the batch on its first failure and lists the remaining target once", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0], targetName: '"OtherCopy"' });+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => (String(args[2]).startsWith("COMMENT ") ? { ...result(), execution_error: true, error: { detail: "ORA-01031" } } : read(...args)));+ const pending = controller.confirmPasteTable();+ await acceptClone();+ await pending;+ expect(ddlCalls()).toHaveLength(2);+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("OtherCopy");+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain("Not executed");+ expect(window.alert).not.toHaveBeenCalled();+ });++ it.each(["rejected", "unknown"])("retains committed structure when data copy is %s", async (outcome) => {+ const { controller } = await mountEntry(surface);+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => {+ if (String(args[2]).startsWith("INSERT INTO")) {+ if (outcome === "unknown") throw new Error("connection lost");+ return { ...result(), execution_error: true, error: { detail: "ORA-01031" } };+ }+ return read(...args);+ });+ const pending = controller.confirmPasteTable();+ await acceptClone();+ await pending;+ const details = document.querySelector("details[data-testid='danger-code-container']")?.textContent;+ expect(details).toContain('Completed and committed: Table "APP"."MixedCopy"');+ expect(details).toContain(outcome === "rejected" ? "Rejected by the database: Data" : "Result unknown; the statement may have reached the server: Data");+ expect(details).toContain('INSERT INTO "APP"."MixedCopy"');+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ });++ it("reports completed targets before a later batch failure and leaves later targets unexecuted", async () => {+ const { controller } = await mountEntry(surface);+ controller.pasteTableMode = "structure-only";+ controller.pasteTableEntries.push({ ...controller.pasteTableEntries[0], targetName: '"OtherCopy"' }, { ...controller.pasteTableEntries[0], targetName: '"LastCopy"' });+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => (String(args[2]).startsWith('CREATE TABLE "APP"."OtherCopy"') ? { ...result(), execution_error: true, error: { detail: "ORA-01031" } } : read(...args)));+ const pending = controller.confirmPasteTable();+ await acceptClone();+ await pending;+ const details = document.querySelector("details[data-testid='danger-code-container']")?.textContent;+ expect(details).toContain("Completed and committed:APP.MixedCopy");+ expect(details).toContain("Rejected by the database");+ expect(details).toContain("Not executed:APP.LastCopy");+ expect(ddlCalls().some((call) => String(call[2]).includes("LastCopy"))).toBe(false);+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ });++ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("uses the existing application dialog and cancels %s without browser prompts", async (action) => {+ const { controller } = await mountEntry(surface);+ const pending = controller[action]();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).not.toBeNull());+ expect(window.confirm).not.toHaveBeenCalled();+ expect(ddlCalls()).toEqual([]);+ const dialog = document.querySelector('[role="dialog"]')!;+ const cancel = Array.from(dialog.querySelectorAll("button")).find((button) => button.textContent?.trim() === i18n.global.t("dangerDialog.cancel"));+ expect(cancel).toBeDefined();+ cancel!.click();+ await pending;+ expect(ddlCalls()).toEqual([]);+ expect(backend.buildCopyTableDataSql).not.toHaveBeenCalled();+ });++ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("honors production confirmation cancellation in %s", async (action) => {+ connection.is_production = true;+ const { controller, refresh } = await mountEntry(surface);+ const pending = controller[action]();+ await acceptClone();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending?.sql).toContain("CREATE TABLE"));+ safety.cancel();+ await pending;+ expect(ddlCalls()).toEqual([]);+ expect(backend.buildCopyTableDataSql).not.toHaveBeenCalled();+ expect(refresh).not.toHaveBeenCalled();+ });++ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("cancels pending %s on unmount before any DDL or data copy", async (action) => {+ const { controller, app } = await mountEntry(surface);+ const pending = controller[action]();+ await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).not.toBeNull());+ mounted.splice(mounted.indexOf(app), 1);+ app.unmount();+ await pending;+ expect(window.confirm).not.toHaveBeenCalled();+ expect(ddlCalls()).toEqual([]);+ expect(backend.buildCopyTableDataSql).not.toHaveBeenCalled();+ });++ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("refreshes after partial failure in %s and stops later writes", async (action) => {+ const { controller, refresh } = await mountEntry(surface);+ const read = backend.executeQuery.getMockImplementation()!;+ backend.executeQuery.mockImplementation(async (...args) => (String(args[2]).startsWith("COMMENT ") ? { ...result(), execution_error: true, error: { detail: "ORA-01031: insufficient privileges" } } : read(...args)));+ const pending = controller[action]();+ await acceptClone();+ await pending;+ expect(ddlCalls()).toHaveLength(2);+ expect(window.alert).not.toHaveBeenCalled();+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain(i18n.global.t("oceanbaseCloneDialog.rejected"));+ expect(refresh).toHaveBeenCalledWith(connection.id, "APP", "APP");+ expect(backend.buildCopyTableDataSql).not.toHaveBeenCalled();+ });++ it("uses the resolved exact name for data copy after structure creation", async () => {+ const { controller } = await mountEntry(surface);+ const pending = controller.confirmPasteTable();+ await acceptClone();+ await pending;+ expect(backend.buildCopyTableDataSql).toHaveBeenCalledWith(expect.objectContaining({ targetName: "MixedCopy", schema: "APP", normalizeNewTargetName: false }));+ expect(ddlCalls().map((call) => call[2])).toEqual(['CREATE TABLE "APP"."MixedCopy" ("ID" NUMBER)', 'COMMENT ON TABLE "APP"."MixedCopy" IS \'source comment\'', 'INSERT INTO "APP"."MixedCopy" SELECT * FROM "APP"."SOURCE"']);+ });+});++describe.each([false, true])("ObjectBrowser clone execution identity (comment rejected: %s)", (rejected) => {+ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("keeps writes on the original connection during %s", async (action) => {+ const { controller, context, refresh } = await mountEntry("objects");+ const read = backend.executeQuery.getMockImplementation()!;+ let release!: () => void;+ const paused = new Promise<void>((resolve) => {+ release = resolve;+ });+ backend.executeQuery.mockImplementation(async (...args) => {+ if (String(args[2]).startsWith("CREATE TABLE")) await paused;+ if (rejected && String(args[2]).startsWith("COMMENT ")) return { ...result(), execution_error: true, error: { detail: "ORA-01031: insufficient privileges" } };+ return read(...args);+ });+ const pending = controller[action]();+ await acceptClone();+ await vi.waitFor(() => expect(ddlCalls()).toHaveLength(1));+ const otherConnection = { ...connection, id: "different-connection" };+ const store = useConnectionStore();+ store.connections.push(otherConnection);+ store.connectedIds.add(otherConnection.id);+ context.value = { connection: otherConnection, database: "OTHER", schema: "OTHER" };+ await nextTick();+ release();+ await pending;+ expect(ddlCalls().map((call) => call.slice(0, 2))).toEqual(ddlCalls().map(() => [connection.id, "APP"]));+ expect(refresh).toHaveBeenCalledWith(connection.id, "APP", "APP");+ expect(refresh.mock.calls.every((call) => call[0] === connection.id)).toBe(true);+ if (rejected) expect(backend.buildCopyTableDataSql).not.toHaveBeenCalled();+ });+});++describe("ObjectBrowser clone confirmation identity", () => {+ it.each(["confirmDuplicateStructure", "confirmPasteTable"])("checks the original production connection after planning in %s", async (action) => {+ connection.is_production = true;+ const { controller, context } = await mountEntry("objects");+ let release!: () => void;+ const paused = new Promise<void>((resolve) => {+ release = resolve;+ });+ backend.buildCreateTableSql.mockImplementationOnce(async () => {+ await paused;+ return { statements: ['CREATE TABLE "APP"."MixedCopy" ("ID" NUMBER);'], warnings: [] };+ });+ const pending = controller[action]();+ await vi.waitFor(() => expect(backend.buildCreateTableSql).toHaveBeenCalled());+ const otherConnection = { ...connection, id: "different-connection", is_production: false };+ const store = useConnectionStore();+ store.connections.push(otherConnection);+ store.connectedIds.add(otherConnection.id);+ context.value = { connection: otherConnection, database: "OTHER", schema: "OTHER" };+ await nextTick();+ release();+ await acceptClone();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending?.database).toBe("APP"));+ safety.cancel();+ await pending;+ expect(ddlCalls()).toEqual([]);+ });+});diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 91dc6fcacb..0615597fd7 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -193,6 +193,10 @@ import {type MysqlAutoIncrementSqlOptions,type TableChildObjectType,} from "@/lib/database/dbAdminSql";+import { executeOceanbaseTableClone, executeOceanbaseTableCloneData, oceanbaseCloneDataPreparationError, OceanbaseTableCloneError, type OceanbaseTableClone } from "@/lib/database/oceanbaseTableClone";+import type { DuplicateTableStructurePlan } from "@/lib/database/dbAdminSql";+import { useOceanbaseCloneDialog } from "@/composables/useOceanbaseCloneDialog";+import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";import { buildRenameObjectSql, buildRenameDatabaseSql, buildRenameDatabasePreflightSql, databaseRenameMaintenanceDatabase, supportsDatabaseRename, supportsObjectRename, type RenameableObjectType } from "@/lib/table/objectRenameSql";import { buildRoutineRenameObjectSourceStatements, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";import { buildViewDdl } from "@/lib/table/viewDdl";@@ -402,6 +406,8 @@ import {} from "./sidebarTreeDialogState";const { t, locale: appLocale } = useI18n();+const cloneDialog = useOceanbaseCloneDialog(t);+const { state: cloneDialogState, open: cloneDialogOpen } = cloneDialog;const connectionStore = useConnectionStore();@@ -3446,6 +3452,7 @@ async function executeTreeNodeSqlWithProductionGuard(beforeExecute?: () => Promise<void>;markDispatched?: () => void;timeoutSecs?: number;+ execute?: (timeoutSecs: number) => ReturnType<typeof api.executeQuery>;} = {},) {if (!node.connectionId) return undefined;@@ -3471,6 +3478,7 @@ async function executeTreeNodeSqlWithProductionGuard(await options.beforeExecute?.();if (options.isCancelledBeforeDispatch?.()) throw new Error("Operation cancelled before it was sent to the database.");options.markDispatched?.();+ if (options.execute) return options.execute(options.timeoutSecs ?? timeoutSecs);return options.executeAsScript ? api.executeScript(node.connectionId!, database, sql, options.schema ?? node.schema) : api.executeQuery(node.connectionId!, database, sql, options.schema ?? node.schema, executionId, { timeoutSecs: options.timeoutSecs ?? timeoutSecs });},});@@ -4797,14 +4805,21 @@ function isDuplicateStructureSource(node: TreeNode): node is DuplicateStructureS}async function confirmDuplicateStructure() {- const node = duplicateStructureSource.value || (isDuplicateStructureSource(activeNode.value) ? activeNode.value : null);+ const node = duplicateStructureSource.value || activeNode.value;+ return databaseTypeForNode(node) === "oceanbase-oracle" ? cloneDialog.run(confirmDuplicateStructureImpl) : confirmDuplicateStructureImpl();+}++async function confirmDuplicateStructureImpl() {+ const sourceNode = duplicateStructureSource.value || (isDuplicateStructureSource(activeNode.value) ? activeNode.value : null);+ const node = sourceNode ? { ...sourceNode } : null;const newName = duplicateTableName.value.trim();if (!newName || !node) return;if (databaseTypeForNode(node) === "victoriametrics") return;+ const databaseType = databaseTypeForNode(node);+ const identifierQuote = connectionStore.connectionIdentifierQuote?.(node.connectionId);showDuplicateDialog.value = false;try {await connectionStore.ensureConnected(node.connectionId);- const databaseType = databaseTypeForNode(node);const plan = await buildDuplicateTableStructurePlan({connectionId: node.connectionId,database: node.database,@@ -4814,22 +4829,45 @@ async function confirmDuplicateStructure() {sourceName: node.label,targetName: newName,tableComment: node.comment,- identifierQuote: connectionStore.connectionIdentifierQuote?.(node.connectionId),+ identifierQuote,});- await executeTreeNodeSqlWithProductionGuard(node, plan.sql, {+ if (!(await cloneDialog.request([{ plan, scope: [node.connectionId, node.database, node.catalog || ""] }]))) return;+ const executed = await executeTreeNodeSqlWithProductionGuard(node, plan.sql, {database: node.database,schema: node.schema,executeAsScript: plan.executeAsScript,+ execute: plan.oceanbaseClone ? (timeoutSecs) => executeOceanbaseTableClone(plan.oceanbaseClone!, (sql) => api.executeQuery(node.connectionId, node.database, sql, plan.oceanbaseClone!.targetSchema, undefined, { timeoutSecs, catalog: node.catalog })) : undefined,});+ if (!executed) return;toast(t("contextMenu.duplicateStructureSuccess", { name: newName }), 3000);await refreshTableList(node);} catch (e: any) {+ if (e instanceof OceanbaseTableCloneError) {+ const refreshed = await Promise.allSettled([connectionStore.refreshObjectListTreeNode(node.connectionId, node.database, e.targetSchema)]);+ cloneDialog.showFailure(+ e,+ [],+ refreshed.flatMap((result) => (result.status === "rejected" ? [result.reason] : [])),+ );+ return;+ }+ if (databaseType === "oceanbase-oracle") {+ cloneDialog.showFailure(e);+ return;+ }toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);}}async function confirmPasteTable() {- const entries = pasteTableEntries.value.filter((entry) => entry.targetName.trim());+ const hasOceanbaseClone = pasteTableEntries.value.some((entry) => entry.connectionId && effectiveDatabaseTypeForConnection(connectionStore.getConfig(entry.connectionId)) === "oceanbase-oracle");+ return hasOceanbaseClone ? cloneDialog.run(confirmPasteTableImpl) : confirmPasteTableImpl();+}++async function confirmPasteTableImpl() {+ const entries = pasteTableEntries.value+ .filter((entry) => entry.targetName.trim())+ .map((entry) => ({ ...entry, databaseType: entry.connectionId ? effectiveDatabaseTypeForConnection(connectionStore.getConfig(entry.connectionId)) : undefined, identifierQuote: connectionStore.connectionIdentifierQuote?.(entry.connectionId) }));if (entries.length === 0) return;const clipboardAtPasteStart = connectionStore.treeClipboard;const mode = pasteTableMode.value;@@ -4851,35 +4889,75 @@ async function confirmPasteTable() {schema: entry.schema,});};+ const preparedClones = new Map<(typeof entries)[number], DuplicateTableStructurePlan>();+ if (mode !== "data-only") {+ try {+ for (const entry of entries.filter((item) => item.databaseType === "oceanbase-oracle")) {+ await connectionStore.ensureConnected(entry.connectionId);+ preparedClones.set(+ entry,+ await buildDuplicateTableStructurePlan({+ connectionId: entry.connectionId,+ database: entry.database,+ databaseType: entry.databaseType,+ schema: entry.schema,+ sourceName: entry.sourceName,+ targetName: entry.targetName.trim(),+ tableComment: entry.tableComment,+ identifierQuote: entry.identifierQuote,+ }),+ );+ }+ if (!(await cloneDialog.request([...preparedClones].map(([entry, plan]) => ({ plan, scope: [entry.connectionId, entry.database, ""] }))))) return;+ } catch (error) {+ cloneDialog.showFailure(+ error,+ entries.map((entry) => `${entry.schema || ""}.${entry.targetName}`),+ );+ return;+ }+ }+ let cloneFailure: { error: unknown; remaining: string[] } | undefined;+ const completedCloneTargets: string[] = [];for (const entry of entries) {- const targetName = entry.targetName.trim();+ let targetName = entry.targetName.trim();+ let schema = entry.schema;+ let completedClone: OceanbaseTableClone | undefined;try {await connectionStore.ensureConnected(entry.connectionId);- const databaseType = entry.connectionId ? effectiveDatabaseTypeForConnection(connectionStore.getConfig(entry.connectionId)) : undefined;+ const databaseType = entry.databaseType;let sourceColumns: ColumnInfo[] | undefined;if (mode === "structure-and-data" || mode === "structure-only") {- const plan = await buildDuplicateTableStructurePlan({- connectionId: entry.connectionId,- database: entry.database,- databaseType,- schema: entry.schema,- sourceName: entry.sourceName,- targetName,- tableComment: entry.tableComment,- identifierQuote: connectionStore.connectionIdentifierQuote?.(entry.connectionId),- });+ const plan =+ preparedClones.get(entry) ||+ (await buildDuplicateTableStructurePlan({+ connectionId: entry.connectionId,+ database: entry.database,+ databaseType,+ schema: entry.schema,+ sourceName: entry.sourceName,+ targetName,+ tableComment: entry.tableComment,+ identifierQuote: entry.identifierQuote,+ }));sourceColumns = plan.sourceColumns;+ if (plan.oceanbaseClone) {+ targetName = plan.oceanbaseClone.targetName;+ schema = plan.oceanbaseClone.targetSchema;+ }const structureExecuted = await executeTreeNodeSqlWithProductionGuard(entry, plan.sql, {database: entry.database,schema: entry.schema,executeAsScript: plan.executeAsScript,+ execute: plan.oceanbaseClone ? (timeoutSecs) => executeOceanbaseTableClone(plan.oceanbaseClone!, (sql) => api.executeQuery(entry.connectionId, entry.database, sql, plan.oceanbaseClone!.targetSchema, undefined, { timeoutSecs })) : undefined,});if (!structureExecuted) {pasteCancelled = true;break;}hasMutatedTable = true;- queueRefreshTarget(entry);+ completedClone = plan.oceanbaseClone;+ queueRefreshTarget({ ...entry, schema });}if (copyData) {if (!sourceColumns) {@@ -4891,14 +4969,20 @@ async function confirmPasteTable() {}const dataSql = await buildCopyTableDataSql({databaseType,- schema: entry.schema,+ schema,sourceName: entry.sourceName,targetName,- normalizeNewTargetName: mode === "structure-and-data",- identifierQuote: connectionStore.connectionIdentifierQuote?.(entry.connectionId),+ normalizeNewTargetName: mode === "structure-and-data" && databaseType !== "oceanbase-oracle",+ identifierQuote: entry.identifierQuote,...dataCopyColumnOptions,});- const dataExecuted = await executeTreeNodeSqlWithProductionGuard(entry, dataSql, { database: entry.database, schema: entry.schema, timeoutSecs: 0 });+ const clone = preparedClones.get(entry)?.oceanbaseClone;+ const dataExecuted = await executeTreeNodeSqlWithProductionGuard(entry, dataSql, {+ database: entry.database,+ schema,+ timeoutSecs: 0,+ execute: clone ? (timeoutSecs) => executeOceanbaseTableCloneData(clone, dataSql, (sql) => api.executeQuery(entry.connectionId, entry.database, sql, schema, undefined, { timeoutSecs })) : undefined,+ });if (!dataExecuted) {pasteCancelled = true;break;@@ -4907,7 +4991,20 @@ async function confirmPasteTable() {queueRefreshTarget(entry);}successCount++;+ if (preparedClones.has(entry)) completedCloneTargets.push(`${schema}.${targetName}`);} catch (e: any) {+ if (preparedClones.has(entry)) {+ if (completedClone && !(e instanceof OceanbaseTableCloneError)) e = oceanbaseCloneDataPreparationError(completedClone, e);+ queueRefreshTarget({ ...entry, schema: e instanceof OceanbaseTableCloneError ? e.targetSchema : schema });+ cloneFailure = {+ error: e,+ remaining: entries.slice(entries.indexOf(entry) + 1).map((pending) => {+ const clone = preparedClones.get(pending)?.oceanbaseClone;+ return `${clone?.targetSchema || pending.schema || ""}.${clone?.targetName || pending.targetName}`;+ }),+ };+ break;+ }pasteFailCount++;firstPasteError ??= e;console.error(`Failed to paste table "${entry.sourceName}" -> "${targetName}":`, e);@@ -4922,6 +5019,10 @@ async function confirmPasteTable() {console.error(`Failed to refresh pasted tables for "${refreshTarget.database}"${refreshTarget.schema ? ` schema "${refreshTarget.schema}"` : ""}:`, e);}}+ if (cloneFailure) {+ cloneDialog.showFailure(cloneFailure.error, cloneFailure.remaining, refreshError ? [refreshError] : [], completedCloneTargets);+ return;+ }if (pasteCancelled) {if (hasMutatedTable && refreshFailCount === 0) {toast(t("contextMenu.pasteTableCancelledAfterPartial"), 5000);@@ -7509,6 +7610,18 @@ defineExpose({</script><template>+ <DangerConfirmDialog+ v-model:open="cloneDialogOpen"+ :title="t(cloneDialogState?.failure ? 'oceanbaseCloneDialog.failed' : 'oceanbaseCloneDialog.title')"+ :message="t(cloneDialogState?.failure ? 'oceanbaseCloneDialog.failedMessage' : 'oceanbaseCloneDialog.message')"+ :details-text="cloneDialogState?.summary"+ :details="cloneDialogState?.details"+ :details-label="t('oceanbaseCloneDialog.details')"+ :show-cancel="!cloneDialogState?.failure"+ :confirm-label="cloneDialogState?.failure ? t('oceanbaseCloneDialog.close') : undefined"+ :close-on-confirm="false"+ @confirm="cloneDialog.confirm"+ /><ModelGenerateDialog v-if="modelGenerationTarget" :key="modelGenerationTarget.id" :target="modelGenerationTarget" @close="modelGenerationTarget = null" /><SqlTemplateInsertRowsDialog v-model:open="insertTemplateRowsOpen" @confirm="confirmInsertTemplateRows" /><Dialogdiff --git a/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.tsnew file mode 100644index 0000000000..13d4cde15b--- /dev/null+++ b/apps/desktop/src/components/structure/TableStructureEditor.oceanbaseTypes.spec.ts@@ -0,0 +1,90 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { afterEach, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import TableStructureEditor from "./TableStructureEditor.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import type { ConnectionConfig } from "@/types/database";+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";+import { TooltipProvider } from "@/components/ui/tooltip";+import LightTooltip from "@/components/ui/LightTooltip.vue";++const backend = vi.hoisted(() => ({+ listDataTypes: vi.fn(),+ buildTableStructureChangeSql: vi.fn().mockResolvedValue({ statements: [], warnings: [] }),+}));+vi.mock("@/lib/backend/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),+ ...backend,+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),+ listIndexes: vi.fn().mockResolvedValue([]),+ listConstraints: vi.fn().mockResolvedValue([]),+ listForeignKeys: vi.fn().mockResolvedValue([]),+ listTriggers: vi.fn().mockResolvedValue([]),+ getTableOwner: vi.fn().mockResolvedValue("APP"),+ getTablePartitionStatus: vi.fn().mockResolvedValue(null),+ listPlugins: vi.fn().mockResolvedValue([]),+ loadSchemaCache: vi.fn().mockResolvedValue(null),+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),+}));++let app: App | undefined;+afterEach(() => {+ app?.unmount();+ document.body.innerHTML = "";+ vi.clearAllMocks();+});++it("filters rejected JDBC recommendations without replacing an existing nonrecommended type", async () => {+ backend.listDataTypes.mockResolvedValue(["NUMBER", "NCLOB", "Long", "LONG RAW", "BFILE", "boolean", "VECTOR(3, FLOAT32)", "CUSTOM_OB_TYPE"]);+ const pinia = createPinia();+ setActivePinia(pinia);+ const connection = { id: "ob-type-picker", name: "OB", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", host: "test", port: 2881, username: "APP", database: "APP" } as ConnectionConfig;+ const store = useConnectionStore();+ store.connections = [connection];+ store.connectedIds.add(connection.id);+ const column: EditableStructureColumn = {+ id: "existing:C",+ name: "C",+ dataType: "NCLOB",+ isNullable: true,+ defaultValue: "",+ comment: "original comment",+ isPrimaryKey: false,+ extra: {},+ original: { name: "C", data_type: "NCLOB", is_nullable: true, column_default: null, comment: "original comment", is_primary_key: false, extra: null },+ originalPosition: 0,+ markedForDrop: false,+ };+ const root = document.createElement("div");+ document.body.append(root);+ const editorProps = {+ connectionId: connection.id,+ database: "APP",+ schema: "APP",+ tableName: "T",+ draft: { initialized: true, activeTab: "columns" as const, newTableName: "", tableComment: "", originalTableComment: "", columns: [column], indexes: [], foreignKeys: [], triggers: [] },+ };+ app = createApp({ render: () => h(TooltipProvider, {}, { default: () => h(TableStructureEditor, editorProps) }) });+ app.component("LightTooltip", LightTooltip);+ app.use(pinia);+ app.use(i18n);+ app.mount(root);+ await vi.waitFor(() => expect(backend.listDataTypes).toHaveBeenCalled());+ await nextTick();+ const picker = root.querySelector<HTMLButtonElement>(".structure-column-data-type button");+ expect(picker?.textContent?.trim()).toBe("NCLOB");+ picker!.click();+ await vi.waitFor(() => expect(document.body.textContent).toContain("CUSTOM_OB_TYPE"));+ const choices = Array.from(document.querySelectorAll('[data-slot="popover-content"] button')).map((button) => button.textContent?.trim());+ expect(choices).toContain("CUSTOM_OB_TYPE");+ expect(choices).toContain("NUMBER");+ for (const rejected of ["NCLOB", "Long", "LONG RAW", "BFILE", "boolean", "VECTOR(3, FLOAT32)"]) expect(choices).not.toContain(rejected);+ picker!.click();+ const comment = Array.from(root.querySelectorAll("input")).find((input) => input.value === "original comment");+ expect(comment).toBeDefined();+ comment!.value = "changed comment";+ comment!.dispatchEvent(new Event("input", { bubbles: true }));+ await vi.waitFor(() => expect(backend.buildTableStructureChangeSql).toHaveBeenLastCalledWith(expect.objectContaining({ columns: [expect.objectContaining({ dataType: "NCLOB", comment: "changed comment", original: expect.objectContaining({ data_type: "NCLOB" }) })] })));+});diff --git a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.tsindex 8da3d10e90..34c9664c43 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts+++ b/apps/desktop/src/components/structure/TableStructureEditor.primaryKey.spec.ts@@ -811,6 +811,28 @@ describe("TableStructureEditor primary key editing", () => {});describe("TableStructureEditor data type options", () => {+ it("supplies the verified OceanBase built-in list to the column picker", async () => {+ const root = await mountEditor("oceanbase-oracle", false, { database: "ob-built-in-types" });+ const picker = root.querySelector<HTMLElement>('[data-searchable-select="true"]');+ if (!picker) throw new Error("Missing data type picker");+ const options = JSON.parse(picker.dataset.options ?? "[]") as string[];+ expect(options).toHaveLength(23);+ expect(options).toEqual(expect.arrayContaining(["number", "float", "json", "xmltype", "sdo_geometry"]));+ for (const rejected of ["nclob", "long", "long raw", "bfile", "boolean", "vector"]) expect(options).not.toContain(rejected);+ expect(picker.dataset.allowCustom).toBe("true");+ });++ it("keeps other dynamic OceanBase types while excluding rejected recommendations", async () => {+ const root = await mountEditor("oceanbase-oracle", false, { database: "ob-dynamic-types", dynamicTypes: ["NUMBER", "VECTOR", "CUSTOM_OB_TYPE"] });+ const picker = root.querySelector<HTMLElement>('[data-searchable-select="true"]');+ if (!picker) throw new Error("Missing data type picker");+ await vi.waitFor(() => expect(JSON.parse(picker.dataset.options ?? "[]").slice(0, 2)).toEqual(["NUMBER", "CUSTOM_OB_TYPE"]));+ const options = JSON.parse(picker.dataset.options ?? "[]") as string[];+ expect(options).not.toContain("VECTOR");+ expect(options.filter((option) => option.toLowerCase() === "number")).toEqual(["NUMBER"]);+ expect(options).toContain("xmltype");+ });+it("keeps dynamic Dameng types first and deduplicates fallback types case-insensitively", async () => {const root = await mountEditor("dameng", false, {database: "dynamic-types-5275",diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex 39edb687b0..c94ae499a5 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -1378,7 +1378,12 @@ const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(daconst structureDialect = computed(() => structureCapabilities.value.dialect);const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment);const dynamicDataTypeOptions = ref<string[]>([]);-const dataTypeOptions = computed(() => mergeDataTypeOptions(dynamicDataTypeOptions.value, getDataTypeOptions(databaseType.value)));+const dataTypeOptions = computed(() => {+ const options = mergeDataTypeOptions(dynamicDataTypeOptions.value, getDataTypeOptions(databaseType.value));+ if (databaseType.value !== "oceanbase-oracle") return options;+ // JDBC may advertise Oracle types that OceanBase rejects.+ return options.filter((type) => !/^(?:nclob|long(?:\s+raw)?|bfile|boolean|vector)\s*(?:\(|$)/i.test(type.trim()));+});const columnEditorControls = computed(() => getColumnEditorControls(databaseType.value));const indexTypesByDb: Record<string, string[]> = {diff --git a/apps/desktop/src/composables/useOceanbaseCloneDialog.ts b/apps/desktop/src/composables/useOceanbaseCloneDialog.tsnew file mode 100644index 0000000000..485f0fd9eb--- /dev/null+++ b/apps/desktop/src/composables/useOceanbaseCloneDialog.ts@@ -0,0 +1,105 @@+import { computed, onScopeDispose, shallowRef } from "vue";+import type { DuplicateTableStructurePlan } from "@/lib/database/dbAdminSql";+import { OceanbaseCloneValidationError, OceanbaseTableCloneError, type OceanbaseTableClone } from "@/lib/database/oceanbaseTableClone";++export interface OceanbaseCloneDialogPlan {+ plan: DuplicateTableStructurePlan;+ /** Captured connection, database and catalog identity, never current UI selection. */+ scope: string[];+}++type Translate = (key: string, values?: Record<string, string | number>) => string;+const quoted = (name: string) => `"${name.replace(/"/g, '""')}"`;+const target = (clone: OceanbaseTableClone) => `${quoted(clone.targetSchema)}.${quoted(clone.targetName)}`;++/** Confirmation and result state for the two existing OceanBase clone surfaces. */+export function useOceanbaseCloneDialog(t: Translate) {+ const state = shallowRef<{ failure: boolean; summary: string; details: string } | null>(null);+ let resolvePending: ((confirmed: boolean) => void) | undefined;+ let disposed = false;+ let running = false;+ const text = (key: string, values?: Record<string, string | number>) => t(`oceanbaseCloneDialog.${key}`, values);+ const open = computed({+ get: () => state.value !== null,+ set: (value: boolean) => {+ if (!value) settle(false);+ },+ });++ function settle(confirmed: boolean) {+ const resolve = resolvePending;+ resolvePending = undefined;+ state.value = null;+ resolve?.(confirmed);+ }++ async function run(action: () => Promise<void>) {+ if (disposed || running || state.value) return;+ running = true;+ try {+ await action();+ } finally {+ running = false;+ }+ }++ function request(plans: OceanbaseCloneDialogPlan[]): Promise<boolean> {+ if (disposed || state.value) return Promise.resolve(false);+ const clones = plans.filter((item) => item.plan.oceanbaseClone);+ if (!clones.length) return Promise.resolve(true);+ const tables = new Set<string>();+ const indexes = new Set<string>();+ for (const item of clones) {+ const clone = item.plan.oceanbaseClone!;+ const scope = [...item.scope, clone.targetSchema];+ const tableKey = JSON.stringify([...scope, clone.targetName]);+ if (tables.has(tableKey)) throw new Error(text("duplicateTarget", { name: target(clone) }));+ tables.add(tableKey);+ for (const name of clone.indexNames) {+ const indexKey = JSON.stringify([...scope, name]);+ if (indexes.has(indexKey)) throw new Error(text("duplicateIndex", { name: `${quoted(clone.targetSchema)}.${quoted(name)}` }));+ indexes.add(indexKey);+ }+ }+ const summary = clones+ .map(({ plan }) => {+ const clone = plan.oceanbaseClone!;+ const scope = text("scope", { columns: clone.columnCount, keys: clone.steps.filter((step) => step.kind === "primaryKey").length, indexes: clone.indexNames.length, comments: clone.steps.filter((step) => step.kind === "comment").length });+ const excluded = clone.exclusions.map((item) => {+ if (item.kind === "partitioning") return text("partitioning");+ const kind = item.kind === "constraint" ? { "FOREIGN KEY": "foreignKey", UNIQUE: "unique", CHECK: "check" }[item.type || ""] || "constraint" : item.kind;+ return `${text(kind)} ${quoted(item.name || "")}`;+ });+ return `${target(clone)}\n${scope}\n${text("excluded")}: ${excluded.join(", ") || text("none")}`;+ })+ .join("\n\n");+ state.value = { failure: false, summary, details: clones.map(({ plan }) => plan.sql).join("\n\n") };+ return new Promise<boolean>((resolve) => {+ resolvePending = resolve;+ });+ }++ function showFailure(error: unknown, unexecutedTargets: string[] = [], refreshErrors: unknown[] = [], completedTargets: string[] = []) {+ if (disposed) return;+ settle(false);+ const execution = error instanceof OceanbaseTableCloneError ? error.execution : undefined;+ const original = execution?.cause ?? error;+ const cause = original instanceof OceanbaseCloneValidationError ? text(original.key, original.values) : original instanceof Error ? original.message : String(original);+ const summary = [error instanceof OceanbaseTableCloneError ? `${quoted(error.targetSchema)}.${quoted(error.targetName)}` : "", cause, text("noRollback")].filter(Boolean).join("\n");+ const details =+ execution?.steps.map((step, position) => {+ const status = position < execution.failedPosition ? "completed" : position > execution.failedPosition || execution.notExecuted ? "notExecuted" : execution.rejected ? "rejected" : "unknown";+ return `${text(status)}: ${text(step.kind)} ${step.name}\n${step.sql}`;+ }) || [];+ if (completedTargets.length) details.unshift(`${text("completed")}:\n${completedTargets.join("\n")}`);+ if (unexecutedTargets.length) details.push(`${text("notExecuted")}:\n${unexecutedTargets.join("\n")}`);+ if (refreshErrors.length) details.push(`${text("refreshFailed")}:\n${refreshErrors.map((value) => (value instanceof Error ? value.message : String(value))).join("\n")}`);+ state.value = { failure: true, summary, details: details.join("\n\n") };+ }++ onScopeDispose(() => {+ disposed = true;+ settle(false);+ });+ return { state, open, request, showFailure, run, confirm: () => settle(true) };+}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 135327756f..627dc287a4 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1,4 +1,5 @@import { sidebarMenuEn as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogEn as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { redisGroupingEn as redisGrouping } from "./redisGrouping";import docs from "./docs/en";import { dataDictionaryEn as dataDictionary } from "./dataDictionaryMessages";@@ -63,6 +64,7 @@ const consul = {};export default {+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "Generate model",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex b05cf01c57..00b4573048 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1,4 +1,5 @@import { sidebarMenuEs as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogEs as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { withEnglishFallback } from "./fallback";import { mongodbDatabaseDumpEs as mongoDump } from "./mongodbDatabaseDump";import { damengDumpEs as damengDump } from "./damengDump";@@ -65,6 +66,7 @@ const consul = {};export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "Generar modelo",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 7f7f9c1c7a..e5aeab00ea 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1,4 +1,5 @@import { sidebarMenuIt as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogIt as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { withEnglishFallback } from "./fallback";import { mongodbDatabaseDumpIt as mongoDump } from "./mongodbDatabaseDump";import { damengDumpIt as damengDump } from "./damengDump";@@ -63,6 +64,7 @@ const consul = {};export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "Genera modello",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex f25a8ec3d5..b658ba6f79 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1,4 +1,5 @@import { sidebarMenuJa as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogJa as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { withEnglishFallback } from "./fallback";import { mongodbDatabaseDumpJa as mongoDump } from "./mongodbDatabaseDump";import { damengDumpJa as damengDump } from "./damengDump";@@ -64,6 +65,7 @@ const consul = {};export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "モデルを生成",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 362fd9cce7..10e7ed5053 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1,4 +1,5 @@import { sidebarMenuKo as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogKo as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { withEnglishFallback } from "./fallback";import { mongodbDatabaseDumpKo as mongoDump } from "./mongodbDatabaseDump";import { damengDumpKo as damengDump } from "./damengDump";@@ -63,6 +64,7 @@ const consul = {};export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "모델 생성",diff --git a/apps/desktop/src/i18n/locales/oceanbaseCloneDialog.ts b/apps/desktop/src/i18n/locales/oceanbaseCloneDialog.tsnew file mode 100644index 0000000000..eee2350b52--- /dev/null+++ b/apps/desktop/src/i18n/locales/oceanbaseCloneDialog.ts@@ -0,0 +1,431 @@+export const oceanbaseCloneDialogEn = {+ invalidName: "Use an ordinary table name or an explicitly double-quoted name.",+ metadataRead: "Unable to read clone metadata. No DDL was executed.",+ metadataTruncated: "Clone metadata was truncated. No DDL was executed.",+ currentSchema: "Current schema is unavailable. No DDL was executed.",+ tableProperties: "Source table properties are unavailable. No DDL was executed.",+ temporaryTable: "Cloning temporary tables is not supported. No DDL was executed.",+ virtualColumns: "Cloning virtual columns is not supported: {names}. No DDL was executed.",+ sourceMetadata: "Source table metadata is missing or inaccessible. No DDL was executed.",+ targetExists: "Target already exists: {name}. No DDL was executed.",+ primaryKeyMetadata: "Source primary-key columns, order or metadata are incomplete or inconsistent. No DDL was executed.",+ createColumns: "Unable to generate complete OceanBase Oracle table columns. No DDL was executed.",+ primaryKeyState: "Cloning disabled, unvalidated, deferrable or unknown-state primary keys is not supported. No DDL was executed.",+ uniqueIndexMetadata: "Source unique-constraint index metadata is unavailable. No DDL was executed.",+ indexExists: "Target index names already exist: {names}. Choose another target table name. No DDL was executed.",+ indexVisibility: "Index visibility is incomplete or ambiguous: {name}. No DDL was executed.",+ indexColumns: "Index column order or direction is incomplete: {name}. No DDL was executed.",+ executionFailed: "The database reported an execution failure without further details.",+ title: "Confirm table copy",+ message: "Review each target and the structure that will be copied.",+ scope: "Copy {columns} columns, {keys} primary key, {indexes} ordinary indexes and {comments} comments.",+ excluded: "Not copied",+ none: "None",+ details: "View SQL and execution details",+ failed: "Table copy stopped",+ failedMessage: "Review the result before trying again.",+ noRollback: "No automatic rollback or cleanup was performed. Check the target before retrying.",+ completed: "Completed and committed",+ rejected: "Rejected by the database",+ unknown: "Result unknown; the statement may have reached the server",+ notExecuted: "Not executed",+ refreshFailed: "Refresh also failed",+ close: "Close",+ table: "Table",+ data: "Data",+ primaryKey: "Primary key",+ index: "Index",+ comment: "Comment",+ constraint: "Constraint",+ foreignKey: "Foreign key",+ unique: "Unique constraint",+ check: "CHECK constraint",+ trigger: "Trigger",+ partitioning: "Partitioning (the target will not be partitioned)",+ duplicateTarget: "Multiple copies target {name}. Change the target names before continuing.",+ duplicateIndex: "The copies would create the same index {name}. Change the target table names before continuing.",+};++export const oceanbaseCloneDialogZhCN = {+ invalidName: "请输入普通表名,或用双引号明确引用表名。",+ metadataRead: "无法读取克隆所需的元数据,未执行 DDL。",+ metadataTruncated: "克隆所需的元数据被截断,未执行 DDL。",+ currentSchema: "无法确定当前 schema,未执行 DDL。",+ tableProperties: "无法读取源表属性,未执行 DDL。",+ temporaryTable: "不支持克隆临时表,未执行 DDL。",+ virtualColumns: "不支持克隆虚拟列:{names}。未执行 DDL。",+ sourceMetadata: "源表元数据缺失或不可访问,未执行 DDL。",+ targetExists: "目标已存在:{name}。未执行 DDL。",+ primaryKeyMetadata: "源表主键的列、列序或元数据不完整或不一致,未执行 DDL。",+ createColumns: "无法生成完整的 OceanBase Oracle 表列定义,未执行 DDL。",+ primaryKeyState: "不支持克隆已禁用、未验证、可延迟或状态未知的主键,未执行 DDL。",+ uniqueIndexMetadata: "无法确定源表唯一约束的支撑索引,未执行 DDL。",+ indexExists: "目标索引名称已存在:{names}。请换用其他目标表名。未执行 DDL。",+ indexVisibility: "索引可见性信息不完整或不明确:{name}。未执行 DDL。",+ indexColumns: "索引列序或排序方向不完整:{name}。未执行 DDL。",+ executionFailed: "数据库报告执行失败,但未返回详细原因。",+ title: "确认复制表",+ message: "请核对各目标表及其复制范围。",+ scope: "复制 {columns} 个列、{keys} 个主键、{indexes} 个普通索引和 {comments} 条注释。",+ excluded: "不复制",+ none: "无",+ details: "查看 SQL 与执行明细",+ failed: "复制表已停止",+ failedMessage: "请核对执行结果后再重试。",+ noRollback: "未自动回滚或清理。重试前请核实目标表的实际状态。",+ completed: "已完成并提交",+ rejected: "数据库已拒绝",+ unknown: "结果未知,语句可能已到达服务器",+ notExecuted: "未执行",+ refreshFailed: "刷新也未成功",+ close: "关闭",+ table: "表",+ data: "数据",+ primaryKey: "主键",+ index: "索引",+ comment: "注释",+ constraint: "约束",+ foreignKey: "外键",+ unique: "唯一约束",+ check: "CHECK 约束",+ trigger: "触发器",+ partitioning: "分区结构(目标为非分区表)",+ duplicateTarget: "多项复制指向同一目标 {name}。请修改目标名称后继续。",+ duplicateIndex: "多项复制会创建同名索引 {name}。请修改目标表名后继续。",+};++export const oceanbaseCloneDialogZhTW = {+ invalidName: "請輸入一般資料表名稱,或使用雙引號明確引用名稱。",+ metadataRead: "無法讀取複製所需的中繼資料,未執行 DDL。",+ metadataTruncated: "複製所需的中繼資料遭截斷,未執行 DDL。",+ currentSchema: "無法確定目前的 schema,未執行 DDL。",+ tableProperties: "無法讀取來源資料表屬性,未執行 DDL。",+ temporaryTable: "不支援複製暫存資料表,未執行 DDL。",+ virtualColumns: "不支援複製虛擬欄位:{names}。未執行 DDL。",+ sourceMetadata: "來源資料表中繼資料缺失或無法存取,未執行 DDL。",+ targetExists: "目標已存在:{name}。未執行 DDL。",+ primaryKeyMetadata: "來源主鍵的欄位、順序或中繼資料不完整或不一致,未執行 DDL。",+ createColumns: "無法產生完整的 OceanBase Oracle 資料表欄位定義,未執行 DDL。",+ primaryKeyState: "不支援複製已停用、未驗證、可延遲或狀態未知的主鍵,未執行 DDL。",+ uniqueIndexMetadata: "無法確定來源唯一約束的支援索引,未執行 DDL。",+ indexExists: "目標索引名稱已存在:{names}。請改用其他目標資料表名稱。未執行 DDL。",+ indexVisibility: "索引可見性資訊不完整或不明確:{name}。未執行 DDL。",+ indexColumns: "索引欄位順序或排序方向不完整:{name}。未執行 DDL。",+ executionFailed: "資料庫回報執行失敗,但未提供詳細原因。",+ title: "確認複製資料表",+ message: "請核對各目標資料表及其複製範圍。",+ scope: "複製 {columns} 個欄位、{keys} 個主鍵、{indexes} 個一般索引及 {comments} 則註解。",+ excluded: "不複製",+ none: "無",+ details: "檢視 SQL 與執行明細",+ failed: "資料表複製已停止",+ failedMessage: "請核對執行結果後再重試。",+ noRollback: "未自動回復或清理。重試前請確認目標資料表的實際狀態。",+ completed: "已完成並提交",+ rejected: "資料庫已拒絕",+ unknown: "結果未知,陳述式可能已送達伺服器",+ notExecuted: "未執行",+ refreshFailed: "重新整理也未成功",+ close: "關閉",+ table: "資料表",+ data: "資料",+ primaryKey: "主鍵",+ index: "索引",+ comment: "註解",+ constraint: "約束",+ foreignKey: "外鍵",+ unique: "唯一約束",+ check: "CHECK 約束",+ trigger: "觸發程序",+ partitioning: "分割區結構(目標不使用分割區)",+ duplicateTarget: "多項複製指向同一目標 {name}。請修改目標名稱後繼續。",+ duplicateIndex: "多項複製會建立同名索引 {name}。請修改目標資料表名稱後繼續。",+};++export const oceanbaseCloneDialogEs = {+ invalidName: "Use un nombre de tabla normal o un nombre entre comillas dobles.",+ metadataRead: "No se pudieron leer los metadatos de la copia. No se ejecutó DDL.",+ metadataTruncated: "Los metadatos de la copia están truncados. No se ejecutó DDL.",+ currentSchema: "El esquema actual no está disponible. No se ejecutó DDL.",+ tableProperties: "Las propiedades de la tabla de origen no están disponibles. No se ejecutó DDL.",+ temporaryTable: "No se admite copiar tablas temporales. No se ejecutó DDL.",+ virtualColumns: "No se admite copiar columnas virtuales: {names}. No se ejecutó DDL.",+ sourceMetadata: "Los metadatos de origen faltan o no son accesibles. No se ejecutó DDL.",+ targetExists: "El destino ya existe: {name}. No se ejecutó DDL.",+ primaryKeyMetadata: "Las columnas, el orden o los metadatos de la clave primaria de origen son incompletos o incoherentes. No se ejecutó DDL.",+ createColumns: "No se pudieron generar las definiciones completas de columnas de OceanBase Oracle. No se ejecutó DDL.",+ primaryKeyState: "No se admite copiar claves primarias deshabilitadas, no validadas, diferibles o de estado desconocido. No se ejecutó DDL.",+ uniqueIndexMetadata: "Los metadatos del índice de la restricción única de origen no están disponibles. No se ejecutó DDL.",+ indexExists: "Los nombres de índice de destino ya existen: {names}. Elija otro nombre de tabla de destino. No se ejecutó DDL.",+ indexVisibility: "La visibilidad del índice es incompleta o ambigua: {name}. No se ejecutó DDL.",+ indexColumns: "El orden o la dirección de las columnas del índice son incompletos: {name}. No se ejecutó DDL.",+ executionFailed: "La base de datos indicó un fallo de ejecución sin más detalles.",+ title: "Confirmar copia de tablas",+ message: "Revise cada destino y la estructura que se copiará.",+ scope: "Copiar {columns} columnas, {keys} claves primarias, {indexes} índices normales y {comments} comentarios.",+ excluded: "No se copia",+ none: "Ninguno",+ details: "Ver SQL y detalles de ejecución",+ failed: "Copia de tablas detenida",+ failedMessage: "Revise el resultado antes de volver a intentarlo.",+ noRollback: "No se realizó ninguna reversión ni limpieza automática. Compruebe el destino antes de reintentar.",+ completed: "Completado y confirmado",+ rejected: "Rechazado por la base de datos",+ unknown: "Resultado desconocido; la sentencia puede haber llegado al servidor",+ notExecuted: "No ejecutado",+ refreshFailed: "La actualización también falló",+ close: "Cerrar",+ table: "Tabla",+ data: "Datos",+ primaryKey: "Clave primaria",+ index: "Índice",+ comment: "Comentario",+ constraint: "Restricción",+ foreignKey: "Clave foránea",+ unique: "Restricción única",+ check: "Restricción CHECK",+ trigger: "Disparador",+ partitioning: "Particionado (el destino no tendrá particiones)",+ duplicateTarget: "Varias copias tienen el mismo destino {name}. Cambie los nombres de destino antes de continuar.",+ duplicateIndex: "Las copias crearían el mismo índice {name}. Cambie los nombres de las tablas de destino antes de continuar.",+};++export const oceanbaseCloneDialogIt = {+ invalidName: "Usa un nome di tabella normale oppure un nome tra virgolette doppie.",+ metadataRead: "Impossibile leggere i metadati per la copia. Nessun DDL eseguito.",+ metadataTruncated: "I metadati per la copia sono troncati. Nessun DDL eseguito.",+ currentSchema: "Lo schema corrente non è disponibile. Nessun DDL eseguito.",+ tableProperties: "Le proprietà della tabella di origine non sono disponibili. Nessun DDL eseguito.",+ temporaryTable: "La copia di tabelle temporanee non è supportata. Nessun DDL eseguito.",+ virtualColumns: "La copia di colonne virtuali non è supportata: {names}. Nessun DDL eseguito.",+ sourceMetadata: "I metadati di origine sono mancanti o inaccessibili. Nessun DDL eseguito.",+ targetExists: "La destinazione esiste già: {name}. Nessun DDL eseguito.",+ primaryKeyMetadata: "Le colonne, l'ordine o i metadati della chiave primaria di origine sono incompleti o incoerenti. Nessun DDL eseguito.",+ createColumns: "Impossibile generare le definizioni complete delle colonne OceanBase Oracle. Nessun DDL eseguito.",+ primaryKeyState: "La copia di chiavi primarie disabilitate, non convalidate, differibili o di stato sconosciuto non è supportata. Nessun DDL eseguito.",+ uniqueIndexMetadata: "I metadati dell'indice del vincolo univoco di origine non sono disponibili. Nessun DDL eseguito.",+ indexExists: "I nomi degli indici di destinazione esistono già: {names}. Scegli un altro nome di tabella. Nessun DDL eseguito.",+ indexVisibility: "La visibilità dell'indice è incompleta o ambigua: {name}. Nessun DDL eseguito.",+ indexColumns: "L'ordine o la direzione delle colonne dell'indice sono incompleti: {name}. Nessun DDL eseguito.",+ executionFailed: "Il database ha segnalato un errore di esecuzione senza ulteriori dettagli.",+ title: "Conferma copia tabelle",+ message: "Verifica ogni destinazione e la struttura da copiare.",+ scope: "Copia {columns} colonne, {keys} chiavi primarie, {indexes} indici ordinari e {comments} commenti.",+ excluded: "Non copiato",+ none: "Nessuno",+ details: "Mostra SQL e dettagli di esecuzione",+ failed: "Copia tabelle interrotta",+ failedMessage: "Verifica il risultato prima di riprovare.",+ noRollback: "Non è stato eseguito alcun rollback o intervento di pulizia automatico. Controlla la destinazione prima di riprovare.",+ completed: "Completato e confermato",+ rejected: "Rifiutato dal database",+ unknown: "Risultato sconosciuto; l'istruzione potrebbe aver raggiunto il server",+ notExecuted: "Non eseguito",+ refreshFailed: "Anche l'aggiornamento è fallito",+ close: "Chiudi",+ table: "Tabella",+ data: "Dati",+ primaryKey: "Chiave primaria",+ index: "Indice",+ comment: "Commento",+ constraint: "Vincolo",+ foreignKey: "Chiave esterna",+ unique: "Vincolo univoco",+ check: "Vincolo CHECK",+ trigger: "Trigger",+ partitioning: "Partizionamento (la destinazione non sarà partizionata)",+ duplicateTarget: "Più copie hanno la stessa destinazione {name}. Modifica i nomi di destinazione prima di continuare.",+ duplicateIndex: "Le copie creerebbero lo stesso indice {name}. Modifica i nomi delle tabelle di destinazione prima di continuare.",+};++export const oceanbaseCloneDialogJa = {+ invalidName: "通常のテーブル名、または二重引用符で囲んだ名前を入力してください。",+ metadataRead: "コピーに必要なメタデータを読み取れません。DDL は実行していません。",+ metadataTruncated: "コピーに必要なメタデータが切り詰められています。DDL は実行していません。",+ currentSchema: "現在のスキーマを特定できません。DDL は実行していません。",+ tableProperties: "コピー元テーブルの属性を取得できません。DDL は実行していません。",+ temporaryTable: "一時テーブルのコピーはサポートしていません。DDL は実行していません。",+ virtualColumns: "仮想列のコピーはサポートしていません:{names}。DDL は実行していません。",+ sourceMetadata: "コピー元のメタデータがないか、アクセスできません。DDL は実行していません。",+ targetExists: "コピー先は既に存在します:{name}。DDL は実行していません。",+ primaryKeyMetadata: "コピー元の主キーの列、列順序、またはメタデータが不完全か矛盾しています。DDL は実行していません。",+ createColumns: "OceanBase Oracle の完全な列定義を生成できません。DDL は実行していません。",+ primaryKeyState: "無効、未検証、遅延可能、または状態不明の主キーはコピーできません。DDL は実行していません。",+ uniqueIndexMetadata: "コピー元の一意制約を支えるインデックスの情報を取得できません。DDL は実行していません。",+ indexExists: "コピー先のインデックス名は既に存在します:{names}。別のテーブル名を指定してください。DDL は実行していません。",+ indexVisibility: "インデックスの可視性情報が不完全か不明確です:{name}。DDL は実行していません。",+ indexColumns: "インデックスの列順序またはソート方向が不完全です:{name}。DDL は実行していません。",+ executionFailed: "データベースが実行エラーを返しました。詳細情報はありません。",+ title: "テーブルのコピーを確認",+ message: "各コピー先とコピーする構造を確認してください。",+ scope: "列 {columns} 個、主キー {keys} 個、通常のインデックス {indexes} 個、コメント {comments} 件をコピーします。",+ excluded: "コピー対象外",+ none: "なし",+ details: "SQL と実行の詳細を表示",+ failed: "テーブルのコピーを停止しました",+ failedMessage: "再試行する前に実行結果を確認してください。",+ noRollback: "自動ロールバックや削除は行っていません。再試行する前にコピー先の状態を確認してください。",+ completed: "完了・コミット済み",+ rejected: "データベースが拒否",+ unknown: "結果不明。ステートメントはサーバーに届いている可能性があります",+ notExecuted: "未実行",+ refreshFailed: "再読み込みにも失敗しました",+ close: "閉じる",+ table: "テーブル",+ data: "データ",+ primaryKey: "主キー",+ index: "インデックス",+ comment: "コメント",+ constraint: "制約",+ foreignKey: "外部キー",+ unique: "一意制約",+ check: "CHECK 制約",+ trigger: "トリガー",+ partitioning: "パーティション構造(コピー先はパーティション化されません)",+ duplicateTarget: "複数のコピー先が {name} になっています。続行する前にコピー先の名前を変更してください。",+ duplicateIndex: "複数のコピーで同名のインデックス {name} が作成されます。続行する前にコピー先テーブル名を変更してください。",+};++export const oceanbaseCloneDialogKo = {+ invalidName: "일반 테이블 이름을 입력하거나 이름을 큰따옴표로 묶으세요.",+ metadataRead: "복사에 필요한 메타데이터를 읽을 수 없습니다. DDL은 실행되지 않았습니다.",+ metadataTruncated: "복사에 필요한 메타데이터가 잘렸습니다. DDL은 실행되지 않았습니다.",+ currentSchema: "현재 스키마를 확인할 수 없습니다. DDL은 실행되지 않았습니다.",+ tableProperties: "원본 테이블 속성을 읽을 수 없습니다. DDL은 실행되지 않았습니다.",+ temporaryTable: "임시 테이블 복사는 지원하지 않습니다. DDL은 실행되지 않았습니다.",+ virtualColumns: "가상 열 복사는 지원하지 않습니다: {names}. DDL은 실행되지 않았습니다.",+ sourceMetadata: "원본 메타데이터가 없거나 접근할 수 없습니다. DDL은 실행되지 않았습니다.",+ targetExists: "대상이 이미 존재합니다: {name}. DDL은 실행되지 않았습니다.",+ primaryKeyMetadata: "원본 기본 키의 열, 순서 또는 메타데이터가 불완전하거나 일치하지 않습니다. DDL은 실행되지 않았습니다.",+ createColumns: "완전한 OceanBase Oracle 열 정의를 생성할 수 없습니다. DDL은 실행되지 않았습니다.",+ primaryKeyState: "비활성화, 미검증, 지연 가능 또는 상태를 알 수 없는 기본 키는 복사할 수 없습니다. DDL은 실행되지 않았습니다.",+ uniqueIndexMetadata: "원본 고유 제약 조건의 지원 인덱스를 확인할 수 없습니다. DDL은 실행되지 않았습니다.",+ indexExists: "대상 인덱스 이름이 이미 존재합니다: {names}. 다른 대상 테이블 이름을 선택하세요. DDL은 실행되지 않았습니다.",+ indexVisibility: "인덱스 표시 여부 정보가 불완전하거나 모호합니다: {name}. DDL은 실행되지 않았습니다.",+ indexColumns: "인덱스 열 순서 또는 정렬 방향이 불완전합니다: {name}. DDL은 실행되지 않았습니다.",+ executionFailed: "데이터베이스가 상세 정보 없이 실행 실패를 보고했습니다.",+ title: "테이블 복사 확인",+ message: "각 대상과 복사할 구조를 확인하세요.",+ scope: "열 {columns}개, 기본 키 {keys}개, 일반 인덱스 {indexes}개, 주석 {comments}개를 복사합니다.",+ excluded: "복사하지 않음",+ none: "없음",+ details: "SQL 및 실행 내역 보기",+ failed: "테이블 복사가 중단되었습니다",+ failedMessage: "다시 시도하기 전에 실행 결과를 확인하세요.",+ noRollback: "자동 롤백이나 정리는 수행되지 않았습니다. 다시 시도하기 전에 대상의 실제 상태를 확인하세요.",+ completed: "완료 및 커밋됨",+ rejected: "데이터베이스에서 거부됨",+ unknown: "결과를 알 수 없음. 구문이 서버에 도달했을 수 있습니다",+ notExecuted: "실행되지 않음",+ refreshFailed: "새로 고침도 실패했습니다",+ close: "닫기",+ table: "테이블",+ data: "데이터",+ primaryKey: "기본 키",+ index: "인덱스",+ comment: "주석",+ constraint: "제약 조건",+ foreignKey: "외래 키",+ unique: "고유 제약 조건",+ check: "CHECK 제약 조건",+ trigger: "트리거",+ partitioning: "파티션 구조 (대상은 파티션을 사용하지 않음)",+ duplicateTarget: "여러 복사가 동일한 대상 {name}을(를) 가리킵니다. 계속하기 전에 대상 이름을 변경하세요.",+ duplicateIndex: "여러 복사가 동일한 인덱스 {name}을(를) 생성합니다. 계속하기 전에 대상 테이블 이름을 변경하세요.",+};++export const oceanbaseCloneDialogPtBR = {+ invalidName: "Use um nome de tabela comum ou um nome entre aspas duplas.",+ metadataRead: "Não foi possível ler os metadados da cópia. Nenhum DDL foi executado.",+ metadataTruncated: "Os metadados da cópia foram truncados. Nenhum DDL foi executado.",+ currentSchema: "O esquema atual não está disponível. Nenhum DDL foi executado.",+ tableProperties: "As propriedades da tabela de origem não estão disponíveis. Nenhum DDL foi executado.",+ temporaryTable: "A cópia de tabelas temporárias não é suportada. Nenhum DDL foi executado.",+ virtualColumns: "A cópia de colunas virtuais não é suportada: {names}. Nenhum DDL foi executado.",+ sourceMetadata: "Os metadados de origem estão ausentes ou inacessíveis. Nenhum DDL foi executado.",+ targetExists: "O destino já existe: {name}. Nenhum DDL foi executado.",+ primaryKeyMetadata: "As colunas, a ordem ou os metadados da chave primária de origem estão incompletos ou inconsistentes. Nenhum DDL foi executado.",+ createColumns: "Não foi possível gerar as definições completas das colunas OceanBase Oracle. Nenhum DDL foi executado.",+ primaryKeyState: "A cópia de chaves primárias desativadas, não validadas, adiáveis ou com estado desconhecido não é suportada. Nenhum DDL foi executado.",+ uniqueIndexMetadata: "Os metadados do índice da restrição única de origem não estão disponíveis. Nenhum DDL foi executado.",+ indexExists: "Os nomes dos índices de destino já existem: {names}. Escolha outro nome de tabela de destino. Nenhum DDL foi executado.",+ indexVisibility: "A visibilidade do índice está incompleta ou ambígua: {name}. Nenhum DDL foi executado.",+ indexColumns: "A ordem ou a direção das colunas do índice estão incompletas: {name}. Nenhum DDL foi executado.",+ executionFailed: "O banco de dados informou uma falha de execução sem mais detalhes.",+ title: "Confirmar cópia de tabelas",+ message: "Revise cada destino e a estrutura que será copiada.",+ scope: "Copiar {columns} colunas, {keys} chaves primárias, {indexes} índices comuns e {comments} comentários.",+ excluded: "Não será copiado",+ none: "Nenhum",+ details: "Ver SQL e detalhes da execução",+ failed: "Cópia de tabelas interrompida",+ failedMessage: "Revise o resultado antes de tentar novamente.",+ noRollback: "Nenhuma reversão ou limpeza automática foi realizada. Verifique o destino antes de tentar novamente.",+ completed: "Concluído e confirmado",+ rejected: "Rejeitado pelo banco de dados",+ unknown: "Resultado desconhecido; a instrução pode ter chegado ao servidor",+ notExecuted: "Não executado",+ refreshFailed: "A atualização também falhou",+ close: "Fechar",+ table: "Tabela",+ data: "Dados",+ primaryKey: "Chave primária",+ index: "Índice",+ comment: "Comentário",+ constraint: "Restrição",+ foreignKey: "Chave estrangeira",+ unique: "Restrição única",+ check: "Restrição CHECK",+ trigger: "Gatilho",+ partitioning: "Particionamento (o destino não será particionado)",+ duplicateTarget: "Várias cópias têm o mesmo destino {name}. Altere os nomes de destino antes de continuar.",+ duplicateIndex: "As cópias criariam o mesmo índice {name}. Altere os nomes das tabelas de destino antes de continuar.",+};++export const oceanbaseCloneDialogRu = {+ invalidName: "Укажите обычное имя таблицы или заключите его в двойные кавычки.",+ metadataRead: "Не удалось прочитать метаданные для копирования. DDL не выполнялся.",+ metadataTruncated: "Метаданные для копирования усечены. DDL не выполнялся.",+ currentSchema: "Не удалось определить текущую схему. DDL не выполнялся.",+ tableProperties: "Свойства исходной таблицы недоступны. DDL не выполнялся.",+ temporaryTable: "Копирование временных таблиц не поддерживается. DDL не выполнялся.",+ virtualColumns: "Копирование виртуальных столбцов не поддерживается: {names}. DDL не выполнялся.",+ sourceMetadata: "Метаданные исходной таблицы отсутствуют или недоступны. DDL не выполнялся.",+ targetExists: "Целевой объект уже существует: {name}. DDL не выполнялся.",+ primaryKeyMetadata: "Столбцы, их порядок или метаданные исходного первичного ключа неполны либо противоречивы. DDL не выполнялся.",+ createColumns: "Не удалось сформировать полные определения столбцов OceanBase Oracle. DDL не выполнялся.",+ primaryKeyState: "Копирование отключённых, непроверенных, отложенных первичных ключей или ключей с неизвестным состоянием не поддерживается. DDL не выполнялся.",+ uniqueIndexMetadata: "Метаданные индекса исходного ограничения уникальности недоступны. DDL не выполнялся.",+ indexExists: "Имена целевых индексов уже существуют: {names}. Выберите другое имя целевой таблицы. DDL не выполнялся.",+ indexVisibility: "Сведения о видимости индекса неполны или неоднозначны: {name}. DDL не выполнялся.",+ indexColumns: "Порядок столбцов или направление сортировки индекса указаны не полностью: {name}. DDL не выполнялся.",+ executionFailed: "База данных сообщила об ошибке выполнения без дополнительных сведений.",+ title: "Подтверждение копирования таблиц",+ message: "Проверьте каждую целевую таблицу и копируемую структуру.",+ scope: "Копируются столбцы: {columns}, первичные ключи: {keys}, обычные индексы: {indexes}, комментарии: {comments}.",+ excluded: "Не копируется",+ none: "Нет",+ details: "Показать SQL и сведения о выполнении",+ failed: "Копирование таблиц остановлено",+ failedMessage: "Проверьте результат перед повторной попыткой.",+ noRollback: "Автоматический откат или очистка не выполнялись. Проверьте состояние целевой таблицы перед повторной попыткой.",+ completed: "Выполнено и зафиксировано",+ rejected: "Отклонено базой данных",+ unknown: "Результат неизвестен; команда могла поступить на сервер",+ notExecuted: "Не выполнено",+ refreshFailed: "Обновление также не удалось",+ close: "Закрыть",+ table: "Таблица",+ data: "Данные",+ primaryKey: "Первичный ключ",+ index: "Индекс",+ comment: "Комментарий",+ constraint: "Ограничение",+ foreignKey: "Внешний ключ",+ unique: "Ограничение уникальности",+ check: "Ограничение CHECK",+ trigger: "Триггер",+ partitioning: "Секционирование (целевая таблица не будет секционирована)",+ duplicateTarget: "Несколько копий имеют одну целевую таблицу {name}. Измените целевые имена перед продолжением.",+ duplicateIndex: "Копии создадут одноимённый индекс {name}. Измените имена целевых таблиц перед продолжением.",+};diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex f49e85e7fd..b023ee4547 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1,4 +1,5 @@import { sidebarMenuPtBR as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogPtBR as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { withEnglishFallback } from "./fallback";import { mongodbDatabaseDumpPtBR as mongoDump } from "./mongodbDatabaseDump";import { damengDumpPtBR as damengDump } from "./damengDump";@@ -64,6 +65,7 @@ const consul = {};export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "Gerar modelo",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 90c55056ff..745b628449 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -1,4 +1,5 @@import { sidebarMenuRu as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogRu as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { withEnglishFallback } from "./fallback";import docs from "./docs/ru";import { dataDictionaryRu as dataDictionary } from "./dataDictionaryMessages";@@ -6,6 +7,7 @@ import { meilisearchManagementRu } from "./meilisearchManagement";// Russian locale. Entries omitted here fall back to English at runtime.export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "Создать модель",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex a270aeb854..1f203036dd 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1,4 +1,5 @@import { sidebarMenuZhCN as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogZhCN as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { redisGroupingZhCN as redisGrouping } from "./redisGrouping";import { withEnglishFallback } from "./fallback";import docs from "./docs/zh-CN";@@ -9,6 +10,7 @@ import { mongodbDatabaseDumpZhCN as mongoDump } from "./mongodbDatabaseDump";import { damengDumpZhCN as damengDump } from "./damengDump";export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "生成模型",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex f51eb07cf2..19dd4b298b 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1,4 +1,5 @@import { sidebarMenuZhTW as sidebarMenu } from "./sidebarMenuMessages";+import { oceanbaseCloneDialogZhTW as oceanbaseCloneDialog } from "./oceanbaseCloneDialog";import { redisGroupingZhTW as redisGrouping } from "./redisGrouping";import { withEnglishFallback } from "./fallback";import { mongodbDatabaseDumpZhTW as mongoDump } from "./mongodbDatabaseDump";@@ -65,6 +66,7 @@ const consul = {};export default withEnglishFallback({+ oceanbaseCloneDialog,sidebarMenu,modelGeneration: {title: "產生模型",diff --git a/apps/desktop/src/lib/__tests__/database/adminSqlIdentifierQuote.spec.ts b/apps/desktop/src/lib/__tests__/database/adminSqlIdentifierQuote.spec.tsindex dd8e493382..eda275e96c 100644--- a/apps/desktop/src/lib/__tests__/database/adminSqlIdentifierQuote.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/adminSqlIdentifierQuote.spec.ts@@ -46,7 +46,9 @@ describe("admin SQL carries the connection identifier quote", () => {});it("threads the quote through copying table data", () => {- expect(treeRuntimeSource).toMatch(/buildCopyTableDataSql\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(entry\.connectionId\)/);- expect(objectBrowserSource).toMatch(/buildCopyTableDataSql\(\{[\s\S]*?identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(props\.connection\.id\)/);+ expect(treeRuntimeSource).toMatch(/identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(entry\.connectionId\)/);+ expect(treeRuntimeSource).toMatch(/buildCopyTableDataSql\(\{[\s\S]*?identifierQuote: entry\.identifierQuote/);+ expect(objectBrowserSource).toMatch(/identifierQuote: connectionStore\.connectionIdentifierQuote\?\.\(props\.connection\.id\)/);+ expect(objectBrowserSource).toMatch(/buildCopyTableDataSql\(\{[\s\S]*?identifierQuote: context\.identifierQuote/);});});diff --git a/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts b/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.tsindex 19b33e63d1..dd264fcb33 100644--- a/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/dbAdminSql.spec.ts@@ -284,6 +284,13 @@ describe("damengDuplicateTableCreateOptions", () => {});describe("buildDuplicateTableStructurePlan", () => {+ it("refuses OceanBase structure cloning when source column metadata cannot be read", async () => {+ apiMock.getColumns.mockRejectedValueOnce(new Error("source columns inaccessible"));+ apiMock.buildDuplicateTableStructureSql.mockResolvedValue('CREATE TABLE "APP"."COPY" AS SELECT * FROM "APP"."SOURCE" WHERE 1=0;');+ await expect(buildDuplicateTableStructurePlan({ connectionId: "ob-clone", database: "APP", databaseType: "oceanbase-oracle", schema: "APP", sourceName: "SOURCE", targetName: "COPY" })).rejects.toThrow("source columns inaccessible");+ expect(apiMock.buildDuplicateTableStructureSql).not.toHaveBeenCalled();+ });+it("loads Oracle metadata through the list APIs and builds a script", async () => {const columns = [{ name: "ID", data_type: "NUMBER", is_nullable: false, column_default: "42", is_primary_key: true }];const indexes = [{ name: "IDX_ORDERS_ID", columns: ["ID"], is_unique: false, is_primary: false }];diff --git a/apps/desktop/src/lib/__tests__/database/oceanbaseTableClone.spec.ts b/apps/desktop/src/lib/__tests__/database/oceanbaseTableClone.spec.tsnew file mode 100644index 0000000000..37e9c26102--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/oceanbaseTableClone.spec.ts@@ -0,0 +1,282 @@+// @vitest-environment happy-dom+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ColumnInfo, QueryResult } from "@/types/database";++const api = vi.hoisted(() => ({ getColumns: vi.fn(), listConstraints: vi.fn(), listIndexes: vi.fn(), listTriggers: vi.fn(), executeQuery: vi.fn(), buildCreateTableSql: vi.fn() }));+vi.mock("@/lib/backend/api", () => api);+import { buildDuplicateTableStructurePlan } from "@/lib/database/dbAdminSql";+import { executeOceanbaseTableClone, OceanbaseTableCloneError } from "@/lib/database/oceanbaseTableClone";++const result = (rows: unknown[][] = []): QueryResult => ({ columns: [], rows, affected_rows: 0, execution_time_ms: 0 }) as QueryResult;+const options = { connectionId: "c", database: "db", databaseType: "oceanbase-oracle" as const, schema: "Source's Schema", sourceName: "Order", targetName: '"New""Table"' };+const columns: ColumnInfo[] = [+ { name: "a", data_type: "VARCHAR2(12 BYTE)", is_nullable: false, column_default: "'a''b'", is_primary_key: true, extra: "", comment: " first 'comment' " },+ { name: "b", data_type: "NUMBER(8,-2)", is_nullable: false, column_default: "-100", is_primary_key: true, extra: "", comment: null },+ { name: 'Mixed"Case', data_type: "VARCHAR2(7 CHAR)", is_nullable: true, column_default: null, is_primary_key: false, extra: "", comment: "中文" },+];++beforeEach(() => {+ vi.resetAllMocks();+ api.getColumns.mockResolvedValue(columns);+ api.listConstraints.mockResolvedValue([+ { name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["b", "a"], enabled: true, valid: true, deferrable: false },+ { name: "FK_SOURCE", constraint_type: "FOREIGN KEY", columns: ["a"] },+ ]);+ api.listIndexes.mockResolvedValue([+ { name: "PK_SOURCE", columns: ["b", "a"], is_primary: true },+ { name: "IX_SOURCE", columns: ['Mixed"Case', "b"], index_type: "NORMAL", is_unique: false },+ { name: "IX_EXPR", columns: ["SYS_NC1"], index_type: "FUNCTION-BASED NORMAL" },+ ]);+ api.listTriggers.mockResolvedValue([{ name: "TRG_SOURCE" }]);+ api.executeQuery.mockImplementation(async (_connection, _database, sql: string) => {+ if (sql.includes("SYS_CONTEXT")) return result([[options.schema]]);+ if (sql.includes("ALL_TAB_COMMENTS")) return result([[" table's comment "]]);+ if (sql.includes("ALL_TABLES")) return result([["NO", "N"]]);+ if (sql.includes("ALL_INDEXES")) return result([["IX_SOURCE", "VISIBLE"]]);+ if (sql.includes("ALL_IND_COLUMNS"))+ return result([+ ["IX_SOURCE", 'Mixed"Case', 1, "DESC"],+ ["IX_SOURCE", "b", 2, "ASC"],+ ]);+ return result();+ });+ api.buildCreateTableSql.mockResolvedValue({ statements: ['CREATE TABLE "Target Schema"."New""Table" ("a" VARCHAR2(12 BYTE) NOT NULL, "b" NUMBER(8,-2) NOT NULL, "Mixed""Case" VARCHAR2(7 CHAR));'], warnings: [] });+});++describe("OceanBase Oracle structure clone", () => {+ it("allows a target name already used by an independently namespaced index", async () => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => {+ if (args[2].includes("ROWNUM <= 1")) return result(args[2].includes("OBJECT_TYPE <> 'INDEX'") ? [] : [[options.targetName]]);+ return original(...args);+ });+ await expect(buildDuplicateTableStructurePlan(options)).resolves.toMatchObject({ oceanbaseClone: { targetName: 'New"Table' } });+ });++ it("preserves an invisible normal index in the executable plan", async () => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => (args[2].includes("ALL_INDEXES") ? result([["IX_SOURCE", "INVISIBLE"]]) : original(...args)));+ const plan = await buildDuplicateTableStructurePlan(options);+ expect(plan.oceanbaseClone?.steps.find((step) => step.kind === "index")?.sql).toContain('("Mixed""Case" DESC, "b" ASC) INVISIBLE;');+ });++ it.each(+ [+ [],+ [["IX_SOURCE", null]],+ [["IX_SOURCE", "UNKNOWN"]],+ [+ ["IX_SOURCE", "VISIBLE"],+ ["IX_SOURCE", "INVISIBLE"],+ ],+ ].map((rows) => [rows]),+ )("refuses incomplete or ambiguous index visibility %j", async (rows) => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => (args[2].includes("ALL_INDEXES") ? result(rows) : original(...args)));+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toMatchObject({ key: "indexVisibility", values: { name: '"IX_SOURCE"' } });+ });++ it.each(["", '""', '"unfinished', "two words", "a.b", "a;drop table b"])("rejects an invalid new target %j before reading metadata", async (targetName) => {+ await expect(buildDuplicateTableStructurePlan({ ...options, targetName })).rejects.toMatchObject({ key: "invalidName" });+ expect(api.getColumns).not.toHaveBeenCalled();+ });++ it("refreshes cached source columns and comments before planning", async () => {+ const plan = await buildDuplicateTableStructurePlan({ ...options, sourceColumns: [], tableComment: "stale comment" });+ expect(api.getColumns).toHaveBeenCalledOnce();+ expect(plan.sourceColumns).toEqual(columns);+ expect(plan.sql).toContain("table''s comment");+ expect(plan.sql).not.toContain("stale comment");+ });++ it("reports partitioning as excluded", async () => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => (args[2].includes("ALL_TABLES") ? result([["YES", "N"]]) : original(...args)));+ const plan = await buildDuplicateTableStructurePlan(options);+ expect(plan.oceanbaseClone?.exclusions).toContainEqual({ kind: "partitioning" });+ });++ it.each([[["NO", "Y"]], [], [[null, "N"]]])("refuses temporary or incomplete table properties %j", async (rows) => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => (args[2].includes("ALL_TABLES") ? result(rows) : original(...args)));+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toThrow();+ expect(api.buildCreateTableSql).not.toHaveBeenCalled();+ });++ it.each([+ ["ordersCopy", "ORDERSCOPY"],+ ['"OrdersCopy"', "OrdersCopy"],+ ])("preserves metadata identities while resolving only the new target %s", async (entered, stored) => {+ const plan = await buildDuplicateTableStructurePlan({ ...options, targetName: entered });+ const request = api.buildCreateTableSql.mock.calls[0]![0];+ expect(request.tableName).toBe(stored);+ expect(request.columns.map((column: any) => column.name)).toEqual(["a", "b", 'Mixed"Case']);+ expect(plan.sourceColumns).toBe(columns);+ expect(plan.oceanbaseClone?.targetName).toBe(stored);+ expect(api.executeQuery.mock.calls.find((call) => call[2].includes("ROWNUM <= 1"))?.[2]).toContain(`OBJECT_NAME = '${stored}'`);+ expect(plan.oceanbaseClone?.steps.find((step) => step.kind === "primaryKey")?.sql).toBe(`ALTER TABLE "Source's Schema"."${stored}" ADD PRIMARY KEY ("b", "a");`);+ expect(plan.oceanbaseClone?.steps.find((step) => step.kind === "comment" && step.sql.includes('"a"'))?.sql).toContain(`"${stored}"."a"`);+ });++ it.each(["ALL_TAB_COLS", "ALL_IND_COLUMNS", "ALL_CONSTRAINTS", "ALL_INDEXES"])("rejects short truncated %s metadata even without has_more", async (dictionary) => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args: Parameters<typeof original>) => {+ if (!args[2].includes(dictionary)) return original(...args);+ const partial = dictionary === "ALL_TAB_COLS" ? result() : dictionary === "ALL_IND_COLUMNS" ? await original(...args) : result([["UQ_SOURCE", "U", "UQ_BACKING"]]);+ return { ...partial, truncated: true, has_more: false };+ });+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toMatchObject({ key: "metadataTruncated" });+ if (dictionary !== "ALL_INDEXES") expect(api.buildCreateTableSql).not.toHaveBeenCalled();+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);+ });+ it("excludes UNIQUE backing indexes and reports foreign keys missing from the constraints API", async () => {+ api.listConstraints.mockResolvedValue([+ { name: "PK_SOURCE", constraint_type: "PRIMARY KEY", columns: ["b", "a"], enabled: true, valid: true, deferrable: false },+ { name: "UQ_SOURCE", constraint_type: "UNIQUE", columns: ["a"] },+ ]);+ api.listIndexes.mockResolvedValue([+ { name: "UQ_BACKING", columns: ["a"], index_type: "NORMAL", is_unique: true },+ { name: "IX_STANDALONE", columns: ["b"], index_type: "NORMAL", is_unique: true },+ ]);+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args: Parameters<typeof original>) => {+ if (args[2].includes("ALL_INDEXES")) return result([["IX_STANDALONE", "VISIBLE"]]);+ if (args[2].includes("ALL_CONSTRAINTS"))+ return result([+ ["UQ_SOURCE", "U", "UQ_BACKING"],+ ["FK_SOURCE", "R", null],+ ]);+ if (args[2].includes("ALL_IND_COLUMNS"))+ return result([+ ["UQ_BACKING", "a", 1, "ASC"],+ ["IX_STANDALONE", "b", 1, "ASC"],+ ]);+ return original(...args);+ });+ const plan = await buildDuplicateTableStructurePlan(options);+ expect(plan.oceanbaseClone?.steps.filter((step) => step.kind === "index")).toHaveLength(1);+ expect(plan.oceanbaseClone?.exclusions).toEqual(+ expect.arrayContaining([+ { kind: "constraint", name: "UQ_SOURCE", type: "UNIQUE" },+ { kind: "constraint", name: "FK_SOURCE", type: "FOREIGN KEY" },+ ]),+ );+ expect(plan.sql).toContain("CREATE UNIQUE INDEX");+ });+ it("reads virtual-column identity from the OceanBase ALL_TAB_COLS dictionary", async () => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args: Parameters<typeof original>) => {+ if (args[2].includes("VIRTUAL_COLUMN") && args[2].includes("ALL_TAB_COLUMNS")) {+ return { ...result(), execution_error: true, error: { detail: "ORA-00904: invalid identifier 'VIRTUAL_COLUMN'" } };+ }+ return original(...args);+ });+ const plan = await buildDuplicateTableStructurePlan(options);+ expect(plan.oceanbaseClone?.targetName).toBe('New"Table');+ expect(api.executeQuery.mock.calls.find((call) => call[2].includes("VIRTUAL_COLUMN"))?.[2]).toContain("FROM SYS.ALL_TAB_COLS WHERE");+ });+ it("refuses a UNIQUE constraint whose backing index identity is unavailable", async () => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args: Parameters<typeof original>) => (args[2].includes("ALL_CONSTRAINTS") ? result([["UQ_SOURCE", "U", null]]) : original(...args)));+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toMatchObject({ key: "uniqueIndexMetadata" });+ });+ it("carries FLOAT binary precision from metadata into the CREATE request", async () => {+ api.getColumns.mockResolvedValue([...columns, { name: "measurement", data_type: "FLOAT", numeric_precision: 24, numeric_scale: null, is_nullable: true, column_default: null, is_primary_key: false, extra: "" }]);+ const plan = await buildDuplicateTableStructurePlan(options);+ const request = api.buildCreateTableSql.mock.calls[0]![0];+ expect(request.columns.find((column: any) => column.name === "measurement")).toMatchObject({ dataType: "FLOAT(24)", original: undefined });+ expect(plan.oceanbaseClone?.columnCount).toBe(columns.length + 1);+ });++ it("rejects virtual columns even when source columns are supplied without their identity", async () => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args: Parameters<typeof original>) => (args[2].includes("VIRTUAL_COLUMN") ? result([['Computed"Value']]) : original(...args)));+ await expect(buildDuplicateTableStructurePlan({ ...options, sourceColumns: columns })).rejects.toMatchObject({ key: "virtualColumns", values: { names: '"Computed""Value"' } });+ expect(api.buildCreateTableSql).not.toHaveBeenCalled();+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);+ expect(api.executeQuery.mock.calls.find((call) => call[2].includes("VIRTUAL_COLUMN"))?.[2]).toContain("OWNER = 'Source''s Schema' AND TABLE_NAME = 'Order'");+ });+ it("routes through column DDL and preserves compound key/index order, quoting and comments", async () => {+ const plan = await buildDuplicateTableStructurePlan(options);+ expect(api.buildCreateTableSql).toHaveBeenCalledWith(expect.objectContaining({ databaseType: "oceanbase-oracle", schema: options.schema, tableName: 'New"Table', indexes: [], foreignKeys: [], triggers: [] }));+ const drafts = api.buildCreateTableSql.mock.calls[0]![0].columns;+ expect(drafts.map((column: any) => [column.dataType, column.isNullable, column.defaultValue, column.isPrimaryKey])).toEqual([+ ["VARCHAR2(12 BYTE)", false, "'a''b'", false],+ ["NUMBER(8,-2)", false, "-100", false],+ ["VARCHAR2(7 CHAR)", true, "", false],+ ]);+ expect(plan.sql).toContain('ADD PRIMARY KEY ("b", "a")');+ expect(plan.sql).toContain('("Mixed""Case" DESC, "b" ASC)');+ expect(plan.sql).toContain(`COMMENT ON TABLE "Source's Schema"."New""Table" IS ' table''s comment ';`);+ expect(plan.sql).toContain(`COMMENT ON COLUMN "Source's Schema"."New""Table"."a" IS ' first ''comment'' ';`);+ expect(plan.oceanbaseClone?.exclusions).toEqual(+ expect.arrayContaining([+ { kind: "constraint", name: "FK_SOURCE", type: "FOREIGN KEY" },+ { kind: "trigger", name: "TRG_SOURCE" },+ { kind: "index", name: "IX_EXPR", type: "FUNCTION-BASED NORMAL" },+ ]),+ );+ expect(plan.sql).not.toMatch(/CTAS|SELECT \*|CREATE TRIGGER|FOREIGN KEY|PK_SOURCE|IX_SOURCE/);+ expect(api.executeQuery.mock.calls.some((call) => call[2].includes("TABLE_OWNER = 'Source''s Schema'"))).toBe(true);+ expect(api.executeQuery.mock.calls.every((call) => call[2].startsWith("SELECT "))).toBe(true);+ });++ it("resolves the current schema when the tree carries no owner", async () => {+ const plan = await buildDuplicateTableStructurePlan({ ...options, schema: undefined });+ expect(plan.oceanbaseClone?.targetSchema).toBe(options.schema);+ expect(api.getColumns).toHaveBeenCalledWith("c", "db", options.schema, "Order", undefined);+ });++ it.each(["missing table", "target conflict", "missing index direction", "truncated dictionary", "permission denied"])("refuses DDL preparation for %s", async (failure) => {+ const original = api.executeQuery.getMockImplementation()!;+ api.executeQuery.mockImplementation(async (...args) => {+ const sql = String(args[2]);+ if (failure === "permission denied") throw new Error("ORA-01031: insufficient privileges");+ if (failure === "missing table" && sql.includes("ALL_TAB_COMMENTS")) return result();+ if (failure === "target conflict" && sql.includes("ROWNUM <= 1")) return result([[options.targetName]]);+ if (failure === "missing index direction" && sql.includes("ALL_IND_COLUMNS"))+ return result([+ ["IX_SOURCE", 'Mixed"Case', 1, null],+ ["IX_SOURCE", "b", 2, "ASC"],+ ]);+ if (failure === "truncated dictionary") return { ...result(), has_more: true };+ return original(...args);+ });+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toThrow();+ expect(api.executeQuery.mock.calls.every((call) => String(call[2]).startsWith("SELECT "))).toBe(true);+ });++ it("does not invent a primary key when its ordered metadata is missing", async () => {+ api.listConstraints.mockResolvedValue([]);+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toMatchObject({ key: "primaryKeyMetadata" });+ });++ it("stops after a lost response and reports committed, unknown and unexecuted steps", async () => {+ const plan = await buildDuplicateTableStructurePlan(options);+ const execute = vi.fn().mockResolvedValueOnce(result()).mockResolvedValueOnce(result()).mockRejectedValueOnce(new Error("ORA-01031: index permission"));+ const error = await executeOceanbaseTableClone(plan.oceanbaseClone!, execute).catch((error) => error);+ expect(error).toBeInstanceOf(OceanbaseTableCloneError);+ expect(error.execution).toMatchObject({ failedPosition: 2, rejected: false });+ expect(error.execution.steps.slice(0, error.execution.failedPosition).map((step: { kind: string }) => step.kind)).toEqual(["table", "primaryKey"]);+ expect(error.execution.steps.slice(error.execution.failedPosition + 1).every((step: { kind: string }) => step.kind === "comment")).toBe(true);+ expect(error.execution.cause.message).toBe("ORA-01031: index permission");+ expect(execute).toHaveBeenCalledTimes(3);+ expect(execute.mock.calls.every((call) => !call[0].endsWith(";"))).toBe(true);+ });++ it("does not recommend deleting an existing target when CREATE fails or is unconfirmed", async () => {+ const plan = await buildDuplicateTableStructurePlan(options);+ const execute = vi.fn().mockResolvedValue({ ...result(), execution_error: true, error: { detail: "ORA-00955: name is already used" } });+ const error = await executeOceanbaseTableClone(plan.oceanbaseClone!, execute).catch((error) => error);+ expect(error.message).toContain("ORA-00955: name is already used");+ expect(error.execution).toMatchObject({ failedPosition: 0, rejected: true });+ expect(error.message).not.toContain("DROP TABLE");+ expect(execute).toHaveBeenCalledTimes(1);+ });++ it("preserves backend metadata error details before generating DDL", async () => {+ api.executeQuery.mockResolvedValue({ ...result(), execution_error: true, error: { detail: "ORA-01031: metadata permission" } });+ await expect(buildDuplicateTableStructurePlan(options)).rejects.toThrow("ORA-01031: metadata permission");+ expect(api.buildCreateTableSql).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/__tests__/table/oracleColumnFidelity.spec.ts b/apps/desktop/src/lib/__tests__/table/oracleColumnFidelity.spec.tsnew file mode 100644index 0000000000..f3f52cb65d--- /dev/null+++ b/apps/desktop/src/lib/__tests__/table/oracleColumnFidelity.spec.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { combineDataTypeForDatabase, createColumnDrafts, createCopiedColumnDrafts, defaultNewColumnDataType, getDataTypeOptions, getDefaultLengthForType, isDataTypeLengthDisabled } from "@/lib/table/tableStructureEditorState";+import type { ColumnInfo } from "@/types/database";++describe.each(["oracle", "oceanbase-oracle"] as const)("%s numeric column fidelity", (databaseType) => {+ it.each([+ ["FLOAT", 63, null, "FLOAT(63)"],+ ["NUMBER", null, -2, "NUMBER(*,-2)"],+ ["NUMBER", 12, -2, "NUMBER(12,-2)"],+ ["NUMBER", null, 3, "NUMBER(*,3)"],+ ["NUMBER", null, 0, "NUMBER(*,0)"],+ ["NUMBER", 12, 0, "NUMBER(12,0)"],+ ["NUMBER", 12, null, "NUMBER(12)"],+ ["NUMBER", null, null, "NUMBER"],+ ["FLOAT", null, null, "FLOAT"],+ ["NUMBER(9,-3)", 9, -3, "NUMBER(9,-3)"],+ ["NUMBER(9,-3)", 12, 2, "NUMBER(9,-3)"],+ ])("retains %s precision %s and scale %s in edit and copy drafts", (dataType, precision, scale, expected) => {+ const metadata: ColumnInfo = {+ name: "AMOUNT",+ data_type: dataType as string,+ numeric_precision: precision as number | null,+ numeric_scale: scale as number | null,+ is_nullable: true,+ is_primary_key: false,+ column_default: null,+ extra: null,+ };+ const draft = createColumnDrafts([metadata], databaseType)[0];+ draft.comment = "updated comment";+ expect(draft.dataType).toBe(expected);+ expect(draft.original?.data_type).toBe(expected);+ expect(createCopiedColumnDrafts([metadata], databaseType, () => "copied")[0].dataType).toBe(expected);+ });++ it("allows editing FLOAT binary precision", () => {+ expect(isDataTypeLengthDisabled(databaseType, "FLOAT")).toBe(false);+ });++ it("selects FLOAT without a MySQL precision and scale default", () => {+ expect(getDefaultLengthForType(databaseType, "FLOAT")).toBe("");+ expect(combineDataTypeForDatabase(databaseType, "FLOAT", getDefaultLengthForType(databaseType, "FLOAT"))).toBe("FLOAT");+ expect(combineDataTypeForDatabase(databaseType, "FLOAT", "63")).toBe("FLOAT(63)");+ });+});++it("keeps MySQL FLOAT defaults and Dameng FLOAT input behavior", () => {+ expect(getDefaultLengthForType("mysql", "FLOAT")).toBe("10,2");+ expect(combineDataTypeForDatabase("mysql", "FLOAT", "10,2")).toBe("FLOAT(10,2)");+ expect(isDataTypeLengthDisabled("dameng", "FLOAT")).toBe(true);+});++describe("OceanBase Oracle built-in type recommendations", () => {+ it.each(["nclob", "long", "long raw", "bfile", "boolean", "vector"])("does not recommend %s rejected by OceanBase 4.2.5.7, while retaining Oracle's list", (type) => {+ expect(getDataTypeOptions("oceanbase-oracle")).not.toContain(type);+ expect(getDataTypeOptions("oracle")).toContain(type);+ });++ it("retains supported extended types and the existing default column type", () => {+ expect(getDataTypeOptions("oceanbase-oracle")).toEqual(expect.arrayContaining(["float", "json", "xmltype", "sdo_geometry", "rowid", "urowid"]));+ expect(defaultNewColumnDataType("oceanbase-oracle")).toBe("clob");+ expect(defaultNewColumnDataType("oracle")).toBe("clob");+ });++ it("preserves existing non-recommended types in edit and copy drafts", () => {+ const column: ColumnInfo = { name: "EXISTING_VALUE", data_type: "VECTOR(3, FLOAT32)", is_nullable: true, is_primary_key: false, column_default: null, extra: null };+ expect(createColumnDrafts([column], "oceanbase-oracle")[0].dataType).toBe(column.data_type);+ expect(createCopiedColumnDrafts([column], "oceanbase-oracle", () => "copy")[0].dataType).toBe(column.data_type);+ });+});diff --git a/apps/desktop/src/lib/database/dbAdminSql.ts b/apps/desktop/src/lib/database/dbAdminSql.tsindex c2f4a19cd9..297d778293 100644--- a/apps/desktop/src/lib/database/dbAdminSql.ts+++ b/apps/desktop/src/lib/database/dbAdminSql.ts@@ -2,6 +2,7 @@ import type { ColumnInfo, ConnectionConfig, DatabaseObjectType, DatabaseType, Foimport * as api from "@/lib/backend/api";import { createColumnDrafts, createForeignKeyDrafts, createIndexDrafts, createTriggerDrafts } from "@/lib/table/tableStructureEditorState";import type { BuildTableStructureChangeSqlOptions } from "@/lib/table/tableStructureEditorSql";+import { buildOceanbaseTableClone, type OceanbaseTableClone } from "./oceanbaseTableClone";export interface DropObjectSqlOptions {databaseType?: DatabaseType;@@ -106,6 +107,7 @@ export interface DuplicateTableStructurePlan {sql: string;sourceColumns?: ColumnInfo[];executeAsScript: boolean;+ oceanbaseClone?: OceanbaseTableClone;}export function collectDuplicateTableColumnComments(columns: readonly Pick<ColumnInfo, "name" | "comment">[]): Array<{ name: string; comment: string }> {@@ -242,6 +244,7 @@ export function sqlServerClonePrimaryKeyConstraintName(indexes: IndexInfo[], tar}export async function buildDuplicateTableStructurePlan(options: DuplicateTableStructurePlanOptions): Promise<DuplicateTableStructurePlan> {+ if (options.databaseType === "oceanbase-oracle") return buildOceanbaseTableClone(options);if (options.databaseType === "oracle") {const columnsPromise = options.sourceColumns ? Promise.resolve(options.sourceColumns) : api.getColumns(options.connectionId, options.database, options.schema || "", options.sourceName, options.catalog);const tableCommentPromise =diff --git a/apps/desktop/src/lib/database/oceanbaseTableClone.ts b/apps/desktop/src/lib/database/oceanbaseTableClone.tsnew file mode 100644index 0000000000..97b58d57ce--- /dev/null+++ b/apps/desktop/src/lib/database/oceanbaseTableClone.ts@@ -0,0 +1,203 @@+import * as api from "@/lib/backend/api";+import { createColumnDrafts } from "@/lib/table/tableStructureEditorState";+import type { QueryResult } from "@/types/database";+import type { DuplicateTableStructurePlan, DuplicateTableStructurePlanOptions } from "./dbAdminSql";++export interface OceanbaseTableClone {+ targetSchema: string;+ targetName: string;+ columnCount: number;+ indexNames: string[];+ exclusions: Array<{ kind: "constraint" | "partitioning" | "trigger" | "index"; name?: string; type?: string }>;+ steps: Array<{ kind: "table" | "primaryKey" | "index" | "comment" | "data"; name: string; sql: string }>;+}++const ident = (name: string) => `"${name.replace(/"/g, '""')}"`;+const literal = (value: string) => `'${value.replace(/'/g, "''")}'`;++export class OceanbaseCloneValidationError extends Error {+ constructor(+ readonly key: string,+ readonly values: Record<string, string> = {},+ ) {+ super(key);+ }+}++export function oceanbaseCloneTargetName(input: string): string {+ const name = input.trim();+ if (/^[A-Za-z][A-Za-z0-9_$#]*$/.test(name)) return name.toUpperCase();+ if (/^"(?:[^"]|"")+"$/.test(name)) return name.slice(1, -1).replace(/""/g, '"');+ throw new OceanbaseCloneValidationError("invalidName");+}++function cloneIndexName(table: string, position: number): string {+ const prefix = table.replace(/[^A-Za-z0-9_$#]/g, "_").toUpperCase() || "TABLE";+ const suffix = `_IDX${position + 1}`;+ return `${prefix.slice(0, 30 - suffix.length)}${suffix}`;+}++/** Clone only the supported logical structure; every dictionary read must succeed before DDL. */+export async function buildOceanbaseTableClone(options: DuplicateTableStructurePlanOptions): Promise<DuplicateTableStructurePlan> {+ let sourceSchema = options.schema || "";+ const query = async (sql: string) => {+ const result = await api.executeQuery(options.connectionId, options.database, sql, sourceSchema, undefined, { catalog: options.catalog, maxRows: 10001 });+ if (result.execution_error) throw result.error?.detail ? new Error(result.error.detail) : new OceanbaseCloneValidationError("metadataRead");+ if (result.truncated === true || result.rows.length >= 10001 || result.has_more) throw new OceanbaseCloneValidationError("metadataTruncated");+ return result.rows;+ };+ if (!sourceSchema) {+ const current = await query("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL");+ if (current.length !== 1 || typeof current[0]?.[0] !== "string" || !current[0][0]) throw new OceanbaseCloneValidationError("currentSchema");+ sourceSchema = current[0][0];+ }+ const targetSchema = sourceSchema;+ const targetName = oceanbaseCloneTargetName(options.targetName);+ const where = `OWNER = ${literal(sourceSchema)} AND TABLE_NAME = ${literal(options.sourceName)}`;+ const columns = await api.getColumns(options.connectionId, options.database, sourceSchema, options.sourceName, options.catalog);+ const [constraints, indexes, triggers, comments, directions, conflicts, virtualColumns, excludedConstraints, tableFlags] = await Promise.all([+ api.listConstraints(options.connectionId, options.database, sourceSchema, options.sourceName, options.catalog),+ api.listIndexes(options.connectionId, options.database, sourceSchema, options.sourceName, options.catalog),+ api.listTriggers(options.connectionId, options.database, sourceSchema, options.sourceName, options.catalog),+ query(`SELECT COMMENTS FROM SYS.ALL_TAB_COMMENTS WHERE ${where} AND TABLE_TYPE = 'TABLE'`),+ query(`SELECT INDEX_NAME, COLUMN_NAME, COLUMN_POSITION, DESCEND FROM SYS.ALL_IND_COLUMNS WHERE TABLE_OWNER = ${literal(sourceSchema)} AND TABLE_NAME = ${literal(options.sourceName)} ORDER BY INDEX_NAME, COLUMN_POSITION`),+ query(`SELECT OBJECT_NAME FROM SYS.ALL_OBJECTS WHERE OWNER = ${literal(targetSchema)} AND OBJECT_NAME = ${literal(targetName)} AND OBJECT_TYPE <> 'INDEX' AND ROWNUM <= 1`),+ query(`SELECT COLUMN_NAME FROM SYS.ALL_TAB_COLS WHERE ${where} AND VIRTUAL_COLUMN = 'YES'`),+ query(`SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, INDEX_NAME FROM SYS.ALL_CONSTRAINTS WHERE ${where} AND CONSTRAINT_TYPE IN ('U', 'R')`),+ query(`SELECT PARTITIONED, TEMPORARY FROM SYS.ALL_TABLES WHERE ${where}`),+ ]);+ if (tableFlags.length !== 1 || !["YES", "NO"].includes(String(tableFlags[0]?.[0])) || !["Y", "N"].includes(String(tableFlags[0]?.[1]))) throw new OceanbaseCloneValidationError("tableProperties");+ if (tableFlags[0]![1] === "Y") throw new OceanbaseCloneValidationError("temporaryTable");+ if (virtualColumns.length) throw new OceanbaseCloneValidationError("virtualColumns", { names: virtualColumns.map((row) => ident(String(row[0]))).join(", ") });+ if (!columns.length || comments.length !== 1) throw new OceanbaseCloneValidationError("sourceMetadata");+ if (conflicts.length) throw new OceanbaseCloneValidationError("targetExists", { name: `${ident(targetSchema)}.${ident(targetName)}` });+ const primaryKeys = constraints.filter((constraint) => constraint.constraint_type === "PRIMARY KEY");+ if (primaryKeys.length > 1 || (columns.some((column) => column.is_primary_key) && primaryKeys.length !== 1)) {+ throw new OceanbaseCloneValidationError("primaryKeyMetadata");+ }+ const target = `${ident(targetSchema)}.${ident(targetName)}`;+ const result = await api.buildCreateTableSql({+ databaseType: "oceanbase-oracle",+ schema: targetSchema,+ tableName: targetName,+ columns: createColumnDrafts(columns, "oceanbase-oracle").map((column, index) => ({+ ...column,+ id: `clone:column:${index}`,+ original: undefined,+ originalPosition: undefined,+ isPrimaryKey: false,+ comment: "",+ })),+ indexes: [],+ foreignKeys: [],+ triggers: [],+ });+ if (result.warnings.length || result.statements.length !== 1) throw result.warnings.length ? new Error(result.warnings.join("\n")) : new OceanbaseCloneValidationError("createColumns");+ const steps: OceanbaseTableClone["steps"] = [{ kind: "table", name: target, sql: result.statements[0]! }];+ for (const primaryKey of primaryKeys) {+ if (!primaryKey.columns.length || primaryKey.columns.some((name) => !columns.some((column) => column.name === name))) throw new OceanbaseCloneValidationError("primaryKeyMetadata");+ if (primaryKey.enabled !== true || primaryKey.valid !== true || primaryKey.deferrable !== false) throw new OceanbaseCloneValidationError("primaryKeyState");+ const markedColumns = columns.filter((column) => column.is_primary_key).map((column) => column.name);+ if (new Set(primaryKey.columns).size !== primaryKey.columns.length || markedColumns.length !== primaryKey.columns.length || markedColumns.some((name) => !primaryKey.columns.includes(name))) throw new OceanbaseCloneValidationError("primaryKeyMetadata");+ const sql = `ALTER TABLE ${target} ADD PRIMARY KEY (${primaryKey.columns.map(ident).join(", ")});`;+ steps.push({ kind: "primaryKey", name: primaryKey.columns.map(ident).join(", "), sql });+ }+ const exclusions: OceanbaseTableClone["exclusions"] = constraints.filter((constraint) => constraint.constraint_type !== "PRIMARY KEY").map((constraint) => ({ kind: "constraint", name: constraint.name, type: constraint.constraint_type }));+ if (tableFlags[0]![0] === "YES") exclusions.push({ kind: "partitioning" });+ const uniqueConstraintIndexes = new Set<string>();+ if (constraints.some((constraint) => constraint.constraint_type === "UNIQUE" && !excludedConstraints.some((row) => row[0] === constraint.name && row[1] === "U"))) throw new OceanbaseCloneValidationError("uniqueIndexMetadata");+ for (const row of excludedConstraints) {+ if (row[1] === "U") {+ if (typeof row[2] !== "string" || !row[2]) throw new OceanbaseCloneValidationError("uniqueIndexMetadata");+ uniqueConstraintIndexes.add(row[2]);+ }+ if (!exclusions.some((item) => item.kind === "constraint" && item.name === row[0])) exclusions.push({ kind: "constraint", name: String(row[0]), type: row[1] === "U" ? "UNIQUE" : "FOREIGN KEY" });+ }+ exclusions.push(...triggers.map((trigger) => ({ kind: "trigger" as const, name: trigger.name })));+ const columnNames = new Set(columns.map((column) => column.name));+ const normalIndexes = indexes.filter((index) => {+ if (index.is_primary || uniqueConstraintIndexes.has(index.name)) return false;+ if (index.index_type?.toUpperCase() !== "NORMAL" || index.key_is_expression?.some(Boolean)) {+ exclusions.push({ kind: "index", name: index.name, type: index.index_type ?? undefined });+ return false;+ }+ return true;+ });+ const newIndexNames = normalIndexes.map((_, index) => cloneIndexName(targetName, index));+ const visibility = normalIndexes.length ? await query(`SELECT INDEX_NAME, VISIBILITY FROM SYS.ALL_INDEXES WHERE TABLE_OWNER = ${literal(sourceSchema)} AND TABLE_NAME = ${literal(options.sourceName)}`) : [];+ if (newIndexNames.length) {+ const taken = await query(`SELECT OBJECT_NAME FROM SYS.ALL_OBJECTS WHERE OWNER = ${literal(targetSchema)} AND OBJECT_TYPE = 'INDEX' AND OBJECT_NAME IN (${newIndexNames.map(literal).join(", ")})`);+ if (taken.length) throw new OceanbaseCloneValidationError("indexExists", { names: taken.map((row) => ident(String(row[0]))).join(", ") });+ }+ normalIndexes.forEach((index, position) => {+ const indexVisibility = visibility.filter((row) => row[0] === index.name);+ if (indexVisibility.length !== 1 || !["VISIBLE", "INVISIBLE"].includes(String(indexVisibility[0]?.[1]))) throw new OceanbaseCloneValidationError("indexVisibility", { name: ident(index.name) });+ const keys = directions.filter((row) => row[0] === index.name);+ if (!keys.length || keys.length !== index.columns.length || keys.some((row, keyPosition) => Number(row[2]) !== keyPosition + 1 || row[1] !== index.columns[keyPosition] || !columnNames.has(String(row[1])) || !["ASC", "DESC"].includes(String(row[3])))) {+ throw new OceanbaseCloneValidationError("indexColumns", { name: ident(index.name) });+ }+ const name = `${ident(targetSchema)}.${ident(newIndexNames[position]!)}`;+ steps.push({ kind: "index", name, sql: `CREATE ${index.is_unique ? "UNIQUE " : ""}INDEX ${name} ON ${target} (${keys.map((row) => `${ident(String(row[1]))} ${row[3]}`).join(", ")})${indexVisibility[0]![1] === "INVISIBLE" ? " INVISIBLE" : ""};` });+ });+ const tableComment = comments[0]![0];+ if (tableComment != null) steps.push({ kind: "comment", name: target, sql: `COMMENT ON TABLE ${target} IS ${literal(String(tableComment))};` });+ for (const column of columns) {+ if (column.comment != null) steps.push({ kind: "comment", name: `${target}.${ident(column.name)}`, sql: `COMMENT ON COLUMN ${target}.${ident(column.name)} IS ${literal(column.comment)};` });+ }+ return { sql: steps.map((step) => step.sql).join("\n"), sourceColumns: columns, executeAsScript: false, oceanbaseClone: { targetSchema, targetName, columnCount: columns.length, indexNames: newIndexNames, exclusions, steps } };+}++export class OceanbaseTableCloneError extends Error {+ constructor(+ message: string,+ readonly targetSchema: string,+ readonly targetName: string,+ readonly execution?: { steps: OceanbaseTableClone["steps"]; failedPosition: number; rejected: boolean; notExecuted?: boolean; cause: unknown },+ ) {+ super(message);+ }+}++/** OB DDL commits independently. Stop at the first failure and preserve an actionable ledger. */+export async function executeOceanbaseTableClone(clone: OceanbaseTableClone, execute: (sql: string) => Promise<QueryResult>): Promise<QueryResult> {+ let result: QueryResult | undefined;+ for (const [position, step] of clone.steps.entries()) {+ let rejected = false;+ try {+ result = await execute(step.sql.replace(/;\s*$/, ""));+ if (result.execution_error) {+ rejected = true;+ throw result.error?.detail ? new Error(result.error.detail) : new OceanbaseCloneValidationError("executionFailed");+ }+ } catch (error) {+ throw new OceanbaseTableCloneError(error instanceof Error ? error.message : String(error), clone.targetSchema, clone.targetName, { steps: clone.steps, failedPosition: position, rejected, cause: error });+ }+ }+ return result!;+}++/** Called only after the structure has committed and data-copy production safety is confirmed. */+export async function executeOceanbaseTableCloneData(clone: OceanbaseTableClone, sql: string, execute: (sql: string) => Promise<QueryResult>): Promise<QueryResult> {+ const name = `${ident(clone.targetSchema)}.${ident(clone.targetName)}`;+ const step: OceanbaseTableClone["steps"][number] = { kind: "data", name, sql };+ try {+ return await executeOceanbaseTableClone({ ...clone, steps: [step] }, execute);+ } catch (error) {+ if (error instanceof OceanbaseTableCloneError && error.execution) {+ throw new OceanbaseTableCloneError(error.message, clone.targetSchema, clone.targetName, { ...error.execution, steps: [...clone.steps, step], failedPosition: clone.steps.length });+ }+ throw error;+ }+}++/** The structure committed, but preparation/protection failed before data execution. */+export function oceanbaseCloneDataPreparationError(clone: OceanbaseTableClone, cause: unknown): OceanbaseTableCloneError {+ const name = `${ident(clone.targetSchema)}.${ident(clone.targetName)}`;+ return new OceanbaseTableCloneError(cause instanceof Error ? cause.message : String(cause), clone.targetSchema, clone.targetName, {+ steps: [...clone.steps, { kind: "data", name, sql: "" }],+ failedPosition: clone.steps.length,+ rejected: false,+ notExecuted: true,+ cause,+ });+}diff --git a/apps/desktop/src/lib/table/tableStructureEditorState.ts b/apps/desktop/src/lib/table/tableStructureEditorState.tsindex 15d996da2d..a81cb8f42d 100644--- a/apps/desktop/src/lib/table/tableStructureEditorState.ts+++ b/apps/desktop/src/lib/table/tableStructureEditorState.ts@@ -352,6 +352,31 @@ export const DATA_TYPE_OPTIONS: Record<string, string[]> = {"xmltype","sdo_geometry",],+ "oceanbase-oracle": [+ "number",+ "integer",+ "float",+ "binary_float",+ "binary_double",+ "char",+ "nchar",+ "varchar2",+ "nvarchar2",+ "clob",+ "date",+ "timestamp",+ "timestamp with time zone",+ "timestamp with local time zone",+ "interval year to month",+ "interval day to second",+ "raw",+ "blob",+ "json",+ "rowid",+ "urowid",+ "xmltype",+ "sdo_geometry",+ ],dameng: ["number","numeric",@@ -567,7 +592,6 @@ const DATA_TYPE_OPTION_ALIASES: Partial<Record<DatabaseType, string>> = {vastbase: "postgres",kingbase: "postgres",firebird: "postgres",- "oceanbase-oracle": "oracle",iris: "oracle",yashandb: "oracle",rqlite: "sqlite",@@ -1049,6 +1073,15 @@ function columnDataTypeForEditor(column: ColumnInfo, databaseType?: DatabaseTypeconst baseType = parsed.baseType.trim().replace(/\s+/g, " ");const normalized = baseType.toLowerCase();+ if (databaseType === "oracle" || databaseType === "oceanbase-oracle") {+ const precision = Number.isInteger(column.numeric_precision) && Number(column.numeric_precision) > 0 ? String(column.numeric_precision) : undefined;+ if (normalized === "float" && precision) return combineDataTypeForDatabase(databaseType, baseType, precision);+ if (normalized === "number") {+ const scale = Number.isInteger(column.numeric_scale) ? String(column.numeric_scale) : undefined;+ if (scale !== undefined && (precision || column.numeric_precision == null)) return combineDataTypeForDatabase(databaseType, baseType, `${precision ?? "*"},${scale}`);+ if (precision) return combineDataTypeForDatabase(databaseType, baseType, precision);+ }+ }if (CHARACTER_LENGTH_METADATA_TYPES.has(normalized) && Number.isInteger(column.character_maximum_length) && Number(column.character_maximum_length) > 0) {return combineDataTypeForDatabase(databaseType, baseType, String(column.character_maximum_length));}@@ -1729,6 +1762,7 @@ export interface DataTypeDefaultOptions {export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseType: string, options: DataTypeDefaultOptions = {}): string {const key = baseType.trim().toLowerCase();+ if ((_dbType === "oracle" || _dbType === "oceanbase-oracle") && key === "float") return "";if (_dbType === "duckdb" && (key === "float" || isDataTypeLengthDisabled(_dbType, baseType))) return "";if (_dbType === "mysql" && options.omitMysqlDeprecatedDefaults && isMysqlDeprecatedDefaultParameterType(key)) return "";if (_dbType === "sqlite" || _dbType === "rqlite" || _dbType === "turso") {@@ -1820,6 +1854,7 @@ export function isDataTypeLengthDisabled(_dbType: DatabaseType | undefined, base// placement; a generic TYPE(length) editor would emit invalid DDL for them.return key.endsWith("[]") || key.startsWith("interval ") || XUGU_TYPE_LENGTH_DISABLES.has(key);} else if (isOracleLikeStructureType(_dbType)) {+ if ((_dbType === "oracle" || _dbType === "oceanbase-oracle") && key === "float") return false;// Dameng/Oracle integer aliases have fixed precision; MySQL-style display widths generate invalid DDL.return ORACLE_LIKE_TYPE_LENGTH_DISABLES.includes(key);} else if (_dbType === "sqlserver") {diff --git a/crates/dbx-core/src/data/data_compare.rs b/crates/dbx-core/src/data/data_compare.rsindex d746ae9619..21581e3917 100644--- a/crates/dbx-core/src/data/data_compare.rs+++ b/crates/dbx-core/src/data/data_compare.rs@@ -12,7 +12,8 @@ use crate::query::{execute_sql_statement_with_options, QueryExecutionOptions};use crate::schema::get_columns_core;use crate::sql_dialect::{build_count_table_sql, build_iris_table_select_sql, firebird_rows_clause, pagination_strategy,- qualified_table_name, quote_table_identifier, PaginationContext, TablePaginationStrategy,+ qualified_table_name, quote_iris_identifier, quote_table_identifier, table_data_qualified_table_name,+ PaginationContext, TablePaginationStrategy,};use crate::transfer::{generate_comment_ddl, generate_create_table_ddl};@@ -1148,32 +1149,35 @@ fn build_data_compare_select_sql(row_limit: usize,offset: usize,) -> String {- let table = qualified_table_name(Some(database_type), Some(schema), table_name);+ let table = if database_type == DatabaseType::Iris {+ table_data_qualified_table_name(Some(database_type), Some(schema), table_name, None)+ } else {+ qualified_table_name(Some(database_type), Some(schema), table_name)+ };+ let quote_column = |column: &str| {+ if database_type == DatabaseType::Iris {+ quote_iris_identifier(column, None)+ } else {+ quote_table_identifier(Some(database_type), column)+ }+ };let select_columns = if columns.is_empty() {"*".to_string()} else {- columns.iter().map(|column| quote_table_identifier(Some(database_type), column)).collect::<Vec<_>>().join(", ")+ columns.iter().map(|column| quote_column(column)).collect::<Vec<_>>().join(", ")};let order_by = if key_columns.is_empty() {String::new()} else {format!(" ORDER BY {}",- key_columns- .iter()- .map(|column| format!("{} ASC", quote_table_identifier(Some(database_type), column)))- .collect::<Vec<_>>()- .join(", ")+ key_columns.iter().map(|column| format!("{} ASC", quote_column(column))).collect::<Vec<_>>().join(", "))};let order_expression = if key_columns.is_empty() {"(SELECT NULL)".to_string()} else {- key_columns- .iter()- .map(|column| format!("{} ASC", quote_table_identifier(Some(database_type), column)))- .collect::<Vec<_>>()- .join(", ")+ key_columns.iter().map(|column| format!("{} ASC", quote_column(column))).collect::<Vec<_>>().join(", ")};match pagination_strategy(Some(database_type), PaginationContext::BoundedRead) {@@ -2964,7 +2968,55 @@ mod tests {25,50,),- "SELECT * FROM (SELECT TOP 75 \"ID\", \"NAME\" FROM \"APP\".\"USERS\" ORDER BY \"ID\" ASC) WHERE %VID > 50"+ "SELECT * FROM (SELECT TOP 75 ID, NAME FROM APP.USERS ORDER BY ID ASC) WHERE %VID > 50"+ );+ }++ #[test]+ fn builds_backend_table_select_sql_for_iris_first_page() {+ assert_eq!(+ build_data_compare_select_sql(+ DatabaseType::Iris,+ "SQLUser",+ "Users",+ &["ID".to_string(), "Name".to_string()],+ &["ID".to_string()],+ 25,+ 0,+ ),+ "SELECT TOP 25 ID, Name FROM SQLUser.Users ORDER BY ID ASC"+ );+ }++ #[test]+ fn builds_backend_table_select_sql_for_iris_delimited_names() {+ assert_eq!(+ build_data_compare_select_sql(+ DatabaseType::Iris,+ "My Schema",+ "User\"Events",+ &["Event ID".to_string(), "User\"Name".to_string()],+ &["Event ID".to_string(), "User\"Name".to_string()],+ 25,+ 50,+ ),+ "SELECT * FROM (SELECT TOP 75 \"Event ID\", \"User\"\"Name\" FROM \"My Schema\".\"User\"\"Events\" ORDER BY \"Event ID\" ASC, \"User\"\"Name\" ASC) WHERE %VID > 50"+ );+ }++ #[test]+ fn builds_backend_table_select_sql_for_jdbc_without_schema_qualification() {+ assert_eq!(+ build_data_compare_select_sql(+ DatabaseType::Jdbc,+ "APP",+ "USERS",+ &["ID".to_string()],+ &["ID".to_string()],+ 25,+ 0,+ ),+ "SELECT ID FROM USERS ORDER BY ID ASC;");}diff --git a/crates/dbx-plugin-runtime/src/plugins.rs b/crates/dbx-plugin-runtime/src/plugins.rsindex d6d1ba72e4..6eca31b329 100644--- a/crates/dbx-plugin-runtime/src/plugins.rs+++ b/crates/dbx-plugin-runtime/src/plugins.rs@@ -790,12 +790,14 @@ for line in sys.stdin:request = json.loads(line)params = request.get('params', {})if request['method'] == 'cancelStatement':- with open(os.path.join(root, 'cancelled'), 'w') as out:+ with open(os.path.join(root, 'cancelled.tmp'), 'w') as out:out.write(params.get('cancelToken', ''))+ os.replace(os.path.join(root, 'cancelled.tmp'), os.path.join(root, 'cancelled'))print(json.dumps({'id': request['id'], 'result': {'cancelled': True}}), flush=True)elif request['method'] == 'executeQuery' and params.get('sql') == 'slow':- with open(os.path.join(root, 'running'), 'w') as out:+ with open(os.path.join(root, 'running.tmp'), 'w') as out:out.write(params.get('cancelToken', ''))+ os.replace(os.path.join(root, 'running.tmp'), os.path.join(root, 'running'))else:print(json.dumps({'id': request['id'], 'result': {'token': params.get('cancelToken')}}), flush=True)"#,diff --git a/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs b/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rsindex 7e3d924ba3..bf8fecc0e1 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/column_alter.rs@@ -160,7 +160,12 @@ pub fn build_single_column_alter_sql(options: SingleColumnAlterSqlOptions) -> Ta} else if options.database_type == Some(crate::models::connection::DatabaseType::Xugu) {statements.extend(build_xugu_existing_column_sql(&table, &options.column));} else {- statements.extend(build_oracle_like_existing_column_sql(dialect, &table, &options.column))+ statements.extend(build_oracle_like_existing_column_sql(+ dialect,+ &table,+ &options.column,+ options.database_type,+ ))}}StructureDialect::SapHana => statements.extend(build_saphana_existing_column_sql(&table, &options.column)),@@ -485,12 +490,12 @@ pub(super) fn build_mysql_existing_column_sql(pub(super) fn build_mysql_existing_column_clause(column: &EditableStructureColumn, position_clause: &str) -> String {let original_name = column.original.as_ref().map(|original| original.name.as_str()).unwrap_or(&column.name);let operation = if column.name == original_name {- format!("MODIFY COLUMN {}", column_definition(StructureDialect::Mysql, column))+ format!("MODIFY COLUMN {}", column_definition(StructureDialect::Mysql, column, None))} else {format!("CHANGE COLUMN {} {}",quote_ident(StructureDialect::Mysql, original_name),- column_definition(StructureDialect::Mysql, column)+ column_definition(StructureDialect::Mysql, column, None))};format!("{operation}{position_clause}")@@ -501,7 +506,7 @@ pub(super) fn build_transwarp_existing_column_clause(column: &EditableStructureCformat!("CHANGE {} {}",quote_ident(StructureDialect::Mysql, original_name),- column_definition(StructureDialect::Mysql, column)+ column_definition(StructureDialect::Mysql, column, None))}@@ -533,7 +538,7 @@ pub(super) fn build_doris_existing_column_sql(if type_changed || nullable_changed || default_changed || comment_changed || !position_clause.is_empty() {statements.push(format!("ALTER TABLE {table} MODIFY COLUMN {}{position_clause};",- column_definition(StructureDialect::Doris, ¤t_column)+ column_definition(StructureDialect::Doris, ¤t_column, None)));}@@ -569,7 +574,7 @@ fn build_postgres_like_existing_column_sql(let type_changed = column.data_type.trim() != original.data_type.trim();if type_changed {let column_name = quote_ident(StructureDialect::Postgres, current_name);- let data_type = column_data_type(StructureDialect::Postgres, column);+ let data_type = column_data_type(StructureDialect::Postgres, column, None);if use_xugu_type_syntax {statements.push(format!("ALTER TABLE {table} ALTER COLUMN {column_name} {data_type};"));} else {@@ -718,7 +723,7 @@ pub(super) fn build_informix_existing_column_sql(table: &str, column: &EditableSlet nullable_changed = column.is_nullable != original.is_nullable;let default_changed = normalize_default(Some(&column.default_value)) != original_default(column);if type_changed || nullable_changed || default_changed {- let mut parts = vec![quote_ident(dialect, ¤t_name), column_data_type(dialect, column)];+ let mut parts = vec![quote_ident(dialect, ¤t_name), column_data_type(dialect, column, None)];if column.is_nullable {parts.push("NULL".to_string());} else {@@ -739,6 +744,7 @@ pub(super) fn build_oracle_like_existing_column_sql(dialect: StructureDialect,table: &str,column: &EditableStructureColumn,+ database_type: Option<crate::models::connection::DatabaseType>,) -> Vec<String> {let Some(original) = &column.original else {return Vec::new();@@ -757,7 +763,7 @@ pub(super) fn build_oracle_like_existing_column_sql(let nullable_changed = column.is_nullable != original.is_nullable;let default_changed = normalize_default(Some(&column.default_value)) != original_default(column);if type_changed || nullable_changed || default_changed {- let data_type = column_data_type(dialect, column);+ let data_type = column_data_type(dialect, column, database_type);let mut parts = vec![quote_ident(dialect, ¤t_name), data_type];let default_value = normalize_default(Some(&column.default_value));if !default_value.is_empty() {@@ -839,7 +845,12 @@ pub(super) fn build_dameng_existing_column_sql(statements.push(format!("ALTER TABLE {table} DROP IDENTITY;"));}- statements.extend(build_oracle_like_existing_column_sql(StructureDialect::Dameng, table, column));+ statements.extend(build_oracle_like_existing_column_sql(+ StructureDialect::Dameng,+ table,+ column,+ Some(crate::models::connection::DatabaseType::Dameng),+ ));if let DamengIdentityTransition::Add { seed, increment } = transition {statements.push(format!(@@ -869,7 +880,7 @@ pub(super) fn build_iris_existing_column_sql(table: &str, column: &EditableStruclet nullable_changed = column.is_nullable != original.is_nullable;let default_changed = normalize_default(Some(&column.default_value)) != original_default(column);if type_changed || nullable_changed || default_changed {- let mut parts = vec![quote_ident(dialect, ¤t_name), column_data_type(dialect, column)];+ let mut parts = vec![quote_ident(dialect, ¤t_name), column_data_type(dialect, column, None)];let default_value = normalize_default(Some(&column.default_value));if !default_value.is_empty() {parts.push(format!("DEFAULT {}", format_default_for_sql(dialect, &column.data_type, &default_value)));@@ -915,7 +926,7 @@ pub(super) fn build_oscar_existing_column_sql(// 类型或默认值变更:带括号的 MODIFY 只允许 "col TYPE [DEFAULT ...]",不含 NULL/NOT NULL。if type_changed || default_changed {- let data_type = column_data_type(dialect, column);+ let data_type = column_data_type(dialect, column, None);let mut parts = vec![quote_ident(dialect, ¤t_name), data_type];let default_value = normalize_default(Some(&column.default_value));if !default_value.is_empty() {@@ -989,7 +1000,7 @@ pub(super) fn build_sqlserver_existing_column_sql(statements.push(build_sqlserver_alter_column_preserving_default_sql(table,¤t_name,- &column_data_type(dialect, column),+ &column_data_type(dialect, column, None),column.is_nullable,));} else {@@ -1001,7 +1012,7 @@ pub(super) fn build_sqlserver_existing_column_sql(statements.push(format!("ALTER TABLE {table} ALTER COLUMN {} {} {null_clause};",quote_ident(dialect, ¤t_name),- column_data_type(dialect, column)+ column_data_type(dialect, column, None)));}}@@ -1128,7 +1139,7 @@ pub(super) fn build_h2_existing_column_sql(table: &str, column: &EditableStructustatements.push(format!("ALTER TABLE {table} ALTER COLUMN {} SET DATA TYPE {};",quote_ident(StructureDialect::H2, ¤t_name),- column_data_type(StructureDialect::H2, column)+ column_data_type(StructureDialect::H2, column, None)));}if column.is_nullable != original.is_nullable {@@ -1297,7 +1308,7 @@ pub(super) fn build_questdb_existing_column_sql(table: &str, column: &EditableStstatements.push(format!("ALTER TABLE {table} ALTER COLUMN {} TYPE {};",quote_ident(StructureDialect::Questdb, current_name),- column_data_type(StructureDialect::Questdb, column)+ column_data_type(StructureDialect::Questdb, column, None)));}statementsdiff --git a/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs b/crates/dbx-sql-schema/src/table_structure_sql/column_format.rsindex 13dac7c2e2..ce0501fb74 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/column_format.rs@@ -1,6 +1,7 @@use super::dialect::{is_oracle_like, StructureDialect};use super::types::{EditableStructureColumn, TableStructureSqlOptions};use super::util::{clean, format_default_for_sql, normalize_default, quote_ident, quote_string};+use crate::models::connection::DatabaseType;/// Drops the `CHARACTER SET` / `COLLATE` inputs of MySQL columns that merely/// inherit the table's default collation, so the generated DDL does not spell@@ -36,8 +37,12 @@ pub(super) fn strip_inherited_mysql_column_charsets(options: &mut TableStructure}}-pub(super) fn column_definition(dialect: StructureDialect, column: &EditableStructureColumn) -> String {- let data_type = column_data_type(dialect, column);+pub(super) fn column_definition(+ dialect: StructureDialect,+ column: &EditableStructureColumn,+ database_type: Option<DatabaseType>,+) -> String {+ let data_type = column_data_type(dialect, column, database_type);let mut parts = vec![quote_ident(dialect, &column.name), data_type];// QuestDB SQL Syntax: ```ALTER TABLE tableName ADD COLUMN [IF NOT EXISTS] columnName typeDef```if dialect == StructureDialect::Questdb {@@ -331,7 +336,18 @@ pub(super) fn is_dameng_identity_compatible_type(data_type: &str) -> bool {}}-pub(super) fn column_data_type(dialect: StructureDialect, column: &EditableStructureColumn) -> String {+pub(super) fn column_data_type(+ dialect: StructureDialect,+ column: &EditableStructureColumn,+ database_type: Option<DatabaseType>,+) -> String {+ if matches!(database_type, Some(DatabaseType::Oracle | DatabaseType::OceanbaseOracle)) {+ let data_type = column.data_type.trim();+ let base_type = data_type.split('(').next().unwrap_or(data_type).trim();+ if base_type.eq_ignore_ascii_case("float") {+ return data_type.to_string();+ }+ }if dialect == StructureDialect::ClickHouse {return clickhouse_column_type(column);}diff --git a/crates/dbx-sql-schema/src/table_structure_sql/columns.rs b/crates/dbx-sql-schema/src/table_structure_sql/columns.rsindex 178a3ba564..f92afff54a 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/columns.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/columns.rs@@ -233,7 +233,7 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu{mysql_primary_key_column_clauses.push(format!("ADD COLUMN {}{position_clause}",- column_definition(StructureDialect::Mysql, column)+ column_definition(StructureDialect::Mysql, column, None)));} else {statements.extend(build_add_column_sql(@@ -350,7 +350,12 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu} else if options.database_type == Some(crate::models::connection::DatabaseType::Xugu) {statements.extend(build_xugu_existing_column_sql(&table, column));} else {- statements.extend(build_oracle_like_existing_column_sql(dialect, &table, column))+ statements.extend(build_oracle_like_existing_column_sql(+ dialect,+ &table,+ column,+ options.database_type,+ ))}}StructureDialect::Dameng => {@@ -718,7 +723,7 @@ pub(super) fn build_add_column_sql(table_name: &str,driver_profile: Option<&str>,) -> Vec<String> {- let definition = column_definition(dialect, column);+ let definition = column_definition(dialect, column, database_type);let mut statements = if database_type == Some(DatabaseType::Transwarp) {vec![format!("ALTER TABLE {table} ADD COLUMNS ({definition});")]} else if is_oracle_like(dialect) || matches!(dialect, StructureDialect::Informix | StructureDialect::SapHana) {diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rsindex cfc551c7ee..88a29b418e 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs@@ -49,7 +49,10 @@ pub(super) fn build_create_table_sql_with_partition_clause(capabilities = capabilities_for(options.database_type, options.driver_profile.as_deref());dialect = capabilities.dialect;}- options.table_name = clean(&options.table_name);+ // OceanBase callers supply decoded identifiers, including quoted clone targets.+ if options.database_type != Some(DatabaseType::OceanbaseOracle) {+ options.table_name = clean(&options.table_name);+ }strip_inherited_mysql_column_charsets(&mut options);let mut warnings = Vec::new();warnings.extend(validate_mysql_engine(&options));@@ -183,7 +186,7 @@ pub(super) fn build_create_table_sql_with_partition_clause(if transwarp::is_partition_column(&options, column) {continue;}- let mut data_type = column_data_type(dialect, column);+ let mut data_type = column_data_type(dialect, column, options.database_type);// SQLite accepts AUTOINCREMENT only on an exact INTEGER PRIMARY KEY,// so integer-family aliases are normalized when auto-increment is on.if dialect == StructureDialect::Sqlitediff --git a/crates/dbx-sql-schema/src/table_structure_sql/transwarp.rs b/crates/dbx-sql-schema/src/table_structure_sql/transwarp.rsindex 9cb4d81163..885de8a528 100644--- a/crates/dbx-sql-schema/src/table_structure_sql/transwarp.rs+++ b/crates/dbx-sql-schema/src/table_structure_sql/transwarp.rs@@ -98,7 +98,7 @@ fn create_options_clause(format!("{} {}",quote_new_ident(Some(DatabaseType::Transwarp), dialect, &column.name),- column_data_type(dialect, column)+ column_data_type(dialect, column, Some(DatabaseType::Transwarp)))}).collect::<Vec<_>>()diff --git a/crates/dbx-sql-schema/tests/oceanbase_clone_names.rs b/crates/dbx-sql-schema/tests/oceanbase_clone_names.rsnew file mode 100644index 0000000000..e4f563e9aa--- /dev/null+++ b/crates/dbx-sql-schema/tests/oceanbase_clone_names.rs@@ -0,0 +1,30 @@+use dbx_sql_schema::table_structure_sql::{build_create_table_sql, TableStructureSqlOptions};++#[test]+fn oceanbase_clone_create_preserves_decoded_quoted_target_names() {+ for name in [" New ", "MixedCase", "A\"B", "普通表"] {+ let options: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": "oceanbase-oracle", "schema": "APP", "tableName": name,+ "columns": [{"id": "new:id", "name": "ID", "dataType": "NUMBER", "isNullable": true}]+ }))+ .unwrap();+ let result = build_create_table_sql(options);+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ let expected = format!("CREATE TABLE \"APP\".\"{}\" (", name.replace('"', "\"\""));+ assert!(result.statements[0].starts_with(&expected), "{:?}", result.statements);+ }+}++#[test]+fn other_databases_keep_create_name_input_trimming() {+ for database_type in ["oracle", "postgres", "mysql"] {+ let options: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "schema": "APP", "tableName": " New ",+ "columns": [{"id": "new:id", "name": "ID", "dataType": "INT", "isNullable": true}]+ }))+ .unwrap();+ let result = build_create_table_sql(options);+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert!(!result.statements[0].contains(" New "), "{:?}", result.statements);+ }+}diff --git a/crates/dbx-sql-schema/tests/oracle_numeric_parameters.rs b/crates/dbx-sql-schema/tests/oracle_numeric_parameters.rsnew file mode 100644index 0000000000..d052ada8d7--- /dev/null+++ b/crates/dbx-sql-schema/tests/oracle_numeric_parameters.rs@@ -0,0 +1,107 @@+use dbx_sql_schema::table_structure_sql::{+ build_create_table_sql, build_single_column_alter_sql, build_table_structure_change_sql,+ SingleColumnAlterSqlOptions, TableStructureSqlOptions,+};++fn numeric_parameters_survive_create_and_add_column(database_type: &str) {+ let options: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "schema": "APP", "tableName": "NUMERIC_COLUMNS",+ "columns": [+ {"id": "new:f", "name": "F", "dataType": "FLOAT(63)", "isNullable": true},+ {"id": "new:n", "name": "N", "dataType": "NUMBER(*,-2)", "isNullable": true}+ ]+ }))+ .unwrap();+ for result in [build_create_table_sql(options.clone()), build_table_structure_change_sql(options)] {+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ let sql = result.statements.join("\n");+ assert!(sql.contains("FLOAT(63)"), "{database_type}: {sql}");+ assert!(sql.contains("NUMBER(*,-2)"), "{database_type}: {sql}");+ }+}++#[test]+fn oracle_numeric_parameters() {+ numeric_parameters_survive_create_and_add_column("oracle");+}++#[test]+fn oceanbase_oracle_numeric_parameters() {+ numeric_parameters_survive_create_and_add_column("oceanbase-oracle");+}++#[test]+fn oracle_float_parameters_survive_both_modify_entry_points() {+ for database_type in ["oracle", "oceanbase-oracle"] {+ let column = serde_json::json!({+ "id": "existing:F", "name": "F", "dataType": "FLOAT(63)", "isNullable": false,+ "original": {"name": "F", "data_type": "FLOAT(63)", "is_nullable": true, "column_default": null}+ });+ let table: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "schema": "APP", "tableName": "NUMERIC_COLUMNS", "columns": [column.clone()]+ }))+ .unwrap();+ let single: SingleColumnAlterSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "schema": "APP", "tableName": "NUMERIC_COLUMNS", "column": column+ }))+ .unwrap();+ for result in [build_table_structure_change_sql(table), build_single_column_alter_sql(single)] {+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert!(+ result.statements.iter().any(|sql| sql.contains("FLOAT(63)") && sql.contains("NOT NULL")),+ "{:?}",+ result.statements+ );+ }+ }+}++#[test]+fn oracle_comment_only_does_not_modify_numeric_types() {+ for database_type in ["oracle", "oceanbase-oracle"] {+ for data_type in ["FLOAT(63)", "NUMBER(*,-2)", "NUMBER(12,0)", "FLOAT", "NUMBER"] {+ let options: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "schema": "APP", "tableName": "NUMERIC_COLUMNS",+ "columns": [{"id": "existing:F", "name": "F", "dataType": data_type, "isNullable": true, "comment": "new comment",+ "original": {"name": "F", "data_type": data_type, "is_nullable": true, "column_default": null}}]+ })).unwrap();+ let result = build_table_structure_change_sql(options);+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert_eq!(result.statements.len(), 1, "{:?}", result.statements);+ assert!(result.statements[0].starts_with("COMMENT ON COLUMN"));+ }+ }+}++#[test]+fn oracle_explicit_invalid_float_parameters_are_not_silently_dropped() {+ for database_type in ["oracle", "oceanbase-oracle"] {+ for data_type in ["FLOAT(10,2)", "FLOAT(127)", "FLOAT", "float(63)", "BINARY_FLOAT", "NUMBER(*,-2)"] {+ let options: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "tableName": "NUMERIC_COLUMNS",+ "columns": [{"id": "new:F", "name": "F", "dataType": data_type, "isNullable": true}]+ }))+ .unwrap();+ let result = build_create_table_sql(options);+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);+ assert!(result.statements.join("\n").contains(data_type), "{:?}", result.statements);+ }+ }+}++#[test]+fn other_oracle_like_databases_keep_existing_float_normalization() {+ for database_type in ["iris", "yashandb", "xugu", "dameng", "oscar"] {+ let options: TableStructureSqlOptions = serde_json::from_value(serde_json::json!({+ "databaseType": database_type, "tableName": "NUMERIC_COLUMNS",+ "columns": [{"id": "new:F", "name": "F", "dataType": "FLOAT(63)", "isNullable": true}]+ }))+ .unwrap();+ for result in [build_create_table_sql(options.clone()), build_table_structure_change_sql(options)] {+ assert!(result.warnings.is_empty(), "{database_type}: {:?}", result.warnings);+ let sql = result.statements.join("\n");+ assert!(sql.contains("FLOAT"), "{database_type}: {sql}");+ assert!(!sql.contains("FLOAT(63)"), "{database_type}: {sql}");+ }+ }+}diff --git a/docs/content/docs/table-structure.cn.mdx b/docs/content/docs/table-structure.cn.mdxindex 70d38a6674..3d55bf4a46 100644--- a/docs/content/docs/table-structure.cn.mdx+++ b/docs/content/docs/table-structure.cn.mdx@@ -115,6 +115,14 @@ description: 可视化查看和修改字段、索引、外键与触发器,并不要根据“能连接”推断“所有 DDL 都能编辑”。当前范围以 [数据库支持](/cn/docs/databases) 和编辑器实际控件为准。+## OceanBase Oracle 表结构克隆++侧栏和对象浏览器中的「克隆表结构」及结构粘贴使用同一复制范围:列类型及参数、BYTE/CHAR 长度单位、默认值、可空性、主键列序、普通索引和表列注释。`FLOAT(p)` 的二进制精度与 `NUMBER(*,s)`、负 scale 会保留。OceanBase 的内置类型推荐基于 4.2.5.7 的建列验证;其他版本仍可手动输入类型,已有字段类型不会被推荐列表替换。++执行前的确认框展示目标、SQL、复制项和排除项。外键、CHECK/UNIQUE 约束、触发器、特殊索引和分区定义不复制;UNIQUE 约束的支撑索引也排除,独立普通唯一索引可以复制。含虚拟列或临时表属性的源表会被拒绝。普通目标名按大写处理;显式双引号名称保留大小写,例如 `orders_copy` 创建 `ORDERS_COPY`,`"OrdersCopy"` 创建 `OrdersCopy`。++DDL 逐条提交,遇到首个错误即停止,不自动回滚或删除目标。失败详情分别列出已确认成功、数据库拒绝或结果未知,以及尚未执行的步骤。重试前,按详情中的 schema 和表名刷新并核对目标结构;通信中断不能证明建表失败。原生 Oracle 的克隆范围保持独立,不受上述 OceanBase 排除规则限制。+## 并发与恢复- 编辑草稿基于打开时读取的元数据,不会自动合并其他客户端的结构变更diff --git a/docs/content/docs/table-structure.mdx b/docs/content/docs/table-structure.mdxindex 2fef14f031..6d7596878c 100644--- a/docs/content/docs/table-structure.mdx+++ b/docs/content/docs/table-structure.mdx@@ -115,6 +115,14 @@ Copy the complete DDL for code review or execution through a migration tool.Do not assume that every DDL feature is editable because a database can connect. Use [Database Support](/en/docs/databases) and the actual editor controls as the current source of truth.+## OceanBase Oracle Structure Cloning++The sidebar and Object Browser use the same scope for structure cloning and structure paste: column types and parameters, BYTE/CHAR units, defaults, nullability, primary-key column order, ordinary indexes, and table/column comments. FLOAT binary precision and NUMBER star precision or negative scale are retained. Built-in OceanBase type recommendations use CREATE-column checks against 4.2.5.7; other types can still be entered manually, and recommendations do not replace existing column types.++Before execution, confirmation shows the target, SQL, copied items, and exclusions. Foreign keys, CHECK/UNIQUE constraints, triggers, special indexes, and partition definitions are excluded. UNIQUE constraint backing indexes are excluded too; independent ordinary unique indexes can be copied. Sources with virtual columns or temporary-table properties are rejected. Ordinary target names fold to uppercase, while explicitly double-quoted names retain case: `orders_copy` creates `ORDERS_COPY`, and `"OrdersCopy"` creates `OrdersCopy`.++Each DDL statement commits separately. Execution stops at the first error without automatic rollback or target deletion. Failure details distinguish confirmed steps, database rejection or unknown results, and steps not executed. Before retrying, refresh and inspect the target using the reported schema and table name; a lost response does not prove creation failed. Native Oracle cloning retains its own scope and is not restricted by these OceanBase exclusions.+## Concurrency and Recovery- Drafts are based on metadata read when the editor opened and do not merge external schema changes automaticallydiff --git a/packages/app-tests/sidebarContextMenuHost.test.ts b/packages/app-tests/sidebarContextMenuHost.test.tsindex 59ec941699..5d84209f2f 100644--- a/packages/app-tests/sidebarContextMenuHost.test.ts+++ b/packages/app-tests/sidebarContextMenuHost.test.ts@@ -64,7 +64,7 @@ test("object source identity and editability are enforced in queryStore", () =>test("successful tree table paste consumes only the clipboard used to start it", () => {const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");- const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTable");+ const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTableImpl");assert.match(confirmPasteTableBody, /const clipboardAtPasteStart = connectionStore\.treeClipboard/);assert.match(confirmPasteTableBody, /if \(pasteFailCount === 0\)/);@@ -74,7 +74,7 @@ test("successful tree table paste consumes only the clipboard used to start it",test("tree table paste keeps the clipboard when production confirmation is cancelled", () => {const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");- const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTable");+ const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTableImpl");assert.match(confirmPasteTableBody, /const structureExecuted = await executeTreeNodeSqlWithProductionGuard[\s\S]*?if \(!structureExecuted\) \{[\s\S]*?pasteCancelled = true;[\s\S]*?break;/);assert.match(confirmPasteTableBody, /const dataExecuted = await executeTreeNodeSqlWithProductionGuard[\s\S]*?if \(!dataExecuted\) \{[\s\S]*?pasteCancelled = true;[\s\S]*?break;/);@@ -84,7 +84,7 @@ test("tree table paste keeps the clipboard when production confirmation is cancetest("tree table paste consumes the clipboard even if only the object-list refresh fails", () => {const runtimeHost = readFileSync("apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue", "utf8");- const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTable");+ const confirmPasteTableBody = functionBody(runtimeHost, "confirmPasteTableImpl");assert.match(confirmPasteTableBody, /let pasteFailCount = 0/);assert.match(confirmPasteTableBody, /let refreshFailCount = 0/);