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(grid): 无主键表行定位器被引擎拒绝时自动降级,修复 Hologres 单击表报错 (#12647) (#12687)
ericbyz72a584568f63
diff --git a/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridActions.spec.tsindex c43c90f04c..cb41e0396b 100644--- a/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts+++ b/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts@@ -2,6 +2,7 @@ import { computed, reactive } from "vue";import { beforeEach, describe, expect, it, vi } from "vitest";import { useDataGridActions } from "@/composables/useDataGridActions";import { clearTableMetadataCache } from "@/lib/metadata/tableMetadataCache";+import { resetRowIdLocatorStateForTests } from "@/lib/table/tableRowIdSupport";import { MAX_QUERY_RESULT_MAX_ROWS } from "@/lib/dataGrid/queryResultRowLimit";import { restoredDataTabReloadFilters } from "@/lib/table/tableDataRefresh";import type { IndexInfo, QueryTab } from "@/types/database";@@ -138,6 +139,7 @@ function tableDataTab(patch: Partial<QueryTab> = {}): QueryTab {describe("useDataGridActions", () => {beforeEach(() => {clearTableMetadataCache();+ resetRowIdLocatorStateForTests();vi.clearAllMocks();mocks.executeTabSql.mockReset();mocks.deleteSchemaCachePrefix.mockReset().mockResolvedValue(undefined);@@ -1449,4 +1451,73 @@ describe("useDataGridActions", () => {expect(mocks.executeTabSql).toHaveBeenCalledWith("tab-1", "SELECT sorted", expect.objectContaining({ pagination: { limit: 10, offset: 0 }, preserveTotalRowCountDuringExecution: true }));});++ it("retries a failed keyless-table load without the row-id locator and remembers the connection (#12647)", async () => {+ const keylessColumn = { name: "id", data_type: "integer", is_nullable: true, column_default: null, is_primary_key: false, extra: null };+ // refresh 意图会用 getColumns 重建元数据:保持重建后仍然无主键+ mocks.getColumns.mockResolvedValue([keylessColumn]);+ const tab = tableDataTab({+ tableMeta: {+ schema: "public",+ tableName: "events",+ tableType: "TABLE",+ columns: [keylessColumn],+ primaryKeys: [],+ },+ });+ mocks.tabs.push(tab);+ const locatorSql = `SELECT tableoid::text || ':' || ctid::text || ':' || xmin::text AS "__DBX_ROWID", * FROM "public"."events" LIMIT 100 OFFSET 0;`;+ const fallbackSql = `SELECT * FROM "public"."events" LIMIT 100 OFFSET 0;`;+ mocks.buildTableSelectSql.mockImplementation(({ includeRowId }: { includeRowId?: boolean }) => Promise.resolve(includeRowId ? locatorSql : fallbackSql));+ mocks.executeTabSql.mockImplementation(async (_id: string, sql: string) => {+ tab.result = sql.includes("__DBX_ROWID")+ ? ({ columns: ["Error"], rows: [["ERROR: Variable tableoid ... can't be found in query translation"]], affected_rows: 0, execution_time_ms: 1, execution_error: true } as QueryTab["result"])+ : ({ columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 } as QueryTab["result"]);+ });+ const actions = useDataGridActions(computed(() => tab));++ await actions.onReloadData(tab.id, tab.sql, "", "", "", 100, 0, "refresh");++ // 首次带定位器失败 → 降级重试一次成功+ expect(mocks.executeTabSql).toHaveBeenCalledTimes(2);+ expect(mocks.executeTabSql).toHaveBeenNthCalledWith(2, "tab-1", fallbackSql, expect.objectContaining({ pagination: { limit: 100, offset: 0 } }));+ expect(mocks.buildTableSelectSql).toHaveBeenLastCalledWith(expect.objectContaining({ includeRowId: false }));+ expect(tab.result?.execution_error).toBeUndefined();+ // 连接已记忆:后续加载不再注入定位器+ mocks.executeTabSql.mockClear();+ mocks.buildTableSelectSql.mockClear();+ await actions.onReloadData(tab.id, tab.sql, "", "", "", 100, 0, "refresh");+ expect(mocks.buildTableSelectSql).toHaveBeenCalledWith(expect.objectContaining({ includeRowId: false }));+ expect(mocks.executeTabSql).toHaveBeenCalledTimes(1);+ expect(mocks.executeTabSql).toHaveBeenCalledWith("tab-1", fallbackSql, expect.anything());+ });++ it("restores the locator when the fallback retry also fails so the real error stays visible (#12647)", async () => {+ const keylessColumn = { name: "id", data_type: "integer", is_nullable: true, column_default: null, is_primary_key: false, extra: null };+ mocks.getColumns.mockResolvedValue([keylessColumn]);+ const tab = tableDataTab({+ tableMeta: {+ schema: "public",+ tableName: "events",+ tableType: "TABLE",+ columns: [keylessColumn],+ primaryKeys: [],+ },+ });+ mocks.tabs.push(tab);+ const errorResult = { columns: ["Error"], rows: [["ERROR: relation does not exist"]], affected_rows: 0, execution_time_ms: 1, execution_error: true } as QueryTab["result"];+ mocks.buildTableSelectSql.mockImplementation(({ includeRowId }: { includeRowId?: boolean }) => Promise.resolve(includeRowId ? `SELECT ... AS "__DBX_ROWID", * FROM t` : `SELECT * FROM t`));+ mocks.executeTabSql.mockImplementation(async () => {+ tab.result = errorResult;+ });+ const actions = useDataGridActions(computed(() => tab));++ await actions.onReloadData(tab.id, tab.sql, "", "", "", 100, 0, "refresh");++ expect(mocks.executeTabSql).toHaveBeenCalledTimes(2);+ // 重试也失败:标记还原,后续仍按原行为注入定位器+ mocks.buildTableSelectSql.mockClear();+ await actions.onReloadData(tab.id, tab.sql, "", "", "", 100, 0, "refresh");+ expect(mocks.buildTableSelectSql).toHaveBeenCalledWith(expect.objectContaining({ includeRowId: true }));+ });});diff --git a/apps/desktop/src/composables/useDataGridActions.ts b/apps/desktop/src/composables/useDataGridActions.tsindex 29cd356854..fa8b90e1d5 100644--- a/apps/desktop/src/composables/useDataGridActions.ts+++ b/apps/desktop/src/composables/useDataGridActions.ts@@ -9,6 +9,7 @@ import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit";import { tableDataLargeValuePreviewOptions, tableDataPreviewRowBudget } from "@/lib/dataGrid/dataGridLargeValues";import { elasticsearchCursorPageJumpRequestCount } from "@/lib/dataGrid/dataGridPagination";import { editablePrimaryKeys, shouldIncludeSyntheticRowId } from "@/lib/table/tableEditing";+import { markRowIdLocatorSupported, markRowIdLocatorUnsupported, rowIdLocatorUnsupported, shouldKeepRowIdLocatorDisabled, shouldRetryWithoutRowIdLocator } from "@/lib/table/tableRowIdSupport";import { tableMetaForDataTab } from "@/lib/table/tableDataTabMeta";import { loadVirtualRowIdentifier } from "@/lib/table/virtualRowIdentifier";import * as api from "@/lib/backend/api";@@ -115,7 +116,9 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)const effectiveDbType = effectiveDatabaseTypeForConnection(config);const tableMeta = tableMetaForDataTab(tab);const primaryKeys = tab.tableMeta ? tab.tableMeta.primaryKeys : (tableMeta?.primaryKeys ?? []);- const useRowId = shouldIncludeSyntheticRowId(effectiveDbType, primaryKeys, tableMeta?.tableType);+ // 已确认该连接拒绝合成行定位器(如 Hologres 拒绝 tableoid,#12647)时不再注入,+ // 避免无主键表每次打开都报错。+ const useRowId = shouldIncludeSyntheticRowId(effectiveDbType, primaryKeys, tableMeta?.tableType) && !rowIdLocatorUnsupported(tab.connectionId);// 列投影只信任真实元数据列:tableMetaForDataTab 的 fallback 列来自查询// 结果(可能是失败结果的 ["Error"]),进入 SQL 会生成非法投影;// 真实列缺失时省略 columns 让 builder 生成 SELECT *@@ -144,6 +147,27 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)});}+ // 行定位器被服务端拒绝时的降级执行(#12647):首次带定位器的加载失败后,+ // 去掉定位器重试一次;重试成功才记住该连接,之后由 buildTableSql 直接跳过+ // 定位器。重试也失败则还原标记,让真实的服务端错误可见。+ async function executeTableDataSqlWithRowIdFallback(tab: QueryTab, sql: string, executeOptions: Parameters<typeof queryStore.executeTabSql>[2], rebuildSql: () => Promise<string>): Promise<void> {+ await queryStore.executeTabSql(tab.id, sql, executeOptions);+ if (!shouldRetryWithoutRowIdLocator(sql, tab.connectionId, tabResultFor(tab))) return;+ markRowIdLocatorUnsupported(tab.connectionId);+ try {+ const fallbackSql = await rebuildSql();+ queryStore.updateSql(tab.id, fallbackSql);+ await queryStore.executeTabSql(tab.id, fallbackSql, executeOptions);+ if (!shouldKeepRowIdLocatorDisabled(tabResultFor(tab))) markRowIdLocatorSupported(tab.connectionId);+ } catch {+ markRowIdLocatorSupported(tab.connectionId);+ }+ }++ function tabResultFor(tab: QueryTab) {+ return queryStore.tabs.find((entry) => entry.id === tab.id)?.result;+ }+async function refreshDataTabTableMeta(tab: QueryTab, options: { force?: boolean; columnsOnly?: boolean; trace?: { traceId: string; elapsed: () => string } } = {}): Promise<boolean> {if (tab.mode !== "data" || !tab.connectionId || !tab.database) return false;const tableMeta = tableMetaForDataTab(tab);@@ -427,10 +451,23 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)}queryStore.updateSql(tab.id, nextSql);console.info("[DBX][reloadData:execute:start]", { traceId, elapsed: elapsed() });- await queryStore.executeTabSql(tab.id, nextSql, {- pagination: { limit: pageLimit, offset: pageOffset },- preserveResultDuringExecution: true,- });+ // 不带定位器的加载保持原执行路径;只有定位器加载才走降级包装(#12647)。+ if (nextSql.includes("__DBX_ROWID")) {+ await executeTableDataSqlWithRowIdFallback(+ tab,+ nextSql,+ {+ pagination: { limit: pageLimit, offset: pageOffset },+ preserveResultDuringExecution: true,+ },+ () => buildTableSql(tab, { whereInput, orderBy: incomingSortMissing ? undefined : orderBy, limit: pageLimit, offset: pageOffset }),+ );+ } else {+ await queryStore.executeTabSql(tab.id, nextSql, {+ pagination: { limit: pageLimit, offset: pageOffset },+ preserveResultDuringExecution: true,+ });+ }console.info("[DBX][reloadData:execute:done]", { traceId, elapsed: elapsed() });} catch (e) {console.error("[DBX][reloadData:error]", { traceId, elapsed: elapsed(), error: e });@@ -632,12 +669,31 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)const continuesResultSession = offset === expectedNextOffset && limit === tab.resultPageLimit;const connection = useConnectionStore().getConfig(tab.connectionId);const sessionId = usesAgentCursorForTableData(connection?.db_type, connection?.driver_profile) && tab.result?.has_more && tab.result.session_id && continuesResultSession ? tab.result.session_id : undefined;- await queryStore.executeTabSql(tab.id, sql, {+ const reloadOptions = {pagination: { offset, limit, sessionId, clientSessionId: sessionId ? tab.resultClientSessionId : undefined },...appendOptions,preserveResultDuringExecution: true,preserveTotalRowCountDuringExecution: true,- });+ };+ // 不带定位器的加载保持原执行路径;只有定位器加载才走降级包装(#12647)。+ if (sql.includes("__DBX_ROWID")) {+ await executeTableDataSqlWithRowIdFallback(tab, sql, reloadOptions, () =>+ buildTableSql(tab, {+ limit,+ offset,+ whereInput,+ orderBy: orderBy ?? tab.orderByInput,+ previewPageSize: tableDataPreviewRowBudget({+ limit,+ offset,+ expectedTotalRows: tab.resultTotalRowCount,+ loadedRowCount: tab.result?.rows.length ?? 0,+ }),+ }),+ );+ } else {+ await queryStore.executeTabSql(tab.id, sql, reloadOptions);+ }}async function onSort(tabId: string | undefined, column: string, columnIndex: number, direction: "asc" | "desc" | null, whereInput?: string, mode: DataGridSortMode = "database", effectiveOrderBy?: string) {diff --git a/apps/desktop/src/lib/table/__tests__/tableRowIdSupport.spec.ts b/apps/desktop/src/lib/table/__tests__/tableRowIdSupport.spec.tsnew file mode 100644index 0000000000..e8ca49ecf7--- /dev/null+++ b/apps/desktop/src/lib/table/__tests__/tableRowIdSupport.spec.ts@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it } from "vitest";+import { markRowIdLocatorSupported, markRowIdLocatorUnsupported, resetRowIdLocatorStateForTests, rowIdLocatorUnsupported, shouldKeepRowIdLocatorDisabled, shouldRetryWithoutRowIdLocator } from "@/lib/table/tableRowIdSupport";+import type { QueryResult } from "@/types/database";++const locatorSql = `SELECT tableoid::text || ':' || ctid::text || ':' || xmin::text AS "__DBX_ROWID", * FROM "public"."events" LIMIT 200;`;+const plainSql = `SELECT * FROM "public"."events" LIMIT 200;`;++function resultOf(executionError: boolean): QueryResult {+ return { columns: ["id"], rows: executionError ? [["db error"]] : [[1]], affected_rows: 0, execution_time_ms: 1, execution_error: executionError } as unknown as QueryResult;+}++describe("tableRowIdSupport", () => {+ beforeEach(() => {+ resetRowIdLocatorStateForTests();+ });++ it("retries once for a failed load whose SQL carried the locator", () => {+ expect(shouldRetryWithoutRowIdLocator(locatorSql, "conn-1", resultOf(true))).toBe(true);+ });++ it("does not retry successful loads, plain SQL, or already-disabled connections", () => {+ expect(shouldRetryWithoutRowIdLocator(locatorSql, "conn-1", resultOf(false))).toBe(false);+ expect(shouldRetryWithoutRowIdLocator(plainSql, "conn-1", resultOf(true))).toBe(false);+ expect(shouldRetryWithoutRowIdLocator(locatorSql, "conn-1", undefined)).toBe(false);+ markRowIdLocatorUnsupported("conn-1");+ expect(shouldRetryWithoutRowIdLocator(locatorSql, "conn-1", resultOf(true))).toBe(false);+ });++ it("keeps the flag only after a successful fallback and restores it on a failed one", () => {+ markRowIdLocatorUnsupported("conn-1");+ expect(shouldKeepRowIdLocatorDisabled(resultOf(false))).toBe(true);+ expect(shouldKeepRowIdLocatorDisabled(resultOf(true))).toBe(false);+ expect(shouldKeepRowIdLocatorDisabled(undefined)).toBe(false);++ markRowIdLocatorSupported("conn-1");+ expect(rowIdLocatorUnsupported("conn-1")).toBe(false);+ });++ it("tracks unsupported connections independently", () => {+ markRowIdLocatorUnsupported("conn-1");+ expect(rowIdLocatorUnsupported("conn-1")).toBe(true);+ expect(rowIdLocatorUnsupported("conn-2")).toBe(false);+ });+});diff --git a/apps/desktop/src/lib/table/tableRowIdSupport.ts b/apps/desktop/src/lib/table/tableRowIdSupport.tsnew file mode 100644index 0000000000..44c17736d6--- /dev/null+++ b/apps/desktop/src/lib/table/tableRowIdSupport.ts@@ -0,0 +1,43 @@+import { DBX_ROWID_COLUMN } from "@/lib/table/tableEditing";+import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";+import type { QueryResult } from "@/types/database";++/**+ * Per-connection memory of engines that rejected the synthetic row-id locator.+ *+ * Keyless PostgreSQL-family tables are opened with a `tableoid`/`ctid`/`xmin`+ * locator projection (see buildTableSelectSql). PostgreSQL-compatible engines+ * without system-column support — Hologres' query translation layer rejects+ * `tableoid` (issue #12647) — fail every such table open with a db error.+ * On the first failure the grid retries once without the locator; a successful+ * retry remembers the connection so later opens skip the locator entirely+ * (keyless tables stay read-only there). Engines that also reject the+ * fallback restore the flag so the user sees the real server error again.+ */+const rowIdLocatorUnsupportedConnections = new Set<string>();++export function rowIdLocatorUnsupported(connectionId: string): boolean {+ return rowIdLocatorUnsupportedConnections.has(connectionId);+}++export function markRowIdLocatorUnsupported(connectionId: string): void {+ rowIdLocatorUnsupportedConnections.add(connectionId);+}++export function markRowIdLocatorSupported(connectionId: string): void {+ rowIdLocatorUnsupportedConnections.delete(connectionId);+}++export function resetRowIdLocatorStateForTests(): void {+ rowIdLocatorUnsupportedConnections.clear();+}++/** A failed data load whose SQL carried the locator is the retry trigger. */+export function shouldRetryWithoutRowIdLocator(sql: string, connectionId: string, result: QueryResult | undefined | null): boolean {+ return sql.includes(DBX_ROWID_COLUMN) && !rowIdLocatorUnsupported(connectionId) && !!result && isQueryExecutionErrorResult(result);+}++/** Only a successful fallback keeps the flag; a failed one shows the real error. */+export function shouldKeepRowIdLocatorDisabled(result: QueryResult | undefined | null): boolean {+ return !!result && !isQueryExecutionErrorResult(result);+}diff --git a/crates/dbx-sql-dialect/src/sql_dialect/tests.rs b/crates/dbx-sql-dialect/src/sql_dialect/tests.rsindex e8501e8eb4..fedd4b45b5 100644--- a/crates/dbx-sql-dialect/src/sql_dialect/tests.rs+++ b/crates/dbx-sql-dialect/src/sql_dialect/tests.rs@@ -1334,6 +1334,34 @@ fn selects_hidden_postgres_tuple_identity_only_for_known_unkeyed_base_tables() {assert!(!keyed.contains("ctid"));}+#[test]+fn hologres_plugin_connections_receive_the_tableoid_locator_for_keyless_tables() {+ // t8y2/dbx#12647: Hologres connects through the plain PostgreSQL plugin+ // type, so the frontend gate enables the keyless-table locator and the+ // click-to-open SELECT projects `tableoid`. Hologres' query translation+ // layer rejects `tableoid` ("Variable tableoid ... can't be found in query+ // translation"), so every keyless table fails to open. Hologres also+ // reports a plain PG-11-style `server_version`, so the gate cannot be+ // driven off the version string alone. This pins the exact statement the+ // client emits today; the fix must stop projecting `tableoid` for engines+ // without system-column support without regressing vanilla PostgreSQL.+ let sql = build_table_data_select_sql(TableDataSelectSqlOptions {+ database_type: Some(DatabaseType::Postgres),+ schema: Some("public".to_string()),+ table_name: "hologres_keyless_events".to_string(),+ table_type: Some("TABLE".to_string()),+ primary_keys: Vec::new(),+ limit: Some(200),+ include_row_id: true,+ ..Default::default()+ });++ assert_eq!(+ sql,+ "SELECT tableoid::text || ':' || ctid::text || ':' || xmin::text AS \"__DBX_ROWID\", * FROM \"public\".\"hologres_keyless_events\" LIMIT 200;"+ );+}+#[test]fn builds_iris_table_data_sql_with_literal_top_and_ordinary_object() {let sql = build_table_data_select_sql(TableDataSelectSqlOptions {