Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix: some sql editor issues (#21460)

ecmadao0bfe2ea4630c
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx
index 180726a6ae..1857fc7fb0 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
maybeUpdateSavedQuery: vi.fn().mockResolvedValue(undefined),
canCreateSavedQueryInProject: vi.fn(() => true),
addTab: vi.fn(() => ({ id: "local-tab" })),
+ updateTab: vi.fn(),
tabsById: new Map<string, { id: string; mode: string }>(),
currentTabId: "",
}));
@@ -73,7 +74,7 @@ vi.mock("@/modules/sql-editor/store/tab", () => ({
tabsById: mocks.tabsById,
currentTabId: mocks.currentTabId,
addTab: mocks.addTab,
- updateTab: vi.fn(),
+ updateTab: mocks.updateTab,
}),
}));
@@ -170,6 +171,7 @@ beforeEach(async () => {
mocks.canCreateSavedQueryInProject.mockReturnValue(true);
mocks.addTab.mockReturnValue({ id: "local-tab" });
mocks.createSavedQuery.mockResolvedValue(undefined);
+ mocks.updateTab.mockReset();
mocks.tabsById.clear();
mocks.currentTabId = "";
({ useConnectionMenu } = await import("./actions"));
@@ -194,7 +196,7 @@ describe("setConnection", () => {
expect(mocks.addTab).toHaveBeenCalled();
});
- test("creates a saved query when the caller may", async () => {
+ test("opens an unsaved local tab when the caller may", async () => {
mocks.canCreateSavedQueryInProject.mockReturnValue(true);
const { setConnection } = await import("./actions");
@@ -206,8 +208,8 @@ describe("setConnection", () => {
await Promise.resolve();
});
- expect(mocks.createSavedQuery).toHaveBeenCalled();
- expect(mocks.addTab).not.toHaveBeenCalled();
+ expect(mocks.createSavedQuery).not.toHaveBeenCalled();
+ expect(mocks.addTab).toHaveBeenCalled();
});
test("does not replace a data explorer tab", async () => {
@@ -228,7 +230,37 @@ describe("setConnection", () => {
});
expect(mocks.maybeUpdateSavedQuery).not.toHaveBeenCalled();
- expect(mocks.createSavedQuery).toHaveBeenCalled();
+ expect(mocks.createSavedQuery).not.toHaveBeenCalled();
+ expect(mocks.addTab).toHaveBeenCalled();
+ });
+
+ test("keeps a local draft dirty when changing its connection", async () => {
+ mocks.currentTabId = "local-tab";
+ mocks.tabsById.set("local-tab", {
+ id: "local-tab",
+ mode: "SAVED_QUERY",
+ savedQuery: "",
+ status: "DIRTY",
+ statement: "SELECT 1",
+ title: "",
+ } as never);
+ const { setConnection } = await import("./actions");
+
+ await act(async () => {
+ setConnection({
+ database: { name: "instances/prod/databases/db1" } as never,
+ newTab: false,
+ });
+ await Promise.resolve();
+ });
+
+ expect(mocks.maybeUpdateSavedQuery).not.toHaveBeenCalled();
+ expect(mocks.updateTab).toHaveBeenCalledWith("local-tab", {
+ connection: {
+ instance: "instances/prod",
+ database: "instances/prod/databases/db1",
+ },
+ });
});
});
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx
index aa2878cc2a..780df7561a 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx
@@ -10,10 +10,7 @@ import { router } from "@/app/router";
import { useSQLEditorAllowAdmin } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
import { useSQLEditorStore } from "@/modules/sql-editor/store";
-import {
- getSQLEditorEditorState,
- useSQLEditorEditorState,
-} from "@/modules/sql-editor/store/editor";
+import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import { getSQLEditorTabsState } from "@/modules/sql-editor/store/tab";
import type {
BatchQueryContext,
@@ -28,7 +25,6 @@ import {
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
autoDatabaseRoute,
- canCreateSavedQueryInProject,
extractDatabaseResourceName,
getInstanceResource,
instanceV1HasAlterSchema,
@@ -53,8 +49,8 @@ const DEFAULT_TAB_MODE: SQLEditorTabMode = "SAVED_QUERY";
/**
* Replaces frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx's `setConnection`.
- * Connects the current tab or creates a new saved query, then sets the tab
- * mode + batch-query context and flips the aside panel to `SCHEMA`.
+ * Connects the current tab or opens a local draft, then sets the tab mode +
+ * batch-query context and flips the aside panel to `SCHEMA`.
*/
export function setConnection(options: {
database?: Database;
@@ -74,8 +70,7 @@ export function setConnection(options: {
const currentTab = tabsState.tabsById.get(tabsState.currentTabId);
const nextMode = mode === "DATA_EXPLORER" ? DEFAULT_TAB_MODE : mode;
const shouldCreateNewTab = newTab || currentTab?.mode === "DATA_EXPLORER";
- const { maybeUpdateSavedQuery, createSavedQuery } =
- useSQLEditorStore.getState();
+ const { maybeUpdateSavedQuery } = useSQLEditorStore.getState();
const batchQueryContext: BatchQueryContext = Object.assign(
{ databases: [] } as BatchQueryContext,
@@ -85,6 +80,11 @@ export function setConnection(options: {
const createOrUpdate = () => {
if (!shouldCreateNewTab && currentTab) {
+ if (!currentTab.savedQuery) {
+ return Promise.resolve(
+ tabsState.updateTab(currentTab.id, { connection })
+ );
+ }
return maybeUpdateSavedQuery({
tabId: currentTab.id,
savedQuery: currentTab.savedQuery,
@@ -93,14 +93,9 @@ export function setConnection(options: {
statement: currentTab.statement,
});
}
- if (!canCreateSavedQueryInProject(getSQLEditorEditorState().project)) {
- // Same fallback as the tab bar's "+": open the tab locally rather than
- // failing the request, so the connection the user picked still opens.
- return Promise.resolve(getSQLEditorTabsState().addTab({ connection }));
- }
- return createSavedQuery({
- database: connection.database,
- });
+ // A new connection starts as a local draft. Auto-save creates the saved
+ // query only after the user enters SQL.
+ return Promise.resolve(getSQLEditorTabsState().addTab({ connection }));
};
void createOrUpdate().then((tab) => {
diff --git a/frontend/src/modules/sql-editor/components/MaskingReasonPopover.test.tsx b/frontend/src/modules/sql-editor/components/MaskingReasonPopover.test.tsx
index 6dd5795cf2..c17394c21a 100644
--- a/frontend/src/modules/sql-editor/components/MaskingReasonPopover.test.tsx
+++ b/frontend/src/modules/sql-editor/components/MaskingReasonPopover.test.tsx
@@ -237,6 +237,20 @@ describe("MaskingReasonPopover", () => {
unmount();
});
+ test("wraps a long masking context within the popover", () => {
+ const context = "Column-level semantic type: sample-" + "x".repeat(500);
+ const { container, render, unmount } = renderIntoContainer(
+ <MaskingReasonPopover reason={makeReason({ context })} />
+ );
+ render();
+
+ const contextValue = Array.from(container.querySelectorAll("span")).find(
+ (element) => element.textContent === context
+ );
+ expect(contextValue?.className).toContain("wrap-anywhere");
+ unmount();
+ });
+
test("does not show the request-unmask button when JIT not available", () => {
setupDefaultMocks(false);
const { container, render, unmount } = renderIntoContainer(
diff --git a/frontend/src/modules/sql-editor/components/MaskingReasonPopover.tsx b/frontend/src/modules/sql-editor/components/MaskingReasonPopover.tsx
index 362fb20ad3..a0a637d47e 100644
--- a/frontend/src/modules/sql-editor/components/MaskingReasonPopover.tsx
+++ b/frontend/src/modules/sql-editor/components/MaskingReasonPopover.tsx
@@ -135,7 +135,7 @@ export function MaskingReasonPopover({
<span className="text-control-placeholder">
{t("masking.reason.context")}:
</span>
- <span className="ml-1">{reason.context}</span>
+ <span className="ml-1 wrap-anywhere">{reason.context}</span>
</div>
)}
diff --git a/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.test.tsx b/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.test.tsx
new file mode 100644
index 0000000000..abc6422754
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.test.tsx
@@ -0,0 +1,37 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { PanelSearchBox } from "./PanelSearchBox";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("PanelSearchBox", () => {
+ let container: HTMLDivElement;
+ let root: ReturnType<typeof createRoot>;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+
+ test("keeps the placeholder clear of the search icon", () => {
+ act(() => {
+ root.render(<PanelSearchBox value="" onChange={() => {}} />);
+ });
+
+ const input = container.querySelector("input") as HTMLInputElement;
+ expect(input.style.paddingInlineStart).toBe("1.75rem");
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.tsx b/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.tsx
index 9765c05950..edafd54024 100644
--- a/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.tsx
+++ b/frontend/src/modules/sql-editor/components/Panels/common/PanelSearchBox.tsx
@@ -30,7 +30,7 @@ export function PanelSearchBox({
<Search className="absolute left-2 top-1/2 -translate-y-1/2 size-3.5 text-control-placeholder pointer-events-none" />
<Input
size="sm"
- className="pl-7 pr-7"
+ style={{ paddingInlineStart: "1.75rem", paddingInlineEnd: "1.75rem" }}
value={value}
placeholder={placeholder ?? t("common.search")}
onChange={handleChange}
diff --git a/frontend/src/modules/sql-editor/components/TabList.test.tsx b/frontend/src/modules/sql-editor/components/TabList.test.tsx
index a407d2b949..1059e662fa 100644
--- a/frontend/src/modules/sql-editor/components/TabList.test.tsx
+++ b/frontend/src/modules/sql-editor/components/TabList.test.tsx
@@ -298,7 +298,7 @@ describe("TabList", () => {
unmount();
});
- test("+ button calls savedQueryStore.createSavedQuery", () => {
+ test("+ button opens an unsaved local tab", () => {
setup([makeTab("a")]);
const { container, render, unmount } = renderIntoContainer(<TabList />);
render();
@@ -309,8 +309,8 @@ describe("TabList", () => {
act(() => {
addButton?.click();
});
- expect(mocks.createSavedQuery).toHaveBeenCalled();
- expect(mocks.addTab).not.toHaveBeenCalled();
+ expect(mocks.createSavedQuery).not.toHaveBeenCalled();
+ expect(mocks.addTab).toHaveBeenCalled();
unmount();
});
diff --git a/frontend/src/modules/sql-editor/components/TabList.tsx b/frontend/src/modules/sql-editor/components/TabList.tsx
index 22fdc4dace..bec949f7fd 100644
--- a/frontend/src/modules/sql-editor/components/TabList.tsx
+++ b/frontend/src/modules/sql-editor/components/TabList.tsx
@@ -30,15 +30,12 @@ import {
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { tabListEvents } from "@/modules/sql-editor/model/TabList/events";
-import { useSQLEditorStore } from "@/modules/sql-editor/store";
-import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import {
getSQLEditorTabsState,
useOpenTabList,
useSQLEditorTabState,
} from "@/modules/sql-editor/store/tab";
import type { SQLEditorTab } from "@/types/sqlEditor/tab";
-import { canCreateSavedQueryInProject } from "@/utils";
import { TabContextMenu, type TabContextMenuHandle } from "./TabContextMenu";
import { TabItem } from "./TabItem/TabItem";
@@ -61,8 +58,6 @@ type PendingClose = {
*/
export function TabList() {
const { t } = useTranslation();
- const createSavedQuery = useSQLEditorStore((s) => s.createSavedQuery);
- const project = useSQLEditorEditorState((s) => s.project);
// Zustand's selector subscribes to in-place tab mutations because
// `updateTab` reassigns / triggers an immer produce on `tabsById`,
@@ -158,18 +153,12 @@ export function TabList() {
[confirmCloseUnsaved, recalculateScrollState]
);
- const handleAddTab = async () => {
+ const handleAddTab = () => {
if (loading) return;
setLoading(true);
try {
- // A new tab is normally backed by a saved query straight away. Without
- // the create permission that request would fail, so open a local draft
- // instead -- the editor keeps working, nothing is persisted.
- if (!canCreateSavedQueryInProject(project)) {
- getSQLEditorTabsState().addTab();
- } else {
- await createSavedQuery({});
- }
+ // A blank tab stays local until auto-save sees SQL content.
+ getSQLEditorTabsState().addTab();
requestAnimationFrame(() => {
const el = scrollRef.current;
if (el) el.scrollTo(el.scrollWidth, 0);
diff --git a/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.test.tsx b/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.test.tsx
new file mode 100644
index 0000000000..38fcda2ac6
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.test.tsx
@@ -0,0 +1,302 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";
+
+const mocks = vi.hoisted(() => ({
+ abortAutoSave: vi.fn(),
+ setAutoSaveController: vi.fn(),
+ maybeUpdateSavedQuery: vi.fn(),
+ createSavedQuery: vi.fn(),
+ updateTab: vi.fn(),
+ getSavedQueryByName: vi.fn(),
+ notify: vi.fn(),
+ canCreateSavedQueryInProject: vi.fn(() => true),
+ tab: {
+ id: "tab-1",
+ savedQuery: "",
+ title: "",
+ status: "DIRTY",
+ statement: "SELECT 1",
+ connection: {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ },
+ },
+ tabsById: new Map(),
+ currentTabId: "tab-1",
+}));
+
+vi.mock("@/modules/sql-editor/store", () => ({
+ useSQLEditorStore: Object.assign(
+ (
+ selector: (state: {
+ abortAutoSave: typeof mocks.abortAutoSave;
+ setAutoSaveController: typeof mocks.setAutoSaveController;
+ maybeUpdateSavedQuery: typeof mocks.maybeUpdateSavedQuery;
+ createSavedQuery: typeof mocks.createSavedQuery;
+ }) => unknown
+ ) =>
+ selector({
+ abortAutoSave: mocks.abortAutoSave,
+ setAutoSaveController: mocks.setAutoSaveController,
+ maybeUpdateSavedQuery: mocks.maybeUpdateSavedQuery,
+ createSavedQuery: mocks.createSavedQuery,
+ }),
+ { getState: () => ({ autoSaveController: null }) }
+ ),
+}));
+
+vi.mock("@/modules/sql-editor/store/editor", () => ({
+ getSQLEditorEditorState: () => ({ project: "projects/proj1" }),
+}));
+
+vi.mock("@/modules/sql-editor/store/tab", () => ({
+ getSQLEditorTabsState: () => ({
+ currentTabId: mocks.currentTabId,
+ tabsById: mocks.tabsById,
+ updateTab: mocks.updateTab,
+ }),
+ useSQLEditorTabState: (
+ selector: (state: {
+ currentTabId: string;
+ tabsById: typeof mocks.tabsById;
+ updateTab: typeof mocks.updateTab;
+ }) => unknown
+ ) =>
+ selector({
+ currentTabId: mocks.currentTabId,
+ tabsById: mocks.tabsById,
+ updateTab: mocks.updateTab,
+ }),
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({
+ getSavedQueryByName: mocks.getSavedQueryByName,
+ notify: mocks.notify,
+ }),
+ },
+}));
+
+vi.mock("@/utils", () => ({
+ canCreateSavedQueryInProject: mocks.canCreateSavedQueryInProject,
+ isSavedQueryWritableV1: vi.fn(() => true),
+}));
+
+describe("useSQLEditorAutoSave", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ mocks.tab.savedQuery = "";
+ mocks.tab.title = "";
+ mocks.tab.status = "DIRTY";
+ mocks.tab.statement = "SELECT 1";
+ mocks.tab.connection = {
+ instance: "instances/inst1",
+ database: "instances/inst1/databases/db1",
+ };
+ mocks.tabsById.clear();
+ mocks.tabsById.set(mocks.tab.id, mocks.tab);
+ mocks.currentTabId = mocks.tab.id;
+ mocks.createSavedQuery.mockResolvedValue(undefined);
+ mocks.updateTab.mockReset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("creates a saved query after an unsaved tab receives SQL", async () => {
+ renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.createSavedQuery).toHaveBeenCalledWith({
+ tabId: "tab-1",
+ title: "",
+ database: "instances/inst1/databases/db1",
+ statement: "SELECT 1",
+ signal: expect.any(AbortSignal),
+ });
+ });
+
+ test("keeps a local draft title when it first auto-saves", async () => {
+ mocks.tab.title = "Query history at 2026-09-16 16:30";
+ renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.createSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Query history at 2026-09-16 16:30" })
+ );
+ });
+
+ test("does not save whitespace-only drafts", async () => {
+ mocks.tab.statement = " \n\t ";
+ renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.createSavedQuery).not.toHaveBeenCalled();
+ });
+
+ test("saves a whitespace-only statement for an existing saved query", async () => {
+ mocks.tab.savedQuery = "projects/proj1/savedQueries/query1";
+ mocks.tab.statement = " \n\t ";
+ mocks.getSavedQueryByName.mockReturnValue({
+ name: mocks.tab.savedQuery,
+ });
+ mocks.maybeUpdateSavedQuery.mockResolvedValue(undefined);
+
+ renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.maybeUpdateSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tabId: "tab-1",
+ savedQuery: "projects/proj1/savedQueries/query1",
+ statement: " \n\t ",
+ })
+ );
+ });
+
+ test("does not start a second create while the first one is saving", async () => {
+ mocks.tab.status = "SAVING";
+ renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.createSavedQuery).not.toHaveBeenCalled();
+ });
+
+ test("saves the edited tab after switching away from an identical clean tab", async () => {
+ const cleanTab = {
+ ...mocks.tab,
+ id: "tab-2",
+ status: "CLEAN",
+ connection: { ...mocks.tab.connection },
+ };
+ mocks.tabsById.set(cleanTab.id, cleanTab);
+ const { rerender } = renderHook(() => useSQLEditorAutoSave());
+
+ mocks.currentTabId = cleanTab.id;
+ rerender();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ expect(mocks.createSavedQuery).not.toHaveBeenCalled();
+
+ mocks.currentTabId = mocks.tab.id;
+ rerender();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.createSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({ tabId: "tab-1" })
+ );
+ });
+
+ test("saves a newer database selection after the first create completes", async () => {
+ let resolveCreate: () => void;
+ mocks.createSavedQuery.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveCreate = resolve;
+ })
+ );
+ mocks.updateTab.mockImplementation((_id, payload) => {
+ Object.assign(mocks.tab, payload);
+ });
+ const { rerender } = renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ mocks.tab.connection = {
+ instance: "instances/inst2",
+ database: "instances/inst2/databases/db2",
+ };
+ rerender();
+ mocks.tab.savedQuery = "projects/proj1/savedQueries/query1";
+ mocks.tab.status = "DIRTY";
+ mocks.getSavedQueryByName.mockReturnValue({ name: mocks.tab.savedQuery });
+
+ await act(async () => {
+ resolveCreate();
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.maybeUpdateSavedQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ database: "instances/inst2/databases/db2",
+ })
+ );
+ });
+
+ test("does not retry a failed save until the tab changes again", async () => {
+ let rejectCreate: (reason?: unknown) => void;
+ mocks.createSavedQuery.mockImplementation(
+ () =>
+ new Promise<void>((_resolve, reject) => {
+ rejectCreate = reject;
+ })
+ );
+ mocks.updateTab.mockImplementation((_id, payload) => {
+ Object.assign(mocks.tab, payload);
+ });
+ const { rerender } = renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+ rerender();
+
+ await act(async () => {
+ rejectCreate(new Error("network failed"));
+ await Promise.resolve();
+ });
+ rerender();
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.createSavedQuery).toHaveBeenCalledTimes(1);
+ });
+
+ test("returns an aborted tab to dirty", async () => {
+ mocks.createSavedQuery.mockRejectedValue(
+ new DOMException("Aborted", "AbortError")
+ );
+ mocks.updateTab.mockImplementation((_id, payload) => {
+ Object.assign(mocks.tab, payload);
+ });
+ renderHook(() => useSQLEditorAutoSave());
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(mocks.updateTab).toHaveBeenLastCalledWith("tab-1", {
+ status: "DIRTY",
+ });
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.ts b/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.ts
index dfc426c90e..d285ff9295 100644
--- a/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.ts
+++ b/frontend/src/modules/sql-editor/components/useSQLEditorAutoSave.ts
@@ -1,20 +1,21 @@
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { useSQLEditorStore } from "@/modules/sql-editor/store";
+import { getSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/modules/sql-editor/store/tab";
import { useAppStore } from "@/stores/app";
-import { isSavedQueryWritableV1 } from "@/utils";
+import { canCreateSavedQueryInProject, isSavedQueryWritableV1 } from "@/utils";
const AUTO_SAVE_DEBOUNCE_MS = 2000;
/**
- * Watches the active tab's `statement` and after a 2s debounce calls
- * `maybeUpdateSavedQuery` if the tab is dirty + writable. Aborts any
- * in-flight auto-save when a newer one starts, reverts the tab to DIRTY
- * on error (unless aborted), and re-flags DIRTY when the statement keeps
- * changing during the save.
+ * Watches the active tab's `statement` and after a 2s debounce persists a
+ * dirty, writable tab. Local drafts become saved queries after their first
+ * non-whitespace SQL; saved queries are updated in place. A newer edit waits
+ * for any active save to finish, then saves the latest statement. Errors and
+ * aborted saves return the tab to DIRTY without retrying unchanged content.
*
* Mounted once at the SQL Editor layout level; safe to call from any
* component but should only be active while the SQL Editor route is.
@@ -27,10 +28,16 @@ export function useSQLEditorAutoSave() {
const maybeUpdateSavedQuery = useSQLEditorStore(
(s) => s.maybeUpdateSavedQuery
);
+ const createSavedQuery = useSQLEditorStore((s) => s.createSavedQuery);
const statement = useSQLEditorTabState(
(s) => s.tabsById.get(s.currentTabId)?.statement
);
+ const database = useSQLEditorTabState(
+ (s) => s.tabsById.get(s.currentTabId)?.connection.database
+ );
+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
+ const [saveVersion, setSaveVersion] = useState(0);
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
@@ -46,24 +53,37 @@ export function useSQLEditorAutoSave() {
debounceTimerRef.current = null;
}
};
- // We re-arm the debounce on every statement change. The save itself
- // reads tab.statement from the tab store at fire time, so capturing
- // only the change-trigger here is sufficient.
- }, [statement]);
+ // A completed save may reveal newer SQL or a newer database selection.
+ // The active tab is included because the save reads live tab state at fire.
+ }, [statement, database, currentTabId, saveVersion]);
const runAutoSave = async () => {
const tabsState = getSQLEditorTabsState();
const tab = tabsState.tabsById.get(tabsState.currentTabId);
- if (!tab?.savedQuery || tab.status === "CLEAN") return;
+ if (
+ !tab ||
+ tab.status === "CLEAN" ||
+ tab.status === "SAVING" ||
+ (!tab.savedQuery && !tab.statement.trim())
+ ) {
+ return;
+ }
- const savedQuery = useAppStore
- .getState()
- .getSavedQueryByName(tab.savedQuery);
- if (!savedQuery || !isSavedQueryWritableV1(savedQuery)) return;
+ if (tab.savedQuery) {
+ const savedQuery = useAppStore
+ .getState()
+ .getSavedQueryByName(tab.savedQuery);
+ if (!savedQuery || !isSavedQueryWritableV1(savedQuery)) return;
+ } else if (
+ !canCreateSavedQueryInProject(getSQLEditorEditorState().project)
+ ) {
+ return;
+ }
abortAutoSave();
const statementToSave = tab.statement;
+ const databaseToSave = tab.connection.database;
const tabId = tab.id;
const controller = new AbortController();
@@ -72,16 +92,34 @@ export function useSQLEditorAutoSave() {
let wasAborted = false;
try {
- await maybeUpdateSavedQuery({
- tabId,
- savedQuery: tab.savedQuery,
- database: tab.connection.database,
- statement: statementToSave,
- signal: controller.signal,
- });
+ if (tab.savedQuery) {
+ await maybeUpdateSavedQuery({
+ tabId,
+ savedQuery: tab.savedQuery,
+ database: databaseToSave,
+ statement: statementToSave,
+ signal: controller.signal,
+ });
+ } else {
+ await createSavedQuery({
+ tabId,
+ title: tab.title,
+ database: databaseToSave,
+ statement: statementToSave,
+ signal: controller.signal,
+ });
+ }
} catch (error) {
- if (error instanceof Error && error.name === "AbortError") {
+ if (
+ typeof error === "object" &&
+ error !== null &&
+ "name" in error &&
+ error.name === "AbortError"
+ ) {
wasAborted = true;
+ if (getSQLEditorTabsState().tabsById.get(tabId)?.status === "SAVING") {
+ getSQLEditorTabsState().updateTab(tabId, { status: "DIRTY" });
+ }
return;
}
if (getSQLEditorTabsState().tabsById.get(tabId)?.status === "SAVING") {
@@ -94,12 +132,17 @@ export function useSQLEditorAutoSave() {
description: error instanceof Error ? error.message : "Unknown error",
});
} finally {
- setAutoSaveController(null);
+ if (useSQLEditorStore.getState().autoSaveController === controller) {
+ setAutoSaveController(null);
+ }
if (!wasAborted) {
- const currentStatement =
- getSQLEditorTabsState().tabsById.get(tabId)?.statement;
- if (currentStatement !== statementToSave) {
+ const currentTab = getSQLEditorTabsState().tabsById.get(tabId);
+ if (
+ currentTab?.statement !== statementToSave ||
+ currentTab?.connection.database !== databaseToSave
+ ) {
getSQLEditorTabsState().updateTab(tabId, { status: "DIRTY" });
+ setSaveVersion((version) => version + 1);
}
}
}
diff --git a/frontend/src/modules/sql-editor/store/savedQuery.test.ts b/frontend/src/modules/sql-editor/store/savedQuery.test.ts
index 6f133e5e33..8452c844a3 100644
--- a/frontend/src/modules/sql-editor/store/savedQuery.test.ts
+++ b/frontend/src/modules/sql-editor/store/savedQuery.test.ts
@@ -185,6 +185,88 @@ describe("saved query save slice — maybeUpdateSavedQuery", () => {
});
});
+describe("saved query save slice — createSavedQuery", () => {
+ test("keeps a newer database selection after a first save response", async () => {
+ const store = makeStore();
+ const tab = getSQLEditorTabsState().addTab({
+ connection: {
+ instance: "instances/inst2",
+ database: "instances/inst2/databases/db2",
+ },
+ statement: "SELECT 1",
+ status: "SAVING",
+ });
+ mocks.savedQueryStore.createSavedQuery.mockResolvedValue({
+ name: "projects/default/savedQueries/query1",
+ });
+
+ await store.getState().createSavedQuery({
+ tabId: tab.id,
+ database: "instances/inst1/databases/db1",
+ statement: tab.statement,
+ });
+
+ expect(getSQLEditorTabsState().tabsById.get(tab.id)).toMatchObject({
+ connection: {
+ instance: "instances/inst2",
+ database: "instances/inst2/databases/db2",
+ },
+ status: "DIRTY",
+ });
+ });
+
+ test("preserves the selected Cosmos DB container when first saving a local draft", async () => {
+ const store = makeStore();
+ const tab = getSQLEditorTabsState().addTab({
+ connection: {
+ instance: "instances/cosmos",
+ database: "instances/cosmos/databases/grs",
+ table: "SUPPORDERS_VIS.items",
+ },
+ statement: "select * from SUPPORDERS_VIS.items",
+ status: "SAVING",
+ });
+ mocks.savedQueryStore.createSavedQuery.mockResolvedValue({
+ name: "projects/default/savedQueries/cosmos-sheet",
+ });
+
+ await store.getState().createSavedQuery({
+ tabId: tab.id,
+ database: tab.connection.database,
+ statement: tab.statement,
+ });
+
+ expect(getSQLEditorTabsState().tabsById.get(tab.id)?.connection).toEqual({
+ instance: "instances/cosmos",
+ database: "instances/cosmos/databases/grs",
+ table: "SUPPORDERS_VIS.items",
+ });
+ });
+
+ test("keeps newer local SQL when an earlier create response arrives", async () => {
+ const store = makeStore();
+ const tab = getSQLEditorTabsState().addTab({
+ statement: "SELECT newer",
+ status: "SAVING",
+ });
+ mocks.savedQueryStore.createSavedQuery.mockResolvedValue({
+ name: "projects/default/savedQueries/query1",
+ });
+
+ await store.getState().createSavedQuery({
+ tabId: tab.id,
+ database: "instances/inst1/databases/db1",
+ statement: "SELECT earlier",
+ });
+
+ expect(getSQLEditorTabsState().tabsById.get(tab.id)).toMatchObject({
+ statement: "SELECT newer",
+ status: "DIRTY",
+ savedQuery: "projects/default/savedQueries/query1",
+ });
+ });
+});
+
describe("saved query save slice — maybeSwitchProject", () => {
test("with an invalid project name returns undefined without setting project", async () => {
const store = makeStore();
diff --git a/frontend/src/modules/sql-editor/store/savedQuery.ts b/frontend/src/modules/sql-editor/store/savedQuery.ts
index f8057bf9eb..6617b8efd0 100644
--- a/frontend/src/modules/sql-editor/store/savedQuery.ts
+++ b/frontend/src/modules/sql-editor/store/savedQuery.ts
@@ -123,6 +123,7 @@ export const createSavedQuerySaveSlice: SQLEditorSliceCreator<
statement = "",
folders = [],
database = "",
+ signal,
}) => {
const editorStore = getSQLEditorEditorState();
const tabStore = getSQLEditorTabsState();
@@ -138,15 +139,35 @@ export const createSavedQuerySaveSlice: SQLEditorSliceCreator<
content: new TextEncoder().encode(statement),
project: editorStore.project,
folder: folders.join("/"),
- })
+ }),
+ signal
);
+ if (signal?.aborted) {
+ throw new DOMException("Aborted", "AbortError");
+ }
+
if (tabId) {
+ const currentTab = tabStore.tabsById.get(tabId);
+ const statementChanged = currentTab?.statement !== statement;
+ const databaseChanged =
+ !currentTab ||
+ currentTab.connection.instance !== connection.instance ||
+ currentTab.connection.database !== connection.database;
+ const nextConnection =
+ currentTab?.connection.instance === connection.instance &&
+ currentTab.connection.database === connection.database
+ ? { ...currentTab.connection, ...connection }
+ : connection;
return tabStore.updateTab(tabId, {
- status: "CLEAN",
+ status: statementChanged || databaseChanged ? "DIRTY" : "CLEAN",
title: savedQueryTitle,
- statement,
- connection,
+ statement: statementChanged
+ ? (currentTab?.statement ?? statement)
+ : statement,
+ connection: databaseChanged
+ ? (currentTab?.connection ?? connection)
+ : nextConnection,
savedQuery: newSavedQuery.name,
});
}
diff --git a/frontend/src/modules/sql-editor/store/types.ts b/frontend/src/modules/sql-editor/store/types.ts
index ba8a28728c..3100973425 100644
--- a/frontend/src/modules/sql-editor/store/types.ts
+++ b/frontend/src/modules/sql-editor/store/types.ts
@@ -139,6 +139,7 @@ export interface SavedQuerySaveSlice {
statement?: string;
folders?: string[];
database?: string;
+ signal?: AbortSignal;
}) => Promise<SQLEditorTab | undefined>;
}
diff --git a/frontend/src/stores/app/savedQuery.ts b/frontend/src/stores/app/savedQuery.ts
index a4ffcbbd70..6f8da4d70b 100644
--- a/frontend/src/stores/app/savedQuery.ts
+++ b/frontend/src/stores/app/savedQuery.ts
@@ -186,7 +186,7 @@ export const createSavedQuerySlice: AppSliceCreator<SavedQuerySlice> = (
return response.folders;
},
- createSavedQuery: async (savedQuery) => {
+ createSavedQuery: async (savedQuery, signal) => {
const fullSavedQuery = savedQuery.name
? savedQuery
: clone(SavedQuerySchema, savedQuery);
@@ -194,7 +194,8 @@ export const createSavedQuerySlice: AppSliceCreator<SavedQuerySlice> = (
createProto(CreateSavedQueryRequestSchema, {
parent: fullSavedQuery.project,
savedQuery: fullSavedQuery,
- })
+ }),
+ { signal }
);
setCacheEntry(response, "FULL");
return response;
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 53e4bfc2e3..09d7b7944b 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -655,7 +655,10 @@ export type SavedQuerySlice = {
parent: string,
filter?: string
) => Promise<string[]>;
- createSavedQuery: (savedQuery: SavedQuery) => Promise<SavedQuery>;
+ createSavedQuery: (
+ savedQuery: SavedQuery,
+ signal?: AbortSignal
+ ) => Promise<SavedQuery>;
patchSavedQuery: (
savedQuery: SavedQuery,
updateMask: string[],