25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(oracle): correct manual transaction last-page pagination
Zzz798c8678bcf1
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex d7ed4df649..f4142e51ca 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -1760,7 +1760,8 @@ export async function exportSnapshotResult(request: SnapshotExportRequest, filePanchor.click();}-export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string, catalog?: string): Promise<boolean> {+export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string, catalog?: string, txnSessionId?: string): Promise<boolean> {+ if (txnSessionId) throw new Error("Manual transaction management is only available in the desktop app.");return post("/api/query/close-session", {connectionId,database,diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 4c328ee036..8dcf43d541 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -2194,13 +2194,14 @@ export async function exportSnapshotResult(request: import("./http").SnapshotExpsignal?.throwIfAborted();}-export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string, catalog?: string): Promise<boolean> {+export async function closeQuerySession(connectionId: string, database: string, sessionId: string, clientSessionId?: string, catalog?: string, txnSessionId?: string): Promise<boolean> {return invoke("close_query_session", {connectionId,database,sessionId,clientSessionId,catalog,+ txnSessionId,});}diff --git a/apps/desktop/src/lib/query/queryCursorOffsetPagination.ts b/apps/desktop/src/lib/query/queryCursorOffsetPagination.tsnew file mode 100644index 0000000000..5a07c930c3--- /dev/null+++ b/apps/desktop/src/lib/query/queryCursorOffsetPagination.ts@@ -0,0 +1,59 @@+import type { QueryResult } from "@/types/database";++/** Reach an offset using a forward-only cursor, keeping only the requested page. */+export async function executeCursorOffsetPage(options: { offset: number; limit: number; fetchPage: (pageSize: number, sessionId?: string) => Promise<QueryResult[]>; closeSession: (sessionId: string) => Promise<unknown>; isCancelled: () => boolean }): Promise<QueryResult[]> {+ let sessionId: string | undefined;+ let skipped = 0;+ let pageCount = 0;+ let executionMs = 0;+ let completeTimings = true;+ let provenReadOnly: true | undefined;+ const timings: Record<string, number> = {};+ try {+ while (true) {+ if (options.isCancelled()) throw new Error("Query canceled");+ // The global row cap can shorten the final page. Stop exactly at the+ // offset instead of overshooting it with that shortened page size.+ const pageSize = skipped < options.offset ? Math.min(options.limit, options.offset - skipped) : options.limit;+ const results = await options.fetchPage(pageSize, sessionId);+ const page = results[0];+ if (!page) {+ if (sessionId) throw new Error("Result session ended before the requested page offset");+ return results;+ }+ // Keep the previous cursor available for cleanup if a malformed response+ // promises more rows without returning its session.+ sessionId = page.session_id ?? (page.has_more ? sessionId : undefined);+ if (options.isCancelled()) throw new Error("Query canceled");+ if (page.has_more && !page.session_id) throw new Error("Result session ended before the requested page offset");+ if (pageCount === 0) provenReadOnly = page.manual_transaction_proven_read_only;+ pageCount += 1;+ executionMs += page.execution_time_ms;+ if (!page.query_timings_ms) completeTimings = false;+ else for (const [key, value] of Object.entries(page.query_timings_ms)) timings[key] = (timings[key] ?? 0) + value;+ const result = {+ ...page,+ // Cursor fetches do not classify SQL; keep the initial execution's proof.+ manual_transaction_proven_read_only: provenReadOnly,+ query_timings_ms: completeTimings ? { ...timings } : undefined,+ execution_time_ms: executionMs,+ timing_page_count: pageCount,+ };+ if (skipped === options.offset && (page.rows.length > 0 || !page.has_more)) return [result];+ if (page.rows.length > pageSize) throw new Error("Result page exceeded the requested cursor page size");+ skipped += page.rows.length;+ if (!page.has_more) return [{ ...result, rows: [] }];+ // Cassandra can return empty intermediate pages with a valid next cursor.+ // Continue advancing that cursor until rows arrive or it is exhausted.+ }+ } catch (error) {+ if (sessionId) {+ try {+ await options.closeSession(sessionId);+ } catch (closeError) {+ console.warn("[DBX][offset-replay-session-close:error]", { sessionId, error: closeError });+ }+ }+ throw error;+ }+}diff --git a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.tsindex cab02d237e..ee91798616 100644--- a/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.hiddenPrimaryKey.spec.ts@@ -8,6 +8,8 @@ const apiMocks = vi.hoisted(() => ({executeQuery: vi.fn(),beginManualTransaction: vi.fn(),executeInManualTransaction: vi.fn(),+ closeQuerySession: vi.fn().mockResolvedValue(false),+ closeClientConnectionSession: vi.fn().mockResolvedValue(false),cancelQuery: vi.fn(),analyzeEditableQueryEditability: vi.fn(),getColumns: vi.fn(),@@ -39,6 +41,8 @@ const {executeQuery,beginManualTransaction,executeInManualTransaction,+ closeQuerySession,+ closeClientConnectionSession,cancelQuery,analyzeEditableQueryEditability,getColumns,@@ -70,8 +74,8 @@ vi.mock("@/lib/backend/api", () => ({analyzeEditableQueryEditability: apiMocks.analyzeEditableQueryEditability,buildDataGridCountSql: apiMocks.buildDataGridCountSql,buildSortedQuerySql: apiMocks.buildSortedQuerySql,- closeClientConnectionSession: vi.fn().mockResolvedValue(undefined),- closeQuerySession: vi.fn().mockResolvedValue(undefined),+ closeClientConnectionSession: apiMocks.closeClientConnectionSession,+ closeQuerySession: apiMocks.closeQuerySession,beginManualTransaction: apiMocks.beginManualTransaction,cancelQuery: apiMocks.cancelQuery,executeInManualTransaction: apiMocks.executeInManualTransaction,@@ -118,6 +122,8 @@ function queryAnalysis(sql: string) {describe("queryStore hidden primary key editing", () => {beforeEach(async () => {vi.clearAllMocks();+ closeQuerySession.mockResolvedValue(false);+ closeClientConnectionSession.mockResolvedValue(false);localStorageValues.clear();const { clearTableMetadataCache } = await import("@/lib/metadata/tableMetadataCache");clearTableMetadataCache();@@ -2729,6 +2735,171 @@ describe("queryStore hidden primary key editing", () => {);});+ it.each([+ [true, 100_000],+ [false, 100_000],+ [true, 2455],+ [false, 2455],+ ] as const)("keeps Oracle last-page and previous-page rows correct with autoCommit=%s, maxRows=%s (#13173)", async (autoCommit, maxRows) => {+ editorSettings.queryResultMaxRows = maxRows;+ getConnectionConfig.mockReturnValue({ id: "oracle-1", name: "Oracle", db_type: "oracle", database: "XE", query_timeout_secs: 30 });+ analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "complex-query" });+ prepareQueryPaginationExecutionPlan.mockImplementation(async (options) => ({+ sqlToExecute: options.sql,+ pageLimit: options.pagination.limit,+ pageOffset: options.pagination.offset,+ useAgentResultSession: true,+ }));+ const rows = Array.from({ length: 2473 }, (_, index) => [index + 1]);+ const total = Math.min(rows.length, maxRows);+ let position = 0;+ const readPage = (maxRows: number, pageSize?: number, sessionId?: string) => {+ if (!sessionId) position = 0;+ const pageRows = rows.slice(position, Math.min(position + (pageSize ?? maxRows), maxRows));+ position += pageRows.length;+ const hasMore = !!pageSize && position < Math.min(rows.length, maxRows);+ return [{ columns: ["ID"], rows: pageRows, affected_rows: 0, execution_time_ms: 1, has_more: hasMore, session_id: hasMore ? "oracle-cursor" : undefined, manual_transaction_proven_read_only: sessionId ? undefined : true }];+ };+ executeMulti.mockImplementation(async (_connection, _database, _sql, _schema, _execution, options) => readPage(options.maxRows, options.pageSize, options.resultSessionId));+ executeInManualTransaction.mockImplementation(async (_txn, _sql, _database, _schema, maxRows, _preview, pageSize, sessionId) => readPage(maxRows, pageSize, sessionId));+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("oracle-1", "XE", "Query");+ store.setAutoCommit(tabId, autoCommit);+ const tab = store.tabs.find((item) => item.id === tabId)!;+ const sql = "WITH a AS (SELECT id FROM events) SELECT a.* FROM a ORDER BY id";+ const loadPage = (offset: number, sessionId?: string) =>+ store.executeTabSql(tabId, sql, {+ pagination: { limit: 200, offset, sessionId },+ preserveResultDuringExecution: true,+ preserveTotalRowCountDuringExecution: true,+ });+ await loadPage(0);+ expect(tab.result?.rows).toEqual(rows.slice(0, 200));+ await loadPage(200, tab.resultSessionId);+ expect(tab.result?.rows).toEqual(rows.slice(200, 400));+ tab.resultTotalRowCount = 2473;++ await loadPage(2400);+ expect(tab.result?.rows).toEqual(rows.slice(2400, total));+ expect(tab.resultPageOffset).toBe(2400);+ expect(tab.resultTotalRowCount).toBe(total);+ expect(tab.result?.has_more).toBe(false);++ await loadPage(2200);+ expect(tab.result?.rows).toEqual(rows.slice(2200, 2400));+ expect(tab.resultPageOffset).toBe(2200);+ expect(tab.result?.has_more).toBe(true);+ if (!autoCommit) expect(tab.result?.manual_transaction_session_id).toBe("txn-1");+ await loadPage(2400, tab.resultSessionId);+ expect(tab.result?.rows).toEqual(rows.slice(2400, total));+ expect(tab.resultTotalRowCount).toBe(total);+ expect(tab.autoCommit).toBe(autoCommit);+ if (!autoCommit) {+ expect(executeMulti).not.toHaveBeenCalled();+ expect(beginManualTransaction).toHaveBeenCalledTimes(1);+ expect(executeInManualTransaction.mock.calls.every((call) => call[0] === "txn-1")).toBe(true);+ expect(executeInManualTransaction.mock.calls.every((call) => call[4] === maxRows)).toBe(true);+ expect(tab.txnPossiblyDirty).not.toBe(true);+ }+ });++ it.each(["fetch error", "missing cursor"])("closes the manual replay cursor after a %s without switching connections", async (failure) => {+ getConnectionConfig.mockReturnValue({ id: "oracle-1", db_type: "oracle", database: "XE" });+ analyzeEditableQueryEditability.mockResolvedValue({ editable: false });+ prepareQueryPaginationExecutionPlan.mockResolvedValue({ sqlToExecute: "SELECT * FROM events", pageLimit: 2, pageOffset: 4, useAgentResultSession: true });+ executeInManualTransaction.mockResolvedValueOnce([{ columns: ["ID"], rows: [[1], [2]], affected_rows: 0, execution_time_ms: 1, has_more: true, session_id: "cursor-1", manual_transaction_proven_read_only: true }]);+ if (failure === "fetch error") executeInManualTransaction.mockRejectedValueOnce(new Error("Cursor fetch failed"));+ else executeInManualTransaction.mockResolvedValueOnce([{ columns: ["ID"], rows: [], affected_rows: 0, execution_time_ms: 1, has_more: true }]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("oracle-1", "XE", "Query");+ store.setAutoCommit(id, false);++ await store.executeTabSql(id, "SELECT * FROM events", { pagination: { limit: 2, offset: 4 } });++ expect(executeInManualTransaction).toHaveBeenCalledTimes(2);+ expect(closeQuerySession).toHaveBeenCalledWith("oracle-1", "XE", "cursor-1", undefined, undefined, "txn-1");+ expect(executeMulti).not.toHaveBeenCalled();+ expect(store.tabs.find((tab) => tab.id === id)?.result?.execution_error).toBe(true);+ });++ it.each([+ [1, "cancel"],+ [3, "cancel"],+ [3, "supersede"],+ ] as const)("closes the returned manual cursor when page %s is interrupted by %s", async (interruptAt, interruption) => {+ getConnectionConfig.mockReturnValue({ id: "oracle-1", db_type: "oracle", database: "XE" });+ analyzeEditableQueryEditability.mockResolvedValue({ editable: false });+ prepareQueryPaginationExecutionPlan.mockResolvedValue({ sqlToExecute: "SELECT * FROM events", pageLimit: 2, pageOffset: 4, useAgentResultSession: true });+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("oracle-1", "XE", "Query");+ store.setAutoCommit(id, false);+ const tab = store.tabs.find((item) => item.id === id)!;+ let calls = 0;+ executeInManualTransaction.mockImplementation(async () => {+ calls += 1;+ if (calls === interruptAt) {+ if (interruption === "cancel") tab.cancelRequestCount = (tab.cancelRequestCount ?? 0) + 1;+ else tab.executionId = "replacement-execution";+ }+ return [{ columns: ["ID"], rows: [[calls * 2 - 1], [calls * 2]], affected_rows: 0, execution_time_ms: 1, has_more: true, session_id: `cursor-${calls}`, manual_transaction_proven_read_only: calls === 1 ? true : undefined }];+ });++ await store.executeTabSql(id, "SELECT * FROM events", { pagination: { limit: 2, offset: 4 } });++ expect(executeInManualTransaction).toHaveBeenCalledTimes(interruptAt);+ expect(closeQuerySession).toHaveBeenCalledWith("oracle-1", "XE", `cursor-${interruptAt}`, undefined, undefined, "txn-1");+ expect(executeMulti).not.toHaveBeenCalled();+ expect(tab.result?.rows).not.toEqual([[5], [6]]);+ });++ it("closes retained manual cursors by their original transaction even when their IDs match", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("oracle-1", "XE", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.txnSessionId = "newest-txn";+ const result = (owner: string) => ({ columns: ["ID"], rows: [[1]], affected_rows: 0, execution_time_ms: 1, session_id: "cursor-1", manual_transaction_session_id: owner });+ tab.result = result("txn-current-result");+ tab.resultSessionId = "cursor-1";+ tab.resultClientSessionId = id;+ tab.resultRuns = [{ id: "old-run", title: "Old result", sequence: 1, sql: "SELECT * FROM events", createdAt: 0, result: result("txn-old-result"), resultSessionId: "cursor-1", resultClientSessionId: id }];++ await store.clearQueryResults(id);++ expect(closeQuerySession.mock.calls).toEqual([+ ["oracle-1", "XE", "cursor-1", undefined, undefined, "txn-current-result"],+ ["oracle-1", "XE", "cursor-1", undefined, undefined, "txn-old-result"],+ ]);+ expect(closeClientConnectionSession).not.toHaveBeenCalled();+ expect(tab.txnSessionId).toBe("newest-txn");+ });++ it("does not clear a replacement cursor while the old transaction's close is pending", async () => {+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const id = store.createTab("oracle-1", "XE", "Query");+ const tab = store.tabs.find((item) => item.id === id)!;+ tab.result = { columns: ["ID"], rows: [[1]], affected_rows: 0, execution_time_ms: 1, session_id: "cursor-1", manual_transaction_session_id: "old-txn" };+ tab.resultSessionId = "cursor-1";+ const pendingClose = deferred<boolean>();+ closeQuerySession.mockReturnValueOnce(pendingClose.promise);+ const clearing = store.clearQueryResults(id);+ tab.result = { columns: ["ID"], rows: [[2]], affected_rows: 0, execution_time_ms: 1, session_id: "cursor-1", manual_transaction_session_id: "new-txn" };+ tab.resultSessionId = "cursor-1";+ tab.resultClientSessionId = id;+ pendingClose.resolve(true);+ await clearing;++ expect(tab.resultSessionId).toBe("cursor-1");+ expect(tab.resultClientSessionId).toBe(id);+ expect(tab.result.manual_transaction_session_id).toBe("new-txn");+ expect(tab.result.session_id).toBe("cursor-1");+ expect(closeQuerySession).toHaveBeenCalledWith("oracle-1", "XE", "cursor-1", undefined, undefined, "old-txn");+ });+it("advances an OceanBase duplicate projection cursor through an offset jump and next page", async () => {getConnectionConfig.mockReturnValue({ id: "ob-1", name: "OceanBase", db_type: "oceanbase-oracle", database: "app", query_timeout_secs: 30 });analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "complex-query" });diff --git a/apps/desktop/src/stores/__tests__/queryStore.tableDataRefresh.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.tableDataRefresh.spec.tsindex dca636d6c9..d4ed4dfecb 100644--- a/apps/desktop/src/stores/__tests__/queryStore.tableDataRefresh.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.tableDataRefresh.spec.ts@@ -609,6 +609,31 @@ describe("queryStore table data refresh", () => {expect(mocks.executeMulti).toHaveBeenCalledTimes(2);});+ it.each(["before offset", "at offset"])("advances through empty Cassandra cursor pages %s", async (emptyPagePosition) => {+ mocks.getConnectionConfig.mockReturnValue({ id: "cassandra-1", name: "Cassandra", db_type: "cassandra", database: "app" });+ const page = (rows: number[]) => ({ columns: ["id"], rows: rows.map((id) => [id]), affected_rows: 0, execution_time_ms: 1, session_id: "cursor-empty", has_more: true });+ const pages = emptyPagePosition === "before offset" ? [[], [1, 2], [3, 4]] : [[1, 2], [], [3, 4]];+ for (const rows of pages) mocks.executeMulti.mockResolvedValueOnce([page(rows)]);+ const { useQueryStore } = await import("@/stores/queryStore");+ const store = useQueryStore();+ const tabId = store.createTab("cassandra-1", "app", "paged_rows", "data");+ store.setTableMeta(tabId, {+ tableName: "paged_rows",+ tableType: "TABLE",+ columns: [{ name: "id", data_type: "int", is_nullable: false, column_default: null, is_primary_key: true, extra: null }],+ primaryKeys: ["id"],+ });++ await store.executeTabSql(tabId, 'SELECT * FROM "paged_rows";', { pagination: { limit: 2, offset: 2 } });++ const tab = store.tabs.find((candidate) => candidate.id === tabId)!;+ expect(tab.result?.rows).toEqual([[3], [4]]);+ expect(tab.result?.timing_page_count).toBe(3);+ expect(tab.resultPageOffset).toBe(2);+ expect(mocks.executeMulti.mock.calls.map((call) => call[5]?.resultSessionId)).toEqual([undefined, "cursor-empty", "cursor-empty"]);+ expect(mocks.closeQuerySession).not.toHaveBeenCalled();+ });+it("closes a Cassandra replay cursor when a later page fails", async () => {mocks.getConnectionConfig.mockReturnValue({ id: "cassandra-1", name: "Cassandra", db_type: "cassandra", database: "app" });mocks.executeMulti.mockResolvedValueOnce([{ columns: ["id"], rows: [[1], [2]], affected_rows: 0, execution_time_ms: 1, session_id: "cursor-lost", has_more: true }]).mockRejectedValueOnce(new Error("query session not found: cursor-lost"));diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex b90ed65c84..572b20c6ce 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -1,5 +1,6 @@import { hasShortDataGridSqlPage } from "@/lib/dataGrid/dataGridPagination";import { createQueryRequestTiming } from "@/lib/queryRequestTiming";+import { executeCursorOffsetPage } from "@/lib/query/queryCursorOffsetPagination";import { mergeQueryMessages, queryResultMessages } from "@/lib/query/queryResultMessages";import { appendNeo4jNodeCells, extractNeo4jNodeCells } from "@/lib/neo4j/neo4jNodeResult";import { UPDATE_RESTORE_KEY, assertUpdateAllowsInteraction } from "@/lib/app/updatePreparation";@@ -1820,24 +1821,32 @@ export const useQueryStore = defineStore("query", () => {const sessionId = tab?.resultSessionId ?? tab?.result?.session_id;if (!tab || !sessionId || sessionId === preserveSessionId) return;const resultClientSessionId = tab.resultClientSessionId;+ const result = tab.result;+ const txnSessionId = result?.manual_transaction_session_id;const catalog = tab.mode === "data" ? tab.tableMeta?.catalog : tab.catalog;const location = tab.mode === "query" ? queryResultExecutionLocation(tab) : { connectionId: tab.connectionId, database: tab.database, catalog };try {const clientSessionId = tab.resultClientSessionId ?? tab.id;- if (location.catalog) await api.closeQuerySession(location.connectionId, location.database, sessionId, clientSessionId, location.catalog);+ if (txnSessionId) await api.closeQuerySession(location.connectionId, location.database, sessionId, undefined, location.catalog, txnSessionId);+ else if (location.catalog) await api.closeQuerySession(location.connectionId, location.database, sessionId, clientSessionId, location.catalog);else await api.closeQuerySession(location.connectionId, location.database, sessionId, clientSessionId);} catch (error) {console.warn("[DBX][query-session:close:error]", { tabId: tab.id, sessionId, error });if (throwOnError) throw error;} finally {- if (tab.resultSessionId === sessionId) tab.resultSessionId = undefined;- if (!tab.resultSessionId) tab.resultClientSessionId = undefined;- if (tab.result?.session_id === sessionId) {- tab.result.session_id = undefined;+ // Different transactions can generate the same cursor ID. Do not clear+ // a replacement result while the previous owner's close is in flight.+ if (tab.result === result) {+ if (tab.resultSessionId === sessionId) tab.resultSessionId = undefined;+ if (!tab.resultSessionId) tab.resultClientSessionId = undefined;+ }+ if (result?.session_id === sessionId) {+ result.session_id = undefined;+ result.manual_transaction_session_id = undefined;// 原地修改了负载,让持有它的 tab 与 run 的估算值都失效- invalidateResultEstimateForPayload(tab.result);+ invalidateResultEstimateForPayload(result);}- if (resultClientSessionId && resultClientSessionId !== tab.id) {+ if (!txnSessionId && resultClientSessionId && resultClientSessionId !== tab.id) {await closeClientSessionId(location.connectionId, location.database, resultClientSessionId, location.catalog, { tabId: tab.id }, throwOnError);}}@@ -2261,16 +2270,17 @@ export const useQueryStore = defineStore("query", () => {if (!tab.result && !tab.results?.length && !tab.resultEvicted && resultRuns.length === 0) return false;const closedSessionIds = new Set<string>();+ const cursorKey = (owner: Pick<QueryTab, "result" | "resultClientSessionId">, sessionId: string) => JSON.stringify([owner.result?.manual_transaction_session_id, owner.resultClientSessionId ?? tab.id, sessionId]);const currentSessionId = tab.resultSessionId ?? tab.result?.session_id;- if (currentSessionId) closedSessionIds.add(currentSessionId);+ if (currentSessionId) closedSessionIds.add(cursorKey(tab, currentSessionId));const closeOperations = [closeResultSession(tab)];closeOperations.push(releaseResultLargeValues(tab.result, ...(tab.results ?? [])));for (const run of resultRuns) {closeOperations.push(releaseResultLargeValues(run.result, ...(run.results ?? [])));if (run.resultCacheKey) void deleteTabResultSnapshot(run.resultCacheKey);- if (!run.resultSessionId || closedSessionIds.has(run.resultSessionId)) continue;- closedSessionIds.add(run.resultSessionId);+ if (!run.resultSessionId || closedSessionIds.has(cursorKey(run, run.resultSessionId))) continue;+ closedSessionIds.add(cursorKey(run, run.resultSessionId));closeOperations.push(closeResultRunSession(tab, run));}@@ -8932,6 +8942,11 @@ export const useQueryStore = defineStore("query", () => {// could not rewrite the SQL for these engines, so a plain execution// would return the first page again (#8993).const isOffsetJumpPage = typeof pageOffset === "number" && pageOffset > 0 && !options?.pagination?.sessionId;+ const needsOffsetReplay = useAgentResultSession && isOffsetJumpPage && (tab.mode === "query" || tab.mode === "data") && !(tab.batchSqlExecution && tab.batchSqlExecution.total > 1);+ const isReplayCancelled = () => {+ const current = findExecutionTab(id);+ return current !== tab || current.executionId !== executionId || current.isCancelling === true || (current.cancelRequestCount ?? 0) !== cancelRequestCountAtStart || manualTransactionTargetEpoch(current) !== executionTargetEpoch;+ };const frontendTimeoutSecs = frontendQueryTimeoutSecsForSql(sqlToExecute, effectiveDbType, queryTimeoutSecs, sqlStatementParameterOptions);if (tab.mode === "data" && effectiveDbType === "oceanbase-oracle") {const meta = tableMetaForDataTab(tab);@@ -8999,60 +9014,14 @@ export const useQueryStore = defineStore("query", () => {});executionDispatched = true;if (tab.mode === "query") clientRequestStartedAt = performance.now();- if (useAgentResultSession && (tab.mode === "query" || tab.mode === "data") && typeof pageOffset === "number" && pageOffset > 0 && !options?.pagination?.sessionId && !(tab.batchSqlExecution && tab.batchSqlExecution.total > 1)) {- return (async () => {- let sessionId: string | undefined;- let skipped = 0;- let pageCount = 0;- let executionMs = 0;- let completeTimings = true;- const timings: Record<string, number> = {};- try {- while (true) {- const pageResults = await api.executeMulti(executionConnectionId, executionDatabase, sqlToExecute, executionSchema, executionId, {- ...executionOptions,- resultSessionId: sessionId,- });- const page = pageResults[0];- if (!page) return pageResults;- pageCount += 1;- executionMs += page.execution_time_ms;- if (!page.query_timings_ms) completeTimings = false;- else for (const [key, value] of Object.entries(page.query_timings_ms)) timings[key] = (timings[key] ?? 0) + value;- // Offset jumps consume several cursor pages before publication.- // Keep their timings as well, without retaining skipped rows.- const timingSummary = { query_timings_ms: completeTimings ? { ...timings } : undefined, execution_time_ms: executionMs, timing_page_count: pageCount };- if (skipped + page.rows.length > pageOffset) {- const start = pageOffset - skipped;- const limit = typeof pageLimit === "number" ? pageLimit : page.rows.length - start;- return [{ ...page, ...timingSummary, rows: page.rows.slice(start, start + limit) }];- }- skipped += page.rows.length;- if (!page.has_more || !page.session_id) {- if (page.has_more) {- // The cursor session ended before the requested offset;- // returning the short page would show the wrong rows.- throw new Error("Result session ended before the requested page offset");- }- return [{ ...page, ...timingSummary, rows: [] }];- }- sessionId = page.session_id;- const replayTab = findExecutionTab(id);- if (replayTab !== tab || replayTab.executionId !== executionId || replayTab.isCancelling || (replayTab.cancelRequestCount ?? 0) !== cancelRequestCountAtStart || manualTransactionTargetEpoch(replayTab) !== executionTargetEpoch) {- throw new Error("Query canceled");- }- }- } catch (error) {- if (sessionId) {- try {- await api.closeQuerySession(executionConnectionId, executionDatabase, sessionId, executionClientSessionId, executionCatalog);- } catch (closeError) {- queryExecutionLog("warn", "offset-replay-session-close:error", { traceId, sessionId, error: closeError });- }- }- throw error;- }- })();+ if (needsOffsetReplay && typeof pageOffset === "number" && typeof pageLimit === "number") {+ return executeCursorOffsetPage({+ offset: pageOffset,+ limit: pageLimit,+ fetchPage: (pageSize, sessionId) => api.executeMulti(executionConnectionId, executionDatabase, sqlToExecute, executionSchema, executionId, { ...executionOptions, pageSize, resultSessionId: sessionId }),+ closeSession: (sessionId) => api.closeQuerySession(executionConnectionId, executionDatabase, sessionId, executionClientSessionId, executionCatalog),+ isCancelled: isReplayCancelled,+ });}return tab.batchSqlExecution && tab.batchSqlExecution.total > 1? api.executeMultiWithProgress(@@ -9107,24 +9076,40 @@ export const useQueryStore = defineStore("query", () => {executionPromise = (async () => {const txnSessionId = tab.txnSessionId;if (!txnSessionId) throw new Error("Manual transaction session was not initialized");- // Offset jumps inside a manual transaction keep the legacy- // single-shot call: the session-consume loop only runs in the- // auto-commit path, and opening a cursor session here would- // strand it after returning the first page.const executeInTransaction = (sessionId: string) => {- const cursor = useAgentResultSession && !isOffsetJumpPage;- const args = [- sessionId,- sqlToExecute,- executionDatabase,- executionSchema,- cursor ? agentProtocolQueryResultMaxRows(queryResultMaxRows) : batchPagination ? agentProtocolQueryResultMaxRows(queryResultMaxRows) : (pageProbeLimit ?? pageLimit ?? agentProtocolQueryResultMaxRows(queryResultMaxRows)),- useLargeValuePreview,- cursor ? pageLimit : undefined,- cursor ? options?.pagination?.sessionId : undefined,- classificationSql,- ] as const;- return effectiveDbType === "sqlserver" ? api.executeInManualTransaction(...args, executionId, frontendTimeoutSecs) : api.executeInManualTransaction(...args);+ const fetchPage = async (pageSize?: number, resultSessionId?: string) => {+ const args = [+ sessionId,+ sqlToExecute,+ executionDatabase,+ executionSchema,+ useAgentResultSession || batchPagination ? agentProtocolQueryResultMaxRows(queryResultMaxRows) : (pageProbeLimit ?? pageLimit ?? agentProtocolQueryResultMaxRows(queryResultMaxRows)),+ useLargeValuePreview,+ useAgentResultSession ? pageSize : undefined,+ useAgentResultSession ? resultSessionId : undefined,+ resultSessionId ? undefined : classificationSql,+ ] as const;+ const results = await (effectiveDbType === "sqlserver" ? api.executeInManualTransaction(...args, executionId, frontendTimeoutSecs) : api.executeInManualTransaction(...args));+ for (const result of results) {+ if (result.session_id) result.manual_transaction_session_id = sessionId;+ }+ // Preserve unproven work even if a later replay fetch fails or+ // the session expires before the requested page is published.+ if (needsOffsetReplay && isInitialStickyClassification && !resultSessionId && tab.txnSessionId === sessionId && results.some((result) => result.manual_transaction_proven_read_only !== true && result.manual_transaction_no_statement !== true)) {+ tab.txnPossiblyDirty = true;+ }+ return results;+ };+ if (needsOffsetReplay && typeof pageOffset === "number" && typeof pageLimit === "number") {+ return executeCursorOffsetPage({+ offset: pageOffset,+ limit: pageLimit,+ fetchPage,+ closeSession: (cursorId) => api.closeQuerySession(executionConnectionId, executionDatabase, cursorId, undefined, executionCatalog, sessionId),+ isCancelled: () => isReplayCancelled() || tab.txnSessionId !== sessionId,+ });+ }+ return fetchPage(pageLimit, options?.pagination?.sessionId);};try {if (effectiveDbType === "sqlserver") tab.txnStatus = "executing";diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 4d7c8fcf75..c9dfc6bc22 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -1802,6 +1802,8 @@ export interface QueryResult {/** Retained result refs also cover cells already hydrated into complete local values. */large_value_refs?: string[];session_id?: string | null;+ /** Frontend-only owner of a manual transaction's result cursor, including retained runs. */+ manual_transaction_session_id?: string;has_more?: boolean;/** Frontend-only SQL page lookahead, independent of the driver's cursor has_more. */page_has_more?: boolean;diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rsindex ea5208f2a4..bdae602a25 100644--- a/crates/dbx-core/src/query/mod.rs+++ b/crates/dbx-core/src/query/mod.rs@@ -3462,6 +3462,31 @@ pub async fn close_query_session(}}+/// Close only the result cursor held by this transaction; never open a normal+/// pool or commit/roll back the transaction as part of result cleanup.+pub async fn close_manual_transaction_query_session(+ state: &AppState,+ connection_id: &str,+ txn_session_id: &str,+ session_id: &str,+) -> Result<bool, String> {+ let connection = {+ let sessions = state.transaction_sessions.read().await;+ let Some(session) = sessions.get(txn_session_id) else {+ return Ok(false);+ };+ if session.connection_id != connection_id {+ return Err("Transaction session belongs to a different connection".to_string());+ }+ Arc::clone(&session.connection)+ };+ let connection = connection.lock().await;+ match &*connection {+ TxnConnection::Agent { client, .. } => client.lock().await.close_query_session(session_id).await,+ _ => Ok(false),+ }+}+pub async fn execute_multi_core(state: &AppState,connection_id: &str,@@ -12368,9 +12393,16 @@ for line in sys.stdin:import sysprint(json.dumps({{"ready": True}}), flush=True)+cursor_ids = {{"cursor-1"}}for line in sys.stdin:request = json.loads(line)method = request.get("method")+ if method == "close_query_session":+ cursor_id = request.get("params", {{}}).get("sessionId")+ closed = cursor_id in cursor_ids+ cursor_ids.discard(cursor_id)+ print(json.dumps({{"jsonrpc": "2.0", "id": request["id"], "result": closed}}), flush=True)+ continueif method == "execute_query":params = request.get("params", {{}})sql = params.get("sql", "")@@ -12448,6 +12480,35 @@ for line in sys.stdin:(state, txn_session_id, dir)}+ #[tokio::test]+ async fn manual_transaction_cursor_cleanup_uses_its_owner_without_ending_transaction() {+ let (state, txn_id, dir) = manual_transaction_test_state(DatabaseType::Oracle).await;+ assert!(close_manual_transaction_query_session(&state, "other-connection", &txn_id, "cursor-1").await.is_err());+ assert!(!close_manual_transaction_query_session(&state, "agent-conn", "missing-txn", "cursor-1")+ .await+ .unwrap());+ // Only the held transaction has an Agent. A lookup through the normal+ // connection pool cannot close this cursor.+ assert!(close_manual_transaction_query_session(&state, "agent-conn", &txn_id, "cursor-1").await.unwrap());+ assert!(!close_manual_transaction_query_session(&state, "agent-conn", &txn_id, "cursor-1").await.unwrap());+ let result = execute_in_manual_transaction_with_options(+ &state,+ &txn_id,+ "SELECT 1 FROM DUAL",+ "ORCL",+ Some("APP"),+ ManualTransactionExecutionOptions::default(),+ )+ .await+ .unwrap();+ assert_eq!(result[0].result.rows[0][0], "SELECT 1 FROM DUAL");+ assert!(state.transaction_sessions.read().await.contains_key(&txn_id));+ rollback_manual_transaction(&state, &txn_id).await.unwrap();+ assert!(!close_manual_transaction_query_session(&state, "agent-conn", &txn_id, "cursor-1").await.unwrap());+ drop(state);+ let _ = std::fs::remove_dir_all(dir);+ }+fn manual_sql_file_request(session_id: &str) -> crate::sql::SqlFileRequest {crate::sql::SqlFileRequest {txn_session_id: Some(session_id.to_string()),diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex 9870654ced..aabee37650 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -384,7 +384,17 @@ pub async fn close_query_session(session_id: String,client_session_id: Option<String>,catalog: Option<String>,+ txn_session_id: Option<String>,) -> Result<bool, String> {+ if let Some(txn_session_id) = txn_session_id {+ return dbx_core::query::close_manual_transaction_query_session(+ &state,+ &connection_id,+ &txn_session_id,+ &session_id,+ )+ .await;+ }dbx_core::query::close_query_session(&state,&connection_id,