fix(database): ask before dropping a table's unsubmitted edits (#7850)

In a table tab, paging, reloading, sorting, filtering or changing the page size after editing a cell dropped the edit without a word, and paging or rerunning a result tab did the same. Both now ask "Changes are not submitted. Data will be lost. Continue?" first; Cancel keeps the edits and the page, sort, filter and page size as they were. Rows can't be edited or added while a page loads, since the load drops them.

Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
ntbang0901 authored and GitHub committed 2026-12-04 00:54:30 +08:00
1 джерело 5f31f1292a
коміт 0e221ba78a
7 files changed
+304 -35

No files matched your search

+6 -3
Переглянути файл
@@ -76,6 +76,7 @@ import {
import styles from "./Database.module.css";
import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from "./tableEditorFocus";
import { tx } from "@/platform/i18n";
import { discardingEdits } from "./unsubmittedEdits";
function time(t: number): string {
const d = new Date(t);
@@ -143,7 +144,8 @@ function pagerOf(tab: ResultTab) {
const state = { page, pageSize, rows: r.rows.length, hasMore: r.hasMore, total: tab.total ?? null };
const w = pageWindow(state);
const canPage = pageable(tab) && !tab.busy;
const go = (p: number, size = pageSize) => void loadResultPage(tab.id, p, size);
const go = (p: number, size = pageSize) =>
discardingEdits(keptEdits.get(r), () => void loadResultPage(tab.id, p, size));
const goLast = async () => {
let lastPage = w.lastPage;
if (lastPage === null) {
@@ -426,6 +428,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
const dirty = hasEdits(edits);
const submitting = useSyncExternalStore(subscribeResults, () => !!r && submittingResults.has(r));
const busy = submitting || !!tab.busy;
const rerun = () => discardingEdits(edits, () => void rerunResult(tab.id));
const submit = async () => {
if (!r || !target || !pk || !editable || busy || submittingResults.has(r)) return;
@@ -517,7 +520,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
const rowsEditable = editable && !busy && view === "table";
handle.commands = pager
? {
reload: { enabled: () => !busy, run: () => void rerunResult(tab.id) },
reload: { enabled: () => !busy, run: rerun },
firstPage: { enabled: () => pager.canPrevious, run: () => pager.go(0) },
previousPage: { enabled: () => pager.canPrevious, run: () => pager.go(pager.page - 1) },
nextPage: { enabled: () => pager.canNext, run: () => pager.go(pager.page + 1) },
@@ -576,7 +579,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
title="Rerun Query"
shortcut={shortcutLabel("db.reloadPage")}
disabled={busy}
onClick={() => void rerunResult(tab.id)}
onClick={rerun}
/>
{!onClose && <PinButton tab={tab} />}
{view === "table" && (
+45 -28
Переглянути файл
@@ -40,6 +40,7 @@ import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from
import { tx } from "@/platform/i18n";
import { shortcutLabel } from "@/platform/keymap";
import { pageWindow } from "./resultView";
import { discardingEdits } from "./unsubmittedEdits";
const PAGE_SIZES = ["100", "500", "1000", "5000"];
@@ -258,15 +259,32 @@ export function TableEditor({ input }: { input: EditorInput }) {
}
};
const onSort = (column: string, add: boolean) =>
setSort((s) => {
const cur = s.find((k) => k.column === column);
// asc → desc → none.
const next = !cur ? { column, descending: false } : !cur.descending ? { column, descending: true } : null;
const rest = add ? s.filter((k) => k.column !== column) : [];
return next ? [...rest, next] : rest;
/** Shows the rows `next` describes, which drops the edits of these. */
const showRows = (next: Partial<Pick<TableViewState, "offset" | "limit" | "sort" | "filter">>) => {
const shown = { offset, limit, sort, filter };
const to = { ...shown, ...next };
if (JSON.stringify(to) === JSON.stringify(shown)) return;
discardingEdits(edits, () => {
setOffset(to.offset);
setLimit(to.limit);
setSort(to.sort);
setFilter(to.filter);
});
};
const reloadPage = () => discardingEdits(edits, reload);
const previousPage = () => showRows({ offset: Math.max(0, offset - limit) });
const nextPage = () => showRows({ offset: offset + limit });
const onSort = (column: string, add: boolean) => {
const cur = sort.find((k) => k.column === column);
// asc → desc → none.
const next = !cur ? { column, descending: false } : !cur.descending ? { column, descending: true } : null;
const rest = add ? sort.filter((k) => k.column !== column) : [];
showRows({ sort: next ? [...rest, next] : rest });
};
// The rows being loaded drop the edits: none can be added meanwhile.
const rowsEditable = editable && !loading;
const dirty = hasEdits(edits);
// Submit / Revert actions (⌘↩ / ⌥⌘Z) reach the latest state through the handle.
const viewRef = useRef<HTMLDivElement>(null);
@@ -308,11 +326,11 @@ export function TableEditor({ input }: { input: EditorInput }) {
const canPrevious = offset > 0 && !loading;
const canNext = !!page?.result.hasMore && !loading;
handle.commands = {
reload: { enabled: () => !loading, run: reload },
firstPage: { enabled: () => canPrevious, run: () => setOffset(0) },
previousPage: { enabled: () => canPrevious, run: () => setOffset(Math.max(0, offset - limit)) },
nextPage: { enabled: () => canNext, run: () => setOffset(offset + limit) },
addRow: { enabled: () => editable, run: addRow },
reload: { enabled: () => !loading, run: reloadPage },
firstPage: { enabled: () => canPrevious, run: () => showRows({ offset: 0 }) },
previousPage: { enabled: () => canPrevious, run: previousPage },
nextPage: { enabled: () => canNext, run: nextPage },
addRow: { enabled: () => rowsEditable, run: addRow },
exportData: {
enabled: () => !!page,
run: () => {
@@ -320,7 +338,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
if (r) showExport({ x: r.left, y: r.bottom });
},
},
deleteRows: { enabled: (rows) => editable && rows.length > 0, run: deleteRows },
deleteRows: { enabled: (rows) => rowsEditable && rows.length > 0, run: deleteRows },
restoreRows: { enabled: (rows) => editable && rows.some((r) => edits.deletes.has(r)), run: restoreRows },
revertRows: {
enabled: (rows) => editable && rowsHaveEdits(edits, rows, loaded),
@@ -352,7 +370,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
icon="refresh"
title="Reload Page"
shortcut={shortcutLabel("db.reloadPage")}
onClick={reload}
onClick={reloadPage}
disabled={loading}
/>
<IconButton
@@ -374,7 +392,13 @@ export function TableEditor({ input }: { input: EditorInput }) {
{editable && (
<>
<span className={styles.toolbarSeparator} />
<IconButton icon="plus" title="Add Row" shortcut={shortcutLabel("db.addRow")} onClick={addRow} />
<IconButton
icon="plus"
title="Add Row"
shortcut={shortcutLabel("db.addRow")}
disabled={loading}
onClick={addRow}
/>
<IconButton
icon="revert"
title="Revert"
@@ -423,10 +447,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
value={filterText}
onChange={setFilterText}
onKeyDown={(e) => {
if (e.key === "Enter") {
setOffset(0);
setFilter(filterText.trim());
}
if (e.key === "Enter") showRows({ offset: 0, filter: filterText.trim() });
}}
/>
</label>
@@ -448,8 +469,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
if (e.key !== "Enter" || orderDraft === null) return;
const next = parseOrderBy(orderDraft, names);
if (!next) return;
setOffset(0);
setSort(next);
showRows({ offset: 0, sort: next });
setOrderDraft(null);
}}
/>
@@ -492,7 +512,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
firstRowNumber={offset + 1}
rowState={(r) => (r >= loaded ? "inserted" : edits.deletes.has(r) ? "deleted" : null)}
isModified={(r, c) => !!edits.updates.get(r)?.has(names[c]!)}
editable={editable}
editable={rowsEditable}
onEdit={onEdit}
onResetCell={onResetCell}
driver={source?.driver}
@@ -510,7 +530,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
title="Previous Page"
shortcut={shortcutLabel("db.previousPage")}
disabled={!canPrevious}
onClick={() => setOffset(Math.max(0, offset - limit))}
onClick={previousPage}
/>
<span className={styles.resultPagerRange}>
{loaded ? tx`${first}-${last} of ${total ?? `${last + 1}+`}` : tx`${loaded} rows`}
@@ -521,7 +541,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
title="Next Page"
shortcut={shortcutLabel("db.nextPage")}
disabled={!canNext}
onClick={() => setOffset(offset + limit)}
onClick={nextPage}
/>
</>
)}
@@ -531,10 +551,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
value={String(limit)}
options={PAGE_SIZES.map((v) => ({ value: v, label: v }))}
renderValue={singlePage ? () => tx`${loaded} rows` : undefined}
onChange={(v) => {
setOffset(0);
setLimit(Number(v));
}}
onChange={(v) => Number(v) !== limit && showRows({ offset: 0, limit: Number(v) })}
/>
</Toolbar>
}
+79 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
ChannelFrame,
DbDriver,
@@ -37,7 +37,8 @@ import {
type ResultTab,
} from "./store";
import { registerResultTabActions } from "./resultTabActions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { activeTableEditor, installTableEditorFocus, type TableCommand } from "./tableEditorFocus";
import { MessagesHost } from "@/workbench/messages";
import * as contributions from "@/workbench/contributions";
import { provideToolWindowService } from "@/workbench/contributions";
@@ -94,6 +95,7 @@ vi.mock("@tanstack/react-virtual", () => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
measure: () => {},
}),
}));
@@ -569,6 +571,81 @@ describe("SQL copied from a result", () => {
});
});
describe("unsubmitted edits of a result", () => {
const button = (name: string) => screen.getByRole("button", { name });
const command = (name: TableCommand) => activeTableEditor()!.commands![name]!.run([]);
async function edited() {
const tab = show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
Object.assign(tab, { page: 1, total: 1600 });
tab.outcome.result!.hasMore = true;
await act(async () =>
render(
<>
<ResultsView />
<MessagesHost />
</>,
),
);
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
const input = screen.getByRole("textbox", { name: "Edit name" });
fireEvent.change(input, { target: { value: "Changed" } });
fireEvent.keyDown(input, { key: "Enter" });
act(() => screen.getByRole("grid").focus());
}
let uninstall = () => {};
beforeEach(() => {
uninstall = installTableEditorFocus();
});
afterEach(() => uninstall());
it.each<[string, () => void, number, number]>([
["Rerun Query", () => fireEvent.click(button("Rerun Query")), 1, 500],
["First Page", () => fireEvent.click(button("First Page")), 0, 500],
["Previous Page", () => fireEvent.click(button("Previous Page")), 0, 500],
["Next Page", () => fireEvent.click(button("Next Page")), 2, 500],
["Last Page", () => fireEvent.click(button("Last Page")), 3, 500],
[
"a page size",
() => {
fireEvent.click(button("Page size"));
fireEvent.click(screen.getByRole("option", { name: "100" }));
},
0,
100,
],
["the Reload shortcut", () => command("reload"), 1, 500],
["the Next Page shortcut", () => command("nextPage"), 2, 500],
["the Last Page shortcut", () => command("lastPage"), 3, 500],
])("%s asks before dropping them", async (_label, run, page, pageSize) => {
await edited();
run();
await act(async () => {});
expect(screen.getByRole("dialog", { name: "Ignore Unsubmitted Changes" })).toBeVisible();
await act(async () => fireEvent.click(button("Cancel")));
expect(backend.execute).not.toHaveBeenCalled();
expect(screen.getByRole("gridcell", { name: "Changed" })).toBeVisible();
expect(useDatabase.getState().results[0]).toMatchObject({ page: 1, pageSize: 500 });
act(() => screen.getByRole("grid").focus());
run();
await act(async () => {});
await act(async () => fireEvent.click(button("Continue")));
expect(backend.execute).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("gridcell", { name: "Changed" })).toBeNull();
expect(useDatabase.getState().results[0]).toMatchObject({ page, pageSize });
});
it("does not ask once they are reverted", async () => {
await edited();
await act(async () => fireEvent.click(button("Revert")));
await act(async () => fireEvent.click(button("Next Page")));
expect(screen.queryByRole("dialog")).toBeNull();
expect(backend.execute).toHaveBeenCalledTimes(1);
});
});
describe("read-only results with a reason", () => {
it.each([
["SELECT * FROM a JOIN b ON a.id = b.id", [{ name: "id" }], [["1"]], "Read-only: the query joins several tables."],
+150 -2
Переглянути файл
@@ -1,12 +1,13 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { DbDriver, DbTablePage } from "@/platform/ipc";
import { MessagesHost } from "@/workbench/messages";
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
import { activeCellGrid, installCellActions } from "./cellActions";
import { getContext } from "@/platform/context";
import { ContextMenuHost } from "@/ui";
import { TableEditor, _resetTableViewStates } from "./TableEditor";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { activeTableEditor, installTableEditorFocus, type TableCommand } from "./tableEditorFocus";
import { tableInput } from "./tableInput";
const backend = vi.hoisted(() => ({
@@ -43,6 +44,7 @@ vi.mock("@tanstack/react-virtual", () => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
measure: () => {},
}),
}));
@@ -307,6 +309,152 @@ it("omits a reset inserted cell from Submit instead of writing SQL NULL", async
}
});
describe("unsubmitted edits", () => {
const request = () => backend.page.mock.calls.at(-1)!.slice(4, 8);
const requests = () => backend.page.mock.calls.length;
const button = (name: string) => screen.getByRole("button", { name });
const enter = (field: string, text: string) => {
const input = screen.getByRole("textbox", { name: field });
fireEvent.change(input, { target: { value: text } });
// Closes the completion, which takes Enter first.
if (screen.queryByRole("listbox", { name: "SQL completion" })) fireEvent.keyDown(input, { key: "Escape" });
fireEvent.keyDown(input, { key: "Enter" });
};
const command = (name: TableCommand) => activeTableEditor()!.commands![name]!.run([]);
/** A table on its second page, sorted and filtered, with Ann changed to Bob. */
async function edited() {
backend.driver = "postgres";
const more = { ...page, result: { ...page.result, hasMore: true } };
backend.page.mockReset().mockResolvedValue({ status: "ok", data: more });
await act(async () => {
render(
<>
<TableEditor input={tableInput("source", "public", "users")} />
<MessagesHost />
</>,
);
});
fireEvent.click(button("Next Page"));
fireEvent.click(screen.getByRole("columnheader", { name: /name/ }));
await act(async () => {});
expect(request()).toEqual([null, [{ column: "name", descending: false }], 500, 500]);
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
const input = screen.getByRole("textbox", { name: "Edit name" });
fireEvent.change(input, { target: { value: "Bob" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(screen.getByRole("gridcell", { name: "Bob" })).toBeVisible();
act(() => screen.getByRole("grid").focus());
}
const sorted = [{ column: "name", descending: false }];
const ACTIONS: Array<[string, () => void, unknown[]]> = [
["Next Page", () => fireEvent.click(button("Next Page")), [null, sorted, 1000, 500]],
["Previous Page", () => fireEvent.click(button("Previous Page")), [null, sorted, 0, 500]],
["Reload Page", () => fireEvent.click(button("Reload Page")), [null, sorted, 500, 500]],
[
"a header sort",
() => fireEvent.click(screen.getByRole("columnheader", { name: /name/ })),
[null, [{ column: "name", descending: true }], 500, 500],
],
["a WHERE filter", () => enter("WHERE filter", "id > 1"), ["id > 1", sorted, 0, 500]],
["an ORDER BY", () => enter("ORDER BY", "id"), [null, [{ column: "id", descending: false }], 0, 500]],
[
"a page size",
() => {
fireEvent.click(button("Page size"));
fireEvent.click(screen.getByRole("option", { name: "100" }));
},
[null, sorted, 0, 100],
],
["the Reload shortcut", () => command("reload"), [null, sorted, 500, 500]],
["the First Page shortcut", () => command("firstPage"), [null, sorted, 0, 500]],
["the Previous Page shortcut", () => command("previousPage"), [null, sorted, 0, 500]],
["the Next Page shortcut", () => command("nextPage"), [null, sorted, 1000, 500]],
];
let uninstall = () => {};
beforeEach(() => {
uninstall = installTableEditorFocus();
});
afterEach(() => uninstall());
it.each(ACTIONS)("%s asks before dropping them", async (_label, run, expected) => {
await edited();
const before = requests();
run();
await act(async () => {});
const dialog = screen.getByRole("dialog", { name: "Ignore Unsubmitted Changes" });
expect(dialog).toHaveTextContent("Changes are not submitted. Data will be lost. Continue?");
await act(async () => fireEvent.click(button("Cancel")));
expect(requests()).toBe(before);
expect(request()).toEqual([null, sorted, 500, 500]);
expect(screen.getByRole("gridcell", { name: "Bob" })).toBeVisible();
expect(button("Submit")).toBeEnabled();
expect(button("Page size")).toHaveTextContent("500");
act(() => screen.getByRole("grid").focus());
run();
await act(async () => {});
await act(async () => fireEvent.click(button("Continue")));
expect(requests()).toBe(before + 1);
expect(request()).toEqual(expected);
expect(screen.getByRole("gridcell", { name: "Ann" })).toBeVisible();
expect(button("Submit")).toBeDisabled();
});
it("does not ask without any, nor when no rows are read again", async () => {
await edited();
const before = requests();
const dialog = () => screen.queryByRole("dialog");
await act(async () => {
fireEvent.click(button("Previous Page"));
});
await act(async () => fireEvent.click(button("Continue")));
expect(requests()).toBe(before + 1);
fireEvent.doubleClick(await screen.findByRole("gridcell", { name: "Ann" }));
const input = screen.getByRole("textbox", { name: "Edit name" });
fireEvent.change(input, { target: { value: "Bob" } });
fireEvent.keyDown(input, { key: "Enter" });
await act(async () => enter("WHERE filter", " "));
await act(async () => enter("ORDER BY", "name"));
expect(dialog()).toBeNull();
expect(screen.getByRole("gridcell", { name: "Bob" })).toBeVisible();
await act(async () => fireEvent.click(button("Revert")));
await act(async () => fireEvent.click(button("Reload Page")));
expect(dialog()).toBeNull();
expect(requests()).toBe(before + 2);
});
it("takes none while other rows are loading", async () => {
await edited();
let finish!: (result: unknown) => void;
backend.page.mockReturnValueOnce(new Promise((resolve) => (finish = resolve)));
fireEvent.click(button("Revert"));
fireEvent.click(button("Next Page"));
await act(async () => {});
expect(button("Add Row")).toBeDisabled();
fireEvent.doubleClick(screen.getByRole("gridcell", { name: "Ann" }));
expect(screen.queryByRole("textbox", { name: "Edit name" })).toBeNull();
await act(async () => finish({ status: "ok", data: page }));
expect(button("Add Row")).toBeEnabled();
fireEvent.doubleClick(screen.getByRole("gridcell", { name: "Ann" }));
expect(screen.getByRole("textbox", { name: "Edit name" })).toBeVisible();
});
it("submits them without asking", async () => {
await edited();
const before = requests();
backend.applyEdits.mockResolvedValue({ status: "ok", data: 1 });
await act(async () => fireEvent.click(button("Submit")));
expect(backend.applyEdits).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("dialog")).toBeNull();
expect(requests()).toBe(before + 1);
});
});
describe("table editor view state", () => {
it("restores the grid's horizontal scroll position when its tab mounts again (#4775)", async () => {
const input = tableInput("source", "default", "users");
+20
Переглянути файл
@@ -0,0 +1,20 @@
/** Asking before grid rows with unsubmitted edits are replaced by others. */
import { tx } from "@/platform/i18n";
import { confirm } from "@/workbench/messages";
import { hasEdits, type PendingEdits } from "./model";
/** Runs `replaceRows`, which drops `edits`; with any pending, only once the user agreed. */
export function discardingEdits(edits: PendingEdits | undefined, replaceRows: () => void): void {
if (!edits || !hasEdits(edits)) {
replaceRows();
return;
}
void confirm({
title: "Ignore Unsubmitted Changes",
message: tx("Changes are not submitted. Data will be lost. Continue?"),
ok: "Continue",
icon: "warning",
}).then((ok) => {
if (ok) replaceRows();
});
}
+2
Переглянути файл
@@ -507,6 +507,8 @@
"I have configured built-in connection security.": "I have configured built-in connection security.",
"Passed to the JDBC driver as connection properties. Configure TLS and other driver-specific settings here or in the JDBC URL. Use the User and Password fields for credentials.": "Passed to the JDBC driver as connection properties. Configure TLS and other driver-specific settings here or in the JDBC URL. Use the User and Password fields for credentials.",
"Use the query console to change JDBC data.": "Use the query console to change JDBC data.",
"Ignore Unsubmitted Changes": "Ignore Unsubmitted Changes",
"Changes are not submitted. Data will be lost. Continue?": "Changes are not submitted. Data will be lost. Continue?",
"Presentation Assistant": "Presentation Assistant",
"Small": "Small",
"Large": "Large",
+2
Переглянути файл
@@ -457,6 +457,8 @@
"I have configured built-in connection security.": "我已配置内置驱动的连接安全设置。",
"Passed to the JDBC driver as connection properties. Configure TLS and other driver-specific settings here or in the JDBC URL. Use the User and Password fields for credentials.": "作为连接属性传递给 JDBC 驱动。请在此处或 JDBC URL 中配置 TLS 和其他驱动专用设置。凭据请使用“用户”和“密码”字段。",
"Use the query console to change JDBC data.": "请使用查询控制台修改 JDBC 数据。",
"Ignore Unsubmitted Changes": "忽略未提交的更改",
"Changes are not submitted. Data will be lost. Continue?": "更改尚未提交,数据将会丢失。是否继续?",
"Presentation Assistant": "演示助手",
"Small": "小",
"Large": "大",