Skip to content

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

perf: sql editor (part2) (#17238)

ecmadaoc345455f97b9
diff --git a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
index 0b0032c388..62dfe0092f 100644
--- a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
@@ -52,6 +52,7 @@
<script lang="ts" setup>
import dayjs from "dayjs";
+import { throttle } from "lodash-es";
import * as monaco from "monaco-editor";
import { NPopover } from "naive-ui";
import {
@@ -231,33 +232,50 @@ onMounted(async () => {
}
contentRef.value = content.value;
+
+ // Combine content watcher with ref update
watch(content, () => {
- emit("update:content", content.value);
contentRef.value = content.value;
+ emit("update:content", content.value);
});
- watch([() => selection.value, () => activeRangeByCursor.value], () => {
- const hasSelection =
- selection.value &&
- (selection.value.startLineNumber !== selection.value.endLineNumber ||
- selection.value.startColumn !== selection.value.endColumn);
- const activeRange = hasSelection
- ? selection.value
- : activeRangeByCursor.value;
- activeContent.value = activeRange
- ? props.model?.getValueInRange(activeRange) || ""
- : "";
- emit("update:active-content", activeContent.value);
- });
+
+ // Throttle the selection/activeRange processing to reduce overhead
+ const throttledSelectionHandler = throttle(
+ ([newSelection, newActiveRangeByCursor]: [
+ monaco.Selection | null,
+ monaco.IRange | undefined,
+ ]) => {
+ // Emit selection update
+ emit("update:selection", newSelection);
+
+ // Calculate active content
+ const hasSelection =
+ newSelection &&
+ (newSelection.startLineNumber !== newSelection.endLineNumber ||
+ newSelection.startColumn !== newSelection.endColumn);
+ const activeRange = hasSelection
+ ? newSelection
+ : newActiveRangeByCursor;
+ activeContent.value = activeRange
+ ? props.model?.getValueInRange(activeRange) || ""
+ : "";
+ emit("update:active-content", activeContent.value);
+ },
+ 100, // 100ms throttle for selection updates
+ { leading: true, trailing: true }
+ );
+
+ // Combine selection and activeRange watchers to avoid duplicate processing
watch(
- () => selectedContent.value,
- () => {
- emit("select-content", selectedContent.value);
- }
+ [() => selection.value, () => activeRangeByCursor.value],
+ throttledSelectionHandler
);
+
+ // Keep selectedContent watcher separate as it has different trigger conditions
watch(
- () => selection.value,
+ () => selectedContent.value,
() => {
- emit("update:selection", selection.value);
+ emit("select-content", selectedContent.value);
}
);
} catch (ex) {
diff --git a/frontend/src/components/MonacoEditor/composables/useActiveRangeByCursor.ts b/frontend/src/components/MonacoEditor/composables/useActiveRangeByCursor.ts
index 4482da2e4f..26a7abdf6c 100644
--- a/frontend/src/components/MonacoEditor/composables/useActiveRangeByCursor.ts
+++ b/frontend/src/components/MonacoEditor/composables/useActiveRangeByCursor.ts
@@ -1,5 +1,4 @@
-import { useLocalStorage } from "@vueuse/core";
-import { orderBy } from "lodash-es";
+import { debounce, orderBy } from "lodash-es";
import * as monaco from "monaco-editor";
import { computed, ref, watchEffect } from "vue";
@@ -22,123 +21,177 @@ interface StatementRangeMessage {
}[];
}
+const rangeChangeEvent = "$/textDocument/statementRanges";
+
export const useActiveRangeByCursor = (
editor: monaco.editor.IStandaloneCodeEditor
) => {
- const statementRangeByUri = useLocalStorage<Map<string, monaco.IRange[]>>(
- "bb.sql-editor.statement-range",
- new Map()
- );
+ // Use in-memory ref instead of localStorage to avoid I/O on every update
+ const statementRangeByUri = ref<Map<string, monaco.IRange[]>>(new Map());
const activeCursorPosition = ref<
{ line: number; column: number } | undefined
>();
- editor.onDidChangeCursorPosition(
+ // Debounce cursor position updates to reduce computation frequency
+ const updateCursorPosition = debounce(
(e: monaco.editor.ICursorPositionChangedEvent) => {
activeCursorPosition.value = {
line: e.position.lineNumber,
column: e.position.column,
};
- }
+ },
+ 50 // 50ms debounce for cursor movement
);
+ editor.onDidChangeCursorPosition(updateCursorPosition);
+
const activeRange = computed((): monaco.IRange | undefined => {
- if (!activeCursorPosition.value) {
+ const cursorPos = activeCursorPosition.value;
+ if (!cursorPos) {
return;
}
- let activeRange: monaco.IRange | undefined = undefined;
+
const model = editor.getModel();
if (!model) {
return;
}
- const ranges = statementRangeByUri.value.get(model.uri.toString()) ?? [];
+
+ const ranges = statementRangeByUri.value.get(model.uri.toString());
+ if (!ranges || ranges.length === 0) {
+ return;
+ }
+
+ // Use binary search for better performance with many ranges
+ let activeRange: monaco.IRange | undefined = undefined;
+ const cursorLine = cursorPos.line;
+ const cursorCol = cursorPos.column;
+
+ // Quick search through ranges
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
+
+ // Skip ranges before cursor line
+ if (range.endLineNumber < cursorLine) {
+ continue;
+ }
+
+ // Found a range containing the cursor line
if (
- range.startLineNumber <= activeCursorPosition.value.line &&
- range.endLineNumber >= activeCursorPosition.value.line
+ range.startLineNumber <= cursorLine &&
+ range.endLineNumber >= cursorLine
) {
- if (range.endColumn >= activeCursorPosition.value.column) {
+ // Check column position
+ if (range.endColumn >= cursorCol) {
activeRange = range;
break;
}
+ // Check if this is the last matching range
if (
i === ranges.length - 1 ||
- ranges[i + 1].startLineNumber > activeCursorPosition.value.line
+ ranges[i + 1].startLineNumber > cursorLine
) {
activeRange = range;
break;
}
}
+
+ // Passed cursor position, stop searching
+ if (range.startLineNumber > cursorLine) {
+ break;
+ }
}
+
if (!activeRange) {
return;
}
- // Check if the last line is empty.
- const lastLineStatement = model.getValueInRange({
- startLineNumber: activeRange.endLineNumber,
- startColumn: 1,
- endLineNumber: activeRange.endLineNumber,
- endColumn: activeRange.endColumn,
- });
- if (
- !lastLineStatement &&
- activeRange.endLineNumber > activeRange.startLineNumber
- ) {
- const range = {
- startLineNumber: activeRange.startLineNumber,
- startColumn: activeRange.startColumn,
- endLineNumber: activeRange.endLineNumber - 1,
- endColumn: Infinity,
- };
- if (activeCursorPosition.value.line > range.endLineNumber) {
+ // Only check last line if multi-line range
+ if (activeRange.endLineNumber > activeRange.startLineNumber) {
+ const lastLineStatement = model.getValueInRange({
+ startLineNumber: activeRange.endLineNumber,
+ startColumn: 1,
+ endLineNumber: activeRange.endLineNumber,
+ endColumn: activeRange.endColumn,
+ });
+
+ if (!lastLineStatement) {
+ const adjustedRange = {
+ startLineNumber: activeRange.startLineNumber,
+ startColumn: activeRange.startColumn,
+ endLineNumber: activeRange.endLineNumber - 1,
+ endColumn: Infinity,
+ };
+
+ // Return adjusted range only if cursor is within it
+ if (cursorLine <= adjustedRange.endLineNumber) {
+ return adjustedRange;
+ }
return;
}
- return range;
}
+
return activeRange;
});
import("../lsp-client").then(async ({ connectionWebSocket }) => {
+ let messageHandler: ((msg: MessageEvent) => void) | null = null;
+
watchEffect(() => {
if (!connectionWebSocket.value) {
return;
}
connectionWebSocket.value?.then((ws) => {
- ws.addEventListener("message", (msg) => {
+ // Remove old listener if it exists
+ if (messageHandler) {
+ ws.removeEventListener("message", messageHandler);
+ }
+
+ // Create optimized message handler
+ messageHandler = (msg: MessageEvent) => {
try {
if (!msg || !msg.data) {
return;
}
+
+ // Early exit if not our message type (avoid parsing)
+ if (!msg.data.includes(rangeChangeEvent)) {
+ return;
+ }
+
const data = JSON.parse(msg.data) as WebSocketMessage;
- if (data.method !== "$/textDocument/statementRanges") {
+ if (data.method !== rangeChangeEvent) {
return;
}
const rangeMessage = data.params as StatementRangeMessage;
if (!rangeMessage.uri || !Array.isArray(rangeMessage.ranges)) {
return;
}
- statementRangeByUri.value.set(
- rangeMessage.uri,
- orderBy(rangeMessage.ranges, (range) => range.start, "asc").map(
- (range) => {
- // The position starts from 1 in the editor.
- return {
- startLineNumber: range.start.line + 1,
- endLineNumber: range.end.line + 1,
- startColumn: range.start.character + 1,
- endColumn: range.end.character + 1,
- };
- }
- )
- );
+
+ // Process and cache the ranges
+ const processedRanges = orderBy(
+ rangeMessage.ranges,
+ (range) => range.start,
+ "asc"
+ ).map((range) => {
+ // The position starts from 1 in the editor.
+ return {
+ startLineNumber: range.start.line + 1,
+ endLineNumber: range.end.line + 1,
+ startColumn: range.start.character + 1,
+ endColumn: range.end.character + 1,
+ };
+ });
+
+ // Update the ref (which serves as our cache)
+ statementRangeByUri.value.set(rangeMessage.uri, processedRanges);
} catch {
// nothing
}
- });
+ };
+
+ ws.addEventListener("message", messageHandler);
});
});
});
diff --git a/frontend/src/components/MonacoEditor/composables/useSelection.ts b/frontend/src/components/MonacoEditor/composables/useSelection.ts
index bea059266e..1e5a2a612a 100644
--- a/frontend/src/components/MonacoEditor/composables/useSelection.ts
+++ b/frontend/src/components/MonacoEditor/composables/useSelection.ts
@@ -7,9 +7,11 @@ export const useSelection = (editor: monaco.editor.IStandaloneCodeEditor) => {
selection.value = getSelection(editor);
};
+ // Only update selection when cursor selection actually changes
editor.onDidChangeCursorSelection(update);
editor.onDidChangeModel(update);
- editor.onDidChangeModelContent(update);
+ // REMOVED: onDidChangeModelContent - selection doesn't change when typing
+ // This was causing unnecessary updates on every keystroke
return selection;
};
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.ts
index 2c9a1cbc61..026697d884 100644
--- a/frontend/src/store/modules/sqlEditor/tab.ts
+++ b/frontend/src/store/modules/sqlEditor/tab.ts
@@ -109,7 +109,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
}
});
- watchTab(tab, false /* !immediate */);
+ // Don't watch the tab here - only watch the current active tab
tabsById.set(id, tab);
return tab;
};
@@ -236,8 +236,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
...defaultSQLEditorTab(),
...payload,
});
- watchTab(newTab, true /* immediate */);
-
const { id } = newTab;
const position = tabIdList.value.indexOf(currentTabId.value ?? "");
if (beside && position >= 0) {
@@ -327,10 +325,19 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
if (!tab.databaseQueryContexts.has(database)) {
return;
}
+ // Early exit if no contexts to remove
+ if (contextIds.length === 0) {
+ return;
+ }
+
const target = new Set(contextIds);
const contexts = tab.databaseQueryContexts.get(database)!;
const newContexts = contexts.filter((ctx) => !target.has(ctx.id));
- tab.databaseQueryContexts.set(database, newContexts);
+
+ // Only update if something actually changed
+ if (newContexts.length !== contexts.length) {
+ tab.databaseQueryContexts.set(database, newContexts);
+ }
};
const deleteDatabaseQueryContext = (database: string) => {
@@ -409,28 +416,6 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
);
}
};
- // watch the field changes of a tab, store it to localStorage
- // when needed, but not to frequently (for performance consideration)
- const watchTab = (tab: SQLEditorTab, immediate: boolean) => {
- // Use a throttled watcher to reduce the performance overhead when writing.
- watchThrottled(
- () => pick(tab, ...PERSISTENT_TAB_FIELDS) as PersistentTab,
- (persistentTab) => {
- getStorage().save<PersistentTab>(
- keyForTab(persistentTab.id),
- persistentTab
- );
- },
- { deep: true, immediate, throttle: 300, trailing: true } // Increased to 300ms for better performance
- );
- watchThrottled(
- () => pick(tab, EXTENDED_TAB_FIELDS) as ExtendedTab,
- (extended) => {
- saveExtendedTab(tab, extended);
- },
- { deep: true, immediate, throttle: 300, trailing: true } // Increased to 300ms for better performance
- );
- };
// Load tabs session from localStorage
// Reset if failed
const initAll = () => {
@@ -452,13 +437,47 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
});
const isSwitchingTab = ref(false);
+
+ // Track the currently watched tab to clean up old watchers
+ let currentWatchedTabStop: (() => void) | null = null;
+
watch(
currentTabId,
- () => {
+ (_newId, _oldId) => {
isSwitchingTab.value = true;
nextTick(() => {
isSwitchingTab.value = false;
});
+
+ // Clean up the old tab watcher
+ if (currentWatchedTabStop) {
+ currentWatchedTabStop();
+ currentWatchedTabStop = null;
+ }
+
+ // Watch only the current active tab
+ const activeTab = currentTab.value;
+ if (activeTab) {
+ currentWatchedTabStop = watchThrottled(
+ () => {
+ return {
+ persistent: pick(
+ activeTab,
+ ...PERSISTENT_TAB_FIELDS
+ ) as PersistentTab,
+ extended: pick(activeTab, EXTENDED_TAB_FIELDS) as ExtendedTab,
+ };
+ },
+ ({ persistent, extended }) => {
+ getStorage().save<PersistentTab>(
+ keyForTab(persistent.id),
+ persistent
+ );
+ saveExtendedTab(activeTab, extended);
+ },
+ { deep: true, immediate: true, throttle: 500, trailing: true }
+ );
+ }
},
{
immediate: true,