Skip to content

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

chore: sql editor fix and optimize (#17482)

ecmadao68fa6f5d2c8f
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 43690f262a..1be4d594fc 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -226,7 +226,6 @@
"n-rows": "{n} rows"
},
"back-to-workspace": "Back to workspace",
- "override": "Override",
"encoding": "Encoding",
"finish": "Finish",
"title": "Title",
@@ -2106,7 +2105,6 @@
"manage-connections": "Manage connections",
"view-detail": "View detail",
"generate-sql": "Generate SQL",
- "current-editing-statement-is-not-empty": "Current editing statement is not empty.",
"run-anyway": "Run anyway",
"no-project": {
"not-member-of-any-projects": "You are not any member of any projects.",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 149bac1ab4..a761289193 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -226,7 +226,6 @@
"n-rows": "{n} filas"
},
"back-to-workspace": "Volver al espacio de trabajo",
- "override": "Anular",
"encoding": "Codificación",
"finish": "Finalizar",
"title": "Título",
@@ -2106,7 +2105,6 @@
"manage-connections": "Gestionar las conexiones",
"view-detail": "Ver detalle",
"generate-sql": "Generar SQL",
- "current-editing-statement-is-not-empty": "La declaración de edición actual no está vacía.",
"run-anyway": "Corre de todos modos",
"no-project": {
"not-member-of-any-projects": "No eres miembro de ningún proyecto.",
@@ -2925,4 +2923,4 @@
"last-visit": "Última visita",
"changelog-for-version": "Registro de cambios para {version}"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 4fe85679cb..7dca31748f 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -226,7 +226,6 @@
"n-rows": "{n} 行"
},
"back-to-workspace": "ワークスペースに戻る",
- "override": "オーバーライド",
"encoding": "エンコーディング",
"finish": "仕上げる",
"title": "タイトル",
@@ -2106,7 +2105,6 @@
"manage-connections": "接続を管理する",
"view-detail": "詳細を見る",
"generate-sql": "SQLの生成",
- "current-editing-statement-is-not-empty": "現在編集中のステートメントは空ではありません。",
"run-anyway": "とにかく走ってください",
"no-project": {
"not-member-of-any-projects": "あなたはどのプロジェクトのメンバーでもありません。",
@@ -2925,4 +2923,4 @@
"last-visit": "最終訪問",
"changelog-for-version": "{version} の変更履歴"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 56ded94025..af5260ceaf 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -226,7 +226,6 @@
"n-rows": "{n} dòng"
},
"back-to-workspace": "Quay lại không gian làm việc",
- "override": "Ghi đè",
"encoding": "Mã hóa",
"finish": "Hoàn tất",
"title": "Tiêu đề",
@@ -2106,7 +2105,6 @@
"manage-connections": "Quản lý kết nối",
"view-detail": "Xem chi tiết",
"generate-sql": "Tạo SQL",
- "current-editing-statement-is-not-empty": "Câu lệnh đang chỉnh sửa hiện tại không trống.",
"run-anyway": "Vẫn chạy",
"no-project": {
"not-member-of-any-projects": "Bạn không phải là thành viên của bất kỳ dự án nào.",
@@ -2925,4 +2923,4 @@
"last-visit": "Lần truy cập cuối",
"changelog-for-version": "Nhật ký thay đổi cho phiên bản {version}"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index bfb2d4ce64..a80fa4b981 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -226,7 +226,6 @@
"n-rows": "{n} 行"
},
"back-to-workspace": "返回工作空间",
- "override": "覆盖",
"encoding": "编码",
"finish": "完成",
"title": "标题",
@@ -2106,7 +2105,6 @@
"manage-connections": "管理连接",
"view-detail": "查看详情",
"generate-sql": "生成 SQL",
- "current-editing-statement-is-not-empty": "当前编辑中的语句不为空。",
"run-anyway": "仍要运行",
"no-project": {
"not-member-of-any-projects": "你不是任何项目的成员。",
@@ -2925,4 +2923,4 @@
"last-visit": "上次访问",
"changelog-for-version": "{version} 的更新日志"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
index 056ac54cf7..7117f4af59 100644
--- a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
@@ -68,9 +68,8 @@
import { useDebounceFn } from "@vueuse/core";
import dayjs from "dayjs";
import { escape } from "lodash-es";
-import * as monaco from "monaco-editor";
import { NButton } from "naive-ui";
-import { computed, reactive, watch, nextTick } from "vue";
+import { computed, reactive, watch } from "vue";
import MaskSpinner from "@/components/misc/MaskSpinner.vue";
import { SearchBox } from "@/components/v2";
import { CopyButton } from "@/components/v2";
@@ -80,13 +79,10 @@ import {
useSQLEditorStore,
type QueryHistoryFilter,
} from "@/store";
-import {
- DEBOUNCE_SEARCH_DELAY,
- getDateForPbTimestampProtoEs,
- type SQLEditorTab,
-} from "@/types";
+import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";
import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
import { getHighlightHTMLByKeyWords } from "@/utils";
+import { useSQLEditorContext } from "@/views/sql-editor/context";
interface State {
search: string;
@@ -96,6 +92,7 @@ interface State {
const tabStore = useSQLEditorTabStore();
const editorStore = useSQLEditorStore();
const queryHistoryStore = useSQLEditorQueryHistoryStore();
+const { events: editorEvents } = useSQLEditorContext();
const state = reactive<State>({
search: "",
@@ -155,13 +152,15 @@ const titleOfQueryHistory = (history: QueryHistory) => {
);
};
-const handleQueryHistoryClick = async (queryHistory: QueryHistory) => {
+const handleQueryHistoryClick = (queryHistory: QueryHistory) => {
const { statement } = queryHistory;
-
- // Open a new tab with the connection and statement.
- const tab = tabStore.currentTab;
-
- const openInNewTab = () => {
+ if (tabStore.currentTab) {
+ editorEvents.emit("append-editor-content", {
+ content: statement,
+ select: true,
+ });
+ } else {
+ // Open a new tab with the connection and statement.
tabStore.addTab(
{
title: `Query history at ${titleOfQueryHistory(queryHistory)}`,
@@ -169,35 +168,6 @@ const handleQueryHistoryClick = async (queryHistory: QueryHistory) => {
},
/* beside */ true
);
- };
- const openInCurrentTab = async (tab: SQLEditorTab) => {
- const newStatement = [tab.statement, statement]
- .filter((s) => s)
- .join("\n\n");
- const selection = new monaco.Selection(
- tab.statement.split("\n").length + 1,
- 0,
- newStatement.split("\n").length + 1,
- 0
- );
- tabStore.updateCurrentTab({
- statement: newStatement,
- });
-
- nextTick(() => {
- tabStore.updateCurrentTab({
- editorState: {
- ...tab.editorState,
- selection: selection,
- },
- });
- });
- };
-
- if (tab) {
- openInCurrentTab(tab);
- } else {
- openInNewTab();
}
};
</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
index ba3a70050f..f559a7256e 100644
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
@@ -11,8 +11,8 @@ import {
LinkIcon,
SquarePenIcon,
} from "lucide-vue-next";
-import { NButton, useDialog, type DropdownOption } from "naive-ui";
-import { computed, h, nextTick, ref } from "vue";
+import { type DropdownOption } from "naive-ui";
+import { computed, nextTick, ref } from "vue";
import { useRouter } from "vue-router";
import { TableIcon } from "@/components/Icon";
import formatSQL from "@/components/MonacoEditor/sqlFormatter";
@@ -42,7 +42,6 @@ import { GetSchemaStringRequest_ObjectType } from "@/types/proto-es/v1/database_
import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";
import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
import {
- defer,
extractInstanceResourceName,
extractProjectResourceName,
generateSimpleDeleteStatement,
@@ -58,7 +57,7 @@ import {
} from "@/utils";
import { keyWithPosition } from "../../EditorCommon";
import { useCurrentTabViewStateContext } from "../../EditorPanel";
-import { useSQLEditorContext } from "../../context";
+import { useSQLEditorContext, type SQLEditorEvents } from "../../context";
import type { NodeTarget, NodeType, TreeNode } from "./tree";
import { readableTextForNodeTarget } from "./tree";
@@ -67,64 +66,6 @@ type DropdownOptionWithTreeNode = DropdownOption & {
};
const SELECT_ALL_LIMIT = 50; // default pagesize of SQL Editor
-const confirmOverrideStatement = async (
- $d: ReturnType<typeof useDialog>,
- _statement: string
-): Promise<"CANCEL" | "OVERRIDE" | "COPY"> => {
- const { currentTab } = useSQLEditorTabStore();
- if (!currentTab) {
- return Promise.resolve("CANCEL");
- }
- if (currentTab.statement.trim().length === 0) {
- return Promise.resolve("OVERRIDE");
- }
-
- const d = defer<"CANCEL" | "OVERRIDE" | "COPY">();
- const dialog = $d.warning({
- title: t("common.warning"),
- content: t("sql-editor.current-editing-statement-is-not-empty"),
- contentClass: "whitespace-pre-wrap",
- style: "z-index: 100000",
- closable: false,
- closeOnEsc: false,
- maskClosable: false,
- action: () => {
- const buttons = [
- h(
- NButton,
- { size: "small", onClick: () => d.resolve("CANCEL") },
- { default: () => t("common.cancel") }
- ),
- h(
- NButton,
- {
- size: "small",
- type: "warning",
- onClick: () => d.resolve("OVERRIDE"),
- },
- { default: () => t("common.override") }
- ),
- h(
- NButton,
- {
- size: "small",
- type: "primary",
- onClick: () => d.resolve("COPY"),
- },
- { default: () => t("common.copy") }
- ),
- ];
- return h(
- "div",
- { class: "flex items-center justify-end gap-2" },
- buttons
- );
- },
- });
- d.promise.then(() => dialog.destroy());
- return d.promise;
-};
-
export const useActions = () => {
const { updateViewState, viewState: currentTabViewState } =
useCurrentTabViewStateContext();
@@ -289,7 +230,6 @@ export const useDropdown = () => {
const { availableActions } = useCurrentTabViewStateContext();
const { events: editorEvents, schemaViewer } = useSQLEditorContext();
const { selectAllFromTableOrView, viewDetail, openNewTab } = useActions();
- const $d = useDialog();
const show = ref(false);
const position = ref<Position>({
@@ -463,7 +403,7 @@ export const useDropdown = () => {
),
engine
);
- applyContentToCurrentTabOrCopyToClipboard(statement, $d);
+ applyContentToCurrentTabOrCopyToClipboard(statement, editorEvents);
},
});
if (type === "table") {
@@ -484,7 +424,10 @@ export const useDropdown = () => {
generateSimpleInsertStatement(engine, schema, table, columns),
engine
);
- applyContentToCurrentTabOrCopyToClipboard(statement, $d);
+ applyContentToCurrentTabOrCopyToClipboard(
+ statement,
+ editorEvents
+ );
},
});
generateSQLChildren.push({
@@ -496,7 +439,10 @@ export const useDropdown = () => {
generateSimpleUpdateStatement(engine, schema, table, columns),
engine
);
- applyContentToCurrentTabOrCopyToClipboard(statement, $d);
+ applyContentToCurrentTabOrCopyToClipboard(
+ statement,
+ editorEvents
+ );
},
});
generateSQLChildren.push({
@@ -508,7 +454,10 @@ export const useDropdown = () => {
generateSimpleDeleteStatement(engine, schema, table),
engine
);
- applyContentToCurrentTabOrCopyToClipboard(statement, $d);
+ applyContentToCurrentTabOrCopyToClipboard(
+ statement,
+ editorEvents
+ );
},
});
}
@@ -604,31 +553,20 @@ const targetSupportsGenerateSQL = (target: NodeTarget) => {
const applyContentToCurrentTabOrCopyToClipboard = async (
content: string,
- $d: ReturnType<typeof useDialog>
+ editorEvents: SQLEditorEvents
) => {
const tabStore = useSQLEditorTabStore();
+
const tab = tabStore.currentTab;
if (!tab) {
copyToClipboard(content);
return;
}
- if (tab.statement.trim().length === 0) {
- tabStore.updateCurrentTab({
- statement: content,
- });
- return;
- }
- const choice = await confirmOverrideStatement($d, content);
- if (choice === "CANCEL") {
- return;
- }
- if (choice === "OVERRIDE") {
- tabStore.updateCurrentTab({
- statement: content,
- });
- return;
- }
- copyToClipboard(content);
+
+ editorEvents.emit("append-editor-content", {
+ content: content,
+ select: true,
+ });
};
const copyToClipboard = (content: string) => {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue
index 26eb82be66..497a1a96ef 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/AdviceItem.vue
@@ -27,6 +27,7 @@
<script setup lang="ts">
import { CircleAlertIcon } from "lucide-vue-next";
+import { Selection } from "monaco-editor";
import { NButton } from "naive-ui";
import { computed } from "vue";
import { positionWithOffset } from "@/components/MonacoEditor/utils";
@@ -71,9 +72,9 @@ const position = computed(() => {
const doScroll = () => {
const { startLine, startColumn, endLine, endColumn } = position.value;
- editorEvents.emit("set-editor-selection", {
- start: { line: startLine, column: startColumn },
- end: { line: endLine, column: endColumn },
- });
+ editorEvents.emit(
+ "set-editor-selection",
+ new Selection(startLine, startColumn, endLine, endColumn)
+ );
};
</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
index cfab799f21..9b9557880e 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
@@ -33,9 +33,10 @@
<script lang="ts" setup>
import { type IDisposable } from "monaco-editor";
+import { type IRange, Selection } from "monaco-editor";
import { storeToRefs } from "pinia";
import { v1 as uuidv1 } from "uuid";
-import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
+import { computed, onBeforeUnmount, ref, watch, nextTick } from "vue";
import type {
AdviceOption,
IStandaloneCodeEditor,
@@ -86,11 +87,7 @@ const {
} = useSQLEditorContext();
const { currentTab, isSwitchingTab } = storeToRefs(tabStore);
const AIContext = useAIContext();
-const pendingFormatContentCommand = ref(false);
-const pendingSetSelectionCommand = ref<{
- start: { line: number; column: number };
- end?: { line: number; column: number };
-}>();
+
const { events: executeSQLEvents } = useExecuteSQL();
const monacoEditorRef = ref<InstanceType<typeof MonacoEditor>>();
@@ -167,12 +164,14 @@ const getActiveStatement = () => {
};
watch(
- () => tabStore.currentTab?.editorState.selection,
- (selection) => {
- if (!selection || !activeSQLEditorRef.value) {
+ () => currentTab.value?.editorState.selection?.toString(),
+ () => {
+ if (!tabStore.currentTab?.editorState.selection) {
return;
}
- activeSQLEditorRef.value.setSelection(selection);
+ activeSQLEditorRef.value?.setSelection(
+ tabStore.currentTab.editorState.selection
+ );
}
);
@@ -295,41 +294,6 @@ const handleEditorReady = (
{ immediate: true }
);
- watch(
- pendingFormatContentCommand,
- (pending) => {
- if (pending) {
- formatEditorContent(editor, dialect.value);
- nextTick(() => {
- pendingFormatContentCommand.value = false;
- });
- }
- },
- { immediate: true }
- );
-
- watch(
- pendingSetSelectionCommand,
- (range) => {
- if (range) {
- const start = range.start;
- const end = range.end ?? start;
- editor.setSelection({
- startLineNumber: start.line,
- startColumn: start.column,
- endLineNumber: end.line,
- endColumn: end.column,
- });
- editor.revealLineNearTop(start.line);
- editor.focus();
- nextTick(() => {
- pendingSetSelectionCommand.value = undefined;
- });
- }
- },
- { immediate: true }
- );
-
watch(
pendingInsertAtCaret,
() => {
@@ -359,6 +323,7 @@ const handleEditorReady = (
{ immediate: true }
);
};
+
const updateAdvices = (
tab: SQLEditorTab,
params: SQLEditorQueryParams,
@@ -396,6 +361,7 @@ const updateAdvices = (
};
});
};
+
const handleUploadFile = (content: string) => {
const editor = activeSQLEditorRef.value;
if (!editor) return;
@@ -422,12 +388,43 @@ const handleUploadFile = (content: string) => {
};
useEmitteryEventListener(editorEvents, "format-content", () => {
- pendingFormatContentCommand.value = true;
-});
-useEmitteryEventListener(editorEvents, "set-editor-selection", (range) => {
- pendingSetSelectionCommand.value = range;
+ if (activeSQLEditorRef.value) {
+ formatEditorContent(activeSQLEditorRef.value, dialect.value);
+ }
});
+useEmitteryEventListener(
+ editorEvents,
+ "set-editor-selection",
+ (selection: IRange) => {
+ activeSQLEditorRef.value?.setSelection(selection);
+ activeSQLEditorRef.value?.revealLineNearTop(selection.startLineNumber);
+ activeSQLEditorRef.value?.focus();
+ }
+);
+
+useEmitteryEventListener(
+ editorEvents,
+ "append-editor-content",
+ ({ content, select }: { content: string; select: boolean }) => {
+ const oldStatement = currentTab.value?.statement ?? "";
+ const newStatement = [oldStatement, content].filter((s) => s).join("\n\n");
+ activeSQLEditorRef.value?.setValue(newStatement);
+
+ if (select) {
+ const selection = new Selection(
+ oldStatement.split("\n").length + 1,
+ 0,
+ newStatement.split("\n").length + 1,
+ 0
+ );
+ nextTick(() => {
+ editorEvents.emit("set-editor-selection", selection);
+ });
+ }
+ }
+);
+
useEmitteryEventListener(
executeSQLEvents,
"update:advices",
diff --git a/frontend/src/views/sql-editor/SQLEditorHomePage.vue b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
index d0461b94ba..971361fc0c 100644
--- a/frontend/src/views/sql-editor/SQLEditorHomePage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
@@ -150,19 +150,15 @@ useEmitteryEventListener(
const editorPanelContext = provideCurrentTabViewStateContext();
-useEmitteryEventListener(
- editorEvents,
- "insert-at-caret",
- async ({ content }) => {
- if (!tabStore.currentTab) return;
- editorPanelContext.updateViewState({
- view: "CODE",
- });
- requestAnimationFrame(() => {
- pendingInsertAtCaret.value = content;
- });
- }
-);
+useEmitteryEventListener(editorEvents, "insert-at-caret", ({ content }) => {
+ if (!tabStore.currentTab) return;
+ editorPanelContext.updateViewState({
+ view: "CODE",
+ });
+ requestAnimationFrame(() => {
+ pendingInsertAtCaret.value = content;
+ });
+});
</script>
<style lang="postcss">
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
index 6fa16df2fa..4c0eaca97c 100644
--- a/frontend/src/views/sql-editor/context.ts
+++ b/frontend/src/views/sql-editor/context.ts
@@ -1,5 +1,6 @@
import { useLocalStorage } from "@vueuse/core";
import Emittery from "emittery";
+import { type IRange } from "monaco-editor";
import type { InjectionKey, Ref } from "vue";
import { inject, provide, ref } from "vue";
import { useSQLEditorStore } from "@/store";
@@ -12,7 +13,7 @@ export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY";
// 30% by default
export const storedAIPanelSize = useLocalStorage("bb.plugin.ai.panel-size", 30);
-type SQLEditorEvents = Emittery<{
+export type SQLEditorEvents = Emittery<{
"save-sheet": {
tab: SQLEditorTab;
editTitle?: boolean;
@@ -29,10 +30,8 @@ type SQLEditorEvents = Emittery<{
"project-context-ready": {
project: string;
};
- "set-editor-selection": {
- start: { line: number; column: number };
- end?: { line: number; column: number };
- };
+ "set-editor-selection": IRange;
+ "append-editor-content": { content: string; select: boolean };
"insert-at-caret": {
content: string;
};