Skip to content

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

fix: sql editor ux (#20461)

ecmadao738e1321ae78
diff --git a/backend/api/lsp/commands.go b/backend/api/lsp/commands.go
index ff1dcb9a7a..11237ef489 100644
--- a/backend/api/lsp/commands.go
+++ b/backend/api/lsp/commands.go
@@ -35,4 +35,9 @@ type SetMetadataCommandArguments struct {
// in other words, SELECT statements only.
// If the scene is "all", it will return completion items for all statements.
Scene string `json:"scene,omitempty"`
+ // The DocumentURI is the URI of the document this metadata applies to.
+ // The metadata is connection-global, but the engine it derives is only
+ // valid for the active document that sent it, so diagnostics are
+ // rescheduled for this URI only (see the setMetadata command handler).
+ DocumentURI lsp.DocumentURI `json:"documentUri,omitempty"`
}
diff --git a/backend/api/lsp/handler.go b/backend/api/lsp/handler.go
index 0f715fff8d..deb37dfa07 100644
--- a/backend/api/lsp/handler.go
+++ b/backend/api/lsp/handler.go
@@ -383,7 +383,20 @@ func (h *Handler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2
Message: fmt.Sprintf("permission denied: %v", err),
}
}
- h.setMetadata(setMetadataParams.Arguments[0])
+ args := setMetadataParams.Arguments[0]
+ h.setMetadata(args)
+ // Statement ranges (used by the active-statement highlight) need
+ // the engine, which is derived from this metadata. Compute them for
+ // the document that sent it, now that the engine is known — this is
+ // what populates the highlight on first open and tab switch.
+ // Scoped to args.DocumentURI: the metadata is connection-global, so
+ // rescheduling other open documents would reparse them with this
+ // document's engine.
+ if uri := args.DocumentURI; uri != "" {
+ if content, found := h.GetFS().get(uri); found {
+ h.diagnosticsDebouncer.ScheduleDiagnostics(ctx, conn, uri, string(content), h)
+ }
+ }
return nil, nil
default:
return nil, &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidParams, Message: fmt.Sprintf("command not supported: %s", params.Command)}
diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsx
index a1b38f49e9..13c725ad46 100644
--- a/frontend/src/react/components/monaco/MonacoEditor.tsx
+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx
@@ -2,7 +2,6 @@ import { create } from "@bufbuild/protobuf";
import { debounce, orderBy } from "lodash-es";
import { Loader2 } from "lucide-react";
import {
- type MutableRefObject,
type ReactNode,
useEffect,
useMemo,
@@ -36,9 +35,14 @@ import {
initializeLSPClient,
subscribeConnectionState,
} from "./lsp-client";
+import {
+ getStatementRanges,
+ setStatementRanges,
+} from "./statement-range-store";
import { ensureSuggestOverrideStyle } from "./suggest-icons";
import {
getOrCreateTextModel,
+ getUriByFilename,
restoreViewState,
storeViewState,
} from "./text-model";
@@ -168,7 +172,6 @@ export function MonacoEditor({
const onActiveContentChangeRef = useRef(onActiveContentChange);
const onReadyRef = useRef(onReady);
const isApplyingExternalChangeRef = useRef(false);
- const activeRangeByUriRef = useRef<Map<string, MonacoTypeRange[]>>(new Map());
const selectionRef = useRef<Selection | null>(null);
const generatedFilename = useMemo(() => {
if (filename) {
@@ -240,7 +243,7 @@ export function MonacoEditor({
onSelectContentRef.current?.(selectedContent);
const cursorPosition = editor.getPosition();
- const ranges = activeRangeByUriRef.current.get(model.uri.toString()) ?? [];
+ const ranges = getStatementRanges(model.uri.toString());
const activeRange =
selection && !selection.isEmpty()
? selection
@@ -408,7 +411,7 @@ export function MonacoEditor({
wsPromise?.then((ws) => {
if (!ws || disposed) return;
messageHandler = (message: MessageEvent) => {
- processStatementRangeMessage(message, activeRangeByUriRef);
+ processStatementRangeMessage(message);
emitSelectionSideEffects();
};
ws.addEventListener("message", messageHandler);
@@ -592,6 +595,7 @@ export function MonacoEditor({
databaseName: string;
scene?: string;
schema?: string;
+ documentUri?: string;
} = {
instanceId: "",
databaseName: "",
@@ -610,6 +614,13 @@ export function MonacoEditor({
}
const apply = debounce(async () => {
const client = await initializeLSPClient();
+ // Tell the server which document this metadata is for, so it can
+ // reschedule diagnostics for exactly this document once the engine is
+ // known (see the backend setMetadata handler). Matches the model URI
+ // the LSP client opened the document with.
+ params.documentUri = (
+ await getUriByFilename(generatedFilename)
+ ).toString();
await executeCommand(client, "setMetadata", [params]);
}, 500);
void apply();
@@ -840,10 +851,7 @@ const attachFormatAction = (
});
};
-const processStatementRangeMessage = (
- message: MessageEvent,
- ref: MutableRefObject<Map<string, MonacoTypeRange[]>>
-) => {
+const processStatementRangeMessage = (message: MessageEvent) => {
if (typeof message.data !== "string") return;
if (!message.data.includes("$/textDocument/statementRanges")) return;
try {
@@ -873,7 +881,7 @@ const processStatementRangeMessage = (
startColumn: range.start.character + 1,
endColumn: range.end.character + 1,
}));
- ref.current.set(payload.params.uri, ranges);
+ setStatementRanges(payload.params.uri, ranges);
} catch (e) {
console.debug("[sql-editor:statementRanges] failed to parse LSP message", {
data: message.data,
diff --git a/frontend/src/react/components/monaco/statement-range-store.ts b/frontend/src/react/components/monaco/statement-range-store.ts
new file mode 100644
index 0000000000..f1e212ddc4
--- /dev/null
+++ b/frontend/src/react/components/monaco/statement-range-store.ts
@@ -0,0 +1,34 @@
+// In-memory store for SQL statement ranges, keyed by document URI.
+//
+// The backend pushes `$/textDocument/statementRanges` over the LSP socket when
+// a document opens (`didOpen`) and on every edit (`didChange`). The active-
+// statement highlight reads these ranges. They must outlive a single editor
+// instance, because the SQL Editor remounts the editor on every tab switch
+// (`key={filename}`) and `didOpen` fires only once per model per page session
+// (models are cached and never disposed), so switching back to a previously
+// visited tab gets no fresh push. A module-level map keyed by URI survives
+// those remounts.
+//
+// This is intentionally NOT persisted to localStorage: a page reload creates a
+// fresh model, which re-triggers `didOpen` and re-fetches the ranges from the
+// backend. Keeping it in memory avoids unbounded storage growth and stale
+// ranges that no longer match a worksheet's content.
+
+export type StatementRange = {
+ startLineNumber: number;
+ endLineNumber: number;
+ startColumn: number;
+ endColumn: number;
+};
+
+const store = new Map<string, StatementRange[]>();
+
+export const getStatementRanges = (uri: string): StatementRange[] =>
+ store.get(uri) ?? [];
+
+export const setStatementRanges = (
+ uri: string,
+ ranges: StatementRange[]
+): void => {
+ store.set(uri, ranges);
+};
diff --git a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx
index 0b7b4fed2f..87a4812a93 100644
--- a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx
@@ -176,7 +176,16 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
{detail && (
<div
className={cn(
- "h-full flex flex-col gap-y-2",
+ // `flex-1 min-h-0` instead of `h-full` so the wrapper absorbs
+ // the space remaining after `SheetHeader` (not 100vh). The
+ // `min-h-0` lets the inner `flex-1 overflow-auto` block
+ // actually clip and scroll — without it, the scroll region
+ // expands to fit its content and the bottom rows render past
+ // the viewport.
+ // Match `SheetBody`'s `px-6 py-4` so the toolbar buttons
+ // and the content code block don't bleed to the sheet's
+ // raw edges.
+ "flex-1 min-h-0 flex flex-col gap-y-2 px-6 py-4",
dark ? "text-white" : "text-main"
)}
>
diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
index 9d10872d64..93fbba472c 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
@@ -87,7 +87,6 @@ export function SQLEditorHomePage() {
}, []);
const hideSidebar = windowWidth < 800;
- const [sidebarSize, setSidebarSize] = useState(25);
const [sidebarExpanded, setSidebarExpanded] = useState(false);
// alter-schema: open a new tab to the plan editor with a pre-filled
@@ -211,12 +210,7 @@ export function SQLEditorHomePage() {
<PanelGroup orientation="horizontal" className="h-full">
{!hideSidebar && (
<>
- <Panel
- defaultSize={`${sidebarSize}%`}
- minSize="10%"
- maxSize="40%"
- onResize={(size) => setSidebarSize(size.asPercentage)}
- >
+ <Panel defaultSize="25%" minSize="10%" maxSize="40%">
<div className="h-full">
<AsidePanel />
</div>