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
feat(grid): export query results to a database
二丫讲梵246df325531f
diff --git a/agents/drivers/goldendb/src/main/java/com/dbx/agent/goldendb/GoldendbAgent.java b/agents/drivers/goldendb/src/main/java/com/dbx/agent/goldendb/GoldendbAgent.javaindex 63b875ec32..4a0fb5efb5 100644--- a/agents/drivers/goldendb/src/main/java/com/dbx/agent/goldendb/GoldendbAgent.java+++ b/agents/drivers/goldendb/src/main/java/com/dbx/agent/goldendb/GoldendbAgent.java@@ -457,6 +457,12 @@ public final class GoldendbAgent extends AbstractJdbcAgent {case Types.BIT:value = rs.getBoolean(index);break;+ case Types.BINARY:+ case Types.VARBINARY:+ case Types.LONGVARBINARY:+ case Types.BLOB:+ value = JdbcExecutor.bytesToHex(rs.getBytes(index));+ break;default:value = rs.getString(index);break;diff --git a/agents/drivers/goldendb/src/test/java/com/dbx/agent/goldendb/GoldendbAgentTest.java b/agents/drivers/goldendb/src/test/java/com/dbx/agent/goldendb/GoldendbAgentTest.javaindex c22fa1d467..7febf55f3e 100644--- a/agents/drivers/goldendb/src/test/java/com/dbx/agent/goldendb/GoldendbAgentTest.java+++ b/agents/drivers/goldendb/src/test/java/com/dbx/agent/goldendb/GoldendbAgentTest.java@@ -2,6 +2,14 @@ package com.dbx.agent.goldendb;import com.dbx.agent.DatabaseAgent;import com.dbx.agent.test.JdbcFakeExecutionBehaviorTest;+import java.lang.reflect.Proxy;+import java.nio.charset.StandardCharsets;+import java.sql.ResultSet;+import java.sql.Types;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;class GoldendbAgentTest extends JdbcFakeExecutionBehaviorTest {@Override@@ -13,4 +21,37 @@ class GoldendbAgentTest extends JdbcFakeExecutionBehaviorTest {protected String resultSetSql() {return "CALL sample_proc()";}++ @Test+ void binaryResultsPreserveBytesInsteadOfReturningAmbiguousText() {+ GoldendbAgent agent = new GoldendbAgent();+ byte[][] values = {+ "deadbeef".getBytes(StandardCharsets.US_ASCII),+ "0x00ff".getBytes(StandardCharsets.US_ASCII),+ new byte[]{0, (byte) 0xff, (byte) 0x80},+ new byte[0]+ };+ String[] expected = {"0x6465616462656566", "0x307830306666", "0x00ff80", "0x"};+ for (int sqlType : new int[]{Types.BINARY, Types.VARBINARY, Types.LONGVARBINARY, Types.BLOB}) {+ for (int i = 0; i < values.length; i++) {+ assertEquals(expected[i], agent.resultValue(binaryResultSet(values[i]), 1, sqlType));+ }+ assertNull(agent.resultValue(binaryResultSet(null), 1, sqlType));+ }+ }++ private static ResultSet binaryResultSet(byte[] bytes) {+ return (ResultSet) Proxy.newProxyInstance(+ GoldendbAgentTest.class.getClassLoader(),+ new Class<?>[]{ResultSet.class},+ (proxy, method, args) -> {+ if ("getBytes".equals(method.getName())) {+ assertEquals(1, args[0]);+ return bytes;+ }+ if ("wasNull".equals(method.getName())) return bytes == null;+ throw new AssertionError("Unexpected ResultSet call: " + method.getName());+ }+ );+ }}diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vueindex cb5a9f8db2..e187b9fe35 100644--- a/apps/desktop/src/components/grid/DataGrid.vue+++ b/apps/desktop/src/components/grid/DataGrid.vue@@ -234,6 +234,7 @@ import {ELASTICSEARCH_PAGE_JUMP_WARNING_REQUESTS,elasticsearchCursorPageJumpRequestCount,hasCompleteLocalDataGridResult,+ hasShortDataGridSqlPage,reconcileDataGridExactTotalWithObservedPage,resolveDataGridPaginationTotal,showDataGridRerunTotalCountAction,@@ -592,6 +593,7 @@ interface DataGridProps {exportColumnExtras?: Array<string | null | undefined>;insertMode?: SqlInsertMode;}) => Promise<api.QueryResultExportRequest | undefined>;+ transferQueryResult?: () => void;allExportResults?: Array<{sheetName: string;result: QueryResult;@@ -3855,23 +3857,46 @@ function selectAndRevealLastLoadedRow() {});}+// SQL-page counts can come from another session. Explicit load-all must+// observe a short tail on the original execution path, even at a cached total.+const loadsSqlPages = computed(() => isResultsContext.value && !!props.pageSql);+const sqlPageExhausted = computed(() =>+ hasShortDataGridSqlPage({+ rowCount: props.result.rows.length,+ pageOffset: props.pageOffset,+ pageLimit: props.pageLimit,+ executedPageOffset: props.executedPageOffset,+ executedPageLimit: props.executedPageLimit,+ }),+);+function nextLoadAllSegment() {+ if (loadsSqlPages.value) {+ if (sqlPageExhausted.value) return null;+ const segment = dataGridLoadAllSegment(props.result.rows.length, infiniteScrollMaxRows.value, true);+ // Preserve the existing bulk load while more rows are expected; a+ // cached end only needs a normal page to probe the actual source.+ return segment && !canFetchNextInfiniteScrollSegment.value ? { offset: segment.offset, limit: Math.min(segment.limit, pageSize.value) } : segment;+ }+ const effectiveTotal = paginationTotalRowCount.value ?? displayedTotalRowCount.value;+ const canFetchMore = canFetchNextInfiniteScrollSegment.value && (!totalRowCountIsExact.value || effectiveTotal === undefined || props.result.rows.length < effectiveTotal);+ const targetMaxRows = dataGridLoadAllInitialTarget(props.result.rows.length, infiniteScrollMaxRows.value, totalRowCountIsExact.value ? effectiveTotal : undefined);+ return dataGridLoadAllSegment(props.result.rows.length, targetMaxRows, canFetchMore);+}+function loadAllRowsAndGoToLast() {if (!props.loadAllRowsEnabled || gridSurfaceBusy.value || infiniteScrollLoading.value || props.result.rows.length === 0) return;// search_after cursor paging fetches page by page; a single giant append// against those cursors is untested, so ES/Easysearch grids keep the// reveal-only shortcut instead of loading everything.if (isResultsContext.value && (resolvedDatabaseType.value === "elasticsearch" || resolvedDatabaseType.value === "easysearch")) return;- const effectiveTotal = paginationTotalRowCount.value ?? displayedTotalRowCount.value;- const canFetchMore = canFetchNextInfiniteScrollSegment.value && (!totalRowCountIsExact.value || effectiveTotal === undefined || props.result.rows.length < effectiveTotal);- const targetMaxRows = dataGridLoadAllInitialTarget(props.result.rows.length, infiniteScrollMaxRows.value, totalRowCountIsExact.value ? effectiveTotal : undefined);- const segment = dataGridLoadAllSegment(props.result.rows.length, targetMaxRows, canFetchMore);+ const segment = nextLoadAllSegment();if (!segment) {loadAllRowsActive.value = true;infiniteScrollAllLoaded = true;selectAndRevealLastLoadedRow();return;}- const knownTotal = effectiveTotal;+ const knownTotal = paginationTotalRowCount.value ?? displayedTotalRowCount.value;const remaining = typeof knownTotal === "number" && Number.isFinite(knownTotal) && knownTotal >= props.result.rows.length ? knownTotal - props.result.rows.length : segment.limit;if (remaining > LOAD_ALL_ROWS_CONFIRM_ROW_THRESHOLD) {pendingLoadAllRows.value = { remaining };@@ -3902,14 +3927,16 @@ function finishOrContinueLoadAllRun(requestedOffset: number | undefined, requestif (!loadAllRowsLoopActive) return false;const effectiveTotal = paginationTotalRowCount.value ?? displayedTotalRowCount.value;const canFetchMore = canFetchNextInfiniteScrollSegment.value && (!totalRowCountIsExact.value || effectiveTotal === undefined || props.result.rows.length < effectiveTotal);- const nextSegment = canFetchMore- ? dataGridLoadAllNextSegment({- loadedRowCount: props.result.rows.length,- requestedOffset: requestedOffset ?? props.result.rows.length,- requestedLimit: requestedLimit ?? pageSize.value,- totalRowCount: totalRowCountIsExact.value ? effectiveTotal : undefined,- })- : null;+ const nextSegment = loadsSqlPages.value+ ? nextLoadAllSegment()+ : canFetchMore+ ? dataGridLoadAllNextSegment({+ loadedRowCount: props.result.rows.length,+ requestedOffset: requestedOffset ?? props.result.rows.length,+ requestedLimit: requestedLimit ?? pageSize.value,+ totalRowCount: totalRowCountIsExact.value ? effectiveTotal : undefined,+ })+ : null;if (!nextSegment) {loadAllRowsLoopActive = false;infiniteScrollAllLoaded = true;@@ -3925,10 +3952,7 @@ function confirmLoadAllRows() {if (!pending) return;pendingLoadAllRows.value = undefined;loadAllRowsConfirmOpen.value = false;- const effectiveTotal = paginationTotalRowCount.value ?? displayedTotalRowCount.value;- const canFetchMore = canFetchNextInfiniteScrollSegment.value && (!totalRowCountIsExact.value || effectiveTotal === undefined || props.result.rows.length < effectiveTotal);- const targetMaxRows = dataGridLoadAllInitialTarget(props.result.rows.length, infiniteScrollMaxRows.value, totalRowCountIsExact.value ? effectiveTotal : undefined);- const segment = dataGridLoadAllSegment(props.result.rows.length, targetMaxRows, canFetchMore);+ const segment = nextLoadAllSegment();if (segment) startLoadAllRows(segment);}function checkInfiniteScroll(scroller: HTMLElement) {@@ -8840,6 +8864,7 @@ const exportMenuItems = computed(() => {if (!hasFullResultExport) {return [+ ...(props.context === "results" && props.transferQueryResult ? [{ value: "database", label: t("grid.exportDatabase") }] : []),{ value: "csv", label: t("grid.exportCsv") },{ value: "xlsx", label: t("grid.exportXlsx") },...(canIncludeSql ? [{ value: "xlsx-with-sql", label: t("grid.exportXlsxWithSql") }] : []),@@ -8856,6 +8881,7 @@ const exportMenuItems = computed(() => {}return [+ ...(props.context === "results" && props.transferQueryResult ? [{ value: "database", label: t("grid.exportDatabase"), separatorBefore: true }] : []),{ value: "page-csv", label: t("grid.exportCurrentPageCsv") },{ value: "page-xlsx", label: t("grid.exportCurrentPageXlsx") },...(canIncludeSql@@ -8903,6 +8929,7 @@ function selectPageSizeMenuItem(value: string) {function selectExportMenuItem(value: string) {const actions: Record<string, () => void> = {+ database: () => props.transferQueryResult?.(),"page-csv": exportCurrentPageCsv,"page-xlsx": exportCurrentPageXlsx,"page-xlsx-with-sql": exportCurrentPageXlsxWithSql,@@ -11200,7 +11227,7 @@ watch(// While a "load all" run is active the per-request row cap must not be// read as the end of data — only the requested-vs-appended count and an// exact known total end the run (#10752).- ...(loadAllRowsLoopActive && appendRequestedLimit ? { loadAll: { requestedLimit: appendRequestedLimit, totalRowCount: totalRowCountIsExact.value ? (paginationTotalRowCount.value ?? displayedTotalRowCount.value) : undefined } } : {}),+ ...(loadAllRowsLoopActive && appendRequestedLimit ? { loadAll: { requestedLimit: appendRequestedLimit, totalRowCount: !loadsSqlPages.value && totalRowCountIsExact.value ? (paginationTotalRowCount.value ?? displayedTotalRowCount.value) : undefined } } : {}),});if (appendCompletion) {if (infiniteScrollEnabled.value || loadAllRowsLoopActive) {@@ -13065,6 +13092,7 @@ function copySubmenu(): ContextMenuItem {function exportSubmenu(): ContextMenuItem {const items: ContextMenuItem[] = [+ ...(props.context === "results" && props.transferQueryResult ? [{ label: t("grid.exportDatabase"), action: props.transferQueryResult }] : []),{ label: t("grid.exportCsv"), action: exportCsv },{ label: t("grid.exportXlsx"), action: exportXlsx },{ label: t("grid.exportJson"), action: exportJson },diff --git a/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts b/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.tsindex e9a1438162..0f87ea3b8b 100644--- a/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts+++ b/apps/desktop/src/components/grid/__tests__/DataGridPaginationShortcuts.spec.ts@@ -1,6 +1,6 @@// @vitest-environment happy-dom-import { createApp, defineComponent, h, markRaw, nextTick, type App, type PropType } from "vue";+import { createApp, defineComponent, h, markRaw, nextTick, shallowRef, type App, type PropType } from "vue";import { createPinia, setActivePinia } from "pinia";import { afterEach, describe, expect, it, vi } from "vitest";import i18n from "@/i18n";@@ -90,6 +90,7 @@ function mountGrid(execution_time_ms: 0,});const paginate = vi.fn();+ const gridState = shallowRef<Record<string, unknown>>({});const host = document.createElement("div");document.body.append(host);@@ -111,6 +112,7 @@ function mountGrid(totalRowCount: options.totalRowCount ?? 500,loading: options.loading ?? false,paginationEnabled: options.paginationEnabled ?? true,+ ...gridState.value,onPaginate: paginate,}),},@@ -124,7 +126,7 @@ function mountGrid(app.mount(host);const mounted = { app, host };mountedApps.push(mounted);- return { host, paginate, settingsStore };+ return { host, paginate, settingsStore, gridState };}async function settle() {@@ -364,3 +366,57 @@ describe("DataGrid custom page size persistence", () => {expect(settingsStore.editorSettings.tableOpenPageSize).toBe(100);});});++describe("DataGrid SQL load-all exhaustion", () => {+ it.each([0, 1])("stops after a %i-row tail and does not probe again", async (tailRows) => {+ const { host, paginate, gridState } = mountGrid({ pageOffset: 0, totalRowCount: 100 });+ const result = (count: number, appended?: number) => ({ columns: ["id"], rows: Array.from({ length: count }, (_, i) => [i]), has_more: false, appended_from_row_count: appended, affected_rows: 0, execution_time_ms: 0 });+ gridState.value = { context: "results", pageSql: "SELECT id FROM items LIMIT 100", executedPageOffset: 0, executedPageLimit: 100, result: result(100) };+ await settle();+ const button = host.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.global.t("grid.loadAllAndGoToLastRow")}"]`)!;+ button.click();+ await settle();+ expect(paginate.mock.calls[0]?.slice(0, 2)).toEqual([100, 100]);+ gridState.value = { ...gridState.value, executedPageOffset: 100, result: result(100 + tailRows, 100) };+ await settle();+ button.click();+ await settle();+ expect(paginate).toHaveBeenCalledOnce();+ });++ it("respects the configured result cap when a SQL page is full", async () => {+ const { host, paginate, settingsStore, gridState } = mountGrid({ pageOffset: 0, totalRowCount: 100 });+ settingsStore.updateEditorSettings({ queryResultMaxRowsEnabled: true, queryResultMaxRows: 100 });+ gridState.value = { context: "results", pageSql: "SELECT id FROM items LIMIT 100", result: { columns: ["id"], rows: Array.from({ length: 100 }, (_, i) => [i]), has_more: false, truncated: true, affected_rows: 0, execution_time_ms: 0 } };+ await settle();+ host.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.global.t("grid.loadAllAndGoToLastRow")}"]`)!.click();+ await settle();+ expect(paginate).not.toHaveBeenCalled();+ });++ it.each([false, true])("probes past a cached total and stops at an empty tail (infiniteScroll=%s)", async (infiniteScroll) => {+ const { host, paginate, settingsStore, gridState } = mountGrid({ infiniteScroll, pageOffset: 0, totalRowCount: 100 });+ settingsStore.updateEditorSettings({ queryResultMaxRowsEnabled: true, queryResultMaxRows: 1000 });+ const rows = Array.from({ length: 100 }, (_, index) => [index]);+ gridState.value = { context: "results", pageSql: "SELECT id FROM items LIMIT 100", executedPageOffset: 0, executedPageLimit: 100, result: { columns: ["id"], rows, has_more: false, affected_rows: 0, execution_time_ms: 0 } };+ await settle();+ const button = host.querySelector<HTMLButtonElement>(`button[aria-label="${i18n.global.t("grid.loadAllAndGoToLastRow")}"]`)!;+ button.click();+ await settle();+ expect(paginate).toHaveBeenCalledOnce();+ expect(paginate.mock.calls[0]?.slice(0, 2)).toEqual([100, 100]);+ expect(paginate.mock.calls[0]?.[4]).toBe(true);++ // COUNT said 100, but the original session has another full page.+ gridState.value = { ...gridState.value, executedPageOffset: 100, result: { columns: ["id"], rows: [...rows, ...rows], has_more: false, appended_from_row_count: 100, affected_rows: 0, execution_time_ms: 0 } };+ await settle();+ expect(paginate).toHaveBeenCalledTimes(2);+ expect(paginate.mock.calls[1]?.slice(0, 2)).toEqual([200, 100]);++ gridState.value = { ...gridState.value, executedPageOffset: 200, result: { columns: ["id"], rows: [...rows, ...rows], has_more: false, appended_from_row_count: 200, affected_rows: 0, execution_time_ms: 0 } };+ await settle();+ button.click();+ await settle();+ expect(paginate).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex c49b5dda07..f501bfee33 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -104,6 +104,7 @@ function preloadDataGridComponent() {const QueryEditor = defineAsyncComponent({ loader: () => import("@/components/editor/QueryEditor.vue"), loadingComponent: QueryLoadingState, delay: 0 });const DataGrid = defineAsyncComponent(loadDataGridComponent);+const QueryResultTransferDialog = defineAsyncComponent(() => import("@/components/transfer/QueryResultTransferDialog.vue"));const RedisKeyBrowser = defineAsyncComponent(() => import("@/components/redis/RedisKeyBrowser.vue"));const RedisQueryConsoleOutput = defineAsyncComponent(() => import("@/components/redis/RedisQueryConsoleOutput.vue"));const RedisDashboard = defineAsyncComponent(() => import("@/components/redis/RedisDashboard.vue"));@@ -199,6 +200,8 @@ import { useToolbarOverflow } from "@/composables/useToolbarOverflow";import { formatElapsedSeconds } from "@/lib/common/elapsedTime";import { copyToClipboard } from "@/lib/common/clipboard";import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";+import { analyzeEditableQuery } from "@/lib/sql/sqlAnalysis";+import { loadQueryResultTransferSourceDdl } from "@/components/transfer/queryResultTransferSource";import { formatDdlForDisplay } from "@/lib/sql/ddlDisplay";import { sqlObjectNavigationTypeFromTableType } from "@/lib/sql/sqlNavigation";import type { CustomSaveHandler } from "@/composables/useDataGridEditor";@@ -638,16 +641,44 @@ function sortQueryGrid(column: string, columnIndex: number, direction: "asc" | "else emit("sort", props.activeTab.id, column, columnIndex, direction, whereInput, mode, effectiveOrderBy);}-async function fetchGridResultForExport(onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void) {+async function fetchGridResultForExport(onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void, probeRowLimit = false, tabId = props.activeTab.id) {const isNeo4j = activeEffectiveDatabaseType.value === "neo4j";- const result = await queryStore.fetchTabResultForExport(props.activeTab.id, onProgress);+ const result = await queryStore.fetchTabResultForExport(tabId, onProgress, probeRowLimit);if (!result || !isNeo4j) return result;extractNeo4jNodeCells(result);extractGraphCells(result);return projectNeo4jNodeResult(result);}+async function loadQueryResultSourceDdl(): Promise<string | undefined> {+ if (props.activeTab.mode !== "query") return undefined;+ return loadQueryResultTransferSourceDdl({+ sql: activeResultExportSql.value,+ databaseType: activeEffectiveDatabaseType.value,+ connectionId: activeResultConnectionId.value,+ database: activeResultDatabase.value,+ schema: activeResultSchema.value,+ catalog: props.activeTab.catalog,+ clientSessionId: props.activeTab.resultClientSessionId ?? props.activeTab.id,+ txnSessionId: props.activeTab.autoCommit === false ? props.activeTab.txnSessionId : undefined,+ });+}+function openQueryResultTransfer() {+ if (props.activeTab.result) {+ queryResultTransferSourceTabId.value = props.activeTab.id;+ queryResultTransferOpen.value = true;+ }+}+function loadQueryResultForTransfer(): Promise<QueryResult | undefined> {+ return queryResultTransferSourceTabId.value === props.activeTab.id ? fetchGridResultForExport(undefined, true, queryResultTransferSourceTabId.value) : Promise.resolve(undefined);+}const activeResultSql = computed(() => resultSqlForGrid(props.activeTab));const activeResultExportSql = computed(() => queryResultExecutionSql(props.activeTab));+const activeResultSourceAnalysis = computed(() => analyzeEditableQuery(activeResultExportSql.value));+const activeResultSourceTable = computed(() => {+ const analysis = activeResultSourceAnalysis.value;+ return analysis?.selectStar && !analysis.sources?.length ? analysis.tableName : undefined;+});+const activeResultSourceSchema = computed(() => activeResultSourceAnalysis.value?.schema ?? activeResultSchema.value);const activeStatementExecutionMarkers = computed(() =>statementExecutionMarkers(props.activeTab.sql,@@ -681,6 +712,18 @@ watch(},);const resultArchiveExporting = ref(false);+const queryResultTransferOpen = ref(false);+const queryResultTransferSourceTabId = ref<string>();+watch(+ () => props.activeTab.id,+ () => {+ // The dialog reads the active tab's result and DDL lazily. Close it when+ // the active tab changes so a pending transfer can never target a+ // different result than the one the user opened it from.+ if (queryResultTransferOpen.value) queryResultTransferOpen.value = false;+ queryResultTransferSourceTabId.value = undefined;+ },+);const canExportResultArchive = computed(() => props.activeTab.mode === "query" && (!!props.activeTab.result || !!props.activeTab.results?.length || !!props.activeTab.resultRuns?.length));const resultAutoSave = computed(() => props.activeTab.resultAutoSave === true);const activeResultRunItem = computed(() => resultRuns.value.find((run) => run.active));@@ -2657,6 +2700,7 @@ defineExpose({:page-jump-progress="activeTab.resultPageJumpProgress":on-execute-sql="async (sql: string) => emit('executeSql', activeTab.id, sql)":full-export-result="fetchGridResultForExport"+ :transfer-query-result="openQueryResultTransfer":query-result-export-request="hasNeo4jNodes? undefined@@ -3522,6 +3566,19 @@ defineExpose({</DialogFooter></DialogContent></Dialog>+ <QueryResultTransferDialog+ v-if="activeTab.result"+ v-model:open="queryResultTransferOpen"+ :source-connection-id="activeResultConnectionId"+ :source-database="activeResultDatabase"+ :source-schema="activeResultSourceSchema"+ :source-table="activeResultSourceTable"+ :source-sql="activeResultExportSql"+ :source-database-type="activeEffectiveDatabaseType"+ :result="activeTab.result"+ :load-result="loadQueryResultForTransfer"+ :load-source-ddl="loadQueryResultSourceDdl"+ /></div></template>diff --git a/apps/desktop/src/components/transfer/QueryResultTransferDialog.vue b/apps/desktop/src/components/transfer/QueryResultTransferDialog.vuenew file mode 100644index 0000000000..ccc1f39276--- /dev/null+++ b/apps/desktop/src/components/transfer/QueryResultTransferDialog.vue@@ -0,0 +1,575 @@+<script setup lang="ts">+import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";+import { useEventListener, useResizeObserver } from "@vueuse/core";+import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";+import { databaseOptionsForConnection } from "@/composables/useDatabaseOptions";+import { useI18n } from "vue-i18n";+import { ArrowRightLeft, Loader2 } from "@lucide/vue";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import { isSchemaAware } from "@/lib/database/databaseFeatureSupport";+import { productionContextForDatabase } from "@/lib/database/productionSafety";+import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";+import { ensureReadOnlyWriteAccess } from "@/lib/database/readOnlyWriteAccess";+import { useToast } from "@/composables/useToast";+import { useSettingsStore } from "@/stores/settingsStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import * as api from "@/lib/backend/api";+import { formatError } from "@/lib/backend/errorUtils";+import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";+import { quoteTableIdentifier } from "@/lib/table/tableSelectSql";+import type { ColumnInfo, ConnectionConfig, DatabaseType, QueryResult } from "@/types/database";+import {+ alwaysIdentityColumnNamesFromDdl,+ identityColumnNamesFromDdl,+ nonInsertableColumnNamesFromDdl,+ queryResultTransferCreateCleanupSql,+ queryResultTransferDatabaseType,+ queryResultTransferIncomplete,+ queryResultTransferNeedsCreateCleanup,+ rewriteCreateTableName,+ supportsQueryResultTransfer,+ transactionalMysqlTableDdl,+} from "./queryResultTransfer";+import { postgresTransferSequenceSyncSql, queryResultTransferInsertSql, withSqlServerIdentityInsert } from "./queryResultTransferStatements";+import { adaptMysqlDdlCollations, mysqlDdlCollations, temporalColumnTypesFromDdl } from "./queryResultTransferDdl";+import { analyzeEditableQuery } from "@/lib/sql/sqlAnalysis";+import { queryResultTransferSqlLiteral, queryResultTransferTargetType } from "./queryResultTransferValues";++const open = defineModel<boolean>("open", { default: false });+const props = defineProps<{+ sourceConnectionId: string;+ sourceDatabase: string;+ sourceSchema?: string;+ sourceTable?: string;+ sourceSql?: string;+ sourceDatabaseType?: DatabaseType;+ result: QueryResult;+ loadResult: () => Promise<QueryResult | undefined>;+ loadSourceDdl?: () => Promise<string | undefined>;+}>();++const { t } = useI18n();+const { toast } = useToast();+const connections = useConnectionStore();+const settingsStore = useSettingsStore();+const productionSafetyStore = useProductionSafetyStore();+const targetConnectionId = ref("");+const targetDatabase = ref("");+const targetDatabases = ref<string[]>([]);+const databasesLoading = ref(false);+let dragBounds = { left: 0, right: 0, top: 0, bottom: 0 };+let dragX = 0;+let dragY = 0;+const dragHandle = ref<HTMLElement>();+const dialogElement = computed(() => dragHandle.value?.closest<HTMLElement>('[data-slot="dialog-content"]'));+let stopActiveDrag: (() => void) | undefined;+let dragFrame: number | undefined;+// Keep pointer movement out of Vue's render cycle: the connection tree and+// export form must not be patched on every mouse event.+function paintPosition() {+ if (dragFrame !== undefined) cancelAnimationFrame(dragFrame);+ dragFrame = undefined;+ const element = dialogElement.value;+ if (element) element.style.transform = `translate3d(${dragX}px, ${dragY}px, 0)`;+}+function schedulePosition() {+ if (dragFrame === undefined) dragFrame = requestAnimationFrame(paintPosition);+}+function updateDragBounds(rect: DOMRect) {+ const left = dragX - rect.left + 8;+ const top = dragY - rect.top + 8;+ // If the viewport is smaller than the content, keep its header accessible.+ dragBounds = { left, right: Math.max(left, dragX + window.innerWidth - rect.right - 8), top, bottom: Math.max(top, dragY + window.innerHeight - rect.bottom - 8) };+}+let positionUpdatePending = false;+function constrainDialogPosition() {+ // Resizing changes the drag coordinate origin. End the old gesture rather+ // than letting its next pointer event restore coordinates from the old size.+ stopActiveDrag?.();+ if (positionUpdatePending) return;+ positionUpdatePending = true;+ void nextTick(() => {+ positionUpdatePending = false;+ if (!open.value) return;+ const rect = dialogElement.value?.getBoundingClientRect();+ if (!rect) return;+ updateDragBounds(rect);+ dragX = Math.max(dragBounds.left, Math.min(dragBounds.right, dragX));+ dragY = Math.max(dragBounds.top, Math.min(dragBounds.bottom, dragY));+ paintPosition();+ });+}+useEventListener(window, "resize", constrainDialogPosition);+useResizeObserver(dialogElement, constrainDialogPosition);+onBeforeUnmount(() => {+ stopActiveDrag?.();+ if (dragFrame !== undefined) cancelAnimationFrame(dragFrame);+});+function startDrag(event: PointerEvent) {+ if (event.button !== 0) return;+ stopActiveDrag?.();+ const handle = event.currentTarget as HTMLElement;+ const rect = handle.closest('[data-slot="dialog-content"]')?.getBoundingClientRect();+ if (!rect) return;+ const start = { x: event.clientX, y: event.clientY, offsetX: dragX, offsetY: dragY };+ updateDragBounds(rect);+ handle.setPointerCapture(event.pointerId);+ const move = (next: PointerEvent) => {+ if (next.pointerId !== event.pointerId) return;+ dragX = Math.max(dragBounds.left, Math.min(dragBounds.right, start.offsetX + next.clientX - start.x));+ dragY = Math.max(dragBounds.top, Math.min(dragBounds.bottom, start.offsetY + next.clientY - start.y));+ schedulePosition();+ };+ const stop = () => {+ paintPosition();+ handle.removeEventListener("pointermove", move);+ handle.removeEventListener("pointerup", finish);+ handle.removeEventListener("pointercancel", cancel);+ window.removeEventListener("blur", stop);+ handle.removeEventListener("lostpointercapture", stop);+ if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId);+ if (stopActiveDrag === stop) stopActiveDrag = undefined;+ };+ const finish = (next: PointerEvent) => {+ if (next.pointerId !== event.pointerId) return;+ move(next);+ stop();+ };+ const cancel = (next: PointerEvent) => {+ if (next.pointerId === event.pointerId) stop();+ };+ stopActiveDrag = stop;+ handle.addEventListener("pointermove", move);+ handle.addEventListener("pointerup", finish);+ handle.addEventListener("pointercancel", cancel);+ window.addEventListener("blur", stop);+ handle.addEventListener("lostpointercapture", stop, { once: true });+ event.preventDefault();+}+const targetSchema = ref("");+const targetTable = ref("");+const mode = ref<"append" | "overwrite">("append");+const createTable = ref(true);+const submitting = ref(false);+const progress = ref("");+const cancelRequested = ref(false);+const canCancel = ref(false);+let sourceRevision = 0;+watch(+ () => [props.result, props.sourceSql, props.sourceDatabaseType, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, props.sourceTable],+ () => {+ sourceRevision += 1;+ },+ { flush: "sync" },+);+onBeforeUnmount(() => {+ sourceRevision += 1;+});++const sqlConnections = computed(() => connections.connections.filter((item) => supportsQueryResultTransfer(item)));+const targetConfig = computed<ConnectionConfig | undefined>(() => (targetConnectionId.value ? connections.getConfig(targetConnectionId.value) : undefined));+const targetDatabaseType = computed(() => queryResultTransferDatabaseType(targetConfig.value));+const reviewMode = ref<"preview" | "confirm" | null>(null);+const reviewOpen = computed({+ get: () => reviewMode.value !== null,+ set: (value: boolean) => {+ if (!value) reviewMode.value = null;+ },+});+const canTransfer = computed(() => open.value && !!targetConfig.value && !!targetDatabaseType.value && !!targetDatabase.value.trim() && !!targetTable.value.trim() && (!isSchemaAware(targetDatabaseType.value) || !!targetSchema.value.trim()) && !submitting.value && !databasesLoading.value);+const sourceLocation = computed(() => [connections.getConfig(props.sourceConnectionId)?.name || props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, props.sourceTable || props.result.sourceLabel].filter(Boolean).join(" / "));+const targetLocation = computed(() => [targetConfig.value?.name, targetDatabase.value.trim(), isSchemaAware(targetDatabaseType.value) ? targetSchema.value.trim() : undefined, targetTable.value.trim()].filter(Boolean).join(" / "));+const operationSummary = computed(() => t(createTable.value ? "grid.exportDatabasePlanCreate" : mode.value === "overwrite" ? "grid.exportDatabasePlanOverwrite" : "grid.exportDatabasePlanAppend"));+// Any edited source/target invalidates the pending approval. Never execute a+// different destination or result than the one shown in the confirmation.+watch(+ () => [open.value, props.result, props.sourceSql, props.sourceDatabaseType, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, props.sourceTable, targetConfig.value, targetDatabase.value, targetSchema.value, targetTable.value, mode.value, createTable.value],+ () => {+ reviewMode.value = null;+ },+ { flush: "sync" },+);+function showReview(mode: "preview" | "confirm") {+ if (canTransfer.value) reviewMode.value = mode;+}+function confirmTransfer() {+ if (reviewMode.value !== "confirm" || !canTransfer.value) return;+ reviewMode.value = null;+ void transfer();+}++watch(open, (value) => {+ if (!value) {+ stopActiveDrag?.();+ if (submitting.value && canCancel.value) cancelRequested.value = true;+ return;+ }+ if (submitting.value) return;+ dragX = 0;+ dragY = 0;+ void nextTick(paintPosition);+ targetConnectionId.value = "";+ targetDatabase.value = "";+ targetSchema.value = "";+ targetTable.value = props.result.sourceLabel?.replace(/[^A-Za-z0-9_]+/g, "_") || "query_result";+ mode.value = "append";+ createTable.value = true;+ progress.value = "";+ cancelRequested.value = false;+ canCancel.value = false;+});++watch([open, targetConnectionId], async ([isOpen, id], _previous, onCleanup) => {+ let stale = false;+ onCleanup(() => {+ stale = true;+ });+ targetDatabases.value = [];+ databasesLoading.value = false;+ targetDatabase.value = "";+ targetSchema.value = "";+ if (!isOpen || !id) return;+ const config = connections.getConfig(id);+ if (!config) return;+ targetDatabase.value = config.database || "";+ targetSchema.value = config.default_schema || "";+ databasesLoading.value = true;+ try {+ await connections.ensureConnected(id);+ if (stale) return;+ const databases = await api.listDatabases(id);+ if (stale) return;+ targetDatabases.value = databaseOptionsForConnection(+ databases.map((item) => item.name),+ config,+ );+ if (!targetDatabase.value && targetDatabases.value.length === 1) targetDatabase.value = targetDatabases.value[0]!;+ } catch (error) {+ if (!stale) toast(formatError(error));+ } finally {+ if (!stale) databasesLoading.value = false;+ }+});++function uniqueColumnNames(columns: string[]): string[] {+ const used = new Set<string>();+ return columns.map((column, index) => {+ const base = column.trim() || `column_${index + 1}`;+ let name = base;+ let suffix = 2;+ while (used.has(name.toLowerCase())) name = `${base}_${suffix++}`;+ used.add(name.toLowerCase());+ return name;+ });+}++function requestCancel() {+ if (submitting.value && canCancel.value) {+ cancelRequested.value = true;+ progress.value = t("grid.exportDatabaseCancelling");+ } else if (!submitting.value) {+ open.value = false;+ }+}++async function transfer() {+ const config = targetConfig.value;+ const databaseType = targetDatabaseType.value;+ const database = targetDatabase.value.trim();+ // In MySQL the database is the namespace. Do not allow a hidden second+ // database qualifier to bypass the selected database's production guard.+ // SQLite transactions execute on the main connection, so every target must+ // explicitly name the selected main/attached database in its SQL.+ const schema = databaseType === "sqlite" ? normalizeSqliteNamespace(database, config) : isSchemaAware(databaseType) ? targetSchema.value.trim() : "";+ const tableName = targetTable.value.trim();+ if (!config || !databaseType || !database || !tableName || (isSchemaAware(databaseType) && !schema) || submitting.value) return;+ const target = { config: { ...config }, databaseType, database, schema, tableName, mode: mode.value, createTable: createTable.value };+ const source = { ...props };+ const revision = sourceRevision;+ const identifierQuote = connections.connectionIdentifierQuote(config.id);+ const quote = (name: string) => (!identifierQuote ? quoteTableIdentifier(databaseType, name) : identifierQuote === "[" ? `[${name.replaceAll("]", "]]")}]` : `${identifierQuote}${name.replaceAll(identifierQuote, identifierQuote + identifierQuote)}${identifierQuote}`);+ const table = [schema, tableName].filter(Boolean).map(quote).join(".");+ let createdTargetTable = false;+ submitting.value = true;+ canCancel.value = true;+ cancelRequested.value = false;+ const checkCancelled = () => {+ if (cancelRequested.value || revision !== sourceRevision || !open.value) throw new Error(t("grid.exportDatabaseCancelled"));+ };+ const execute = async (sql: string) => {+ // DDL was already split above. Keep cleanup blocks intact even when a+ // generic JDBC connection uses a different backend statement splitter.+ const result = await api.executeQuery(target.config.id, target.database, sql, target.schema || undefined, undefined, { executionMode: "simple" });+ if (result.execution_error) throw new Error(result.error ? formatError(result.error) : t("grid.exportDatabaseExecutionFailed"));+ return result;+ };+ try {+ const allowed = await ensureReadOnlyWriteAccess({ connection: target.config, source: "Query result transfer", treatAsMutation: true });+ checkCancelled();+ if (!allowed) return;+ if (productionContextForDatabase(target.config, target.database).active) {+ const confirmed = await productionSafetyStore.requestConfirmation({+ sql: `${target.mode === "overwrite" ? "DELETE FROM" : "INSERT INTO"} ${table}`,+ connectionName: target.config.name,+ database: target.database,+ productionDatabases: target.config.production_databases,+ source: t("grid.exportDatabase"),+ });+ checkCancelled();+ if (!confirmed) return;+ }+ const fullResult = await source.loadResult();+ checkCancelled();+ if (!fullResult || !fullResult.columns.length || fullResult.execution_error) throw new Error(t("grid.exportDatabaseEmpty"));+ const rowLimit = settingsStore.editorSettings.exportRowLimitEnabled ? settingsStore.editorSettings.exportRowLimit : undefined;+ if (rowLimit && fullResult.rows.length > rowLimit) throw new Error(t("grid.exportDatabaseRowLimit", { limit: rowLimit }));+ if (queryResultTransferIncomplete(fullResult, rowLimit)) throw new Error(t("grid.exportDatabaseIncomplete"));++ const analysis = analyzeEditableQuery(source.sourceSql || "");+ const canReuseSourceDdl = target.createTable && source.sourceDatabaseType === target.databaseType && !!source.sourceTable && !!analysis?.selectStar && !analysis.sources?.length;+ let tableDdl: string | undefined;+ let existingColumns: ColumnInfo[] | undefined;+ if (canReuseSourceDdl) {+ tableDdl = await source.loadSourceDdl?.();+ checkCancelled();+ if (!tableDdl) throw new Error(t("grid.exportDatabaseDdlUnavailable"));+ } else if (!target.createTable) {+ // Existing targets have their own generated/identity columns and types.+ tableDdl = await api.getTableDisplayDdl(target.config.id, target.database, target.schema || target.database, target.tableName);+ checkCancelled();+ if (!tableDdl) throw new Error(t("grid.exportDatabaseDdlUnavailable"));+ if (["mysql", "goldendb"].includes(target.databaseType) && !transactionalMysqlTableDdl(tableDdl)) throw new Error(t("grid.exportDatabaseNonTransactionalTarget"));+ existingColumns = await api.getColumns(target.config.id, target.database, target.schema || target.database, target.tableName);+ checkCancelled();+ if (!existingColumns.length) throw new Error(t("grid.exportDatabaseDdlUnavailable"));+ }+ const nonInsertable = tableDdl ? nonInsertableColumnNamesFromDdl(tableDdl, target.databaseType) : new Set<string>();+ const declaredTemporalTypes = tableDdl ? temporalColumnTypesFromDdl(tableDdl, target.databaseType) : new Map<string, string | null>();+ const identity = tableDdl ? identityColumnNamesFromDdl(tableDdl, target.databaseType) : new Set<string>();+ const alwaysIdentity = tableDdl ? alwaysIdentityColumnNamesFromDdl(tableDdl, target.databaseType) : new Set<string>();+ const hidden = new Set(fullResult.hidden_column_indexes ?? []);+ const visibleIndexes = fullResult.columns.map((_, index) => index).filter((index) => !hidden.has(index));+ const visibleNames = visibleIndexes.map((index) => fullResult.columns[index]!);+ const existingColumn = (name: string) => existingColumns?.find((item) => item.name === name) ?? (["mysql", "goldendb", "sqlserver"].includes(target.databaseType) ? existingColumns?.find((item) => item.name.toLowerCase() === name.toLowerCase()) : undefined);+ const columnNames = tableDdl ? visibleNames.map((name) => existingColumn(name)?.name ?? name) : uniqueColumnNames(visibleNames);+ const writableIndexes = columnNames.map((column, index) => ({ column, index: visibleIndexes[index]! })).filter(({ column }) => !nonInsertable.has(column));+ if (!writableIndexes.length) throw new Error(t("grid.exportDatabaseNoWritableColumns"));+ const identityColumns = writableIndexes.filter(({ column }) => identity.has(column));+ const pgIdentity = ["postgres", "kingbase", "highgo", "vastbase"].includes(target.databaseType);+ if (identityColumns.length && !pgIdentity && target.databaseType !== "sqlserver") throw new Error(t("grid.exportDatabaseIdentityUnsupported"));+ if (identityColumns.length && target.config.driver_profile === "sqlserver-legacy") throw new Error(t("grid.exportDatabaseIdentityUnsupported"));+ const overrideIdentity = writableIndexes.some(({ column }) => alwaysIdentity.has(column));+ const columns = writableIndexes.map(({ column }) => quote(column));+ const targetColumnTypes = writableIndexes.map(({ column, index }) => {+ const declaredTemporalType = declaredTemporalTypes.get(column);+ if (declaredTemporalType === null) throw new Error(t("grid.exportDatabaseValueUnsupported", { column }));+ if (existingColumns) {+ const metadata = existingColumn(column);+ if (!metadata) throw new Error(t("grid.exportDatabaseTargetColumnMissing", { column }));+ return declaredTemporalType ?? metadata.data_type;+ }+ if (declaredTemporalType) return declaredTemporalType;+ if (canReuseSourceDdl && fullResult.column_types?.[index]) return fullResult.column_types[index]!;+ return queryResultTransferTargetType(fullResult.column_types?.[index], target.databaseType, source.sourceDatabaseType);+ });+ const createStatements: string[] = [];+ const statements: string[] = [];+ if (target.createTable) {+ progress.value = t("grid.exportDatabasePreparing");+ const targetTables = await api.listTables(target.config.id, target.database, target.schema);+ checkCancelled();+ if (targetTables.some((item) => item.name.toLowerCase() === target.tableName.toLowerCase())) throw new Error(t("grid.exportDatabaseTargetExists", { table: target.tableName }));+ let rewrittenDdl = tableDdl ? rewriteCreateTableName(tableDdl, table, target.databaseType, ["mysql", "goldendb"].includes(target.databaseType) ? source.sourceSchema || source.sourceDatabase : undefined) : undefined;+ if (canReuseSourceDdl && !rewrittenDdl) throw new Error(t("grid.exportDatabaseDdlUnavailable"));+ if (rewrittenDdl && ["mysql", "goldendb"].includes(target.databaseType) && mysqlDdlCollations(rewrittenDdl).length) {+ const metadata = await execute("SHOW COLLATION");+ checkCancelled();+ const column = metadata.columns.findIndex((name) => name.toLowerCase() === "collation");+ const supported = column < 0 ? [] : metadata.rows.map((row) => String(row[column] ?? ""));+ const adapted = adaptMysqlDdlCollations(rewrittenDdl, supported);+ if (adapted.unsupported.length) throw new Error(t("grid.exportDatabaseUnsupportedCollation", { collations: adapted.unsupported.join(", ") }));+ rewrittenDdl = adapted.ddl;+ if (adapted.changes.length) toast(t("grid.exportDatabaseCollationAdapted", { changes: adapted.changes.join(", ") }), 10000);+ }+ if (rewrittenDdl)+ createStatements.push(+ ...splitSqlStatementRanges(rewrittenDdl, target.databaseType)+ .map((range) => range.sql)+ .filter((sql) => sql.trim()),+ );+ else createStatements.push(`CREATE TABLE ${table} (${writableIndexes.map(({ column }, index) => `${quote(column)} ${targetColumnTypes[index]}`).join(", ")})`);+ } else if (target.mode === "overwrite") statements.push(`DELETE FROM ${table}`);++ const inserts: string[] = [];+ const buildInserts = (values: string[]) => (target.config.driver_profile === "sqlserver-legacy" ? values.flatMap((value) => queryResultTransferInsertSql(table, columns, [value], target.databaseType)) : queryResultTransferInsertSql(table, columns, values, target.databaseType, overrideIdentity));+ for (let offset = 0; offset < fullResult.rows.length; offset += 200) {+ checkCancelled();+ const rows = fullResult.rows.slice(offset, offset + 200);+ const values = rows.map((row) => {+ if (row.length !== fullResult.columns.length) throw new Error(t("grid.exportDatabaseIncomplete"));+ const literals = writableIndexes.map(({ column, index }, columnIndex) => {+ const literal = queryResultTransferSqlLiteral(row[index], target.databaseType, fullResult.column_types?.[index], targetColumnTypes[columnIndex], source.sourceDatabaseType);+ if (literal === undefined) throw new Error(t("grid.exportDatabaseValueUnsupported", { column }));+ return literal;+ });+ return `(${literals.join(", ")})`;+ });+ // Split large batches down to a single row before rejecting oversized values.+ let batch: string[] = [];+ let bytes = 0;+ for (const value of values) {+ const length = new TextEncoder().encode(value).length;+ if (length > 512 * 1024) throw new Error(t("grid.exportDatabaseBatchTooLarge"));+ if (bytes + length > 512 * 1024) {+ inserts.push(...buildInserts(batch));+ batch = [];+ bytes = 0;+ }+ batch.push(value);+ bytes += length;+ }+ inserts.push(...buildInserts(batch));+ progress.value = `${Math.min(offset + rows.length, fullResult.rows.length)} / ${fullResult.rows.length}`;+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ if (target.databaseType === "sqlserver" && identityColumns.length && inserts.length) statements.push(withSqlServerIdentityInsert(table, inserts));+ else statements.push(...inserts);+ if (pgIdentity && identityColumns.length && fullResult.rows.length) {+ for (const { column } of identityColumns) {+ statements.push(postgresTransferSequenceSyncSql(table, column));+ }+ }+ checkCancelled();+ progress.value = t("grid.exportDatabaseWriting");+ canCancel.value = false;+ if (target.createTable && queryResultTransferNeedsCreateCleanup(target.databaseType)) {+ // CREATE can commit implicitly. Only take ownership after it succeeds;+ // a concurrent creator's table must never be deleted by our cleanup.+ await execute(createStatements[0]!);+ createdTargetTable = true;+ for (const ddl of createStatements.slice(1)) await execute(ddl);+ if (statements.length) await api.executeInTransaction(target.config.id, target.database, statements, target.schema || undefined);+ } else {+ const batch = [...createStatements, ...statements];+ if (batch.length) await api.executeInTransaction(target.config.id, target.database, batch, target.schema || undefined);+ }+ toast(t("grid.exportDatabaseDone"));+ open.value = false;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (createdTargetTable) {+ try {+ await execute(queryResultTransferCreateCleanupSql(table, target.databaseType));+ } catch (cleanupError) {+ toast(t("grid.exportDatabaseCleanupFailed", { table, message, error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) }), 8000);+ return;+ }+ }+ toast(message, 6000);+ } finally {+ submitting.value = false;+ canCancel.value = false;+ progress.value = "";+ }+}+</script>++<template>+ <Dialog v-model:open="open" :modal="false">+ <DialogContent class="sm:max-w-[640px] !animate-none !transition-none will-change-transform" :show-close-button="!submitting" @escape-key-down="submitting && $event.preventDefault()" @interact-outside.prevent>+ <DialogHeader>+ <div ref="dragHandle" class="cursor-move touch-none select-none pr-8" @pointerdown="startDrag">+ <DialogTitle class="flex items-center gap-2"><ArrowRightLeft class="h-4 w-4" />{{ t("grid.exportDatabase") }}</DialogTitle>+ <DialogDescription>{{ t("grid.exportDatabaseDescription", { database: sourceDatabase, columns: result.columns.length, rows: result.rows.length }) }}</DialogDescription>+ </div>+ </DialogHeader>+ <div class="grid gap-3 py-2">+ <div class="space-y-1.5">+ <Label>{{ t("transfer.targetConnection") }}</Label>+ <ConnectionTreeSelect+ v-model="targetConnectionId"+ :connections="sqlConnections"+ :layout="connections.sidebarLayout"+ :placeholder="t('transfer.selectConnection')"+ :search-placeholder="t('transfer.searchConnection')"+ :empty-text="t('common.noResults')"+ :disabled="submitting"+ trigger-class="h-8 w-full justify-between text-xs"+ list-class="w-[var(--reka-popover-trigger-width)]"+ />+ </div>+ <div class="grid grid-cols-2 gap-3">+ <div class="space-y-1.5">+ <Label>{{ t("transfer.targetDatabase") }}</Label+ ><SearchableSelect+ v-model="targetDatabase"+ :options="targetDatabases"+ :loading="databasesLoading"+ :disabled="submitting || !targetConnectionId"+ allow-custom+ :placeholder="t('transfer.selectDatabase')"+ :search-placeholder="t('transfer.searchDatabase')"+ :empty-text="t('common.noResults')"+ :loading-text="t('common.loading')"+ trigger-class="h-8 w-full justify-between text-xs"+ content-class="w-[var(--reka-popover-trigger-width)]"+ />+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("transfer.targetSchema") }}{{ isSchemaAware(targetDatabaseType) ? " *" : "" }}</Label+ ><Input v-model="targetSchema" :disabled="submitting || !isSchemaAware(targetDatabaseType)" class="h-8 text-xs" />+ </div>+ </div>+ <div class="space-y-1.5">+ <Label>{{ t("grid.exportDatabaseTable") }}</Label+ ><Input v-model="targetTable" :disabled="submitting" class="h-8 text-xs" />+ </div>+ <div class="flex flex-wrap items-center gap-4 text-xs">+ <label class="flex items-center gap-2"><input v-model="createTable" :disabled="submitting" type="checkbox" />{{ t("grid.exportDatabaseCreateTable") }}</label>+ <label class="flex items-center gap-2"><input v-model="mode" :disabled="submitting" type="radio" value="append" />{{ t("transfer.modeAppend") }}</label>+ <label class="flex items-center gap-2"><input v-model="mode" :disabled="submitting" type="radio" value="overwrite" />{{ t("grid.exportDatabaseModeOverwrite") }}</label>+ </div>+ <p v-if="progress" class="text-xs text-muted-foreground">{{ progress }}</p>+ </div>+ <DialogFooter>+ <Button variant="outline" size="sm" :disabled="submitting && !canCancel" @click="requestCancel">{{ t("transfer.cancel") }}</Button>+ <Button variant="outline" size="sm" :disabled="!canTransfer" data-testid="transfer-preview" @click="showReview('preview')">{{ t("grid.exportDatabasePreview") }}</Button>+ <Button size="sm" :disabled="!canTransfer" @click="showReview('confirm')"><Loader2 v-if="submitting" class="mr-1.5 h-3.5 w-3.5 animate-spin" /><ArrowRightLeft v-else class="mr-1.5 h-3.5 w-3.5" />{{ t("transfer.start") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ <Dialog v-if="reviewOpen" v-model:open="reviewOpen">+ <DialogContent class="sm:max-w-[640px]" @interact-outside.prevent>+ <DialogHeader>+ <DialogTitle>{{ t(reviewMode === "confirm" ? "grid.exportDatabaseConfirmTitle" : "grid.exportDatabasePreview") }}</DialogTitle>+ <DialogDescription>{{ t(reviewMode === "confirm" ? "grid.exportDatabaseConfirmDescription" : "grid.exportDatabasePreviewDescription") }}</DialogDescription>+ </DialogHeader>+ <div class="min-h-0 overflow-y-auto space-y-4" data-testid="transfer-overview">+ <dl class="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-3 text-sm">+ <dt class="text-muted-foreground">{{ t("grid.exportDatabaseSource") }}</dt>+ <dd class="break-words">{{ sourceLocation }}</dd>+ <dt class="text-muted-foreground">{{ t("grid.exportDatabaseTarget") }}</dt>+ <dd class="break-words font-medium">{{ targetLocation }}</dd>+ <dt class="text-muted-foreground">{{ t("grid.exportDatabaseScope") }}</dt>+ <dd>{{ t("grid.exportDatabaseLoadedScope", { rows: result.rows.length, columns: result.columns.length }) }}</dd>+ <dt class="text-muted-foreground">{{ t("grid.exportDatabaseOperations") }}</dt>+ <dd>{{ operationSummary }}</dd>+ <dt class="text-muted-foreground">{{ t("grid.exportDatabaseColumns") }}</dt>+ <dd class="max-h-28 overflow-y-auto break-words">{{ result.columns.join(", ") }}</dd>+ </dl>+ <p class="text-xs text-muted-foreground">{{ t("grid.exportDatabasePreviewScopeNote") }}</p>+ <p v-if="!createTable && mode === 'overwrite'" class="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive" role="alert">{{ t("grid.exportDatabaseOverwriteWarning") }}</p>+ </div>+ <DialogFooter>+ <Button variant="outline" size="sm" data-testid="transfer-review-back" @click="reviewMode = null">{{ t("grid.exportDatabaseBack") }}</Button>+ <Button v-if="reviewMode === 'preview'" size="sm" :disabled="!canTransfer" data-testid="transfer-preview-start" @click="showReview('confirm')">{{ t("transfer.start") }}</Button>+ <Button v-else size="sm" :variant="!createTable && mode === 'overwrite' ? 'destructive' : 'default'" :disabled="!canTransfer" data-testid="transfer-confirm" @click="confirmTransfer">{{ t("grid.exportDatabaseConfirm") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/transfer/__tests__/QueryResultTransferDialog.spec.ts b/apps/desktop/src/components/transfer/__tests__/QueryResultTransferDialog.spec.tsnew file mode 100644index 0000000000..bbe59f24a8--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/QueryResultTransferDialog.spec.ts@@ -0,0 +1,959 @@+// @vitest-environment happy-dom++import { createApp, defineComponent, h, nextTick, ref, shallowRef, type App } from "vue";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ConnectionConfig, DatabaseType, QueryResult } from "@/types/database";++const { DatabaseSync } = process.getBuiltinModule("node:sqlite") as typeof import("node:sqlite");++const api = vi.hoisted(() => ({+ executeInTransaction: vi.fn(),+ executeQuery: vi.fn(),+ executeMulti: vi.fn(),+ listTables: vi.fn(),+ listDatabases: vi.fn(),+ getTableDisplayDdl: vi.fn(),+ getColumns: vi.fn(),+}));+const storeMocks = vi.hoisted(() => ({+ connections: [] as ConnectionConfig[],+ connectionStore: null as {+ connections: ConnectionConfig[];+ sidebarLayout: { groups: unknown[]; order: unknown[] };+ ensureConnected: (id: string) => Promise<void>;+ getConfig: (id: string) => ConnectionConfig | undefined;+ connectionIdentifierQuote: (id: string) => string | undefined;+ } | null,+ settingsStore: { editorSettings: { exportRowLimitEnabled: false, exportRowLimit: 1000 } },+ productionSafetyStore: { requestConfirmation: vi.fn() },+ toast: vi.fn(),+ ensureReadOnlyWriteAccess: vi.fn(),+}));++vi.mock("@/lib/backend/api", () => api);+vi.mock("@/lib/database/readOnlyWriteAccess", () => ({ ensureReadOnlyWriteAccess: storeMocks.ensureReadOnlyWriteAccess }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: storeMocks.toast }) }));+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => storeMocks.settingsStore }));+vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => storeMocks.productionSafetyStore }));+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => storeMocks.connectionStore }));+vi.mock("vue-i18n", () => ({+ useI18n: () => ({+ t: (key: string, values?: Record<string, unknown>) => (values ? `${key} ${JSON.stringify(values)}` : key),+ }),+}));++vi.mock("@/components/ui/dialog", async () => {+ const { defineComponent, h } = await import("vue");+ const passthrough = defineComponent({+ inheritAttrs: false,+ props: { open: { type: Boolean, default: undefined } },+ setup(_props, { attrs, slots }) {+ return () => h("div", attrs, slots.default?.());+ },+ });+ const content = defineComponent({+ inheritAttrs: false,+ setup(_props, { attrs, slots }) {+ return () => h("div", { ...attrs, "data-slot": "dialog-content" }, slots.default?.());+ },+ });+ return { Dialog: passthrough, DialogContent: content, DialogDescription: passthrough, DialogFooter: passthrough, DialogHeader: passthrough, DialogTitle: passthrough };+});++vi.mock("@/components/ui/button", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ Button: defineComponent({+ inheritAttrs: false,+ props: { disabled: Boolean },+ emits: ["click"],+ setup(props, { attrs, emit, slots }) {+ return () => h("button", { ...attrs, disabled: props.disabled, onClick: (event: Event) => emit("click", event) }, slots.default?.());+ },+ }),+ };+});++vi.mock("@/components/ui/input", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ Input: defineComponent({+ inheritAttrs: false,+ props: { modelValue: { type: String, default: "" }, disabled: Boolean },+ emits: ["update:modelValue"],+ setup(props, { attrs, emit }) {+ return () =>+ h("input", {+ ...attrs,+ disabled: props.disabled,+ value: props.modelValue,+ onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value),+ });+ },+ }),+ };+});++vi.mock("@/components/ui/searchable-select/SearchableSelect.vue", () => ({+ default: defineComponent({+ props: ["modelValue", "options", "loading", "disabled"],+ emits: ["update:modelValue"],+ setup(props, { emit }) {+ return () => h("input", { value: props.modelValue, disabled: props.disabled, "data-databases": JSON.stringify(props.options), "data-loading": String(props.loading), onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value) });+ },+ }),+}));++vi.mock("@/components/ui/label", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ Label: defineComponent({+ setup(_props, { slots }) {+ return () => h("label", slots.default?.());+ },+ }),+ };+});++vi.mock("@/components/connection/ConnectionTreeSelect.vue", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ default: defineComponent({+ props: { modelValue: { type: String, default: "" }, connections: { type: Array, default: () => [] } },+ emits: ["update:modelValue"],+ setup(props, { emit }) {+ return () =>+ h(+ "select",+ {+ "data-testid": "target-connection",+ value: props.modelValue,+ onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value),+ },+ (props.connections as ConnectionConfig[]).map((connection) => h("option", { value: connection.id }, connection.name)),+ );+ },+ }),+ };+});++vi.mock("@lucide/vue", async () => {+ const { defineComponent, h } = await import("vue");+ const icon = defineComponent({ setup: () => () => h("span") });+ return { ArrowRightLeft: icon, Loader2: icon };+});++import QueryResultTransferDialog from "../QueryResultTransferDialog.vue";++const mountedApps: App[] = [];+const result: QueryResult = {+ columns: ["id", "name"],+ column_types: ["INTEGER", "VARCHAR(32)"],+ rows: [+ [1, "Alice"],+ [2, "Bob"],+ ],+ affected_rows: 0,+ execution_time_ms: 1,+ sourceLabel: "items",+};++function config(id: string, dbType: DatabaseType): ConnectionConfig {+ return { id, name: `${dbType} target`, db_type: dbType, host: "localhost", port: 1234, username: "user", password: "secret", database: "target", default_schema: "app" };+}++function configureStore(target: ConnectionConfig): void {+ storeMocks.connections = [target];+ storeMocks.connectionStore = {+ connections: storeMocks.connections,+ ensureConnected: vi.fn().mockResolvedValue(undefined),+ sidebarLayout: { groups: [], order: [] },+ getConfig: (id) => storeMocks.connections.find((connection) => connection.id === id),+ connectionIdentifierQuote: () => undefined,+ };+}++async function settle(): Promise<void> {+ for (let index = 0; index < 6; index += 1) {+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+}++async function mountDialog(target: ConnectionConfig, overrides: Partial<Record<string, unknown>> = {}) {+ configureStore(target);+ const model = ref(false);+ const dynamicProps = shallowRef(overrides);+ const loadResult = vi.fn().mockResolvedValue(result);+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp(+ defineComponent({+ setup() {+ return () =>+ h(QueryResultTransferDialog, {+ open: model.value,+ "onUpdate:open": (value: boolean) => {+ model.value = value;+ },+ sourceConnectionId: "source",+ sourceDatabase: "source_db",+ sourceDatabaseType: "mysql",+ result,+ loadResult,+ ...dynamicProps.value,+ });+ },+ }),+ );+ mountedApps.push(app);+ app.mount(container);+ model.value = true;+ await settle();+ const connection = container.querySelector<HTMLSelectElement>("[data-testid='target-connection']")!;+ connection.value = target.id;+ connection.dispatchEvent(new Event("change", { bubbles: true }));+ await settle();+ return {+ app,+ container,+ model,+ loadResult,+ setProps: (values: Record<string, unknown>) => {+ dynamicProps.value = { ...dynamicProps.value, ...values };+ },+ };+}++function input(container: HTMLElement, type: string, index = 0): HTMLInputElement {+ return [...container.querySelectorAll<HTMLInputElement>(`input[type='${type}']`)][index]!;+}++function startButton(container: HTMLElement): HTMLButtonElement {+ return [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("transfer.start"))!;+}++async function startTransfer(container: HTMLElement): Promise<void> {+ startButton(container).click();+ await settle();+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-confirm"]')!.click();+ await settle();+}++function textInput(container: HTMLElement, index: number): HTMLInputElement {+ return [...container.querySelectorAll<HTMLInputElement>("input:not([type])")][index]!;+}++function setInput(element: HTMLInputElement, value: string): void {+ element.value = value;+ element.dispatchEvent(new Event("input", { bubbles: true }));+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((complete) => {+ resolve = complete;+ });+ return { promise, resolve };+}++describe("QueryResultTransferDialog execution boundaries", () => {+ beforeEach(() => {+ api.executeInTransaction.mockReset().mockResolvedValue(undefined);+ api.executeQuery.mockReset().mockResolvedValue({ columns: [], rows: [] });+ api.executeMulti.mockReset();+ api.listDatabases.mockReset().mockResolvedValue([{ name: "target_db" }]);+ api.listTables.mockReset().mockResolvedValue([]);+ api.getTableDisplayDdl.mockReset().mockResolvedValue('CREATE TABLE "items" ("id" INTEGER, "name" VARCHAR(32)) ENGINE=InnoDB');+ api.getColumns.mockReset().mockResolvedValue([+ { name: "id", data_type: "INTEGER" },+ { name: "name", data_type: "VARCHAR(32)" },+ ]);+ storeMocks.ensureReadOnlyWriteAccess.mockReset().mockResolvedValue(true);+ storeMocks.productionSafetyStore.requestConfirmation.mockReset().mockResolvedValue(true);+ storeMocks.toast.mockReset();+ storeMocks.settingsStore.editorSettings = { exportRowLimitEnabled: false, exportRowLimit: 1000 };+ });++ afterEach(() => {+ for (const app of mountedApps.splice(0)) app.unmount();+ document.body.textContent = "";+ });++ it.each(["postgres", "sqlite", "sqlserver"] as DatabaseType[])("keeps %s overwrite/create in one transaction", async (dbType) => {+ const { container } = await mountDialog(config("target", dbType));+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ expect(api.executeInTransaction).toHaveBeenCalledTimes(1);+ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(statements.some((statement) => /^CREATE TABLE /i.test(statement))).toBe(true);+ expect(statements.some((statement) => /^INSERT INTO /i.test(statement))).toBe(true);+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("loads searchable database options for the selected connection", async () => {+ api.listDatabases.mockResolvedValue([{ name: "app" }, { name: "archive" }]);+ const { container } = await mountDialog({ id: "target", name: "MySQL", db_type: "mysql", database: "app" } as ConnectionConfig);+ expect(api.listDatabases).toHaveBeenCalledWith("target");+ expect(textInput(container, 0).getAttribute("data-databases")).toBe('["app","archive"]');+ expect(textInput(container, 0).value).toBe("app");+ });++ it("ignores a database response from a closed dialog", async () => {+ let resolveOld!: (value: { name: string }[]) => void;+ api.listDatabases.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveOld = resolve;+ }),+ );+ const { container, model } = await mountDialog({ id: "target", name: "MySQL", db_type: "mysql", database: "app" } as ConnectionConfig);+ model.value = false;+ await settle();+ model.value = true;+ await settle();+ api.listDatabases.mockResolvedValueOnce([{ name: "new_database" }]);+ const connection = container.querySelector<HTMLSelectElement>("[data-testid='target-connection']")!;+ connection.value = "target";+ connection.dispatchEvent(new Event("change", { bubbles: true }));+ await settle();+ resolveOld([{ name: "stale_database" }]);+ await settle();+ expect(textInput(container, 0).getAttribute("data-databases")).toBe('["new_database"]');+ });++ it("previews the destination and operations without reading or writing data", async () => {+ const { container, loadResult } = await mountDialog(config("target", "mysql"));+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-preview"]')!.click();+ await settle();+ const overview = container.querySelector('[data-testid="transfer-overview"]')!;+ expect(overview.textContent).toContain("mysql target / target / items");+ expect(overview.textContent).toContain("exportDatabasePlanCreate");+ expect(overview.textContent).toContain('"rows":2,"columns":2');+ expect(overview.textContent).toContain("id, name");+ expect(loadResult).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-review-back"]')!.click();+ await settle();+ expect(container.querySelector('[data-testid="transfer-overview"]')).toBeNull();+ expect(textInput(container, 2).value).toBe("items");+ });++ it("requires a separate confirmation after Start, and cancellation performs no transfer", async () => {+ const { container, loadResult } = await mountDialog(config("target", "mysql"));+ startButton(container).click();+ await settle();+ expect(container.querySelector('[data-testid="transfer-confirm"]')).not.toBeNull();+ expect(loadResult).not.toHaveBeenCalled();+ expect(storeMocks.ensureReadOnlyWriteAccess).not.toHaveBeenCalled();+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-review-back"]')!.click();+ await settle();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ await startTransfer(container);+ expect(api.executeInTransaction).toHaveBeenCalledTimes(1);+ });++ it("requires confirmation from preview and warns that overwrite deletes all existing rows", async () => {+ const { container, loadResult } = await mountDialog(config("target", "mysql"));+ input(container, "checkbox").click();+ input(container, "radio", 1).click();+ await settle();+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-preview"]')!.click();+ await settle();+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("exportDatabaseOverwriteWarning");+ expect(container.querySelector('[data-testid="transfer-overview"]')?.textContent).toContain("exportDatabasePlanOverwrite");+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-preview-start"]')!.click();+ await settle();+ expect(loadResult).not.toHaveBeenCalled();+ container.querySelector<HTMLButtonElement>('[data-testid="transfer-confirm"]')!.click();+ await settle();+ expect(api.executeInTransaction.mock.calls[0][2][0]).toMatch(/^DELETE FROM/);+ });++ it.each(["target", "source", "close"])("invalidates confirmation when %s changes", async (change) => {+ const { container, setProps, model, loadResult } = await mountDialog(config("target", "mysql"));+ startButton(container).click();+ await settle();+ const confirm = container.querySelector<HTMLButtonElement>('[data-testid="transfer-confirm"]')!;+ if (change === "target") setInput(textInput(container, 2), "different_table");+ else if (change === "source") setProps({ result: { ...result, rows: [[3, "Other"]] } });+ else model.value = false;+ await settle();+ expect(container.querySelector('[data-testid="transfer-confirm"]')).toBeNull();+ confirm.click();+ await settle();+ expect(loadResult).not.toHaveBeenCalled();+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ });++ it("moves the dialog using the title and resets its position when reopened", async () => {+ const { container, model } = await mountDialog({ id: "target", name: "MySQL", db_type: "mysql", database: "app" } as ConnectionConfig);+ expect(container.querySelector('[modal="false"]')).not.toBeNull();+ const handle = container.querySelector<HTMLElement>(".cursor-move")!;+ const content = handle.parentElement!.parentElement!;+ content.setAttribute("data-slot", "dialog-content");+ vi.spyOn(content, "getBoundingClientRect").mockReturnValue({ left: 100, top: 100, right: 500, bottom: 500 } as DOMRect);+ handle.setPointerCapture = vi.fn();+ handle.hasPointerCapture = vi.fn().mockReturnValue(false);+ handle.dispatchEvent(new PointerEvent("pointerdown", { button: 0, clientX: 150, clientY: 150, pointerId: 1 }));+ handle.dispatchEvent(new PointerEvent("pointermove", { clientX: 180, clientY: 170, pointerId: 1 }));+ await new Promise(requestAnimationFrame);+ expect(content.style.transform).toBe("translate3d(30px, 20px, 0)");+ handle.dispatchEvent(new Event("lostpointercapture"));+ model.value = false;+ await settle();+ model.value = true;+ await settle();+ expect(content.style.transform).toBe("translate3d(0px, 0px, 0)");+ });++ it("coalesces pointer moves and flushes the last position on release without rerendering the form", async () => {+ const { container } = await mountDialog(config("target", "mysql"));+ const handle = container.querySelector<HTMLElement>(".cursor-move")!;+ const content = container.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+ const bounds = vi.spyOn(content, "getBoundingClientRect").mockReturnValue({ left: 100, top: 100, right: 500, bottom: 500 } as DOMRect);+ handle.setPointerCapture = vi.fn();+ handle.hasPointerCapture = vi.fn().mockReturnValue(false);+ const frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation(() => 42);+ const cancelled = vi.spyOn(window, "cancelAnimationFrame");+ const mutations: MutationRecord[] = [];+ const observer = new MutationObserver((records) => mutations.push(...records));+ observer.observe(content, { childList: true, subtree: true });+ try {+ handle.dispatchEvent(new PointerEvent("pointerdown", { button: 0, clientX: 150, clientY: 150, pointerId: 1 }));+ for (let x = 151; x <= 180; x++) {+ handle.dispatchEvent(new PointerEvent("pointermove", { clientX: x, clientY: 170, pointerId: 1 }));+ }+ await nextTick();+ expect(frame).toHaveBeenCalledTimes(1);+ expect(bounds).toHaveBeenCalledTimes(1);+ expect(content.style.transform).toBe("translate3d(0px, 0px, 0)");+ handle.dispatchEvent(new PointerEvent("pointerup", { clientX: 190, clientY: 180, pointerId: 1 }));+ expect(content.style.transform).toBe("translate3d(40px, 30px, 0)");+ expect(cancelled).toHaveBeenCalledWith(42);+ handle.dispatchEvent(new PointerEvent("pointermove", { clientX: 900, clientY: 900, pointerId: 1 }));+ await nextTick();+ expect(content.style.transform).toBe("translate3d(40px, 30px, 0)");+ expect(mutations).toHaveLength(0);+ } finally {+ observer.disconnect();+ frame.mockRestore();+ cancelled.mockRestore();+ }+ });++ it.each([false, true])("keeps the header visible after resize (active drag=%s)", async (activeDrag) => {+ const { container } = await mountDialog(config("target", "mysql"));+ const handle = container.querySelector<HTMLElement>(".cursor-move")!;+ const content = container.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+ const rect = vi.spyOn(content, "getBoundingClientRect").mockReturnValue({ left: 100, top: 100, right: 500, bottom: 500 } as DOMRect);+ handle.setPointerCapture = vi.fn();+ handle.hasPointerCapture = vi.fn().mockReturnValue(true);+ handle.releasePointerCapture = vi.fn();+ handle.dispatchEvent(new PointerEvent("pointerdown", { button: 0, clientX: 150, clientY: 150, pointerId: 1 }));+ handle.dispatchEvent(new PointerEvent("pointermove", { clientX: 180, clientY: 170, pointerId: 1 }));+ await nextTick();+ if (!activeDrag) handle.dispatchEvent(new Event("lostpointercapture"));+ // The centered layout moved the previously dragged header outside the viewport.+ rect.mockReturnValue({ left: -100, top: -150, right: 500, bottom: 400 } as DOMRect);+ window.dispatchEvent(new Event("resize"));+ await nextTick();+ await nextTick();+ expect(content.style.transform).toBe("translate3d(138px, 178px, 0)");+ handle.dispatchEvent(new PointerEvent("pointermove", { clientX: 900, clientY: 900, pointerId: 1 }));+ await nextTick();+ expect(content.style.transform).toBe("translate3d(138px, 178px, 0)");+ expect(handle.releasePointerCapture).toHaveBeenCalledWith(1);+ });++ it("repositions when the dialog content itself changes size", async () => {+ const originalObserver = globalThis.ResizeObserver;+ const observers: Array<{ callback: ResizeObserverCallback; target?: Element }> = [];+ vi.stubGlobal(+ "ResizeObserver",+ class {+ target?: Element;+ constructor(public callback: ResizeObserverCallback) {+ observers.push(this);+ }+ observe(target: Element) {+ this.target = target;+ }+ unobserve() {}+ disconnect() {}+ },+ );+ try {+ const { container } = await mountDialog(config("target", "mysql"));+ const content = container.querySelector<HTMLElement>('[data-slot="dialog-content"]')!;+ vi.spyOn(content, "getBoundingClientRect").mockReturnValue({ left: 100, top: -50, right: 500, bottom: 500 } as DOMRect);+ const observer = observers.find((item) => item.target === content)!;+ expect(observer).toBeDefined();+ observer.callback([], observer as unknown as ResizeObserver);+ await nextTick();+ await nextTick();+ expect(content.style.transform).toBe("translate3d(0px, 58px, 0)");+ } finally {+ vi.stubGlobal("ResizeObserver", originalObserver);+ }+ });++ it("preserves the original native transaction error without an out-of-transaction drop", async () => {+ api.executeInTransaction.mockRejectedValueOnce(new Error("insert failed"));+ const { container } = await mountDialog(config("target", "postgres"));+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ expect(api.executeInTransaction).toHaveBeenCalledTimes(1);+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith("insert failed", 6000);+ });++ it("stops before loading the result when the write guard denies the transfer", async () => {+ storeMocks.ensureReadOnlyWriteAccess.mockResolvedValueOnce(false);+ const { container, loadResult } = await mountDialog(config("target", "postgres"));+ await startTransfer(container);++ expect(storeMocks.ensureReadOnlyWriteAccess).toHaveBeenCalledTimes(1);+ expect(loadResult).not.toHaveBeenCalled();+ expect(api.listTables).not.toHaveBeenCalled();+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it.each(["mysql", "postgres", "sqlite", "sqlserver", "oracle", "oceanbase-oracle", "dameng", "yashandb", "h2", "db2"] as DatabaseType[])("rejects create for an existing %s target before any mutation", async (dbType) => {+ api.listTables.mockResolvedValueOnce([{ name: "items" }]);+ const { container } = await mountDialog(config("target", dbType));+ const create = input(container, "checkbox");+ expect(create.checked).toBe(true);+ expect(create.disabled).toBe(false);+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ expect(api.listTables).toHaveBeenCalled();+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith(expect.stringContaining("grid.exportDatabaseTargetExists"), 6000);+ });++ it.each(["mysql", "oracle", "h2"] as DatabaseType[])("cleans up a newly created %s table after a failed write", async (dbType) => {+ api.executeInTransaction.mockRejectedValueOnce(new Error("insert failed"));+ const { container } = await mountDialog(config("target", dbType));+ await startTransfer(container);++ expect(api.executeQuery).toHaveBeenCalledTimes(2);+ expect(api.executeQuery.mock.calls[0][2]).toMatch(/^CREATE TABLE /);+ expect(api.executeQuery.mock.calls[1][2]).toContain("DROP TABLE");+ expect(api.executeQuery.mock.invocationCallOrder[0]).toBeLessThan(api.executeInTransaction.mock.invocationCallOrder[0]);+ expect(api.executeInTransaction.mock.invocationCallOrder[0]).toBeLessThan(api.executeQuery.mock.invocationCallOrder[1]);+ expect(storeMocks.toast).toHaveBeenCalledWith("insert failed", 6000);+ });++ it.each(["mysql", "oracle", "h2"] as DatabaseType[])("never deletes a %s target when CREATE itself fails", async (dbType) => {+ api.executeQuery.mockRejectedValueOnce(new Error("table already exists"));+ const { container } = await mountDialog(config("target", dbType));+ await startTransfer(container);++ expect(api.executeQuery).toHaveBeenCalledTimes(1);+ expect(api.executeQuery.mock.calls[0][2]).toMatch(/^CREATE TABLE /);+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith("table already exists", 6000);+ });++ it("uses GoldenDB identifier quoting without a cached driver quote across create, insert and cleanup", async () => {+ api.executeInTransaction.mockRejectedValueOnce(new Error("insert failed"));+ const { container } = await mountDialog(config("target", "goldendb"));+ expect(storeMocks.connectionStore!.connectionIdentifierQuote("target")).toBeUndefined();+ await startTransfer(container);++ expect(api.executeQuery).toHaveBeenCalledTimes(2);+ const create = api.executeQuery.mock.calls[0][2] as string;+ const insert = api.executeInTransaction.mock.calls[0][2][0] as string;+ const cleanup = api.executeQuery.mock.calls[1][2] as string;+ expect(create).toMatch(/^CREATE TABLE .*`items` \(`id` /);+ expect(insert).toMatch(/^INSERT INTO .*`items` \(`id`, `name`\) VALUES /);+ expect(cleanup).toMatch(/^DROP TABLE IF EXISTS .*`items`$/);+ expect(storeMocks.toast).toHaveBeenCalledWith("insert failed", 6000);+ });++ it.each(["create", "append", "overwrite"] as const)("writes only the selected SQLite attached database in %s mode", async (mode) => {+ const db = new DatabaseSync(":memory:");+ try {+ db.exec(`ATTACH ':memory:' AS aux;+ CREATE TABLE main.items (id INTEGER, name TEXT);+ INSERT INTO main.items VALUES (8, 'main sentinel');+ CREATE TABLE main.source (id INTEGER, name TEXT);+ CREATE UNIQUE INDEX main.source_name ON source (lower(name)) WHERE name IS NOT NULL;`);+ if (mode !== "create") db.exec("CREATE TABLE aux.items (id INTEGER, name TEXT); INSERT INTO aux.items VALUES (9, 'aux sentinel');");+ api.listTables.mockImplementation(async (_connectionId, _database, schema) => db.prepare(`SELECT name FROM "${schema}".sqlite_master WHERE type = 'table'`).all());+ api.getTableDisplayDdl.mockResolvedValueOnce('CREATE TABLE "items" ("id" INTEGER, "name" TEXT)');+ api.getColumns.mockResolvedValueOnce([+ { name: "id", data_type: "INTEGER" },+ { name: "name", data_type: "TEXT" },+ ]);+ api.executeInTransaction.mockImplementationOnce(async (_connectionId, _database, statements: string[]) => {+ db.exec("BEGIN");+ try {+ for (const statement of statements) db.exec(statement);+ db.exec("COMMIT");+ } catch (error) {+ db.exec("ROLLBACK");+ throw error;+ }+ });+ const sourceDdl = db+ .prepare("SELECT sql FROM main.sqlite_master WHERE tbl_name = 'source' AND sql IS NOT NULL ORDER BY type DESC")+ .all()+ .map((row) => row.sql)+ .join(";\n");+ const { container } = await mountDialog({ ...config("target", "sqlite"), host: ":memory:", database: "aux" }, { sourceDatabaseType: "sqlite", sourceTable: "source", sourceSql: "SELECT * FROM source", loadSourceDdl: vi.fn().mockResolvedValue(sourceDdl) });+ if (mode !== "create") input(container, "checkbox").click();+ if (mode === "overwrite") input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ expect(storeMocks.toast).toHaveBeenCalledWith("grid.exportDatabaseDone");+ expect(db.prepare("SELECT * FROM main.items").all()).toEqual([{ id: 8, name: "main sentinel" }]);+ expect(db.prepare("SELECT * FROM aux.items ORDER BY id").all()).toEqual([{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }, ...(mode === "append" ? [{ id: 9, name: "aux sentinel" }] : [])]);+ if (mode === "create") {+ expect(api.listTables).toHaveBeenCalledWith("target", "aux", "aux");+ expect(db.prepare("SELECT sql FROM aux.sqlite_master WHERE type = 'index' AND tbl_name = 'items'").all()).toHaveLength(1);+ expect(() => db.exec("INSERT INTO aux.items VALUES (3, 'ALICE')")).toThrow(/UNIQUE/);+ expect(db.prepare("SELECT name FROM main.sqlite_master WHERE type = 'index' AND tbl_name = 'items'").all()).toEqual([]);+ } else {+ expect(api.getTableDisplayDdl).toHaveBeenCalledWith("target", "aux", "aux", "items");+ }+ } finally {+ db.close();+ }+ });++ it.each(["/tmp/target.sqlite", "target.sqlite"])("normalizes a SQLite file target %s to main", async (host) => {+ const { container } = await mountDialog({ ...config("target", "sqlite"), host, database: host });+ await startTransfer(container);+ expect(api.listTables).toHaveBeenCalledWith("target", host, "main");+ expect(api.executeInTransaction.mock.calls[0][2][0]).toMatch(/^CREATE TABLE "main"\."items" /);+ });++ it("sends generic JDBC Oracle cleanup as one complete PL/SQL statement", async () => {+ api.executeInTransaction.mockRejectedValueOnce(new Error("insert failed"));+ const target = { ...config("target", "jdbc"), connection_string: "jdbc:oracle:thin:@localhost:1521/XEPDB1" };+ const { container } = await mountDialog(target);+ await startTransfer(container);++ expect(api.executeMulti).not.toHaveBeenCalled();+ expect(api.executeQuery).toHaveBeenCalledTimes(2);+ expect(api.executeQuery.mock.calls[1]).toEqual(["target", "target", `BEGIN EXECUTE IMMEDIATE 'DROP TABLE "app"."items" CASCADE CONSTRAINTS'; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN RAISE; END IF; END;`, "app", undefined, { executionMode: "simple" }]);+ expect(storeMocks.toast).toHaveBeenCalledWith("insert failed", 6000);+ });++ it("surfaces a single-statement cleanup failure together with the original write failure", async () => {+ api.executeInTransaction.mockRejectedValueOnce(new Error("insert failed"));+ api.executeQuery.mockResolvedValueOnce({ columns: [], rows: [] }).mockRejectedValueOnce(new Error("cleanup denied"));+ const { container } = await mountDialog({ ...config("target", "jdbc"), connection_string: "jdbc:oracle:thin:@localhost:1521/XEPDB1" });+ await startTransfer(container);++ expect(storeMocks.toast).toHaveBeenCalledWith(expect.stringContaining('"message":"insert failed","error":"cleanup denied"'), 8000);+ expect(storeMocks.toast).not.toHaveBeenCalledWith("grid.exportDatabaseDone");+ });++ it("does not claim ownership when a single-statement CREATE returns an execution error", async () => {+ api.executeQuery.mockResolvedValueOnce({ columns: [], rows: [], execution_error: true });+ const { container } = await mountDialog(config("target", "mysql"));+ await startTransfer(container);++ expect(api.executeQuery).toHaveBeenCalledTimes(1);+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith("grid.exportDatabaseExecutionFailed", 6000);+ });++ it("allows overwrite/create for an empty H2 target after the preflight", async () => {+ api.listTables.mockResolvedValueOnce([]);+ const { container } = await mountDialog(config("target", "h2"));+ const create = input(container, "checkbox");+ expect(create.checked).toBe(true);+ expect(create.disabled).toBe(false);+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(api.listTables).toHaveBeenCalled();+ expect(api.executeQuery.mock.calls[0][2]).toMatch(/^CREATE TABLE /);+ expect(statements.some((statement) => /^CREATE TABLE /i.test(statement))).toBe(false);+ expect(statements.some((statement) => /^INSERT INTO /i.test(statement))).toBe(true);+ });++ it("writes only to an existing Oracle table when creation is unchecked", async () => {+ const { container } = await mountDialog(config("target", "oracle"));+ input(container, "checkbox").click();+ await settle();+ await startTransfer(container);++ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(api.listTables).not.toHaveBeenCalled();+ expect(api.getTableDisplayDdl).toHaveBeenCalledWith("target", "target", "app", "items");+ expect(statements.some((statement) => /^CREATE TABLE |^DROP TABLE /i.test(statement))).toBe(false);+ expect(statements[0]).toMatch(/^INSERT ALL\n/);+ expect(statements[0]).toContain("SELECT 1 FROM dual");+ });++ it("uses delete plus insert for an existing H2 table when creation is unchecked", async () => {+ const { container } = await mountDialog(config("target", "h2"));+ input(container, "checkbox").click();+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(api.listTables).not.toHaveBeenCalled();+ expect(statements[0]).toMatch(/^DELETE FROM /i);+ expect(statements.some((statement) => /^CREATE TABLE |^DROP TABLE /i.test(statement))).toBe(false);+ expect(statements.some((statement) => /^INSERT INTO /i.test(statement))).toBe(true);+ });++ it("keeps an existing MySQL target untouched when creation was requested", async () => {+ api.listTables.mockResolvedValueOnce([{ name: "items" }]);+ const { container } = await mountDialog(config("target", "mysql"));+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);++ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("reuses the source MySQL DDL when the result is a direct table projection", async () => {+ api.executeQuery.mockResolvedValueOnce({ columns: ["Collation"], rows: [["utf8mb4_0900_ai_ci"]] });+ const sourceDdl = "CREATE TABLE `apis` (`id` bigint unsigned NOT NULL AUTO_INCREMENT, `method` varchar(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_apis_method` (`method`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;";+ const loadSourceDdl = vi.fn().mockResolvedValue(sourceDdl);+ const sourceResult = {+ ...result,+ columns: ["id", "method"],+ rows: [+ [1, "GET"],+ [2, "POST"],+ ],+ };+ const { container } = await mountDialog(config("target", "mysql"), { sourceTable: "apis", sourceSql: "SELECT * FROM apis", result: sourceResult, loadResult: vi.fn().mockResolvedValue(sourceResult), loadSourceDdl });+ await startTransfer(container);++ const createStatement = api.executeQuery.mock.calls.find((call) => /^CREATE TABLE /i.test(call[2]))![2];+ expect(loadSourceDdl).toHaveBeenCalledTimes(1);+ expect(createStatement).toContain("bigint unsigned NOT NULL AUTO_INCREMENT");+ expect(createStatement).toContain("varchar(20) DEFAULT NULL");+ expect(createStatement).toContain("KEY `idx_apis_method` (`method`)");+ expect(createStatement).toContain("COLLATE=utf8mb4_0900_ai_ci");+ });++ it.each(["utf8mb4_unicode_520_ci", "utf8mb4_unicode_ci"])("adapts MySQL 8 DDL to target collation %s before creating the table", async (collation) => {+ api.executeQuery.mockResolvedValueOnce({ columns: ["Collation", "Charset"], rows: [[collation, "utf8mb4"]] });+ const ddl = "CREATE TABLE items (id INT, name VARCHAR(32) COLLATE utf8mb4_0900_ai_ci) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci";+ const { container } = await mountDialog(config("target", "mysql"), { sourceTable: "items", sourceSql: "SELECT * FROM items", loadSourceDdl: vi.fn().mockResolvedValue(ddl) });+ await startTransfer(container);+ expect(api.executeQuery.mock.calls[0].slice(0, 3)).toEqual(["target", "target", "SHOW COLLATION"]);+ const create = api.executeQuery.mock.calls[1][2] as string;+ expect(create).toContain(`COLLATE ${collation}`);+ expect(create).toContain(`COLLATE=${collation}`);+ expect(create).not.toContain("0900");+ expect(api.executeInTransaction).toHaveBeenCalledTimes(1);+ expect(storeMocks.toast.mock.calls.some(([message]) => message.includes("exportDatabaseCollationAdapted"))).toBe(true);+ });++ it("stops before CREATE when the target has no known compatible collation", async () => {+ api.executeQuery.mockResolvedValueOnce({ columns: ["Collation"], rows: [["latin1_swedish_ci"]] });+ const { container } = await mountDialog(config("target", "mysql"), { sourceTable: "items", sourceSql: "SELECT * FROM items", loadSourceDdl: vi.fn().mockResolvedValue("CREATE TABLE items (id INT, name TEXT) ENGINE=InnoDB COLLATE=utf8mb4_0900_ai_ci") });+ await startTransfer(container);+ expect(api.executeQuery).toHaveBeenCalledTimes(1);+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith(expect.stringContaining("exportDatabaseUnsupportedCollation"), 6000);+ });++ it("exports ordinary column projections without requesting an unavailable source DDL", async () => {+ const loadSourceDdl = vi.fn().mockResolvedValue(undefined);+ const { container } = await mountDialog(config("target", "mysql"), { sourceTable: "items", sourceSql: "SELECT id, name FROM items", loadSourceDdl });+ await startTransfer(container);++ expect(loadSourceDdl).not.toHaveBeenCalled();+ expect(api.executeQuery.mock.calls[0][2]).toMatch(/^CREATE TABLE /);+ expect(api.executeInTransaction).toHaveBeenCalledTimes(1);+ });++ it("inspects the existing target DDL instead of the source when create is unchecked", async () => {+ const loadSourceDdl = vi.fn().mockResolvedValue(undefined);+ const { container } = await mountDialog(config("target", "mysql"), { sourceTable: "items", sourceSql: "SELECT * FROM items", loadSourceDdl });+ input(container, "checkbox").click();+ await settle();+ await startTransfer(container);++ expect(loadSourceDdl).not.toHaveBeenCalled();+ expect(api.getTableDisplayDdl).toHaveBeenCalled();+ expect(api.executeInTransaction).toHaveBeenCalledTimes(1);+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("resolves existing MySQL column casing before excluding generated columns", async () => {+ api.getTableDisplayDdl.mockResolvedValueOnce("CREATE TABLE items (id INTEGER, name VARCHAR(32), total INTEGER AS (id * 2) STORED) ENGINE=InnoDB");+ api.getColumns.mockResolvedValueOnce([+ { name: "id", data_type: "INTEGER" },+ { name: "name", data_type: "VARCHAR(32)" },+ { name: "total", data_type: "INTEGER" },+ ]);+ const sourceResult = { ...result, columns: ["ID", "NAME", "TOTAL"], rows: [[1, "Alice", 2]], column_types: ["INTEGER", "VARCHAR", "INTEGER"] };+ const { container } = await mountDialog(config("target", "mysql"), { loadResult: vi.fn().mockResolvedValue(sourceResult) });+ input(container, "checkbox").click();+ await settle();+ await startTransfer(container);+ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(statements[0]).toContain("(`id`, `name`)");+ expect(statements[0]).not.toContain("total");+ });++ it.each(["TIMESTAMP(3)", "TIMESTAMP", "TIME"])("rejects fractional loss using an existing H2 %s declaration before overwriting", async (declaration) => {+ api.getTableDisplayDdl.mockResolvedValueOnce(`CREATE TABLE "items" ("created" ${declaration})`);+ // H2 getColumns only exposes DATA_TYPE, omitting DATETIME_PRECISION.+ api.getColumns.mockResolvedValueOnce([{ name: "created", data_type: declaration.startsWith("TIME(") || declaration === "TIME" ? "TIME" : "TIMESTAMP" }]);+ const sourceResult = { ...result, columns: ["created"], column_types: ["TIMESTAMP"], rows: [[declaration === "TIME" ? "12:34:56.123456789" : "2026-10-07 12:34:56.123456789"]] };+ const { container } = await mountDialog(config("target", "h2"), { loadResult: vi.fn().mockResolvedValue(sourceResult), sourceDatabaseType: "h2" });+ input(container, "checkbox").click();+ input(container, "radio", 1).click();+ await settle();+ await startTransfer(container);+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith(expect.stringContaining("grid.exportDatabaseValueUnsupported"), 6000);+ });++ it("allows insignificant zeroes past an existing target's declared temporal precision", async () => {+ api.getTableDisplayDdl.mockResolvedValueOnce('CREATE TABLE "items" ("created" TIMESTAMP(3))');+ api.getColumns.mockResolvedValueOnce([{ name: "created", data_type: "TIMESTAMP" }]);+ const sourceResult = { ...result, columns: ["created"], column_types: ["TIMESTAMP"], rows: [["2026-10-07 12:34:56.123000000"]] };+ const { container } = await mountDialog(config("target", "h2"), { loadResult: vi.fn().mockResolvedValue(sourceResult), sourceDatabaseType: "h2" });+ input(container, "checkbox").click();+ await settle();+ await startTransfer(container);+ expect(api.executeInTransaction.mock.calls[0][2][0]).toContain("2026-10-07 12:34:56.123000000");+ });++ it("retains the declared precision when reusing a same-engine source DDL", async () => {+ const sourceResult = { ...result, columns: ["created"], column_types: ["TIMESTAMP"], rows: [["2026-10-07 12:34:56.123456789"]] };+ const loadSourceDdl = vi.fn().mockResolvedValue('CREATE TABLE "items" ("created" TIMESTAMP(9))');+ const { container } = await mountDialog(config("target", "h2"), { result: sourceResult, loadResult: vi.fn().mockResolvedValue(sourceResult), sourceDatabaseType: "h2", sourceSql: 'SELECT * FROM "items"', sourceTable: "items", loadSourceDdl });+ await startTransfer(container);+ expect(api.executeQuery.mock.calls[0][2]).toContain("TIMESTAMP(9)");+ expect(api.executeInTransaction.mock.calls[0][2][0]).toContain("2026-10-07 12:34:56.123456789");+ });++ it("rejects an unknown bare temporal declaration instead of assuming wire precision", async () => {+ api.getTableDisplayDdl.mockResolvedValueOnce('CREATE TABLE "items" ("created" TIMESTAMP)');+ api.getColumns.mockResolvedValueOnce([{ name: "created", data_type: "TIMESTAMP" }]);+ const sourceResult = { ...result, columns: ["created"], column_types: ["TIMESTAMP"], rows: [["2026-10-07 12:34:56.123456789"]] };+ const { container } = await mountDialog(config("target", "iris"), { loadResult: vi.fn().mockResolvedValue(sourceResult) });+ input(container, "checkbox").click();+ await settle();+ await startTransfer(container);+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith(expect.stringContaining("grid.exportDatabaseValueUnsupported"), 6000);+ });++ it.each(["sqlserver", "jdbc"] as const)("keeps SQL Server identity batches intact for a %s target", async (dbType) => {+ api.getTableDisplayDdl.mockResolvedValueOnce("CREATE TABLE [items] ([Id] int IDENTITY(1,1), [name] nvarchar(32))");+ api.getColumns.mockResolvedValueOnce([+ { name: "Id", data_type: "int" },+ { name: "name", data_type: "nvarchar(32)" },+ ]);+ const { container } = await mountDialog({ ...config("target", dbType), connection_string: "jdbc:sqlserver://localhost:1433;databaseName=target" });+ input(container, "checkbox").click();+ await settle();+ await startTransfer(container);+ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(statements).toHaveLength(1);+ expect(statements[0]).toMatch(/^BEGIN TRY[\s\S]+END CATCH$/);+ expect(statements[0]).toContain("SET IDENTITY_INSERT [app].[items] ON");+ expect(statements[0]).toContain("([Id], [name])");+ expect(api.executeMulti).not.toHaveBeenCalled();+ });++ it("uses individual inserts for the SQL Server 2000 profile", async () => {+ const { container } = await mountDialog({ ...config("target", "sqlserver"), driver_profile: "sqlserver-legacy" });+ await startTransfer(container);+ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ expect(statements.filter((sql) => sql.startsWith("INSERT INTO"))).toHaveLength(2);+ expect(statements.join("\n")).not.toContain("),\n(");+ });++ it("requires an explicit namespace for schema-aware targets instead of guessing from the database", async () => {+ const { container } = await mountDialog({ ...config("target", "postgres"), default_schema: undefined });+ expect(startButton(container).disabled).toBe(true);+ setInput(textInput(container, 1), "sales");+ await settle();+ await startTransfer(container);+ expect(api.listTables.mock.calls[0][2]).toBe("sales");+ expect(api.executeInTransaction.mock.calls[0][2][0]).toMatch(/^CREATE TABLE "sales"\."items"/);+ });++ it.each(["postgres", "jdbc"] as const)("preserves PostgreSQL identity DO blocks and exact column names for a %s target", async (dbType) => {+ const sourceResult = { ...result, columns: ["Id", "id", " name ", "computed"], rows: [[7, 9, "value", 14]], column_types: ["BIGINT", "INTEGER", "TEXT", "INTEGER"] };+ const loadSourceDdl = vi.fn().mockResolvedValue('CREATE TABLE "items" ("Id" bigint GENERATED ALWAYS AS IDENTITY, "id" integer, " name " text, "computed" integer GENERATED ALWAYS AS ("Id" * 2) STORED)');+ const { container } = await mountDialog(+ { ...config("target", dbType), connection_string: "jdbc:postgresql://localhost:5432/target" },+ { sourceDatabaseType: "postgres", sourceTable: "items", sourceSql: 'SELECT * FROM "items"', result: sourceResult, loadResult: vi.fn().mockResolvedValue(sourceResult), loadSourceDdl },+ );+ await startTransfer(container);+ const statements = api.executeInTransaction.mock.calls[0][2] as string[];+ const insert = statements.find((sql) => sql.startsWith("INSERT INTO"));+ expect(insert).toContain('("Id", "id", " name ") OVERRIDING SYSTEM VALUE');+ expect(insert).not.toContain("computed");+ expect(statements[statements.length - 1]).toContain("pg_get_serial_sequence");+ expect(statements[statements.length - 1]).toMatch(/^DO \$dbx_transfer\$[\s\S]+END;\n\$dbx_transfer\$$/);+ expect(api.executeMulti).not.toHaveBeenCalled();+ });++ it.each(["cancel", "close", "source change"])("stops a pending result load after %s without writing", async (action) => {+ const pending = deferred<QueryResult>();+ const { container, model, setProps } = await mountDialog(config("target", "postgres"), { loadResult: () => pending.promise });+ await startTransfer(container);+ await settle();+ if (action === "cancel") [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("transfer.cancel"))!.click();+ else if (action === "close") model.value = false;+ else setProps({ sourceSql: "SELECT * FROM different_table" });+ await settle();+ pending.resolve(result);+ await settle();++ expect(api.executeInTransaction).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(storeMocks.toast).toHaveBeenCalledWith("grid.exportDatabaseCancelled", 6000);+ });++ it("matches a marked production database case-insensitively and stops on denied confirmation", async () => {+ const target = { ...config("target", "mysql"), production_databases: ["TARGET"] };+ storeMocks.productionSafetyStore.requestConfirmation.mockResolvedValueOnce(false);+ const { container, loadResult } = await mountDialog(target);+ await startTransfer(container);++ expect(storeMocks.productionSafetyStore.requestConfirmation).toHaveBeenCalledWith(expect.objectContaining({ database: "target" }));+ expect(loadResult).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeInTransaction).not.toHaveBeenCalled();+ });++ it("ignores a MySQL schema field so it cannot redirect writes into another database", async () => {+ const { container } = await mountDialog(config("target", "mysql"));+ expect(textInput(container, 1).disabled).toBe(true);+ setInput(textInput(container, 1), "production");+ await settle();+ await startTransfer(container);++ expect(api.executeQuery.mock.calls[0][1]).toBe("target");+ expect(api.executeQuery.mock.calls[0][2]).toMatch(/^CREATE TABLE `items` /);+ expect(api.executeQuery.mock.calls[0][3]).toBeUndefined();+ expect(api.executeInTransaction.mock.calls[0][3]).toBeUndefined();+ });+});diff --git a/apps/desktop/src/components/transfer/__tests__/queryResultTransfer.spec.ts b/apps/desktop/src/components/transfer/__tests__/queryResultTransfer.spec.tsnew file mode 100644index 0000000000..26c905c6da--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/queryResultTransfer.spec.ts@@ -0,0 +1,317 @@+import { describe, expect, it } from "vitest";+import { temporalColumnTypesFromDdl } from "../queryResultTransferDdl";+import {+ binaryQueryResultValueHex,+ alwaysIdentityColumnNamesFromDdl,+ identityColumnNamesFromDdl,+ nonInsertableColumnNamesFromDdl,+ normalizeQueryResultColumnType,+ queryResultTransferCreateCleanupSql,+ queryResultTransferDatabaseType,+ queryResultTransferIncomplete,+ queryResultTransferNeedsCreateCleanup,+ queryResultTransferStagingCleanupSql,+ rewriteCreateTableName,+ supportsQueryResultTransfer,+ supportsQueryResultTransferDatabaseType,+ transactionalMysqlTableDdl,+} from "../queryResultTransfer";++describe("query result transfer", () => {+ it("reads temporal precision and zones from column declarations without reading defaults as types", () => {+ const ddl = `CREATE TABLE "events" (+ "created" TIMESTAMP ( 3 ) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP(6),+ "local" TIMESTAMP(9) WITH LOCAL TIME ZONE,+ "clock" TIME(2) WITHOUT TIME ZONE,+ "text" VARCHAR(99) DEFAULT 'TIMESTAMP(1)',+ "custom" app.timestamp,+ "items" TIMESTAMP(3)[],+ CONSTRAINT "events_check" CHECK ("created" > TIMESTAMP '2020-01-01 00:00:00')+ )`;+ expect([...temporalColumnTypesFromDdl(ddl, "postgres")]).toEqual([+ ["created", "TIMESTAMP(3) WITH TIME ZONE"],+ ["local", "TIMESTAMP(9) WITH LOCAL TIME ZONE"],+ ["clock", "TIME(2) WITHOUT TIME ZONE"],+ ]);+ });++ it.each([+ ["h2", "TIME", "TIME(0)"],+ ["h2", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP(6) WITH TIME ZONE"],+ ["postgres", "TIMESTAMPTZ", "TIMESTAMPTZ(6)"],+ ["mysql", "DATETIME", "DATETIME(0)"],+ ["goldendb", "TIME", "TIME(0)"],+ ["sqlserver", "[datetime2]", "DATETIME2(7)"],+ ["sqlserver", "DATETIMEOFFSET", "DATETIMEOFFSET(7)"],+ ["sqlserver", "DATETIME", "DATETIME"],+ ["oracle", "TIMESTAMP WITH LOCAL TIME ZONE", "TIMESTAMP(6) WITH LOCAL TIME ZONE"],+ ["oracle", "DATE", "DATE"],+ ["db2", "TIMESTAMP", "TIMESTAMP(6)"],+ ] as const)("uses the actual %s default for a bare %s declaration", (databaseType, declaration, expected) => {+ expect(temporalColumnTypesFromDdl(`CREATE TABLE events (created ${declaration})`, databaseType).get("created")).toBe(expected);+ });++ it("marks unknown temporal defaults explicitly and leaves SQLite affinity and SQL Server rowversion alone", () => {+ expect(temporalColumnTypesFromDdl("CREATE TABLE events (created TIMESTAMP)", "iris").get("created")).toBeNull();+ expect(temporalColumnTypesFromDdl("CREATE TABLE events (created TIMESTAMP(3))", "iris").get("created")).toBe("TIMESTAMP(3)");+ expect(temporalColumnTypesFromDdl("CREATE TABLE events (created TIMESTAMP(3))", "sqlite").size).toBe(0);+ expect(temporalColumnTypesFromDdl("CREATE TABLE events (version TIMESTAMP)", "sqlserver").size).toBe(0);+ });++ it.each(["UNIQUE NULLS DISTINCT", "UNIQUE NULLS NOT DISTINCT", "UNIQUE NULLS ALL DISTINCT", "HASH", "SPATIAL"])("rewrites the H2 SCRIPT index modifier %s without changing its semantics", (modifiers) => {+ const ddl = `CREATE MEMORY TABLE "PUBLIC"."APIS" ("NAME" VARCHAR(32)); CREATE ${modifiers} INDEX "PUBLIC"."IDX_NAME" ON "PUBLIC"."APIS"("NAME" NULLS FIRST);`;+ const rewritten = rewriteCreateTableName(ddl, '"TARGET"."COPY"', "h2");+ expect(rewritten).toContain(`CREATE ${modifiers} INDEX "COPY_IDX_NAME_dbx_`);+ expect(rewritten).toContain('ON "TARGET"."COPY"("NAME" NULLS FIRST)');+ expect(rewritten).not.toContain('"PUBLIC"');+ });++ it("preserves H2 SCRIPT table and column comments before parsing the columns", () => {+ const ddl = `CREATE MEMORY TABLE "PUBLIC"."APIS" COMMENT 'table (APIS) desc' (+ "CREATED" TIMESTAMP(3) COMMENT 'column desc', "TOTAL" INTEGER GENERATED ALWAYS AS (1)+ );`;+ expect(rewriteCreateTableName(ddl, '"TARGET"."COPY"', "h2")).toBe(ddl.replace('"PUBLIC"."APIS"', '"TARGET"."COPY"'));+ expect(temporalColumnTypesFromDdl(ddl, "h2").get("CREATED")).toBe("TIMESTAMP(3)");+ expect(nonInsertableColumnNamesFromDdl(ddl, "h2")).toEqual(new Set(["TOTAL"]));+ expect(rewriteCreateTableName('CREATE TABLE "APIS" COMMENT unknown (id INT)', '"COPY"', "h2")).toBeUndefined();+ });++ it("excludes document and non-transfer targets while retaining SQL targets", () => {+ for (const type of ["mongodb", "redis", "dynamodb", "neo4j"] as const) expect(supportsQueryResultTransfer({ db_type: type })).toBe(false);+ expect(queryResultTransferDatabaseType({ db_type: "gbase" })).toBeUndefined();+ expect(supportsQueryResultTransfer({ db_type: "gbase" })).toBe(false);+ for (const type of ["mysql", "postgres", "h2"] as const) expect(supportsQueryResultTransfer({ db_type: type })).toBe(true);+ for (const type of ["clickhouse", "duckdb", "rqlite", "turso", "cloudflare-d1", "argo", "hive", "spark"] as const) expect(supportsQueryResultTransferDatabaseType(type)).toBe(false);+ for (const driver_profile of ["doris", "selectdb", "starrocks"]) expect(supportsQueryResultTransfer({ db_type: "mysql", driver_profile })).toBe(false);+ });++ it("resolves supported JDBC targets before checking transfer capability", () => {+ const connection = { db_type: "jdbc" as const, connection_string: "jdbc:h2:mem:transfer-test" };+ expect(queryResultTransferDatabaseType(connection)).toBe("h2");+ expect(supportsQueryResultTransfer(connection)).toBe(true);+ });++ it("makes bare MySQL variable-length types valid for CREATE TABLE", () => {+ expect(normalizeQueryResultColumnType("varchar", "mysql")).toBe("VARCHAR(255)");+ expect(normalizeQueryResultColumnType("varbinary", "mysql")).toBe("VARBINARY(255)");+ expect(normalizeQueryResultColumnType("enum", "mysql")).toBe("TEXT");+ expect(normalizeQueryResultColumnType("varchar(20)", "mysql")).toBe("varchar(20)");+ });++ it("decodes the backend's canonical binary result values before INSERT", () => {+ expect(binaryQueryResultValueHex("0x4869")).toBe("4869");+ expect(binaryQueryResultValueHex("plain text")).toBe("706c61696e2074657874");+ expect(binaryQueryResultValueHex(new Uint8Array([0, 255]))).toBe("00ff");+ expect(binaryQueryResultValueHex([0, 255])).toBe("00ff");+ expect(binaryQueryResultValueHex({ data: [0, 255] })).toBe("00ff");+ });++ it("builds an idempotent cleanup statement for a staging table", () => {+ expect(queryResultTransferStagingCleanupSql("`db`.`apis__dbx_transfer_abc`")).toBe("DROP TABLE IF EXISTS `db`.`apis__dbx_transfer_abc`");+ });++ it("cleans up newly created Oracle-family tables after non-transactional DDL failures", () => {+ expect(queryResultTransferNeedsCreateCleanup("oracle")).toBe(true);+ expect(queryResultTransferCreateCleanupSql('"APP"."apis"', "oracle")).toContain('DROP TABLE "APP"."apis" CASCADE CONSTRAINTS');+ expect(queryResultTransferNeedsCreateCleanup("postgres")).toBe(false);+ for (const type of ["mysql", "goldendb", "h2"] as const) {+ expect(queryResultTransferNeedsCreateCleanup(type)).toBe(true);+ expect(queryResultTransferCreateCleanupSql('"apis"', type)).toBe('DROP TABLE IF EXISTS "apis"');+ }+ });++ it("rewrites only the CREATE TABLE name while preserving source DDL", () => {+ const ddl = "CREATE TABLE `apis` (`id` bigint unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";+ expect(rewriteCreateTableName(ddl, "`aaa_apis`")).toBe("CREATE TABLE `aaa_apis` (`id` bigint unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");+ });++ it("rewrites table references in every statement of a reusable PostgreSQL DDL", () => {+ const ddl = ['CREATE TABLE "public"."apis" ("id" bigint);', 'COMMENT ON TABLE "public"."apis" IS \'source table\';', 'CREATE INDEX "idx_apis_id" ON "public"."apis" ("id");'].join("\n");+ expect(rewriteCreateTableName(ddl, '"archive"."aaa_apis"', "postgres", "public", "apis")).toContain('COMMENT ON TABLE "archive"."aaa_apis"');+ expect(rewriteCreateTableName(ddl, '"archive"."aaa_apis"', "postgres", "public", "apis")).toMatch(/CREATE INDEX "aaa_apis_idx_apis_id_dbx_[a-f0-9]+" ON "archive"\."aaa_apis"/);+ });++ it("keeps a reusable MySQL table definition instead of rebuilding generic columns", () => {+ const ddl = `CREATE TABLE \`apis\` (+ \`id\` bigint unsigned NOT NULL AUTO_INCREMENT,+ \`created_at\` datetime(3) DEFAULT NULL,+ \`updated_at\` datetime(3) DEFAULT NULL,+ \`deleted_at\` datetime(3) DEFAULT NULL,+ \`method\` varchar(20) DEFAULT NULL COMMENT '''请求方式''',+ \`path\` varchar(100) DEFAULT NULL COMMENT '''访问路径''',+ \`category\` varchar(50) DEFAULT NULL COMMENT '''所属类别''',+ \`remark\` varchar(100) DEFAULT NULL COMMENT '''备注''',+ \`creator\` varchar(20) DEFAULT NULL COMMENT '''创建人''',+ PRIMARY KEY (\`id\`),+ KEY \`idx_apis_deleted_at\` (\`deleted_at\`)+) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;`;+ const rewritten = rewriteCreateTableName(ddl, "`1_apis`", "mysql", undefined, "apis");+ expect(rewritten).toContain("`id` bigint unsigned NOT NULL AUTO_INCREMENT");+ expect(rewritten).toContain("varchar(20) DEFAULT NULL");+ expect(rewritten).toContain("COLLATE=utf8mb4_0900_ai_ci");+ expect(rewritten).toBe(ddl.replace("CREATE TABLE `apis`", "CREATE TABLE `1_apis`"));+ });++ it("detects generated and SQL Server rowversion columns as non-insertable", () => {+ const mysql = "CREATE TABLE t (\n id bigint,\n full_name varchar(255) GENERATED ALWAYS AS (id) STORED\n);";+ expect(nonInsertableColumnNamesFromDdl(mysql, "mysql")).toEqual(new Set(["full_name"]));+ const sqlserver = "CREATE TABLE t (\n id int,\n version rowversion\n);";+ expect(nonInsertableColumnNamesFromDdl(sqlserver, "sqlserver")).toEqual(new Set(["version"]));+ });++ it("detects shorthand and multiline computed columns", () => {+ const mysql = "CREATE TABLE t (\n id bigint,\n total decimal(10,2) AS (\n price * quantity\n ) STORED\n);";+ expect(nonInsertableColumnNamesFromDdl(mysql, "mysql")).toEqual(new Set(["total"]));+ const sqlserver = "CREATE TABLE t (\n id int,\n total AS (price * quantity) PERSISTED\n);";+ expect(nonInsertableColumnNamesFromDdl(sqlserver, "sqlserver")).toEqual(new Set(["total"]));+ });++ it("keeps identities and ordinary defaults writable without treating CAST AS as a generated column", () => {+ const ddl = 'CREATE TABLE "t" ("id" bigint GENERATED ALWAYS AS IDENTITY, "other_id" int GENERATED BY DEFAULT AS IDENTITY, "serial_id" bigserial, "value" int DEFAULT CAST(1 AS integer), "computed" int GENERATED ALWAYS AS (value * 2) STORED)';+ expect(nonInsertableColumnNamesFromDdl(ddl, "postgres")).toEqual(new Set(["computed"]));+ expect(identityColumnNamesFromDdl(ddl, "postgres")).toEqual(new Set(["id", "other_id", "serial_id"]));+ expect(alwaysIdentityColumnNamesFromDdl(ddl, "postgres")).toEqual(new Set(["id"]));+ const sqlserver = "CREATE TABLE [t] ([id] bigint IDENTITY(1,1), [version] rowversion, [total] AS ([id] * 2))";+ expect(nonInsertableColumnNamesFromDdl(sqlserver, "sqlserver")).toEqual(new Set(["version", "total"]));+ expect(identityColumnNamesFromDdl(sqlserver, "sqlserver")).toEqual(new Set(["id"]));+ const caseSensitive = 'CREATE TABLE t ("ID" int GENERATED ALWAYS AS IDENTITY, "id" int, "VALUE" int GENERATED ALWAYS AS (id * 2) STORED, "value" int)';+ expect(identityColumnNamesFromDdl(caseSensitive, "postgres")).toEqual(new Set(["ID"]));+ expect(nonInsertableColumnNamesFromDdl(caseSensitive, "postgres")).toEqual(new Set(["VALUE"]));+ });++ it("changes only table grammar positions, including comments and self references", () => {+ const ddl = [+ 'CREATE TABLE "public"."apis" ("apis" int, "parent" int REFERENCES "public"."apis" ("apis"), "other" int REFERENCES "archive"."apis" ("apis"), CONSTRAINT "apis_check" CHECK (apis > 0));',+ 'CREATE INDEX "idx" ON "public"."apis" ("apis") WHERE apis > 0;',+ 'COMMENT ON COLUMN "public"."apis"."apis" IS \'apis\';',+ ].join("\n");+ const result = rewriteCreateTableName(ddl, '"public"."copied"', "postgres", "public", "apis")!;+ expect(result).toContain('CREATE TABLE "public"."copied" ("apis" int');+ expect(result).toContain('REFERENCES "public"."copied" ("apis")');+ expect(result).toContain('REFERENCES "archive"."apis" ("apis")');+ expect(result).toContain("CHECK (apis > 0)");+ expect(result).toContain('ON "public"."copied" ("apis") WHERE apis > 0');+ expect(result).toContain('COMMENT ON COLUMN "public"."copied"."apis" IS \'apis\'');+ });++ it("renames PostgreSQL constraints, indexes and their comments consistently", () => {+ const ddl = ['CREATE TABLE "public"."apis" ("id" bigint, CONSTRAINT "apis_pkey" PRIMARY KEY ("id"));', 'CREATE UNIQUE INDEX "idx" ON "public"."apis" ("id");', 'COMMENT ON CONSTRAINT "apis_pkey" ON "public"."apis" IS \'primary key\';', 'COMMENT ON INDEX "public"."idx" IS \'index\';'].join("\n");+ const result = rewriteCreateTableName(ddl, '"public"."copy"', "postgres", "public", "apis")!;+ const primaryKey = result.match(/CONSTRAINT ("[^"]+") PRIMARY KEY/)![1];+ const index = result.match(/CREATE UNIQUE INDEX ("[^"]+")/)![1];+ expect(primaryKey).not.toBe('"apis_pkey"');+ expect(index).not.toBe('"idx"');+ expect(result).toContain(`COMMENT ON CONSTRAINT ${primaryKey} ON "public"."copy"`);+ expect(result).toContain(`COMMENT ON INDEX "public".${index}`);+ });++ it("renames MySQL schema-scoped constraints without changing table-scoped index names", () => {+ const ddl = "CREATE TABLE `apis` (`id` int, `parent` int, KEY `idx` (`parent`), CONSTRAINT `apis_fk` FOREIGN KEY (`parent`) REFERENCES `apis` (`id`))";+ for (const type of ["mysql", "goldendb"] as const) {+ const result = rewriteCreateTableName(ddl, "`copy`", type, undefined, "apis")!;+ expect(result).toContain("KEY `idx` (`parent`)");+ expect(result).toMatch(/CONSTRAINT `copy_apis_fk_dbx_[a-f0-9]+` FOREIGN KEY/);+ expect(result).toContain("REFERENCES `copy` (`id`)");+ }+ });++ it("rewrites SQL Server table and column description properties while preserving their text", () => {+ const tableComment = "EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'apis table in dbo', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'apis'";+ const columnComment = "EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'User''s display name', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'apis', @level2type=N'COLUMN', @level2name=N'apis'";+ const ddl = `CREATE TABLE [dbo].[apis] ([apis] nvarchar(100)); ${tableComment}; ${columnComment};`;+ const result = rewriteCreateTableName(ddl, "[archive].[copy]", "sqlserver", "dbo", "apis")!;+ expect(result).toContain("@value=N'apis table in dbo'");+ expect(result).toContain("@value=N'User''s display name'");+ expect(result.match(/@level0name=N'archive'/g)).toHaveLength(2);+ expect(result.match(/@level1name=N'copy'/g)).toHaveLength(2);+ expect(result).toContain("@level2name=N'apis'");+ const defaultSchema = rewriteCreateTableName(ddl, "[copy]", "sqlserver", "dbo", "apis")!;+ expect(defaultSchema).toContain("OBJECT_SCHEMA_NAME(OBJECT_ID(N''[copy]'', N''U''))");+ expect(defaultSchema.match(/@level0name=@dbx_transfer_schema/g)).toHaveLength(2);+ expect(defaultSchema.match(/EXEC\(N'DECLARE @dbx_transfer_schema/g)).toHaveLength(2);+ });++ it("rejects unsupported SQL Server metadata procedures and foreign target properties", () => {+ const prefix = "CREATE TABLE [dbo].[apis] ([id] int); ";+ const property = "EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'text', @level0type=N'SCHEMA', @level0name=N'dbo', @level1type=N'TABLE', @level1name=N'other'";+ expect(rewriteCreateTableName(prefix + property, "[copy]", "sqlserver", "dbo", "apis")).toBeUndefined();+ expect(rewriteCreateTableName(prefix + "EXEC dbo.custom_procedure 'apis'", "[copy]", "sqlserver", "dbo", "apis")).toBeUndefined();+ const temporal = "CREATE TABLE [dbo].[apis] ([id] int) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[apis_history]));";+ expect(rewriteCreateTableName(temporal, "[copy]", "sqlserver", "dbo", "apis")).toBeUndefined();+ });++ it("keeps generated identifiers within byte limits without losing uniqueness", () => {+ const longName = "查询结果".repeat(30);+ const ddl = `CREATE TABLE apis (id int, CONSTRAINT first PRIMARY KEY (id)); CREATE INDEX second ON apis (id)`;+ const result = rewriteCreateTableName(ddl, `"${longName}"`, "postgres", undefined, "apis")!;+ const primaryKey = result.match(/CONSTRAINT "([^"]+)" PRIMARY KEY/)![1];+ const index = result.match(/CREATE INDEX "([^"]+)"/)![1];+ expect(new TextEncoder().encode(primaryKey).length).toBeLessThanOrEqual(63);+ expect(new TextEncoder().encode(index).length).toBeLessThanOrEqual(63);+ expect(primaryKey).not.toBe(index);+ });++ it("keeps SQLite index namespaces on the index rather than the ON table", () => {+ const ddl = 'CREATE TABLE "apis" (id int); CREATE INDEX "idx" ON "apis" (id)';+ const result = rewriteCreateTableName(ddl, '"archive"."copy"', "sqlite", undefined, "apis")!;+ expect(result).toMatch(/CREATE INDEX "archive"\."copy_idx_dbx_[a-f0-9]+" ON "copy" \(id\)/);+ });++ it("rejects foreign table statements, additional tables and unsupported scripts before replay", () => {+ for (const ddl of [+ "CREATE TABLE apis (id int); ALTER TABLE other ADD x int",+ "CREATE TABLE apis (id int); CREATE TABLE other (id int)",+ "CREATE TABLE apis (id int); DELETE FROM apis",+ "CREATE TABLE apis PARTITION OF parent FOR VALUES IN (1)",+ "CREATE TABLE apis (id int); ALTER TABLE apis ATTACH PARTITION other FOR VALUES IN (1)",+ ]) {+ expect(rewriteCreateTableName(ddl, '"copy"', "postgres", undefined, "apis")).toBeUndefined();+ }+ expect(rewriteCreateTableName('CREATE TABLE "Apis" (id int)', '"copy"', "postgres", undefined, "apis")).toBeUndefined();+ });++ it("preserves MySQL backslash-escaped comments containing table-like text", () => {+ const ddl = "CREATE TABLE `apis` (`id` int COMMENT 'user\\'s apis', `apis` int)";+ expect(rewriteCreateTableName(ddl, "`copy`", "mysql", undefined, "apis")).toBe("CREATE TABLE `copy` (`id` int COMMENT 'user\\'s apis', `apis` int)");+ });++ it("does not allow IF NOT EXISTS to hide a concurrent target-name collision", () => {+ const result = rewriteCreateTableName("CREATE TABLE IF NOT EXISTS apis (id int); CREATE INDEX IF NOT EXISTS idx ON apis (id)", '"copy"', "postgres", undefined, "apis")!;+ expect(result).not.toContain("IF NOT EXISTS");+ expect(result).toContain('"copy" (id int)');+ });++ it("recognizes the actual MySQL transaction-capable storage engine", () => {+ expect(transactionalMysqlTableDdl("CREATE TABLE t (id int) ENGINE=InnoDB")).toBe(true);+ expect(transactionalMysqlTableDdl("CREATE TABLE t (id int) ENGINE='InnoDB'")).toBe(true);+ expect(transactionalMysqlTableDdl("CREATE TABLE t (id int COMMENT 'ENGINE=InnoDB') ENGINE=MyISAM")).toBe(false);+ expect(transactionalMysqlTableDdl("CREATE TABLE t (id int) ENGINE=MyISAM COMMENT='ENGINE=InnoDB'")).toBe(false);+ expect(transactionalMysqlTableDdl("CREATE TABLE t (id int) /* ENGINE=InnoDB */")).toBe(false);+ expect(transactionalMysqlTableDdl("CREATE TABLE t (`ENGINE` text DEFAULT 'InnoDB')")).toBe(false);+ });++ it("accepts the H2 MEMORY/CACHED table forms emitted by its SCRIPT metadata path", () => {+ for (const storage of ["MEMORY", "CACHED"]) {+ const ddl = `CREATE ${storage} TABLE "PUBLIC"."APIS"("ID" INTEGER);`;+ expect(rewriteCreateTableName(ddl, '"ARCHIVE"."COPY"', "h2", "PUBLIC", "APIS")).toBe(`CREATE ${storage} TABLE "ARCHIVE"."COPY"("ID" INTEGER);`);+ }+ });++ it("rewrites schema-qualified constraints emitted by H2 SCRIPT", () => {+ const ddl = 'CREATE MEMORY TABLE "PUBLIC"."APIS"("ID" INTEGER NOT NULL, "CODE" CHARACTER VARYING(30));\nALTER TABLE "PUBLIC"."APIS" ADD CONSTRAINT "PUBLIC"."CONSTRAINT_1" PRIMARY KEY("ID");\nALTER TABLE "PUBLIC"."APIS" ADD CONSTRAINT "PUBLIC"."UQ_CODE" UNIQUE("CODE");';+ const rewritten = rewriteCreateTableName(ddl, '"ARCHIVE"."COPY"', "h2")!;+ expect(rewritten).toMatch(/ADD CONSTRAINT "ARCHIVE"\."COPY_CONSTRAINT_1_dbx_[a-f0-9]+" PRIMARY KEY/);+ expect(rewritten).toMatch(/ADD CONSTRAINT "ARCHIVE"\."COPY_UQ_CODE_dbx_[a-f0-9]+" UNIQUE/);+ expect(rewritten).not.toContain('"PUBLIC"');+ const unqualified = rewriteCreateTableName(ddl, '"COPY"', "h2")!;+ expect(unqualified).toMatch(/ADD CONSTRAINT "COPY_CONSTRAINT_1_dbx_[a-f0-9]+" PRIMARY KEY/);+ });++ it("rejects incomplete fallback results even without a row limit", () => {+ const result = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 0 };+ expect(queryResultTransferIncomplete({ ...result, truncated: true })).toBe(true);+ expect(queryResultTransferIncomplete({ ...result, has_more: true })).toBe(true);+ expect(queryResultTransferIncomplete(result, 1)).toBe(false);+ expect(queryResultTransferIncomplete({ ...result, rows: [[1], [2]] }, 1)).toBe(true);+ });+});diff --git a/apps/desktop/src/components/transfer/__tests__/queryResultTransferCollations.spec.ts b/apps/desktop/src/components/transfer/__tests__/queryResultTransferCollations.spec.tsnew file mode 100644index 0000000000..35e05e6a5d--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/queryResultTransferCollations.spec.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { adaptMysqlDdlCollations, mysqlDdlCollations } from "../queryResultTransferDdl";++describe("MySQL transfer collation compatibility", () => {+ const ddl = "CREATE TABLE t (`utf8mb4_0900_ai_ci` TEXT COLLATE 'utf8mb4_0900_ai_ci' DEFAULT 'COLLATE utf8mb4_0900_ai_ci', b TEXT COLLATE `utf8mb4_bin`) DEFAULT CHARSET=utf8mb4 COLLATE=UTF8MB4_0900_AI_CI COMMENT='utf8mb4_0900_ai_ci'; -- COLLATE utf8mb4_0900_ai_ci";++ it("rewrites column/table clauses without changing names, defaults, comments or supported rules", () => {+ const result = adaptMysqlDdlCollations(ddl, ["utf8mb4_unicode_ci", "utf8mb4_unicode_520_ci", "utf8mb4_bin"]);+ expect(result.unsupported).toEqual([]);+ expect(result.changes).toEqual(["utf8mb4_0900_ai_ci → utf8mb4_unicode_520_ci"]);+ expect(result.ddl).toContain("`utf8mb4_0900_ai_ci` TEXT COLLATE utf8mb4_unicode_520_ci DEFAULT 'COLLATE utf8mb4_0900_ai_ci'");+ expect(result.ddl).toContain("COLLATE `utf8mb4_bin`");+ expect(result.ddl).toContain("COLLATE=utf8mb4_unicode_520_ci COMMENT='utf8mb4_0900_ai_ci'; -- COLLATE utf8mb4_0900_ai_ci");+ expect(mysqlDdlCollations(ddl)).toEqual(["utf8mb4_0900_ai_ci", "utf8mb4_bin"]);+ });++ it("preserves the source byte-for-byte when supported", () => {+ expect(adaptMysqlDdlCollations(ddl, ["UTF8MB4_0900_AI_CI", "utf8mb4_bin"])).toEqual({ ddl, changes: [], unsupported: [] });+ });++ it("does not guess replacements for case-sensitive or language-specific rules", () => {+ const sql = "CREATE TABLE t (v TEXT COLLATE utf8mb4_0900_as_cs) COLLATE=utf8mb4_de_pb_0900_ai_ci";+ expect(adaptMysqlDdlCollations(sql, ["utf8mb4_unicode_ci"]).unsupported).toEqual(["utf8mb4_de_pb_0900_ai_ci", "utf8mb4_0900_as_cs"]);+ });++ it("does not query metadata for collation-like text in data", () => {+ expect(mysqlDdlCollations("CREATE TABLE t (`collate` TEXT DEFAULT 'COLLATE utf8mb4_0900_ai_ci') -- COLLATE utf8mb4_0900_ai_ci")).toEqual([]);+ });+});diff --git a/apps/desktop/src/components/transfer/__tests__/queryResultTransferSource.spec.ts b/apps/desktop/src/components/transfer/__tests__/queryResultTransferSource.spec.tsnew file mode 100644index 0000000000..a73a526939--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/queryResultTransferSource.spec.ts@@ -0,0 +1,274 @@+import { DatabaseSync } from "node:sqlite";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { loadQueryResultTransferSourceDdl } from "../queryResultTransferSource";+import { rewriteCreateTableName } from "../queryResultTransferDdl";++const api = vi.hoisted(() => ({ getTableDdl: vi.fn(), getTableDisplayDdl: vi.fn(), executeMulti: vi.fn() }));+vi.mock("@/lib/backend/api", () => api);+let h2Tables: string[][];++describe("query result transfer source DDL", () => {+ beforeEach(() => {+ api.getTableDdl.mockReset().mockResolvedValue('CREATE TABLE "public"."apis" ("id" serial PRIMARY KEY);');+ api.getTableDisplayDdl.mockReset().mockResolvedValue('CREATE TABLE "public"."apis" ("id" serial PRIMARY KEY); ALTER TABLE "public"."apis" OWNER TO "source_owner"; SET ROLE "source_owner"; GRANT SELECT ON "public"."apis" TO "reader"; RESET ROLE;');+ api.executeMulti.mockReset().mockImplementation(async (_connection, _database, sql) => {+ if (sql.startsWith("SELECT TABLE_SCHEMA,")) return [{ rows: h2Tables }];+ return [{ columns: ["nspname"], rows: [["application"]] }];+ });+ h2Tables = [["PUBLIC", "APIS", "BASE TABLE"]];+ });++ it("uses the executable PostgreSQL table DDL instead of display access and partition statements", async () => {+ const ddl = await loadQueryResultTransferSourceDdl({ sql: 'SELECT * FROM "public"."apis"', databaseType: "postgres", connectionId: "source", database: "source_db", schema: "other_schema" });++ expect(api.getTableDdl).toHaveBeenCalledWith("source", "source_db", "public", "apis", undefined, undefined);+ expect(api.getTableDisplayDdl).not.toHaveBeenCalled();+ expect(ddl).toBe('CREATE TABLE "public"."apis" ("id" serial PRIMARY KEY);');+ });++ it("resolves an unqualified PostgreSQL table through the active schema's fallback search path", async () => {+ api.executeMulti.mockResolvedValueOnce([{ columns: ["nspname"], rows: [["public"]] }]);+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "postgres", connectionId: "source", database: "source_db", schema: "tenant" });+ expect(api.executeMulti).toHaveBeenCalledWith("source", "source_db", expect.stringContaining("pg_catalog.to_regclass"), "tenant", undefined, expect.any(Object));+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "source_db", "public", "apis", undefined, undefined);+ });++ it("resolves a PostgreSQL relation through search_path on the source query session", async () => {+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM APIS", databaseType: "postgres", connectionId: "source", database: "source_db", clientSessionId: "query_session" });+ expect(api.executeMulti).toHaveBeenCalledWith("source", "source_db", expect.stringContaining("pg_catalog.to_regclass('\"apis\"')"), undefined, undefined, { executionMode: "simple", maxRows: 1, catalog: undefined, clientSessionId: "query_session" });+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "source_db", "application", "apis", undefined, undefined);+ });++ it("folds only unquoted PostgreSQL source names and avoids resolving an explicit schema", async () => {+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM PUBLIC.APIS", databaseType: "postgres", connectionId: "source", database: "source_db" });+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "source_db", "public", "apis", undefined, undefined);+ expect(api.executeMulti).not.toHaveBeenCalled();+ api.getTableDdl.mockClear();+ await loadQueryResultTransferSourceDdl({ sql: 'SELECT * FROM "Public"."APIS"', databaseType: "postgres", connectionId: "source", database: "source_db" });+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "source_db", "Public", "APIS", undefined, undefined);+ });++ it.each([+ { columns: ["nspname"], rows: [] },+ { columns: ["nspname"], rows: [["wrong"]], execution_error: true },+ ])("does not fetch an arbitrary schema when relation resolution fails", async (result) => {+ api.executeMulti.mockResolvedValueOnce([result]);+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "postgres", connectionId: "source", database: "source_db" })).toBeUndefined();+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it("keeps SQL Server temporal details for the DDL safety check", async () => {+ const ddl = "CREATE TABLE [app].[apis] ([id] int, PERIOD FOR SYSTEM_TIME ([start], [end])) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [app].[apis_history]));";+ api.getTableDisplayDdl.mockResolvedValueOnce(ddl);+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM app.apis", databaseType: "sqlserver", connectionId: "source", database: "source_db" })).toBe(ddl);+ expect(api.getTableDisplayDdl).toHaveBeenCalledWith("source", "source_db", "app", "apis", undefined, undefined);+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it("resolves a MySQL database qualifier without retaining the prior database as schema", async () => {+ const ddl = "CREATE TABLE `apis` (`id` int) ENGINE=InnoDB";+ api.executeMulti.mockResolvedValueOnce([{ rows: [["apis", ddl]] }]);+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM `archive`.`apis`", databaseType: "mysql", connectionId: "source", database: "main", schema: "main", clientSessionId: "query_session" })).toBe(ddl);+ expect(api.executeMulti).toHaveBeenCalledWith("source", "main", "SHOW CREATE TABLE `archive`.`apis`", undefined, undefined, expect.objectContaining({ clientSessionId: "query_session" }));+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it("uses the selected MySQL database as its metadata namespace", async () => {+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "mysql", connectionId: "source", database: "source_db", schema: "stale_schema" });+ expect(api.executeMulti).toHaveBeenCalledWith("source", "source_db", "SHOW CREATE TABLE `source_db`.`apis`", undefined, undefined, expect.any(Object));+ });++ it.each(["mysql", "goldendb"] as const)("rejects the source session's temporary table instead of copying its permanent shadow (%s)", async (databaseType) => {+ api.executeMulti.mockResolvedValueOnce([{ rows: [["apis", "CREATE TEMPORARY TABLE `apis` (`id` int)"]] }]);+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType, connectionId: "source", database: "main", clientSessionId: "source_session" })).toBeUndefined();+ expect(api.executeMulti.mock.calls[0]![5]).toMatchObject({ clientSessionId: "source_session" });+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it.each(["mysql", "postgres", "sqlite", "h2"] as const)("does not reuse metadata outside the source manual transaction (%s)", async (databaseType) => {+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType, connectionId: "source", database: "main", txnSessionId: "manual_txn" })).toBeUndefined();+ expect(api.executeMulti).not.toHaveBeenCalled();+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it("preserves a SQLite attached database namespace for metadata", async () => {+ api.executeMulti.mockResolvedValueOnce([{ rows: [["apis", "CREATE TABLE apis (id int)", "table"]] }]).mockResolvedValueOnce([{ rows: [] }]);+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM aux.apis", databaseType: "sqlite", connectionId: "source", database: "/tmp/source.sqlite", schema: "main" });+ expect(api.getTableDdl).not.toHaveBeenCalled();+ expect(api.executeMulti).toHaveBeenCalledWith("source", "/tmp/source.sqlite", expect.stringContaining('FROM "aux".sqlite_master'), undefined, undefined, expect.any(Object));+ });++ it("preserves real SQLite explicit indexes through the source metadata path", async () => {+ const db = new DatabaseSync(":memory:");+ try {+ db.exec(`ATTACH DATABASE ':memory:' AS "analytics.db";+ CREATE TABLE "analytics.db"."api's" (id INTEGER PRIMARY KEY, code TEXT, active INT, inline_unique TEXT UNIQUE);+ CREATE UNIQUE INDEX "analytics.db".uq_code ON "api's" (lower(code)) WHERE active = 1;+ CREATE INDEX "analytics.db".idx_active ON "api's" (active DESC);+ CREATE TRIGGER "analytics.db".excluded_trigger AFTER INSERT ON "api's" BEGIN SELECT 1; END;+ INSERT INTO "analytics.db"."api's" VALUES (1, 'sample', 1, 'one');`);+ // Execute the real metadata SQL on the same connection as the source rows.+ api.executeMulti.mockImplementation(async (_connection, _database, sql) => [+ {+ rows: db+ .prepare(sql)+ .all()+ .map((row) => Object.values(row)),+ },+ ]);+ const ddl = await loadQueryResultTransferSourceDdl({ sql: 'SELECT * FROM "analytics.db"."api\'s"', databaseType: "sqlite", connectionId: "source", database: "main", clientSessionId: "query_session" });+ expect(ddl).toContain("CREATE UNIQUE INDEX");+ expect(ddl).not.toContain("CREATE TRIGGER");+ expect(ddl).not.toContain("sqlite_autoindex");+ expect(api.getTableDdl).not.toHaveBeenCalled();+ expect(api.executeMulti.mock.calls[0]![5]).toMatchObject({ clientSessionId: "query_session" });+ const rewritten = rewriteCreateTableName(ddl!, '"main"."copy"', "sqlite");+ expect(rewritten).toBeDefined();+ db.exec(`${rewritten}; INSERT INTO main.copy SELECT * FROM "analytics.db"."api's";`);+ expect(db.prepare('PRAGMA main.index_list("copy")').all()).toHaveLength(3);+ expect(() => db.exec("INSERT INTO copy VALUES (2, 'SAMPLE', 1, 'two')")).toThrow(/UNIQUE constraint failed/);+ db.exec("INSERT INTO copy VALUES (2, 'SAMPLE', 0, 'two')");+ expect(db.prepare("SELECT count(*) AS count FROM copy").get()!.count).toBe(2);+ } finally {+ db.close();+ }+ });++ it("uses SQLite temp/main/attachment lookup order and actual case on the source session", async () => {+ const db = new DatabaseSync(":memory:");+ try {+ db.exec(`ATTACH DATABASE ':memory:' AS "first/attached"; ATTACH DATABASE ':memory:' AS second;+ CREATE TABLE main.apis(id INT, marker TEXT DEFAULT 'main');+ CREATE TABLE "first/attached".apis(id INT, marker TEXT DEFAULT 'first');+ CREATE TABLE second.apis(id INT, marker TEXT DEFAULT 'second');+ CREATE TEMP TABLE apis(id INT, marker TEXT DEFAULT 'temp');+ CREATE UNIQUE INDEX temp.uq_apis ON apis(id);`);+ api.executeMulti.mockImplementation(async (_connection, _database, sql) => [+ {+ rows: db+ .prepare(sql)+ .all()+ .map((row) => Object.values(row)),+ },+ ]);+ const request = { sql: "SELECT * FROM APIS", databaseType: "sqlite" as const, connectionId: "source", database: "second", clientSessionId: "source_session" };+ const tempDdl = await loadQueryResultTransferSourceDdl(request);+ expect(tempDdl).toContain("DEFAULT 'temp'");+ const rewritten = rewriteCreateTableName(tempDdl!, '"second"."copy"', "sqlite")!;+ db.exec(`${rewritten}; INSERT INTO second.copy(id) VALUES(1)`);+ expect(() => db.exec("INSERT INTO second.copy(id) VALUES(1)")).toThrow(/UNIQUE constraint failed/);+ expect(await loadQueryResultTransferSourceDdl({ ...request, sql: "SELECT * FROM MAIN.APIS" })).toContain("DEFAULT 'main'");+ expect(await loadQueryResultTransferSourceDdl({ ...request, sql: 'SELECT * FROM "first/attached".APIS' })).toContain("DEFAULT 'first'");+ db.exec("DROP TABLE temp.apis");+ expect(await loadQueryResultTransferSourceDdl(request)).toContain("DEFAULT 'main'");+ db.exec("DROP TABLE main.apis");+ expect(await loadQueryResultTransferSourceDdl(request)).toContain("DEFAULT 'first'");+ expect(api.executeMulti.mock.calls.every((call) => call[5].clientSessionId === "source_session")).toBe(true);+ expect(api.getTableDdl).not.toHaveBeenCalled();+ } finally {+ db.close();+ }+ });++ it("does not skip a shadowing SQLite view to copy a different permanent table", async () => {+ const db = new DatabaseSync(":memory:");+ try {+ db.exec("CREATE TABLE apis (id INT); CREATE TEMP VIEW apis AS SELECT 42 AS id");+ api.executeMulti.mockImplementation(async (_connection, _database, sql) => [+ {+ rows: db+ .prepare(sql)+ .all()+ .map((row) => Object.values(row)),+ },+ ]);+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "sqlite", connectionId: "source", database: "main" })).toBeUndefined();+ } finally {+ db.close();+ }+ });++ it.each([{ rows: [], truncated: true }, { rows: [], has_more: true }, { rows: [], execution_error: true }, { rows: [["CREATE INDEX truncated..."]], large_value_cells: [{ row_index: 0, column_index: 0, original_bytes: 100000 }] }, { rows: [[null]] }])(+ "does not silently omit SQLite indexes after incomplete metadata: %s",+ async (result) => {+ api.executeMulti.mockResolvedValueOnce([{ rows: [["apis", "CREATE TABLE apis (id int)", "table"]] }]).mockResolvedValueOnce([result]);+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM main.apis", databaseType: "sqlite", connectionId: "source", database: "main" })).toBeUndefined();+ },+ );++ it.each(["APIS", "apis", "Apis"])("resolves unquoted H2 names from physical metadata (%s)", async (physicalName) => {+ h2Tables = [["PUBLIC", physicalName, "BASE TABLE"]];+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "h2", connectionId: "source", database: "test", schema: "PUBLIC" });+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "test", "PUBLIC", physicalName, undefined, undefined);+ });++ it("resolves an unquoted H2 schema without imposing uppercase storage", async () => {+ h2Tables = [["public", "apis", "BASE TABLE"]];+ await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM PUBLIC.APIS", databaseType: "h2", connectionId: "source", database: "test" });+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "test", "public", "apis", undefined, undefined);+ });++ it("retains exact quoted H2 names and rejects ambiguous unquoted tables", async () => {+ h2Tables = [["Public", "apis", "BASE TABLE"]];+ await loadQueryResultTransferSourceDdl({ sql: 'SELECT * FROM "Public"."apis"', databaseType: "h2", connectionId: "source", database: "test" });+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "test", "Public", "apis", undefined, undefined);+ api.executeMulti.mockClear();+ api.getTableDdl.mockClear();+ h2Tables = [+ ["PUBLIC", "APIS", "BASE TABLE"],+ ["PUBLIC", "apis", "BASE TABLE"],+ ];+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "h2", connectionId: "source", database: "test", schema: "PUBLIC" })).toBeUndefined();+ expect(api.getTableDdl).not.toHaveBeenCalled();+ expect(api.executeMulti.mock.calls.some((call) => call[2].startsWith("SCRIPT "))).toBe(false);+ });++ it("reads H2 SCRIPT through the independent metadata API to avoid committing the source transaction", async () => {+ // H2 2.2.224 reproduction: BEGIN; INSERT INTO APIS VALUES(1); SCRIPT+ // NODATA TABLE APIS; ROLLBACK; SELECT COUNT(*) FROM APIS returns 1.+ // The source session must receive only the read-only metadata lookup.+ const statements = ['CREATE MEMORY TABLE "PUBLIC"."APIS"("ID" INTEGER NOT NULL);', 'ALTER TABLE "PUBLIC"."APIS" ADD CONSTRAINT "PUBLIC"."CONSTRAINT_1" PRIMARY KEY("ID");', 'CREATE UNIQUE NULLS DISTINCT INDEX "PUBLIC"."IDX" ON "PUBLIC"."APIS"("ID" NULLS FIRST);'];+ api.getTableDdl.mockResolvedValueOnce(statements.join("\n"));+ const ddl = await loadQueryResultTransferSourceDdl({ sql: 'SELECT * FROM "PUBLIC"."APIS"', databaseType: "h2", connectionId: "source", database: "test", clientSessionId: "source_session" });+ expect(ddl).toBe(statements.join("\n"));+ expect(api.getTableDdl).toHaveBeenCalledWith("source", "test", "PUBLIC", "APIS", undefined, undefined);+ expect(api.executeMulti).toHaveBeenCalledTimes(1);+ expect(api.executeMulti).toHaveBeenCalledWith("source", "test", "SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES", undefined, undefined, expect.objectContaining({ clientSessionId: "source_session" }));+ expect(rewriteCreateTableName(ddl!, '"ARCHIVE"."COPY"', "h2")).toContain('ON "ARCHIVE"."COPY"');+ });++ it("preserves real H2 SCRIPT inline table and column comments through rewriting", async () => {+ const statements = ['CREATE MEMORY TABLE "PUBLIC"."APIS" COMMENT \'table desc\'(\n "ID" INTEGER NOT NULL,\n "NAME" CHARACTER VARYING COMMENT \'column desc\'\n);', 'ALTER TABLE "PUBLIC"."APIS" ADD CONSTRAINT "PUBLIC"."CONSTRAINT_1" PRIMARY KEY("ID");'];+ api.getTableDdl.mockResolvedValueOnce(statements.join("\n"));+ const ddl = await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "h2", connectionId: "source", database: "test", schema: "PUBLIC" });+ const rewritten = rewriteCreateTableName(ddl!, '"ARCHIVE"."COPY"', "h2");+ expect(rewritten).toContain('CREATE MEMORY TABLE "ARCHIVE"."COPY" COMMENT \'table desc\'');+ expect(rewritten).toContain("\"NAME\" CHARACTER VARYING COMMENT 'column desc'");+ });++ it("preserves H2 explicit sequence dependencies so the rewriter can reject them safely", async () => {+ api.getTableDdl.mockResolvedValueOnce('CREATE SEQUENCE IF NOT EXISTS "PUBLIC"."SEQ" START WITH 1; CREATE MEMORY TABLE "PUBLIC"."APIS"("ID" BIGINT DEFAULT NEXT VALUE FOR "PUBLIC"."SEQ");');+ const ddl = await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "h2", connectionId: "source", database: "test", schema: "PUBLIC" });+ expect(ddl).toContain("CREATE SEQUENCE");+ expect(rewriteCreateTableName(ddl!, '"ARCHIVE"."COPY"', "h2")).toBeUndefined();+ });++ it("refuses H2 local temporary metadata on the source session without choosing a permanent shadow", async () => {+ h2Tables = [["PUBLIC", "Apis", "LOCAL TEMPORARY"]];+ expect(await loadQueryResultTransferSourceDdl({ sql: 'SELECT * FROM "PUBLIC"."Apis"', databaseType: "h2", connectionId: "source", database: "test", clientSessionId: "source_session" })).toBeUndefined();+ expect(api.executeMulti.mock.calls.every((call) => call[5].clientSessionId === "source_session")).toBe(true);+ expect(api.executeMulti.mock.calls.some((call) => call[2].startsWith("SCRIPT "))).toBe(false);+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it.each(["SELECT id FROM apis", "SELECT a.*, b.name FROM apis a JOIN users b ON b.id = a.id", "SELECT 1 AS id"])("does not fetch whole-table DDL for %s", async (sql) => {+ expect(await loadQueryResultTransferSourceDdl({ sql, databaseType: "postgres", connectionId: "source", database: "source_db", schema: "public" })).toBeUndefined();+ expect(api.getTableDdl).not.toHaveBeenCalled();+ });++ it("returns unavailable instead of switching to display DDL after a metadata error", async () => {+ api.getTableDdl.mockRejectedValueOnce(new Error("metadata failed"));+ expect(await loadQueryResultTransferSourceDdl({ sql: "SELECT * FROM apis", databaseType: "postgres", connectionId: "source", database: "source_db", schema: "public" })).toBeUndefined();+ expect(api.getTableDisplayDdl).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/components/transfer/__tests__/queryResultTransferSqlite.spec.ts b/apps/desktop/src/components/transfer/__tests__/queryResultTransferSqlite.spec.tsnew file mode 100644index 0000000000..4a851e6dcb--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/queryResultTransferSqlite.spec.ts@@ -0,0 +1,66 @@+import { DatabaseSync } from "node:sqlite";+import { describe, expect, it } from "vitest";+import { nonInsertableColumnNamesFromDdl, rewriteCreateTableName } from "../queryResultTransfer";+import { queryResultTransferInsertSql } from "../queryResultTransferStatements";+import { queryResultTransferSqlLiteral } from "../queryResultTransferValues";++describe("query result transfer against SQLite", () => {+ it("copies a real schema and values, including generated columns, references and quoted identifiers", () => {+ const db = new DatabaseSync(":memory:");+ try {+ db.exec(`PRAGMA foreign_keys = ON;+ CREATE TABLE "apis" (+ "id" INTEGER PRIMARY KEY AUTOINCREMENT,+ " name " TEXT NOT NULL DEFAULT 'fallback',+ "parent" INTEGER REFERENCES "apis" ("id"),+ "length" INTEGER GENERATED ALWAYS AS (length(" name ")) STORED+ );+ CREATE INDEX "idx_apis_name" ON "apis" (" name ");`);+ const insert = db.prepare('INSERT INTO "apis" (" name ", "parent") VALUES (?, ?)');+ insert.run("C:\\data\\请求", null);+ insert.run("O'Reilly", 1);+ const rows = db.prepare('SELECT * FROM "apis"').all();+ const ddl = db+ .prepare("SELECT sql FROM sqlite_master WHERE tbl_name = 'apis' AND sql IS NOT NULL ORDER BY type DESC")+ .all()+ .map((row) => row.sql)+ .join(";\n");+ const rewritten = rewriteCreateTableName(ddl, '"copy"', "sqlite", undefined, "apis");+ expect(rewritten).toBeDefined();+ const generated = nonInsertableColumnNamesFromDdl(ddl, "sqlite");+ const columns = Object.keys(rows[0]!).filter((name) => !generated.has(name));+ const values = rows.map((row) => `(${columns.map((column) => queryResultTransferSqlLiteral(row[column], "sqlite")).join(", ")})`);+ const statements = queryResultTransferInsertSql(+ '"copy"',+ columns.map((column) => `"${column}"`),+ values,+ "sqlite",+ );+ db.exec(`BEGIN; ${rewritten}; ${statements.join(";")}; COMMIT;`);++ expect(db.prepare('SELECT * FROM "copy"').all()).toEqual(rows);+ expect(db.prepare('PRAGMA table_xinfo("copy")').all()).toEqual(db.prepare('PRAGMA table_xinfo("apis")').all());+ expect(db.prepare('PRAGMA foreign_key_list("copy")').all()[0]?.table).toBe("copy");+ expect(db.prepare('PRAGMA index_list("copy")').all()).toHaveLength(1);+ db.exec('INSERT INTO "copy" DEFAULT VALUES');+ expect(db.prepare('SELECT id, " name " AS name, length FROM "copy" WHERE id = 3').get()).toEqual({ id: 3, name: "fallback", length: 8 });+ } finally {+ db.close();+ }+ });++ it("rolls back both table creation and rows when a copied constraint rejects an insert", () => {+ const db = new DatabaseSync(":memory:");+ try {+ const ddl = rewriteCreateTableName("CREATE TABLE source (id INTEGER PRIMARY KEY, value TEXT NOT NULL)", '"copy"', "sqlite")!;+ db.exec("BEGIN");+ db.exec(ddl);+ const statements = queryResultTransferInsertSql('"copy"', ['"id"', '"value"'], ["(1, 'ok')", "(2, NULL)"], "sqlite");+ expect(() => statements.forEach((sql) => db.exec(sql))).toThrow(/NOT NULL/);+ db.exec("ROLLBACK");+ expect(db.prepare("SELECT name FROM sqlite_master WHERE name = 'copy'").get()).toBeUndefined();+ } finally {+ db.close();+ }+ });+});diff --git a/apps/desktop/src/components/transfer/__tests__/queryResultTransferStatements.spec.ts b/apps/desktop/src/components/transfer/__tests__/queryResultTransferStatements.spec.tsnew file mode 100644index 0000000000..75d302fddf--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/queryResultTransferStatements.spec.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";+import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";+import { postgresTransferSequenceSyncSql, queryResultTransferInsertSql, withSqlServerIdentityInsert } from "../queryResultTransferStatements";++describe("query result transfer statements", () => {+ it("uses Oracle INSERT ALL for multiple rows and portable individual inserts on JDBC variants", () => {+ for (const type of ["oracle", "oceanbase-oracle"] as const) {+ expect(queryResultTransferInsertSql('"t"', ['"id"'], ["(1)", "(2)"], type)).toEqual(['INSERT ALL\nINTO "t" ("id") VALUES (1)\nINTO "t" ("id") VALUES (2)\nSELECT 1 FROM dual']);+ }+ for (const type of ["dameng", "yashandb", "iris", "db2"] as const) expect(queryResultTransferInsertSql('"t"', ['"id"'], ["(1)", "(2)"], type)).toEqual(['INSERT INTO "t" ("id") VALUES (1)', 'INSERT INTO "t" ("id") VALUES (2)']);+ });++ it("places the PostgreSQL identity override before VALUES", () => {+ expect(queryResultTransferInsertSql('"t"', ['"id"'], ["(1)"], "postgres", true)).toEqual(['INSERT INTO "t" ("id") OVERRIDING SYSTEM VALUE VALUES (1)']);+ expect(queryResultTransferInsertSql('"t"', ['"id"'], [], "postgres", true)).toEqual([]);+ });++ it("restores SQL Server session state and rethrows percent-containing error text safely", () => {+ const sql = withSqlServerIdentityInsert("[t]", ["INSERT INTO [t] ([id]) VALUES (1)"]);+ expect(sql.match(/SET IDENTITY_INSERT \[t\] OFF/g)).toHaveLength(2);+ expect(sql).toContain("RAISERROR(N'%s', 16, 1, @dbx_transfer_error)");+ expect(sql.indexOf("ERROR_MESSAGE()")).toBeLessThan(sql.lastIndexOf("SET IDENTITY_INSERT [t] OFF"));+ // executeInTransaction sends this array element as one SQL Server batch;+ // it must keep ON, inserts and both OFF paths within that same session.+ expect(sql).toContain("BEGIN TRY\nSET IDENTITY_INSERT [t] ON;");+ });++ it("synchronizes PostgreSQL sequences in their direction after locking and without setval", () => {+ const sql = postgresTransferSequenceSyncSql('"public"."copy"', "id");+ expect(sql).toContain("SELECT increment_by FROM ");+ expect(sql).toContain("SELECT seqincrement FROM pg_catalog.pg_sequence");+ expect(sql).toContain("CASE WHEN dbx_increment > 0 THEN 'MAX' ELSE 'MIN' END");+ expect(sql).toContain("dbx_next := dbx_last + CASE WHEN dbx_called THEN dbx_increment ELSE 0 END");+ expect(sql).toContain("FLOOR((dbx_edge - dbx_next) / dbx_increment) * dbx_increment");+ expect(sql.indexOf("' INCREMENT BY '")).toBeLessThan(sql.indexOf("SELECT last_value"));+ expect(sql).not.toContain("setval(");+ expect(sql).toContain("END;\n$dbx_transfer$");+ expect(splitSqlStatementRanges(sql, "postgres")).toHaveLength(1);+ });++ it("quotes PostgreSQL names and chooses a delimiter that cannot occur in user input", () => {+ const sql = postgresTransferSequenceSyncSql('"s"."copy$dbx_transfer$"', "id'\"\\");+ expect(sql).toMatch(/^DO \$dbx_transfer_\$/);+ expect(sql).toContain("pg_get_serial_sequence");+ expect(splitSqlStatementRanges(sql, "postgres")).toHaveLength(1);+ });+});diff --git a/apps/desktop/src/components/transfer/__tests__/queryResultTransferValues.spec.ts b/apps/desktop/src/components/transfer/__tests__/queryResultTransferValues.spec.tsnew file mode 100644index 0000000000..0faff1fac7--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/queryResultTransferValues.spec.ts@@ -0,0 +1,338 @@+import { describe, expect, it } from "vitest";+import { queryResultTransferIsBinaryColumnType, queryResultTransferSqlLiteral, queryResultTransferTargetType } from "../queryResultTransferValues";++describe("query result transfer value literals", () => {+ it.each([+ ["sqlite", "BLOB", "X'0001fe'"],+ ["postgres", "bytea", "decode('0001fe', 'hex')"],+ ["sqlserver", "varbinary(max)", "0x0001fe"],+ ["oracle", "BLOB", "HEXTORAW('0001fe')"],+ ["oceanbase-oracle", "BLOB", "HEXTORAW('0001fe')"],+ ["mysql", "BLOB", "X'0001fe'"],+ ["h2", "BLOB", "X'0001fe'"],+ ["db2", "BLOB", "BX'0001fe'"],+ ] as const)("preserves binary bytes for %s", (databaseType, targetType, expected) => {+ expect(queryResultTransferTargetType("bytea", databaseType)).toBe(targetType);+ expect(queryResultTransferSqlLiteral("0x0001fe", databaseType, "bytea", targetType)).toBe(expected);+ });++ it("treats SQL Server timestamp/rowversion values as binary", () => {+ expect(queryResultTransferTargetType("timestamp", "postgres", "sqlserver")).toBe("bytea");+ expect(queryResultTransferTargetType("rowversion", "sqlite", "sqlserver")).toBe("BLOB");+ expect(queryResultTransferSqlLiteral("0x0001fe", "postgres", "timestamp", "bytea", "sqlserver")).toBe("decode('0001fe', 'hex')");+ });++ it("fails closed for an unverified binary dialect", () => {+ expect(queryResultTransferSqlLiteral("0x0001fe", "hive", "binary", "BINARY")).toBeUndefined();+ });++ it("fails closed for malformed canonical binary values", () => {+ expect(queryResultTransferSqlLiteral("0xnot-hex", "postgres", "bytea", "bytea")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("0x123", "sqlite", "blob", "BLOB")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("not encoded bytes", "postgres", "bytea", "bytea")).toBeUndefined();+ expect(queryResultTransferSqlLiteral([0, 256], "postgres", "bytea", "bytea")).toBeUndefined();+ });++ it("keeps the original bytes when the backend returns a typed byte array", () => {+ expect(queryResultTransferSqlLiteral(new Uint8Array([0, 255]), "postgres", "bytea", "bytea")).toBe("decode('00ff', 'hex')");+ });++ it("retains GoldenDB binary payloads whose bytes resemble hexadecimal display text", () => {+ // GoldendbAgent.resultValue returns canonical hex even for ASCII bytes.+ expect(queryResultTransferSqlLiteral("0x6465616462656566", "goldendb", "VARBINARY", "VARBINARY(16)", "goldendb")).toBe("X'6465616462656566'");+ expect(queryResultTransferSqlLiteral("0x307830306666", "goldendb", "BLOB", "BLOB", "goldendb")).toBe("X'307830306666'");+ expect(queryResultTransferSqlLiteral("0x00ff80", "goldendb", "BINARY", "BINARY(3)", "goldendb")).toBe("X'00ff80'");+ expect(queryResultTransferSqlLiteral("0x", "goldendb", "BLOB", "BLOB", "goldendb")).toBe("X''");+ expect(queryResultTransferSqlLiteral(null, "goldendb", "BLOB", "BLOB", "goldendb")).toBe("NULL");+ });++ it.each([+ ["sqlite", "1", "0"],+ ["postgres", "TRUE", "FALSE"],+ ["oracle", "1", "0"],+ ["oceanbase-oracle", "1", "0"],+ ["sqlserver", "1", "0"],+ ] as const)("aligns boolean literals with the target type for %s", (databaseType, expectedTrue, expectedFalse) => {+ const targetType = queryResultTransferTargetType("boolean", databaseType);+ expect(queryResultTransferSqlLiteral("true", databaseType, "boolean", targetType)).toBe(expectedTrue);+ expect(queryResultTransferSqlLiteral(false, databaseType, "boolean", targetType)).toBe(expectedFalse);+ });++ it("keeps exact numeric strings unquoted", () => {+ expect(queryResultTransferSqlLiteral("900719925474099312345", "postgres", "numeric", "NUMERIC")).toBe("900719925474099312345");+ expect(queryResultTransferSqlLiteral("12.3400", "oracle", "decimal", "NUMBER(10,4)")).toBe("12.3400");+ });++ it("preserves native boolean values even when metadata is absent", () => {+ expect(queryResultTransferSqlLiteral(true, "sqlite")).toBe("1");+ expect(queryResultTransferSqlLiteral(false, "postgres")).toBe("FALSE");+ });++ it.each(["postgres", "kingbase", "highgo", "vastbase", "gaussdb", "kwdb", "opengauss"] as const)("quotes %s backslashes and control characters independently of session string settings", (databaseType) => {+ expect(queryResultTransferSqlLiteral("C:\\new\\files\\'quote", databaseType, "text")).toBe("E'C:\\\\new\\\\files\\\\''quote'");+ expect(queryResultTransferSqlLiteral("line\n\t\r\x08\x0c\x01\x7f", databaseType, "text")).toBe("E'line\\x0a\\x09\\x0d\\x08\\x0c\\x01\\x7f'");+ expect(queryResultTransferSqlLiteral("O'Brien", databaseType, "text")).toBe("'O''Brien'");+ expect(queryResultTransferSqlLiteral("nul\0value", databaseType, "text")).toBeUndefined();+ });++ it("does not map exact decimals to floating point or an implicit zero scale", () => {+ expect(queryResultTransferTargetType("decimal(38,18)", "sqlserver", "mysql")).toBe("DECIMAL(38,18)");+ expect(queryResultTransferTargetType("decimal(65,30)", "postgres", "mysql")).toBe("NUMERIC");+ expect(queryResultTransferTargetType("numeric(65,30)", "oracle", "postgres")).toBe("CLOB");+ expect(queryResultTransferTargetType("decimal", "mysql", "mysql")).toBe("LONGTEXT");+ expect(queryResultTransferTargetType("numeric", "sqlite", "postgres")).toBe("TEXT");+ expect(queryResultTransferSqlLiteral("900719925474099312345.123456789", "sqlite", "numeric", "TEXT", "postgres")).toBe("'900719925474099312345.123456789'");+ expect(queryResultTransferSqlLiteral(Number("9007199254740993"), "postgres", "bigint")).toBeUndefined();+ });++ it("keeps PostgreSQL int8 and MySQL unsigned result metadata within range", () => {+ expect(queryResultTransferTargetType("int8", "mysql", "postgres")).toBe("BIGINT");+ expect(queryResultTransferTargetType("bigint", "mysql", "mysql")).toBe("DECIMAL(20,0)");+ expect(queryResultTransferTargetType("bigint unsigned", "postgres", "mysql")).toBe("DECIMAL(20,0)");+ expect(queryResultTransferTargetType("bigint", "sqlite", "mysql")).toBe("TEXT");+ expect(queryResultTransferSqlLiteral("18446744073709551615", "sqlite", "bigint", "TEXT", "mysql")).toBe("'18446744073709551615'");+ });++ it("preserves MySQL precision and lengths that native result headers omit", () => {+ expect(queryResultTransferTargetType("datetime", "mysql", "mysql")).toBe("datetime(6)");+ expect(queryResultTransferTargetType("time", "mysql", "mysql")).toBe("time(6)");+ expect(queryResultTransferTargetType("varchar", "mysql", "mysql")).toBe("LONGTEXT");+ expect(queryResultTransferTargetType("varbinary", "mysql", "mysql")).toBe("LONGBLOB");+ expect(queryResultTransferTargetType("bit", "mysql", "mysql")).toBe("BIT(64)");+ });++ it("widens bare character and binary metadata without using dialect default lengths", () => {+ expect(queryResultTransferTargetType("VARCHAR2", "oracle", "oracle")).toBe("CLOB");+ expect(queryResultTransferTargetType("NVARCHAR2", "oracle", "oracle")).toBe("NCLOB");+ expect(queryResultTransferTargetType("RAW", "oracle", "oracle")).toBe("BLOB");+ expect(queryResultTransferTargetType("NVARCHAR", "sqlserver", "sqlserver")).toBe("nvarchar(max)");+ expect(queryResultTransferTargetType("CHAR", "sqlserver", "sqlserver")).toBe("nvarchar(max)");+ expect(queryResultTransferTargetType("VARBINARY", "sqlserver", "sqlserver")).toBe("varbinary(max)");+ expect(queryResultTransferTargetType("NVARCHAR(32)", "sqlserver", "sqlserver")).toBe("NVARCHAR(32)");+ expect(queryResultTransferTargetType("VARCHAR", "h2", "h2")).toBe("CLOB");+ });++ it.each(["BINARY VARYING", "BINARY LARGE OBJECT", "VARBINARY", "BLOB"])("preserves H2 bytes reported as %s", (sourceType) => {+ expect(queryResultTransferIsBinaryColumnType(sourceType, "h2")).toBe(true);+ expect(queryResultTransferTargetType(sourceType, "h2", "h2").toUpperCase()).toBe("BLOB");+ // The original wire name also becomes the target type when source DDL is reused.+ expect(queryResultTransferSqlLiteral("0x00ff", "h2", sourceType, sourceType, "h2")).toBe("X'00ff'");+ expect(queryResultTransferSqlLiteral("0x", "h2", sourceType, sourceType, "h2")).toBe("X''");+ expect(queryResultTransferTargetType(sourceType, "postgres", "h2")).toBe("bytea");+ expect(queryResultTransferSqlLiteral("0x00ff", "postgres", sourceType, "bytea", "h2")).toBe("decode('00ff', 'hex')");+ });++ it("marks H2 JSON payloads as JSON instead of converting them to JSON strings", () => {+ expect(queryResultTransferTargetType("JSON", "h2", "h2")).toBe("JSON");+ for (const payload of ['{"a":1}', "[1,2]", '"hello"', "true", "123", "null"]) {+ expect(queryResultTransferSqlLiteral(payload, "h2", "JSON", undefined, "h2")).toBe(`JSON '${payload}'`);+ }+ expect(queryResultTransferSqlLiteral('{"path":"C:\\\\o\'clock"}', "h2", "JSON", "JSON", "h2")).toBe("JSON '{\"path\":\"C:\\\\o''clock\"}'");+ expect(queryResultTransferSqlLiteral(null, "h2", "JSON", "JSON", "h2")).toBe("NULL");+ // Existing H2 JSON columns may receive structured values from another source.+ expect(queryResultTransferSqlLiteral({ a: 1 }, "h2", "jsonb", "JSON", "postgres")).toBe("JSON '{\"a\":1}'");+ expect(queryResultTransferSqlLiteral([1, 2], "h2", "_int4", "JSON", "postgres")).toBe("JSON '[1,2]'");+ });++ it.each(["TIME", "TIMESTAMP", "TIME WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITHOUT TIME ZONE"])("preserves H2 fractional precision omitted from %s result metadata", (sourceType) => {+ const targetType = sourceType.replace(/^(TIME|TIMESTAMP)\b/, "$1(9)").toLowerCase();+ expect(queryResultTransferTargetType(sourceType, "h2", "h2")).toBe(targetType);+ });++ it("retains explicit H2 temporal precision and accepts other sources at full precision", () => {+ expect(queryResultTransferTargetType("TIMESTAMP(3)", "h2", "h2")).toBe("TIMESTAMP(3)");+ expect(queryResultTransferTargetType("TIMESTAMP(9)", "h2", "oracle")).toBe("TIMESTAMP(9)");+ expect(queryResultTransferTargetType("datetime2", "h2", "sqlserver")).toBe("TIMESTAMP(9)");+ });++ it.each([+ ["TIMESTAMP", "h2"],+ ["TIMESTAMP", "oracle"],+ ["TimeStampDTY", "oracle"],+ ["datetime2", "sqlserver"],+ ] as const)("preserves possible precision in %s from %s when a destination stops at microseconds", (sourceType, sourceDatabaseType) => {+ const value = sourceDatabaseType === "sqlserver" ? "2026-10-07 12:34:56.1234567" : "2026-10-07 12:34:56.123456789";+ expect(queryResultTransferTargetType(sourceType, "postgres", sourceDatabaseType)).toBe("TEXT");+ expect(queryResultTransferTargetType(sourceType, "mysql", sourceDatabaseType)).toBe("LONGTEXT");+ expect(queryResultTransferSqlLiteral(value, "postgres", sourceType, undefined, sourceDatabaseType)).toBe(`'${value}'`);+ expect(queryResultTransferSqlLiteral(value, "mysql", sourceType, undefined, sourceDatabaseType)).toBe(`CONVERT(X'${Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("")}' USING utf8mb4)`);+ });++ it("uses temporal target columns only when their precision can retain the source", () => {+ expect(queryResultTransferTargetType("TIMESTAMP", "sqlserver", "h2")).toBe("nvarchar(max)");+ expect(queryResultTransferTargetType("TIMESTAMP(6)", "postgres", "oracle")).toBe("TIMESTAMP");+ expect(queryResultTransferTargetType("TIMESTAMP(6)", "mysql", "oracle")).toBe("DATETIME(6)");+ expect(queryResultTransferTargetType("TIMESTAMP(7)", "sqlserver", "oracle")).toBe("datetime2(7)");+ expect(queryResultTransferTargetType("TIMESTAMP", "db2", "h2")).toBe("TIMESTAMP(9)");+ expect(queryResultTransferTargetType("TIMESTAMP", "db2", "db2")).toBe("TIMESTAMP(12)");+ expect(queryResultTransferTargetType("TIMESTAMP(12)", "h2", "db2")).toBe("CLOB");+ });++ it.each([+ ["postgres", "TIMESTAMP(6)"],+ ["mysql", "DATETIME(6)"],+ ["sqlserver", "datetime2(6)"],+ ["h2", "TIMESTAMP(6)"],+ ["oracle", "TIMESTAMP(6)"],+ ["db2", "TIMESTAMP(6)"],+ ] as const)("rejects nonzero fractional digits beyond the explicit %s target precision", (databaseType, targetType) => {+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.123456789", databaseType, "TIMESTAMP", targetType, "h2")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.123456000", databaseType, "TIMESTAMP", targetType, "h2")).not.toBeUndefined();+ });++ it("checks known target limits without confusing bare result headers with default declaration precision", () => {+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.1234567", "postgres", "datetime2", "timestamp", "sqlserver")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.12345678", "sqlserver", "TIMESTAMP", "datetime2", "h2")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("12:34:56.1234567+08:00", "h2", "TIME WITH TIME ZONE", "TIME(6) WITH TIME ZONE", "h2")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("12:34:56.000000001", "mysql", "time", "TIME(0)", "mysql")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("-12:34:56.000000001", "mysql", "time", "TIME(0)", "mysql")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.123456789", "h2", "TIMESTAMP", "TIMESTAMP", "h2")).not.toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07T12:34:56.123456789", "oracle", "TIMESTAMP", "TIMESTAMP", "oracle")).not.toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.123456", "mysql", "datetime", "datetime", "mysql")).not.toBeUndefined();+ });++ it("preserves SQL Server datetime tick values without rounding exact timestamps from another source", () => {+ for (const fraction of ["001", "002", "003", "007", "897"]) {+ expect(queryResultTransferSqlLiteral(`2026-10-07 12:34:56.${fraction}`, "sqlserver", "TIMESTAMP(3)", "datetime", "h2")).toBeUndefined();+ }+ for (const fraction of ["000", "010", "020", "100", "990"]) {+ expect(queryResultTransferSqlLiteral(`2026-10-07 12:34:56.${fraction}`, "sqlserver", "TIMESTAMP(3)", "datetime", "h2")).not.toBeUndefined();+ }+ for (const sourceType of ["datetime", "datetimen"]) {+ for (const fraction of ["000", "003", "007", "897"]) {+ expect(queryResultTransferSqlLiteral(`2026-10-07 12:34:56.${fraction}`, "sqlserver", sourceType, "datetime", "sqlserver")).not.toBeUndefined();+ }+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.001", "sqlserver", sourceType, "datetime", "sqlserver")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.896666666", "sqlserver", sourceType, "datetime", "sqlserver")).toBeUndefined();+ }+ // The native driver publishes 3-digit canonical display text, not raw ticks.+ expect(queryResultTransferTargetType("datetime", "postgres", "sqlserver")).toBe("TIMESTAMP");+ expect(queryResultTransferSqlLiteral("2026-06-29 10:11:12.897", "postgres", "datetime", undefined, "sqlserver")).toBe("'2026-06-29 10:11:12.897'");+ });++ it("rejects clock fields that DATE and SMALLDATETIME would discard", () => {+ for (const databaseType of ["postgres", "mysql", "sqlserver", "h2", "db2"] as const) {+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56", databaseType, "TIMESTAMP", "DATE", "h2")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 00:00:00.000", databaseType, "TIMESTAMP", "DATE", "h2")).not.toBeUndefined();+ }+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:01", "sqlserver", "datetime2", "smalldatetime", "sqlserver")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:00.001", "sqlserver", "datetime2", "smalldatetime", "sqlserver")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:00.000", "sqlserver", "datetime2", "smalldatetime", "sqlserver")).not.toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56", "oracle", "TIMESTAMP", "DATE", "oracle")).toBe("TO_DATE('2026-10-07 12:34:56', 'YYYY-MM-DD HH24:MI:SS')");+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56", "sqlite", "TEXT", "DATE", "sqlite")).toBe("'2026-10-07 12:34:56'");+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56.123456789", "sqlite", "TEXT", "DATE", "sqlite")).toBe("'2026-10-07 12:34:56.123456789'");+ });++ it("normalizes SQL Server TDS type names into usable target SQL types", () => {+ expect(queryResultTransferTargetType("intn", "sqlserver", "sqlserver")).toBe("bigint");+ expect(queryResultTransferTargetType("numericn", "sqlserver", "sqlserver")).toBe("nvarchar(max)");+ expect(queryResultTransferTargetType("datetimen", "sqlserver", "sqlserver")).toBe("datetime2(7)");+ expect(queryResultTransferTargetType("guid", "sqlserver", "sqlserver")).toBe("uniqueidentifier");+ expect(queryResultTransferTargetType("daten", "sqlserver", "sqlserver")).toBe("date");+ expect(queryResultTransferTargetType("timen", "sqlserver", "sqlserver")).toBe("time(7)");+ expect(queryResultTransferTargetType("datetimeoffsetn", "sqlserver", "sqlserver")).toBe("datetimeoffset(7)");+ expect(queryResultTransferSqlLiteral("9223372036854775807", "postgres", "intn", "BIGINT", "sqlserver")).toBe("9223372036854775807");+ expect(queryResultTransferSqlLiteral("1", "postgres", "bitn", "BOOLEAN", "sqlserver")).toBe("TRUE");+ });++ it("does not embed source type names as extra SQL statements", () => {+ expect(queryResultTransferTargetType("integer); DROP TABLE other_table; --", "postgres", "postgres")).toBe("TEXT");+ expect(queryResultTransferTargetType("_text[]); DROP TABLE other_table; --", "postgres", "postgres")).toBe("TEXT");+ expect(queryResultTransferTargetType('"Custom Type"', "postgres", "postgres")).toBe("TEXT");+ expect(queryResultTransferTargetType("integer DEFAULT dangerous_function()", "postgres", "postgres")).toBe("TEXT");+ expect(queryResultTransferTargetType("numeric DEFAULT dangerous_function()", "oracle", "oracle")).toBe("CLOB");+ expect(queryResultTransferTargetType("_integer DEFAULT dangerous_function()", "postgres", "postgres")).toBe("TEXT");+ expect(queryResultTransferTargetType("my_custom_type", "postgres", "postgres")).toBe("TEXT");+ expect(queryResultTransferSqlLiteral("FALSE", "postgres", "bool DEFAULT dangerous_function()", undefined, "postgres")).toBe("'FALSE'");+ expect(queryResultTransferSqlLiteral("not hex", "postgres", "blob DEFAULT dangerous_function()", undefined, "postgres")).toBe("'not hex'");+ expect(queryResultTransferSqlLiteral(["a", "b"], "postgres", "_my_custom_type", undefined, "postgres")).toBe('\'["a","b"]\'');+ expect(queryResultTransferTargetType("TIMESTAMP(6) WITH TIME ZONE", "oracle", "oracle")).toBe("TIMESTAMP(6) WITH TIME ZONE");+ expect(queryResultTransferTargetType("NUMBER(38, 6)", "oracle", "oracle")).toBe("number(38, 6)");+ });++ it("emits typed PostgreSQL arrays, including empty, nested and binary arrays", () => {+ expect(queryResultTransferTargetType("_int8", "postgres", "postgres")).toBe("int8[]");+ expect(queryResultTransferSqlLiteral(["9223372036854775807", null], "postgres", "_int8", "int8[]", "postgres")).toBe("ARRAY[9223372036854775807, NULL]::int8[]");+ expect(queryResultTransferSqlLiteral(["9223372036854775807", null], "postgres", "_int8", "_int8", "postgres")).toBe("ARRAY[9223372036854775807, NULL]::int8[]");+ expect(queryResultTransferSqlLiteral([], "postgres", "_text", "text[]", "postgres")).toBe("ARRAY[]::text[]");+ expect(+ queryResultTransferSqlLiteral(+ [+ [1, 2],+ [3, 4],+ ],+ "postgres",+ "_int4",+ "int4[]",+ "postgres",+ ),+ ).toBe("ARRAY[ARRAY[1, 2]::int4[], ARRAY[3, 4]::int4[]]::int4[]");+ expect(queryResultTransferSqlLiteral(["0x00ff"], "postgres", "_bytea", "bytea[]", "postgres")).toBe("ARRAY[decode('00ff', 'hex')]::bytea[]");+ expect(queryResultTransferSqlLiteral(["C:\\test"], "postgres", "_text", "text[]", "postgres")).toBe("ARRAY[E'C:\\\\test']::text[]");+ expect(queryResultTransferTargetType("int4[]", "sqlite", "postgres")).toBe("TEXT");+ expect(queryResultTransferSqlLiteral([1, null, 2], "sqlite", "int4[]", "TEXT", "postgres")).toBe("'[1,null,2]'");+ });++ it("preserves bit strings without interpreting them as text bytes or boolean truthiness", () => {+ expect(queryResultTransferSqlLiteral("00100101", "mysql", "bit", "BIT(64)", "mysql")).toBe("B'00100101'");+ expect(queryResultTransferSqlLiteral("00100101", "postgres", "bit", "BIT VARYING", "mysql")).toBe("B'00100101'");+ expect(queryResultTransferSqlLiteral("00100101", "sqlite", "bit", "TEXT", "mysql")).toBe("'00100101'");+ expect(queryResultTransferSqlLiteral("not-bits", "mysql", "bit", "BIT(64)", "mysql")).toBeUndefined();+ expect(queryResultTransferSqlLiteral(true, "postgres", "bit", "BOOLEAN", "sqlserver")).toBe("TRUE");+ });++ it("uses NLS-independent Oracle date and timestamp literals", () => {+ expect(queryResultTransferSqlLiteral("2026-10-07", "oracle", "DATE", "DATE", "oracle")).toBe("DATE '2026-10-07'");+ expect(queryResultTransferSqlLiteral("2026-10-07 12:34:56", "oracle", "DATE", "DATE", "oracle")).toBe("TO_DATE('2026-10-07 12:34:56', 'YYYY-MM-DD HH24:MI:SS')");+ expect(queryResultTransferSqlLiteral("2026-10-07T12:34:56.123456789", "oracle", "TIMESTAMP(9)", "TIMESTAMP(9)", "oracle")).toBe("TO_TIMESTAMP('2026-10-07 12:34:56.123456789', 'YYYY-MM-DD HH24:MI:SS.FF')");+ expect(queryResultTransferSqlLiteral("2026-10-07T12:34:56.123Z", "oracle", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE", "oracle")).toBe("TO_TIMESTAMP_TZ('2026-10-07 12:34:56.123 +00:00', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')");+ expect(queryResultTransferSqlLiteral("07-OCT-26", "oracle", "DATE", "DATE", "oracle")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("2026-10-07T12:34:56.123", "oracle", "DATE", "DATE", "oracle")).toBeUndefined();+ expect(queryResultTransferTargetType("DATE", "postgres", "oracle")).toBe("TIMESTAMP");+ expect(queryResultTransferTargetType("TIMESTAMP WITH TIME ZONE", "mysql", "oracle")).toBe("LONGTEXT");+ expect(queryResultTransferTargetType("time", "oracle", "mysql")).toBe("CLOB");+ });++ it("normalizes Oracle-go wire timestamp names for reused DDL and generic targets", () => {+ expect(queryResultTransferTargetType("TimeStampDTY", "oracle", "oracle")).toBe("TIMESTAMP(9)");+ expect(queryResultTransferTargetType("TimeStampTZ_DTY", "oracle", "oracle")).toBe("TIMESTAMP(9) WITH TIME ZONE");+ expect(queryResultTransferTargetType("TIMESTAMP", "oracle", "oracle")).toBe("TIMESTAMP(9)");+ expect(queryResultTransferTargetType("TIMESTAMP WITH LOCAL TIME ZONE", "oracle", "oracle")).toBe("TIMESTAMP(9) with local time zone");+ expect(queryResultTransferSqlLiteral("2026-10-07T12:34:56.123456789", "oracle", "TimeStampDTY", "TimeStampDTY", "oracle")).toBe("TO_TIMESTAMP('2026-10-07 12:34:56.123456789', 'YYYY-MM-DD HH24:MI:SS.FF')");+ expect(queryResultTransferSqlLiteral("2026-10-07T12:34:56.123456789+08:00", "oracle", "TimeStampTZ_DTY", "TimeStampTZ_DTY", "oracle")).toBe("TO_TIMESTAMP_TZ('2026-10-07 12:34:56.123456789 +08:00', 'YYYY-MM-DD HH24:MI:SS.FF TZH:TZM')");+ expect(queryResultTransferTargetType("TimeStampDTY", "h2", "oracle")).toBe("TIMESTAMP(9)");+ expect(queryResultTransferTargetType("TimeStampTZ_DTY", "mysql", "oracle")).toBe("LONGTEXT");+ });++ it("preserves an empty Oracle BLOB rather than converting it to NULL", () => {+ expect(queryResultTransferSqlLiteral("0x", "oracle", "BLOB", "BLOB", "oracle")).toBe("EMPTY_BLOB()");+ expect(queryResultTransferSqlLiteral("0x", "oracle", "RAW", "RAW", "oracle")).toBeUndefined();+ });++ it("preserves empty Oracle CLOBs and rejects strings that VARCHAR2 would turn into NULL", () => {+ expect(queryResultTransferSqlLiteral("", "oracle", "text", "CLOB", "postgres")).toBe("EMPTY_CLOB()");+ expect(queryResultTransferSqlLiteral("", "oracle", "nvarchar", "NCLOB", "sqlserver")).toBe("EMPTY_CLOB()");+ expect(queryResultTransferSqlLiteral("", "oracle", "text", "VARCHAR2(4000)", "postgres")).toBeUndefined();+ expect(queryResultTransferSqlLiteral(null, "oracle", "text", "CLOB", "postgres")).toBe("NULL");+ });++ it.each(["CLOB", "NCLOB"])("chunks large Oracle %s text without breaking characters or escaping", (targetType) => {+ const value = "😀中文'\\ ".repeat(600);+ const literal = queryResultTransferSqlLiteral(value, "oracle", "text", targetType, "postgres")!;+ const constructor = targetType === "NCLOB" ? "TO_NCLOB" : "TO_CLOB";+ const chunks = [...literal.matchAll(new RegExp(`${constructor}\\('((?:''|[^'])*)'\\)`, "g"))].map((match) => match[1]!);+ expect(chunks.length).toBeGreaterThan(1);+ expect(chunks.every((chunk) => new TextEncoder().encode(chunk).length <= 3900)).toBe(true);+ expect(chunks.map((chunk) => chunk.replaceAll("''", "'")).join("")).toBe(value);+ expect(literal).toBe(chunks.map((chunk) => `${constructor}('${chunk}')`).join(" || "));+ });++ it("keeps the Oracle literal boundary explicit for non-LOB and unverified compatible drivers", () => {+ expect(queryResultTransferSqlLiteral("x".repeat(4000), "oracle", "text", "CLOB", "postgres")).toBe(`'${"x".repeat(4000)}'`);+ expect(queryResultTransferSqlLiteral("x".repeat(4001), "oracle", "text", "CLOB", "postgres")).toContain("TO_CLOB(");+ expect(queryResultTransferSqlLiteral("x".repeat(4001), "oceanbase-oracle", "text", "CLOB", "postgres")).toContain("TO_CLOB(");+ expect(queryResultTransferSqlLiteral("x".repeat(4001), "oracle", "text", "VARCHAR2(5000)", "postgres")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("x".repeat(4001), "dameng", "text", "CLOB", "postgres")).toBeUndefined();+ expect(queryResultTransferSqlLiteral("x".repeat(4001), "yashandb", "text", "CLOB", "postgres")).toBeUndefined();+ });+});diff --git a/apps/desktop/src/components/transfer/queryResultTransfer.ts b/apps/desktop/src/components/transfer/queryResultTransfer.tsnew file mode 100644index 0000000000..8661e14993--- /dev/null+++ b/apps/desktop/src/components/transfer/queryResultTransfer.ts@@ -0,0 +1,73 @@+import { supportsTransfer } from "@/lib/database/databaseFeatureSupport";+import { parseBinaryCellBytes } from "@/lib/dataGrid/binaryCellDownload";+import { effectiveDatabaseTypeForConnection, transferDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";+import type { ConnectionConfig, DatabaseType, QueryResult } from "@/types/database";+export { alwaysIdentityColumnNamesFromDdl, identityColumnNamesFromDdl, nonInsertableColumnNamesFromDdl, rewriteCreateTableName, transactionalMysqlTableDdl } from "./queryResultTransferDdl";++// MongoDB's transfer capability uses document writes, not SQL transactions.+export function queryResultTransferDatabaseType(connection?: Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "connection_string" | "url_params" | "jdbc_driver_class" | "jdbc_driver_paths" | "database_info" | "external_config" | "username">): DatabaseType | undefined {+ const effective = effectiveDatabaseTypeForConnection(connection);+ if (effective === "doris" || effective === "starrocks") return undefined;+ const type = transferDatabaseTypeForConnection(connection);+ return type && supportsQueryResultTransferDatabaseType(type) ? type : undefined;+}++// An agent runtime alone does not imply transactions (for example Hive/Spark+// reject them and ArgoDB auto-commits). Keep this list tied to implemented+// transaction paths, not the broader table-transfer feature flag.+const TRANSACTIONAL_TRANSFER_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlite", "sqlserver", "oracle", "oceanbase-oracle", "dameng", "yashandb", "kingbase", "highgo", "vastbase", "h2", "db2", "iris", "goldendb"]);++/** executeInTransaction has a SQL batch transaction path for these engines. */+export function supportsQueryResultTransferDatabaseType(type?: DatabaseType): boolean {+ return !!type && supportsTransfer(type) && TRANSACTIONAL_TRANSFER_TYPES.has(type);+}++export function supportsQueryResultTransfer(connection?: Parameters<typeof queryResultTransferDatabaseType>[0]): boolean {+ return queryResultTransferDatabaseType(connection) !== undefined;+}++export function queryResultTransferIncomplete(result: QueryResult, rowLimit?: number): boolean {+ return result.truncated === true || result.has_more === true || (rowLimit !== undefined && result.rows.length > rowLimit);+}++export function normalizeQueryResultColumnType(sourceType: string, databaseType: DatabaseType): string {+ const type = sourceType.trim();+ if (databaseType === "mysql" && /^varchar$/i.test(type)) return "VARCHAR(255)";+ if (databaseType === "mysql" && /^varbinary$/i.test(type)) return "VARBINARY(255)";+ if (databaseType === "mysql" && /^(enum|set)$/i.test(type)) return "TEXT";+ return type;+}++/** Return the original bytes represented by a query-result binary value. */+export function binaryQueryResultValueHex(value: unknown): string {+ const parsed = parseBinaryCellBytes(value, "binary");+ if (parsed) return Array.from(parsed, (byte) => byte.toString(16).padStart(2, "0")).join("");+ if (typeof value === "string") {+ return Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("");+ }+ if (value instanceof ArrayBuffer) return Array.from(new Uint8Array(value), (byte) => byte.toString(16).padStart(2, "0")).join("");+ if (ArrayBuffer.isView(value)) {+ const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");+ }+ return Array.from(new TextEncoder().encode(typeof value === "object" ? JSON.stringify(value) : String(value)), (byte) => byte.toString(16).padStart(2, "0")).join("");+}++/** Build the idempotent cleanup statement for a transfer staging table. */+export function queryResultTransferStagingCleanupSql(table: string): string {+ return `DROP TABLE IF EXISTS ${table}`;+}++const ORACLE_STYLE_CLEANUP_TYPES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "dameng", "yashandb"]);+const NON_TRANSACTIONAL_DDL_TYPES = new Set<DatabaseType>([...ORACLE_STYLE_CLEANUP_TYPES, "mysql", "goldendb", "h2"]);++export function queryResultTransferNeedsCreateCleanup(databaseType: DatabaseType): boolean {+ return NON_TRANSACTIONAL_DDL_TYPES.has(databaseType);+}++/** Remove a newly created target after an agent-backed non-transactional DDL failure. */+export function queryResultTransferCreateCleanupSql(table: string, databaseType: DatabaseType): string {+ if (!ORACLE_STYLE_CLEANUP_TYPES.has(databaseType)) return queryResultTransferStagingCleanupSql(table);+ const escapedTable = table.replaceAll("'", "''");+ return `BEGIN EXECUTE IMMEDIATE 'DROP TABLE ${escapedTable} CASCADE CONSTRAINTS'; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN RAISE; END IF; END;`;+}diff --git a/apps/desktop/src/components/transfer/queryResultTransferDdl.ts b/apps/desktop/src/components/transfer/queryResultTransferDdl.tsnew file mode 100644index 0000000000..3fb23c061b--- /dev/null+++ b/apps/desktop/src/components/transfer/queryResultTransferDdl.ts@@ -0,0 +1,420 @@+import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";+import { sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";+import { tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";+import type { SqlSemanticToken } from "@/lib/sql/semantic/types";+import type { DatabaseType } from "@/types/database";++function isMysqlDdl(databaseType: DatabaseType): boolean {+ return databaseType === "mysql" || databaseType === "goldendb";+}++function tokensForDdl(sql: string, databaseType: DatabaseType): SqlSemanticToken[] {+ const dialect = isMysqlDdl(databaseType) ? "mysql" : sqlFormatDialectForDbType(databaseType);+ return tokenizeSqlSemantic(sql, dialect, { mysqlBackslashEscape: dialect === "mysql", mysqlDashCommentRequiresWhitespace: dialect === "mysql" }).filter((token) => token.kind !== "comment");+}++function identifier(token?: SqlSemanticToken): string | undefined {+ if (token?.kind === "word") return token.text;+ if (token?.kind === "quoted_identifier") return unquoteSqlSemanticIdentifier(token);+ return undefined;+}++function word(token: SqlSemanticToken | undefined, value: string): boolean {+ return token?.kind === "word" && token.normalized === value;+}++function readName(tokens: SqlSemanticToken[], start: number): SqlSemanticToken[] {+ if (identifier(tokens[start]) === undefined) return [];+ const parts = [tokens[start]!];+ for (let index = start + 1; tokens[index]?.text === "." && identifier(tokens[index + 1]) !== undefined; index += 2) parts.push(tokens[index + 1]!);+ return parts;+}++/** Check the actual MySQL table option, never ENGINE-like text in a comment or column. */+export function transactionalMysqlTableDdl(ddl: string): boolean {+ for (const range of splitSqlStatementRanges(ddl, "mysql")) {+ const tokens = tokensForDdl(range.sql, "mysql");+ if (!word(tokens[0], "create") || tokens.some((token) => token.closed === false)) continue;+ const table = tokens.findIndex((token) => word(token, "table") && token.depth === 0);+ const close = tokens.findIndex((token, index) => index > table && token.text === ")" && token.depth === 0);+ if (table < 0 || close < 0) continue;+ const engines: string[] = [];+ for (let index = close + 1; index < tokens.length; index += 1) {+ if (tokens[index]!.depth !== 0 || !word(tokens[index], "engine")) continue;+ let value = index + 1;+ if (tokens[value]?.text === "=") value += 1;+ const token = tokens[value];+ const name = token?.kind === "string" ? token.text.slice(1, -1).replaceAll("''", "'") : identifier(token);+ if (!name) return false;+ engines.push(name.toLowerCase());+ }+ return engines.length === 1 && engines[0] === "innodb";+ }+ return false;+}++function columnDefinitions(ddl: string, databaseType: DatabaseType): SqlSemanticToken[][] {+ const definitions: SqlSemanticToken[][] = [];+ const constraints = new Set(["primary", "key", "unique", "constraint", "check", "foreign", "index", "fulltext", "spatial", "period"]);+ for (const range of splitSqlStatementRanges(ddl, databaseType)) {+ const tokens = tokensForDdl(range.sql, databaseType);+ if (!word(tokens[0], "create")) continue;+ const tableIndex = tokens.findIndex((token) => word(token, "table") && token.depth === 0);+ if (tableIndex < 0) continue;+ const openIndex = tokens.findIndex((token, index) => index > tableIndex && token.text === "(" && token.depth === 0);+ if (openIndex < 0) continue;+ let start = openIndex + 1;+ for (let index = start; index < tokens.length; index += 1) {+ const token = tokens[index]!;+ const end = token.text === ")" && token.depth === 0;+ if (!end && !(token.text === "," && token.depth === 1)) continue;+ const definition = tokens.slice(start, index);+ const first = definition[0];+ if (identifier(first) !== undefined && !(first?.kind === "word" && constraints.has(first.normalized))) definitions.push(definition);+ if (end) break;+ start = index + 1;+ }+ }+ return definitions;+}++function definitionWords(definition: SqlSemanticToken[]): string[] {+ // An AS inside DEFAULT CAST(...) is not a computed-column declaration.+ return definition+ .slice(1)+ .filter((token) => token.depth === 1 && token.kind === "word")+ .map((token) => token.normalized);+}++/** A DDL declaration carries the target precision that result/column metadata can omit. */+export function temporalColumnTypesFromDdl(ddl: string, databaseType: DatabaseType): Map<string, string | null> {+ const types = new Map<string, string | null>();+ // SQLite does not enforce temporal precision in a column declaration.+ if (databaseType === "sqlite") return types;+ const temporalNames = new Set(["date", "time", "timetz", "timestamp", "timestamptz", "datetime", "datetime2", "datetimeoffset", "smalldatetime"]);+ for (const definition of columnDefinitions(ddl, databaseType)) {+ const name = identifier(definition[0])!;+ const typeToken = definition[1];+ const base = identifier(typeToken)?.toLowerCase();+ if (!base || !temporalNames.has(base) || (typeToken?.kind !== "word" && databaseType !== "sqlserver") || definition[2]?.text === ".") continue;+ if (databaseType === "sqlserver" && base === "timestamp") continue; // rowversion+ let index = 2;+ let precision: number | undefined;+ if (definition[index]?.text === "(") {+ if (!/^\d+$/.test(definition[index + 1]?.text ?? "") || definition[index + 2]?.text !== ")") {+ types.set(name, null);+ continue;+ }+ precision = Number(definition[index + 1]!.text);+ index += 3;+ }+ let zone = "";+ if (word(definition[index], "with") || word(definition[index], "without")) {+ const start = index++;+ if (word(definition[index], "local")) index += 1;+ if (!word(definition[index], "time") || !word(definition[index + 1], "zone")) {+ types.set(name, null);+ continue;+ }+ index += 2;+ zone =+ " " ++ definition+ .slice(start, index)+ .map((token) => token.text.toUpperCase())+ .join(" ");+ }+ // Preserve the array type for the array serializer instead of replacing it with a scalar.+ if (definition[index]?.text.startsWith("[") || word(definition[index], "array")) continue;+ if (["date", "smalldatetime"].includes(base) || (databaseType === "sqlserver" && base === "datetime")) {+ types.set(name, base.toUpperCase());+ continue;+ }+ if (precision === undefined) {+ if (isMysqlDdl(databaseType)) precision = 0;+ else if (["postgres", "kingbase", "highgo", "vastbase"].includes(databaseType)) precision = 6;+ else if (databaseType === "sqlserver" && ["time", "datetime2", "datetimeoffset"].includes(base)) precision = 7;+ else if (databaseType === "h2") precision = base === "time" ? 0 : base === "timestamp" || base === "datetime" ? 6 : undefined;+ else if (["oracle", "oceanbase-oracle", "db2"].includes(databaseType) && base === "timestamp") precision = 6;+ }+ // Unknown defaults must not fall back to a wire type's maximum precision.+ types.set(name, precision === undefined ? null : `${base.toUpperCase()}(${precision})${zone}`);+ }+ return types;+}++/** Identity columns are writable when the caller enables the dialect's override. */+export function nonInsertableColumnNamesFromDdl(ddl: string, databaseType: DatabaseType): Set<string> {+ return new Set(+ columnDefinitions(ddl, databaseType)+ .filter((definition) => {+ const words = definitionWords(definition);+ return (!words.includes("identity") && (words.includes("generated") || words.includes("as"))) || (databaseType === "sqlserver" && (words[0] === "rowversion" || words[0] === "timestamp"));+ })+ .map((definition) => identifier(definition[0])!),+ );+}++/** Includes PostgreSQL SERIAL, whose owned sequence also needs advancing after explicit inserts. */+export function identityColumnNamesFromDdl(ddl: string, databaseType: DatabaseType): Set<string> {+ return new Set(+ columnDefinitions(ddl, databaseType)+ .filter((definition) => {+ const words = definitionWords(definition);+ return words.includes("identity") || (sqlFormatDialectForDbType(databaseType) === "postgres" && ["serial", "smallserial", "bigserial", "serial2", "serial4", "serial8"].includes(words[0] ?? ""));+ })+ .map((definition) => identifier(definition[0])!),+ );+}++export function alwaysIdentityColumnNamesFromDdl(ddl: string, databaseType: DatabaseType): Set<string> {+ return new Set(+ columnDefinitions(ddl, databaseType)+ .filter((definition) => {+ const words = definitionWords(definition);+ return words.includes("identity") && words.includes("generated") && words.includes("always");+ })+ .map((definition) => identifier(definition[0])!),+ );+}++function quoteName(value: string, databaseType: DatabaseType): string {+ if (isMysqlDdl(databaseType)) return "`" + value.replaceAll("`", "``") + "`";+ if (databaseType === "sqlserver") return "[" + value.replaceAll("]", "]]") + "]";+ return '"' + value.replaceAll('"', '""') + '"';+}++/** Names scoped to a schema must not collide with the source table's objects. */+function copiedObjectName(target: string, original: string, databaseType: DatabaseType): string {+ const input = `${target}_${original}`;+ let hash = 2166136261;+ for (const char of input) hash = Math.imul(hash ^ char.codePointAt(0)!, 16777619);+ const suffix = `_dbx_${(hash >>> 0).toString(16).padStart(8, "0")}`;+ const limit = ["oracle", "oceanbase-oracle"].includes(databaseType) ? 30 : databaseType === "sqlserver" ? 128 : isMysqlDdl(databaseType) ? 64 : 63;+ let prefix = "";+ for (const char of input) {+ if (new TextEncoder().encode(prefix + char + suffix).length > limit) break;+ prefix += char;+ }+ return quoteName(prefix + suffix, databaseType);+}++/** Accept only the named description-property call emitted by our SQL Server DDL renderer. */+function sqlServerDescriptionParameters(tokens: SqlSemanticToken[]): Map<string, { value: string; tokens: SqlSemanticToken[] }> | undefined {+ const procedure = readName(tokens, 1);+ if (procedure.length !== 2 || identifier(procedure[0])?.toLowerCase() !== "sys" || identifier(procedure[1])?.toLowerCase() !== "sp_addextendedproperty") return undefined;+ const parameters = new Map<string, { value: string; tokens: SqlSemanticToken[] }>();+ for (let index = 4; index < tokens.length; ) {+ const name = tokens[index++];+ if (name?.kind !== "word" || !name.normalized.startsWith("@") || tokens[index++]?.text !== "=" || parameters.has(name.normalized)) return undefined;+ const valueTokens: SqlSemanticToken[] = [];+ if (word(tokens[index], "n")) valueTokens.push(tokens[index++]!);+ const value = tokens[index++];+ if (value?.kind !== "string" || value.quote !== "'") return undefined;+ valueTokens.push(value);+ parameters.set(name.normalized, { value: value.text.slice(1, -1).replaceAll("''", "'"), tokens: valueTokens });+ if (index < tokens.length && tokens[index++]?.text !== ",") return undefined;+ }+ const required = ["@name", "@value", "@level0type", "@level0name", "@level1type", "@level1name"];+ const hasColumn = parameters.has("@level2type") || parameters.has("@level2name");+ if (hasColumn) required.push("@level2type", "@level2name");+ if (parameters.size !== required.length || required.some((name) => !parameters.has(name))) return undefined;+ if (parameters.get("@name")!.value !== "MS_Description" || parameters.get("@level0type")!.value.toUpperCase() !== "SCHEMA" || parameters.get("@level1type")!.value.toUpperCase() !== "TABLE" || (hasColumn && parameters.get("@level2type")!.value.toUpperCase() !== "COLUMN")) return undefined;+ return parameters;+}++/**+ * Rewrite only grammar positions naming the table or its dependent objects.+ * Unknown statements are rejected: replaying a partially rewritten script can+ * otherwise alter the source table or quietly leave dependencies behind.+ */+export function rewriteCreateTableName(ddl: string, qualifiedTable: string, databaseType: DatabaseType = "mysql", sourceSchema?: string, sourceTable?: string): string | undefined {+ const ranges = splitSqlStatementRanges(ddl, databaseType);+ const targetParts = readName(tokensForDdl(qualifiedTable, databaseType), 0);+ const targetName = identifier(targetParts[targetParts.length - 1]);+ if (!targetName || !ranges.length) return undefined;+ const targetSchema =+ targetParts.length > 1+ ? targetParts+ .slice(0, -1)+ .map((token) => token.text)+ .join(".")+ : undefined;+ const replacements: Array<{ start: number; end: number; value: string }> = [];+ const objectNames = new Map<string, string>();+ let createCount = 0;+ let resolvedSource = sourceTable;+ let resolvedSchema = sourceSchema;+ const matchIdentifier = (token: SqlSemanticToken, value: string) => (token.kind === "quoted_identifier" ? identifier(token) === value : identifier(token)?.toLowerCase() === value.toLowerCase());+ const matchesSource = (parts: SqlSemanticToken[]) => parts.length > 0 && !!resolvedSource && matchIdentifier(parts[parts.length - 1]!, resolvedSource) && (parts.length < 2 || !resolvedSchema || matchIdentifier(parts[parts.length - 2]!, resolvedSchema));+ const renameObject = (token: SqlSemanticToken) => {+ const name = identifier(token)!;+ if (!objectNames.has(name)) objectNames.set(name, copiedObjectName(targetName, name, databaseType));+ return objectNames.get(name)!;+ };++ for (const range of ranges) {+ const tokens = tokensForDdl(range.sql, databaseType);+ if (!tokens.length) continue;+ if (tokens.some((token) => token.closed === false)) return undefined;+ const replace = (parts: SqlSemanticToken[], value: string) => replacements.push({ start: range.from + parts[0]!.span.start, end: range.from + parts[parts.length - 1]!.span.end, value });+ const tableAt = (start: number, column = false, value = qualifiedTable): boolean => {+ const parts = readName(tokens, start);+ const tableParts = column ? parts.slice(0, -1) : parts;+ if (!matchesSource(tableParts)) return false;+ replace(tableParts, value);+ return true;+ };+ let handlesTableDefinition = false;+ if (word(tokens[0], "create")) {+ let index = 1;+ while (tokens[index]?.kind === "word") {+ if (["temporary", "temp", "unlogged", "unique", "clustered", "nonclustered", "bitmap", ...(databaseType === "h2" ? ["memory", "cached", "hash", "spatial"] : [])].includes(tokens[index]!.normalized)) {+ index += 1;+ } else if (databaseType === "h2" && word(tokens[index], "nulls")) {+ // H2 SCRIPT emits NULLS DISTINCT even for an ordinary unique index.+ index += 1;+ if (word(tokens[index], "not") || word(tokens[index], "all")) index += 1;+ if (!word(tokens[index], "distinct")) return undefined;+ index += 1;+ } else break;+ }+ const kind = tokens[index++];+ if (word(tokens[index], "if") && word(tokens[index + 1], "not") && word(tokens[index + 2], "exists")) {+ // An existing object must fail CREATE, including a concurrent creator+ // racing the dialog's metadata check. Never insert into it silently.+ replace(tokens.slice(index, index + 3), "");+ index += 3;+ }+ if (word(kind, "table")) {+ const parts = readName(tokens, index);+ resolvedSource ??= identifier(parts[parts.length - 1]);+ resolvedSchema ??= parts.length > 1 ? identifier(parts[parts.length - 2]) : undefined;+ let definitionStart = index + parts.length * 2 - 1;+ // H2 SCRIPT places the table comment between its name and columns.+ if (databaseType === "h2" && word(tokens[definitionStart], "comment") && tokens[definitionStart + 1]?.kind === "string") definitionStart += 2;+ if (++createCount !== 1 || !tableAt(index) || tokens[definitionStart]?.text !== "(") return undefined;+ // A copied partition cannot safely keep a parent in another transfer.+ if (tokens.some((token, i) => token.depth === 0 && word(token, "partition") && word(tokens[i + 1], "of"))) return undefined;+ // PostgreSQL permits an explicit identity sequence name. Reusing it+ // can collide with the source sequence; this uncommon dependency needs+ // a sequence-aware schema transfer rather than partial DDL rewriting.+ if (tokens.some((token, i) => word(token, "sequence") && word(tokens[i + 1], "name"))) return undefined;+ if (tokens.some((token) => word(token, "system_versioning") || word(token, "history_table"))) return undefined;+ handlesTableDefinition = true;+ } else if (word(kind, "index")) {+ const parts = readName(tokens, index);+ const on = tokens.findIndex((token, i) => i > index && token.depth === 0 && word(token, "on"));+ const tableIndex = word(tokens[on + 1], "only") ? on + 2 : on + 1;+ const tableValue = databaseType === "sqlite" ? targetParts[targetParts.length - 1]!.text : qualifiedTable;+ if (!parts.length || on < 0 || !tableAt(tableIndex, false, tableValue)) return undefined;+ // MySQL/SQL Server indexes are table-scoped. PostgreSQL takes the+ // schema from ON; Oracle/SQLite permit an explicit index namespace.+ const renamed = isMysqlDdl(databaseType) || databaseType === "sqlserver" ? parts[parts.length - 1]!.text : renameObject(parts[parts.length - 1]!);+ const qualifyIndex = databaseType === "sqlite" || ["oracle", "oceanbase-oracle", "dameng", "yashandb"].includes(databaseType);+ replace(parts, qualifyIndex && targetSchema ? `${targetSchema}.${renamed}` : renamed);+ } else return undefined;+ } else if (word(tokens[0], "alter") && word(tokens[1], "table")) {+ let index = 2;+ if (word(tokens[index], "only")) index += 1;+ if (!tableAt(index)) return undefined;+ // Dependencies created by a separate source DDL are not copied here.+ if (tokens.some((token) => token.depth === 0 && (word(token, "attach") || word(token, "detach") || word(token, "rename")))) return undefined;+ handlesTableDefinition = true;+ } else if (word(tokens[0], "comment") && word(tokens[1], "on")) {+ if (word(tokens[2], "table") || word(tokens[2], "column")) {+ if (!tableAt(3, word(tokens[2], "column"))) return undefined;+ } else if (word(tokens[2], "constraint")) {+ if (identifier(tokens[3]) === undefined || !word(tokens[4], "on") || !tableAt(5)) return undefined;+ replace([tokens[3]!], renameObject(tokens[3]!));+ } else if (word(tokens[2], "index")) {+ const parts = readName(tokens, 3);+ const name = identifier(parts[parts.length - 1]);+ if (!name || !objectNames.has(name)) return undefined;+ replace(parts, `${targetSchema ? targetSchema + "." : ""}${objectNames.get(name)}`);+ } else return undefined;+ } else if (databaseType === "sqlserver" && (word(tokens[0], "exec") || word(tokens[0], "execute"))) {+ const parameters = sqlServerDescriptionParameters(tokens);+ if (!parameters || parameters.get("@level1name")!.value !== resolvedSource || (resolvedSchema && parameters.get("@level0name")!.value !== resolvedSchema)) return undefined;+ const stringLiteral = (value: string) => "N'" + value.replaceAll("'", "''") + "'";+ const tableParameter = parameters.get("@level1name")!;+ const schemaParameter = parameters.get("@level0name")!;+ if (targetSchema) {+ replace(tableParameter.tokens, stringLiteral(targetName));+ replace(schemaParameter.tokens, stringLiteral(identifier(targetParts[targetParts.length - 2])!));+ } else {+ // Default schemas are per user. Resolve the table just created on the+ // server rather than assuming dbo or reusing the source schema. The+ // dynamic batch keeps the local variable with EXEC in one statement.+ const edits = [+ { tokens: tableParameter.tokens, value: stringLiteral(targetName) },+ { tokens: schemaParameter.tokens, value: "@dbx_transfer_schema" },+ ].sort((left, right) => right.tokens[0]!.span.start - left.tokens[0]!.span.start);+ let propertySql = range.sql;+ for (const edit of edits) propertySql = propertySql.slice(0, edit.tokens[0]!.span.start) + edit.value + propertySql.slice(edit.tokens[edit.tokens.length - 1]!.span.end);+ const dynamicSql = `DECLARE @dbx_transfer_schema sysname = OBJECT_SCHEMA_NAME(OBJECT_ID(${stringLiteral(qualifiedTable)}, N'U'));\n${propertySql}`;+ replacements.push({ start: range.from, end: range.from + range.sql.length, value: `EXEC(${stringLiteral(dynamicSql)})` });+ }+ } else return undefined;++ if (handlesTableDefinition) {+ for (let index = 0; index < tokens.length; index += 1) {+ const token = tokens[index]!;+ if (word(token, "references")) {+ const parts = readName(tokens, index + 1);+ if (matchesSource(parts)) replace(parts, databaseType === "sqlite" ? targetParts[targetParts.length - 1]!.text : qualifiedTable);+ }+ if (word(token, "constraint") && identifier(tokens[index + 1]) !== undefined) {+ const parts = readName(tokens, index + 1);+ const renamed = renameObject(parts[parts.length - 1]!);+ // H2 SCRIPT qualifies ordinary primary/unique/check constraints.+ // Rename the object, never the schema token preceding its name.+ replace(parts, parts.length > 1 && targetSchema ? `${targetSchema}.${renamed}` : renamed);+ }+ }+ }+ }+ if (createCount !== 1) return undefined;+ let result = ddl;+ for (const replacement of replacements.sort((left, right) => right.start - left.start)) result = result.slice(0, replacement.start) + replacement.value + result.slice(replacement.end);+ return result;+}++/** Only inspect COLLATE clauses; never replace matching text in data/comments. */+function mysqlCollationTokens(ddl: string): Array<{ start: number; end: number; name: string }> {+ const clauses: Array<{ start: number; end: number; name: string }> = [];+ for (const range of splitSqlStatementRanges(ddl, "mysql")) {+ const tokens = tokensForDdl(range.sql, "mysql");+ for (let i = 0; i < tokens.length; i++) {+ if (!word(tokens[i], "collate")) continue;+ const token = tokens[i + (tokens[i + 1]?.text === "=" ? 2 : 1)];+ const name = token?.kind === "string" ? token.text.slice(1, -1) : identifier(token);+ if (token && name) clauses.push({ start: range.from + token.span.start, end: range.from + token.span.end, name: name.toLowerCase() });+ }+ }+ return clauses;+}++export function mysqlDdlCollations(ddl: string): string[] {+ return [...new Set(mysqlCollationTokens(ddl).map((clause) => clause.name))];+}++export function adaptMysqlDdlCollations(ddl: string, supportedNames: string[]): { ddl: string; changes: string[]; unsupported: string[] } {+ const supported = new Set(supportedNames.map((name) => name.toLowerCase()));+ const changes = new Set<string>();+ const unsupported = new Set<string>();+ let result = ddl;+ for (const clause of mysqlCollationTokens(ddl).reverse()) {+ if (supported.has(clause.name)) continue;+ // Keep utf8mb4 and accent/case insensitivity. Do not guess mappings for+ // language-specific, binary or case-sensitive collations.+ const replacement = clause.name === "utf8mb4_0900_ai_ci" ? ["utf8mb4_unicode_520_ci", "utf8mb4_unicode_ci"].find((name) => supported.has(name)) : undefined;+ if (!replacement) {+ unsupported.add(clause.name);+ continue;+ }+ result = result.slice(0, clause.start) + replacement + result.slice(clause.end);+ changes.add(`${clause.name} → ${replacement}`);+ }+ return { ddl: result, changes: [...changes], unsupported: [...unsupported] };+}diff --git a/apps/desktop/src/components/transfer/queryResultTransferSource.ts b/apps/desktop/src/components/transfer/queryResultTransferSource.tsnew file mode 100644index 0000000000..84a539b5cd--- /dev/null+++ b/apps/desktop/src/components/transfer/queryResultTransferSource.ts@@ -0,0 +1,147 @@+import * as api from "@/lib/backend/api";+import { isSchemaAware, isSingleDatabase } from "@/lib/database/databaseFeatureSupport";+import { analyzeEditableQuery } from "@/lib/sql/sqlAnalysis";+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";+import type { DatabaseType } from "@/types/database";+import { queryResultTransferSqlLiteral } from "./queryResultTransferValues";++const POSTGRES_SOURCE_TYPES = new Set<DatabaseType>(["postgres", "kingbase", "highgo", "vastbase"]);+const ORACLE_SOURCE_TYPES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "dameng", "yashandb"]);++export interface QueryResultTransferSourceDdlRequest {+ sql: string;+ databaseType?: DatabaseType;+ connectionId: string;+ database: string;+ schema?: string;+ catalog?: string;+ clientSessionId?: string;+ txnSessionId?: string;+}++/** Read one executable table definition, without display-only access statements. */+export async function loadQueryResultTransferSourceDdl(request: QueryResultTransferSourceDdlRequest): Promise<string | undefined> {+ // Metadata APIs do not participate in the separate manual transaction.+ // A complete row snapshot is usable, but its uncommitted DDL is not.+ if (!request.connectionId || !request.database || request.txnSessionId) return undefined;+ const analysis = analyzeEditableQuery(request.sql);+ if (!analysis?.selectStar || analysis.sources?.length) return undefined;++ const fold = (name: string, quoted?: boolean) => {+ if (quoted || !request.databaseType) return name;+ if (POSTGRES_SOURCE_TYPES.has(request.databaseType)) return name.toLowerCase();+ if (ORACLE_SOURCE_TYPES.has(request.databaseType)) return name.toUpperCase();+ return name;+ };+ let table = fold(analysis.tableName, analysis.tableNameQuoted);+ let database = request.database;+ let schema = analysis.schema ? fold(analysis.schema, analysis.schemaQuoted) : request.schema;+ let catalog = analysis.catalog ?? request.catalog;+ if (!isSchemaAware(request.databaseType) && !isSingleDatabase(request.databaseType)) {+ if (analysis.schema && !analysis.catalog) database = analysis.schema;+ // MySQL metadata prefers its schema argument over database. A prior query+ // schema must not override an explicitly qualified source database.+ schema = database;+ catalog = request.catalog;+ }+ try {+ const readOnSourceSession = async (sql: string, querySchema?: string) => {+ const results = await api.executeMulti(request.connectionId, request.database, sql, querySchema, undefined, {+ executionMode: "simple",+ maxRows: 10000,+ catalog: request.catalog,+ clientSessionId: request.clientSessionId,+ });+ const result = results[0];+ return results.length === 1 && result && !result.execution_error && !result.truncated && !result.has_more && !result.large_value_cells?.length ? result : undefined;+ };+ if (request.databaseType === "mysql" || request.databaseType === "goldendb") {+ // Temporary MySQL tables shadow same-named permanent tables even when+ // qualified. SHOW CREATE must run on the session that produced the rows.+ const quote = (name: string) => "`" + name.replaceAll("`", "``") + "`";+ const result = await readOnSourceSession(`SHOW CREATE TABLE ${quote(database)}.${quote(table)}`);+ const ddl = result?.rows[0]?.[1];+ if (result?.rows.length !== 1 || typeof ddl !== "string" || !ddl.trim()) return undefined;+ const tokens = tokenizeSqlSemantic(ddl, "mysql", { mysqlBackslashEscape: true, mysqlDashCommentRequiresWhitespace: true }).filter((token) => token.kind !== "comment");+ // A target temporary table would disappear on another pooled connection;+ // do not silently change its lifetime or read a permanent shadow instead.+ if (tokens[0]?.normalized === "create" && tokens[1]?.normalized === "temporary") return undefined;+ return ddl;+ }+ if (request.databaseType === "sqlite") {+ const quote = (name: string) => '"' + name.replaceAll('"', '""') + '"';+ const literal = (name: string) => queryResultTransferSqlLiteral(name, "sqlite")!;+ let namespaces: string[];+ if (analysis.schema) namespaces = [analysis.schema];+ else {+ const databases = await readOnSourceSession("PRAGMA database_list");+ if (!databases || databases.rows.some((row) => typeof row[0] !== "number" || typeof row[1] !== "string")) return undefined;+ // SQLite resolves bare names in temp, main, then attachment order;+ // selecting a sidebar database does not change this SQL lookup order.+ namespaces = [...new Set(["temp", "main", ...[...databases.rows].sort((left, right) => Number(left[0]) - Number(right[0])).map((row) => row[1] as string)])];+ }+ for (const namespace of namespaces) {+ const master = `${quote(namespace)}.sqlite_master`;+ const definitions = await readOnSourceSession(`SELECT name, sql, type FROM ${master} WHERE type IN ('table', 'view') AND name = ${literal(table)} COLLATE NOCASE`);+ if (!definitions) return undefined;+ if (!definitions.rows.length) continue;+ const definition = definitions.rows[0]!;+ if (definitions.rows.length !== 1 || definition[2] !== "table" || typeof definition[0] !== "string" || typeof definition[1] !== "string" || !definition[1].trim()) return undefined;+ // Read exact index SQL, including expressions and WHERE clauses. The+ // actual table name also handles case-insensitive SQLite name lookup.+ const indexes = await readOnSourceSession(`SELECT sql FROM ${master} WHERE type = 'index' AND tbl_name = ${literal(definition[0])} COLLATE NOCASE AND sql IS NOT NULL ORDER BY name`);+ if (!indexes || indexes.rows.some((row) => typeof row[0] !== "string" || !row[0].trim())) return undefined;+ return [definition[1], ...indexes.rows.map((row) => row[0] as string)].join("\n;\n");+ }+ return undefined;+ }+ if (request.databaseType === "h2") {+ // H2 can store unquoted names in upper, lower or original case. Resolve+ // the physical metadata name without assuming DATABASE_TO_UPPER. An+ // ambiguous case-only match must not copy a different quoted table.+ const metadata = await readOnSourceSession("SELECT TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES", request.schema);+ if (!metadata || metadata.rows.some((row) => row.slice(0, 3).length !== 3 || row.slice(0, 3).some((value) => typeof value !== "string"))) return undefined;+ const uniqueName = (names: string[], name: string) => {+ const matches = [...new Set(names)].filter((candidate) => candidate.toLowerCase() === name.toLowerCase());+ return matches.length === 1 ? matches[0] : undefined;+ };+ if (analysis.schema && !analysis.schemaQuoted) {+ schema = uniqueName(+ metadata.rows.map((row) => row[0] as string),+ analysis.schema,+ );+ }+ if (!schema) return undefined;+ const tables = metadata.rows.filter((row) => row[0] === schema && (analysis.tableNameQuoted ? row[1] === table : (row[1] as string).toLowerCase() === table.toLowerCase()));+ if (tables.length !== 1 || /TEMPORARY/i.test(tables[0]![2] as string)) return undefined;+ table = tables[0]![1] as string;+ // H2 SCRIPT implicitly commits even a user-typed BEGIN. Once this+ // source session proves the physical table is permanent, use the+ // independent metadata connection for SCRIPT through getTableDdl.+ }+ if (request.databaseType && POSTGRES_SOURCE_TYPES.has(request.databaseType) && !analysis.schema) {+ // current_schema() alone can select the first search_path entry even+ // when the queried table lives in a later one. Resolve this relation on+ // the source query session instead of guessing public or the DB name.+ const relation = '"' + table.replaceAll('"', '""') + '"';+ const literal = queryResultTransferSqlLiteral(relation, "postgres");+ const results = await api.executeMulti(request.connectionId, database, `SELECT n.nspname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = pg_catalog.to_regclass(${literal}) AND c.relkind IN ('r', 'p', 'f')`, request.schema, undefined, {+ executionMode: "simple",+ maxRows: 1,+ catalog,+ clientSessionId: request.clientSessionId,+ });+ const resolvedSchema = results[0]?.rows[0]?.[0];+ if (results.some((result) => result.execution_error) || typeof resolvedSchema !== "string" || !resolvedSchema) return undefined;+ schema = resolvedSchema;+ }+ if (isSchemaAware(request.databaseType) && !schema) return undefined;+ // SQL Server's display DDL includes temporal-table metadata. The ordinary+ // renderer omits it, which would make an unsafe temporal copy look plain.+ const loadDdl = request.databaseType === "sqlserver" ? api.getTableDisplayDdl : api.getTableDdl;+ const ddl = await loadDdl(request.connectionId, database, schema || database, table, undefined, catalog);+ return ddl || undefined;+ } catch {+ return undefined;+ }+}diff --git a/apps/desktop/src/components/transfer/queryResultTransferStatements.ts b/apps/desktop/src/components/transfer/queryResultTransferStatements.tsnew file mode 100644index 0000000000..9817435808--- /dev/null+++ b/apps/desktop/src/components/transfer/queryResultTransferStatements.ts@@ -0,0 +1,69 @@+import type { DatabaseType } from "@/types/database";+import { queryResultTransferSqlLiteral } from "./queryResultTransferValues";++/** Keep the Oracle multi-row form in sync with data/transfer.rs::InsertSqlTemplate. */+export function queryResultTransferInsertSql(table: string, columns: string[], values: string[], databaseType: DatabaseType, overrideIdentity = false): string[] {+ if (!values.length) return [];+ const destination = `${table} (${columns.join(", ")})`;+ if ((databaseType === "oracle" || databaseType === "oceanbase-oracle") && values.length > 1) {+ return [`INSERT ALL\n${values.map((row) => `INTO ${destination} VALUES ${row}`).join("\n")}\nSELECT 1 FROM dual`];+ }+ const override = overrideIdentity ? " OVERRIDING SYSTEM VALUE" : "";+ // Single-row statements also work on JDBC engines without comma-separated VALUES.+ if (!["mysql", "postgres", "sqlite", "sqlserver", "h2", "kingbase", "highgo", "vastbase", "goldendb"].includes(databaseType)) {+ return values.map((row) => `INSERT INTO ${destination}${override} VALUES ${row}`);+ }+ return [`INSERT INTO ${destination}${override} VALUES ${values.join(",\n")}`];+}++/** IDENTITY_INSERT is session state: restore it on both the success and error paths. */+export function withSqlServerIdentityInsert(table: string, statements: string[]): string {+ return `BEGIN TRY\nSET IDENTITY_INSERT ${table} ON;\n${statements.join(";\n")};\nSET IDENTITY_INSERT ${table} OFF;\nEND TRY\nBEGIN CATCH\nDECLARE @dbx_transfer_error nvarchar(2048);\nSET @dbx_transfer_error = ERROR_MESSAGE();\nSET IDENTITY_INSERT ${table} OFF;\nRAISERROR(N'%s', 16, 1, @dbx_transfer_error);\nEND CATCH`;+}++/**+ * Advance an owned PostgreSQL sequence without moving it backwards or changing+ * its increment grid. ALTER SEQUENCE locks concurrent nextval calls; RESTART is+ * transactional on PostgreSQL 10+, unlike setval. The catalog branch preserves+ * compatibility with older SERIAL-only servers.+ * https://www.postgresql.org/docs/current/sql-altersequence.html+ * https://www.postgresql.org/docs/9.6/sql-altersequence.html+ */+export function postgresTransferSequenceSyncSql(table: string, column: string): string {+ const literal = (value: string) => queryResultTransferSqlLiteral(value, "postgres")!;+ const quotedColumn = '"' + column.replaceAll('"', '""') + '"';+ const body = `DECLARE+ dbx_sequence regclass;+ dbx_increment bigint;+ dbx_last numeric;+ dbx_called boolean;+ dbx_next numeric;+ dbx_edge numeric;+ dbx_restart numeric;+BEGIN+ dbx_sequence := pg_catalog.pg_get_serial_sequence(${literal(table)}, ${literal(column)})::regclass;+ IF dbx_sequence IS NULL THEN+ RAISE EXCEPTION 'Unable to find the owned identity/serial sequence';+ END IF;+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'pg_catalog' AND c.relname = 'pg_sequence') THEN+ EXECUTE 'SELECT seqincrement FROM pg_catalog.pg_sequence WHERE seqrelid = $1' INTO dbx_increment USING dbx_sequence;+ ELSE+ EXECUTE 'SELECT increment_by FROM ' || dbx_sequence::text INTO dbx_increment;+ END IF;+ IF dbx_increment IS NULL OR dbx_increment = 0 THEN+ RAISE EXCEPTION 'Unable to read the identity/serial sequence increment';+ END IF;+ EXECUTE 'ALTER SEQUENCE ' || dbx_sequence::text || ' INCREMENT BY ' || dbx_increment::text;+ EXECUTE 'SELECT last_value, is_called FROM ' || dbx_sequence::text INTO dbx_last, dbx_called;+ EXECUTE 'SELECT ' || CASE WHEN dbx_increment > 0 THEN 'MAX' ELSE 'MIN' END || ${literal(`(${quotedColumn}::numeric) FROM ${table}`)} INTO dbx_edge;+ dbx_next := dbx_last + CASE WHEN dbx_called THEN dbx_increment ELSE 0 END;+ IF (dbx_increment > 0 AND dbx_edge >= dbx_next) OR (dbx_increment < 0 AND dbx_edge <= dbx_next) THEN+ dbx_restart := dbx_next + FLOOR((dbx_edge - dbx_next) / dbx_increment) * dbx_increment;+ EXECUTE 'ALTER SEQUENCE ' || dbx_sequence::text || ' RESTART WITH ' || dbx_restart::text;+ PERFORM pg_catalog.nextval(dbx_sequence);+ END IF;+END;`;+ let delimiter = "$dbx_transfer$";+ while (body.includes(delimiter)) delimiter = delimiter.slice(0, -1) + "_$";+ return `DO ${delimiter}\n${body}\n${delimiter}`;+}diff --git a/apps/desktop/src/components/transfer/queryResultTransferValues.ts b/apps/desktop/src/components/transfer/queryResultTransferValues.tsnew file mode 100644index 0000000000..a915b1283a--- /dev/null+++ b/apps/desktop/src/components/transfer/queryResultTransferValues.ts@@ -0,0 +1,468 @@+import type { DatabaseType } from "@/types/database";+import { parseBinaryCellBytes } from "@/lib/dataGrid/binaryCellDownload";+import { binaryQueryResultValueHex } from "./queryResultTransfer";+import { normalizeQueryResultColumnType } from "./queryResultTransfer";++/** Database families for which this transfer path can emit a lossless binary literal. */+const SQLITE_TYPES = new Set<DatabaseType>(["sqlite", "rqlite", "turso", "cloudflare-d1"]);+const POSTGRES_TYPES = new Set<DatabaseType>(["postgres", "kingbase", "highgo", "vastbase", "gaussdb", "kwdb", "opengauss"]);+const MYSQL_TYPES = new Set<DatabaseType>(["mysql", "goldendb"]);+// Dameng is registered as a separate driver, but the transfer backend groups+// it with Oracle-family targets (NUMBER booleans and HEXTORAW binary values).+const ORACLE_TYPES = new Set<DatabaseType>(["oracle", "oceanbase-oracle", "dameng", "yashandb"]);++const BINARY_COLUMN_TYPE_RE = /\b(?:binary|varbinary|tinyblob|blob|mediumblob|longblob|bytea|bytes|image|raw|long\s+raw|long\s+varbinary)\b/i;+const BOOLEAN_COLUMN_TYPE_RE = /\b(?:bool|boolean)\b/i;+const INTEGER_COLUMN_TYPE_RE = /^(?:tinyint|smallint|mediumint|int|int2|int4|int8|integer|bigint|serial|bigserial)\b/i;+const EXACT_COLUMN_TYPE_RE = /^(?:decimal|numeric|number|money|smallmoney)\b/i;+const NUMERIC_COLUMN_TYPE_RE = /^(?:tinyint|smallint|mediumint|int|int2|int4|int8|integer|bigint|serial|bigserial|decimal|numeric|number|money|smallmoney|real|double|float|float4|float8|binary_float|binary_double)\b/i;+const NUMERIC_LITERAL_RE = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;++function normalizeSourceType(sourceType: string | undefined, databaseType?: DatabaseType): string | undefined {+ if (databaseType === "oracle") {+ // Oracle-go exposes these go-ora wire names; its temporal values retain+ // up to nine fractional digits (main.go::normalizeValue).+ const types: Record<string, string> = {+ timestampdty: "TIMESTAMP(9)",+ timestamptz_dty: "TIMESTAMP(9) WITH TIME ZONE",+ };+ return types[sourceType?.trim().toLowerCase() || ""] || sourceType;+ }+ if (databaseType === "h2") {+ // H2 2.x exposes standard SQL names in ResultSetMetaData, while the+ // transfer helpers use their BLOB/VARBINARY aliases.+ const type = sourceType?.trim();+ if (/^binary varying(?:\s*\(\s*\d+\s*\))?$/i.test(type || "")) return type!.replace(/^binary varying/i, "varbinary");+ if (/^binary large object$/i.test(type || "")) return "BLOB";+ if (/^character large object$/i.test(type || "")) return "CLOB";+ return sourceType;+ }+ if (databaseType !== "sqlserver") return sourceType;+ // Tiberius exposes TDS wire type names for several nullable columns. These+ // names describe values but are not valid CREATE TABLE data types.+ const types: Record<string, string> = {+ int1: "tinyint",+ int2: "smallint",+ int4: "int",+ int8: "bigint",+ intn: "bigint",+ bitn: "bit",+ float4: "real",+ float8: "float",+ floatn: "float",+ decimaln: "decimal",+ numericn: "numeric",+ money4: "smallmoney",+ datetimen: "datetime2(7)",+ datetime4: "smalldatetime",+ daten: "date",+ timen: "time(7)",+ datetimeoffsetn: "datetimeoffset(7)",+ guid: "uniqueidentifier",+ };+ return types[sourceType?.trim().toLowerCase() || ""] || sourceType;+}++function postgresArrayElementType(type: string | undefined, databaseType?: DatabaseType): string | undefined {+ if (!databaseType || !POSTGRES_TYPES.has(databaseType)) return undefined;+ const normalized = type?.trim();+ if (normalized?.endsWith("[]")) return normalized.slice(0, -2);+ // Native PostgreSQL result metadata uses wire names, e.g. _int8 and _text.+ if (normalized?.startsWith("_")) return normalized.slice(1);+ return undefined;+}++/** Only built-in type declarations understood by this transfer path may become SQL. */+function isGenericTypeDeclaration(type: string): boolean {+ const scalar = type.replace(/(?:\[\])+$/, "").trim();+ if (+ /^(?:bool|boolean|real|double precision|binary_float|binary_double|money|smallmoney|date|smalldatetime|serial|smallserial|bigserial|text|ntext|tinytext|mediumtext|longtext|blob|tinyblob|mediumblob|longblob|clob|nclob|bytea|image|uuid|uniqueidentifier|json|jsonb|xml|inet|cidr|macaddr|macaddr8|tsvector|tsquery|geometry|geography|rowversion|enum|set|long raw)$/i.test(+ scalar,+ )+ )+ return true;+ if (/^(?:tinyint|smallint|mediumint|int|integer|bigint|int2|int4|int8|float|float4|float8|double|decimal|numeric|number)(?:\s*\(\s*(?:\d+|\*)\s*(?:,\s*-?\d+\s*)?\))?(?:\s+unsigned)?(?:\s+zerofill)?$/i.test(scalar)) return true;+ if (/^(?:char|varchar|nchar|nvarchar|varchar2|nvarchar2|character|character varying|binary|varbinary|raw|bit|varbit|bit varying|vector)(?:\s*\(\s*(?:\d+|max)\s*(?:char|byte)?\s*\))?$/i.test(scalar)) return true;+ return /^(?:timestamp|timestamptz|time|timetz|datetime|datetime2|datetimeoffset)(?:\s*\(\s*\d+\s*\))?(?:\s+(?:with(?: local)?|without) time zone)?$/i.test(scalar);+}++function textTargetType(databaseType: DatabaseType): string {+ if (databaseType === "sqlserver") return "nvarchar(max)";+ if (ORACLE_TYPES.has(databaseType) || databaseType === "db2" || databaseType === "h2") return "CLOB";+ if (MYSQL_TYPES.has(databaseType)) return "LONGTEXT";+ return "TEXT";+}++function temporalFractionalPrecision(type: string, databaseType?: DatabaseType): number | undefined {+ if (/^(?:date|smalldatetime)$/i.test(type)) return 0;+ // Native SQL Server results call format_sqlserver_datetime_display, which+ // turns the driver's 1/300-second nanosecond approximation into 3-digit+ // canonical display text (for example .896666666 becomes .897).+ if (databaseType === "sqlserver" && /^datetime$/i.test(type)) return 3;+ const temporal = type.match(/^(?:timestamp|timestamptz|time|timetz|datetime|datetime2|datetimeoffset)(?:\s*\(\s*(\d+)\s*\))?(?:\s+(?:with(?: local)?|without) time zone)?$/i);+ if (!temporal || (databaseType === "sqlserver" && /^timestamp\b/i.test(type))) return undefined;+ if (temporal[1] !== undefined) return Number(temporal[1]);+ // Result headers omit the declaration's precision. Use the engine's upper+ // bound, never the default for a freshly declared bare type.+ if (databaseType && (POSTGRES_TYPES.has(databaseType) || MYSQL_TYPES.has(databaseType))) return 6;+ if (databaseType === "sqlserver") return 7;+ if (databaseType === "oracle" || databaseType === "oceanbase-oracle" || databaseType === "h2") return 9;+ if (databaseType === "db2") return 12;+ return undefined;+}++function timestampTargetType(sourceType: string, databaseType: DatabaseType, sourceDatabaseType?: DatabaseType): string {+ const precision = temporalFractionalPrecision(sourceType, sourceDatabaseType);+ if (precision === undefined) return textTargetType(databaseType);+ // PostgreSQL/MySQL stop at microseconds; SQL Server datetime2 stops at+ // 100 ns. A successful assignment otherwise rounds a 7–9 digit wire value.+ if (MYSQL_TYPES.has(databaseType)) return precision <= 6 ? "DATETIME(6)" : textTargetType(databaseType);+ if (POSTGRES_TYPES.has(databaseType)) return precision <= 6 ? "TIMESTAMP" : textTargetType(databaseType);+ if (databaseType === "sqlserver") return precision <= 7 ? "datetime2(7)" : textTargetType(databaseType);+ if (databaseType === "h2" || ORACLE_TYPES.has(databaseType)) return precision <= 9 ? "TIMESTAMP(9)" : textTargetType(databaseType);+ if (databaseType === "db2") return precision <= 12 ? `TIMESTAMP(${Math.max(6, precision)})` : textTargetType(databaseType);+ return precision <= 6 ? "TIMESTAMP" : textTargetType(databaseType);+}++function exactTargetType(type: string, databaseType: DatabaseType): string {+ if (POSTGRES_TYPES.has(databaseType)) return "NUMERIC";+ const precision = type.match(/^(?:decimal|numeric|number)\s*\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\)$/i);+ if (precision) {+ const digits = Number(precision[1]);+ const scale = Number(precision[2] || 0);+ const maxPrecision = MYSQL_TYPES.has(databaseType) ? 65 : databaseType === "db2" ? 31 : 38;+ if (!SQLITE_TYPES.has(databaseType) && digits > 0 && digits <= maxPrecision && scale <= digits && (!MYSQL_TYPES.has(databaseType) || scale <= 30)) {+ return `${ORACLE_TYPES.has(databaseType) ? "NUMBER" : "DECIMAL"}(${digits},${scale})`;+ }+ }+ // Result metadata often omits precision and scale. Floating point or a bare+ // DECIMAL (which can default to scale 0) would silently round exact values.+ return textTargetType(databaseType);+}++export function queryResultTransferIsBinaryColumnType(sourceType?: string, sourceDatabaseType?: DatabaseType): boolean {+ sourceType = normalizeSourceType(sourceType, sourceDatabaseType);+ if (postgresArrayElementType(sourceType, sourceDatabaseType)) return false;+ return BINARY_COLUMN_TYPE_RE.test(sourceType || "") || (sourceDatabaseType === "sqlserver" && /\b(?:timestamp|rowversion)\b/i.test(sourceType || ""));+}++export function queryResultTransferIsBooleanColumnType(sourceType?: string): boolean {+ return BOOLEAN_COLUMN_TYPE_RE.test(sourceType || "");+}++/**+ * Map a source column type to the target type used by the generic CREATE TABLE path.+ * Reusing this helper for literals keeps boolean and binary values aligned with the+ * type emitted in the target DDL.+ */+export function queryResultTransferTargetType(sourceType: string | undefined, databaseType: DatabaseType, sourceDatabaseType?: DatabaseType): string {+ sourceType = normalizeSourceType(sourceType, sourceDatabaseType);+ const type = (sourceType || "").trim().toLowerCase();+ const arrayElementType = postgresArrayElementType(type, sourceDatabaseType);+ // A user-defined type name can itself contain valid SQL clauses. Restrict+ // this path to complete built-in type declarations, not a blacklist of SQL.+ if (!isGenericTypeDeclaration(arrayElementType || type)) return textTargetType(databaseType);+ if (arrayElementType) return POSTGRES_TYPES.has(databaseType) ? `${arrayElementType}[]` : textTargetType(databaseType);+ const sourceIsSqlServerBinary = sourceDatabaseType === "sqlserver" && /\b(?:timestamp|rowversion)\b/i.test(type);++ if (sourceIsSqlServerBinary) {+ if (POSTGRES_TYPES.has(databaseType)) return "bytea";+ if (MYSQL_TYPES.has(databaseType)) return "BLOB";+ if (ORACLE_TYPES.has(databaseType)) return "BLOB";+ if (databaseType === "sqlserver") return "varbinary(max)";+ if (databaseType === "db2" || databaseType === "h2") return "BLOB";+ return "BLOB";+ }++ if (EXACT_COLUMN_TYPE_RE.test(type)) {+ if (sourceDatabaseType === databaseType && (POSTGRES_TYPES.has(databaseType) || ORACLE_TYPES.has(databaseType))) return type;+ return exactTargetType(type, databaseType);+ }+ if (/^(?:bit|varbit|bit varying)\b/.test(type) && sourceDatabaseType !== databaseType) {+ if (sourceDatabaseType === "sqlserver") {+ if (SQLITE_TYPES.has(databaseType)) return "INTEGER";+ return ORACLE_TYPES.has(databaseType) ? "NUMBER(1)" : "BOOLEAN";+ }+ if (POSTGRES_TYPES.has(databaseType)) return "BIT VARYING";+ return textTargetType(databaseType);+ }+ if (sourceDatabaseType === databaseType && type) {+ if (/^(?:varchar|char|nvarchar|nchar|varchar2|nvarchar2|character|character varying)$/.test(type)) {+ return ORACLE_TYPES.has(databaseType) && type.startsWith("n") ? "NCLOB" : textTargetType(databaseType);+ }+ if (/^(?:binary|varbinary|raw|long raw)$/.test(type)) {+ if (databaseType === "sqlserver") return "varbinary(max)";+ return MYSQL_TYPES.has(databaseType) ? "LONGBLOB" : "BLOB";+ }+ // MySQL's result headers expose bare types, without lengths or precision.+ // Do not let CREATE TABLE's defaults truncate an otherwise valid result.+ if (MYSQL_TYPES.has(databaseType)) {+ if (/^(?:varchar|char|enum|set)$/.test(type)) return "LONGTEXT";+ if (/^(?:binary|varbinary)$/.test(type)) return "LONGBLOB";+ if (/^(?:datetime|timestamp|time)$/.test(type)) return `${type}(6)`;+ if (type === "bit") return "BIT(64)";+ if (INTEGER_COLUMN_TYPE_RE.test(type) && !/unsigned/.test(type)) return "DECIMAL(20,0)";+ }+ // H2 result headers omit fractional precision. TIME defaults to 0 and+ // TIMESTAMP to 6, even though source values can contain nine digits.+ if (databaseType === "h2") {+ const temporal = type.match(/^(time|timestamp)(\s+(?:with|without) time zone)?$/);+ if (temporal) return `${temporal[1]}(9)${temporal[2] || ""}`;+ }+ if (databaseType === "oracle" || databaseType === "oceanbase-oracle") {+ const temporal = type.match(/^timestamp(\s+with(?: local)? time zone)?$/);+ if (temporal) return `TIMESTAMP(9)${temporal[1] || ""}`;+ }+ if (databaseType === "db2" && /^timestamp$/.test(type)) return "TIMESTAMP(12)";+ if (POSTGRES_TYPES.has(databaseType) && /^(?:bit|varbit|bit varying)$/.test(type)) return "BIT VARYING";+ return normalizeQueryResultColumnType(sourceType!, databaseType);+ }++ if (SQLITE_TYPES.has(databaseType)) {+ if (BOOLEAN_COLUMN_TYPE_RE.test(type)) return "INTEGER";+ if (INTEGER_COLUMN_TYPE_RE.test(type)) return sourceDatabaseType && MYSQL_TYPES.has(sourceDatabaseType) ? "TEXT" : /unsigned/.test(type) ? "TEXT" : "INTEGER";+ if (/real|double|float/.test(type)) return "REAL";+ if (BINARY_COLUMN_TYPE_RE.test(type)) return "BLOB";+ return "TEXT";+ }++ if (BOOLEAN_COLUMN_TYPE_RE.test(type)) {+ if (databaseType === "sqlserver") return "bit";+ if (ORACLE_TYPES.has(databaseType)) return "NUMBER(1)";+ return "BOOLEAN";+ }+ if (INTEGER_COLUMN_TYPE_RE.test(type)) {+ if (/unsigned/.test(type) || (sourceDatabaseType && MYSQL_TYPES.has(sourceDatabaseType))) return ORACLE_TYPES.has(databaseType) ? "NUMBER(20,0)" : "DECIMAL(20,0)";+ if (/bigint|bigserial|int8/.test(type)) return ORACLE_TYPES.has(databaseType) ? "NUMBER(19)" : "BIGINT";+ return ORACLE_TYPES.has(databaseType) ? "NUMBER" : "INTEGER";+ }+ if (/real|double|float/.test(type)) {+ if (databaseType === "sqlserver") return "float";+ if (ORACLE_TYPES.has(databaseType)) return "BINARY_DOUBLE";+ return ["db2", "dameng"].includes(databaseType) ? "DOUBLE" : "DOUBLE PRECISION";+ }+ if (/^date$/.test(type) && !(sourceDatabaseType && ORACLE_TYPES.has(sourceDatabaseType))) return "DATE";+ if (/^(?:time|timetz)\b/.test(type) || /time zone|timestamptz|datetimeoffset/.test(type)) return textTargetType(databaseType);+ if (/date|time|timestamp/.test(type)) {+ return timestampTargetType(type, databaseType, sourceDatabaseType);+ }+ if (/json/.test(type)) {+ if (databaseType === "postgres") return "jsonb";+ if (databaseType === "mysql") return "json";+ if (databaseType === "sqlserver") return "nvarchar(max)";+ return "CLOB";+ }+ if (BINARY_COLUMN_TYPE_RE.test(type) || sourceIsSqlServerBinary) {+ if (POSTGRES_TYPES.has(databaseType)) return "bytea";+ if (MYSQL_TYPES.has(databaseType)) return "BLOB";+ if (ORACLE_TYPES.has(databaseType)) return "BLOB";+ if (databaseType === "sqlserver") return "varbinary(max)";+ if (databaseType === "h2" || databaseType === "db2") return "BLOB";+ return "BLOB";+ }+ return textTargetType(databaseType);+}++function escapedTextLiteral(value: string, databaseType: DatabaseType, targetType?: string): string | undefined {+ const escaped = value.replaceAll("'", "''");+ if (ORACLE_TYPES.has(databaseType)) {+ const encoder = new TextEncoder();+ if (encoder.encode(escaped).length > 4000) {+ // Mirror data_grid_sql.rs::format_oracle_lob_assignment_literal: each+ // literal stays below Oracle 19c's STANDARD limit, and concatenation+ // happens on LOB values instead of overflowing a VARCHAR2 expression.+ if ((databaseType !== "oracle" && databaseType !== "oceanbase-oracle") || !/^(?:n?clob)\b/i.test(targetType || "")) return undefined;+ const constructor = /^nclob\b/i.test(targetType || "") ? "TO_NCLOB" : "TO_CLOB";+ const chunks: string[] = [];+ let chunk = "";+ let byteLength = 0;+ for (const character of value) {+ const escapedCharacter = character === "'" ? "''" : character;+ const length = encoder.encode(escapedCharacter).length;+ if (byteLength + length > 3900) {+ chunks.push(`${constructor}('${chunk}')`);+ chunk = "";+ byteLength = 0;+ }+ chunk += escapedCharacter;+ byteLength += length;+ }+ if (chunk) chunks.push(`${constructor}('${chunk}')`);+ return chunks.join(" || ");+ }+ }+ const isAsciiControl = (character: string) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127;+ if (POSTGRES_TYPES.has(databaseType) && Array.from(value).some((character) => character === "\\" || isAsciiControl(character))) {+ // Match dbx-sql-core/value_literals.rs. E strings are independent of+ // standard_conforming_strings, including quotes following a backslash.+ const pgEscaped = Array.from(value, (character) => {+ if (character === "\\") return "\\\\";+ if (character === "'") return "''";+ return isAsciiControl(character) ? `\\x${character.charCodeAt(0).toString(16).padStart(2, "0")}` : character;+ }).join("");+ return `E'${pgEscaped}'`;+ }+ if (databaseType === "sqlserver") return `N'${escaped}'`;+ if (MYSQL_TYPES.has(databaseType)) {+ const bytes = new TextEncoder().encode(value);+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");+ return `CONVERT(X'${hex}' USING utf8mb4)`;+ }+ return `'${escaped}'`;+}++function booleanValue(value: unknown): boolean | undefined {+ if (typeof value === "boolean") return value;+ if (typeof value === "number" && (value === 0 || value === 1)) return value === 1;+ if (typeof value !== "string") return undefined;+ const normalized = value.trim().toLowerCase();+ if (normalized === "true" || normalized === "t" || normalized === "yes" || normalized === "1") return true;+ if (normalized === "false" || normalized === "f" || normalized === "no" || normalized === "0") return false;+ return undefined;+}++function binaryLiteral(value: unknown, databaseType: DatabaseType, targetType: string, sourceType?: string, sourceDatabaseType?: DatabaseType): string | undefined {+ if (!queryResultTransferIsBinaryColumnType(sourceType, sourceDatabaseType)) return undefined;+ if (typeof value === "string") {+ const trimmed = value.trim();+ const prefixed = trimmed.match(/^(?:0x|\\x)(.*)$/i);+ if (prefixed) {+ const hex = prefixed[1]!.replace(/\s+/g, "");+ // The backend's binary contract is a 0x-prefixed byte string. Do not+ // reinterpret malformed values as the UTF-8 bytes of their display text.+ if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(hex)) return undefined;+ }+ }+ if (!(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && !parseBinaryCellBytes(value, "binary")) return undefined;+ const hex = binaryQueryResultValueHex(value);+ if (SQLITE_TYPES.has(databaseType) || databaseType === "h2") return `X'${hex}'`;+ if (POSTGRES_TYPES.has(databaseType)) return `decode('${hex}', 'hex')`;+ if (MYSQL_TYPES.has(databaseType)) return `X'${hex}'`;+ if (databaseType === "sqlserver") return `0x${hex}`;+ if (ORACLE_TYPES.has(databaseType)) return hex.length > 0 ? `HEXTORAW('${hex}')` : /blob/i.test(targetType) ? "EMPTY_BLOB()" : undefined;+ if (databaseType === "db2") return `BX'${hex}'`;+ // Do not silently turn canonical binary values into quoted text for engines+ // whose binary literal syntax is not verified here.+ return undefined;+}++function numericStringLiteral(value: string, sourceType?: string): string | undefined {+ if (!NUMERIC_COLUMN_TYPE_RE.test(sourceType || "")) return undefined;+ const normalized = value.trim();+ return NUMERIC_LITERAL_RE.test(normalized) ? normalized : undefined;+}++function postgresArrayLiteral(value: unknown, databaseType: DatabaseType, elementType: string, sourceDatabaseType: DatabaseType): string | undefined {+ // Text-fallback PostgreSQL results already use the server's array syntax.+ if (typeof value === "string") return escapedTextLiteral(value, databaseType);+ if (!Array.isArray(value) || !/^[a-z][a-z0-9_]*(?:\[\])*$/i.test(elementType)) return undefined;+ const literals = value.map((item) => {+ if (Array.isArray(item) && !/^(?:json|jsonb)$/i.test(elementType)) return postgresArrayLiteral(item, databaseType, elementType, sourceDatabaseType);+ return queryResultTransferSqlLiteral(item, databaseType, elementType, elementType, sourceDatabaseType);+ });+ if (literals.some((literal) => literal === undefined)) return undefined;+ return `ARRAY[${literals.join(", ")}]::${elementType}[]`;+}++function oracleTemporalLiteral(value: string, targetType: string): string | undefined {+ // Explicit masks mirror the backend transfer path and avoid NLS_DATE_FORMAT+ // and NLS_TIMESTAMP_FORMAT changing the meaning of a query result value.+ const parts = value.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}:\d{2})(\.\d{1,9})?(?:\s*(Z|[+-]\d{2}:\d{2}))?)?$/i);+ if (!parts) return undefined;+ const [, date, time = "00:00:00", fraction = "", zone] = parts;+ if (/^date$/i.test(targetType.trim())) {+ if (zone || (fraction && !/^\.0+$/.test(fraction))) return undefined;+ if (time === "00:00:00") return `DATE '${date}'`;+ return `TO_DATE('${date} ${time}', 'YYYY-MM-DD HH24:MI:SS')`;+ }+ const mask = `YYYY-MM-DD HH24:MI:SS${fraction ? ".FF" : ""}`;+ if (zone) {+ if (!/with (?:local )?time zone/i.test(targetType)) return undefined;+ const offset = /^z$/i.test(zone) ? "+00:00" : zone;+ return `TO_TIMESTAMP_TZ('${date} ${time}${fraction} ${offset}', '${mask} TZH:TZM')`;+ }+ if (/with (?:local )?time zone/i.test(targetType)) return undefined;+ return `TO_TIMESTAMP('${date} ${time}${fraction}', '${mask}')`;+}++function bitStringLiteral(value: unknown, databaseType: DatabaseType, sourceDatabaseType: DatabaseType | undefined, targetType: string): string | undefined {+ // SQL Server bit is boolean, while PostgreSQL/MySQL bit values are bit strings.+ if (sourceDatabaseType === "sqlserver") {+ const bool = booleanValue(value);+ if (bool === undefined) return undefined;+ if (databaseType === "sqlserver" || ORACLE_TYPES.has(databaseType) || SQLITE_TYPES.has(databaseType)) return bool ? "1" : "0";+ return bool ? "TRUE" : "FALSE";+ }+ const bits = typeof value === "boolean" ? (value ? "1" : "0") : String(value);+ if (!/^[01]+$/.test(bits)) return undefined;+ if (/^(?:bit|varbit)/i.test(targetType) && (MYSQL_TYPES.has(databaseType) || POSTGRES_TYPES.has(databaseType))) return `B'${bits}'`;+ return escapedTextLiteral(bits, databaseType, targetType);+}++/**+ * Emit a SQL literal for query-result transfer. `undefined` means the value+ * cannot be represented safely by this path; callers must abort the transfer.+ */+export function queryResultTransferSqlLiteral(value: unknown, databaseType: DatabaseType, sourceType?: string, targetType?: string, sourceDatabaseType?: DatabaseType): string | undefined {+ const sourceIsSqlServerDatetime = sourceDatabaseType === "sqlserver" && /^(?:datetime|datetimen)$/i.test(sourceType?.trim() || "");+ sourceType = normalizeSourceType(sourceType, sourceDatabaseType);+ if (value === null || value === undefined) return "NULL";+ if (typeof value === "string" && value.includes("\0") && POSTGRES_TYPES.has(databaseType)) return undefined;+ const effectiveType = (normalizeSourceType(targetType, databaseType) || queryResultTransferTargetType(sourceType, databaseType, sourceDatabaseType)).toLowerCase();+ if (typeof value === "string") {+ const parts = value.trim().match(/^(?:\d{4}-\d{2}-\d{2}[T ])?([+-]?\d{2,3}):(\d{2}):(\d{2})(?:\.(\d+))?(?:\s*(?:Z|[+-]\d{2}:\d{2}))?$/i);+ const fraction = parts?.[4];+ const precision = SQLITE_TYPES.has(databaseType) ? undefined : temporalFractionalPrecision(effectiveType, databaseType);+ if (fraction && precision !== undefined && /[1-9]/.test(fraction.slice(precision))) return undefined;+ if (parts) {+ // Oracle DATE retains the clock; SQLite DATE has no temporal coercion.+ if (effectiveType === "date" && !ORACLE_TYPES.has(databaseType) && !SQLITE_TYPES.has(databaseType) && parts.slice(1, 4).some((part) => Number(part) !== 0)) return undefined;+ if (databaseType === "sqlserver" && effectiveType === "smalldatetime" && Number(parts[3]) !== 0) return undefined;+ if (databaseType === "sqlserver" && effectiveType === "datetime") {+ const millisecondDigit = (fraction || "").padEnd(3, "0")[2]!;+ // A legacy SQL Server value's canonical .003/.007 display text maps+ // back to the same 1/300-second tick. Other sources are exact decimal+ // times: only 10 ms multiples are exactly representable as ticks.+ if (sourceIsSqlServerDatetime ? !/[037]/.test(millisecondDigit) : millisecondDigit !== "0") return undefined;+ }+ }+ }+ // Unknown user-defined types are serialized as values; their names must not+ // accidentally select boolean, binary or numeric conversion by a substring.+ if (!isGenericTypeDeclaration(postgresArrayElementType(sourceType, sourceDatabaseType) || sourceType || "")) sourceType = undefined;+ if (databaseType === "h2" && /^json\b/.test(effectiveType)) {+ // A character literal assigned to H2 JSON becomes a JSON string. Mark+ // the payload as JSON so objects, arrays and scalars retain their kind.+ const text = typeof value === "object" ? JSON.stringify(value) : String(value);+ return `JSON ${escapedTextLiteral(text, databaseType, effectiveType)}`;+ }+ if (value === "" && ORACLE_TYPES.has(databaseType)) return /^(?:n?clob)\b/.test(effectiveType) ? "EMPTY_CLOB()" : undefined;+ const arrayElementType = postgresArrayElementType(sourceType, sourceDatabaseType);+ if (arrayElementType && isGenericTypeDeclaration(arrayElementType) && POSTGRES_TYPES.has(databaseType) && postgresArrayElementType(effectiveType, databaseType)) return postgresArrayLiteral(value, databaseType, arrayElementType, sourceDatabaseType!);+ if (arrayElementType) return escapedTextLiteral(typeof value === "string" ? value : JSON.stringify(value), databaseType, effectiveType);+ if (/^(?:bit|varbit|bit varying)\b/i.test(sourceType || "")) return bitStringLiteral(value, databaseType, sourceDatabaseType, effectiveType);++ const binary = binaryLiteral(value, databaseType, effectiveType, sourceType, sourceDatabaseType);+ if (queryResultTransferIsBinaryColumnType(sourceType, sourceDatabaseType)) return binary;++ const bool = typeof value === "boolean" || queryResultTransferIsBooleanColumnType(sourceType) ? booleanValue(value) : undefined;+ if (bool !== undefined) {+ const numericBooleanTarget = /^(?:number|numeric|decimal|tinyint|smallint|int|integer|bit)\b/.test(effectiveType) || ORACLE_TYPES.has(databaseType) || databaseType === "sqlserver" || SQLITE_TYPES.has(databaseType);+ if (numericBooleanTarget) return bool ? "1" : "0";+ return bool ? "TRUE" : "FALSE";+ }++ if (typeof value === "string" && ORACLE_TYPES.has(databaseType) && /^(?:date|timestamp)\b/.test(effectiveType)) return oracleTemporalLiteral(value, effectiveType);+ if (typeof value === "number" && (INTEGER_COLUMN_TYPE_RE.test(sourceType || "") || EXACT_COLUMN_TYPE_RE.test(sourceType || "")) && Number.isInteger(value) && !Number.isSafeInteger(value)) return undefined;+ if (/^(?:n?varchar|n?char|text|longtext|mediumtext|n?clob)\b/.test(effectiveType)) {+ return escapedTextLiteral(typeof value === "object" ? JSON.stringify(value) : String(value), databaseType, effectiveType);+ }+ if (typeof value === "number" && Number.isFinite(value)) return String(value);+ if (typeof value === "string") {+ const numeric = numericStringLiteral(value, sourceType);+ if (numeric) return numeric;+ }++ const text = typeof value === "object" ? JSON.stringify(value) : String(value);+ return escapedTextLiteral(text, databaseType, effectiveType);+}diff --git a/apps/desktop/src/components/ui/dialog/__tests__/dialogLayerOrder.spec.ts b/apps/desktop/src/components/ui/dialog/__tests__/dialogLayerOrder.spec.tsindex 894b9e5ba3..49a9e0a3d2 100644--- a/apps/desktop/src/components/ui/dialog/__tests__/dialogLayerOrder.spec.ts+++ b/apps/desktop/src/components/ui/dialog/__tests__/dialogLayerOrder.spec.ts@@ -317,3 +317,53 @@ describe("dialog layer order", () => {expect(getComputedStyle(popperWrapper!).zIndex).toContain("80");});});++describe("non-modal floating dialogs", () => {+ it("leaves the background interactive and stays open when it receives focus", async () => {+ const host = document.createElement("div");+ document.body.append(host);+ const state = reactive({ open: true, clicks: 0 });+ const app = createApp(+ defineComponent({+ setup: () => () => [+ h("button", { id: "background-action", onClick: () => state.clicks++ }, "Background"),+ h(+ Dialog,+ {+ open: state.open,+ modal: false,+ "onUpdate:open": (value: boolean) => {+ state.open = value;+ },+ },+ {+ default: () =>+ h(+ DialogContent,+ { onInteractOutside: (event: Event) => event.preventDefault() },+ {+ default: () => h(DialogTitle, null, { default: () => "Floating export" }),+ },+ ),+ },+ ),+ ],+ }),+ );+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} } }));+ app.mount(host);+ mountedApps.push({ unmount: () => app.unmount(), host });+ await flush();+ expect(document.querySelector('[data-slot="dialog-overlay"]')).toBeNull();+ expect(document.body.style.pointerEvents).not.toBe("none");+ const button = host.querySelector<HTMLButtonElement>("#background-action")!;+ expect(button.closest('[aria-hidden="true"]')).toBeNull();+ button.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }));+ button.focus();+ button.click();+ await flush();+ expect(state.open).toBe(true);+ expect(state.clicks).toBe(1);+ expect(document.activeElement).toBe(button);+ });+});diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 98394782e9..f8b866d79c 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -1875,6 +1875,50 @@ export default withEnglishFallback({selectionCells: "{count} xana",clearSelection: "Seçimi təmizlə",export: "İxrac et",+ exportDatabase: "Verilənlər bazasına ixrac et",+ exportDatabasePreview: "İcraya ön baxış",+ exportDatabaseConfirmTitle: "Köçürməni təsdiqlə",+ exportDatabaseConfirmDescription: "Hədəfi və əməliyyatları yoxlayın. Təsdiqdən sonra hədəf verilənlər bazasına yazılmağa başlanacaq.",+ exportDatabasePreviewDescription: "Bu köçürməni nəzərdən keçirin. Ön baxış hədəf verilənlər bazasına məlumat yazmır.",+ exportDatabaseSource: "Mənbə",+ exportDatabaseTarget: "Hədəf",+ exportDatabaseScope: "Məlumat həcmi",+ exportDatabaseLoadedScope: "Hazırda yüklənib: {rows} sətir · {columns} sütun",+ exportDatabaseOperations: "Planlaşdırılan əməliyyatlar",+ exportDatabaseColumns: "Mənbə nəticəsinin sütunları",+ exportDatabasePreviewScopeNote: "Hazırda yüklənmiş sətirlərin sayı göstərilir. İcra zamanı ixrac edilə bilən tam nəticə yüklənir, sətir limiti, hədəf cədvəl və sütun uyğunluğu yoxlanılır. Faktiki köçürülən sətirlərin sayı tam nəticədən asılıdır.",+ exportDatabasePlanCreate: "Hədəf cədvəli yarat → sətirləri əlavə et (cədvəl varsa dayan; mövcud cədvəli silmə)",+ exportDatabasePlanAppend: "Mövcud məlumatları saxlayaraq hədəf cədvələ sətirlər əlavə et (INSERT)",+ exportDatabasePlanOverwrite: "Hədəf cədvəldəki BÜTÜN mövcud sətirləri sil (WHERE olmadan DELETE) → bu nəticəni əlavə et",+ exportDatabaseOverwriteWarning: "Üzərinə yazma bu nəticədə olmayan məlumatlar daxil olmaqla hədəf cədvəldəki BÜTÜN mövcud sətirləri silir. Hədəf bağlantını, verilənlər bazasını və cədvəli yoxlayın.",+ exportDatabaseBack: "Parametrlərə qayıt",+ exportDatabaseConfirm: "Köçürməni təsdiqlə",+ exportDatabaseDescription: "{database} · {columns} sütun · {rows} sətir yüklənib",+ exportDatabaseExecutionFailed: "Hədəf verilənlər bazası SQL ifadəsini rədd etdi.",+ exportDatabaseNonTransactionalTarget: "Mövcud MySQL cədvəlinə yazmaq üçün InnoDB tələb olunur ki, köçürmə uğursuz olduqda əməliyyat geri qaytarıla bilsin.",+ exportDatabaseIdentityUnsupported: "Bu hədəf drayver açıq şəkildə verilmiş identifikator dəyərlərini təhlükəsiz saxlaya və onların ardıcıllığını yeniləyə bilmir. Heç bir məlumat yazılmadı.",+ exportDatabaseTargetColumnMissing: "Hədəf cədvəldə {column} adlı yazıla bilən sütun yoxdur.",+ exportDatabaseTable: "Hədəf cədvəl",+ exportDatabaseCreateTable: "Hədəf cədvəli yarat",+ exportDatabaseModeOverwrite: "Üzərinə yaz (DELETE + INSERT)",+ exportDatabaseDone: "Sorğu nəticəsi verilənlər bazasına ixrac edildi",+ exportDatabaseCancelling: "Ləğv edilir…",+ exportDatabaseCancelled: "Hədəf verilənlər bazasına yazılmadan əvvəl köçürmə ləğv edildi.",+ exportDatabaseEmpty: "Sorğu nəticəsi boşdur və ya əlçatan deyil.",+ exportDatabaseIncomplete: "Sorğu nəticəsi tam deyil. Heç bir məlumat yazılmadı; köçürmədən əvvəl sorğunu yenidən icra edib tam nəticəni əldə edin.",+ exportDatabaseLoadComplete: "Bu nəticə aktiv kursor və ya əl ilə idarə olunan tranzaksiyadan istifadə edir. Köçürmədən əvvəl nəticə cədvəlində bütün sətirləri yükləyin.",+ exportDatabaseRowLimit: "Sorğu nəticəsi ixrac sətir limitini ({limit}) aşır; köçürmədən əvvəl nəticəni azaldın və ya limiti artırın.",+ exportDatabaseBatchTooLarge: "Bir sətir köçürmə ifadəsinin ölçü limitini (512 KiB) aşır. Köçürmədən əvvəl dəyərin ölçüsünü azaldın.",+ exportDatabasePreparing: "Hədəf cədvəl hazırlanır…",+ exportDatabaseCreating: "Hədəf cədvəl yaradılır…",+ exportDatabaseWriting: "Sorğu nəticəsi hədəf verilənlər bazasına yazılır…",+ exportDatabaseUnsupportedCollation: "Hədəf aşağıdakı müqayisə qaydalarını dəstəkləmir və məlum uyğun alternativ yoxdur. Cədvəl yaradılmadı: {collations}",+ exportDatabaseCollationAdapted: "Müqayisə qaydaları hədəfə uyğunlaşdırıldı: {changes}. Sıralama və mətn bərabərliyinin yoxlanması mənbədən fərqlənə bilər.",+ exportDatabaseDdlUnavailable: "Mənbə cədvəlin DDL-i oxuna və ya təhlükəsiz yenidən yazıla bilmədiyi üçün köçürmə ləğv edildi.",+ exportDatabaseNoWritableColumns: "Nəticədə hədəf cədvələ yazıla bilən sütun yoxdur.",+ exportDatabaseTargetExists: "Hədəf cədvəl {table} artıq mövcuddur. Ona yazmaq üçün «Hədəf cədvəli yarat» seçimini söndürün və ya başqa cədvəl seçin.",+ exportDatabaseValueUnsupported: "Nəticədə hədəf verilənlər bazasında təhlükəsiz təmsil edilə bilməyən dəyər var.",+ exportDatabaseCleanupFailed: "Köçürmə uğursuz oldu: {message}. Müvəqqəti cədvəl {table} silinə bilmədi: {error}.",exportCsv: "CSV-yə ixrac et",exportXlsx: "XLSX-ə ixrac et",exportXlsxWithSql: "SQL ilə XLSX-ə ixrac et",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex abf0a57723..260b4bf1f7 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -2312,6 +2312,50 @@ export default {selectionCells: "{count} cells",clearSelection: "Clear Selection",export: "Export",+ exportDatabase: "Export to Database",+ exportDatabasePreview: "Execution preview",+ exportDatabaseConfirmTitle: "Confirm transfer",+ exportDatabaseConfirmDescription: "Review the destination and operations. Confirming will start writing to the target database.",+ exportDatabasePreviewDescription: "Review this transfer. Preview does not write to the target database.",+ exportDatabaseSource: "Source",+ exportDatabaseTarget: "Destination",+ exportDatabaseScope: "Data size",+ exportDatabaseLoadedScope: "Currently loaded: {rows} rows · {columns} columns",+ exportDatabaseOperations: "Planned operations",+ exportDatabaseColumns: "Source result columns",+ exportDatabasePreviewScopeNote: "This shows the currently loaded row count. Execution loads the full exportable result and checks row limits, the target table and column compatibility. The actual transferred row count depends on the complete result.",+ exportDatabasePlanCreate: "Create target table → insert rows (stop if the table exists; do not delete it)",+ exportDatabasePlanAppend: "Append rows to the existing target table (INSERT), preserving existing data",+ exportDatabasePlanOverwrite: "Delete ALL existing target rows (DELETE without WHERE) → insert this result",+ exportDatabaseOverwriteWarning: "Overwrite deletes ALL existing rows in the target table, including data absent from this result. Verify the target connection, database and table.",+ exportDatabaseBack: "Back to settings",+ exportDatabaseConfirm: "Confirm transfer",+ exportDatabaseDescription: "{database} · {columns} columns · {rows} loaded rows",+ exportDatabaseExecutionFailed: "The target database rejected the statement.",+ exportDatabaseNonTransactionalTarget: "Writing to an existing MySQL table requires InnoDB so a failed transfer can roll back.",+ exportDatabaseIdentityUnsupported: "This target driver cannot safely preserve explicit identity values and advance their sequence. No data was written.",+ exportDatabaseTargetColumnMissing: "The target table has no writable column named {column}.",+ exportDatabaseTable: "Target table",+ exportDatabaseCreateTable: "Create target table",+ exportDatabaseModeOverwrite: "Overwrite (DELETE + INSERT)",+ exportDatabaseDone: "Query result exported to database",+ exportDatabaseCancelling: "Cancelling…",+ exportDatabaseCancelled: "Transfer cancelled before writing to the target database.",+ exportDatabaseEmpty: "The query result is empty or unavailable.",+ exportDatabaseIncomplete: "The query result is incomplete. No data was written; rerun the query with a complete result before transferring.",+ exportDatabaseLoadComplete: "This result uses an active cursor or manual transaction. Load all rows in the result grid before transferring it.",+ exportDatabaseRowLimit: "The query result exceeds the export row limit ({limit}); reduce the result or raise the limit before transferring it.",+ exportDatabaseBatchTooLarge: "A single row exceeds the transfer statement size limit (512 KiB). Reduce the value size before transferring.",+ exportDatabasePreparing: "Preparing target table…",+ exportDatabaseCreating: "Creating target table…",+ exportDatabaseWriting: "Writing query result to the target database…",+ exportDatabaseUnsupportedCollation: "The target does not support these collations and no known compatible replacement is available. No table was created: {collations}",+ exportDatabaseCollationAdapted: "Adapted collations for the target: {changes}. Sorting and string equality may differ from the source.",+ exportDatabaseDdlUnavailable: "The source table DDL could not be read or safely rewritten, so the transfer was cancelled.",+ exportDatabaseNoWritableColumns: "The result contains no columns that can be written to the target table.",+ exportDatabaseTargetExists: "The target table {table} already exists. Disable Create target table to write to it, or choose another table.",+ exportDatabaseValueUnsupported: "The result contains a value that cannot be represented safely in the target database.",+ exportDatabaseCleanupFailed: "Transfer failed: {message}. The temporary table {table} could not be removed: {error}.",exportCsv: "Export CSV",exportXlsx: "Export XLSX",exportXlsxWithSql: "Export XLSX with SQL",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex f37acab9a9..877fe30fe8 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -2173,6 +2173,51 @@ export default withEnglishFallback({selectionCells: "{count} celdas",clearSelection: "Limpiar selección",export: "Exportar",+ exportDatabase: "Exportar a base de datos",+ exportDatabasePreview: "Vista previa de ejecución",+ exportDatabaseConfirmTitle: "Confirmar transferencia",+ exportDatabaseConfirmDescription: "Revise el destino y las operaciones. Al confirmar, se empezará a escribir en la base de datos de destino.",+ exportDatabasePreviewDescription: "Revise esta transferencia. La vista previa no escribe en la base de datos de destino.",+ exportDatabaseSource: "Origen",+ exportDatabaseTarget: "Destino",+ exportDatabaseScope: "Volumen de datos",+ exportDatabaseLoadedScope: "Cargadas actualmente: {rows} filas · {columns} columnas",+ exportDatabaseOperations: "Operaciones previstas",+ exportDatabaseColumns: "Columnas del resultado de origen",+ exportDatabasePreviewScopeNote:+ "Se muestra el número de filas cargadas actualmente. Al ejecutar, se carga el resultado exportable completo y se comprueban el límite de filas, la tabla de destino y la compatibilidad de las columnas. El número de filas transferidas depende del resultado completo.",+ exportDatabasePlanCreate: "Crear tabla de destino → insertar filas (detener si la tabla existe; no eliminarla)",+ exportDatabasePlanAppend: "Añadir filas a la tabla de destino existente (INSERT), conservando los datos existentes",+ exportDatabasePlanOverwrite: "Eliminar TODAS las filas existentes del destino (DELETE sin WHERE) → insertar este resultado",+ exportDatabaseOverwriteWarning: "Sobrescribir elimina TODAS las filas existentes de la tabla de destino, incluidos los datos que no aparecen en este resultado. Verifique la conexión, la base de datos y la tabla de destino.",+ exportDatabaseBack: "Volver a la configuración",+ exportDatabaseConfirm: "Confirmar transferencia",+ exportDatabaseDescription: "{database} · {columns} columnas · {rows} filas cargadas",+ exportDatabaseExecutionFailed: "La base de datos de destino rechazó la sentencia.",+ exportDatabaseNonTransactionalTarget: "Escribir en una tabla MySQL existente requiere InnoDB para poder revertir la transferencia si falla.",+ exportDatabaseIdentityUnsupported: "Este controlador de destino no puede conservar de forma segura los valores explícitos de identidad y actualizar su secuencia. No se escribió ningún dato.",+ exportDatabaseTargetColumnMissing: "La tabla de destino no tiene una columna editable llamada {column}.",+ exportDatabaseTable: "Tabla de destino",+ exportDatabaseCreateTable: "Crear tabla de destino",+ exportDatabaseModeOverwrite: "Sobrescribir (DELETE + INSERT)",+ exportDatabaseDone: "Resultado de la consulta exportado a la base de datos",+ exportDatabaseCancelling: "Cancelando…",+ exportDatabaseCancelled: "Transferencia cancelada antes de escribir en la base de datos de destino.",+ exportDatabaseEmpty: "El resultado de la consulta está vacío o no está disponible.",+ exportDatabaseIncomplete: "El resultado de la consulta está incompleto. No se escribió ningún dato; vuelva a ejecutar la consulta para obtener el resultado completo antes de transferirlo.",+ exportDatabaseLoadComplete: "Este resultado utiliza un cursor activo o una transacción manual. Cargue todas las filas en la cuadrícula de resultados antes de transferirlo.",+ exportDatabaseRowLimit: "El resultado supera el límite de filas de exportación ({limit}); reduzca el resultado o aumente el límite antes de transferirlo.",+ exportDatabaseBatchTooLarge: "Una fila supera el límite de tamaño de la sentencia de transferencia (512 KiB). Reduzca el tamaño del valor antes de transferirla.",+ exportDatabasePreparing: "Preparando tabla de destino…",+ exportDatabaseCreating: "Creando tabla de destino…",+ exportDatabaseWriting: "Escribiendo el resultado de la consulta en la base de datos de destino…",+ exportDatabaseUnsupportedCollation: "El destino no admite estas intercalaciones y no hay una alternativa compatible conocida. No se creó ninguna tabla: {collations}",+ exportDatabaseCollationAdapted: "Intercalaciones adaptadas al destino: {changes}. La ordenación y la comparación de igualdad de cadenas pueden diferir del origen.",+ exportDatabaseDdlUnavailable: "No se pudo leer o reescribir de forma segura el DDL de la tabla de origen, por lo que se canceló la transferencia.",+ exportDatabaseNoWritableColumns: "El resultado no contiene columnas que se puedan escribir en la tabla de destino.",+ exportDatabaseTargetExists: "La tabla de destino {table} ya existe. Desactive «Crear tabla de destino» para escribir en ella o elija otra tabla.",+ exportDatabaseValueUnsupported: "El resultado contiene un valor que no se puede representar de forma segura en la base de datos de destino.",+ exportDatabaseCleanupFailed: "Error de transferencia: {message}. No se pudo eliminar la tabla temporal {table}: {error}.",exportCsv: "Exportar CSV",exportXlsx: "Exportar XLSX",exportXlsxWithSql: "Exportar XLSX con SQL",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex 692a11a5bd..e321ba73c4 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -2147,6 +2147,50 @@ export default withEnglishFallback({selectionCells: "{count} sel",clearSelection: "Bersihkan Pilihan",export: "Ekspor",+ exportDatabase: "Ekspor ke Basis Data",+ exportDatabasePreview: "Pratinjau eksekusi",+ exportDatabaseConfirmTitle: "Konfirmasi transfer",+ exportDatabaseConfirmDescription: "Periksa tujuan dan operasi. Konfirmasi akan memulai penulisan ke basis data tujuan.",+ exportDatabasePreviewDescription: "Tinjau transfer ini. Pratinjau tidak menulis ke basis data tujuan.",+ exportDatabaseSource: "Sumber",+ exportDatabaseTarget: "Tujuan",+ exportDatabaseScope: "Ukuran data",+ exportDatabaseLoadedScope: "Saat ini dimuat: {rows} baris · {columns} kolom",+ exportDatabaseOperations: "Operasi yang direncanakan",+ exportDatabaseColumns: "Kolom hasil sumber",+ exportDatabasePreviewScopeNote: "Ini menunjukkan jumlah baris yang saat ini dimuat. Eksekusi memuat seluruh hasil yang dapat diekspor dan memeriksa batas baris, tabel tujuan, serta kompatibilitas kolom. Jumlah baris yang ditransfer bergantung pada hasil lengkap.",+ exportDatabasePlanCreate: "Buat tabel tujuan → sisipkan baris (hentikan jika tabel sudah ada; jangan hapus tabel tersebut)",+ exportDatabasePlanAppend: "Tambahkan baris ke tabel tujuan yang sudah ada (INSERT), dengan mempertahankan data yang ada",+ exportDatabasePlanOverwrite: "Hapus SEMUA baris yang ada di tabel tujuan (DELETE tanpa WHERE) → sisipkan hasil ini",+ exportDatabaseOverwriteWarning: "Penimpaan menghapus SEMUA baris yang ada di tabel tujuan, termasuk data yang tidak terdapat dalam hasil ini. Periksa koneksi, basis data, dan tabel tujuan.",+ exportDatabaseBack: "Kembali ke pengaturan",+ exportDatabaseConfirm: "Konfirmasi transfer",+ exportDatabaseDescription: "{database} · {columns} kolom · {rows} baris dimuat",+ exportDatabaseExecutionFailed: "Basis data tujuan menolak pernyataan tersebut.",+ exportDatabaseNonTransactionalTarget: "Penulisan ke tabel MySQL yang sudah ada memerlukan InnoDB agar transaksi dapat dibatalkan jika transfer gagal.",+ exportDatabaseIdentityUnsupported: "Driver tujuan ini tidak dapat mempertahankan nilai identitas eksplisit dan memperbarui urutannya dengan aman. Tidak ada data yang ditulis.",+ exportDatabaseTargetColumnMissing: "Tabel tujuan tidak memiliki kolom yang dapat ditulis bernama {column}.",+ exportDatabaseTable: "Tabel tujuan",+ exportDatabaseCreateTable: "Buat tabel tujuan",+ exportDatabaseModeOverwrite: "Timpa (DELETE + INSERT)",+ exportDatabaseDone: "Hasil kueri diekspor ke basis data",+ exportDatabaseCancelling: "Membatalkan…",+ exportDatabaseCancelled: "Transfer dibatalkan sebelum menulis ke basis data tujuan.",+ exportDatabaseEmpty: "Hasil kueri kosong atau tidak tersedia.",+ exportDatabaseIncomplete: "Hasil kueri tidak lengkap. Tidak ada data yang ditulis; jalankan ulang kueri untuk mendapatkan hasil lengkap sebelum mentransfer.",+ exportDatabaseLoadComplete: "Hasil ini menggunakan kursor aktif atau transaksi manual. Muat semua baris di kisi hasil sebelum mentransfer.",+ exportDatabaseRowLimit: "Hasil kueri melebihi batas baris ekspor ({limit}); kurangi hasil atau naikkan batas sebelum mentransfer.",+ exportDatabaseBatchTooLarge: "Satu baris melebihi batas ukuran pernyataan transfer (512 KiB). Kurangi ukuran nilai sebelum mentransfer.",+ exportDatabasePreparing: "Menyiapkan tabel tujuan…",+ exportDatabaseCreating: "Membuat tabel tujuan…",+ exportDatabaseWriting: "Menulis hasil kueri ke basis data tujuan…",+ exportDatabaseUnsupportedCollation: "Tujuan tidak mendukung kolasi berikut dan tidak ada pengganti kompatibel yang diketahui. Tidak ada tabel yang dibuat: {collations}",+ exportDatabaseCollationAdapted: "Kolasi disesuaikan untuk tujuan: {changes}. Pengurutan dan perbandingan kesamaan string dapat berbeda dari sumber.",+ exportDatabaseDdlUnavailable: "DDL tabel sumber tidak dapat dibaca atau ditulis ulang dengan aman, sehingga transfer dibatalkan.",+ exportDatabaseNoWritableColumns: "Hasil tidak berisi kolom yang dapat ditulis ke tabel tujuan.",+ exportDatabaseTargetExists: "Tabel tujuan {table} sudah ada. Nonaktifkan «Buat tabel tujuan» untuk menulis ke tabel tersebut, atau pilih tabel lain.",+ exportDatabaseValueUnsupported: "Hasil berisi nilai yang tidak dapat direpresentasikan dengan aman di basis data tujuan.",+ exportDatabaseCleanupFailed: "Transfer gagal: {message}. Tabel sementara {table} tidak dapat dihapus: {error}.",exportCsv: "Ekspor CSV",exportXlsx: "Ekspor XLSX",exportXlsxWithSql: "Ekspor XLSX dengan SQL",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex ea79b70883..5f0704de78 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -2071,6 +2071,51 @@ export default withEnglishFallback({selectionCells: "{count} celle",clearSelection: "Cancella Selezione",export: "Esporta",+ exportDatabase: "Esporta nel database",+ exportDatabasePreview: "Anteprima esecuzione",+ exportDatabaseConfirmTitle: "Conferma trasferimento",+ exportDatabaseConfirmDescription: "Verifica la destinazione e le operazioni. La conferma avvierà la scrittura nel database di destinazione.",+ exportDatabasePreviewDescription: "Visualizza il riepilogo del trasferimento. L'anteprima non scrive nel database di destinazione.",+ exportDatabaseSource: "Origine",+ exportDatabaseTarget: "Destinazione",+ exportDatabaseScope: "Dimensione dei dati",+ exportDatabaseLoadedScope: "Attualmente caricate: {rows} righe · {columns} colonne",+ exportDatabaseOperations: "Operazioni previste",+ exportDatabaseColumns: "Colonne del risultato di origine",+ exportDatabasePreviewScopeNote:+ "Viene mostrato il numero di righe attualmente caricate. L'esecuzione carica il risultato esportabile completo e verifica i limiti di righe, la tabella di destinazione e la compatibilità delle colonne. Il numero di righe trasferite dipende dal risultato completo.",+ exportDatabasePlanCreate: "Crea tabella di destinazione → inserisci righe (interrompi se la tabella esiste; non eliminarla)",+ exportDatabasePlanAppend: "Aggiungi righe alla tabella di destinazione esistente (INSERT), mantenendo i dati esistenti",+ exportDatabasePlanOverwrite: "Elimina TUTTE le righe esistenti nella destinazione (DELETE senza WHERE) → inserisci questo risultato",+ exportDatabaseOverwriteWarning: "La sovrascrittura elimina TUTTE le righe esistenti nella tabella di destinazione, inclusi i dati assenti da questo risultato. Verifica la connessione, il database e la tabella di destinazione.",+ exportDatabaseBack: "Torna alle impostazioni",+ exportDatabaseConfirm: "Conferma trasferimento",+ exportDatabaseDescription: "{database} · {columns} colonne · {rows} righe caricate",+ exportDatabaseExecutionFailed: "Il database di destinazione ha rifiutato l'istruzione.",+ exportDatabaseNonTransactionalTarget: "La scrittura in una tabella MySQL esistente richiede InnoDB per poter annullare la transazione in caso di errore del trasferimento.",+ exportDatabaseIdentityUnsupported: "Questo driver di destinazione non può preservare in sicurezza i valori espliciti di identità e aggiornare la relativa sequenza. Nessun dato è stato scritto.",+ exportDatabaseTargetColumnMissing: "La tabella di destinazione non contiene una colonna scrivibile denominata {column}.",+ exportDatabaseTable: "Tabella di destinazione",+ exportDatabaseCreateTable: "Crea tabella di destinazione",+ exportDatabaseModeOverwrite: "Sovrascrivi (DELETE + INSERT)",+ exportDatabaseDone: "Risultato della query esportato nel database",+ exportDatabaseCancelling: "Annullamento…",+ exportDatabaseCancelled: "Trasferimento annullato prima della scrittura nel database di destinazione.",+ exportDatabaseEmpty: "Il risultato della query è vuoto o non disponibile.",+ exportDatabaseIncomplete: "Il risultato della query è incompleto. Nessun dato è stato scritto; riesegui la query per ottenere il risultato completo prima del trasferimento.",+ exportDatabaseLoadComplete: "Questo risultato utilizza un cursore attivo o una transazione manuale. Carica tutte le righe nella griglia dei risultati prima del trasferimento.",+ exportDatabaseRowLimit: "Il risultato della query supera il limite di righe esportabili ({limit}); riduci il risultato o aumenta il limite prima del trasferimento.",+ exportDatabaseBatchTooLarge: "Una singola riga supera il limite di dimensione dell'istruzione di trasferimento (512 KiB). Riduci la dimensione del valore prima del trasferimento.",+ exportDatabasePreparing: "Preparazione della tabella di destinazione…",+ exportDatabaseCreating: "Creazione della tabella di destinazione…",+ exportDatabaseWriting: "Scrittura del risultato della query nel database di destinazione…",+ exportDatabaseUnsupportedCollation: "La destinazione non supporta queste regole di confronto e non è disponibile un'alternativa compatibile nota. Nessuna tabella è stata creata: {collations}",+ exportDatabaseCollationAdapted: "Regole di confronto adattate alla destinazione: {changes}. L'ordinamento e il confronto di uguaglianza delle stringhe possono differire dall'origine.",+ exportDatabaseDdlUnavailable: "Impossibile leggere o riscrivere in sicurezza il DDL della tabella di origine. Il trasferimento è stato annullato.",+ exportDatabaseNoWritableColumns: "Il risultato non contiene colonne scrivibili nella tabella di destinazione.",+ exportDatabaseTargetExists: "La tabella di destinazione {table} esiste già. Disattiva «Crea tabella di destinazione» per scrivervi oppure scegli un'altra tabella.",+ exportDatabaseValueUnsupported: "Il risultato contiene un valore che non può essere rappresentato in sicurezza nel database di destinazione.",+ exportDatabaseCleanupFailed: "Trasferimento non riuscito: {message}. Impossibile eliminare la tabella temporanea {table}: {error}.",exportCsv: "Esporta CSV",exportXlsx: "Esporta XLSX",exportXlsxWithSql: "Esporta XLSX con SQL",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 05998e796e..bbd09f6342 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -2080,6 +2080,50 @@ export default withEnglishFallback({selectionCells: "{count} 個のセル",clearSelection: "選択をクリア",export: "エクスポート",+ exportDatabase: "データベースにエクスポート",+ exportDatabasePreview: "実行プレビュー",+ exportDatabaseConfirmTitle: "転送の確認",+ exportDatabaseConfirmDescription: "転送先と操作を確認してください。確定すると転送先データベースへの書き込みが始まります。",+ exportDatabasePreviewDescription: "今回の転送の概要を確認します。プレビューでは転送先データベースへの書き込みは行いません。",+ exportDatabaseSource: "転送元",+ exportDatabaseTarget: "転送先",+ exportDatabaseScope: "データ量",+ exportDatabaseLoadedScope: "読み込み済み: {rows} 行 · {columns} 列",+ exportDatabaseOperations: "実行予定の操作",+ exportDatabaseColumns: "転送元の結果列",+ exportDatabasePreviewScopeNote: "現在読み込み済みの行数を表示しています。実行時にはエクスポート可能な結果全体を読み込み、行数制限、転送先テーブル、列の互換性を確認します。実際の転送行数は結果全体に基づきます。",+ exportDatabasePlanCreate: "転送先テーブルを作成 → 行を挿入(テーブルが存在する場合は停止し、既存テーブルは削除しません)",+ exportDatabasePlanAppend: "既存の転送先テーブルに行を追加(INSERT)し、既存データを保持",+ exportDatabasePlanOverwrite: "転送先テーブルの既存の全行を削除(WHERE なしの DELETE)→ 今回の結果を挿入",+ exportDatabaseOverwriteWarning: "上書きすると、今回の結果に含まれないデータも含め、転送先テーブルの既存の全行が削除されます。転送先の接続、データベース、テーブルを確認してください。",+ exportDatabaseBack: "設定に戻る",+ exportDatabaseConfirm: "転送を確定",+ exportDatabaseDescription: "{database} · {columns} 列 · {rows} 行読み込み済み",+ exportDatabaseExecutionFailed: "転送先データベースでステートメントの実行に失敗しました。",+ exportDatabaseNonTransactionalTarget: "既存の MySQL テーブルへの書き込みには、転送失敗時にロールバックできるよう InnoDB が必要です。",+ exportDatabaseIdentityUnsupported: "この転送先ドライバーでは ID 列の値の保持とシーケンスの更新を安全に行えません。データは書き込まれていません。",+ exportDatabaseTargetColumnMissing: "転送先テーブルに {column} という書き込み可能な列がありません。",+ exportDatabaseTable: "転送先テーブル",+ exportDatabaseCreateTable: "転送先テーブルを作成",+ exportDatabaseModeOverwrite: "上書き(DELETE + INSERT)",+ exportDatabaseDone: "クエリ結果をデータベースにエクスポートしました",+ exportDatabaseCancelling: "キャンセル中…",+ exportDatabaseCancelled: "転送先データベースへの書き込み前に転送をキャンセルしました。",+ exportDatabaseEmpty: "クエリ結果が空か、利用できません。",+ exportDatabaseIncomplete: "クエリ結果が不完全です。データは書き込まれていません。クエリを再実行して完全な結果を取得してから転送してください。",+ exportDatabaseLoadComplete: "この結果はアクティブなカーソルまたは手動トランザクションを使用しています。結果グリッドですべての行を読み込んでから転送してください。",+ exportDatabaseRowLimit: "クエリ結果がエクスポート行数の上限({limit})を超えています。結果を絞り込むか上限を増やしてから転送してください。",+ exportDatabaseBatchTooLarge: "1 行が転送ステートメントのサイズ上限(512 KiB)を超えています。値のサイズを小さくしてから転送してください。",+ exportDatabasePreparing: "転送先テーブルを準備中…",+ exportDatabaseCreating: "転送先テーブルを作成中…",+ exportDatabaseWriting: "クエリ結果を転送先データベースに書き込み中…",+ exportDatabaseUnsupportedCollation: "転送先は次の照合順序に対応しておらず、既知の互換性のある代替もありません。テーブルは作成されていません: {collations}",+ exportDatabaseCollationAdapted: "転送先に合わせて照合順序を調整しました: {changes}。並べ替えや文字列の等価判定が転送元と異なる場合があります。",+ exportDatabaseDdlUnavailable: "転送元テーブルの DDL を読み取るか安全に書き換えることができないため、転送をキャンセルしました。",+ exportDatabaseNoWritableColumns: "結果に転送先テーブルへ書き込み可能な列がありません。",+ exportDatabaseTargetExists: "転送先テーブル {table} は既に存在します。「転送先テーブルを作成」をオフにして書き込むか、別のテーブルを選択してください。",+ exportDatabaseValueUnsupported: "結果に転送先データベースで安全に表現できない値が含まれています。",+ exportDatabaseCleanupFailed: "転送に失敗しました: {message}。一時テーブル {table} を削除できませんでした: {error}。",exportCsv: "CSVエクスポート",exportXlsx: "XLSXエクスポート",exportXlsxWithSql: "SQL付きXLSXをエクスポート",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex afd3ea8148..31d93401b1 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -2120,6 +2120,50 @@ export default withEnglishFallback({selectionCells: "{count}개 셀",clearSelection: "선택 해제",export: "내보내기",+ exportDatabase: "데이터베이스로 내보내기",+ exportDatabasePreview: "실행 미리보기",+ exportDatabaseConfirmTitle: "전송 확인",+ exportDatabaseConfirmDescription: "대상 위치와 작업을 확인하세요. 확인하면 대상 데이터베이스에 쓰기를 시작합니다.",+ exportDatabasePreviewDescription: "이번 전송의 개요를 확인합니다. 미리보기는 대상 데이터베이스에 데이터를 쓰지 않습니다.",+ exportDatabaseSource: "원본",+ exportDatabaseTarget: "대상 위치",+ exportDatabaseScope: "데이터 규모",+ exportDatabaseLoadedScope: "현재 로드됨: {rows}개 행 · {columns}개 열",+ exportDatabaseOperations: "예정된 작업",+ exportDatabaseColumns: "원본 결과 열",+ exportDatabasePreviewScopeNote: "현재 로드된 행 수를 표시합니다. 실행 시 내보낼 수 있는 전체 결과를 로드하고 행 수 제한, 대상 테이블 및 열 호환성을 확인합니다. 실제 전송 행 수는 전체 결과에 따라 결정됩니다.",+ exportDatabasePlanCreate: "대상 테이블 생성 → 행 삽입 (테이블이 이미 있으면 중단하며 기존 테이블을 삭제하지 않음)",+ exportDatabasePlanAppend: "기존 대상 테이블에 행 추가 (INSERT), 기존 데이터 유지",+ exportDatabasePlanOverwrite: "대상 테이블의 기존 행 전체 삭제 (WHERE 없는 DELETE) → 이번 결과 삽입",+ exportDatabaseOverwriteWarning: "덮어쓰기는 이번 결과에 없는 데이터를 포함하여 대상 테이블의 기존 행을 모두 삭제합니다. 대상 연결, 데이터베이스 및 테이블을 확인하세요.",+ exportDatabaseBack: "설정으로 돌아가기",+ exportDatabaseConfirm: "전송 확인",+ exportDatabaseDescription: "{database} · {columns}개 열 · {rows}개 행 로드됨",+ exportDatabaseExecutionFailed: "대상 데이터베이스에서 구문 실행에 실패했습니다.",+ exportDatabaseNonTransactionalTarget: "전송 실패 시 롤백하려면 기존 MySQL 테이블에 쓰는 데 InnoDB 엔진이 필요합니다.",+ exportDatabaseIdentityUnsupported: "이 대상 드라이버는 명시적 ID 값을 안전하게 유지하고 시퀀스를 갱신할 수 없습니다. 데이터를 쓰지 않았습니다.",+ exportDatabaseTargetColumnMissing: "대상 테이블에 {column} 이름의 쓰기 가능한 열이 없습니다.",+ exportDatabaseTable: "대상 테이블",+ exportDatabaseCreateTable: "대상 테이블 생성",+ exportDatabaseModeOverwrite: "덮어쓰기 (DELETE + INSERT)",+ exportDatabaseDone: "쿼리 결과를 데이터베이스로 내보냈습니다",+ exportDatabaseCancelling: "취소 중…",+ exportDatabaseCancelled: "대상 데이터베이스에 쓰기 전에 전송을 취소했습니다.",+ exportDatabaseEmpty: "쿼리 결과가 비어 있거나 사용할 수 없습니다.",+ exportDatabaseIncomplete: "쿼리 결과가 불완전합니다. 데이터를 쓰지 않았습니다. 쿼리를 다시 실행하여 전체 결과를 얻은 후 전송하세요.",+ exportDatabaseLoadComplete: "이 결과는 활성 커서 또는 수동 트랜잭션을 사용합니다. 결과 그리드에서 모든 행을 로드한 후 전송하세요.",+ exportDatabaseRowLimit: "쿼리 결과가 내보내기 행 수 제한({limit})을 초과합니다. 결과를 줄이거나 제한을 늘린 후 전송하세요.",+ exportDatabaseBatchTooLarge: "단일 행이 전송 구문 크기 제한(512 KiB)을 초과합니다. 값의 크기를 줄인 후 전송하세요.",+ exportDatabasePreparing: "대상 테이블 준비 중…",+ exportDatabaseCreating: "대상 테이블 생성 중…",+ exportDatabaseWriting: "쿼리 결과를 대상 데이터베이스에 쓰는 중…",+ exportDatabaseUnsupportedCollation: "대상이 다음 정렬 규칙을 지원하지 않으며 알려진 호환 대안도 없습니다. 테이블을 생성하지 않았습니다: {collations}",+ exportDatabaseCollationAdapted: "대상에 맞게 정렬 규칙을 조정했습니다: {changes}. 정렬 및 문자열 동일성 비교가 원본과 다를 수 있습니다.",+ exportDatabaseDdlUnavailable: "원본 테이블의 DDL을 읽거나 안전하게 수정할 수 없어 전송을 취소했습니다.",+ exportDatabaseNoWritableColumns: "결과에 대상 테이블에 쓸 수 있는 열이 없습니다.",+ exportDatabaseTargetExists: "대상 테이블 {table}이(가) 이미 있습니다. 쓰려면 '대상 테이블 생성'을 해제하거나 다른 테이블을 선택하세요.",+ exportDatabaseValueUnsupported: "결과에 대상 데이터베이스에서 안전하게 표현할 수 없는 값이 포함되어 있습니다.",+ exportDatabaseCleanupFailed: "전송 실패: {message}. 임시 테이블 {table}을(를) 삭제할 수 없습니다: {error}.",exportCsv: "CSV 내보내기",exportXlsx: "XLSX 내보내기",exportXlsxWithSql: "SQL 포함 XLSX 내보내기",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 2e57d25dc1..a521d7ce0d 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -2073,6 +2073,50 @@ export default withEnglishFallback({selectionCells: "{count} células",clearSelection: "Limpar Seleção",export: "Exportar",+ exportDatabase: "Exportar para banco de dados",+ exportDatabasePreview: "Prévia da execução",+ exportDatabaseConfirmTitle: "Confirmar transferência",+ exportDatabaseConfirmDescription: "Revise o destino e as operações. Ao confirmar, a gravação no banco de dados de destino será iniciada.",+ exportDatabasePreviewDescription: "Revise esta transferência. A prévia não grava no banco de dados de destino.",+ exportDatabaseSource: "Origem",+ exportDatabaseTarget: "Destino",+ exportDatabaseScope: "Volume de dados",+ exportDatabaseLoadedScope: "Carregadas atualmente: {rows} linhas · {columns} colunas",+ exportDatabaseOperations: "Operações previstas",+ exportDatabaseColumns: "Colunas do resultado de origem",+ exportDatabasePreviewScopeNote: "Este é o número de linhas carregadas atualmente. A execução carrega o resultado exportável completo e verifica o limite de linhas, a tabela de destino e a compatibilidade das colunas. O número de linhas transferidas depende do resultado completo.",+ exportDatabasePlanCreate: "Criar tabela de destino → inserir linhas (interromper se a tabela existir; não excluí-la)",+ exportDatabasePlanAppend: "Adicionar linhas à tabela de destino existente (INSERT), preservando os dados existentes",+ exportDatabasePlanOverwrite: "Excluir TODAS as linhas existentes do destino (DELETE sem WHERE) → inserir este resultado",+ exportDatabaseOverwriteWarning: "A sobrescrita exclui TODAS as linhas existentes na tabela de destino, inclusive os dados ausentes deste resultado. Verifique a conexão, o banco de dados e a tabela de destino.",+ exportDatabaseBack: "Voltar às configurações",+ exportDatabaseConfirm: "Confirmar transferência",+ exportDatabaseDescription: "{database} · {columns} colunas · {rows} linhas carregadas",+ exportDatabaseExecutionFailed: "O banco de dados de destino rejeitou a instrução.",+ exportDatabaseNonTransactionalTarget: "A gravação em uma tabela MySQL existente requer InnoDB para permitir a reversão em caso de falha na transferência.",+ exportDatabaseIdentityUnsupported: "Este driver de destino não pode preservar com segurança os valores explícitos de identidade e atualizar sua sequência. Nenhum dado foi gravado.",+ exportDatabaseTargetColumnMissing: "A tabela de destino não possui uma coluna gravável chamada {column}.",+ exportDatabaseTable: "Tabela de destino",+ exportDatabaseCreateTable: "Criar tabela de destino",+ exportDatabaseModeOverwrite: "Sobrescrever (DELETE + INSERT)",+ exportDatabaseDone: "Resultado da consulta exportado para o banco de dados",+ exportDatabaseCancelling: "Cancelando…",+ exportDatabaseCancelled: "Transferência cancelada antes da gravação no banco de dados de destino.",+ exportDatabaseEmpty: "O resultado da consulta está vazio ou indisponível.",+ exportDatabaseIncomplete: "O resultado da consulta está incompleto. Nenhum dado foi gravado; execute a consulta novamente para obter o resultado completo antes de transferir.",+ exportDatabaseLoadComplete: "Este resultado usa um cursor ativo ou uma transação manual. Carregue todas as linhas na grade de resultados antes de transferir.",+ exportDatabaseRowLimit: "O resultado excede o limite de linhas de exportação ({limit}); reduza o resultado ou aumente o limite antes de transferir.",+ exportDatabaseBatchTooLarge: "Uma única linha excede o limite de tamanho da instrução de transferência (512 KiB). Reduza o tamanho do valor antes de transferir.",+ exportDatabasePreparing: "Preparando tabela de destino…",+ exportDatabaseCreating: "Criando tabela de destino…",+ exportDatabaseWriting: "Gravando o resultado da consulta no banco de dados de destino…",+ exportDatabaseUnsupportedCollation: "O destino não oferece suporte a estas regras de ordenação e não há uma alternativa compatível conhecida. Nenhuma tabela foi criada: {collations}",+ exportDatabaseCollationAdapted: "Regras de ordenação adaptadas ao destino: {changes}. A ordenação e a comparação de igualdade de strings podem diferir da origem.",+ exportDatabaseDdlUnavailable: "Não foi possível ler ou reescrever com segurança o DDL da tabela de origem, portanto a transferência foi cancelada.",+ exportDatabaseNoWritableColumns: "O resultado não contém colunas que possam ser gravadas na tabela de destino.",+ exportDatabaseTargetExists: "A tabela de destino {table} já existe. Desative «Criar tabela de destino» para gravar nela ou escolha outra tabela.",+ exportDatabaseValueUnsupported: "O resultado contém um valor que não pode ser representado com segurança no banco de dados de destino.",+ exportDatabaseCleanupFailed: "Falha na transferência: {message}. Não foi possível remover a tabela temporária {table}: {error}.",exportCsv: "Exportar CSV",exportXlsx: "Exportar XLSX",exportXlsxWithSql: "Exportar XLSX com SQL",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex cccae06cd2..07e240d8ea 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -2210,6 +2210,50 @@ export default withEnglishFallback({selectionCells: "Ячеек: {count}",clearSelection: "Снять выделение",export: "Экспорт",+ exportDatabase: "Экспорт в базу данных",+ exportDatabasePreview: "Предпросмотр выполнения",+ exportDatabaseConfirmTitle: "Подтверждение переноса",+ exportDatabaseConfirmDescription: "Проверьте назначение и операции. После подтверждения начнётся запись в целевую базу данных.",+ exportDatabasePreviewDescription: "Просмотрите сведения о переносе. Предпросмотр не записывает данные в целевую базу данных.",+ exportDatabaseSource: "Источник",+ exportDatabaseTarget: "Назначение",+ exportDatabaseScope: "Объём данных",+ exportDatabaseLoadedScope: "Загружено строк: {rows} · Столбцов: {columns}",+ exportDatabaseOperations: "Планируемые операции",+ exportDatabaseColumns: "Столбцы исходного результата",+ exportDatabasePreviewScopeNote: "Показано количество уже загруженных строк. При выполнении будет загружен полный доступный для экспорта результат и проверены ограничение строк, целевая таблица и совместимость столбцов. Фактическое количество перенесённых строк зависит от полного результата.",+ exportDatabasePlanCreate: "Создать целевую таблицу → вставить строки (остановиться, если таблица существует; не удалять её)",+ exportDatabasePlanAppend: "Добавить строки в существующую целевую таблицу (INSERT), сохранив имеющиеся данные",+ exportDatabasePlanOverwrite: "Удалить ВСЕ имеющиеся строки целевой таблицы (DELETE без WHERE) → вставить этот результат",+ exportDatabaseOverwriteWarning: "Перезапись удалит ВСЕ имеющиеся строки целевой таблицы, включая данные, отсутствующие в этом результате. Проверьте целевое подключение, базу данных и таблицу.",+ exportDatabaseBack: "Вернуться к настройкам",+ exportDatabaseConfirm: "Подтвердить перенос",+ exportDatabaseDescription: "{database} · Столбцов: {columns} · Загружено строк: {rows}",+ exportDatabaseExecutionFailed: "Целевая база данных отклонила инструкцию.",+ exportDatabaseNonTransactionalTarget: "Для записи в существующую таблицу MySQL требуется InnoDB, чтобы можно было откатить транзакцию при сбое переноса.",+ exportDatabaseIdentityUnsupported: "Этот целевой драйвер не может безопасно сохранить явные значения столбца идентификаторов и обновить их последовательность. Данные не записаны.",+ exportDatabaseTargetColumnMissing: "В целевой таблице нет доступного для записи столбца с именем {column}.",+ exportDatabaseTable: "Целевая таблица",+ exportDatabaseCreateTable: "Создать целевую таблицу",+ exportDatabaseModeOverwrite: "Перезаписать (DELETE + INSERT)",+ exportDatabaseDone: "Результат запроса экспортирован в базу данных",+ exportDatabaseCancelling: "Отмена…",+ exportDatabaseCancelled: "Перенос отменён до записи в целевую базу данных.",+ exportDatabaseEmpty: "Результат запроса пуст или недоступен.",+ exportDatabaseIncomplete: "Результат запроса неполный. Данные не записаны; повторите запрос и получите полный результат перед переносом.",+ exportDatabaseLoadComplete: "Этот результат использует активный курсор или ручную транзакцию. Загрузите все строки в таблицу результатов перед переносом.",+ exportDatabaseRowLimit: "Результат запроса превышает ограничение строк экспорта ({limit}); сократите результат или увеличьте ограничение перед переносом.",+ exportDatabaseBatchTooLarge: "Одна строка превышает ограничение размера инструкции переноса (512 KiB). Уменьшите размер значения перед переносом.",+ exportDatabasePreparing: "Подготовка целевой таблицы…",+ exportDatabaseCreating: "Создание целевой таблицы…",+ exportDatabaseWriting: "Запись результата запроса в целевую базу данных…",+ exportDatabaseUnsupportedCollation: "Целевая база не поддерживает следующие правила сравнения, и известной совместимой замены нет. Таблица не создана: {collations}",+ exportDatabaseCollationAdapted: "Правила сравнения адаптированы для целевой базы: {changes}. Сортировка и проверка равенства строк могут отличаться от источника.",+ exportDatabaseDdlUnavailable: "Не удалось прочитать или безопасно переписать DDL исходной таблицы, поэтому перенос отменён.",+ exportDatabaseNoWritableColumns: "Результат не содержит столбцов, доступных для записи в целевую таблицу.",+ exportDatabaseTargetExists: "Целевая таблица {table} уже существует. Отключите «Создать целевую таблицу», чтобы записать в неё данные, или выберите другую таблицу.",+ exportDatabaseValueUnsupported: "Результат содержит значение, которое нельзя безопасно представить в целевой базе данных.",+ exportDatabaseCleanupFailed: "Ошибка переноса: {message}. Не удалось удалить временную таблицу {table}: {error}.",exportCsv: "Экспорт CSV",exportXlsx: "Экспорт XLSX",exportXlsxWithSql: "Экспорт XLSX с SQL",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 1819c27370..7d31b8012c 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -1874,6 +1874,50 @@ export default withEnglishFallback({selectionCells: "{count} hücre",clearSelection: "Seçimi Temizle",export: "Dışa Aktar",+ exportDatabase: "Veritabanına aktar",+ exportDatabasePreview: "İşlem önizlemesi",+ exportDatabaseConfirmTitle: "Aktarımı onayla",+ exportDatabaseConfirmDescription: "Hedefi ve işlemleri kontrol edin. Onaylandığında hedef veritabanına yazma işlemi başlayacaktır.",+ exportDatabasePreviewDescription: "Bu aktarımı inceleyin. Önizleme hedef veritabanına veri yazmaz.",+ exportDatabaseSource: "Kaynak",+ exportDatabaseTarget: "Hedef",+ exportDatabaseScope: "Veri boyutu",+ exportDatabaseLoadedScope: "Şu anda yüklenen: {rows} satır · {columns} sütun",+ exportDatabaseOperations: "Planlanan işlemler",+ exportDatabaseColumns: "Kaynak sonuç sütunları",+ exportDatabasePreviewScopeNote: "Şu anda yüklenen satır sayısı gösterilir. İşlem sırasında aktarılabilir sonucun tamamı yüklenir; satır sınırları, hedef tablo ve sütun uyumluluğu kontrol edilir. Aktarılan gerçek satır sayısı tam sonuca bağlıdır.",+ exportDatabasePlanCreate: "Hedef tabloyu oluştur → satırları ekle (tablo varsa dur; mevcut tabloyu silme)",+ exportDatabasePlanAppend: "Mevcut verileri koruyarak hedef tabloya satır ekle (INSERT)",+ exportDatabasePlanOverwrite: "Hedef tablodaki mevcut TÜM satırları sil (WHERE olmadan DELETE) → bu sonucu ekle",+ exportDatabaseOverwriteWarning: "Üzerine yazma, bu sonuçta bulunmayan veriler dahil hedef tablodaki mevcut TÜM satırları siler. Hedef bağlantıyı, veritabanını ve tabloyu kontrol edin.",+ exportDatabaseBack: "Ayarlara dön",+ exportDatabaseConfirm: "Aktarımı onayla",+ exportDatabaseDescription: "{database} · {columns} sütun · {rows} satır yüklendi",+ exportDatabaseExecutionFailed: "Hedef veritabanı SQL ifadesini reddetti.",+ exportDatabaseNonTransactionalTarget: "Mevcut bir MySQL tablosuna yazmak, aktarım başarısız olursa geri alınabilmesi için InnoDB gerektirir.",+ exportDatabaseIdentityUnsupported: "Bu hedef sürücü, açıkça belirtilen kimlik değerlerini güvenle koruyup bunların dizisini güncelleyemiyor. Hiçbir veri yazılmadı.",+ exportDatabaseTargetColumnMissing: "Hedef tabloda {column} adlı yazılabilir bir sütun yok.",+ exportDatabaseTable: "Hedef tablo",+ exportDatabaseCreateTable: "Hedef tabloyu oluştur",+ exportDatabaseModeOverwrite: "Üzerine yaz (DELETE + INSERT)",+ exportDatabaseDone: "Sorgu sonucu veritabanına aktarıldı",+ exportDatabaseCancelling: "İptal ediliyor…",+ exportDatabaseCancelled: "Hedef veritabanına yazılmadan önce aktarım iptal edildi.",+ exportDatabaseEmpty: "Sorgu sonucu boş veya kullanılamıyor.",+ exportDatabaseIncomplete: "Sorgu sonucu eksik. Hiçbir veri yazılmadı; aktarmadan önce sorguyu yeniden çalıştırıp tam sonucu alın.",+ exportDatabaseLoadComplete: "Bu sonuç etkin bir imleç veya elle yönetilen bir işlem kullanıyor. Aktarmadan önce sonuç tablosundaki tüm satırları yükleyin.",+ exportDatabaseRowLimit: "Sorgu sonucu dışa aktarma satır sınırını ({limit}) aşıyor; aktarmadan önce sonucu daraltın veya sınırı artırın.",+ exportDatabaseBatchTooLarge: "Tek bir satır, aktarım ifadesinin boyut sınırını (512 KiB) aşıyor. Aktarmadan önce değer boyutunu küçültün.",+ exportDatabasePreparing: "Hedef tablo hazırlanıyor…",+ exportDatabaseCreating: "Hedef tablo oluşturuluyor…",+ exportDatabaseWriting: "Sorgu sonucu hedef veritabanına yazılıyor…",+ exportDatabaseUnsupportedCollation: "Hedef şu karşılaştırma düzenlerini desteklemiyor ve bilinen uyumlu bir alternatif yok. Tablo oluşturulmadı: {collations}",+ exportDatabaseCollationAdapted: "Karşılaştırma düzenleri hedefe uyarlandı: {changes}. Sıralama ve metin eşitliği karşılaştırmaları kaynaktan farklı olabilir.",+ exportDatabaseDdlUnavailable: "Kaynak tablo DDL'i okunamadığı veya güvenle yeniden yazılamadığı için aktarım iptal edildi.",+ exportDatabaseNoWritableColumns: "Sonuç, hedef tabloya yazılabilecek sütun içermiyor.",+ exportDatabaseTargetExists: "Hedef tablo {table} zaten var. Bu tabloya yazmak için «Hedef tabloyu oluştur» seçeneğini kapatın veya başka bir tablo seçin.",+ exportDatabaseValueUnsupported: "Sonuç, hedef veritabanında güvenle temsil edilemeyen bir değer içeriyor.",+ exportDatabaseCleanupFailed: "Aktarım başarısız: {message}. Geçici tablo {table} kaldırılamadı: {error}.",exportCsv: "CSV Dışa Aktar",exportXlsx: "XLSX Dışa Aktar",exportXlsxWithSql: "SQL ile XLSX Dışa Aktar",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 78e16f6fac..91e247434e 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -2246,6 +2246,50 @@ export default withEnglishFallback({selectionCells: "{count} 个单元",clearSelection: "清除选区",export: "导出",+ exportDatabase: "导出到数据库",+ exportDatabasePreview: "执行预览",+ exportDatabaseConfirmTitle: "确认执行传输",+ exportDatabaseConfirmDescription: "请核对目标位置及执行操作,确认后将开始写入目标数据库。",+ exportDatabasePreviewDescription: "查看本次传输的概览;预览不会写入目标数据库。",+ exportDatabaseSource: "数据来源",+ exportDatabaseTarget: "目标位置",+ exportDatabaseScope: "数据规模",+ exportDatabaseLoadedScope: "当前已加载 {rows} 行 · {columns} 列",+ exportDatabaseOperations: "预计操作",+ exportDatabaseColumns: "源结果列",+ exportDatabasePreviewScopeNote: "这里展示当前结果的已加载行数。执行时会读取完整可导出结果,并检查行数限制、目标表及字段兼容性,实际传输行数以完整结果为准。",+ exportDatabasePlanCreate: "创建目标表 → 插入数据(若表已存在则停止,不删除已有表)",+ exportDatabasePlanAppend: "向已有目标表追加数据(INSERT),保留原有数据",+ exportDatabasePlanOverwrite: "删除目标表全部已有数据(DELETE,无 WHERE 条件)→ 插入本次结果",+ exportDatabaseOverwriteWarning: "覆盖操作会删除目标表全部已有数据,包括本次结果未包含的数据。请确认目标连接、数据库和表名无误。",+ exportDatabaseBack: "返回修改",+ exportDatabaseConfirm: "确认传输",+ exportDatabaseDescription: "{database} · {columns} 列 · 已加载 {rows} 行",+ exportDatabaseExecutionFailed: "目标数据库执行语句失败。",+ exportDatabaseNonTransactionalTarget: "写入已有 MySQL 表需要使用 InnoDB 引擎,以便传输失败时回滚。",+ exportDatabaseIdentityUnsupported: "当前目标驱动尚不能安全保留标识列的值并同步其序列,未写入任何数据。",+ exportDatabaseTargetColumnMissing: "目标表中不存在名为 {column} 的可写列。",+ exportDatabaseTable: "目标表",+ exportDatabaseCreateTable: "创建目标表",+ exportDatabaseModeOverwrite: "覆盖(DELETE + INSERT)",+ exportDatabaseDone: "查询结果已导出到数据库",+ exportDatabaseCancelling: "正在取消…",+ exportDatabaseCancelled: "已取消传输,未向目标数据库写入数据。",+ exportDatabaseEmpty: "查询结果为空或不可用。",+ exportDatabaseIncomplete: "查询结果不完整,未写入任何数据。请重新查询并取得完整结果后再传输。",+ exportDatabaseLoadComplete: "当前结果使用了活动游标或手动事务,请在结果网格中加载全部行后再传输。",+ exportDatabaseRowLimit: "查询结果超过导出行数上限({limit}),请缩小结果集或提高上限后再传输。",+ exportDatabaseBatchTooLarge: "单行数据超过传输语句大小限制(512 KiB),请缩小该行数据后重试。",+ exportDatabasePreparing: "正在准备目标表…",+ exportDatabaseCreating: "正在创建目标表…",+ exportDatabaseWriting: "正在将查询结果写入目标数据库…",+ exportDatabaseUnsupportedCollation: "目标数据库不支持以下排序规则,且没有已知兼容替代,尚未创建表:{collations}",+ exportDatabaseCollationAdapted: "已适配目标数据库排序规则:{changes}。排序和字符串相等判断可能与源库不同。",+ exportDatabaseDdlUnavailable: "无法读取或安全改写源表 DDL,传输已取消。",+ exportDatabaseNoWritableColumns: "查询结果没有可以写入目标表的列。",+ exportDatabaseTargetExists: "目标表 {table} 已存在。请取消勾选“创建目标表”后写入,或更换目标表名称。",+ exportDatabaseValueUnsupported: "查询结果中存在无法在目标数据库安全表示的值,传输已取消。",+ exportDatabaseCleanupFailed: "传输失败:{message}。临时表 {table} 未能自动清理:{error}。",exportCsv: "导出 CSV",exportXlsx: "导出 XLSX",exportXlsxWithSql: "导出 XLSX(含 SQL)",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 00f8a00cbd..c673433820 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -2073,6 +2073,50 @@ export default withEnglishFallback({selectionCells: "{count} 個儲存格",clearSelection: "清除選區",export: "匯出",+ exportDatabase: "匯出至資料庫",+ exportDatabasePreview: "執行預覽",+ exportDatabaseConfirmTitle: "確認執行傳輸",+ exportDatabaseConfirmDescription: "請核對目標位置及執行操作,確認後將開始寫入目標資料庫。",+ exportDatabasePreviewDescription: "查看本次傳輸的概覽;預覽不會寫入目標資料庫。",+ exportDatabaseSource: "資料來源",+ exportDatabaseTarget: "目標位置",+ exportDatabaseScope: "資料規模",+ exportDatabaseLoadedScope: "目前已載入 {rows} 列 · {columns} 欄",+ exportDatabaseOperations: "預計操作",+ exportDatabaseColumns: "來源結果欄位",+ exportDatabasePreviewScopeNote: "此處顯示目前已載入的列數。執行時會讀取完整可匯出結果,並檢查列數限制、目標資料表及欄位相容性,實際傳輸列數以完整結果為準。",+ exportDatabasePlanCreate: "建立目標資料表 → 插入資料(若資料表已存在則停止,不刪除既有資料表)",+ exportDatabasePlanAppend: "向既有目標資料表新增資料(INSERT),保留原有資料",+ exportDatabasePlanOverwrite: "刪除目標資料表全部既有資料(DELETE,無 WHERE 條件)→ 插入本次結果",+ exportDatabaseOverwriteWarning: "覆寫操作會刪除目標資料表全部既有資料,包括本次結果未包含的資料。請確認目標連線、資料庫和資料表名稱無誤。",+ exportDatabaseBack: "返回修改",+ exportDatabaseConfirm: "確認傳輸",+ exportDatabaseDescription: "{database} · {columns} 欄 · 已載入 {rows} 列",+ exportDatabaseExecutionFailed: "目標資料庫執行陳述式失敗。",+ exportDatabaseNonTransactionalTarget: "寫入既有 MySQL 資料表需要使用 InnoDB 引擎,以便傳輸失敗時回復交易。",+ exportDatabaseIdentityUnsupported: "目前目標驅動程式無法安全保留識別欄位的值並同步其序列,未寫入任何資料。",+ exportDatabaseTargetColumnMissing: "目標資料表中不存在名為 {column} 的可寫入欄位。",+ exportDatabaseTable: "目標資料表",+ exportDatabaseCreateTable: "建立目標資料表",+ exportDatabaseModeOverwrite: "覆寫(DELETE + INSERT)",+ exportDatabaseDone: "查詢結果已匯出至資料庫",+ exportDatabaseCancelling: "正在取消…",+ exportDatabaseCancelled: "已取消傳輸,未向目標資料庫寫入資料。",+ exportDatabaseEmpty: "查詢結果為空或無法使用。",+ exportDatabaseIncomplete: "查詢結果不完整,未寫入任何資料。請重新查詢並取得完整結果後再傳輸。",+ exportDatabaseLoadComplete: "目前結果使用了作用中的游標或手動交易,請在結果網格中載入全部資料列後再傳輸。",+ exportDatabaseRowLimit: "查詢結果超過匯出列數上限({limit}),請縮小結果集或提高上限後再傳輸。",+ exportDatabaseBatchTooLarge: "單列資料超過傳輸陳述式大小限制(512 KiB),請縮小該列資料後重試。",+ exportDatabasePreparing: "正在準備目標資料表…",+ exportDatabaseCreating: "正在建立目標資料表…",+ exportDatabaseWriting: "正在將查詢結果寫入目標資料庫…",+ exportDatabaseUnsupportedCollation: "目標資料庫不支援以下定序,且沒有已知相容替代,尚未建立資料表:{collations}",+ exportDatabaseCollationAdapted: "已調整為目標資料庫支援的定序:{changes}。排序和字串相等判斷可能與來源資料庫不同。",+ exportDatabaseDdlUnavailable: "無法讀取或安全改寫來源資料表 DDL,傳輸已取消。",+ exportDatabaseNoWritableColumns: "查詢結果沒有可以寫入目標資料表的欄位。",+ exportDatabaseTargetExists: "目標資料表 {table} 已存在。請取消勾選「建立目標資料表」後寫入,或更換目標資料表名稱。",+ exportDatabaseValueUnsupported: "查詢結果中存在無法在目標資料庫安全表示的值,傳輸已取消。",+ exportDatabaseCleanupFailed: "傳輸失敗:{message}。暫存資料表 {table} 無法自動清理:{error}。",exportCsv: "匯出 CSV",exportXlsx: "匯出 XLSX",exportXlsxWithSql: "匯出 XLSX(含 SQL)",diff --git a/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts b/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.tsindex 2dbbcd6d4b..0a2689a087 100644--- a/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts@@ -285,7 +285,7 @@ describe("jdbc dialect inference", () => {expect(transferDatabaseTypeForConnection(undefined)).toBeUndefined();expect(transferDatabaseTypeForConnection({ db_type: "mysql" })).toBe("mysql");expect(transferDatabaseTypeForConnection({ db_type: "postgres" })).toBe("postgres");- expect(transferDatabaseTypeForConnection({ db_type: "gbase" })).toBe("mysql");+ expect(transferDatabaseTypeForConnection({ db_type: "gbase" })).toBeUndefined();expect(transferDatabaseTypeForConnection({ db_type: "jdbc", connection_string: "jdbc:gbase://localhost:5258/dbx_test" })).toBe("gbase");// A generic-JDBC Doris URL keeps its raw db_type (never admitted), matching// the pre-effective-type behavior for unknown jdbc connections.diff --git a/apps/desktop/src/lib/dataGrid/dataGridPagination.ts b/apps/desktop/src/lib/dataGrid/dataGridPagination.tsindex 523407c139..bd687db0f9 100644--- a/apps/desktop/src/lib/dataGrid/dataGridPagination.ts+++ b/apps/desktop/src/lib/dataGrid/dataGridPagination.ts@@ -73,6 +73,15 @@ export function resolveDataGridPaginationTotal(options: { paginationTotalRowCounreturn Math.min(total, options.maxRows);}+/** A rewritten SQL page proves exhaustion only after a short (possibly empty) tail. */+export function hasShortDataGridSqlPage(options: { rowCount: number; pageOffset?: number; pageLimit?: number; executedPageOffset?: number; executedPageLimit?: number }): boolean {+ const offset = options.pageOffset ?? 0;+ const lastOffset = options.executedPageOffset ?? offset;+ const limit = options.executedPageLimit ?? options.pageLimit;+ const lastRows = options.rowCount - (lastOffset - offset);+ return limit !== undefined && limit > 0 && lastRows >= 0 && lastRows < limit;+}+export interface ReconcileDataGridExactTotalOptions {offset: number;rowCount: number;diff --git a/apps/desktop/src/lib/database/jdbcDialect.ts b/apps/desktop/src/lib/database/jdbcDialect.tsindex 7f26b48cf5..466190cd21 100644--- a/apps/desktop/src/lib/database/jdbcDialect.ts+++ b/apps/desktop/src/lib/database/jdbcDialect.ts@@ -119,6 +119,11 @@ export function effectiveDatabaseTypeForConnection(connection?: JdbcDialectConne* would drop them from the connection list and disable every non-table kind.*/export function transferDatabaseTypeForConnection(connection?: JdbcDialectConnection): DatabaseType | undefined {+ // GBase connections are mapped to the MySQL dialect for SQL generation, but+ // the GBase driver manifest explicitly disables data transfer. Keep that+ // capability restriction attached to the raw connection type instead of+ // exposing the mapped MySQL type to transfer callers.+ if (connection?.db_type === "gbase") return undefined;const effective = effectiveDatabaseTypeForConnection(connection);if (effective === "doris" || effective === "starrocks") return connection?.db_type;return effective;diff --git a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.tsindex 098c22ae2e..d906c4c7d9 100644--- a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts@@ -34,6 +34,8 @@ const prepareQueryPaginationExecutionPlan = vi.fn(async (options) => ({const editorSettings = {pageSize: 100,autoCalculateTotalRows: false,+ queryResultMaxRowsEnabled: true,+ queryResultMaxRows: 100_000,};function deferred<T>() {@@ -122,6 +124,8 @@ describe("queryStore hidden primary key editing", () => {}));editorSettings.pageSize = 100;editorSettings.autoCalculateTotalRows = false;+ editorSettings.queryResultMaxRowsEnabled = true;+ editorSettings.queryResultMaxRows = 100_000;executeQuery.mockResolvedValue({columns: ["row_count"],rows: [[0]],@@ -1963,6 +1967,52 @@ describe("queryStore hidden primary key editing", () => {expect(tab.queryAnalysis).toBeUndefined();});+ it.each([+ { manual: false, tailRows: 0 },+ { manual: false, tailRows: 1 },+ { manual: false, tailRows: 4 },+ { manual: true, tailRows: 0 },+ { manual: true, tailRows: 1 },+ { manual: true, tailRows: 4 },+ ])("accounts for appended rows once (manual=$manual, tail=$tailRows)", async ({ manual, tailRows }) => {+ editorSettings.queryResultMaxRows = 10;+ analyzeEditableQueryEditability.mockResolvedValue({ editable: false });+ prepareQueryPaginationExecutionPlan.mockImplementation(async (options) => ({+ sqlToExecute: options.sql,+ pageSql: options.sql,+ pageLimit: options.pagination.limit,+ pageOffset: options.pagination.offset,+ countSql: undefined,+ useAgentResultSession: false,+ }));+ const page = (offset: number, count: number) => ({ columns: ["id"], rows: Array.from({ length: count }, (_, index) => [offset + index]), has_more: false, affected_rows: 0, execution_time_ms: 1 });+ const execute = manual ? executeInManualTransaction : executeMulti;+ execute.mockResolvedValueOnce([page(0, 6)]).mockResolvedValueOnce([page(6, tailRows)]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ if (manual) {+ tab.autoCommit = false;+ tab.txnSessionId = "source-transaction";+ }+ await store.executeTabSql(id, "SELECT id FROM items", { pagination: { limit: 6, offset: 0 } });+ await store.executeTabSql(id, "SELECT id FROM items", {+ pagination: { limit: 4, offset: 6 },+ preserveResultDuringExecution: true,+ appendResult: { maxRows: 10 },+ });+ expect(tab.result?.rows).toHaveLength(6 + tailRows);+ expect(tab.result?.truncated === true).toBe(tailRows === 4);+ expect(tab.resultExecutedPageOffset).toBe(6);+ expect(tab.resultPageOffset).toBe(0);+ if (tailRows < 4) {+ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual(tab.result?.rows);+ expect(execute).toHaveBeenCalledTimes(2);+ }+ if (manual) expect(tab.txnSessionId).toBe("source-transaction");+ });+it("removes the generated row number before appending OceanBase Oracle pages", async () => {const sql = "SELECT LEVEL AS N FROM DUAL CONNECT BY LEVEL <= 4";getConnectionConfig.mockReturnValue({ id: "ob-1", name: "OceanBase", db_type: "oceanbase-oracle", database: "app" });diff --git a/apps/desktop/src/stores/__tests__/queryStore.queryResultExport.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.queryResultExport.spec.tsindex 98129ba585..00bab72415 100644--- a/apps/desktop/src/stores/__tests__/queryStore.queryResultExport.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.queryResultExport.spec.ts@@ -5,10 +5,19 @@ const mocks = vi.hoisted(() => ({ensureConnected: vi.fn(),getConfig: vi.fn(),connectionIdentifierQuote: vi.fn(),+ executeMulti: vi.fn(),+ prepareQueryPaginationExecutionPlan: vi.fn(),+ closeClientConnectionSession: vi.fn(),+ closeQuerySession: vi.fn(),+ exportSettings: { exportRowLimitEnabled: false, exportRowLimit: 100 },}));vi.mock("@/lib/backend/api", () => ({saveOpenTabsState: vi.fn().mockResolvedValue(undefined),+ executeMulti: mocks.executeMulti,+ prepareQueryPaginationExecutionPlan: mocks.prepareQueryPaginationExecutionPlan,+ closeClientConnectionSession: mocks.closeClientConnectionSession,+ closeQuerySession: mocks.closeQuerySession,}));vi.mock("@/stores/connectionStore", () => ({@@ -23,8 +32,7 @@ vi.mock("@/stores/settingsStore", () => ({useSettingsStore: () => ({editorSettings: {exportBatchSize: 1000,- exportRowLimitEnabled: false,- exportRowLimit: 100_000,+ ...mocks.exportSettings,globalQueryTimeoutSecs: 30,queryExportKeysetOptimizationEnabled: true,numericColumnRightAlign: true,@@ -44,13 +52,332 @@ function installLocalStorage() {describe("queryStore query result export", () => {beforeEach(() => {vi.clearAllMocks();+ mocks.exportSettings.exportRowLimitEnabled = false;installLocalStorage();setActivePinia(createPinia());mocks.ensureConnected.mockResolvedValue(undefined);+ mocks.closeClientConnectionSession.mockResolvedValue(undefined);+ mocks.closeQuerySession.mockResolvedValue(undefined);mocks.getConfig.mockReturnValue({ id: "kingbase-1", name: "Kingbase", db_type: "kingbase", database: "app", query_timeout_secs: 30 });mocks.connectionIdentifierQuote.mockReturnValue("[");});+ it.each([99, 100, 101])("probes a result of %i rows without a cached total", async (count) => {+ mocks.exportSettings.exportRowLimitEnabled = true;+ mocks.getConfig.mockReturnValue({ id: "mysql-1", db_type: "mysql", database: "app" });+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (request) => ({+ sqlToExecute: request.sql,+ pageLimit: request.pagination.limit,+ pageOffset: request.pagination.offset,+ useAgentResultSession: false,+ }));+ mocks.executeMulti.mockImplementation(async (_id, _database, _sql, _schema, _executionId, options) => [+ {+ columns: ["id"],+ rows: Array.from({ length: Math.min(count, options.maxRows) }, (_, index) => [index]),+ execution_time_ms: 0,+ affected_rows: 0,+ },+ ]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const { queryResultTransferIncomplete } = await import("@/components/transfer/queryResultTransfer");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.sql = "SELECT id FROM items";+ tab.lastExecutedSql = tab.sql;+ tab.result = { columns: ["id"], column_types: ["bigint unsigned"], rows: [[0]], execution_time_ms: 0, affected_rows: 0 };+ expect(tab.resultTotalRowCount).toBeUndefined();+ const result = await store.fetchTabResultForExport(id, undefined, true);+ expect(result?.rows).toHaveLength(count);+ expect(result?.column_types).toEqual(["bigint unsigned"]);+ expect(queryResultTransferIncomplete(result!, 100)).toBe(count > 100);+ expect(mocks.executeMulti).toHaveBeenCalledWith("mysql-1", "app", tab.sql, undefined, expect.any(String), expect.objectContaining({ maxRows: 101 }));+ const ordinaryExport = await store.fetchTabResultForExport(id);+ expect(ordinaryExport?.rows).toHaveLength(Math.min(count, 100));+ });++ it("does not treat an earlier page's has_more marker as incomplete", async () => {+ mocks.getConfig.mockReturnValue({ id: "mysql-1", db_type: "mysql", database: "app" });+ mocks.prepareQueryPaginationExecutionPlan.mockResolvedValue({ sqlToExecute: "SELECT id FROM items", pageLimit: 1, pageOffset: 0, useAgentResultSession: true });+ mocks.executeMulti.mockImplementation(async (_id, _database, _sql, _schema, _executionId, options) => [+ options.resultSessionId ? { columns: ["id"], rows: [[2]], has_more: false, session_id: "s2", execution_time_ms: 0, affected_rows: 0 } : { columns: ["id"], rows: [[1]], has_more: true, session_id: "s1", execution_time_ms: 0, affected_rows: 0 },+ ]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const { queryResultTransferIncomplete } = await import("@/components/transfer/queryResultTransfer");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.sql = "SELECT id FROM items";+ tab.lastExecutedSql = tab.sql;+ tab.result = { columns: ["id"], rows: [[1]], execution_time_ms: 0, affected_rows: 0 };+ const result = await store.fetchTabResultForExport(id, undefined, true);+ expect(result?.rows).toEqual([[1], [2]]);+ expect(queryResultTransferIncomplete(result!)).toBe(false);+ });++ it.each(["CALL update_and_list_items()", "INSERT INTO items VALUES (1) RETURNING id", "WITH changed AS (DELETE FROM items RETURNING id) SELECT * FROM changed"])("does not replay a result-producing mutation during transfer: %s", async (sql) => {+ mocks.getConfig.mockReturnValue({ id: "oracle-1", db_type: "oracle", database: "app" });+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("oracle-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = sql;+ tab.result = { columns: ["id"], rows: [[1]], execution_time_ms: 0, affected_rows: 1, has_more: false };++ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual([[1]]);+ expect(mocks.prepareQueryPaginationExecutionPlan).not.toHaveBeenCalled();+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it.each(["has_more", "unknown_completeness", "truncated", "last_page", "large_value"])("rejects an incomplete cached mutation result (%s) without replaying it", async (reason) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "CALL update_and_list_items()";+ tab.result = { columns: ["id"], rows: [[1]], execution_time_ms: 0, affected_rows: 1, has_more: reason === "has_more", truncated: reason === "truncated" };+ if (reason === "unknown_completeness") tab.result.has_more = undefined;+ if (reason === "last_page") tab.resultPageOffset = 10;+ if (reason === "large_value") tab.result.large_value_cells = [{ row_index: 0, column_index: 0, original_bytes: 10000 }];++ await expect(store.fetchTabResultForExport(id, undefined, true)).rejects.toThrow();+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it.each(["missing_result", "missing_session", "empty_cursor_page", "missing_has_more", "changed_columns", "changed_types", "pagination_error"])("rejects incomplete transfer pagination (%s)", async (reason) => {+ mocks.getConfig.mockReturnValue({ id: "oracle-1", db_type: "oracle", database: "app" });+ mocks.prepareQueryPaginationExecutionPlan.mockResolvedValue({ sqlToExecute: "SELECT id FROM items", pageLimit: 1, pageOffset: 0, useAgentResultSession: true, ...(reason === "pagination_error" ? { paginationError: "Cannot paginate this query" } : {}) });+ const completePage = { columns: ["id"], column_types: ["integer"], rows: [[1]], has_more: false, session_id: "s1", execution_time_ms: 0, affected_rows: 0 };+ if (reason === "changed_columns" || reason === "changed_types") {+ mocks.executeMulti.mockResolvedValueOnce([{ ...completePage, has_more: true }]).mockResolvedValueOnce([{ ...completePage, ...(reason === "changed_columns" ? { columns: ["name"] } : { column_types: ["text"] }) }]);+ } else {+ mocks.executeMulti.mockResolvedValue(reason === "missing_result" ? [] : [{ ...completePage, has_more: reason === "missing_has_more" ? undefined : true, session_id: reason === "missing_session" ? undefined : "s1", rows: reason === "empty_cursor_page" ? [] : [[1]] }]);+ }+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("oracle-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM items";+ tab.result = { ...completePage, has_more: true, session_id: undefined };++ await expect(store.fetchTabResultForExport(id, undefined, true)).rejects.toThrow();+ expect(mocks.executeMulti.mock.calls.length).toBeLessThanOrEqual(2);+ });++ it("removes only recorded hidden columns when exporting a sorted query", async () => {+ mocks.getConfig.mockReturnValue({ id: "mysql-1", db_type: "mysql", database: "app" });+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (request) => ({ sqlToExecute: request.sql, pageLimit: 1000, pageOffset: 0, useAgentResultSession: false }));+ mocks.executeMulti.mockResolvedValue([{ columns: ["name", "__DBX_PK_0"], column_types: ["varchar", "int"], rows: [["Ada", 42]], execution_time_ms: 0, affected_rows: 0 }]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT name FROM items";+ tab.resultSortedSql = "SELECT name, id AS __DBX_PK_0 FROM items ORDER BY name";+ tab.result = { columns: ["name", "__DBX_PK_0"], column_types: ["varchar", "int"], rows: [["Ada", 42]], hidden_column_indexes: [1], execution_time_ms: 0, affected_rows: 0 };++ const result = await store.fetchTabResultForExport(id, undefined, true);+ expect(result?.columns).toEqual(["name"]);+ expect(result?.column_types).toEqual(["varchar"]);+ expect(result?.rows).toEqual([["Ada"]]);+ expect(tab.result.columns).toEqual(["name", "__DBX_PK_0"]);++ tab.result.hidden_column_indexes = undefined;+ expect((await store.fetchTabResultForExport(id, undefined, true))?.columns).toEqual(["name", "__DBX_PK_0"]);+ });++ it("transfers a complete visible snapshot without re-executing session-local SQL", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT name, id AS __DBX_PK_0 FROM session_temp_items";+ tab.result = { columns: ["name", "__DBX_PK_0"], column_types: ["varchar", "int"], hidden_column_indexes: [1], rows: [["visible value", 42]], has_more: false, execution_time_ms: 0, affected_rows: 0 };++ const result = await store.fetchTabResultForExport(id, undefined, true);+ expect(result?.rows).toEqual([["visible value"]]);+ expect(result?.columns).toEqual(["name"]);+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ expect(mocks.ensureConnected).not.toHaveBeenCalled();+ tab.result.rows[0]![0] = "changed later";+ expect(result?.rows).toEqual([["visible value"]]);+ });++ it.each(["mysql", "postgres", "highgo"])("fetches beyond a full SQL page whose driver reports has_more=false (%s)", async (dbType) => {+ mocks.getConfig.mockReturnValue({ id: "source", db_type: dbType, database: "app" });+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (request) => ({ sqlToExecute: request.sql, pageLimit: request.pagination.limit, pageOffset: request.pagination.offset, useAgentResultSession: false }));+ mocks.executeMulti.mockResolvedValue([{ columns: ["id"], rows: [[1], [2], [3]], has_more: false, execution_time_ms: 0, affected_rows: 0 }]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("source", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM items";+ tab.result = { columns: ["id"], rows: [[1], [2]], has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = 2;+ tab.resultPageOffset = 0;++ tab.resultPageSql = "SELECT id FROM items LIMIT 2";++ expect(tab.resultTotalRowCount).toBeUndefined();+ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual([[1], [2], [3]]);+ expect(mocks.executeMulti).toHaveBeenCalledTimes(1);+ });++ it.each(["short_first_page", "short_appended_page", "exhausted_cursor"])("keeps a snapshot whose completeness is proven (%s)", async (reason) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM session_temp_items";+ const rows = reason === "short_first_page" ? [[1]] : reason === "short_appended_page" ? [[1], [2], [3]] : [[1], [2]];+ // JDBC closes an exhausted cursor and returns no session_id, including+ // when its last page happens to be exactly full.+ tab.result = { columns: ["id"], rows, has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = 2;+ tab.resultPageOffset = 0;+ tab.resultExecutedPageLimit = 2;+ tab.resultExecutedPageOffset = reason === "short_appended_page" ? 2 : 0;+ if (reason !== "exhausted_cursor") tab.resultPageSql = "SELECT id FROM session_temp_items LIMIT 2";++ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual(rows);+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it.each([undefined, 2, 4])("does not use a full SQL page's cached count (%s) as proof of exhaustion", async (cachedTotal) => {+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (request) => ({ sqlToExecute: request.sql, pageLimit: request.pagination.limit, pageOffset: request.pagination.offset, useAgentResultSession: false }));+ mocks.executeMulti.mockResolvedValue([{ columns: ["id"], rows: [[1], [2], [3], [4], [5]], has_more: false, execution_time_ms: 0, affected_rows: 0 }]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM items";+ tab.result = { columns: ["id"], rows: [[1], [2], [3], [4]], has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = 2;+ tab.resultPageOffset = 0;+ tab.resultExecutedPageLimit = 2;+ tab.resultExecutedPageOffset = 2;+ tab.resultPageSql = "SELECT id FROM items LIMIT 2";+ // COUNT can run on another session, where a same-named permanent table+ // has fewer rows than the temporary table behind the actual SELECT.+ tab.resultTotalRowCount = cachedTotal;++ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual([[1], [2], [3], [4], [5]]);+ expect(mocks.executeMulti).toHaveBeenCalledTimes(1);+ });++ it("rejects a full cached SQL page if export pagination is unavailable", async () => {+ mocks.prepareQueryPaginationExecutionPlan.mockResolvedValue({ sqlToExecute: "SELECT id FROM items", useAgentResultSession: false });+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM items";+ tab.result = { columns: ["id"], rows: [[1]], has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = 1;+ tab.resultPageOffset = 0;+ tab.resultPageSql = `SELECT id FROM items LIMIT ${tab.resultPageLimit}`;++ await expect(store.fetchTabResultForExport(id, undefined, true)).rejects.toThrow();+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ });++ it.each([false, true])("only transfers a complete manual-transaction snapshot (complete=%s)", async (complete) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.autoCommit = false;+ tab.txnSessionId = "uncommitted-source";+ tab.lastExecutedSql = "SELECT id FROM items";+ tab.result = { columns: ["id"], rows: [[1]], has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = complete ? 2 : 1;+ tab.resultPageOffset = 0;+ tab.resultPageSql = `SELECT id FROM items LIMIT ${tab.resultPageLimit}`;+ if (complete) tab.resultTotalRowCount = 1;++ if (complete) expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual([[1]]);+ else await expect(store.fetchTabResultForExport(id, undefined, true)).rejects.toThrow();+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ });++ it.each([0, 1])("transfers a manual-transaction snapshot after a %i-row tail without replay", async (tailRows) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.autoCommit = false;+ tab.txnSessionId = "uncommitted-source";+ tab.lastExecutedSql = "SELECT id FROM items";+ tab.result = { columns: ["id"], rows: Array.from({ length: 2 + tailRows }, (_, index) => [index]), has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = 2;+ tab.resultPageOffset = 0;+ tab.resultExecutedPageLimit = 2;+ tab.resultExecutedPageOffset = 2;+ tab.resultPageSql = "SELECT id FROM items LIMIT 2";+ tab.resultTotalRowCount = 2;+ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual(tab.result.rows);+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ expect(tab.txnSessionId).toBe("uncommitted-source");+ });++ it.each([undefined, "source-result-session"])("keeps the source client session while reading paginated transfer rows (%s)", async (resultClientSessionId) => {+ mocks.getConfig.mockReturnValue({ id: "mysql-1", db_type: "mysql", database: "app" });+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (request) => ({ sqlToExecute: request.sql, pageLimit: request.pagination.limit, pageOffset: request.pagination.offset, useAgentResultSession: false }));+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("mysql-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM session_temp_items";+ tab.result = { columns: ["id"], rows: [[1]], has_more: false, execution_time_ms: 0, affected_rows: 0 };+ tab.resultPageLimit = 1;+ tab.resultPageOffset = 0;+ tab.resultPageSql = "SELECT id FROM session_temp_items LIMIT 1";+ tab.resultClientSessionId = resultClientSessionId;+ const expectedSession = resultClientSessionId ?? id;+ mocks.executeMulti.mockImplementation(async (_connectionId, _database, _sql, _schema, _executionId, options) => [{ columns: ["id"], rows: options.clientSessionId === expectedSession ? [[1], [2]] : [[99]], has_more: false, execution_time_ms: 0, affected_rows: 0 }]);++ expect((await store.fetchTabResultForExport(id, undefined, true))?.rows).toEqual([[1], [2]]);+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ await store.fetchTabResultForExport(id);+ expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith("mysql-1", "app", `${id}:export`);+ });++ it("leaves the grid's live cursor untouched until its full result is loaded", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT id FROM session_temp_items";+ tab.result = { columns: ["id"], rows: [[1]], has_more: true, session_id: "grid-cursor", execution_time_ms: 0, affected_rows: 0 };+ tab.resultSessionId = "grid-cursor";+ tab.resultPageLimit = 1;+ tab.resultPageOffset = 0;++ await expect(store.fetchTabResultForExport(id, undefined, true)).rejects.toThrow();+ expect(mocks.executeMulti).not.toHaveBeenCalled();+ expect(mocks.closeQuerySession).not.toHaveBeenCalled();+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ expect(tab.resultSessionId).toBe("grid-cursor");+ });++ it("closes only the newly opened cursor when its first page has a large-value preview", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("kingbase-1", "app", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.lastExecutedSql = "SELECT payload FROM items";+ tab.result = { columns: ["payload"], rows: [["preview"]], has_more: false, large_value_cells: [{ row_index: 0, column_index: 0, original_bytes: 10000 }], execution_time_ms: 0, affected_rows: 0 };+ mocks.prepareQueryPaginationExecutionPlan.mockResolvedValue({ sqlToExecute: tab.lastExecutedSql, pageLimit: 1, pageOffset: 0, useAgentResultSession: true });+ mocks.executeMulti.mockResolvedValue([{ ...tab.result, session_id: "new-export-cursor", has_more: true }]);++ await expect(store.fetchTabResultForExport(id, undefined, true)).rejects.toThrow();+ expect(mocks.closeQuerySession).toHaveBeenCalledWith("kingbase-1", "app", "new-export-cursor", id, undefined);+ expect(mocks.closeClientConnectionSession).not.toHaveBeenCalled();+ });+it("passes the live connection identifier quote to backend SQL export", async () => {const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 43e3fd40ba..32076ab06b 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -1,3 +1,4 @@+import { hasShortDataGridSqlPage } from "@/lib/dataGrid/dataGridPagination";import { createQueryRequestTiming } from "@/lib/queryRequestTiming";import { appendNeo4jNodeCells, extractNeo4jNodeCells } from "@/lib/neo4j/neo4jNodeResult";import { UPDATE_RESTORE_KEY, assertUpdateAllowsInteraction } from "@/lib/app/updatePreparation";@@ -8327,7 +8328,10 @@ export const useQueryStore = defineStore("query", () => {current.resultTotalRowCount = undefined;}const resultRowCount = current.result?.rows.length ?? 0;- const resultLimitReached = !!current.result && queryResultLimitReached(pageOffset, resultRowCount, queryResultMaxRows);+ // Appends already include all earlier rows. Measure the merged result+ // from its logical start, not from the offset of the latest tail page.+ const resultStartOffset = shouldAppendResult ? current.resultPageOffset : pageOffset;+ const resultLimitReached = !!current.result && queryResultLimitReached(resultStartOffset, resultRowCount, queryResultMaxRows);if (resultLimitReached && current.result) {current.result.has_more = false;current.result.truncated = true;@@ -9334,7 +9338,7 @@ export const useQueryStore = defineStore("query", () => {});}- async function fetchTabResultForExport(id: string, onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void): Promise<QueryResult | undefined> {+ async function fetchTabResultForExport(id: string, onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void, probeRowLimit = false): Promise<QueryResult | undefined> {const tab = tabs.value.find((t) => t.id === id);if (!tab?.result) return undefined;@@ -9450,8 +9454,71 @@ export const useQueryStore = defineStore("query", () => {if (tab.mode !== "query") return tab.result;+ const sourceResult = probeRowLimit+ ? { ...tab.result, columns: [...tab.result.columns], column_types: tab.result.column_types ? [...tab.result.column_types] : undefined, hidden_column_indexes: tab.result.hidden_column_indexes ? [...tab.result.hidden_column_indexes] : undefined, rows: tab.result.rows.map((row) => [...row]) }+ : tab.result;+ const sourcePageOffset = tab.resultPageOffset ?? 0;+ const sourceTotalRows = tab.resultTotalRowCount;+ const sourceClientSessionId = tab.resultClientSessionId ?? tabClientSessionId(tab);+ const sourcePageLimit = tab.resultExecutedPageLimit ?? tab.resultPageLimit;+ const sourceLastPageOffset = tab.resultExecutedPageOffset ?? sourcePageOffset;+ // Native drivers also report has_more=false for SELECT ... LIMIT n: it+ // exhausts that SQL statement, not the original query. resultPageSql records+ // a rewritten SQL page; cursors execute the original query and clear their+ // session_id on exhaustion. A SQL page needs a short tail: background COUNT+ // can use another session and see a different table behind a temporary name.+ // Appended segments retain resultPageOffset=0, so inspect their last page.+ const sourceSnapshotComplete =+ sourceResult.has_more === false &&+ !sourceResult.truncated &&+ !sourceResult.large_value_cells?.length &&+ !sourceResult.execution_error &&+ sourcePageOffset === 0 &&+ (typeof sourceTotalRows !== "number" || sourceTotalRows <= sourceResult.rows.length) &&+ (!tab.resultPageSql || hasShortDataGridSqlPage({ rowCount: sourceResult.rows.length, pageOffset: sourcePageOffset, executedPageOffset: sourceLastPageOffset, executedPageLimit: sourcePageLimit }));+ const sourceHiddenNames = new Set((sourceResult.hidden_column_indexes ?? []).map((index) => sourceResult.columns[index]).filter((name): name is string => name !== undefined && sourceResult.columns.filter((column) => column === name).length === 1));+ const resultForTransfer = (result: QueryResult): QueryResult => {+ if (!probeRowLimit) return result;+ const hidden = new Set(result.hidden_column_indexes ?? []);+ result.columns.forEach((name, index) => {+ if (sourceHiddenNames.has(name)) hidden.add(index);+ });+ if (hidden.size === 0) return result;+ const indexes = result.columns.map((_, index) => index).filter((index) => !hidden.has(index));+ const indexMap = new Map(indexes.map((index, ordinal) => [index, ordinal]));+ return {+ ...result,+ columns: indexes.map((index) => result.columns[index]!),+ column_types: result.column_types ? indexes.map((index) => result.column_types?.[index] ?? "") : undefined,+ column_sortables: result.column_sortables ? indexes.map((index) => result.column_sortables?.[index] ?? true) : undefined,+ rows: result.rows.map((row) => indexes.map((index) => row[index])),+ spatial_values: result.spatial_values?.map((row) => indexes.map((index) => row[index] ?? null)),+ spatial_columns: result.spatial_columns?.filter((column) => indexMap.has(column.column_index)).map((column) => ({ ...column, column_index: indexMap.get(column.column_index)! })),+ neo4j_node_cells: result.neo4j_node_cells?.filter((cell) => indexMap.has(cell.column_index)).map((cell) => ({ ...cell, column_index: indexMap.get(cell.column_index)! })),+ hidden_column_indexes: undefined,+ };+ };+ const cachedResultForExport = (): QueryResult => {+ // A last page (has_more=false) is not a complete result. Nor is a LOB+ // preview safe to write as if it were the underlying value.+ if (probeRowLimit && !sourceSnapshotComplete) {+ throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ }+ return resultForTransfer(sourceResult);+ };+ // Reuse a result explicitly known to be complete. Re-executing it on the+ // export session can lose temporary tables, session settings or uncommitted+ // values, and would no longer transfer the snapshot shown to the user.+ if (probeRowLimit && sourceSnapshotComplete) return resultForTransfer(sourceResult);+ // A separate execution cannot see this transaction's uncommitted values.+ // Keep its writes and cursor untouched; only a fully loaded snapshot is+ // safe to transfer without re-entering the manual transaction protocol.+ // An Agent timeout cancels every cursor on its client session. Do not+ // borrow that session while the grid still owns a live cursor either.+ if (probeRowLimit && ((tab.autoCommit === false && tab.txnSessionId) || tab.resultSessionId || sourceResult.session_id)) throw new Error(i18n.global.t("grid.exportDatabaseLoadComplete"));const sql = queryResultExecutionSql(tab);- if (!sql.trim()) return tab.result;+ const baseSql = queryResultBaseSql(tab);+ if (!sql.trim()) return cachedResultForExport();const location = queryResultExecutionLocation(tab);const connStore = useConnectionStore();@@ -9459,14 +9526,23 @@ export const useQueryStore = defineStore("query", () => {const conn = connStore.getConfig(location.connectionId);const effectiveDbType = effectiveDatabaseTypeForConnection(conn);const executableSql = effectiveDbType === "mysql" ? stripMysqlClientDisplayCommand(sql) : sql;+ if (probeRowLimit && effectiveDbType !== "mongodb") {+ const assessment = classifySqlRisk(executableSql, { dialect: effectiveDbType });+ const statement = assessment.statements[0];+ // CALL and DML RETURNING/OUTPUT may return rows, but exporting them must+ // never repeat their source-side mutations just to obtain those rows.+ if (assessment.risk !== "read" || assessment.statements.length !== 1 || (statement?.firstKeyword !== "select" && statement?.firstKeyword !== "with")) return cachedResultForExport();+ }const executionDatabase = location.database;// main 引入全局查询超时:queryTimeoutSecsForConnection 现需传入全局默认值;// settingsStore 取 defineStore 顶层声明的实例(本函数无局部覆盖)。const queryTimeoutSecs = queryTimeoutSecsForConnection(conn, settingsStore.editorSettings.globalQueryTimeoutSecs);const useAgentCursor = usesAgentCursorForQuery(conn?.db_type, conn?.driver_profile);- const queryBaseSql = effectiveDbType === "mysql" ? stripMysqlClientDisplayCommand(queryResultBaseSql(tab)) : queryResultBaseSql(tab);+ const queryBaseSql = effectiveDbType === "mysql" ? stripMysqlClientDisplayCommand(baseSql) : baseSql;const exportSettings = useSettingsStore().editorSettings;- const exportRowLimit = exportSettings.exportRowLimitEnabled ? exportSettings.exportRowLimit : Number.POSITIVE_INFINITY;+ // Database transfers read one extra row to distinguish a complete result at+ // the limit from a partial export, without relying on a cached COUNT.+ const exportRowLimit = exportSettings.exportRowLimitEnabled ? exportSettings.exportRowLimit + (probeRowLimit ? 1 : 0) : Number.POSITIVE_INFINITY;if (effectiveDbType === "mongodb") {let mongoCommand;@@ -9528,28 +9604,33 @@ export const useQueryStore = defineStore("query", () => {// BSON-faithful cell encoding.const result = mongoDocumentsToQueryResult(documents, performance.now() - exportStartedAt, totalRows ?? documents.length, copyDocuments, totalRows !== null, { documentGridValues: false });if (result.columns.length === 0) {- result.columns = tab.result.columns;- result.column_types = tab.result.column_types;+ result.columns = sourceResult.columns;+ result.column_types = sourceResult.column_types;}result.affected_rows = documents.length;result.truncated = false;result.has_more = false;- return result;+ return resultForTransfer(result);}- const agentExportMaxRows = exportSettings.exportRowLimitEnabled ? exportSettings.exportRowLimit : 2_147_483_647;+ const agentExportMaxRows = Math.min(exportRowLimit, 2_147_483_647);// Use the already-computed total row count as a progress estimate so the// export dialog shows a moving bar instead of a stuck 0 while paginating.const totalRows = typeof tab.resultTotalRowCount === "number" ? Math.min(tab.resultTotalRowCount, exportRowLimit) : null;const pageLimit = Math.max(tab.resultPageLimit ?? 0, TABLE_DATA_EXPORT_PAGE_SIZE);const rows: QueryResult["rows"] = [];let columns: string[] = [];+ let columnTypes: string[] = [];let executionTimeMs = 0;let offset = 0;let sessionId: string | undefined;- const clientSessionId = tabClientSessionId(tab, "export");+ // A database transfer must retain session-local tables and settings. The+ // file-export path owns a separate client session; this path borrows the+ // source session and must not close it when exporting finishes.+ const clientSessionId = probeRowLimit ? sourceClientSessionId : tabClientSessionId(tab, "export");const exportExecutionId = uuid();+ let incomplete = false;try {while (rows.length < exportRowLimit) {const remaining = exportRowLimit - rows.length;@@ -9562,7 +9643,8 @@ export const useQueryStore = defineStore("query", () => {useAgentCursor,firstPageUsesActualSql: true,});- if (typeof plan.pageLimit !== "number" || typeof plan.pageOffset !== "number") return tab.result;+ if (probeRowLimit && plan.paginationError) throw new Error(plan.paginationError);+ if (typeof plan.pageLimit !== "number" || typeof plan.pageOffset !== "number") return cachedResultForExport();const executionOptions = plan.useAgentResultSession? {maxRows: agentExportMaxRows,@@ -9575,30 +9657,53 @@ export const useQueryStore = defineStore("query", () => {}: { maxRows: plan.pageLimit, fetchSize: plan.pageLimit, clientSessionId, catalog: location.catalog, timeoutSecs: queryTimeoutSecs };const results = await api.executeMulti(location.connectionId, executionDatabase, plan.sqlToExecute, location.schema, exportExecutionId, executionOptions);- if (!results[0]) break;+ if (!results[0]) {+ if (probeRowLimit) throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ break;+ }const result = stripPaginationRowNumber(results[0], plan.paginationRowNumberColumn);+ // Capture ownership before validating the page. A first page with a+ // preview/error still owns a new cursor that must be closed without+ // closing the borrowed source client session.+ const nextSessionId = result.session_id?.trim() || sessionId;+ sessionId = nextSessionId;+ if (probeRowLimit && (result.execution_error || result.server_message || result.large_value_cells?.length)) throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ if (probeRowLimit && columns.length > 0 && (result.columns.length !== columns.length || result.columns.some((column, index) => column !== columns[index]))) throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ if (probeRowLimit && columnTypes.length > 0 && result.column_types?.length && (columnTypes.length !== result.column_types.length || result.column_types.some((type, index) => type !== columnTypes[index]))) throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ if (probeRowLimit && plan.useAgentResultSession && (typeof result.has_more !== "boolean" || (result.has_more && (!nextSessionId || result.rows.length === 0)))) throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ if (probeRowLimit && result.has_more && result.rows.length === 0) throw new Error(i18n.global.t("grid.exportDatabaseIncomplete"));+ // `has_more` only describes the current page. It is expected to be true+ // for every page except the last one, so it must not be accumulated as+ // an incomplete-export marker.+ incomplete = incomplete || result.truncated === true;if (columns.length === 0) columns = result.columns;+ if (columnTypes.length === 0 && result.column_types?.length) columnTypes = result.column_types;rows.push(...result.rows);executionTimeMs += result.execution_time_ms ?? 0;onProgress?.({ rowsExported: rows.length, totalRows });- sessionId = result.session_id ?? undefined;- const shouldFetchNextPage = plan.useAgentResultSession ? result.has_more === true : result.rows.length >= plan.pageLimit;+ const shouldFetchNextPage = plan.useAgentResultSession ? result.has_more === true : result.rows.length >= plan.pageLimit || (probeRowLimit && result.has_more === true);if (!shouldFetchNextPage || rows.length >= exportRowLimit) break;offset += result.rows.length;}} finally {- if (sessionId) void api.closeQuerySession(location.connectionId, location.database, sessionId, clientSessionId, location.catalog);- void closeClientSessionId(location.connectionId, location.database, clientSessionId, location.catalog, { tabId: tab.id });+ try {+ if (sessionId) await api.closeQuerySession(location.connectionId, location.database, sessionId, clientSessionId, location.catalog);+ } catch (error) {+ queryExecutionLog("warn", "query-export-session-close:error", { sessionId, error });+ } finally {+ if (!probeRowLimit) void closeClientSessionId(location.connectionId, location.database, clientSessionId, location.catalog, { tabId: tab.id });+ }}- return {- columns: columns.length ? columns : tab.result.columns,+ return resultForTransfer({+ columns: columns.length ? columns : sourceResult.columns,+ column_types: columnTypes.length ? columnTypes : sourceResult.column_types,rows,affected_rows: 0,execution_time_ms: executionTimeMs,- truncated: false,- has_more: false,- };+ truncated: probeRowLimit && (incomplete || (exportSettings.exportRowLimitEnabled && rows.length > exportSettings.exportRowLimit)),+ has_more: probeRowLimit && (incomplete || (exportSettings.exportRowLimitEnabled && rows.length > exportSettings.exportRowLimit)),+ });}async function buildQueryResultExportRequest(id: string, options: BuildQueryResultExportRequestOptions) {diff --git a/docs/content/docs/data-transfer.cn.mdx b/docs/content/docs/data-transfer.cn.mdxindex 2ffb65ccfb..1a7eebc91d 100644--- a/docs/content/docs/data-transfer.cn.mdx+++ b/docs/content/docs/data-transfer.cn.mdx@@ -7,7 +7,7 @@ description: 在不同连接、数据库、Schema 或数据库引擎之间批量<Callout type="warn">跨引擎传输会经过 DBX 的字段和类型转换层。目标数据库的权限、约束、触发器、默认值和类型语义仍会影响结果。重要迁移应先在测试环境演练并做行数与关键字段校验。</Callout>-## 两个入口+## 入口### 数据传输向导@@ -21,6 +21,22 @@ description: 在不同连接、数据库、Schema 或数据库引擎之间批量- 粘贴到另一个连接、数据库或 Schema 时,DBX 会自动打开数据传输向导并带入源表和目标位置- 表数据复制会跳过生成列或计算列,并对 PostgreSQL identity、SQL Server identity 等路径应用相应写入处理+### 查询结果导出到数据库++在查询结果网格的“导出”菜单或右键菜单中选择“导出到数据库”,填写目标连接、数据库、Schema(如适用)和表名。++填写目标后,可点击“执行预览”查看数据来源、目标位置、当前已加载行列数、源字段和预计操作。预览不会写入数据库;显示的行数是当前已加载行数,执行时仍会读取完整可导出结果并检查限制。点击“开始传输”后必须再次点击“确认传输”;覆盖已有表时会明确提示删除目标表全部原有数据。返回修改会保留当前填写内容。++- **创建目标表**:同引擎的单表 `SELECT * FROM 表` 会读取源表 DDL,保留字段类型、长度、精度、默认值、注释、主键、索引及表选项,再替换目标表名。Schema 内必须唯一的索引或约束名会调整,避免与源对象冲突。无法安全复制结构时会停止,不会自动降级为全部文本字段。+- 投影、关联、表达式查询和跨引擎查询使用结果字段生成新表;这些结果没有唯一对应的整表 DDL。元数据不足或目标时间精度不足时使用可保留值的文本类型,不推断原表约束。写入已有表时,无法保留的时间精度会在写入前报错。+- 创建表时目标名称必须尚不存在。写入已有表请取消勾选“创建目标表”;追加保留原数据,覆盖以事务执行 `DELETE + INSERT`,保留目标结构、外键和触发器。MySQL 已有表需要 InnoDB。+- 导出读取完整查询结果,并检查导出行数限制、分页完整性和大字段预览。存储过程或会修改数据的语句不会为了传输而再次执行;只有已完整加载的结果可直接使用。+- 使用活动游标或手动事务的结果需要先在网格中加载全部行。普通分页在源查询会话中读取,保留会话设置,避免从其他连接读到不同数据。+- 手动事务中暂不支持复制源表结构;提交或回滚后重新查询,再选择“创建目标表”。MySQL、H2 临时表也会停止结构复制,避免生成生命周期不同的目标表。+- 准备阶段可以取消;开始写入后等待事务结束。对于会隐式提交建表的驱动,写入失败后会尝试删除本次成功创建的表,清理失败会显示表名。++此入口只列出已实现事务写入的目标驱动。它不迁移独立触发器、权限或跨表依赖;复杂 DDL、目标不兼容的类型和不支持的标识列处理会明确失败。需要整库或多对象迁移时使用数据传输向导。+## 向导流程<Steps>diff --git a/docs/content/docs/data-transfer.mdx b/docs/content/docs/data-transfer.mdxindex 3d32a4f31a..b2ac9a7ec2 100644--- a/docs/content/docs/data-transfer.mdx+++ b/docs/content/docs/data-transfer.mdx@@ -7,7 +7,7 @@ Data Transfer copies tables or collections from one source into another connecti<Callout type="warn">Cross-engine transfer passes through DBX field and type conversion. Target privileges, constraints, triggers, defaults, and engine semantics still determine the result. Rehearse important migrations and validate row counts and key fields afterward.</Callout>-## Two Entry Points+## Entry Points### Data Transfer Wizard@@ -21,6 +21,22 @@ After copying one or more tables in the object tree, paste them at a target loca- Pasting into another connection, database, or schema opens the Data Transfer wizard with the source tables and target prefilled- Whole-row copy excludes generated or computed columns and applies path-specific handling for PostgreSQL identity and SQL Server identity columns+### Export Query Results to a Database++Choose **Export to Database** from the query result grid's export or context menu, then select the target connection, database, schema where applicable, and table name.++After selecting the destination, use **Execution preview** to review the source, destination, currently loaded row and column counts, source columns, and planned operations. Preview does not write to the database; execution still loads the full exportable result and checks limits. **Start Transfer** opens a separate confirmation step; only **Confirm transfer** begins execution. Overwriting an existing table explicitly warns that all existing target rows will be deleted. Returning to settings preserves your selections.++- **Create target table**: for a single-table `SELECT * FROM table` on the same engine, DBX reads the source DDL and preserves column types, lengths, precision, defaults, comments, primary keys, indexes, and table options while replacing the table name. Schema-wide index and constraint names are adjusted to avoid collisions. Unsafe or unavailable DDL stops the transfer instead of silently creating text columns.+- Projections, joins, expressions, and cross-engine queries generate a table from result fields. They have no unique whole-table DDL. Insufficient metadata or target timestamp precision uses text types to preserve values without inferring source constraints. Writes to existing tables reject temporal values that cannot retain their precision before writing.+- A new target name must not already exist. To write to an existing table, disable **Create target table**. Append keeps its rows; overwrite runs `DELETE + INSERT` in a transaction while keeping its structure, foreign keys, and triggers. Existing MySQL targets require InnoDB.+- The transfer checks the complete result, export row limit, pagination, and large-value previews. Procedures and statements that modify data are not rerun for export; only their fully loaded results can be reused.+- Results with an active cursor or manual transaction must first load all rows in the grid. Ordinary pagination reads through the source query session to preserve session settings and avoid reading different data on another connection.+- Copying source table structure inside a manual transaction is not supported. Commit or roll back and rerun the query before choosing **Create target table**. MySQL and H2 temporary tables also stop structure copying instead of creating a target with a different lifetime.+- Cancel during preparation. Once writing starts, wait for the transaction to finish. Drivers that implicitly commit table creation attempt to remove the table created by this transfer if writing fails; cleanup failures identify that table.++This entry point lists target drivers with implemented transactional writes. It does not migrate standalone triggers, grants, or cross-table dependencies. Complex DDL, incompatible types, and unsupported identity handling fail explicitly. Use the Data Transfer wizard for database or multi-object migrations.+## Wizard Workflow<Steps>diff --git a/packages/app-tests/dataGridInfiniteScroll.test.ts b/packages/app-tests/dataGridInfiniteScroll.test.tsindex 8b076ba783..efa901b29c 100644--- a/packages/app-tests/dataGridInfiniteScroll.test.ts+++ b/packages/app-tests/dataGridInfiniteScroll.test.ts@@ -50,7 +50,7 @@ test("load-all selects the last loaded row only after a valid append completes",// ES guard and the large-shot confirmation, so extract both bodies.const loadAllFn = source.match(/function loadAllRowsAndGoToLast\(\) \{[\s\S]*?\nfunction confirmLoadAllRows\(\) \{[\s\S]*?\n\}/)?.[0] ?? "";assert.match(loadAllFn, /gridSurfaceBusy\.value \|\| infiniteScrollLoading\.value/);- assert.match(loadAllFn, /dataGridLoadAllSegment/);+ assert.match(loadAllFn, /const segment = nextLoadAllSegment\(\)/);assert.match(loadAllFn, /if \(!segment\) \{[\s\S]*?selectAndRevealLastLoadedRow\(\);[\s\S]*?return;/);assert.match(loadAllFn, /resolvedDatabaseType\.value === "elasticsearch" \|\| resolvedDatabaseType\.value === "easysearch"/);assert.match(loadAllFn, /LOAD_ALL_ROWS_CONFIRM_ROW_THRESHOLD/);