25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(query): only explicitly selected schemas qualify unqualified SQL Server names (#12819)
zipg34ace56b4d11
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex 73429bafae..cac9f4de58 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -3309,7 +3309,7 @@ async function newQuery(options: NewQueryOptions = {}) {includeDatabaseName: settingsStore.editorSettings.generateSqlIncludeDatabaseName,quoteIdentifiers: settingsStore.editorSettings.generateSqlQuoteIdentifiers,});- const tabId = queryStore.createTab(conn.id, target.database, undefined, "query", target.schema, initialSql, target.catalog);+ const tabId = queryStore.createTab(conn.id, target.database, undefined, "query", target.schema, initialSql, target.catalog, { schemaQualifiesSql: target.schemaQualifiesSql === true });if (initialSql) {const prefilledTab = queryStore.tabs.find((t) => t.id === tabId);if (prefilledTab) {@@ -3636,7 +3636,8 @@ async function clearActiveDefaultDatabase(tabId?: string) {function changeActiveSchema(tabId: string, schema: string | undefined) {const tab = resolveToolbarTab(tabId);if (!tab) return;- queryStore.updateSchema(tab.id, schema);+ // 工具栏选择是显式执行作用域:SQL Server 未限定表名会按它改写(#8951)。+ queryStore.updateSchema(tab.id, schema, { schemaQualifiesSql: true });if (tab.externalSqlPath) rememberExternalSqlFileTarget(tab.externalSqlPath, { connectionId: tab.connectionId, database: tab.database, catalog: tab.catalog, schema });}@@ -5506,7 +5507,7 @@ onUnmounted(() => {}"@open-database-search-target="(_tabId: string, target: any) => openDatabaseSearchTarget(target)"- @object-schema-change="(tabId: string, schema: string | undefined) => queryStore.updateSchema(tabId, schema)"+ @object-schema-change="(tabId: string, schema: string | undefined) => queryStore.updateSchema(tabId, schema, { schemaQualifiesSql: true })"@object-browser-viewport-change="(tabId: string, viewport: any) => queryStore.updateObjectBrowserViewport(tabId, viewport)"@object-browser-search-change="(tabId: string, query: string) => queryStore.updateObjectBrowserSearch(tabId, query)"@object-browser-filter-change="(tabId: string, filter: ObjectBrowserFilter) => queryStore.updateObjectBrowserFilter(tabId, filter)"diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 4d8f09ceb0..40b975f2c5 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -2191,7 +2191,7 @@ async function newQuery(options: { reuseQueryTabByScope?: boolean } = {}) {return;}if (openDefault) await queryStore.openDefaultQuery({ connectionId: node.connectionId, database: node.database, catalog: node.catalog });- else queryStore.createTab(node.connectionId, node.database, undefined, "query", node.schema, undefined, node.catalog);+ else queryStore.createTab(node.connectionId, node.database, undefined, "query", node.schema, undefined, node.catalog, { schemaQualifiesSql: true });return;}const connection = connectionStore.getConfig(node.connectionId);@@ -2265,7 +2265,7 @@ async function openMultiTableSqlTemplate(targets: Array<TreeNode & { connectionI}function openSqlTemplateTab(connectionId: string, database: string, schema: string | undefined, catalog: string | undefined, sql: string, title?: string) {- const tabId = queryStore.createTab(connectionId, database, title, "query", schema, undefined, catalog, { forceWordWrap: true });+ const tabId = queryStore.createTab(connectionId, database, title, "query", schema, undefined, catalog, { forceWordWrap: true, schemaQualifiesSql: true });queryStore.updateSql(tabId, sql);}diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.savedSqlContextMenu.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.savedSqlContextMenu.spec.tsindex dd51022153..9e4c435c71 100644--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.savedSqlContextMenu.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.savedSqlContextMenu.spec.ts@@ -157,7 +157,7 @@ describe("SidebarTreeRuntimeHost saved SQL context menu (#9127)", () => {expect(newQueryItem).toBeDefined();await newQueryItem?.action?.();- expect(createTabSpy).toHaveBeenCalledWith("conn-mysql", "app", undefined, "query", "public", undefined, "def");+ expect(createTabSpy).toHaveBeenCalledWith("conn-mysql", "app", undefined, "query", "public", undefined, "def", { schemaQualifiesSql: true });});it("includes new query option on saved-sql-file node", async () => {@@ -187,7 +187,7 @@ describe("SidebarTreeRuntimeHost saved SQL context menu (#9127)", () => {expect(newQueryItem).toBeDefined();await newQueryItem?.action?.();- expect(createTabSpy).toHaveBeenCalledWith("conn-mysql", "app", undefined, "query", "public", undefined, undefined);+ expect(createTabSpy).toHaveBeenCalledWith("conn-mysql", "app", undefined, "query", "public", undefined, undefined, { schemaQualifiesSql: true });});it("omits new query option on saved-sql-root when database type does not support queries", async () => {diff --git a/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts b/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.tsindex 7684a6f594..781164ed6b 100644--- a/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/jdbcDialect.spec.ts@@ -29,6 +29,7 @@ import {setGaussdbCountQueryDop,setGaussdbIdentifierQuoteStyle,setGaussdbTargetServerType,+ sqlServerQualifiesSqlWithTabSchema,supportsGaussdbIdentifierQuoteStyle,transferDatabaseTypeForConnection,codeMirrorSqlDialectForConnection,@@ -686,3 +687,14 @@ describe("object list schema", () => {expect(objectListSchemaForConnection({ db_type: dbType, username: "app_user" })).toBe("");});});++describe("schema qualification scope", () => {+ it("only scopes the SQL rewrite for SQL Server", () => {+ expect(sqlServerQualifiesSqlWithTabSchema({ db_type: "sqlserver" })).toBe(true);+ expect(sqlServerQualifiesSqlWithTabSchema({ db_type: "sqlserver", driver_profile: "sqlserver-legacy" })).toBe(true);+ expect(sqlServerQualifiesSqlWithTabSchema({ db_type: "postgres" })).toBe(false);+ expect(sqlServerQualifiesSqlWithTabSchema({ db_type: "iris" })).toBe(false);+ expect(sqlServerQualifiesSqlWithTabSchema({ db_type: "kingbase" })).toBe(false);+ expect(sqlServerQualifiesSqlWithTabSchema(undefined)).toBe(false);+ });+});diff --git a/apps/desktop/src/lib/__tests__/sql/newQueryContext.spec.ts b/apps/desktop/src/lib/__tests__/sql/newQueryContext.spec.tsindex 682bd80891..b9d879a05a 100644--- a/apps/desktop/src/lib/__tests__/sql/newQueryContext.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/newQueryContext.spec.ts@@ -467,3 +467,61 @@ describe("resolveNewQueryInitialSql", () => {).toBeUndefined();});});++describe("resolveNewQueryTarget schema qualification", () => {+ const connections = [{ id: "sql-1", host: "localhost", database: "app", default_schema: "dbo", db_type: "sqlserver" as const }];++ it("keeps an implicit tab schema for browsing but out of the SQL scope", () => {+ const target = resolveNewQueryTarget({+ activeTab: { connectionId: "sql-1", database: "app", schema: "core" },+ connections,+ preferredSource: "tab",+ });+ expect(target?.schema).toBe("core");+ expect(target?.schemaQualifiesSql).toBeUndefined();+ });++ it("propagates a schema the user explicitly selected on the tab", () => {+ const target = resolveNewQueryTarget({+ activeTab: { connectionId: "sql-1", database: "app", schema: "core", schemaQualifiesSql: true },+ connections,+ preferredSource: "tab",+ });+ expect(target?.schema).toBe("core");+ expect(target?.schemaQualifiesSql).toBe(true);+ });++ it("treats a sidebar schema node as an explicit selection", () => {+ const target = resolveNewQueryTarget({+ selectedTreeNode: { type: "schema", connectionId: "sql-1", database: "app", schema: "core", label: "core" },+ connections,+ preferredSource: "sidebar",+ });+ expect(target?.schema).toBe("core");+ expect(target?.schemaQualifiesSql).toBe(true);+ });++ it("does not promote the connection default schema from a connection node", () => {+ const target = resolveNewQueryTarget({+ selectedTreeNode: { type: "database", connectionId: "sql-1", database: "app", label: "app" },+ connections,+ preferredSource: "sidebar",+ });+ expect(target?.schema).toBe("dbo");+ expect(target?.schemaQualifiesSql).toBeUndefined();+ });++ it("treats an object schema from table metadata as explicit", () => {+ const target = resolveNewQueryTarget({+ activeTab: {+ connectionId: "sql-1",+ database: "app",+ tableMeta: { schema: "sales", tableName: "orders", columns: [], primaryKeys: [] },+ },+ connections,+ preferredSource: "tab",+ });+ expect(target?.schema).toBe("sales");+ expect(target?.schemaQualifiesSql).toBe(true);+ });+});diff --git a/apps/desktop/src/lib/database/jdbcDialect.ts b/apps/desktop/src/lib/database/jdbcDialect.tsindex a5005c6b6b..062f9d7c38 100644--- a/apps/desktop/src/lib/database/jdbcDialect.ts+++ b/apps/desktop/src/lib/database/jdbcDialect.ts@@ -297,6 +297,16 @@ export function connectionUsesSchemaExecutionContext(connection?: JdbcDialectConreturn connection?.db_type === "jdbc" && inferJdbcDialect(connection) === "databend";}+/**+ * SQL Server 没有会话级 Schema 切换:后端会把 SQL 文本里未限定的表名改写成+ * `[schema].[table]`(#8951)。因此页签 Schema 一旦随执行下发就会改变 SQL 语义,+ * 只有用户显式选择的 Schema 才可以参与改写;连接默认 / 恢复 / 保存的 Schema+ * 仅用于浏览与补全。IRIS/Kingbase 复用同一改写机制,但本次只收紧 SQL Server。+ */+export function sqlServerQualifiesSqlWithTabSchema(connection?: JdbcDialectConnection): boolean {+ return effectiveDatabaseTypeForConnection(connection) === "sqlserver";+}+export function connectionQueryExecutionSchema(connection: JdbcDialectConnection | undefined, database: string | undefined, schema: string | undefined, dataMode: boolean): string | undefined {if (connectionUsesSchemaExecutionContext(connection)) return schema || database || undefined;if (dataMode || connectionUsesDatabaseObjectTreeMode(connection)) return undefined;diff --git a/apps/desktop/src/lib/sql/newQueryContext.ts b/apps/desktop/src/lib/sql/newQueryContext.tsindex 23ee10d9a9..3f906fb2b0 100644--- a/apps/desktop/src/lib/sql/newQueryContext.ts+++ b/apps/desktop/src/lib/sql/newQueryContext.ts@@ -7,6 +7,8 @@ export interface NewQueryTarget {connectionId: string;database: string;schema?: string;+ /** 该 schema 是否由用户显式选择,可参与 SQL Server 的未限定表名改写。 */+ schemaQualifiesSql?: boolean;catalog?: string;shouldRefreshDefaultDatabase: boolean;}@@ -36,9 +38,11 @@ export function findTreeNodeById(nodes: TreeNode[], id: string | null | undefineexport function resolveNewQueryTarget(input: ResolveNewQueryTargetInput): NewQueryTarget | null {const primaryContext = input.preferredSource === "sidebar" ? input.selectedTreeNode || undefined : input.activeTab;const secondaryContext = input.preferredSource === "sidebar" ? input.activeTab : input.selectedTreeNode || undefined;- const primaryTarget = targetFromContext(primaryContext, input.connections);+ const primaryKind: NewQueryContextSource = input.preferredSource === "sidebar" ? "sidebar" : "tab";+ const secondaryKind: NewQueryContextSource = primaryKind === "sidebar" ? "tab" : "sidebar";+ const primaryTarget = targetFromContext(primaryContext, input.connections, primaryKind);if (primaryTarget) return primaryTarget;- const secondaryTarget = targetFromContext(secondaryContext, input.connections);+ const secondaryTarget = targetFromContext(secondaryContext, input.connections, secondaryKind);if (secondaryTarget) return secondaryTarget;const activeConnection = input.activeConnectionId ? input.connections.find((connection) => connection.id === input.activeConnectionId) : undefined;@@ -68,8 +72,9 @@ function singleOnlineSqlConnection(connections: ResolveNewQueryTargetInput["conn}function targetFromContext(- context: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta"> | Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | undefined,+ context: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta" | "schemaQualifiesSql"> | Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | undefined,connections: Pick<ConnectionConfig, "id" | "host" | "database" | "default_schema" | "db_type">[],+ contextKind: NewQueryContextSource,): NewQueryTarget | null {if (!context?.connectionId) return null;const connection = connections.find((item) => item.id === context.connectionId);@@ -78,10 +83,17 @@ function targetFromContext(const database = connection.db_type === "sqlite" ? normalizeSqliteNamespace(contextDatabase, connection) : contextDatabase;const objectBrowser = "objectBrowser" in context ? context.objectBrowser : undefined;const tableMeta = "tableMeta" in context ? context.tableMeta : undefined;+ const schema = context.schema ?? objectBrowser?.schema ?? tableMeta?.schema ?? connection.default_schema;+ // 侧栏节点自身的 schema 都是用户点出来的;连接/库节点回落到 default_schema+ // 时不算显式。页签只有显式选择(或来自更具体的对象上下文)才算显式,+ // 避免把默认/恢复的 schema 带进执行。+ const schemaQualifiesSql =+ schema === undefined ? false : contextKind === "sidebar" ? context.schema !== undefined : ("schemaQualifiesSql" in context && context.schemaQualifiesSql === true) || (!!objectBrowser?.schema && schema === objectBrowser.schema) || (!!tableMeta?.schema && schema === tableMeta.schema);return {connectionId: context.connectionId,database,- schema: context.schema ?? objectBrowser?.schema ?? tableMeta?.schema ?? connection.default_schema,+ schema,+ ...(schemaQualifiesSql ? { schemaQualifiesSql: true } : {}),catalog: context.catalog ?? objectBrowser?.catalog ?? tableMeta?.catalog,shouldRefreshDefaultDatabase: !context.database,};diff --git a/apps/desktop/src/stores/__tests__/queryStore.sqlServerSchemaScope.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.sqlServerSchemaScope.spec.tsnew file mode 100644index 0000000000..24cf99f814--- /dev/null+++ b/apps/desktop/src/stores/__tests__/queryStore.sqlServerSchemaScope.spec.ts@@ -0,0 +1,187 @@+import { createPinia, setActivePinia } from "pinia";+import { serializeOpenTabs } from "@/lib/app/openTabsPersistence";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ analyzeEditableQueryEditability: vi.fn(),+ cancelQuery: vi.fn(),+ closeClientConnectionSession: vi.fn(),+ closeQuerySession: vi.fn(),+ ensureConnected: vi.fn(),+ executeMulti: vi.fn(),+ executeMultiWithProgress: vi.fn(),+ executeQuery: vi.fn(),+ getConnectionConfig: vi.fn(),+ prepareQueryPaginationExecutionPlan: vi.fn(),+ saveOpenTabsState: vi.fn(),+ clearDataGridPendingSnapshot: vi.fn(),+ clearDataGridPendingSnapshotsForTab: vi.fn(),+}));++vi.mock("@/lib/backend/api", () => ({+ analyzeEditableQueryEditability: mocks.analyzeEditableQueryEditability,+ cancelQuery: mocks.cancelQuery,+ closeClientConnectionSession: mocks.closeClientConnectionSession,+ closeQuerySession: mocks.closeQuerySession,+ executeMulti: mocks.executeMulti,+ executeMultiWithProgress: mocks.executeMultiWithProgress,+ executeQuery: mocks.executeQuery,+ prepareQueryPaginationExecutionPlan: mocks.prepareQueryPaginationExecutionPlan,+ saveOpenTabsState: mocks.saveOpenTabsState,+}));++vi.mock("@/stores/connectionStore", () => ({+ useConnectionStore: () => ({+ ensureConnected: mocks.ensureConnected,+ getConfig: mocks.getConnectionConfig,+ recordConnectionLostError: vi.fn(),+ }),+}));++vi.mock("@/stores/settingsStore", () => ({+ useSettingsStore: () => ({+ editorSettings: { autoCalculateTotalRows: false, pageSize: 100, continueOnErrorOnBatch: false, defaultAutoKeepResults: false },+ }),+}));++vi.mock("@/composables/useDataGridEditor", () => ({+ clearDataGridPendingSnapshot: mocks.clearDataGridPendingSnapshot,+ clearDataGridPendingSnapshotsForTab: mocks.clearDataGridPendingSnapshotsForTab,+}));++function installLocalStorage() {+ const data = new Map<string, string>();+ vi.stubGlobal("localStorage", {+ getItem: vi.fn((key: string) => data.get(key) ?? null),+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),+ removeItem: vi.fn((key: string) => data.delete(key)),+ });+}++/** The 4th positional argument of executeMulti is the tab's schema. */+function executedSchema(): string | undefined {+ const call = mocks.executeMulti.mock.calls.at(-1);+ expect(call).toBeDefined();+ return call![3] as string | undefined;+}++describe("SQL Server 页签 Schema 的显式作用域", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ installLocalStorage();+ setActivePinia(createPinia());+ mocks.cancelQuery.mockResolvedValue(true);+ mocks.ensureConnected.mockResolvedValue(undefined);+ mocks.getConnectionConfig.mockReturnValue({ id: "sql-1", name: "SQL Server", db_type: "sqlserver", database: "app", query_timeout_secs: 30 });+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (options) => ({+ sqlToExecute: options.sql,+ pageSql: undefined,+ pageLimit: undefined,+ pageOffset: undefined,+ countSql: undefined,+ useAgentResultSession: false,+ }));+ mocks.analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "multiple-statements" });+ mocks.executeMulti.mockResolvedValue([{ columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]);+ mocks.executeMultiWithProgress.mockImplementation(async (connectionId, database, sql, onProgress, schema, options) => {+ const results = await mocks.executeMulti(connectionId, database, sql, schema, options?.executionId, options);+ results.forEach((result: any, index: number) => {+ onProgress({+ executionId: options?.executionId,+ statementIndex: index,+ completed: index + 1,+ total: results.length,+ success: result.execution_error !== true,+ executionTimeMs: result.execution_time_ms,+ affectedRows: result.affected_rows,+ error: result.error,+ });+ });+ return results;+ });+ });++ it("隐式 Schema(连接默认/恢复的页签/保存的 SQL)不参与 SQL Server 改写", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ // createTab 不传 schemaQualifiesSql 等价于恢复/默认来源。+ const tabId = store.createTab("sql-1", "app", "Query", "query", "core");+ await store.executeTabSql(tabId, "SELECT * FROM products");++ expect(executedSchema()).toBeUndefined();+ expect(store.tabs.find((tab) => tab.id === tabId)?.schema).toBe("core");+ });++ it("工具栏显式选择 Schema 后仍按它改写(保留 #8951)", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("sql-1", "app", "Query", "query");++ store.updateSchema(tabId, "core", { schemaQualifiesSql: true });+ await store.executeTabSql(tabId, "SELECT * FROM products");++ expect(executedSchema()).toBe("core");+ });++ it("侧栏 Schema 节点新建查询时同样是显式作用域", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("sql-1", "app", "Query", "query", "core", undefined, undefined, { schemaQualifiesSql: true });+ await store.executeTabSql(tabId, "SELECT * FROM products");++ expect(executedSchema()).toBe("core");+ });++ it.each([true, false])("复制页签保留 Schema 的执行作用域(显式选择:%s)", async (explicit) => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const sql = "UPDATE products SET status = 'done' WHERE id = 1";+ const tabId = store.createTab("sql-1", "app", "Query", "query", "core", sql);+ if (explicit) store.updateSchema(tabId, "core", { schemaQualifiesSql: true });+ const expectedSchema = explicit ? "core" : undefined;+ await store.executeTabSql(tabId, sql);+ expect(executedSchema()).toBe(expectedSchema);++ store.duplicateTab(tabId);+ const duplicated = store.tabs.find((tab) => tab.id !== tabId)!;+ expect(duplicated.schema).toBe("core");+ expect(duplicated.sql).toBe(sql);+ await store.executeTabSql(duplicated.id, duplicated.sql);++ expect(executedSchema()).toBe(expectedSchema);+ });++ it("清空或切换数据库会同时清掉显式作用域", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("sql-1", "app", "Query", "query", "core", undefined, undefined, { schemaQualifiesSql: true });+ store.updateDatabase(tabId, "other");+ const tab = store.tabs.find((item) => item.id === tabId)!;+ expect(tab.schema).toBeUndefined();+ expect(tab.schemaQualifiesSql).toBeUndefined();++ store.updateSchema(tabId, "core", { schemaQualifiesSql: true });+ store.updateSchema(tabId, undefined);+ expect(tab.schemaQualifiesSql).toBeUndefined();+ });++ it("非 SQL Server 数据库不受显式作用域限制", async () => {+ mocks.getConnectionConfig.mockReturnValue({ id: "pg-1", name: "PG", db_type: "postgres", database: "app", query_timeout_secs: 30 });+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("pg-1", "app", "Query", "query", "reporting");+ await store.executeTabSql(tabId, 'SELECT * FROM "users"');++ expect(executedSchema()).toBe("reporting");+ });++ it("显式作用域不随页签持久化,恢复后回到服务器默认解析", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("sql-1", "app", "Query", "query", "core", undefined, undefined, { schemaQualifiesSql: true });+ const tab = store.tabs.find((item) => item.id === tabId)!;++ expect(serializeOpenTabs([tab])[0]).not.toHaveProperty("schemaQualifiesSql");+ });+});diff --git a/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.tsindex bd3f68c40c..593693d13e 100644--- a/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.sqlserverExplain.spec.ts@@ -84,7 +84,7 @@ describe("queryStore SQL Server explain", () => {it("executes all SHOWPLAN batches in an isolated session and closes it", async () => {const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();- const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");+ const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo", undefined, undefined, { schemaQualifiesSql: true });await store.explainTabSql(tabId, sourceSql, "sqlserver");@@ -118,7 +118,7 @@ describe("queryStore SQL Server explain", () => {mocks.executeMulti.mockResolvedValue([rowsResult, planResult]);const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();- const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");+ const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo", undefined, undefined, { schemaQualifiesSql: true });await store.explainTabSql(tabId, sourceSql, "sqlserver", "autotrace");@@ -137,7 +137,7 @@ describe("queryStore SQL Server explain", () => {it("keeps SHOWPLAN when the autotrace toggle is off", async () => {const { useQueryStore } = await import("@/stores/queryStore");const store = useQueryStore();- const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");+ const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo", undefined, undefined, { schemaQualifiesSql: true });await store.explainTabSql(tabId, sourceSql, "sqlserver", "explain");@@ -179,4 +179,16 @@ describe("queryStore SQL Server explain", () => {expect(mocks.executeQuery.mock.calls[0]?.[2]).toBe("SET SHOWPLAN_XML ON;");await vi.waitFor(() => expect(mocks.closeClientConnectionSession).toHaveBeenCalledTimes(1));});++ it("keeps an implicit tab schema out of the SHOWPLAN batches", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ // 恢复的页签 / 连接默认 schema:只用于浏览,不参与 SQL 改写。+ const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");++ await store.explainTabSql(tabId, sourceSql, "sqlserver");++ expect(mocks.executeQuery.mock.calls[0]?.slice(0, 4)).toEqual(["sqlserver-1", "dbx_explain_plan_test", "SET SHOWPLAN_XML ON;", undefined]);+ expect(mocks.executeMulti.mock.calls[0]?.slice(0, 4)).toEqual(["sqlserver-1", "dbx_explain_plan_test", sourceSql, undefined]);+ });});diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 2db4768f4d..011c062dba 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -96,7 +96,16 @@ import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";import { MetadataTaskLimiter } from "@/lib/metadata/metadataTaskLimiter";import { formatDdlForDisplay } from "@/lib/sql/ddlDisplay";import { buildTableSelectSql, quoteTableDataIdentifier } from "@/lib/table/tableSelectSql";-import { connectionObjectTreeNodeSchema, connectionQueryExecutionSchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, gaussdbCountQueryDopHint, jdbcConnectionUsesDriverRowOffset, metadataSchemaForConnection } from "@/lib/database/jdbcDialect";+import {+ connectionObjectTreeNodeSchema,+ connectionQueryExecutionSchema,+ connectionUsesDatabaseObjectTreeMode,+ effectiveDatabaseTypeForConnection,+ gaussdbCountQueryDopHint,+ jdbcConnectionUsesDriverRowOffset,+ metadataSchemaForConnection,+ sqlServerQualifiesSqlWithTabSchema,+} from "@/lib/database/jdbcDialect";import { frontendQueryTimeoutDelayMs, frontendQueryTimeoutSecsForSql, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";import { queryResultNameFromPreamble, queryResultSourceLabel, queryResultSourceNameParts } from "@/lib/sql/queryResultSource";import { sqlServerCountUsesLocalTempTable } from "@/lib/query/queryResultCountSession";@@ -326,6 +335,8 @@ function isViewOnlySourceWithoutEditablePayload(initialEditing: boolean | undefiinterface UpdateExecutionTargetOptions {persistSavedSqlTarget?: boolean;+ /** 用户显式选择了该 Schema(工具栏/对象选择器),允许 SQL Server 改写。 */+ schemaQualifiesSql?: boolean;}type DroppedTableObjectType = "TABLE" | "VIEW" | "MATERIALIZED_VIEW";@@ -1689,12 +1700,23 @@ export const useQueryStore = defineStore("query", () => {return run?.multiDbExecution?.kind === "multi-db" ? run.multiDbExecution.target : undefined;}+ /**+ * SQL Server 的 Schema 参数会触发后端把未限定表名改写为 `[schema].[table]`。+ * 只有用户显式选择的 Schema 才能参与该改写;默认/恢复/保存的 Schema 继续用于+ * 浏览与补全,但不再改变 SQL 语义。其它数据库原样返回。+ */+ function queryExecutionSchemaForTab(tab: QueryTab): string | undefined {+ if (!tab.schema) return undefined;+ const connection = useConnectionStore().getConfig(tab.connectionId);+ return sqlServerQualifiesSqlWithTabSchema(connection) && tab.schemaQualifiesSql !== true ? undefined : tab.schema;+ }+function queryResultExecutionLocation(tab: QueryTab) {const target = activeResultExecutionTarget(tab.id);return {connectionId: target?.connectionId ?? tab.connectionId,database: target?.database ?? tab.database,- schema: target?.schema ?? tab.schema,+ schema: target?.schema ?? queryExecutionSchemaForTab(tab),catalog: target?.catalog ?? tab.catalog,};}@@ -3028,12 +3050,13 @@ export const useQueryStore = defineStore("query", () => {schema?: string,initialSql?: string,catalog?: string,- options: { forceNew?: boolean; activate?: boolean; forceWordWrap?: boolean; insertAfterActive?: boolean; sourceView?: boolean; reuseQueryTabByScope?: boolean } = {},+ options: { forceNew?: boolean; activate?: boolean; forceWordWrap?: boolean; insertAfterActive?: boolean; sourceView?: boolean; reuseQueryTabByScope?: boolean; schemaQualifiesSql?: boolean } = {},) {if (title && !options.forceNew) {const existing = findTabByIdentity(connectionId, database, title, mode, schema, catalog);if (existing) {if (options.sourceView) existing.sourceView = true;+ if (options.schemaQualifiesSql && existing.schema) existing.schemaQualifiesSql = true;switchTab(existing.id);return existing.id;}@@ -3046,6 +3069,7 @@ export const useQueryStore = defineStore("query", () => {// in their own right and never take over the activation slot.const existing = tabs.value.find((tab) => tab.mode === "query" && !tab.savedSqlId && !tab.externalSqlPath && !tab.objectSource && tab.connectionId === connectionId && tab.database === database && (tab.schema || "") === (schema || "") && (tab.catalog || "") === (catalog || ""));if (existing) {+ if (options.schemaQualifiesSql && existing.schema) existing.schemaQualifiesSql = true;switchTab(existing.id);return existing.id;}@@ -3062,6 +3086,7 @@ export const useQueryStore = defineStore("query", () => {connectionId,database,schema,+ schemaQualifiesSql: schema && options.schemaQualifiesSql ? true : undefined,catalog,sql: initialSql ?? "",isExecuting: false,@@ -3114,7 +3139,7 @@ export const useQueryStore = defineStore("query", () => {return existing.id;}- const id = createTab(options.connectionId, options.database, options.title, "query", options.schema, options.sql, options.catalog, { forceNew: true, sourceView: true });+ const id = createTab(options.connectionId, options.database, options.title, "query", options.schema, options.sql, options.catalog, { forceNew: true, sourceView: true, schemaQualifiesSql: true });setObjectSource(id, options.objectSource);return id;}@@ -3178,7 +3203,7 @@ export const useQueryStore = defineStore("query", () => {return existing.id;}- const id = createTab(options.connectionId, options.database, options.title, "query", options.schema, "", options.catalog, { forceNew: true, sourceView: true });+ const id = createTab(options.connectionId, options.database, options.title, "query", options.schema, "", options.catalog, { forceNew: true, sourceView: true, schemaQualifiesSql: true });const tab = tabs.value.find((candidate) => candidate.id === id);if (tab) tab.sourceLoad = { startedAt: Date.now(), initialEditing: options.initialEditing, request: { ...options.request } };void loadObjectSourceIntoTab(id);@@ -5100,6 +5125,7 @@ export const useQueryStore = defineStore("query", () => {connectionId: original.connectionId,database: original.database,schema: original.schema,+ schemaQualifiesSql: original.schemaQualifiesSql,catalog: original.catalog,sql: original.sql,originalSql: "",@@ -6277,6 +6303,7 @@ export const useQueryStore = defineStore("query", () => {void closeClientConnectionSession(tab);tab.database = database;tab.schema = undefined;+ tab.schemaQualifiesSql = undefined;tab.objectBrowser = undefined;clearResultPayload(tab);tab.lastExecutedSql = undefined;@@ -6311,6 +6338,7 @@ export const useQueryStore = defineStore("query", () => {tab.catalog = catalog;tab.database = database;tab.schema = undefined;+ tab.schemaQualifiesSql = undefined;tab.objectBrowser = undefined;clearResultPayload(tab);tab.lastExecutedSql = undefined;@@ -6323,7 +6351,12 @@ export const useQueryStore = defineStore("query", () => {function updateSchema(id: string, schema: string | undefined, options: UpdateExecutionTargetOptions = {}) {const tab = tabs.value.find((t) => t.id === id);- if (!tab || tab.schema === schema) return;+ if (!tab) return;+ if (tab.schema === schema) {+ // 同一个 Schema 再次被显式选择时,也要把它提升为执行作用域。+ if (schema !== undefined && options.schemaQualifiesSql) tab.schemaQualifiesSql = true;+ return;+ }if (tab.isExplaining) {void cancelTabExplain(id);clearExplain(tab);@@ -6339,6 +6372,9 @@ export const useQueryStore = defineStore("query", () => {clearExplain(tab);}tab.schema = schema;+ // 只有显式选择才允许参与 SQL Server 的未限定表名改写;隐式来源(连接默认、+ // 恢复的页签、保存的 SQL、外部文件)只更新浏览/补全上下文。+ tab.schemaQualifiesSql = schema !== undefined && options.schemaQualifiesSql === true ? true : undefined;if (tab.mode === "objects") tab.objectBrowser = { ...tab.objectBrowser, schema, filter: undefined, viewport: undefined };persistSavedSqlExecutionTarget(tab, options);}@@ -6356,6 +6392,7 @@ export const useQueryStore = defineStore("query", () => {tab.catalog = undefined;tab.objectBrowser = undefined;tab.schema = undefined;+ tab.schemaQualifiesSql = undefined;clearResultPayload(tab);tab.lastExecutedSql = undefined;tab.resultBaseSql = undefined;@@ -7862,6 +7899,12 @@ export const useQueryStore = defineStore("query", () => {await connStore.ensureDatabaseCompatibilityMode(executionConnectionId, targetDatabase || conn?.database);}const targetSchema = resumedExecutionTarget ? resumedExecutionTarget.schema : targetContext?.scope === "connection" ? undefined : (databaseTargetContext?.schema ?? executionTarget?.schema ?? tab.schema);+ // SQL Server 没有会话级 Schema:schema 参数只用于把未限定表名改写成+ // `[schema].[table]`。多库/批量恢复目标里的 schema 是上次真正下发过的值,+ // 页签 schema 则必须由用户显式选择,避免默认/恢复的 schema 改变 SQL 语义。+ const schemaFromExplicitTarget = resumedExecutionTarget?.schema !== undefined || databaseTargetContext?.schema !== undefined || executionTarget?.schema !== undefined;+ const schemaQualifiesSql = schemaFromExplicitTarget || tab.schemaQualifiesSql === true;+ const executionSchema = connectionQueryExecutionSchema(conn, targetDatabase, sqlServerQualifiesSqlWithTabSchema(conn) && !schemaQualifiesSql ? undefined : targetSchema, tab.mode === "data");const executionDatabase = targetDatabase;const sqlStatementParameterOptions = sqlStatementParameterOptionsForCompatibility(effectiveDbType,@@ -7882,7 +7925,7 @@ export const useQueryStore = defineStore("query", () => {connectionId: executionConnectionId,catalog: executionCatalog,database: targetDatabase,- schema: targetSchema,+ schema: executionSchema,},sqlStatementParameterOptions,)@@ -8686,7 +8729,6 @@ export const useQueryStore = defineStore("query", () => {executedSql: sqlToExecute,};- const executionSchema = connectionQueryExecutionSchema(conn, targetDatabase, targetSchema, tab.mode === "data");// Jumping to a non-zero offset without a live cursor session: the plan// could not rewrite the SQL for these engines, so a plain execution// would return the first page again (#8993).@@ -9239,7 +9281,7 @@ export const useQueryStore = defineStore("query", () => {tabId: id,connectionId: executionConnectionId,database: executionDatabase,- schema: executionTarget?.schema ?? current.schema,+ schema: executionSchema,catalog: executionCatalog,countSql,countSqlTarget: dataCountTarget@@ -9544,7 +9586,7 @@ export const useQueryStore = defineStore("query", () => {}try {const mode = databaseType === "dameng" && explainMode === "autotrace" ? "autotrace" : "explain";- const planText = (await api.getExplainInfo(tab.connectionId, tab.database, tab.schema, sql, mode)) as string | undefined;+ const planText = (await api.getExplainInfo(tab.connectionId, tab.database, queryExecutionSchemaForTab(tab), sql, mode)) as string | undefined;const current = tabs.value.find((t) => t.id === id);if (current?.explainExecutionId === executionId) {if (planText && planText.length > 0) {@@ -9613,7 +9655,7 @@ export const useQueryStore = defineStore("query", () => {let tableResult: QueryResult | undefined;let tableError: unknown;try {- tableResult = await api.executeQuery(tab.connectionId, tab.database, tableSql, tab.schema, executionId, {+ tableResult = await api.executeQuery(tab.connectionId, tab.database, tableSql, queryExecutionSchemaForTab(tab), executionId, {clientSessionId,catalog: tab.catalog,timeoutSecs: queryTimeoutSecs,@@ -9625,7 +9667,7 @@ export const useQueryStore = defineStore("query", () => {tableSql = compatibility.fallbackSql;tab.explainTableSql = tableSql;try {- tableResult = await api.executeQuery(tab.connectionId, tab.database, tableSql, tab.schema, executionId, {+ tableResult = await api.executeQuery(tab.connectionId, tab.database, tableSql, queryExecutionSchemaForTab(tab), executionId, {clientSessionId,catalog: tab.catalog,timeoutSecs: queryTimeoutSecs,@@ -9666,7 +9708,7 @@ export const useQueryStore = defineStore("query", () => {try {const latest = tabs.value.find((t) => t.id === id);if (latest?.explainExecutionId === executionId) latest.explainSql = jsonBuilt.sql;- const jsonResult = await api.executeQuery(tab.connectionId, tab.database, jsonBuilt.sql, tab.schema, executionId, {+ const jsonResult = await api.executeQuery(tab.connectionId, tab.database, jsonBuilt.sql, queryExecutionSchemaForTab(tab), executionId, {clientSessionId,catalog: tab.catalog,timeoutSecs: queryTimeoutSecs,@@ -9725,7 +9767,7 @@ export const useQueryStore = defineStore("query", () => {tab.explainClientSessionId = clientSessionId;let planCaptureEnabled = false;try {- await api.executeQuery(tab.connectionId, tab.database, planCaptureOn, tab.schema, executionId, {+ await api.executeQuery(tab.connectionId, tab.database, planCaptureOn, queryExecutionSchemaForTab(tab), executionId, {clientSessionId,timeoutSecs: queryTimeoutSecs,executionMode: "simple",@@ -9735,7 +9777,7 @@ export const useQueryStore = defineStore("query", () => {return { ok: true as const, sql: built.sql };}- const results = await api.executeMulti(tab.connectionId, tab.database, sql, tab.schema, executionId, {+ const results = await api.executeMulti(tab.connectionId, tab.database, sql, queryExecutionSchemaForTab(tab), executionId, {clientSessionId,timeoutSecs: queryTimeoutSecs,executionMode: "simple",@@ -9763,7 +9805,7 @@ export const useQueryStore = defineStore("query", () => {} finally {if (planCaptureEnabled) {try {- await api.executeQuery(tab.connectionId, tab.database, planCaptureOff, tab.schema, undefined, {+ await api.executeQuery(tab.connectionId, tab.database, planCaptureOff, queryExecutionSchemaForTab(tab), undefined, {clientSessionId,timeoutSecs: queryTimeoutSecs > 0 ? Math.min(queryTimeoutSecs, 5) : 5,executionMode: "simple",@@ -9797,7 +9839,7 @@ export const useQueryStore = defineStore("query", () => {const clientSessionId = postgresAnalyze ? `${tabClientSessionId(tab, "explain")}:${executionId}` : tabClientSessionId(tab, "explain");if (postgresAnalyze) tab.explainClientSessionId = clientSessionId;try {- const result = await api.executeQuery(tab.connectionId, tab.database, built.sql, tab.schema, executionId, {+ const result = await api.executeQuery(tab.connectionId, tab.database, built.sql, queryExecutionSchemaForTab(tab), executionId, {clientSessionId,catalog: tab.catalog,timeoutSecs: queryTimeoutSecs,@@ -10705,7 +10747,7 @@ export const useQueryStore = defineStore("query", () => {exportId,connectionId: tab.connectionId,database: tab.database,- schema: tab.schema,+ schema: queryExecutionSchemaForTab(tab),sql: executableSql,queryBaseSql: executableSql,databaseType: effectiveDbType,diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 49950c431e..1630f9a8b6 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -2175,6 +2175,17 @@ export interface QueryTab {/** Optional branch context for a driver-profile database workspace. */workspaceBranch?: string;schema?: string;+ /**+ * 该 Schema 是否由用户为当前页签显式选择(工具栏 / 侧栏 Schema 节点)。+ *+ * SQL Server 没有会话级 Schema 切换,后端会把未限定的表名按页签 Schema+ * 改写(#8951)。只有显式选择才能参与改写:连接默认 Schema、恢复的页签、+ * 保存的 SQL、外部文件带来的 Schema 只用于浏览/补全/预填,否则+ * `SELECT * FROM t` 会被错误地限定到非默认 Schema。+ *+ * 该字段是运行时状态,不随页签持久化,恢复的页签因此回到服务器默认解析。+ */+ schemaQualifiesSql?: boolean;/** Doris / StarRocks multi-catalog: the external catalog this tab's* database belongs to (undefined for internal/default catalog). */catalog?: string;diff --git a/packages/app-tests/externalSqlFileTargetPersistence.test.ts b/packages/app-tests/externalSqlFileTargetPersistence.test.tsindex 60ae77d2ca..c554b45cf6 100644--- a/packages/app-tests/externalSqlFileTargetPersistence.test.ts+++ b/packages/app-tests/externalSqlFileTargetPersistence.test.ts@@ -56,7 +56,7 @@ test("external SQL catalog changes persist their complete target", () => {test("external SQL schema changes persist their complete target", () => {const source = functionSource(appSource, "function changeActiveSchema", "function openGitHub");- assert.ok(source.includes("queryStore.updateSchema(tab.id, schema)"));+ assert.ok(source.includes("queryStore.updateSchema(tab.id, schema, { schemaQualifiesSql: true })"));assert.ok(source.includes("rememberExternalSqlFileTarget"));assert.ok(source.includes("{ connectionId: tab.connectionId, database: tab.database, catalog: tab.catalog, schema }"));});diff --git a/packages/app-tests/newQueryContext.test.ts b/packages/app-tests/newQueryContext.test.tsindex 741a4fd0d5..a83f8b3d73 100644--- a/packages/app-tests/newQueryContext.test.ts+++ b/packages/app-tests/newQueryContext.test.ts@@ -83,6 +83,7 @@ test("new query target uses the selected sidebar node when there is no active taconnectionId: "conn-tree",database: "reporting",schema: "public",+ schemaQualifiesSql: true,catalog: undefined,shouldRefreshDefaultDatabase: false,});