diff --git a/apps/desktop/src/components/layout/AppDialogs.vue b/apps/desktop/src/components/layout/AppDialogs.vue index 9c8bd0adc5..674cc716e6 100644 --- a/apps/desktop/src/components/layout/AppDialogs.vue +++ b/apps/desktop/src/components/layout/AppDialogs.vue @@ -268,6 +268,7 @@ watch( v-model:open="dialogs.showSqlFileDialog.value" :prefill-connection-id="dialogs.sqlFilePrefillConnectionId.value" :prefill-database="dialogs.sqlFilePrefillDatabase.value" + :prefill-schema="dialogs.sqlFilePrefillSchema.value" :prefill-file-path="dialogs.sqlFilePrefillFilePath.value" :prefill-preview="dialogs.sqlFilePrefillPreview.value" /> diff --git a/apps/desktop/src/components/layout/SqlFilePanel.vue b/apps/desktop/src/components/layout/SqlFilePanel.vue index 4995c14858..6758a61846 100644 --- a/apps/desktop/src/components/layout/SqlFilePanel.vue +++ b/apps/desktop/src/components/layout/SqlFilePanel.vue @@ -275,6 +275,7 @@ function executeFile(path: string) { connectionStore.sqlFileSource = { connectionId: target.connectionId, database: target.database, + ...(target.schema ? { schema: target.schema } : {}), filePath: path, }; } diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts index 6631c4ce04..f4d406f0dd 100644 --- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts +++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts @@ -26,6 +26,7 @@ const mocks = vi.hoisted(() => ({ connections: [{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" }] as Array<{ id: string; name: string; db_type: string; driver_profile: string; database: string }>, getConfig: vi.fn(), refreshDatabaseTreeNode: vi.fn(), + refreshObjectListTreeNode: vi.fn(), requestConfirmation: vi.fn(), toast: vi.fn(), trackerTask: undefined as any, @@ -33,7 +34,7 @@ const mocks = vi.hoisted(() => ({ updateSqlFileTask: vi.fn(), uuid: vi.fn(), queryStore: { - tabs: [{ id: "mysql-tab", connectionId: "mysql-1", database: "" }], + tabs: [{ id: "mysql-tab", connectionId: "mysql-1", database: "" }] as Array<{ id: string; connectionId: string; database: string; schema?: string; catalog?: string }>, activeTabId: "mysql-tab" as string | null, }, })); @@ -63,7 +64,10 @@ vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast vi.mock("@/composables/useExportTracker", () => ({ useExportTracker: () => ({ addSqlFileTask: mocks.addSqlFileTask, updateSqlFileTask: mocks.updateSqlFileTask }), })); -vi.mock("@/composables/useDatabaseOptions", () => ({ fetchSqlFileTargetOptions: mocks.fetchSqlFileTargetOptions })); +vi.mock("@/composables/useDatabaseOptions", () => ({ + fetchSqlFileTargetOptions: mocks.fetchSqlFileTargetOptions, + namespaceOptionsAreSchemas: (connection: { db_type?: string } | undefined) => ["oracle", "dameng", "oceanbase-oracle"].includes(connection?.db_type ?? ""), +})); vi.mock("@/lib/connection/connectionLevelDatabaseBootstrap", () => ({ requiresSqlFileTargetDatabaseSelection: () => false, supportsConnectionLevelDatabaseBootstrap: (connection: any) => connection?.db_type === "mysql" })); vi.mock("@/lib/database/productionSafety", () => ({ productionContextForDatabase: () => ({ active: false, databases: [] }) })); vi.mock("@/stores/productionSafetyStore", () => ({ @@ -77,6 +81,7 @@ vi.mock("@/stores/connectionStore", () => ({ ensureConnected: mocks.ensureConnected, getConfig: mocks.getConfig, refreshDatabaseTreeNode: mocks.refreshDatabaseTreeNode, + refreshObjectListTreeNode: mocks.refreshObjectListTreeNode, }), })); vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => mocks.queryStore })); @@ -257,6 +262,7 @@ beforeEach(() => { }); mocks.cancelSqlFileExecution.mockResolvedValue(true); mocks.refreshDatabaseTreeNode.mockResolvedValue(undefined); + mocks.refreshObjectListTreeNode.mockResolvedValue(undefined); mocks.requestConfirmation.mockResolvedValue(true); mocks.uuid.mockReset().mockReturnValueOnce("run-1").mockReturnValueOnce("run-2"); mocks.queryStore.tabs = [{ id: "mysql-tab", connectionId: "mysql-1", database: "" }]; @@ -636,6 +642,93 @@ describe("SqlFileExecutionDialog retries", () => { expect(mocks.ensureConnected).not.toHaveBeenCalledWith("mysql-1"); }); + it.each([ + ["MySQL", "mysql"], + ["PostgreSQL", "postgres"], + ])("keeps the selected %s namespace in the database field", async (name, dbType) => { + mocks.connections = [{ id: "database-1", name, db_type: dbType, driver_profile: dbType, database: "configured_db" }]; + mocks.queryStore.tabs = [{ id: "database-tab", connectionId: "database-1", database: "selected_db", schema: "remembered_schema" }]; + mocks.queryStore.activeTabId = "database-tab"; + mocks.fetchSqlFileTargetOptions.mockResolvedValue(["configured_db", "selected_db"]); + + await mountReadyDialog(); + await completeFirstExecution(); + + expect(mocks.executeSqlFiles.mock.calls[0]![0]).toMatchObject({ connectionId: "database-1", database: "selected_db" }); + expect(mocks.executeSqlFiles.mock.calls[0]![0]).not.toHaveProperty("schema"); + }); + + it("restores and executes a remembered OceanBase Oracle schema without replacing the connection database", async () => { + mocks.connections = [ + { id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "first" }, + { id: "ob-oracle-1", name: "OceanBase Oracle", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", database: "tenant_service" }, + ]; + rememberExternalSqlFileTarget("/tmp/first.sql", { connectionId: "ob-oracle-1", database: "APP", schema: "APP" }); + mocks.fetchSqlFileTargetOptions.mockResolvedValue(["SYS", "APP"]); + + await mountReadyDialog(); + await completeFirstExecution(); + + expect(mocks.executeSqlFiles.mock.calls[0]![0]).toMatchObject({ + connectionId: "ob-oracle-1", + database: "tenant_service", + schema: "APP", + }); + expect(mocks.refreshObjectListTreeNode).toHaveBeenCalledWith("ob-oracle-1", "tenant_service", "APP"); + }); + + it("restores a legacy root-schema target that stored the schema in database", async () => { + mocks.connections = [{ id: "ob-oracle-1", name: "OceanBase Oracle", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", database: "tenant_service" }]; + mocks.queryStore.tabs = [{ id: "ob-tab", connectionId: "ob-oracle-1", database: "tenant_service" }]; + mocks.queryStore.activeTabId = "ob-tab"; + rememberExternalSqlFileTarget("/tmp/first.sql", { connectionId: "ob-oracle-1", database: "APP" }); + mocks.fetchSqlFileTargetOptions.mockResolvedValue(["SYS", "APP"]); + + await mountReadyDialog(); + await completeFirstExecution(); + + expect(mocks.executeSqlFiles.mock.calls[0]![0]).toMatchObject({ + connectionId: "ob-oracle-1", + database: "tenant_service", + schema: "APP", + }); + }); + + it("keeps an empty configured Oracle-family database empty when restoring a legacy schema target", async () => { + mocks.connections = [{ id: "ob-oracle-1", name: "OceanBase Oracle", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", database: "" }]; + mocks.queryStore.tabs = [{ id: "ob-tab", connectionId: "ob-oracle-1", database: "" }]; + mocks.queryStore.activeTabId = "ob-tab"; + rememberExternalSqlFileTarget("/tmp/first.sql", { connectionId: "ob-oracle-1", database: "APP" }); + mocks.fetchSqlFileTargetOptions.mockResolvedValue(["SYS", "APP"]); + + await mountReadyDialog(); + await completeFirstExecution(); + + expect(mocks.executeSqlFiles.mock.calls[0]![0]).toMatchObject({ + connectionId: "ob-oracle-1", + database: "", + schema: "APP", + }); + }); + + it("uses the same OceanBase Oracle database and schema for manual SQL-file execution", async () => { + mocks.connections = [{ id: "ob-oracle-1", name: "OceanBase Oracle", db_type: "oceanbase-oracle", driver_profile: "oceanbase-oracle", database: "tenant_service" }]; + mocks.queryStore.tabs = [{ id: "ob-tab", connectionId: "ob-oracle-1", database: "APP", schema: "APP" }]; + mocks.queryStore.activeTabId = "ob-tab"; + mocks.fetchSqlFileTargetOptions.mockResolvedValue(["SYS", "APP"]); + + await enableManualTransaction(); + await completeFirstExecution(); + + expect(mocks.beginManualTransaction).toHaveBeenCalledWith("ob-oracle-1", "tenant_service", "APP"); + expect(mocks.executeSqlFiles.mock.calls[0]![0]).toMatchObject({ + connectionId: "ob-oracle-1", + database: "tenant_service", + schema: "APP", + txnSessionId: "txn-1", + }); + }); + it("does not select a connection when the active tab is non-SQL", async () => { mocks.connections = [ { id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "first" }, diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue index 64c49d1e81..a421d7184e 100644 --- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue +++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue @@ -20,7 +20,7 @@ import { productionContextForDatabase } from "@/lib/database/productionSafety"; import { connectionIsEffectivelyReadOnly, ensureReadOnlyWriteAccess } from "@/lib/database/readOnlyWriteAccess"; import { supportsSqlFileExecution, supportsTransaction } from "@/lib/database/databaseFeatureSupport"; import { formatError, isManualTransactionSessionExpired } from "@/lib/backend/errorUtils"; -import { fetchSqlFileTargetOptions } from "@/composables/useDatabaseOptions"; +import { fetchSqlFileTargetOptions, namespaceOptionsAreSchemas } from "@/composables/useDatabaseOptions"; import { requiresSqlFileTargetDatabaseSelection, supportsConnectionLevelDatabaseBootstrap } from "@/lib/connection/connectionLevelDatabaseBootstrap"; import { beginManualTransaction, commitManualTransaction, rollbackManualTransaction, cancelSqlFileExecution, executeSqlFiles, inspectSqlFileTables, listenSqlFileProgress, previewSqlFile, type SqlFilePreview, type SqlFileProgress, type SqlFileStatus, type SqlFileTable } from "@/lib/backend/api"; import { activeTabExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget"; @@ -41,6 +41,7 @@ const open = defineModel("open", { default: false }); const props = defineProps<{ prefillConnectionId?: string; prefillDatabase?: string; + prefillSchema?: string; prefillFilePath?: string; prefillPreview?: SqlFilePreview; }>(); @@ -117,7 +118,7 @@ function tooltipText(item: SqlFilePreview): string { const selectingFile = ref(false); const loadingPreview = ref(false); const connectionId = ref(""); -const database = ref(""); +const targetNamespace = ref(""); const databaseOptions = ref([]); const loadingDatabases = ref(false); const preferredTarget = ref(); @@ -165,6 +166,8 @@ interface PerFileSummary { failureCount: number; affectedRows: number; } +type SqlFileExecutionTarget = { database: string; schema?: string }; + const perFileResults = ref([]); const currentFileIndex = ref(-1); const currentFileName = ref(""); @@ -224,7 +227,7 @@ async function finishTransaction(commit: boolean) { terminalStatus.value = outcomeUnknown ? "error" : committed ? "done" : "cancelled"; if (progress.value) updateSqlFileTask(executionId.value, { ...progress.value, status: terminalStatus.value }); } - await refreshTargetAfterImport(); + await refreshTargetAfterImport(sqlFileExecutionTarget()); return true; } catch (error: any) { toast(error?.message || String(error), 5000); @@ -314,7 +317,7 @@ const canStart = computed(() => { hasDatabaseContext ||= item.establishesDatabaseContext === true; return true; }); - return !!database.value.trim() || !requiresSqlFileTargetDatabaseSelection(connection, canExecuteWithoutSelectedDatabase); + return !!targetNamespace.value.trim() || !requiresSqlFileTargetDatabaseSelection(connection, canExecuteWithoutSelectedDatabase); }); const statusTone = computed(() => { @@ -383,27 +386,62 @@ function statusLabel(status: SqlFileStatus | "idle") { function resolveInitialTarget(): ExternalSqlFileTarget { if (props.prefillConnectionId && sqlConnections.value.some((c) => c.id === props.prefillConnectionId)) { - return { connectionId: props.prefillConnectionId, database: props.prefillDatabase ?? "" }; + return { + connectionId: props.prefillConnectionId, + database: props.prefillDatabase ?? "", + schema: props.prefillSchema, + }; } if (props.prefillFilePath) return { connectionId: "", database: "" }; return activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId)); } -function applyTarget(target: ExternalSqlFileTarget) { - preferredTarget.value = target; - connectionId.value = target.connectionId; - database.value = target.database; +function normalizeTargetForConnection(target: ExternalSqlFileTarget): ExternalSqlFileTarget { + const connection = store.getConfig(target.connectionId); + if (!namespaceOptionsAreSchemas(connection)) return target; + + const configuredDatabase = connection?.database?.trim() || ""; + const requestedDatabase = target.database.trim(); + const explicitSchema = target.schema?.trim() || undefined; + const legacySchema = explicitSchema || (requestedDatabase && requestedDatabase !== configuredDatabase ? requestedDatabase : undefined); + return { + ...target, + database: configuredDatabase, + ...(legacySchema ? { schema: legacySchema } : { schema: undefined }), + }; } -function chooseDatabase(names: string[], id: string) { - const configDatabase = store.getConfig(id)?.database ?? ""; - const preferredDatabase = preferredTarget.value?.connectionId === id ? preferredTarget.value.database : props.prefillDatabase; +function applyTarget(target: ExternalSqlFileTarget) { + const normalizedTarget = normalizeTargetForConnection(target); + preferredTarget.value = normalizedTarget; + connectionId.value = normalizedTarget.connectionId; + targetNamespace.value = namespaceOptionsAreSchemas(store.getConfig(normalizedTarget.connectionId)) ? (normalizedTarget.schema ?? "") : normalizedTarget.database; +} + +function chooseNamespace(names: string[], id: string) { + const connection = store.getConfig(id); + const optionsAreSchemas = namespaceOptionsAreSchemas(connection); + const preferred = preferredTarget.value?.connectionId === id ? preferredTarget.value : undefined; + const preferredNamespace = preferred ? (optionsAreSchemas ? preferred.schema : preferred.database) : optionsAreSchemas ? (id === props.prefillConnectionId ? props.prefillSchema : undefined) : props.prefillDatabase; + const configuredNamespace = optionsAreSchemas ? (connection?.default_schema ?? "") : (connection?.database ?? ""); if (names.length > 0) { - if (preferredDatabase && names.includes(preferredDatabase)) return preferredDatabase; - if (configDatabase && names.includes(configDatabase)) return configDatabase; + if (preferredNamespace && names.includes(preferredNamespace)) return preferredNamespace; + if (configuredNamespace && names.includes(configuredNamespace)) return configuredNamespace; return names.length === 1 ? names[0] : ""; } - return preferredDatabase ?? configDatabase; + return preferredNamespace ?? configuredNamespace; +} + +function sqlFileExecutionTarget(): SqlFileExecutionTarget { + const namespace = targetNamespace.value.trim(); + const connection = store.getConfig(connectionId.value); + if (namespaceOptionsAreSchemas(connection)) { + return { + database: connection?.database?.trim() || "", + ...(namespace ? { schema: namespace } : {}), + }; + } + return { database: namespace }; } function resetExecution() { @@ -444,7 +482,7 @@ async function loadDatabasesForConnection(id: string) { databaseOptions.value = []; if (!sqlConnections.value.some((c) => c.id === id)) { - database.value = ""; + targetNamespace.value = ""; return; } @@ -456,11 +494,11 @@ async function loadDatabasesForConnection(id: string) { const names = await fetchSqlFileTargetOptions(id, connection); if (token !== databaseLoadToken) return; databaseOptions.value = names; - database.value = chooseDatabase(names, id); + targetNamespace.value = chooseNamespace(names, id); } catch { if (token !== databaseLoadToken) return; databaseOptions.value = []; - database.value = chooseDatabase([], id); + targetNamespace.value = chooseNamespace([], id); } finally { if (token === databaseLoadToken) { loadingDatabases.value = false; @@ -566,11 +604,15 @@ function isTerminalProgress(status: SqlFileStatus): boolean { return status === "done" || status === "error" || status === "cancelled"; } -async function refreshTargetAfterImport() { +async function refreshTargetAfterImport(target: SqlFileExecutionTarget) { if (refreshedTarget.value) return; refreshedTarget.value = true; try { - await store.refreshDatabaseTreeNode(connectionId.value, database.value.trim()); + if (target.schema) { + await store.refreshObjectListTreeNode(connectionId.value, target.database, target.schema); + } else { + await store.refreshDatabaseTreeNode(connectionId.value, target.database); + } } catch (e: any) { toast(e?.message || String(e), 5000); } @@ -578,13 +620,14 @@ async function refreshTargetAfterImport() { async function startExecution() { if (!canStart.value || previews.value.length === 0) return; + const target = sqlFileExecutionTarget(); // Await the unlock guard only when it can actually prompt/block (effectively // read-only); writable or already-unlocked connections stay synchronous so // the running state flips in the same tick as the click. if (connectionIsEffectivelyReadOnly(selectedConnection.value)) { if (!(await ensureReadOnlyWriteAccess({ connection: selectedConnection.value, source: t("readOnlyUnlock.sourceSqlFile"), treatAsMutation: true }))) return; } - const productionContext = productionContextForDatabase(selectedConnection.value, database.value); + const productionContext = productionContextForDatabase(selectedConnection.value, target.database); if (productionContext.active) { // File previews are truncated, so production file execution is always reviewed instead of inferring safety from a partial preview. const confirmed = await productionSafetyStore.requestConfirmation({ @@ -593,7 +636,7 @@ async function startExecution() { .join("\n\n") .slice(0, 20_000), connectionName: selectedConnection.value?.name, - database: database.value, + database: target.database, productionDatabases: productionContext.databases, source: t("production.sourceSqlFile"), }); @@ -625,7 +668,7 @@ async function startExecution() { } if (manualTransaction.value) { - const sessionId = await beginManualTransaction(connectionId.value, database.value.trim()); + const sessionId = target.schema ? await beginManualTransaction(connectionId.value, target.database, target.schema) : await beginManualTransaction(connectionId.value, target.database); txnSessionId.value = sessionId; commitUncertain.value = false; if (disposed || cancelRequested.value) { @@ -701,7 +744,8 @@ async function startExecution() { { executionId: batchId, connectionId: connectionId.value, - database: database.value.trim(), + database: target.database, + ...(target.schema ? { schema: target.schema } : {}), filePath: executionPaths[0]!, continueOnError: continueOnError.value, ...(txnSessionId.value ? { txnSessionId: txnSessionId.value } : {}), @@ -724,7 +768,7 @@ async function startExecution() { unlisten(); } - if (completedSuccessfully && !txnSessionId.value) await refreshTargetAfterImport(); + if (completedSuccessfully && !txnSessionId.value) await refreshTargetAfterImport(target); } catch (e: any) { terminalStatus.value = cancelRequested.value ? "cancelled" : "error"; terminalError.value = e?.message || String(e); @@ -920,7 +964,7 @@ watch(
- @@ -929,7 +973,7 @@ watch(
- +
diff --git a/apps/desktop/src/composables/__tests__/useDatabaseOptions.spec.ts b/apps/desktop/src/composables/__tests__/useDatabaseOptions.spec.ts index 080ce3cff8..aba74fae5a 100644 --- a/apps/desktop/src/composables/__tests__/useDatabaseOptions.spec.ts +++ b/apps/desktop/src/composables/__tests__/useDatabaseOptions.spec.ts @@ -215,6 +215,7 @@ describe("namespace options", () => { it("identifies connection-root namespace options as schemas", () => { expect(namespaceOptionsAreSchemas({ db_type: "dameng" })).toBe(true); expect(namespaceOptionsAreSchemas({ db_type: "oracle" })).toBe(true); + expect(namespaceOptionsAreSchemas({ db_type: "oceanbase-oracle" })).toBe(true); expect( namespaceOptionsAreSchemas({ db_type: "jdbc", diff --git a/apps/desktop/src/composables/useDialogSources.ts b/apps/desktop/src/composables/useDialogSources.ts index 58cbb2d4a4..6dcf6e2579 100644 --- a/apps/desktop/src/composables/useDialogSources.ts +++ b/apps/desktop/src/composables/useDialogSources.ts @@ -64,6 +64,7 @@ const dataComparePrefillTable = ref(""); const dataCompareSessionId = ref(null); const sqlFilePrefillConnectionId = ref(""); const sqlFilePrefillDatabase = ref(""); +const sqlFilePrefillSchema = ref(); const sqlFilePrefillFilePath = ref(""); const sqlFilePrefillPreview = ref(); const diagramPrefillConnectionId = ref(""); @@ -221,6 +222,7 @@ export function useDialogSources() { if (v) { sqlFilePrefillConnectionId.value = v.connectionId; sqlFilePrefillDatabase.value = v.database; + sqlFilePrefillSchema.value = v.schema; sqlFilePrefillFilePath.value = v.filePath ?? ""; sqlFilePrefillPreview.value = v.preview; showSqlFileDialog.value = true; @@ -236,6 +238,7 @@ export function useDialogSources() { if (!open) { sqlFilePrefillConnectionId.value = ""; sqlFilePrefillDatabase.value = ""; + sqlFilePrefillSchema.value = undefined; sqlFilePrefillFilePath.value = ""; sqlFilePrefillPreview.value = undefined; } @@ -629,6 +632,7 @@ export function useDialogSources() { dataCompareSessionId, sqlFilePrefillConnectionId, sqlFilePrefillDatabase, + sqlFilePrefillSchema, sqlFilePrefillFilePath, sqlFilePrefillPreview, diagramPrefillConnectionId, diff --git a/apps/desktop/src/composables/useLargeSqlFileFallback.ts b/apps/desktop/src/composables/useLargeSqlFileFallback.ts index e7c9dae5f1..1a062ae91b 100644 --- a/apps/desktop/src/composables/useLargeSqlFileFallback.ts +++ b/apps/desktop/src/composables/useLargeSqlFileFallback.ts @@ -21,6 +21,7 @@ export function useLargeSqlFileStreamingFallback() { connectionStore.sqlFileSource = { connectionId: target.connectionId, database: target.database, + ...(target.schema ? { schema: target.schema } : {}), filePath: path, }; toast(t("sqlFile.largeFileExecutionOpened", { size: formatSqlFileSize(sizeBytes) }), 6000); diff --git a/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts b/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts index 0fbc91f524..770a6ae0ba 100644 --- a/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts +++ b/apps/desktop/src/composables/useSidebarTreeToolRuntime.ts @@ -62,6 +62,7 @@ export function useSidebarTreeToolRuntime(options: SidebarTreeToolRuntimeOptions connectionStore.sqlFileSource = { connectionId: activeNode.value.connectionId, database: activeNode.value.database ?? "", + ...(activeNode.value.schema ? { schema: activeNode.value.schema } : {}), }; } diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts index 1024176e8f..7f18ad9a38 100644 --- a/apps/desktop/src/lib/backend/tauri.ts +++ b/apps/desktop/src/lib/backend/tauri.ts @@ -5267,6 +5267,7 @@ export interface SqlFileRequest { executionId: string; connectionId: string; database: string; + schema?: string; filePath: string; continueOnError: boolean; txnSessionId?: string; diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts index d1b9ec23b8..08f18ed6a5 100644 --- a/apps/desktop/src/stores/connectionStore.ts +++ b/apps/desktop/src/stores/connectionStore.ts @@ -589,7 +589,7 @@ export const useConnectionStore = defineStore("connection", () => { schema?: string; tableName?: string; } | null>(null); - const sqlFileSource = ref<{ connectionId: string; database: string; filePath?: string; preview?: SqlFilePreview } | null>(null); + const sqlFileSource = ref<{ connectionId: string; database: string; schema?: string; filePath?: string; preview?: SqlFilePreview } | null>(null); const diagramSource = ref<{ connectionId: string; database: string; diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs index af5f7624dd..da0dbd9a87 100644 --- a/crates/dbx-core/src/connection/mod.rs +++ b/crates/dbx-core/src/connection/mod.rs @@ -8653,6 +8653,21 @@ mod tests { assert_eq!(scoped.database.as_deref(), Some("ORCL")); } + #[test] + fn connection_root_schema_databases_keep_the_configured_database() { + for database_type in [DatabaseType::Oracle, DatabaseType::Dameng, DatabaseType::OceanbaseOracle] { + let mut config = mysql_config(Some("tenant_service")); + config.db_type = database_type; + + let scoped = database_connection_config(&config, Some("APP")); + + assert_eq!(scoped.database.as_deref(), Some("tenant_service")); + } + + let mysql = database_connection_config(&mysql_config(Some("tenant_service")), Some("analytics")); + assert_eq!(mysql.database.as_deref(), Some("analytics")); + } + #[test] fn oracle_reuses_connection_scoped_pool_for_schema_database_keys() { assert_eq!( diff --git a/crates/dbx-core/src/data/sql_file_import.rs b/crates/dbx-core/src/data/sql_file_import.rs index 1ebe70272d..102c7ee803 100644 --- a/crates/dbx-core/src/data/sql_file_import.rs +++ b/crates/dbx-core/src/data/sql_file_import.rs @@ -589,7 +589,7 @@ async fn set_relational_constraints_enabled( &request.connection_id, &request.database, sql, - None, + request.schema.as_deref(), Some(token.clone()), QueryExecutionOptions::default(), ) @@ -604,10 +604,13 @@ async fn sql_file_transaction_schema(state: &AppState, request: &SqlFileRequest) let sessions = state.transaction_sessions.read().await; let session = sessions.get(session_id).ok_or("SQL file transaction session not found; no statements were retried")?; - if session.connection_id != request.connection_id || session.database != request.database { + if session.connection_id != request.connection_id + || session.database != request.database + || request.schema.as_ref().is_some_and(|schema| session.schema.as_ref() != Some(schema)) + { return Err("SQL file target does not match its manual transaction".to_string()); } - Ok(session.schema.clone()) + Ok(request.schema.clone().or_else(|| session.schema.clone())) } async fn with_sql_file_transaction( @@ -2592,7 +2595,7 @@ async fn execute_sql_file_statement( &request.connection_id, &request.database, sql, - None, + request.schema.as_deref(), Some(child_token), QueryExecutionOptions { execution_id: Some(execution_id), timeout_secs, ..Default::default() }, ) @@ -2704,6 +2707,7 @@ mod tests { execution_id: "file-missing-session".to_string(), connection_id: "unconfigured".to_string(), database: String::new(), + schema: None, file_path: String::new(), continue_on_error: false, selected_tables: None, @@ -3056,6 +3060,7 @@ mod tests { execution_id: "file-progress".to_string(), connection_id: "unconfigured".to_string(), database: String::new(), + schema: None, file_path: path.to_string_lossy().to_string(), continue_on_error: false, selected_tables: None, @@ -3488,6 +3493,7 @@ mod tests { execution_id: "gauss-stop-on-error".to_string(), connection_id: "gauss-stream".to_string(), database: String::new(), + schema: None, file_path: path.to_string_lossy().to_string(), continue_on_error: true, selected_tables: None, diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rs index 84e5209e6b..8fe82f16a4 100644 --- a/crates/dbx-core/src/query/mod.rs +++ b/crates/dbx-core/src/query/mod.rs @@ -11427,7 +11427,11 @@ for line in sys.stdin: request = json.loads(line) method = request.get("method") if method == "execute_query": - sql = request.get("params", {{}}).get("sql", "") + params = request.get("params", {{}}) + sql = params.get("sql", "") + if "REQUIRE_APP_SCHEMA" in sql and params.get("schema") != "APP": + print(json.dumps({{"jsonrpc": "2.0", "id": request["id"], "error": {{"code": -32000, "message": "schema was not forwarded"}}}}), flush=True) + continue if "RAISE_FILE_ERROR" in sql: print(json.dumps({{"jsonrpc": "2.0", "id": request["id"], "error": {{"code": -32000, "message": "file statement rejected"}}}}), flush=True) continue @@ -11491,7 +11495,7 @@ for line in sys.stdin: snapshot_rotation_safe: true, connection_id: "agent-conn".to_string(), database: "ORCL".to_string(), - schema: None, + schema: Some("APP".to_string()), }, ); (state, txn_session_id, dir) @@ -11503,6 +11507,7 @@ for line in sys.stdin: execution_id: "manual-file-test".to_string(), connection_id: "agent-conn".to_string(), database: "ORCL".to_string(), + schema: Some("APP".to_string()), file_path: String::new(), continue_on_error: false, selected_tables: None, @@ -11521,7 +11526,7 @@ for line in sys.stdin: crate::data::sql_file_import::execute_sql_file_content( &state, &request, - "UPDATE T SET V = 1; UPDATE T SET V = 2;", + "SELECT REQUIRE_APP_SCHEMA; UPDATE T SET V = 2;", CancellationToken::new(), std::time::Instant::now(), |event| events.push(event), @@ -11637,6 +11642,23 @@ for line in sys.stdin: assert!(events.is_empty()); assert!(state.transaction_sessions.read().await.contains_key(&session_id)); } + let mut request = manual_sql_file_request(&session_id); + request.schema = Some("OTHER".to_string()); + let mut events = Vec::new(); + let error = crate::data::sql_file_import::execute_sql_file_content( + &state, + &request, + "UPDATE T SET V = 1;", + CancellationToken::new(), + std::time::Instant::now(), + |event| events.push(event), + ) + .await + .unwrap_err(); + assert!(error.contains("target does not match")); + assert!(events.is_empty()); + assert!(state.transaction_sessions.read().await.contains_key(&session_id)); + rollback_manual_transaction(&state, &session_id).await.unwrap(); let error = crate::data::sql_file_import::execute_sql_file_content( &state, diff --git a/crates/dbx-core/tests/live_mysql57.rs b/crates/dbx-core/tests/live_mysql57.rs index 0bbdbd1213..e4e8ae6bcf 100644 --- a/crates/dbx-core/tests/live_mysql57.rs +++ b/crates/dbx-core/tests/live_mysql57.rs @@ -1297,6 +1297,7 @@ INSERT INTO install_check (id) VALUES (1), (2); execution_id: format!("exec-{suffix}"), connection_id: config.id.clone(), database: String::new(), + schema: None, file_path: std::env::temp_dir() .join(format!("issue-2356-mysql-install-{suffix}.sql")) .to_string_lossy() @@ -1386,6 +1387,7 @@ INSERT INTO children (parent_id) VALUES (LAST_INSERT_ID()); execution_id: format!("exec-{suffix}"), connection_id: config.id.clone(), database: String::new(), + schema: None, file_path: std::env::temp_dir() .join(format!("issue-7738-mysql-order-{suffix}.sql")) .to_string_lossy() @@ -1462,6 +1464,7 @@ async fn live_sql_file_import_preserves_raw_mysql_binary_literal_bytes() { execution_id: format!("exec-{suffix}"), connection_id: config.id.clone(), database: String::new(), + schema: None, file_path: std::env::temp_dir().join(format!("mysql-binary-dump-{suffix}.sql")).to_string_lossy().into_owned(), continue_on_error: false, selected_tables: None, diff --git a/crates/dbx-core/tests/live_mysql_database_export.rs b/crates/dbx-core/tests/live_mysql_database_export.rs index 458660b2ce..56a748475e 100644 --- a/crates/dbx-core/tests/live_mysql_database_export.rs +++ b/crates/dbx-core/tests/live_mysql_database_export.rs @@ -74,7 +74,7 @@ async fn live_mysql_selected_table_restore_preserves_unselected_tables() { assert_eq!(tables.len(), 2); let request = SqlFileRequest { txn_session_id: None, - execution_id: format!("restore-{suffix}-{compressed}"), connection_id: connection_id.clone(), database: database.clone(), file_path: path.display().to_string(), continue_on_error: false, + execution_id: format!("restore-{suffix}-{compressed}"), connection_id: connection_id.clone(), database: database.clone(), schema: None, file_path: path.display().to_string(), continue_on_error: false, selected_tables: Some(vec![SqlFileTable { database: Some(database.clone()), name: "chosen".into() }]), part_cooldown_ms: 0, skip_relational_constraints: false, @@ -91,7 +91,7 @@ async fn live_mysql_selected_table_restore_preserves_unselected_tables() { std::fs::write(&path, "DROP TABLE chosen; INSERT INTO chosen VALUES (1, 'bad'); CALL unexpected();").map_err(|e| e.to_string())?; let request = SqlFileRequest { txn_session_id: None, - execution_id: format!("invalid-{suffix}"), connection_id: connection_id.clone(), database: database.clone(), file_path: path.display().to_string(), continue_on_error: true, + execution_id: format!("invalid-{suffix}"), connection_id: connection_id.clone(), database: database.clone(), schema: None, file_path: path.display().to_string(), continue_on_error: true, selected_tables: Some(vec![SqlFileTable { database: None, name: "chosen".into() }]), part_cooldown_ms: 0, skip_relational_constraints: false, @@ -175,6 +175,7 @@ async fn live_mysql_database_export_restores_dependent_views() { execution_id: format!("live-mysql-import-{suffix}"), connection_id: connection_id.clone(), database: String::new(), + schema: None, file_path: file_path.to_string_lossy().to_string(), continue_on_error: false, selected_tables: None, diff --git a/crates/dbx-core/tests/live_oceanbase_sql_file_transaction.rs b/crates/dbx-core/tests/live_oceanbase_sql_file_transaction.rs index c08ca9b984..8d5e2ba66c 100644 --- a/crates/dbx-core/tests/live_oceanbase_sql_file_transaction.rs +++ b/crates/dbx-core/tests/live_oceanbase_sql_file_transaction.rs @@ -65,7 +65,7 @@ async fn live_oceanbase_sql_files_commit_rollback_failure_and_cancel() { query(&state, "file-writer", &database, &format!("INSERT INTO {table} VALUES (1, 10)")).await?; let mut request = SqlFileRequest { execution_id: "live-manual-file".to_string(), connection_id: "file-writer".to_string(), - database: database.clone(), file_path: String::new(), continue_on_error: false, + database: database.clone(), schema: None, file_path: String::new(), continue_on_error: false, selected_tables: None, part_cooldown_ms: 0, skip_relational_constraints: false, txn_session_id: None, }; let first = directory.path().join("first.sql"); diff --git a/crates/dbx-core/tests/live_postgres_all_schema_export.rs b/crates/dbx-core/tests/live_postgres_all_schema_export.rs index 924414f8a3..1437852312 100644 --- a/crates/dbx-core/tests/live_postgres_all_schema_export.rs +++ b/crates/dbx-core/tests/live_postgres_all_schema_export.rs @@ -149,6 +149,7 @@ async fn live_postgres_all_schema_export_restores_one_sql_file() { execution_id: format!("postgres-all-schema-import-{suffix}"), connection_id: target_connection_id.clone(), database: target_database.clone(), + schema: None, file_path: export_path.display().to_string(), continue_on_error: false, selected_tables: None, diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rs index 5586e78744..319b2f00c4 100644 --- a/crates/dbx-core/tests/live_sqlserver_completion.rs +++ b/crates/dbx-core/tests/live_sqlserver_completion.rs @@ -1301,6 +1301,7 @@ async fn live_sqlserver_sql_file_import_executes_go_batches() { execution_id: format!("live-sqlserver-file-{suffix}"), connection_id: connection_id.to_string(), database: database.clone(), + schema: None, file_path: "fixture.sql".to_string(), continue_on_error: false, selected_tables: None, diff --git a/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs b/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs index 8f889dc7e5..12fc4a35bb 100644 --- a/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs +++ b/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs @@ -210,6 +210,7 @@ async fn manual_e2e_sqlserver_default_split_zip_export_then_import_skip_relation execution_id: format!("e2e-import-{}", uuid::Uuid::new_v4()), connection_id: import_connection_id.to_string(), database: import_database.to_string(), + schema: None, file_path: extracted_paths[0].to_string_lossy().to_string(), continue_on_error: false, txn_session_id: None, diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rs index 67d7d6c207..391be13e4d 100644 --- a/crates/dbx-sql-core/src/sql.rs +++ b/crates/dbx-sql-core/src/sql.rs @@ -57,6 +57,10 @@ pub struct SqlFileRequest { pub execution_id: String, pub connection_id: String, pub database: String, + /// Optional schema/session namespace for databases where it is distinct + /// from the database used to establish the connection. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub schema: Option, pub file_path: String, pub continue_on_error: bool, /// Reuse a held manual transaction instead of committing through ordinary query execution. @@ -3008,9 +3012,36 @@ mod tests { fuzzy_subsequence_match, optimize_sql_file_import_statements, prepare_sql_file_statement, split_sql_script, split_sql_statement_ranges_with_options, split_sql_statements_for_database, starts_with_executable_sql_keyword, starts_with_executable_sql_keyword_for_database, starts_with_oracle_style_routine_body, SqlDialectProfile, - SqlFileStatementAction, SqlParsingOptions, SqlStatementSplitter, + SqlFileRequest, SqlFileStatementAction, SqlParsingOptions, SqlStatementSplitter, }; + #[test] + fn sql_file_request_schema_is_optional_and_round_trips_when_present() { + let legacy = serde_json::json!({ + "executionId": "legacy", + "connectionId": "mysql-1", + "database": "app", + "filePath": "backup.sql", + "continueOnError": false + }); + let legacy_request: SqlFileRequest = serde_json::from_value(legacy).unwrap(); + assert_eq!(legacy_request.schema, None); + assert!(serde_json::to_value(&legacy_request).unwrap().get("schema").is_none()); + + let with_schema = serde_json::json!({ + "executionId": "oracle-schema", + "connectionId": "oceanbase-oracle-1", + "database": "tenant_service", + "schema": "APP", + "filePath": "restore.sql", + "continueOnError": false + }); + let request: SqlFileRequest = serde_json::from_value(with_schema).unwrap(); + assert_eq!(request.database, "tenant_service"); + assert_eq!(request.schema.as_deref(), Some("APP")); + assert_eq!(serde_json::to_value(request).unwrap()["schema"], "APP"); + } + #[test] fn fuzzy_subsequence_match_matches_ordered_characters() { assert!(fuzzy_subsequence_match("system_user", "sysu"));