Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(grid): keep commit state across result grid remounts

t8y24285e0488d17
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index be2e8e2a4f..d3b0684359 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -616,6 +616,8 @@ interface DataGridProps {
/** Document stores (e.g. MongoDB) count exactly on demand without SQL tableMeta/countSql. */
countTotalRows?: () => Promise<number | undefined>;
loading?: boolean;
+ /** Tab that owns this grid; a running save is tracked by tab (#13226). */
+ tabId?: string;
cacheKey?: string;
columnWidthCacheKey?: string;
pendingStateKey?: string;
@@ -4660,6 +4662,7 @@ const editor = useDataGridEditor({
ensureManualTransactionSession: computed(() => props.ensureManualTransactionSession),
onManualTransactionMutation: () => props.onManualTransactionMutation?.(),
onSaveConflict: (message) => toast(message, 5000),
+ onAdoptedSaveCompleted: () => toast(t("grid.saveCompleted"), 3000),
sql: computed(() => props.sql),
searchText,
whereFilterInput,
@@ -4677,6 +4680,10 @@ const editor = useDataGridEditor({
pageSize,
currentPage,
cacheKey: computed(() => props.pendingStateKey ?? props.cacheKey),
+ // A save outlives a tab switch that unmounts this grid, so it is tracked by
+ // tab and result payload rather than by component instance (#13226).
+ tabId: computed(() => props.tabId),
+ resultViewGeneration: computed(() => props.viewGeneration),
onResultPayloadMutated: () => queryStore.invalidateResultEstimateForPayload(props.result),
refreshSavedRows,
prepareSaveBaseline: async (changes) => {
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index dbf6cfd195..876ec51e99 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -2876,6 +2876,7 @@ defineExpose({
:cache-key="activeResultGridCacheKey"
:column-width-cache-key="activeResultGridColumnWidthCacheKey"
:pending-state-key="activeResultGridInstanceKey"
+ :tab-id="activeTab.id"
:view-generation="activeTab.resultViewGeneration"
class="flex-1 min-h-0"
:result="activeGridResult!"
@@ -3437,6 +3438,7 @@ defineExpose({
:busy-started-at="activeTab.isExecuting ? activeTab.queryExecutionStartedAt : undefined"
:editable="!activeTab.tableMetaPending && (isTableDataEditable(activeEffectiveDatabaseType, activeTableMeta?.primaryKeys ?? [], activeTableMeta?.tableType) || !!influxDbV1DeleteSaveHandler)"
:custom-save-handler="influxDbV1DeleteSaveHandler"
+ :tab-id="activeTab.id"
context="table-data"
@view-sql="viewTableSql"
:initial-where-input="activeTab.whereInput"
diff --git a/apps/desktop/src/composables/__tests__/useDataGridEditor.tabSwitchSave.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridEditor.tabSwitchSave.spec.ts
new file mode 100644
index 0000000000..1af380b927
--- /dev/null
+++ b/apps/desktop/src/composables/__tests__/useDataGridEditor.tabSwitchSave.spec.ts
@@ -0,0 +1,462 @@
+// @vitest-environment happy-dom
+import { createApp, computed, defineComponent, h, nextTick, ref, type Ref } from "vue";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { clearDataGridPendingSnapshotsForTab, pendingDataGridSaveCount, useDataGridEditor } from "@/composables/useDataGridEditor";
+import type { CellValue } from "@/lib/dataGrid/cellValue";
+
+const mocks = vi.hoisted(() => ({
+ getConfig: vi.fn(),
+ prepareDataGridSave: vi.fn(),
+ executeBatch: vi.fn(),
+ executeInTransaction: vi.fn(),
+ executeInManualTransaction: vi.fn(),
+ executeQuery: vi.fn(),
+ addHistory: vi.fn(),
+}));
+
+vi.mock("@/lib/backend/api", () => ({
+ prepareDataGridSave: mocks.prepareDataGridSave,
+ executeBatch: mocks.executeBatch,
+ executeConditionalUpdate: vi.fn(),
+ cancelConditionalUpdate: vi.fn(),
+ executeInTransaction: mocks.executeInTransaction,
+ executeInManualTransaction: mocks.executeInManualTransaction,
+ executeQuery: mocks.executeQuery,
+ unlockConnectionWrites: vi.fn(),
+ lockConnectionWrites: vi.fn(),
+ connectionWriteUnlockState: vi.fn().mockResolvedValue(0),
+}));
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({ getConfig: mocks.getConfig }),
+}));
+vi.mock("@/stores/historyStore", () => ({
+ useHistoryStore: () => ({ add: mocks.addHistory }),
+}));
+vi.mock("@/stores/productionSafetyStore", () => ({
+ useProductionSafetyStore: () => ({}),
+}));
+
+type Editor = ReturnType<typeof useDataGridEditor>;
+
+const TABLE_META = { tableName: "orders", columns: [{ name: "id", data_type: "int" }, { name: "status", data_type: "varchar" }], primaryKeys: ["id"] };
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+ reject: (error: unknown) => void;
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ });
+ return { promise, resolve, reject };
+}
+
+interface GridFixture {
+ editor: Editor;
+ tabId: string;
+ emit: ReturnType<typeof vi.fn>;
+ refreshSavedRows: ReturnType<typeof vi.fn>;
+ onAdoptedSaveCompleted: ReturnType<typeof vi.fn>;
+}
+
+/**
+ * Mounts (through a real component, so the composable's lifecycle hooks run) a
+ * grid editor for one query tab. The query tab unmounts the grid when the user
+ * leaves it or switches to the summary view, and mounts a fresh one on return.
+ */
+function mountGrid(options: { tabId?: string; cacheKey?: string; withoutTabId?: boolean } = {}) {
+ const tabId = options.tabId ?? "query-tab-1";
+ const cacheKey = options.cacheKey ?? "query-tab-1-current-0";
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const emit = vi.fn();
+ const refreshSavedRows = vi.fn(async () => false);
+ const onAdoptedSaveCompleted = vi.fn();
+ const rows: CellValue[][] = Array.from({ length: 4 }, (_, index) => [index + 1, "pending"]);
+ let editor!: Editor;
+
+ const GridHost = defineComponent({
+ setup() {
+ const result = ref({ columns: ["id", "status"], rows });
+ editor = useDataGridEditor({
+ result: result as Ref<{ columns: string[]; rows: CellValue[][] }>,
+ editable: ref(true),
+ databaseType: ref("postgres"),
+ connectionId: ref("connection-1"),
+ database: ref("app"),
+ // Not reactive in the template render: the save compares the table meta
+ // it prepared against this one after every await.
+ tableMeta: computed(() => TABLE_META),
+ onExecuteSql: ref(undefined),
+ sql: ref("select * from orders"),
+ searchText: ref(""),
+ whereFilterInput: ref(""),
+ currentWhereInput: ref(undefined),
+ orderByInput: ref(""),
+ rowStatusFilter: ref("all"),
+ pageSize: ref(100),
+ currentPage: ref(1),
+ cacheKey: ref(cacheKey),
+ tabId: options.withoutTabId ? undefined : ref(tabId),
+ resultViewGeneration: ref("generation-initial"),
+ getRowItem: (rowId) => {
+ const row = rows[rowId];
+ if (rowId < 0 || !row) return undefined;
+ const changes = editor?.dirtyRows.value.get(rowId);
+ return { id: rowId, sourceIndex: rowId, data: row, isNew: false, isDeleted: false, isDirtyCol: row.map((_, index) => changes?.has(index) ?? false), status: changes?.size ? "edited" : "normal" };
+ },
+ refreshSavedRows,
+ onAdoptedSaveCompleted,
+ emit,
+ });
+ return () => h("div");
+ },
+ });
+
+ const app = createApp(GridHost);
+ app.mount(host);
+ const fixture: GridFixture = { editor, tabId, emit, refreshSavedRows, onAdoptedSaveCompleted };
+ return {
+ ...fixture,
+ // A remount replaces the editor; always hand out the mounted instance.
+ get currentEditor() {
+ return editor;
+ },
+ unmount() {
+ app.unmount();
+ host.remove();
+ },
+ };
+}
+
+function stageFourPendingUpdates(editor: Editor) {
+ // Four edited rows, like the bulk paste in the report.
+ editor.dirtyRows.value = new Map(Array.from({ length: 4 }, (_, rowId) => [rowId, new Map([[1, "saved"]])]));
+ expect(editor.pendingChangeCount.value).toBe(4);
+}
+
+async function flush() {
+ await nextTick();
+ await Promise.resolve();
+ await nextTick();
+}
+
+describe("useDataGridEditor save across a grid unmount (#13226)", () => {
+ beforeEach(() => {
+ expect(pendingDataGridSaveCount(), "registry leaked from the previous test").toBe(0);
+ mocks.getConfig.mockReset().mockReturnValue(undefined);
+ mocks.prepareDataGridSave.mockReset();
+ mocks.executeBatch.mockReset();
+ mocks.executeInTransaction.mockReset();
+ mocks.executeInTransaction.mockResolvedValue([]);
+ mocks.addHistory.mockReset().mockResolvedValue(undefined);
+ });
+
+ it("adopts the running save after a remount: no stale badge, busy commit, then refresh and report", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ // The server write is now in flight (the grid shows the busy commit icon).
+ await flush();
+ expect(first.currentEditor.isSaving.value).toBe(true);
+ expect(mocks.executeBatch).toHaveBeenCalledOnce();
+ expect(first.emit).not.toHaveBeenCalled();
+
+ // The user leaves the tab (or opens the summary view) while the server is
+ // still writing, then comes back: a fresh grid for the same tab/result.
+ first.unmount();
+ await flush();
+ const second = mountGrid();
+
+ // Same visible state as never having left: the 4 saved changes are not
+ // pending any more and the commit action stays busy until the save ends.
+ expect(second.currentEditor.pendingChangeCount.value).toBe(0);
+ expect(second.currentEditor.isSaving.value).toBe(true);
+ expect(second.emit).not.toHaveBeenCalled();
+
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+
+ expect(second.currentEditor.isSaving.value).toBe(false);
+ expect(second.currentEditor.hasPendingChanges.value).toBe(false);
+ // The returning grid reloads the result and reports the completed save.
+ const reload = second.emit.mock.calls.find(([event]) => event === "reload");
+ expect(reload).toBeDefined();
+ expect(reload?.[1]).toBe("select * from orders");
+ expect(second.onAdoptedSaveCompleted).toHaveBeenCalledOnce();
+ second.unmount();
+ });
+
+ it("refreshes the finished result when the grid returns after the save already settled", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ first.unmount();
+ await flush();
+
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+ // Nobody was mounted when the save ended, so the reload is still owed.
+
+ const second = mountGrid();
+ await flush();
+ expect(second.currentEditor.pendingChangeCount.value).toBe(0);
+ expect(second.currentEditor.isSaving.value).toBe(false);
+ const reload = second.emit.mock.calls.find(([event]) => event === "reload");
+ expect(reload).toBeDefined();
+ // The next mount never repeats the refresh.
+ second.unmount();
+ const third = mountGrid();
+ await flush();
+ expect(third.emit).not.toHaveBeenCalled();
+ third.unmount();
+ });
+
+ it("keeps the pending changes when the adopted save fails", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ first.unmount();
+ await flush();
+
+ const second = mountGrid();
+ execution.reject(new Error("deadlock found"));
+ await saving;
+ await flush();
+
+ // The write did not happen: nothing was saved, nothing to reload, but the
+ // changes must be back for a retry rather than lost.
+ expect(second.currentEditor.isSaving.value).toBe(false);
+ expect(second.currentEditor.pendingChangeCount.value).toBe(4);
+ expect(second.emit).not.toHaveBeenCalled();
+ expect(second.onAdoptedSaveCompleted).not.toHaveBeenCalled();
+
+ // A further remount still sees the failed changes as pending.
+ second.unmount();
+ const third = mountGrid();
+ await flush();
+ expect(third.currentEditor.pendingChangeCount.value).toBe(4);
+ third.unmount();
+ });
+
+ it("does not adopt a save that belongs to another tab", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ first.unmount();
+ await flush();
+
+ // A different query tab must not be blocked by another tab's save.
+ const other = mountGrid({ tabId: "query-tab-2", cacheKey: "query-tab-2-current-0" });
+ other.currentEditor.dirtyRows.value = new Map([[0, new Map([[1, "other tab"]])]]);
+ expect(other.currentEditor.pendingChangeCount.value).toBe(1);
+ expect(other.currentEditor.isSaving.value).toBe(false);
+ expect(other.emit).not.toHaveBeenCalled();
+ other.unmount();
+
+ // The save settles with no grid mounted: its reload is owed to the grid that
+ // returns to query-tab-1, which then consumes it.
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+ const back = mountGrid();
+ await flush();
+ expect(back.emit.mock.calls.some(([event]) => event === "reload")).toBe(true);
+ back.unmount();
+ expect(pendingDataGridSaveCount()).toBe(0);
+ });
+
+ it("adopts the save of a grid mounted without a tab id (cache-key fallback)", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid({ withoutTabId: true });
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ await flush();
+ expect(first.currentEditor.isSaving.value).toBe(true);
+
+ first.unmount();
+ await flush();
+ const second = mountGrid({ withoutTabId: true });
+
+ // No tabId: the cache key identifies the grid, so it still adopts the save.
+ expect(second.currentEditor.isSaving.value).toBe(true);
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+
+ expect(second.currentEditor.isSaving.value).toBe(false);
+ expect(second.currentEditor.pendingChangeCount.value).toBe(0);
+ expect(second.emit.mock.calls.some(([event]) => event === "reload")).toBe(true);
+ expect(second.onAdoptedSaveCompleted).toHaveBeenCalledOnce();
+ second.unmount();
+ // The adopted record is consumed, so the registry does not leak.
+ expect(pendingDataGridSaveCount()).toBe(0);
+ });
+
+ it("does not resurrect the saved rows when the save succeeds with no grid mounted", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ // Leaving persists the pending changes: this is the snapshot that used to
+ // come back as the stale "498" badge.
+ first.unmount();
+ await flush();
+
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+
+ const second = mountGrid();
+ await flush();
+ expect(second.currentEditor.pendingChangeCount.value).toBe(0);
+ expect(second.currentEditor.hasPendingChanges.value).toBe(false);
+ expect(second.currentEditor.isSaving.value).toBe(false);
+ // Never left a running save behind, and never reported a save it did not see.
+ expect(second.onAdoptedSaveCompleted).not.toHaveBeenCalled();
+ // The reload it owed was consumed by the grid that returned.
+ expect(second.emit.mock.calls.some(([event]) => event === "reload")).toBe(true);
+ second.unmount();
+ expect(pendingDataGridSaveCount()).toBe(0);
+ });
+
+ it("keeps the pending changes retryable when the save fails with no grid mounted", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ first.unmount();
+ await flush();
+
+ execution.reject(new Error("deadlock found"));
+ await saving;
+ await flush();
+
+ const second = mountGrid();
+ await flush();
+ expect(second.currentEditor.isSaving.value).toBe(false);
+ expect(second.currentEditor.pendingChangeCount.value).toBe(4);
+ expect(second.emit).not.toHaveBeenCalled();
+ expect(second.onAdoptedSaveCompleted).not.toHaveBeenCalled();
+ second.unmount();
+ expect(pendingDataGridSaveCount()).toBe(0);
+ });
+
+ it("keeps both saves of a split view independent and does not drop the running one", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const leftExecution = deferred<{ affected_rows: number }>();
+ const rightExecution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(leftExecution.promise).mockReturnValueOnce(rightExecution.promise);
+
+ // Split view: two grids of the same tab and result payload, both mounted.
+ const left = mountGrid();
+ const right = mountGrid();
+ stageFourPendingUpdates(left.currentEditor);
+ stageFourPendingUpdates(right.currentEditor);
+ const leftSaving = left.currentEditor.saveChanges();
+ await flush();
+ const rightSaving = right.currentEditor.saveChanges();
+ await flush();
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(2);
+ expect(pendingDataGridSaveCount()).toBe(2);
+
+ // The older save settles first: it must not delete the still-running one.
+ leftExecution.resolve({ affected_rows: 4 });
+ await leftSaving;
+ await flush();
+ expect(right.currentEditor.isSaving.value).toBe(true);
+ expect(pendingDataGridSaveCount()).toBe(1);
+
+ rightExecution.resolve({ affected_rows: 4 });
+ await rightSaving;
+ await flush();
+ expect(right.currentEditor.isSaving.value).toBe(false);
+ expect(pendingDataGridSaveCount()).toBe(0);
+ // Each grid reported its own save; neither toasted as an adopter.
+ expect(left.onAdoptedSaveCompleted).not.toHaveBeenCalled();
+ expect(right.onAdoptedSaveCompleted).not.toHaveBeenCalled();
+ left.unmount();
+ right.unmount();
+ });
+
+ it("drops the pending saves of a closed tab", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ await flush();
+ expect(pendingDataGridSaveCount()).toBe(1);
+
+ first.unmount();
+ await flush();
+ clearDataGridPendingSnapshotsForTab("query-tab-1");
+ expect(pendingDataGridSaveCount()).toBe(0);
+
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+ expect(pendingDataGridSaveCount()).toBe(0);
+ });
+
+ it("reports an adopted completion once, even across further remounts", async () => {
+ mocks.prepareDataGridSave.mockResolvedValue({ statements: ["UPDATE orders SET status = 'saved'"], rollbackStatements: [] });
+ const execution = deferred<{ affected_rows: number }>();
+ mocks.executeBatch.mockReturnValueOnce(execution.promise);
+
+ const first = mountGrid();
+ stageFourPendingUpdates(first.currentEditor);
+ const saving = first.currentEditor.saveChanges();
+ first.unmount();
+ await flush();
+
+ const second = mountGrid();
+ execution.resolve({ affected_rows: 4 });
+ await saving;
+ await flush();
+ expect(second.onAdoptedSaveCompleted).toHaveBeenCalledOnce();
+
+ second.unmount();
+ const third = mountGrid();
+ await flush();
+ expect(third.onAdoptedSaveCompleted).not.toHaveBeenCalled();
+ expect(third.currentEditor.isSaving.value).toBe(false);
+ third.unmount();
+ expect(pendingDataGridSaveCount()).toBe(0);
+ });
+
+});
diff --git a/apps/desktop/src/composables/useDataGridEditor.ts b/apps/desktop/src/composables/useDataGridEditor.ts
index b3895955d9..0dce7a522e 100644
--- a/apps/desktop/src/composables/useDataGridEditor.ts
+++ b/apps/desktop/src/composables/useDataGridEditor.ts
@@ -154,12 +154,22 @@ export interface UseDataGridEditorOptions {
pageSize: Ref<number>;
currentPage: Ref<number>;
cacheKey?: ComputedRef<string | undefined>;
+ /**
+ * Tab that owns the displayed result. A tab switch unmounts the grid while a
+ * save is still running, so the in-flight save must be tracked per tab
+ * (issue #13226).
+ */
+ tabId?: ComputedRef<string | undefined>;
+ /** Identity of the displayed result payload; a new payload never inherits a running save. */
+ resultViewGeneration?: ComputedRef<string | undefined>;
/** 保存成功后结果负载被原地修改时通知宿主,使缓存的字节估算失效。 */
onResultPayloadMutated?: () => void;
prepareSaveBaseline?: (changes: { dirtyRows: ReadonlyMap<number, ReadonlyMap<number, CellValue>>; deletedRows: ReadonlySet<number> }) => Promise<void>;
refreshSavedRows?: (request: { dirtyRows: ReadonlyMap<number, ReadonlyMap<number, CellValue>>; columns: readonly string[]; rows: readonly (readonly CellValue[])[] }) => Promise<boolean>;
onCellValueChanged?: (rowId: number, columnIndex: number) => void;
prepareFullReload?: () => void;
+ /** The adopted save (started by a previous grid instance that is gone) finished and the host grid refreshed. */
+ onAdoptedSaveCompleted?: () => void;
emit: (event: "reload", sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => void;
}
@@ -180,6 +190,9 @@ interface PendingChangesSnapshot {
// re-execute, sort, paginate, eviction reload — still starts at the first row
// (#7341).
scrollFromTabSwitch?: boolean;
+ // Written while this instance's save was in flight. The save already owns
+ // those changes, so a remount must not restore them as pending (#13226).
+ saving?: boolean;
columnCount: number;
rowCount: number;
}
@@ -206,6 +219,100 @@ type PendingChangesHistorySnapshot = Pick<PendingChangesSnapshot, "newRows" | "n
const pendingChangesCache = new Map<string, PendingChangesSnapshot>();
const closingPendingSnapshotTabs = new Set<string>();
+
+/**
+ * In-flight saves, keyed by tab and result payload.
+ *
+ * A save keeps running after the grid that started it is unmounted (tab switch,
+ * summary view), because the columns of a result key are the same for every
+ * instance of that grid. Its side effects — `isSaving`, clearing the saved
+ * pending changes, refreshing the viewer — all lived on the unmounted instance,
+ * so returning to the tab showed the stale "498" badge, kept the commit button
+ * enabled and never refreshed or reported the result (issue #13226).
+ *
+ * The next instance of the same tab and result adopts the save: it views
+ * `isSaving` from here and reloads its result once the save settles. A record
+ * outlives a save that settled while no grid was mounted, so that grid still
+ * gets the refresh it missed; it is released once a grid consumed it, when the
+ * tab closes, or when the tab's result is replaced.
+ */
+interface PendingSaveRecord {
+ /** Id of this record: a settling save only ever settles its own record. */
+ id: number;
+ key: string;
+ running: boolean;
+ /** The instance that started the save: only another instance reports it. */
+ owner: object;
+ /** A grid that was unmounted mid-save asked to reload its result afterwards. */
+ refreshAfter: boolean;
+ /** The completion was already reported, so a remount never repeats it. */
+ reported: boolean;
+ /** The grid currently showing this result, if any: it reloads and reports. */
+ live?: PendingSaveWatcher;
+}
+
+/** What a grid of the same tab and result can do for the save it adopted. */
+interface PendingSaveWatcher {
+ isMounted: () => boolean;
+ /** The save failed: show its changes again so the user can retry. */
+ restore: (snapshot: PendingSaveSnapshot) => void;
+ refresh: () => void;
+ reportSaved: () => void;
+ /** The save it adopted settled: stop showing it as running. */
+ settled: () => void;
+}
+
+/**
+ * Saves grouped by key. Several grids can show the same tab and result payload
+ * (split view); each save keeps its own record, and only a record that is still
+ * running is adoptable.
+ */
+const pendingSaves = new Map<string, PendingSaveRecord[]>();
+let saveInstanceSeq = 0;
+let saveRecordSeq = 0;
+/** Bumped on every registry change: grids read the non-reactive map through it. */
+const pendingSavesVersion = ref(0);
+
+function touchPendingSaves() {
+ pendingSavesVersion.value++;
+}
+
+/** Removes one record, keeping the other saves of the same grid alive. */
+function dropPendingSave(record: PendingSaveRecord) {
+ const list = pendingSaves.get(record.key);
+ if (!list) return;
+ const index = list.indexOf(record);
+ if (index < 0) return;
+ list.splice(index, 1);
+ if (!list.length) pendingSaves.delete(record.key);
+ touchPendingSaves();
+}
+
+/**
+ * Reads registry state through the reactive version: the registry itself is a
+ * module-level Map, so computeds must subscribe to the version to follow it.
+ */
+function readingPendingSaves<T>(value: T): T {
+ void pendingSavesVersion.value;
+ return value;
+}
+
+/** The save a returning grid adopts: the one still running for this grid. */
+function adoptablePendingSave(key: string | undefined): PendingSaveRecord | undefined {
+ if (!key) return undefined;
+ return pendingSaves.get(key)?.find((record) => record.running);
+}
+
+/** The save whose reload is still owed to a returning grid. */
+function owedPendingSave(key: string | undefined): PendingSaveRecord | undefined {
+ if (!key) return undefined;
+ return pendingSaves.get(key)?.find((record) => record.refreshAfter);
+}
+
+function saveRegistryKey(tabId: string, revision?: string) {
+ return revision ? `${tabId}\u0000${revision}` : tabId;
+}
+
const BEFORE_TAB_SWITCH_EVENT = "dbx:before-tab-switch";
const MAX_PENDING_CHANGES_HISTORY = 100;
const MAX_PENDING_HISTORY_CELLS = 2_000_000;
@@ -243,6 +350,21 @@ export function clearDataGridPendingSnapshotsForTab(tabId: string) {
for (const key of pendingChangesCache.keys()) {
if (cacheKeyBelongsToTab(key, tabId)) pendingChangesCache.delete(key);
}
+ // Its saves cannot be adopted any more either (#13226). Save keys are
+ // `tabId\u0000revision` (or a cache key), so compare the part before it.
+ const staleSaveKeys: string[] = [];
+ for (const key of pendingSaves.keys()) {
+ if (cacheKeyBelongsToTab(key.split("\u0000")[0] ?? key, tabId)) staleSaveKeys.push(key);
+ }
+ staleSaveKeys.forEach((key) => pendingSaves.delete(key));
+ touchPendingSaves();
+}
+
+/** Exposed for tests: how many in-flight save records the registry holds. */
+export function pendingDataGridSaveCount(): number {
+ let count = 0;
+ for (const records of pendingSaves.values()) count += records.length;
+ return count;
}
export function clearDataGridPendingSnapshot(cacheKey: string) {
@@ -282,7 +404,10 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
pageSize,
currentPage,
cacheKey,
+ tabId,
+ resultViewGeneration,
onCellValueChanged,
+ onAdoptedSaveCompleted,
} = options;
const editingCell = ref<{ rowId: number; col: number } | null>(null);
@@ -378,12 +503,38 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
let scrollSnapshotFromTabSwitch = false;
let saveScrollSnapshotTimer = 0;
let componentActive = true;
+ // Without a component instance (plain unit usage) there is no lifecycle to
+ // follow: the editor is the live grid from the start.
+ const componentInstance = getCurrentInstance();
+ let mounted = !componentInstance;
+
+ // A save belongs to the grid of a tab and result payload, so the grid that
+ // replaces it finds it and views its busy state until it settles (#13226).
+ // A grid without either identity can only be replaced by itself.
+ const instanceSaveKey = `instance-${++saveInstanceSeq}`;
+ const saveOwner = {};
+ const currentSaveKey = () => {
+ const tab = tabId?.value;
+ if (tab) return saveRegistryKey(tab, resultViewGeneration?.value);
+ const key = cacheKey?.value;
+ return key ? saveRegistryKey(key, resultViewGeneration?.value) : instanceSaveKey;
+ };
+ let pendingSaveKey = currentSaveKey();
+ // The save this instance shows: started here or adopted from the registry.
+ // Tracked per instance, so a grid never settles or consumes another grid's
+ // save on the same result (split view).
+ let currentRecord: PendingSaveRecord | undefined;
+ const isAdoptedRunning = () => readingPendingSaves(currentRecord?.running) === true;
// Restore cached pending changes from a previous instance (e.g. after result eviction + reload)
const key = cacheKey?.value;
if (key) {
const cached = pendingChangesCache.get(key);
- if (cached && cached.columnCount === result.value.columns.length && cached.rowCount === result.value.rows.length) {
+ // A snapshot written while a save was in flight belongs to that save. Once
+ // the save is gone (and this instance did not adopt it) restoring it would
+ // resurrect changes the server already has (#13226).
+ const savedByGoneSave = cached?.saving === true && !isAdoptedRunning();
+ if (cached && !savedByGoneSave && cached.columnCount === result.value.columns.length && cached.rowCount === result.value.rows.length) {
newRows.value = cached.newRows;
restoreNewRowMeta(cached.newRowMeta ?? []);
quickEntryDraftRow.value = cached.quickEntryDraftRow ? [...cached.quickEntryDraftRow] : [];
@@ -422,7 +573,18 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
// --- Transaction state ---
const transactionActive = ref(false);
+ // True while this instance saves or while it adopted the save of a previous
+ // instance for the same tab and result. It stays a plain writable ref: the
+ // registry mirrors an adopted save into it, and hosts (and tests) may pin it.
const isSaving = ref(false);
+ // Busy state this instance owns itself, so mirroring an adopted save never
+ // clears a save this instance is running.
+ let localSaveBusy = false;
+ const setLocalSaveBusy = (busy: boolean) => {
+ localSaveBusy = busy;
+ isSaving.value = busy || isAdoptedRunning();
+ };
+ const adoptedSave = computed(() => isAdoptedRunning());
const saveError = ref("");
const previewValidationMessage = ref("");
const conditionalUpdateExecution = shallowRef<ConditionalUpdateExecution>();
@@ -1749,7 +1911,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
async function finishSaveChanges(savedSnapshot?: PendingSaveSnapshot) {
- isSaving.value = false;
+ setLocalSaveBusy(false);
if (!hasPendingChanges.value) manualSaveRequired.value = false;
if (pendingAutoSaveRequested && dataGridQuickEntryEnabled.value) {
applyQueuedAutoSaveChanges(savedSnapshot);
@@ -1766,9 +1928,12 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
}
- async function finishInterruptedSaveChanges(snapshot: PendingSaveSnapshot) {
+ async function finishInterruptedSaveChanges(snapshot: PendingSaveSnapshot, record?: PendingSaveRecord) {
snapshot.newRowRefs.forEach((row) => savingNewRows.delete(row));
await finishSaveChanges();
+ // The changes stay pending for a retry, and the grid that shows them stops
+ // waiting for this save (#13226).
+ onPendingSaveSettled(snapshot, false, record);
}
function saveStatementOptions(snapshot = snapshotPendingSaveChanges()) {
@@ -1845,6 +2010,195 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
return id ? connectionStore.getConfig(id)?.driver_profile : undefined;
}
+ // --- In-flight save ownership across grid unmounts ---
+ // A save keeps running in its instance after the grid is unmounted (tab
+ // switch, summary view). The registry record above follows it, so whichever
+ // grid of the result is in the DOM reloads and reports in its place (#13226).
+ let persistenceKnown = false;
+ let lastPersistedNewRows: CellValue[][] = [];
+
+ function persistGridState() {
+ savePendingSnapshot(true, true);
+ persistenceKnown = true;
+ lastPersistedNewRows = [...newRows.value];
+ }
+
+ // Rows this instance left pending when it wrote its state: the only ones the
+ // persisted snapshot can still be holding after a save wrote them.
+ function keptNewRowsAfter(snapshot: PendingSaveSnapshot) {
+ if (!persistenceKnown) return [];
+ return lastPersistedNewRows.filter((row) => snapshot.newRowRefs.includes(row) && savingNewRows.has(row));
+ }
+
+ // Drops changes a save already wrote from the persisted grid state, so a grid
+ // that returns later never restores them as pending (#13226). On failure only
+ // the rows this save is still retrying go back; the rest were written by an
+ // earlier save that went through.
+ function clearPersistedPendingChangesForSave(snapshot?: PendingSaveSnapshot, completed = false) {
+ const k = cacheKey?.value;
+ const cached = k ? pendingChangesCache.get(k) : undefined;
+ if (!k || !cached) return;
+ if (!completed && !snapshot) return;
+ // Success: everything this save wrote leaves the snapshot (rows another grid
+ // added meanwhile stay). Failure: only rows the statement batch already
+ // wrote leave it, so the change being retried survives for the next mount.
+ const keptNewRows = completed ? [] : snapshot ? keptNewRowsAfter(snapshot) : [...cached.newRows];
+ const keptDirtyRows = completed || !snapshot ? new Map<number, Map<number, CellValue>>() : new Map([...cached.dirtyRows].filter(([rowIndex]) => snapshot.dirtyRows.has(rowIndex)));
+ const keptDeletedRows = completed || !snapshot ? new Set<number>() : new Set([...cached.deletedRows].filter((rowIndex) => snapshot.deletedRows.has(rowIndex)));
+ Object.assign(cached, {
+ newRows: keptNewRows,
+ newRowMeta: cached.newRowMeta.slice(cached.newRowMeta.length - keptNewRows.length),
+ dirtyRows: keptDirtyRows,
+ deletedRows: keptDeletedRows,
+ saving: false,
+ manualSaveRequired: !completed && snapshot ? true : cached.manualSaveRequired,
+ });
+ if (!keptNewRows.length && !keptDirtyRows.size && !keptDeletedRows.size && !cached.quickEntryDraftRow && !cached.editingCell && !cached.scroll) pendingChangesCache.delete(k);
+ }
+
+ // Called where a successful save would reload the grid. The grid in the DOM
+ // does it now, either this one or the one that replaced it while it was
+ // unmounted; with nothing in the DOM the reload waits for the grid that returns
+ // (a later new result replaces it anyway).
+ function reloadAfterSave(record?: PendingSaveRecord) {
+ if (!record) return;
+ const live = mounted ? undefined : record.live?.isMounted() ? record.live : undefined;
+ if (mounted) reloadCurrentData();
+ else if (live) live.refresh();
+ else record.refreshAfter = true;
+ }
+
+ function settlePendingSave(snapshot: PendingSaveSnapshot, completed: boolean, record: PendingSaveRecord | undefined) {
+ if (!record) return;
+ // Only ever settle this save, never another grid's save on the same result.
+ record.running = false;
+ const live = mounted ? undefined : record.live?.isMounted() ? record.live : undefined;
+ // The save is done: whatever it wrote must not come back from the snapshot
+ // the previous grid persisted, whether or not a grid is mounted now.
+ clearPersistedPendingChangesForSave(snapshot, completed);
+ if (live) {
+ // A grid replaced this one mid-save and owns the outcome: it shows the
+ // failure itself, and reloads and reports a save that went through.
+ if (!completed) live.restore(snapshot);
+ if (record.refreshAfter) {
+ record.refreshAfter = false;
+ live.refresh();
+ }
+ if (completed && !record.reported) {
+ record.reported = true;
+ live.reportSaved();
+ }
+ dropPendingSave(record);
+ // The adopting grid stopped viewing a running save: release its busy state.
+ live.settled();
+ return;
+ }
+ if (mounted) {
+ dropPendingSave(record);
+ isSaving.value = localSaveBusy || isAdoptedRunning();
+ // A grid that started the save reports it itself; an adopting grid reports
+ // the completion it would otherwise miss, once per record (#13226).
+ if (completed && !record.reported && record.owner !== saveOwner) {
+ record.reported = true;
+ onAdoptedSaveCompleted?.();
+ }
+ return;
+ }
+ // No grid is mounted. A successful save still owes the grid that returns its
+ // reload, so the record stays until that grid consumes it. A failed save
+ // keeps its pending changes in the persisted state instead, so its record
+ // (which could never be adopted again) goes.
+ if (!record.refreshAfter) dropPendingSave(record);
+ touchPendingSaves();
+ }
+
+ function beginPendingSave(): PendingSaveRecord | undefined {
+ const key = currentSaveKey();
+ if (!key) return undefined;
+ pendingSaveKey = key;
+ // Split view: another grid of the same result may be saving too. Its record
+ // stays, so both saves settle and report independently.
+ const record: PendingSaveRecord = { id: ++saveRecordSeq, key, running: true, owner: saveOwner, refreshAfter: false, reported: false, live: mounted ? saveWatcher : undefined };
+ pendingSaves.set(key, [...(pendingSaves.get(key) ?? []), record]);
+ currentRecord = record;
+ touchPendingSaves();
+ return record;
+ }
+
+ // The grid in the DOM is the one that reloads and reports for this save. It
+ // claims the record on mount and hands it back when it leaves, so the save
+ // started by an unmounted grid still reaches whoever shows the result.
+ const saveWatcher: PendingSaveWatcher = {
+ isMounted: () => mounted && pendingSaveKey === currentSaveKey(),
+ restore: (snapshot) => {
+ newRows.value = snapshot.newRows;
+ dirtyRows.value = snapshot.dirtyRows;
+ deletedRows.value = snapshot.deletedRows;
+ manualSaveRequired.value = true;
+ },
+ refresh: () => void refreshCurrentData(),
+ reportSaved: () => onAdoptedSaveCompleted?.(),
+ settled: () => {
+ if (currentRecord && !currentRecord.running) currentRecord = undefined;
+ isSaving.value = localSaveBusy || isAdoptedRunning();
+ },
+ };
+
+ // Resolves the save of this grid after the key is known (or changed) and makes
+ // this grid its live viewer: a cache-key grid has no tabId, so the record is
+ // looked up here rather than only when the key happens to match already.
+ function syncCurrentSave(syncKey: boolean) {
+ const key = currentSaveKey();
+ if (syncKey && key !== pendingSaveKey) {
+ // Another result payload: a save still running for the old one keeps
+ // running, but this grid will never show its outcome.
+ const previous = currentRecord;
+ if (previous) releasePendingSaveRecord(previous);
+ pendingSaveKey = key;
+ currentRecord = undefined;
+ }
+ if (currentRecord && currentRecord.running && !pendingSaves.get(currentRecord.key)?.includes(currentRecord)) currentRecord = undefined;
+ if (!currentRecord || !currentRecord.running) {
+ const adopted = adoptablePendingSave(key) ?? owedPendingSave(key);
+ if (adopted) currentRecord = adopted;
+ }
+ const record = currentRecord;
+ if (record?.running) record.live = saveWatcher;
+ if (record?.refreshAfter) {
+ record.refreshAfter = false;
+ void refreshCurrentData();
+ }
+ if (record && !record.running && !record.refreshAfter) dropPendingSave(record);
+ if (record?.running) isSaving.value = true;
+ }
+
+ function claimPendingSave() {
+ syncCurrentSave(true);
+ }
+
+ function adoptRunningSave() {
+ syncCurrentSave(true);
+ }
+
+ function releasePendingSaveRecord(record: PendingSaveRecord) {
+ if (record.live === saveWatcher) record.live = undefined;
+ }
+
+ // Mirrors an adopted save into `isSaving`, so a remounted grid shows the busy
+ // commit action without making `isSaving` a derived value (#13226).
+ watch(
+ adoptedSave,
+ (adopted) => {
+ isSaving.value = localSaveBusy || adopted;
+ },
+ { flush: "sync" },
+ );
+
+ function onPendingSaveSettled(snapshot: PendingSaveSnapshot, completed: boolean, record: PendingSaveRecord | undefined) {
+ settlePendingSave(snapshot, completed, record);
+ }
+
+
function tableHistoryTarget() {
if (joinedWriteTargets.value?.length) return [...new Set(joinedWriteTargets.value.map(({ tableMeta: target }) => [target.database, target.schema, target.tableName].filter(Boolean).join(".")))].join(", ");
if (!tableMeta.value) return "";
@@ -1937,11 +2291,25 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
options.emit("reload", sql.value, searchText.value, options.currentWhereInput.value, orderByInput.value.trim() || undefined, pageSize.value, (currentPage.value - 1) * pageSize.value);
}
+ // Refreshes the result whose grid started a save, for a reload that was left
+ // over when that grid unmounted. The rows still belong to this result (only a
+ // new payload replaces the grid) and the current sort, page and filters are
+ // the view the user is returning to.
+ async function refreshCurrentData() {
+ options.prepareFullReload?.();
+ try {
+ await options.refreshSavedRows?.({ dirtyRows: new Map(), columns: result.value.columns, rows: result.value.rows });
+ } catch (error) {
+ console.warn("[DBX] failed to refresh saved data grid rows", error);
+ }
+ reloadCurrentData();
+ }
+
function completeConditionalUpdate(execution: ConditionalUpdateExecution) {
if (conditionalUpdateExecution.value !== execution) return false;
execution.outcome = "completed";
conditionalUpdateExecution.value = undefined;
- isSaving.value = false;
+ setLocalSaveBusy(false);
reloadCurrentData();
return true;
}
@@ -1997,7 +2365,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
outcome: "not-started",
};
conditionalUpdateExecution.value = execution;
- isSaving.value = true;
+ setLocalSaveBusy(true);
const startedAt = Date.now();
try {
if (execution.cancelRequested) return null;
@@ -2034,7 +2402,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
} finally {
if (conditionalUpdateExecution.value === execution && execution.outcome !== "unknown") {
conditionalUpdateExecution.value = undefined;
- isSaving.value = false;
+ setLocalSaveBusy(false);
}
}
}
@@ -2046,7 +2414,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (!execution.dispatched) {
execution.outcome = "not-started";
conditionalUpdateExecution.value = undefined;
- isSaving.value = false;
+ setLocalSaveBusy(false);
return true;
}
execution.cancelling = true;
@@ -2114,7 +2482,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
saveError.value = "";
previewValidationMessage.value = "";
- isSaving.value = true;
+ setLocalSaveBusy(true);
+ const saveRecord = beginPendingSave();
snapshot.newRowRefs.forEach((row) => savingNewRows.add(row));
const shouldReloadAfterSave = snapshot.newRows.length > 0 || snapshot.deletedRows.size > 0;
// SQL saves may update columns the client can't predict (e.g. an ON UPDATE CURRENT_TIMESTAMP
@@ -2134,7 +2503,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const confirmSaveRequest = options.confirmSaveRequest?.value;
if (confirmSaveRequest) {
if (saveOptions.autoSave) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
let statements: string[];
@@ -2144,7 +2513,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (statements.length === 0) throw new Error("This data source did not produce a safe mutation preview.");
} catch (e: any) {
saveError.value = normalizeDataGridSaveError(databaseType.value, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const saveConfirmed = await confirmSaveRequest({
@@ -2155,7 +2524,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
statements,
});
if (!saveConfirmed) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
}
@@ -2164,7 +2533,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
} catch (e: any) {
saveError.value = normalizeDataGridSaveError(databaseType.value, e);
if (customHandler.reloadOnFailure && shouldReloadAfterSave) reloadCurrentData();
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
snapshot.newRowRefs.forEach((row) => savingNewRows.delete(row));
@@ -2185,7 +2554,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (options.prepareSaveBaseline) await options.prepareSaveBaseline(snapshot);
} catch (error) {
saveError.value = normalizeDataGridSaveError(databaseType.value, error);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const stmtOptions = saveStatementOptions(snapshot);
@@ -2195,7 +2564,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
preparedSave = await prepareSaveStatements(stmtOptions);
} catch (e: any) {
saveError.value = normalizeDataGridSaveError(databaseType.value, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
}
@@ -2205,17 +2574,17 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
// draft staged until it becomes valid instead of surfacing a save
// failure for an expected intermediate state.
previewValidationMessage.value = preparedSave.validationError;
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
saveError.value = preparedSave.validationError;
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const stmts = preparedSave?.statements ?? [];
if (stmts.length === 0) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const rollbackStmts = preparedSave?.rollbackStatements ?? [];
@@ -2226,7 +2595,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (!txnSessionId) throw new Error("Manual transaction session was not initialized");
} catch (error) {
saveError.value = normalizeDataGridSaveError(databaseType.value, error);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
}
@@ -2234,19 +2603,19 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const guardError = await verifyKeylessGuards(preparedSave?.keylessGuards ?? [], preparedSave?.executionSchema, txnSessionId);
if (guardError) {
saveError.value = guardError;
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
} catch (e: any) {
saveError.value = normalizeDataGridSaveError(databaseType.value, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const productionAssessment = assessProductionSql(stmts.join(";\n"), connection, database.value);
if (productionAssessment.active && productionAssessment.isMutation) {
// Autosave must never write production data without an operator reviewing the generated statements.
if (saveOptions.autoSave) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const confirmed = await productionSafetyStore.requestConfirmation({
@@ -2257,7 +2626,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
source: i18n.global.t("readOnlyUnlock.sourceDataEditor"),
});
if (!confirmed) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
}
@@ -2268,7 +2637,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
const confirmSaveRequest = options.confirmSaveRequest?.value;
if (confirmSaveRequest) {
if (saveOptions.autoSave) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const saveConfirmed = await confirmSaveRequest({
@@ -2279,12 +2648,12 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
statements: stmts,
});
if (!saveConfirmed) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
}
if (!editable.value || stmtOptions?.tableMeta !== tableMeta.value) {
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
const start = Date.now();
@@ -2308,7 +2677,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (stmts.length === 1 && results.length === 1) singleStatementAffectedRows = results[0]?.affected_rows;
} catch (e: any) {
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
} else if (useTransaction.value && stmts.length > 1 && hasBackendSaveTarget.value) {
@@ -2318,7 +2687,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
: await api.executeInTransaction(connectionId.value!, database.value ?? "", stmts, preparedSave?.executionSchema);
} catch (e: any) {
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
} else if (hasBackendSaveTarget.value) {
@@ -2329,7 +2698,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (stmts.length === 1) singleStatementAffectedRows = apiResult?.affected_rows;
} catch (e: any) {
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
} else if (onExecuteSql.value) {
@@ -2339,7 +2708,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
}
} catch (e: any) {
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, e);
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
}
@@ -2356,7 +2725,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (missedSingleRowIdUpdate) {
manualSaveRequired.value = true;
saveError.value = await recordFailedDataGridHistory(stmts, rollbackStmts, start, snapshot, new Error(i18n.global.t("grid.rowIdUpdateConflict")));
- await finishInterruptedSaveChanges(snapshot);
+ await finishInterruptedSaveChanges(snapshot, saveRecord);
return;
}
// Anonymous PL/SQL reports zero for an unknown JDBC update count; its
@@ -2401,9 +2770,10 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
// Notify before reload can replace the rows and clear their error state.
if (deleteConflict) options.onSaveConflict?.(deleteConflict);
if (shouldReloadAfterSqlSave && !savedRowsRefreshed) {
- reloadCurrentData();
+ reloadAfterSave(saveRecord);
}
await finishSaveChanges(snapshot);
+ onPendingSaveSettled(snapshot, true, saveRecord);
// These deletes reached a terminal result. Refresh and report the mismatch
// instead of leaving a missing ROWID queued for an impossible retry.
if (deleteConflict) saveError.value = deleteConflict;
@@ -2467,6 +2837,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
transactionActive: transactionActive.value,
scroll,
scrollFromTabSwitch: scroll ? scrollSnapshotFromTabSwitch : false,
+ // Only a snapshot that still carries pending changes is owned by the save.
+ saving: isSaving.value && (newRows.value.length > 0 || dirtyRows.value.size > 0 || deletedRows.value.size > 0),
columnCount: result.value.columns.length,
rowCount: result.value.rows.length,
});
@@ -2486,11 +2858,12 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
// receives this window event, so only the grid whose own tab is being left may
// claim the scroll restore. A missing fromTabId falls through to "start at top".
if (key && detail?.fromTabId && cacheKeyBelongsToTab(key, detail.fromTabId)) scrollSnapshotFromTabSwitch = true;
- savePendingSnapshot(true, true);
+ // A save in flight already owns the changes it is writing; persisting them
+ // here would bring them back after a remount (#13226).
+ if (!isSaving.value) persistGridState();
if (editingCell.value) suppressNextBlurCommit = true;
}
- const componentInstance = getCurrentInstance();
if (componentInstance && typeof window !== "undefined") {
window.addEventListener(BEFORE_TAB_SWITCH_EVENT, onBeforeTabSwitch);
}
@@ -2498,22 +2871,34 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
if (componentInstance) {
onMounted(() => {
componentActive = true;
+ mounted = true;
applyScrollPosition(pendingScrollRestore);
+ claimPendingSave();
+ adoptRunningSave();
});
onActivated(() => {
componentActive = true;
+ mounted = true;
restorePendingSnapshotFocus();
+ claimPendingSave();
+ adoptRunningSave();
});
onDeactivated(() => {
- savePendingSnapshot(true, true);
+ if (currentRecord) releasePendingSaveRecord(currentRecord);
+ if (!isSaving.value) persistGridState();
componentActive = false;
+ mounted = false;
});
// Save pending changes before the component is destroyed so they can be
// restored if a new DataGrid instance is created for the same tab
// (e.g. after result eviction + reload).
onBeforeUnmount(() => {
- savePendingSnapshot(true, true);
+ if (currentRecord) releasePendingSaveRecord(currentRecord);
+ // Persist even mid-save: the snapshot is marked `saving`, so a grid that
+ // returns after a failure still restores changes it can retry.
+ persistGridState();
+ mounted = false;
if (typeof window !== "undefined") {
window.removeEventListener(BEFORE_TAB_SWITCH_EVENT, onBeforeTabSwitch);
}
@@ -2641,6 +3026,8 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
// instance, so specs drive the tab-switch path directly.
onBeforeTabSwitch,
restorePendingSnapshotFocus,
+ adoptRunningSave,
+ adoptedSave,
syncHeaderScroll: (headerRef: Ref<HTMLDivElement | undefined>) => (e: Event) => {
if (headerRef.value) {
headerRef.value.scrollLeft = (e.target as HTMLElement).scrollLeft;
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 0159f79063..a0f25441dd 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -3596,6 +3596,7 @@ export default {
noColumnsFound: "No columns found",
queryError: "Query Error",
saveErrorTitle: "Failed to Save Changes",
+ saveCompleted: "Changes saved; the result was refreshed.",
dataUnavailable: "Table data needs to be reloaded.",
viewSnapshotSelectionNotRestored: "The previous view was restored, but its selection was too large to keep.",
cachedResultUnavailable: "The cached result is missing or incompatible.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index cabd45ae47..f299c8cb42 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -3527,6 +3527,7 @@ export default withEnglishFallback({
noColumnsFound: "未找到列",
queryError: "查询出错",
saveErrorTitle: "数据修改保存失败",
+ saveCompleted: "更改已保存,结果已刷新。",
dataUnavailable: "表数据需要重新加载。",
viewSnapshotSelectionNotRestored: "已恢复上次的视图位置,但过大的选择范围未能保留。",
dataUnavailableHintPrefix: "按 ",