Skip to content

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

perf: sql editor (part1) (#17236)

ecmadaof92a08cc5bc6
diff --git a/backend/api/lsp/fs_handler.go b/backend/api/lsp/fs_handler.go
index 1944b5a85a..9889b5cfd5 100644
--- a/backend/api/lsp/fs_handler.go
+++ b/backend/api/lsp/fs_handler.go
@@ -4,15 +4,11 @@ import (
"bytes"
"context"
"encoding/json"
- "log/slog"
"os"
lsp "github.com/bytebase/lsp-protocol"
"github.com/pkg/errors"
"github.com/sourcegraph/jsonrpc2"
-
- "github.com/bytebase/bytebase/backend/common/log"
- "github.com/bytebase/bytebase/backend/plugin/parser/base"
)
// GetFS returns the file system.
@@ -82,27 +78,10 @@ func (h *Handler) handleFileSystemRequest(ctx context.Context, conn *jsonrpc2.Co
if !found {
return &os.PathError{Op: "Open", Path: string(uri), Err: os.ErrNotExist}
}
- diagnostics, err := base.Diagnose(ctx, base.DiagnoseContext{}, h.getEngineType(ctx), string(content))
- if err != nil {
- slog.Warn("diagnose error", log.BBError(err))
- }
- if err := conn.Notify(ctx, string(LSPMethodPublishDiagnostics), &lsp.PublishDiagnosticsParams{
- URI: uri,
- Diagnostics: diagnostics,
- }); err != nil {
- return err
- }
- statementRanges, err := base.GetStatementRanges(ctx, base.StatementRangeContext{}, h.getEngineType(ctx), string(content))
- if err != nil {
- slog.Warn("get statement ranges error", log.BBError(err))
- } else if len(statementRanges) != 0 {
- if err := conn.Notify(ctx, string(LSPCustomMethodSQLStatementRanges), &SQLStatementRangesParams{
- URI: uri,
- Ranges: statementRanges,
- }); err != nil {
- return err
- }
- }
+
+ // Use debounced diagnostics for better performance
+ // This prevents diagnostics from running on every keystroke
+ h.diagnosticsDebouncer.ScheduleDiagnostics(ctx, conn, uri, string(content), h)
return nil
})
diff --git a/backend/api/lsp/handler.go b/backend/api/lsp/handler.go
index 4e2a56b77f..db758f9dd7 100644
--- a/backend/api/lsp/handler.go
+++ b/backend/api/lsp/handler.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log/slog"
"sync"
+ "time"
lsp "github.com/bytebase/lsp-protocol"
"github.com/pkg/errors"
@@ -47,7 +48,14 @@ const (
// NewHandler creates a new Language Server Protocol handler.
func NewHandler(s *store.Store, profile *config.Profile) jsonrpc2.Handler {
- return lspHandler{Handler: jsonrpc2.HandlerWithError((&Handler{store: s, profile: profile}).handle)}
+ handler := &Handler{
+ store: s,
+ profile: profile,
+ diagnosticsDebouncer: NewDiagnosticsDebouncer(500 * time.Millisecond), // 500ms debounce
+ contentCache: NewContentCache(100), // Cache up to 100 documents
+ perfMonitor: NewPerformanceMonitor(),
+ }
+ return lspHandler{Handler: jsonrpc2.HandlerWithError(handler.handle)}
}
type lspHandler struct {
@@ -73,6 +81,11 @@ type Handler struct {
shutDown bool
profile *config.Profile
cancelF sync.Map // map[jsonrpc2.ID]context.CancelFunc
+
+ // Performance optimizations
+ diagnosticsDebouncer *DiagnosticsDebouncer
+ contentCache *ContentCache
+ perfMonitor *PerformanceMonitor
}
// ShutDown shuts down the handler.
@@ -181,6 +194,10 @@ func (h *Handler) reset(params *lsp.InitializeParams) error {
defer h.mu.Unlock()
h.init = params
h.fs = NewMemFS()
+ // Clear any pending diagnostics on reset
+ if h.diagnosticsDebouncer != nil {
+ h.diagnosticsDebouncer.Clear()
+ }
return nil
}
diff --git a/backend/api/lsp/performance_optimizer.go b/backend/api/lsp/performance_optimizer.go
new file mode 100644
index 0000000000..722cf2335b
--- /dev/null
+++ b/backend/api/lsp/performance_optimizer.go
@@ -0,0 +1,340 @@
+package lsp
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ lsp "github.com/bytebase/lsp-protocol"
+ "github.com/sourcegraph/jsonrpc2"
+
+ "github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/plugin/parser/base"
+)
+
+// DiagnosticsDebouncer manages debounced diagnostics for performance optimization
+type DiagnosticsDebouncer struct {
+ mu sync.Mutex
+ pendingDiagnostics map[lsp.DocumentURI]*pendingDiagnostic
+ defaultDelay time.Duration
+}
+
+type pendingDiagnostic struct {
+ uri lsp.DocumentURI
+ content string
+ timer *time.Timer
+ cancelled bool
+}
+
+// NewDiagnosticsDebouncer creates a new diagnostics debouncer
+func NewDiagnosticsDebouncer(defaultDelay time.Duration) *DiagnosticsDebouncer {
+ return &DiagnosticsDebouncer{
+ pendingDiagnostics: make(map[lsp.DocumentURI]*pendingDiagnostic),
+ defaultDelay: defaultDelay,
+ }
+}
+
+// ScheduleDiagnostics schedules diagnostics to be run after a delay, cancelling any pending diagnostics for the same URI
+func (d *DiagnosticsDebouncer) ScheduleDiagnostics(
+ ctx context.Context,
+ conn *jsonrpc2.Conn,
+ uri lsp.DocumentURI,
+ content string,
+ handler *Handler,
+) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+
+ // Cancel existing pending diagnostic for this URI
+ if existing, exists := d.pendingDiagnostics[uri]; exists {
+ existing.cancelled = true
+ if existing.timer != nil {
+ existing.timer.Stop()
+ }
+ }
+
+ // Create new pending diagnostic
+ pending := &pendingDiagnostic{
+ uri: uri,
+ content: content,
+ cancelled: false,
+ }
+
+ // Schedule the diagnostic
+ pending.timer = time.AfterFunc(d.defaultDelay, func() {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+
+ // Check if this diagnostic was cancelled
+ if pending.cancelled {
+ return
+ }
+
+ // Remove from pending map
+ delete(d.pendingDiagnostics, uri)
+
+ // Run diagnostics in a goroutine to avoid blocking
+ go d.runDiagnostics(ctx, conn, uri, content, handler)
+ })
+
+ d.pendingDiagnostics[uri] = pending
+}
+
+// runDiagnostics performs the actual diagnostics and sends results
+func (*DiagnosticsDebouncer) runDiagnostics(
+ ctx context.Context,
+ conn *jsonrpc2.Conn,
+ uri lsp.DocumentURI,
+ content string,
+ handler *Handler,
+) {
+ // Check context cancellation before starting
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ start := time.Now()
+ engineType := handler.getEngineType(ctx)
+
+ // Check cache first for statement ranges
+ var diagnostics []lsp.Diagnostic
+ var statementRanges []lsp.Range
+ var cacheHit bool
+
+ if handler.contentCache != nil {
+ if cached, exists := handler.contentCache.Get(string(uri)); exists && cached.Content == content {
+ // Use cached statement ranges if content hasn't changed
+ statementRanges = cached.StatementRanges
+ cacheHit = true
+ slog.Debug("Using cached statement ranges",
+ slog.String("uri", string(uri)))
+ }
+ }
+
+ // Run expensive diagnostics (always fresh, not cached)
+ var err error
+ diagnostics, err = base.Diagnose(ctx, base.DiagnoseContext{}, engineType, content)
+ if err != nil {
+ slog.Warn("diagnose error", log.BBError(err))
+ }
+
+ // Check context cancellation after diagnostics
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ // Log diagnostic performance
+ slog.Debug("Debounced diagnostics completed",
+ slog.String("uri", string(uri)),
+ slog.Duration("duration", time.Since(start)),
+ slog.Int("diagnosticCount", len(diagnostics)),
+ slog.Bool("cacheHit", cacheHit))
+
+ // Send diagnostics notification
+ if err := conn.Notify(ctx, string(LSPMethodPublishDiagnostics), &lsp.PublishDiagnosticsParams{
+ URI: uri,
+ Diagnostics: diagnostics,
+ }); err != nil {
+ slog.Warn("failed to publish diagnostics", log.BBError(err))
+ }
+
+ // Parse statement ranges if not cached
+ if !cacheHit {
+ rangeStart := time.Now()
+ statementRanges, err = base.GetStatementRanges(ctx, base.StatementRangeContext{}, engineType, content)
+ if err != nil {
+ slog.Warn("get statement ranges error", log.BBError(err))
+ } else {
+ slog.Debug("Statement range parsing completed",
+ slog.String("uri", string(uri)),
+ slog.Duration("duration", time.Since(rangeStart)),
+ slog.Int("rangeCount", len(statementRanges)))
+
+ // Cache the results
+ if handler.contentCache != nil {
+ handler.contentCache.Set(string(uri), &CachedContent{
+ Content: content,
+ LastModified: time.Now(),
+ StatementRanges: statementRanges,
+ })
+ }
+ }
+ }
+
+ // Send statement ranges if available
+ if len(statementRanges) != 0 {
+ if err := conn.Notify(ctx, string(LSPCustomMethodSQLStatementRanges), &SQLStatementRangesParams{
+ URI: uri,
+ Ranges: statementRanges,
+ }); err != nil {
+ slog.Warn("failed to publish statement ranges", log.BBError(err))
+ }
+ }
+}
+
+// Clear cancels all pending diagnostics
+func (d *DiagnosticsDebouncer) Clear() {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+
+ for _, pending := range d.pendingDiagnostics {
+ pending.cancelled = true
+ if pending.timer != nil {
+ pending.timer.Stop()
+ }
+ }
+ d.pendingDiagnostics = make(map[lsp.DocumentURI]*pendingDiagnostic)
+}
+
+// ContentCache implements a simple LRU cache for parsed content
+type ContentCache struct {
+ mu sync.RWMutex
+ cache map[string]*CachedContent
+ maxEntries int
+ order []string // Track order for LRU eviction
+}
+
+type CachedContent struct {
+ Content string
+ LastModified time.Time
+ StatementRanges []lsp.Range
+}
+
+// NewContentCache creates a new content cache
+func NewContentCache(maxEntries int) *ContentCache {
+ return &ContentCache{
+ cache: make(map[string]*CachedContent),
+ maxEntries: maxEntries,
+ order: make([]string, 0, maxEntries),
+ }
+}
+
+// Get retrieves cached content
+func (c *ContentCache) Get(uri string) (*CachedContent, bool) {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+
+ content, exists := c.cache[uri]
+ return content, exists
+}
+
+// Invalidate removes a specific entry from cache
+func (c *ContentCache) Invalidate(uri string) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ delete(c.cache, uri)
+ for i, u := range c.order {
+ if u == uri {
+ c.order = append(c.order[:i], c.order[i+1:]...)
+ break
+ }
+ }
+}
+
+// Set stores content in cache with LRU eviction
+func (c *ContentCache) Set(uri string, content *CachedContent) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ // Check if already exists
+ if _, exists := c.cache[uri]; exists {
+ // If already exists, just update and move to end
+ for i, u := range c.order {
+ if u == uri {
+ // More efficient removal for common case of updating existing entry
+ copy(c.order[i:], c.order[i+1:])
+ c.order = c.order[:len(c.order)-1]
+ break
+ }
+ }
+ }
+
+ // Add to end (most recently used)
+ c.order = append(c.order, uri)
+
+ // Evict oldest if over capacity
+ if len(c.order) > c.maxEntries {
+ oldest := c.order[0]
+ delete(c.cache, oldest)
+ c.order = c.order[1:]
+ }
+
+ c.cache[uri] = content
+}
+
+// PerformanceMonitor tracks LSP performance metrics
+type PerformanceMonitor struct {
+ mu sync.RWMutex
+ requestCounts map[Method]int64
+ requestDurations map[Method]time.Duration
+ lastReset time.Time
+}
+
+// NewPerformanceMonitor creates a new performance monitor
+func NewPerformanceMonitor() *PerformanceMonitor {
+ return &PerformanceMonitor{
+ requestCounts: make(map[Method]int64),
+ requestDurations: make(map[Method]time.Duration),
+ lastReset: time.Now(),
+ }
+}
+
+// RecordRequest records a request for performance monitoring
+func (p *PerformanceMonitor) RecordRequest(method Method, duration time.Duration) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+
+ p.requestCounts[method]++
+ p.requestDurations[method] += duration
+}
+
+// GetStats returns current performance statistics
+func (p *PerformanceMonitor) GetStats() map[Method]struct {
+ Count int64
+ TotalTime time.Duration
+ AverageTime time.Duration
+} {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+
+ stats := make(map[Method]struct {
+ Count int64
+ TotalTime time.Duration
+ AverageTime time.Duration
+ })
+
+ for method, count := range p.requestCounts {
+ totalTime := p.requestDurations[method]
+ avgTime := time.Duration(0)
+ if count > 0 {
+ avgTime = totalTime / time.Duration(count)
+ }
+ stats[method] = struct {
+ Count int64
+ TotalTime time.Duration
+ AverageTime time.Duration
+ }{
+ Count: count,
+ TotalTime: totalTime,
+ AverageTime: avgTime,
+ }
+ }
+
+ return stats
+}
+
+// Reset clears all performance statistics
+func (p *PerformanceMonitor) Reset() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+
+ p.requestCounts = make(map[Method]int64)
+ p.requestDurations = make(map[Method]time.Duration)
+ p.lastReset = time.Now()
+}
diff --git a/frontend/src/components/MonacoEditor/composables/useAutoComplete.ts b/frontend/src/components/MonacoEditor/composables/useAutoComplete.ts
index 2856ba733a..2f748a1a9c 100644
--- a/frontend/src/components/MonacoEditor/composables/useAutoComplete.ts
+++ b/frontend/src/components/MonacoEditor/composables/useAutoComplete.ts
@@ -1,3 +1,4 @@
+import { debounce } from "lodash-es";
import * as monaco from "monaco-editor";
import type { Ref } from "vue";
import { computed, watch } from "vue";
@@ -53,30 +54,33 @@ export const useAutoComplete = async (
return p;
});
+ // Debounce LSP metadata updates to reduce WebSocket requests
+ const debouncedSetMetadata = debounce(async (params: SetMetadataParams) => {
+ if (readonly.value) {
+ return;
+ }
+
+ // Initialize LSP client if not already initialized.
+ try {
+ const { executeCommand, initializeLSPClient } = await import(
+ "../lsp-client"
+ );
+ const client = await initializeLSPClient();
+ const result = await executeCommand(client, "setMetadata", [params]);
+ console.debug(
+ `[MonacoEditor] setMetadata(${JSON.stringify(params)}): ${JSON.stringify(
+ result
+ )}`
+ );
+ } catch (err) {
+ console.error("[MonacoEditor] Failed to initialize LSP client", err);
+ }
+ }, 500); // 500ms debounce to significantly reduce LSP requests
+
watch(
[() => JSON.stringify(params.value), () => readonly.value],
- async () => {
- if (readonly.value) {
- return;
- }
-
- // Initialize LSP client if not already initialized.
- try {
- const { executeCommand, initializeLSPClient } = await import(
- "../lsp-client"
- );
- const client = await initializeLSPClient();
- const result = await executeCommand(client, "setMetadata", [
- params.value,
- ]);
- console.debug(
- `[MonacoEditor] setMetadata(${JSON.stringify(params.value)}): ${JSON.stringify(
- result
- )}`
- );
- } catch (err) {
- console.error("[MonacoEditor] Failed to initialize LSP client", err);
- }
+ () => {
+ debouncedSetMetadata(params.value);
},
{ immediate: true }
);
diff --git a/frontend/src/components/MonacoEditor/composables/useContent.ts b/frontend/src/components/MonacoEditor/composables/useContent.ts
index 6f099b1785..e1ed6977c5 100644
--- a/frontend/src/components/MonacoEditor/composables/useContent.ts
+++ b/frontend/src/components/MonacoEditor/composables/useContent.ts
@@ -1,3 +1,4 @@
+import { debounce } from "lodash-es";
import * as monaco from "monaco-editor";
import { ref } from "vue";
import type { MonacoModule } from "../types";
@@ -7,12 +8,19 @@ export const useContent = (
editor: monaco.editor.IStandaloneCodeEditor
) => {
const content = ref(getContent(editor));
+
+ // Debounce content updates to reduce excessive reactive updates
+ const debouncedUpdate = debounce(() => {
+ content.value = getContent(editor);
+ }, 50); // Short debounce to balance responsiveness and performance
+
const update = () => {
+ // For model changes, update immediately
content.value = getContent(editor);
};
editor.onDidChangeModel(update);
- editor.onDidChangeModelContent(update);
+ editor.onDidChangeModelContent(debouncedUpdate);
return content;
};
diff --git a/frontend/src/components/MonacoEditor/lsp-client.ts b/frontend/src/components/MonacoEditor/lsp-client.ts
index 781da3bc87..1ddccb94d7 100644
--- a/frontend/src/components/MonacoEditor/lsp-client.ts
+++ b/frontend/src/components/MonacoEditor/lsp-client.ts
@@ -1,4 +1,4 @@
-import { omit } from "lodash-es";
+import { omit, throttle } from "lodash-es";
import { MonacoLanguageClient } from "monaco-languageclient";
import type { ExecuteCommandParams } from "vscode-languageclient";
import { CloseAction, ErrorAction, State } from "vscode-languageclient";
@@ -128,11 +128,43 @@ const createLanguageClient = async (): Promise<MonacoLanguageClient> => {
const socket = toSocket(ws);
const reader = new WebSocketMessageReader(socket);
const writer = new WebSocketMessageWriter(socket);
- return new MonacoLanguageClient({
+ // NOTE: We cannot debounce textDocument/didChange as it breaks LSP incremental sync
+ const client = new MonacoLanguageClient({
name: "Bytebase Language Client",
clientOptions: {
// use a language id as a document selector
documentSelector: ["sql"],
+ // Optimize initialization options
+ initializationOptions: {
+ // Request server to batch/throttle expensive operations
+ performanceMode: true,
+ // Reduce diagnostic frequency
+ diagnosticDelay: 500,
+ // Disable expensive features during typing
+ disableFeaturesWhileTyping: true,
+ },
+ // Configure which capabilities to enable
+ middleware: {
+ // Throttle hover requests
+ provideHover: throttle(async (document, position, token, next) => {
+ return next(document, position, token);
+ }, 300),
+ // Throttle completion requests
+ provideCompletionItem: throttle(
+ async (document, position, context, token, next) => {
+ // Only trigger completion on specific characters
+ const triggerCharacters = [".", ",", "(", " "];
+ if (
+ context.triggerKind === 1 &&
+ !triggerCharacters.includes(context.triggerCharacter || "")
+ ) {
+ return { items: [] }; // Return empty for non-trigger characters
+ }
+ return next(document, position, context, token);
+ },
+ 200
+ ),
+ },
// disable the default error handler
errorHandler: {
error: (error, message, count) => {
@@ -163,6 +195,8 @@ const createLanguageClient = async (): Promise<MonacoLanguageClient> => {
writer,
},
});
+
+ return client;
};
const createWebSocketAndStartClient = (): {
@@ -218,16 +252,6 @@ export const initializeLSPClient = () => {
return job;
};
-export const useLSPClient = () => {
- const { client } = state;
- if (!client) {
- throw new Error(
- "Unexpected `useLSPClient` call before lsp client initialized"
- );
- }
- return client;
-};
-
export const executeCommand = async (
client: MonacoLanguageClient,
command: string,
diff --git a/frontend/src/components/MonacoEditor/text-model.ts b/frontend/src/components/MonacoEditor/text-model.ts
index b97816d305..bee385126d 100644
--- a/frontend/src/components/MonacoEditor/text-model.ts
+++ b/frontend/src/components/MonacoEditor/text-model.ts
@@ -1,3 +1,4 @@
+import { debounce } from "lodash-es";
import type * as MonacoType from "monaco-editor";
import { isRef, markRaw, ref, shallowRef, unref, watch } from "vue";
import type { Language, MaybeRef } from "@/types";
@@ -64,12 +65,32 @@ export const useMonacoTextModel = (
{ immediate: true }
);
+ // Debounced content sync to reduce excessive model updates
+ const debouncedUpdateModel = debounce(
+ (model: MonacoType.editor.ITextModel, content: string) => {
+ if (model.getValue() === content) return;
+ model.setValue(content);
+ },
+ 50
+ );
+
watch(
[model, () => unref(content)],
([model, content]) => {
if (!model) return;
if (model.getValue() === content) return;
- model.setValue(content);
+
+ // For significant content changes or initial loads, update immediately
+ const currentValue = model.getValue();
+ if (
+ currentValue === "" ||
+ Math.abs(content.length - currentValue.length) > 100
+ ) {
+ model.setValue(content);
+ } else {
+ // For minor edits, use debounced update
+ debouncedUpdateModel(model, content);
+ }
},
{ immediate: true }
);
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.ts
index 7c1d2c3a98..2c9a1cbc61 100644
--- a/frontend/src/store/modules/sqlEditor/tab.ts
+++ b/frontend/src/store/modules/sqlEditor/tab.ts
@@ -421,14 +421,14 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
persistentTab
);
},
- { deep: true, immediate, throttle: 100, trailing: true }
+ { 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: 100, trailing: true }
+ { deep: true, immediate, throttle: 300, trailing: true } // Increased to 300ms for better performance
);
};
// Load tabs session from localStorage
diff --git a/frontend/src/utils/performance.ts b/frontend/src/utils/performance.ts
new file mode 100644
index 0000000000..31be356529
--- /dev/null
+++ b/frontend/src/utils/performance.ts
@@ -0,0 +1,24 @@
+/**
+ * Performance utilities for SQL Editor optimizations
+ */
+import { debounce } from "lodash-es";
+
+/**
+ * Optimized content change handler for Monaco Editor
+ */
+export const createOptimizedContentHandler = (
+ onContentChange: (content: string) => void,
+ onImmediate?: (content: string) => void
+) => {
+ const debouncedHandler = debounce(onContentChange, 150);
+
+ return (content: string) => {
+ // Call immediate handler for UI responsiveness if provided
+ if (onImmediate) {
+ onImmediate(content);
+ }
+
+ // Debounce the heavy operations
+ debouncedHandler(content);
+ };
+};
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
index 93f28760db..fbe32afd73 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
@@ -67,6 +67,7 @@ import {
useInstanceV1EditorLanguage,
instanceV1AllowsExplain,
} from "@/utils";
+import { createOptimizedContentHandler } from "@/utils/performance";
import { useSQLEditorContext } from "../../context";
import UploadFileButton from "./UploadFileButton.vue";
import { activeSQLEditorRef } from "./state";
@@ -116,24 +117,34 @@ const filename = computed(() => {
return `${name}.${ext}`;
});
-const handleUpdateStatement = (value: string) => {
- // When we are switching between tabs, the MonacoEditor emits a 'change'
- // event, but we shouldn't update the current tab;
- if (isSwitchingTab.value) {
- return;
- }
- const tab = currentTab.value;
- if (!tab) {
- return;
- }
- if (value === tab.statement) {
- return;
+// Optimized content handler using performance utilities
+const handleUpdateStatement = createOptimizedContentHandler(
+ // Heavy operation (debounced)
+ (value: string) => {
+ const tab = currentTab.value;
+ if (!tab || value === tab.statement) {
+ return;
+ }
+ tabStore.updateCurrentTab({
+ statement: value,
+ status: "DIRTY",
+ });
+ },
+ // Immediate operation for UI responsiveness
+ (value: string) => {
+ // When we are switching between tabs, the MonacoEditor emits a 'change'
+ // event, but we shouldn't update the current tab;
+ if (isSwitchingTab.value) {
+ return;
+ }
+ const tab = currentTab.value;
+ if (!tab || value === tab.statement) {
+ return;
+ }
+ // Directly update the reactive tab for immediate UI feedback
+ tab.statement = value;
}
- tabStore.updateCurrentTab({
- statement: value,
- status: "DIRTY",
- });
-};
+);
const handleUpdateSelectedStatement = (value: string) => {
tabStore.updateCurrentTab({
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
index e95ec12902..953e2f0f28 100644
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
@@ -28,6 +28,7 @@
</template>
<script lang="ts" setup>
+import { debounce } from "lodash-es";
import type { editor as Editor, IDisposable } from "monaco-editor";
import * as monaco from "monaco-editor";
import { storeToRefs } from "pinia";
@@ -104,6 +105,11 @@ const getLineNumber = (lineNumber: number) => {
return "->";
};
+// Debounced version for better performance
+const debouncedEmitUpdate = debounce((value: string) => {
+ emit("update:content", value);
+}, 100);
+
const handleChange = (value: string) => {
// When we are switching between tabs, the MonacoEditor emits a 'change'
// event, but we shouldn't update the current tab;
@@ -111,7 +117,8 @@ const handleChange = (value: string) => {
return;
}
- emit("update:content", value);
+ // Use debounced emit to reduce excessive updates
+ debouncedEmitUpdate(value);
};
const execute = (explain = false) => {