Skip to content

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

chore: use `MonacoEditor` in issue detail page (#1646)

boojack618885a2f467
diff --git a/frontend/src/components/Issue/IssueTaskStatementPanel.vue b/frontend/src/components/Issue/IssueTaskStatementPanel.vue
index d5e3f6e268..96d83b0327 100644
--- a/frontend/src/components/Issue/IssueTaskStatementPanel.vue
+++ b/frontend/src/components/Issue/IssueTaskStatementPanel.vue
@@ -80,25 +80,29 @@
class="whitespace-pre-wrap mt-2 w-full overflow-hidden"
:class="state.editing ? 'border-t border-x' : 'border-t border-x'"
>
- <EmbeddedMonacoEditor
- :value="state.editing ? state.editStatement : statement"
- :database-list="databaseList"
- :table-list="tableList"
+ <MonacoEditor
+ ref="editorRef"
+ class="w-full h-auto max-h-[360px]"
+ :value="state.editStatement"
:readonly="!state.editing"
- :min-height="
- state.editing ? EDITOR_MIN_HEIGHT.EDITABLE : EDITOR_MIN_HEIGHT.READONLY
- "
- :max-height="EDITOR_MAX_HEIGHT"
@change="onStatementChange"
+ @ready="handleMonacoEditorReady"
/>
</div>
</template>
<script lang="ts">
-import { onMounted, reactive, watch, defineComponent, computed } from "vue";
+import {
+ onMounted,
+ reactive,
+ watch,
+ defineComponent,
+ computed,
+ ref,
+} from "vue";
import { useTableStore, useUIStateStore } from "@/store";
import { useIssueLogic } from "./logic";
-import EmbeddedMonacoEditor from "../MonacoEditor/EmbeddedMonacoEditor.vue";
+import MonacoEditor from "../MonacoEditor/MonacoEditor.vue";
interface LocalState {
editing: boolean;
@@ -109,12 +113,11 @@ const EDITOR_MIN_HEIGHT = {
READONLY: 0, // not limited to keep the UI compact
EDITABLE: 120, // ~= 6 lines, a reasonable size to start writing SQL
};
-const EDITOR_MAX_HEIGHT = 360; // ~= 20 lines, not too high for most screen size
export default defineComponent({
name: "IssueTaskStatementPanel",
components: {
- EmbeddedMonacoEditor,
+ MonacoEditor,
},
props: {
sqlHint: {
@@ -140,6 +143,8 @@ export default defineComponent({
editStatement: statement.value,
});
+ const editorRef = ref<InstanceType<typeof MonacoEditor>>();
+
const formatOnSave = computed({
get: () => uiStateStore.issueFormatStatementOnSave,
set: (value: boolean) =>
@@ -157,7 +162,11 @@ export default defineComponent({
// Reset the edit state after creating the issue.
watch(create, (curNew, prevNew) => {
if (!curNew && prevNew) {
+ if (formatOnSave.value) {
+ editorRef.value?.formatEditorContent();
+ }
state.editing = false;
+ updateEditorHeight();
}
});
@@ -165,12 +174,34 @@ export default defineComponent({
state.editStatement = cur;
});
+ const handleMonacoEditorReady = () => {
+ editorRef.value?.setEditorAutoCompletionContext(
+ databaseList.value,
+ tableList.value
+ );
+
+ updateEditorHeight();
+ };
+
+ const updateEditorHeight = () => {
+ const contentHeight =
+ editorRef.value?.editorInstance?.getContentHeight() as number;
+ let actualHeight = contentHeight;
+ if (state.editing && actualHeight < EDITOR_MIN_HEIGHT.EDITABLE) {
+ actualHeight = EDITOR_MIN_HEIGHT.EDITABLE;
+ }
+ editorRef.value?.setEditorContentHeight(actualHeight);
+ };
+
const beginEdit = () => {
state.editStatement = statement.value;
state.editing = true;
};
const saveEdit = () => {
+ if (formatOnSave.value) {
+ editorRef.value?.formatEditorContent();
+ }
updateStatement(state.editStatement, () => {
state.editing = false;
});
@@ -188,25 +219,25 @@ export default defineComponent({
// time the user types.
updateStatement(state.editStatement);
}
+
+ updateEditorHeight();
};
return {
create,
allowEditStatement,
statement,
- databaseList,
- tableList,
- updateStatement,
allowApplyStatementToOtherStages,
- applyStatementToOtherStages,
formatOnSave,
state,
+ editorRef,
+ updateStatement,
+ applyStatementToOtherStages,
beginEdit,
saveEdit,
cancelEdit,
onStatementChange,
- EDITOR_MIN_HEIGHT,
- EDITOR_MAX_HEIGHT,
+ handleMonacoEditorReady,
};
},
});
diff --git a/frontend/src/components/MonacoEditor/EmbeddedMonacoEditor.vue b/frontend/src/components/MonacoEditor/EmbeddedMonacoEditor.vue
deleted file mode 100644
index f27187d270..0000000000
--- a/frontend/src/components/MonacoEditor/EmbeddedMonacoEditor.vue
+++ /dev/null
@@ -1,206 +0,0 @@
-<template>
- <div ref="editorRef" class="w-full overflow-hidden"></div>
-</template>
-
-<script lang="ts" setup>
-import {
- onMounted,
- ref,
- toRef,
- toRaw,
- nextTick,
- onUnmounted,
- watch,
- PropType,
-} from "vue";
-import { editor as Editor } from "monaco-editor";
-import { Database, SQLDialect, Table } from "@/types";
-import { useMonaco } from "./useMonaco";
-import { useLineDecorations } from "./lineDecorations";
-
-const props = defineProps({
- value: {
- type: String,
- required: true,
- },
- language: {
- type: String,
- default: "mysql",
- },
- readonly: {
- type: Boolean,
- default: false,
- },
- databaseList: {
- type: Array as PropType<Database[]>,
- default: () => [],
- },
- tableList: {
- type: Array as PropType<Table[]>,
- default: () => [],
- },
- minHeight: {
- type: Number,
- default: 0,
- },
- maxHeight: {
- type: Number,
- default: 0,
- },
-});
-
-const emit = defineEmits<{
- (e: "change", content: string): void;
-}>();
-
-const editorRef = ref();
-const statement = toRef(props, "value");
-const language = toRef(props, "language");
-const readonly = toRef(props, "readonly");
-
-let editorInstance: Editor.IStandaloneCodeEditor;
-
-const {
- monaco,
- formatContent,
- setAutoCompletionContext,
- setPositionAtEndOfLine,
-} = await useMonaco(language.value);
-
-const init = async () => {
- const model = monaco.editor.createModel(
- statement.value,
- toRaw(language.value)
- );
-
- editorInstance = monaco.editor.create(editorRef.value, {
- model,
- tabSize: 2,
- insertSpaces: true,
- autoClosingQuotes: "always",
- detectIndentation: false,
- folding: false,
- automaticLayout: true,
- theme: "vs-light",
- minimap: {
- enabled: false,
- },
- wordWrap: "on",
- fixedOverflowWidgets: true,
- scrollBeyondLastLine: false,
- });
-
- // add format sql action in context menu
- editorInstance.addAction({
- id: "FormatSQL",
- label: "Format SQL",
- keybindings: [
- monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF,
- ],
- contextMenuGroupId: "operation",
- contextMenuOrder: 1,
- run: () => {
- if (readonly.value) {
- return;
- }
- formatContent(editorInstance, language.value as SQLDialect);
- nextTick(() => setPositionAtEndOfLine(editorInstance));
- },
- });
-
- // typed something, change the text
- editorInstance.onDidChangeModelContent(() => {
- const value = editorInstance.getValue();
- emit("change", value);
- });
-
- editorInstance.onDidChangeCursorPosition((e) => {
- const { defineLineDecorations, disposeLineDecorations } =
- useLineDecorations(editorInstance, e.position);
- // clear the old decorations
- disposeLineDecorations();
-
- // define the new decorations
- nextTick(() => {
- defineLineDecorations();
- });
- });
-
- // set the editor's autoComplete context
- watch(
- [() => props.databaseList, () => props.tableList],
- ([databaseList, tableList]) => {
- setAutoCompletionContext(databaseList, tableList);
- },
- {
- immediate: true,
- }
- );
-
- // set the editor focus when the tab is selected
- if (!readonly.value) {
- editorInstance.focus();
-
- nextTick(() => setPositionAtEndOfLine(editorInstance));
- }
-
- watch(
- () => readonly.value,
- (readOnly) => {
- if (editorInstance) {
- editorInstance.updateOptions({
- readOnly,
- renderLineHighlight: readOnly ? "none" : "line",
- });
- if (!readOnly) {
- editorInstance.focus();
- nextTick(() => setPositionAtEndOfLine(editorInstance));
- }
- }
- },
- {
- immediate: true,
- }
- );
-
- const fitSize = () => {
- const container = editorRef.value;
- if (!container) return;
-
- const contentHeight = editorInstance.getContentHeight();
- let actualHeight = contentHeight;
- if (props.minHeight > 0 && actualHeight < props.minHeight) {
- actualHeight = props.minHeight;
- }
- if (props.maxHeight > 0 && actualHeight > props.maxHeight) {
- actualHeight = props.maxHeight;
- }
- container.style.height = `${actualHeight}px`;
- };
-
- watch(statement, (statement) => {
- if (statement !== model.getValue()) {
- model.setValue(statement);
- }
- requestAnimationFrame(fitSize);
- });
-
- fitSize();
-};
-
-onMounted(() => {
- init();
-});
-
-onUnmounted(() => {
- editorInstance.dispose();
-});
-</script>
-
-<style>
-.monaco-editor .cldr.sql-fragment {
- @apply bg-indigo-600;
- width: 3px !important;
- margin-left: 2px;
-}
-</style>
diff --git a/frontend/src/components/MonacoEditor/MonacoEditor.vue b/frontend/src/components/MonacoEditor/MonacoEditor.vue
index 5e8977e750..49deefbcf5 100644
--- a/frontend/src/components/MonacoEditor/MonacoEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoEditor.vue
@@ -1,5 +1,5 @@
<template>
- <div ref="editorContainerRef" style="width: 100%; height: 100%"></div>
+ <div ref="editorContainerRef"></div>
</template>
<script lang="ts" setup>
@@ -34,16 +34,8 @@ const props = defineProps({
});
const emit = defineEmits<{
- (e: "update:value", content: string): void;
(e: "change", content: string): void;
(e: "change-selection", content: string): void;
- (
- e: "run-query",
- content: {
- explain: boolean;
- query: string;
- }
- ): void;
(e: "save", content: string): void;
(e: "ready"): void;
}>();
@@ -52,7 +44,7 @@ const sqlCode = toRef(props, "value");
const language = toRef(props, "language");
const readOnly = toRef(props, "readonly");
const monacoInstanceRef = ref();
-const editorContainerRef = ref();
+const editorContainerRef = ref<HTMLDivElement>();
// use shallowRef to avoid deep conversion which will cause page crash.
const editorInstanceRef = shallowRef<Editor.IStandaloneCodeEditor>();
@@ -86,44 +78,9 @@ const getEditorInstance = () => {
codeLens: false,
});
- // add the run query action in context menu
+ // add `Format SQL` action into context menu
editorInstance.addAction({
- id: "RunQuery",
- label: "Run Query",
- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
- contextMenuGroupId: "operation",
- contextMenuOrder: 0,
- run: async () => {
- const typedValue = editorInstance.getValue();
- const selectedValue = editorInstance
- .getModel()
- ?.getValueInRange(editorInstance.getSelection()!) as string;
- const query = selectedValue || typedValue;
- emit("run-query", { explain: false, query });
- },
- });
-
- // add the run query action in context menu
- editorInstance.addAction({
- id: "ExplainQuery",
- label: "Explain Query",
- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],
- contextMenuGroupId: "operation",
- contextMenuOrder: 0,
- run: async () => {
- const typedValue = editorInstance.getValue();
- const selectedValue = editorInstance
- .getModel()
- ?.getValueInRange(editorInstance.getSelection()!) as string;
-
- const query = selectedValue || typedValue;
- emit("run-query", { explain: true, query });
- },
- });
-
- // add format sql action in context menu
- editorInstance.addAction({
- id: "FormatSQL",
+ id: "format-sql",
label: "Format SQL",
keybindings: [
monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF,
@@ -233,7 +190,16 @@ const getEditorContentHeight = () => {
return editorInstanceRef.value?.getContentHeight();
};
+const setEditorContentHeight = (height: number) => {
+ editorContainerRef.value!.style.height = `${
+ height ?? getEditorContentHeight()
+ }px`;
+};
+
const formatEditorContent = () => {
+ if (readOnly.value) {
+ return;
+ }
monacoInstanceRef.value?.formatContent(
editorInstanceRef.value!,
language.value as SQLDialect
@@ -252,10 +218,12 @@ const setEditorAutoCompletionContext = (
};
defineExpose({
+ editorInstance: editorInstanceRef,
formatEditorContent,
getEditorContent,
setEditorContent,
getEditorContentHeight,
+ setEditorContentHeight,
setEditorAutoCompletionContext,
});
</script>
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 2c0c755d5a..140cd740ad 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -44,6 +44,7 @@ const useExecuteSQL = () => {
};
const execute = async (
+ query: string,
config: ExecuteConfig,
option?: Partial<ExecuteOption>
) => {
@@ -51,24 +52,19 @@ const useExecuteSQL = () => {
notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));
}
- const currentTab = tabStore.currentTab;
const isDisconnected = sqlEditorStore.isDisconnected;
- const statement = currentTab.statement;
- const selectedStatement = currentTab.selectedStatement;
- const sqlStatement = selectedStatement || statement;
-
if (isDisconnected) {
notify("CRITICAL", t("sql-editor.select-connection"));
return;
}
- const { data } = parseSQL(sqlStatement);
-
- if (isEmpty(sqlStatement)) {
+ if (isEmpty(query)) {
notify("CRITICAL", t("sql-editor.notify-empty-statement"));
return;
}
+ const { data } = parseSQL(query);
+
if (data === undefined) {
notify("CRITICAL", t("sql-editor.notify-invalid-sql-statement"));
return;
@@ -101,7 +97,7 @@ const useExecuteSQL = () => {
}
let selectStatement =
- data !== null ? transformSQL(data, config.databaseType) : sqlStatement;
+ data !== null ? transformSQL(data, config.databaseType) : query;
if (option?.explain) {
selectStatement = `EXPLAIN ${selectStatement}`;
}
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue b/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue
index 6b3992eaf8..0b0bf8d6c0 100644
--- a/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/EditorAction.vue
@@ -159,11 +159,23 @@ const hasReadonlyDataSource = computed(() => {
const { execute, state: executeState } = useExecuteSQL();
const handleRunQuery = async () => {
- await execute({ databaseType: selectedInstanceEngine.value });
+ const currentTab = tabStore.currentTab;
+ const statement = currentTab.statement;
+ const selectedStatement = currentTab.selectedStatement;
+ const query = selectedStatement || statement;
+ await execute(query, { databaseType: selectedInstanceEngine.value });
};
const handleExplainQuery = () => {
- execute({ databaseType: selectedInstanceEngine.value }, { explain: true });
+ const currentTab = tabStore.currentTab;
+ const statement = currentTab.statement;
+ const selectedStatement = currentTab.selectedStatement;
+ const query = selectedStatement || statement;
+ execute(
+ query,
+ { databaseType: selectedInstanceEngine.value },
+ { explain: true }
+ );
};
const gotoInstanceDetailPage = () => {
diff --git a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
index 1c39f0f3ec..87b4d7bea8 100644
--- a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue
@@ -5,19 +5,21 @@
<MonacoEditor
ref="editorRef"
v-model:value="sqlCode"
+ class="w-full h-full"
:language="selectedLanguage"
:readonly="readonly"
@change="handleChange"
@change-selection="handleChangeSelection"
- @run-query="handleRunQuery"
@save="handleSaveSheet"
+ @ready="handleEditorReady"
/>
</div>
</template>
<script lang="ts" setup>
import { debounce } from "lodash-es";
-import { computed, defineEmits, ref, watch } from "vue";
+import { computed, defineEmits, ref, watch, watchEffect } from "vue";
+import * as monaco from "monaco-editor";
import {
useInstanceStore,
useTabStore,
@@ -64,22 +66,6 @@ const selectedLanguage = computed(() => {
});
const readonly = computed(() => sheetStore.isReadOnly);
-watch(
- () => selectedInstance.value,
- () => {
- if (selectedInstance.value) {
- const databaseList = databaseStore.getDatabaseListByInstanceId(
- selectedInstance.value.id
- );
- const tableList = databaseList
- .map((item) => tableStore.getTableListByDatabaseId(item.id))
- .flat();
-
- editorRef.value?.setEditorAutoCompletionContext(databaseList, tableList);
- }
- }
-);
-
watch(
() => sqlEditorStore.shouldSetContent,
() => {
@@ -113,17 +99,62 @@ const handleChangeSelection = debounce((value: string) => {
});
}, 300);
-const handleRunQuery = async ({
- explain,
- query,
-}: {
- explain: boolean;
- query: string;
-}) => {
- await execute({ databaseType: selectedInstanceEngine.value }, { explain });
-};
-
const handleSaveSheet = () => {
emit("save-sheet");
};
+
+const handleEditorReady = () => {
+ editorRef.value?.editorInstance?.addAction({
+ id: "RunQuery",
+ label: "Run Query",
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],
+ contextMenuGroupId: "operation",
+ contextMenuOrder: 0,
+ run: async () => {
+ const typedValue = editorRef.value?.editorInstance?.getValue();
+ const selectedValue = editorRef.value?.editorInstance
+ ?.getModel()
+ ?.getValueInRange(
+ editorRef.value?.editorInstance?.getSelection() as any
+ ) as string;
+ const query = selectedValue || typedValue || "";
+ await execute(query, { databaseType: selectedInstanceEngine.value });
+ },
+ });
+
+ editorRef.value?.editorInstance?.addAction({
+ id: "ExplainQuery",
+ label: "Explain Query",
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],
+ contextMenuGroupId: "operation",
+ contextMenuOrder: 0,
+ run: async () => {
+ const typedValue = editorRef.value?.editorInstance?.getValue();
+ const selectedValue = editorRef.value?.editorInstance
+ ?.getModel()
+ ?.getValueInRange(
+ editorRef.value?.editorInstance?.getSelection() as any
+ ) as string;
+ const query = selectedValue || typedValue || "";
+ await execute(
+ query,
+ { databaseType: selectedInstanceEngine.value },
+ { explain: true }
+ );
+ },
+ });
+
+ watchEffect(() => {
+ if (selectedInstance.value) {
+ const databaseList = databaseStore.getDatabaseListByInstanceId(
+ selectedInstance.value.id
+ );
+ const tableList = databaseList
+ .map((item) => tableStore.getTableListByDatabaseId(item.id))
+ .flat();
+
+ editorRef.value?.setEditorAutoCompletionContext(databaseList, tableList);
+ }
+ });
+};
</script>