Skip to content

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

chore(sql-editor): different check behavior for issue and editor mode (#13560)

Liu Ji0cb600955886
diff --git a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
index 1d8613d553..aea456126e 100644
--- a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
@@ -61,6 +61,7 @@ import {
useOptionByKey,
useOptions,
useSelectedContent,
+ useSelection,
useSuggestOptionByLanguage,
useLineHighlights,
useLSPConnectionState,
@@ -74,6 +75,7 @@ import type {
ITextModel,
LineHighlightOption,
MonacoModule,
+ Selection as MonacoSelection,
} from "./types";
const props = withDefaults(
@@ -106,6 +108,7 @@ const props = withDefaults(
const emit = defineEmits<{
(e: "update:content", content: string): void;
(e: "select-content", content: string): void;
+ (e: "update:selection", selection: MonacoSelection | null): void;
(e: "ready", monaco: MonacoModule, editor: IStandaloneCodeEditor): void;
}>();
@@ -165,6 +168,7 @@ onMounted(async () => {
useFormatContent(monaco, editor, toRef(props, "dialect"));
const content = useContent(monaco, editor);
const selectedContent = useSelectedContent(monaco, editor);
+ const selection = useSelection(monaco, editor);
useAdvices(monaco, editor, toRef(props, "advices"));
useLineHighlights(monaco, editor, toRef(props, "lineHighlights"));
useAutoHeight(monaco, editor, containerRef, toRef(props, "autoHeight"));
@@ -189,6 +193,9 @@ onMounted(async () => {
watchEffect(() => {
emit("select-content", selectedContent.value);
});
+ watchEffect(() => {
+ emit("update:selection", selection.value);
+ });
} catch (ex) {
console.error("[MonacoEditor] initialize failed", ex);
}
diff --git a/frontend/src/components/MonacoEditor/composables/index.ts b/frontend/src/components/MonacoEditor/composables/index.ts
index 1c75a24bd7..72c550eabd 100644
--- a/frontend/src/components/MonacoEditor/composables/index.ts
+++ b/frontend/src/components/MonacoEditor/composables/index.ts
@@ -2,6 +2,7 @@ export * from "./useOptions";
export * from "./useModel";
export * from "./useContent";
export * from "./useSelectedContent";
+export * from "./useSelection";
export * from "./useFormatContent";
export * from "./useSuggestOptionByLanguage";
export * from "./useAdvices";
diff --git a/frontend/src/components/MonacoEditor/composables/useSelection.ts b/frontend/src/components/MonacoEditor/composables/useSelection.ts
new file mode 100644
index 0000000000..a7dce15724
--- /dev/null
+++ b/frontend/src/components/MonacoEditor/composables/useSelection.ts
@@ -0,0 +1,26 @@
+import type monaco from "monaco-editor";
+import { shallowRef } from "vue";
+import type { MonacoModule } from "../types";
+
+export const useSelection = (
+ monaco: MonacoModule,
+ editor: monaco.editor.IStandaloneCodeEditor
+) => {
+ const selection = shallowRef<monaco.Selection | null>(getSelection(editor));
+ const update = () => {
+ selection.value = getSelection(editor);
+ };
+
+ editor.onDidChangeCursorSelection(update);
+ editor.onDidChangeModel(update);
+ editor.onDidChangeModelContent(update);
+
+ return selection;
+};
+
+const getSelection = (editor: monaco.editor.IStandaloneCodeEditor) => {
+ const model = editor.getModel();
+ if (!model) return null;
+ const selection = editor.getSelection();
+ return selection;
+};
diff --git a/frontend/src/components/MonacoEditor/types.ts b/frontend/src/components/MonacoEditor/types.ts
index a8de92c229..81ec2d1032 100644
--- a/frontend/src/components/MonacoEditor/types.ts
+++ b/frontend/src/components/MonacoEditor/types.ts
@@ -56,3 +56,5 @@ export const SupportedLanguages: monaco.languages.ILanguageExtensionPoint[] = [
mimetypes: ["application/redis"],
},
];
+
+export type Selection = monaco.Selection;
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 377eeeee13..ebbfdb78d7 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -1,7 +1,9 @@
-import { isEmpty } from "lodash-es";
+import Emittery from "emittery";
+import { head, isEmpty } from "lodash-es";
import { Status } from "nice-grpc-common";
import { markRaw } from "vue";
import { parseSQL } from "@/components/MonacoEditor/sqlParser";
+import { sqlServiceClient } from "@/grpcweb";
import { t } from "@/plugins/i18n";
import {
pushNotification,
@@ -10,28 +12,46 @@ import {
useSQLEditorTabStore,
useSQLStore,
useSQLEditorQueryHistoryStore,
+ useAppFeature,
} from "@/store";
import type {
ComposedDatabase,
SQLResultSetV1,
BBNotificationStyle,
SQLEditorQueryParams,
+ SQLEditorTab,
} from "@/types";
import { isValidDatabaseName } from "@/types";
import {
+ Advice,
Advice_Status,
advice_StatusToJSON,
+ CheckRequest_ChangeType,
} from "@/types/proto/v1/sql_service";
import {
emptySQLEditorTabQueryContext,
hasPermissionToCreateChangeDatabaseIssue,
} from "@/utils";
+import { extractGrpcErrorMessage } from "@/utils/grpcweb";
+
+// SKIP_CHECK_THRESHOLD is the MaxSheetCheckSize in the backend.
+const SKIP_CHECK_THRESHOLD = 1024 * 1024;
+
+const events = new Emittery<{
+ "update:advices": {
+ tab: SQLEditorTab;
+ params: SQLEditorQueryParams;
+ advices: Advice[];
+ };
+}>();
+
+type SQLCheckResult = { passed: boolean; advices?: Advice[] };
const useExecuteSQL = () => {
const databaseStore = useDatabaseV1Store();
const tabStore = useSQLEditorTabStore();
const sqlEditorStore = useSQLEditorStore();
-
+ const sqlCheckStyle = useAppFeature("bb.feature.sql-editor.sql-check-style");
const notify = (
type: BBNotificationStyle,
title: string,
@@ -45,7 +65,7 @@ const useExecuteSQL = () => {
});
};
- const preflight = (params: SQLEditorQueryParams) => {
+ const preflight = async (params: SQLEditorQueryParams) => {
const tab = tabStore.currentTab;
if (!tab) {
return false;
@@ -74,6 +94,67 @@ const useExecuteSQL = () => {
return true;
};
+ const check = async (): Promise<SQLCheckResult> => {
+ const tab = tabStore.currentTab;
+ if (!tab) {
+ return { passed: false };
+ }
+
+ const params = tab.queryContext?.params;
+ const abortController = tab.queryContext?.abortController;
+ if (!params) {
+ return { passed: false };
+ }
+ if (params.statement.length > SKIP_CHECK_THRESHOLD) {
+ return { passed: true };
+ }
+ const response = await sqlServiceClient.check(
+ {
+ name: params.connection.database,
+ statement: params.statement,
+ changeType: CheckRequest_ChangeType.SQL_EDITOR,
+ },
+ {
+ signal: abortController?.signal,
+ }
+ );
+ const { advices } = response;
+ events.emit("update:advices", { tab, params, advices });
+ return { passed: advices.length === 0, advices };
+ };
+
+ const notifyAdvices = (advices: Advice[]) => {
+ let adviceStatus: "SUCCESS" | "ERROR" | "WARNING" = "SUCCESS";
+ let adviceNotifyMessage = "";
+ for (const advice of advices) {
+ if (advice.status === Advice_Status.SUCCESS) {
+ continue;
+ }
+
+ if (advice.status === Advice_Status.ERROR) {
+ adviceStatus = "ERROR";
+ } else if (adviceStatus !== "ERROR") {
+ adviceStatus = "WARNING";
+ }
+
+ adviceNotifyMessage += `${advice_StatusToJSON(advice.status)}: ${
+ advice.title
+ }\n`;
+ if (advice.content) {
+ adviceNotifyMessage += `${advice.content}\n`;
+ }
+ }
+
+ if (adviceStatus !== "SUCCESS") {
+ const notifyStyle = adviceStatus === "ERROR" ? "CRITICAL" : "WARN";
+ notify(
+ notifyStyle,
+ t("sql-editor.sql-review-result"),
+ adviceNotifyMessage
+ );
+ }
+ };
+
const cleanup = () => {
const tab = tabStore.currentTab;
if (!tab) return;
@@ -88,12 +169,13 @@ const useExecuteSQL = () => {
const tab = tabStore.currentTab;
if (!tab) {
- return;
+ return cleanup();
}
const { mode } = tab;
if (mode === "ADMIN") {
- return;
+ return cleanup();
}
+
const queryContext = tab.queryContext!;
const batchQueryContext = tab.batchQueryContext;
const { data } = await parseSQL(params.statement);
@@ -146,10 +228,52 @@ const useExecuteSQL = () => {
allowExport: false,
});
};
+ const abort = (error: string, advices: Advice[] = []) => {
+ fail(batchQueryDatabases[0], {
+ error,
+ results: [],
+ advices,
+ status: Status.ABORTED,
+ allowExport: false,
+ });
+ return cleanup();
+ };
const { abortController } = queryContext;
+
const sqlStore = useSQLStore();
queryContext.beginTimestampMS = Date.now();
+
+ const checkBehavior = params.skipCheck ? "SKIP" : sqlCheckStyle.value;
+ let checkResult: SQLCheckResult = { passed: true };
+ if (checkBehavior !== "SKIP") {
+ try {
+ checkResult = await check();
+ } catch (error) {
+ return abort(extractGrpcErrorMessage(error));
+ }
+ }
+ if (checkBehavior === "PREFLIGHT" && !checkResult.passed) {
+ return abort(
+ head(checkResult.advices)?.content ?? "",
+ checkResult.advices
+ );
+ }
+ if (
+ checkBehavior === "NOTIFICATION" &&
+ !checkResult.passed &&
+ checkResult.advices
+ ) {
+ const { advices } = checkResult;
+ const errorAdvice = advices.find(
+ (advice) => advice.status === Advice_Status.ERROR
+ );
+ if (errorAdvice) {
+ notifyAdvices(advices);
+ return abort(errorAdvice.content);
+ }
+ }
+
for (const database of batchQueryDatabases) {
if (abortController.signal.aborted) {
// Once any one of the batch queries is aborted, don't go further
@@ -196,35 +320,12 @@ const useExecuteSQL = () => {
abortController.signal
);
}
-
- let adviceStatus: "SUCCESS" | "ERROR" | "WARNING" = "SUCCESS";
- let adviceNotifyMessage = "";
- for (const advice of resultSet.advices) {
- if (advice.status === Advice_Status.SUCCESS) {
- continue;
- }
-
- if (advice.status === Advice_Status.ERROR) {
- adviceStatus = "ERROR";
- } else if (adviceStatus !== "ERROR") {
- adviceStatus = "WARNING";
- }
-
- adviceNotifyMessage += `${advice_StatusToJSON(advice.status)}: ${
- advice.title
- }\n`;
- if (advice.content) {
- adviceNotifyMessage += `${advice.content}\n`;
- }
- }
-
- if (adviceStatus !== "SUCCESS") {
- const notifyStyle = adviceStatus === "ERROR" ? "CRITICAL" : "WARN";
- notify(
- notifyStyle,
- t("sql-editor.sql-review-result"),
- adviceNotifyMessage
- );
+ if (checkBehavior === "NOTIFICATION") {
+ const combinedAdvices =
+ resultSet.advices.length > 0
+ ? resultSet.advices
+ : (checkResult.advices ?? []);
+ notifyAdvices(combinedAdvices);
}
if (resultSet.error) {
@@ -262,6 +363,7 @@ const useExecuteSQL = () => {
};
return {
+ events,
execute,
};
};
diff --git a/frontend/src/customAppProfile.ts b/frontend/src/customAppProfile.ts
index b3f3ffce0c..c2043052a7 100644
--- a/frontend/src/customAppProfile.ts
+++ b/frontend/src/customAppProfile.ts
@@ -105,6 +105,7 @@ const overrideAppFeatures = (
"bb.feature.sql-editor.disallow-share-worksheet": true,
"bb.feature.sql-editor.disallow-edit-schema": true,
"bb.feature.sql-editor.hide-advance-instance-features": true,
+ "bb.feature.sql-editor.sql-check-style": "PREFLIGHT"
});
}
};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index d4fde5cad4..f6e6f9b85a 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2473,7 +2473,8 @@
"manage-connections": "Manage connections",
"view-detail": "View detail",
"generate-sql": "Generate SQL",
- "current-editing-statement-is-not-empty": "Current editing statement is not empty."
+ "current-editing-statement-is-not-empty": "Current editing statement is not empty.",
+ "run-anyway": "Run anyway"
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 0a8d3709b7..5c88a45086 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2473,7 +2473,8 @@
"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."
+ "current-editing-statement-is-not-empty": "La declaración de edición actual no está vacía.",
+ "run-anyway": "Corre de todos modos"
},
"schema-editor": {
"self": "Editor de esquema",
@@ -3694,4 +3695,4 @@
"worksheet": {
"self": "Hoja de trabajo"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 301c2a21d8..e2cb4fae33 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2473,7 +2473,8 @@
"manage-connections": "接続を管理する",
"view-detail": "詳細を見る",
"generate-sql": "SQLの生成",
- "current-editing-statement-is-not-empty": "現在編集中のステートメントは空ではありません。"
+ "current-editing-statement-is-not-empty": "現在編集中のステートメントは空ではありません。",
+ "run-anyway": "とにかく走ってください"
},
"schema-editor": {
"self": "スキーマエディタ",
@@ -3694,4 +3695,4 @@
"worksheet": {
"self": "ワークシート"
}
-}
\ No newline at end of file
+}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 7959247b73..7bc217e95e 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2473,7 +2473,8 @@
"manage-connections": "管理连接",
"view-detail": "查看详情",
"generate-sql": "生成 SQL",
- "current-editing-statement-is-not-empty": "当前编辑中的语句不为空。"
+ "current-editing-statement-is-not-empty": "当前编辑中的语句不为空。",
+ "run-anyway": "仍要运行"
},
"schema-editor": {
"self": "Schema 编辑器",
diff --git a/frontend/src/types/appProfile.ts b/frontend/src/types/appProfile.ts
index 0a605dda93..2b896c11d7 100644
--- a/frontend/src/types/appProfile.ts
+++ b/frontend/src/types/appProfile.ts
@@ -44,6 +44,7 @@ export type AppFeatures = {
"bb.feature.sql-editor.hide-projects": boolean;
"bb.feature.sql-editor.hide-environments": boolean;
"bb.feature.sql-editor.hide-advance-instance-features": boolean;
+ "bb.feature.sql-editor.sql-check-style": "PREFLIGHT" | "NOTIFICATION";
};
export type AppProfile = {
@@ -98,5 +99,6 @@ export const defaultAppProfile = (): AppProfile => ({
"bb.feature.sql-editor.hide-projects": false,
"bb.feature.sql-editor.hide-environments": false,
"bb.feature.sql-editor.hide-advance-instance-features": false,
+ "bb.feature.sql-editor.sql-check-style": "NOTIFICATION",
},
});
diff --git a/frontend/src/types/sqlEditor/editor.ts b/frontend/src/types/sqlEditor/editor.ts
index 4d5bcc32d8..0a1831df9f 100644
--- a/frontend/src/types/sqlEditor/editor.ts
+++ b/frontend/src/types/sqlEditor/editor.ts
@@ -72,4 +72,6 @@ export type SQLEditorQueryParams = {
statement: string; // the statement snapshot of the query
engine: Engine;
explain: boolean;
+ selection: monaco.Selection | null;
+ skipCheck?: boolean;
};
diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.ts
index 374ef631c9..afa4370de5 100644
--- a/frontend/src/types/sqlEditor/tab.ts
+++ b/frontend/src/types/sqlEditor/tab.ts
@@ -1,3 +1,7 @@
+import type {
+ AdviceOption,
+ Selection as MonacoSelection,
+} from "@/components/MonacoEditor";
import type { SQLResultSetV1 } from "../v1/sql";
import type { SQLEditorConnection, SQLEditorQueryParams } from "./editor";
@@ -49,6 +53,10 @@ export type SQLEditorTab = {
database: string;
keys: string[];
};
+ editorState: {
+ selection: MonacoSelection | null;
+ advices: AdviceOption[];
+ };
};
export type CoreSQLEditorTab = Pick<
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
index ff98cc052c..9bec12d101 100644
--- a/frontend/src/utils/sqlEditor.ts
+++ b/frontend/src/utils/sqlEditor.ts
@@ -42,6 +42,10 @@ export const defaultSQLEditorTab = (): SQLEditorTab => {
database: UNKNOWN_DATABASE_NAME,
keys: [],
},
+ editorState: {
+ selection: null,
+ advices: [],
+ },
};
};
@@ -173,6 +177,7 @@ export const emptySQLEditorTabQueryContext = (): SQLEditorTabQueryContext => ({
engine: Engine.MYSQL,
explain: false,
statement: "",
+ selection: null,
},
});
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
index 8ad275d787..c8c630351f 100644
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
@@ -680,6 +680,7 @@ const runQuery = async (
connection,
explain: false,
engine: database.instanceResource.engine,
+ selection: tab.editorState.selection,
});
};
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
index 5311b2033f..2f2076ecf7 100644
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
@@ -265,6 +265,7 @@ const handleRunQuery = () => {
connection: { ...tab.connection },
engine: instance.value.engine,
explain: false,
+ selection: tab.editorState.selection,
});
uiStateStore.saveIntroStateByKey({
key: "data.query",
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vue
index c31da9f575..dd7f752d9e 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView.vue
@@ -1,19 +1,69 @@
<template>
<div
- class="text-md font-normal flex items-center gap-x-3"
+ class="text-md font-normal flex flex-col gap-2"
:class="[dark ? 'text-matrix-green-hover' : 'text-control-light']"
>
- <span>{{ error }}</span>
- <slot name="suffix" />
+ <div class="flex items-center gap-3">
+ <span>{{ error }}</span>
+ <slot name="suffix" />
+ </div>
+ <div v-if="viewMode === 'RICH'">
+ <NButton
+ v-if="showRunAnywayButton"
+ size="small"
+ type="primary"
+ @click="runAnyway"
+ >
+ {{ $t("sql-editor.run-anyway") }}
+ </NButton>
+ </div>
</div>
</template>
<script lang="ts" setup>
+import { NButton } from "naive-ui";
+import { computed } from "vue";
+import { useExecuteSQL } from "@/composables/useExecuteSQL";
+import { useAppFeature } from "@/store";
+import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";
+import { Advice_Status } from "@/types/proto/v1/sql_service";
import { useSQLResultViewContext } from "./context";
-defineProps<{
+const props = defineProps<{
error: string | undefined;
+ executeParams?: SQLEditorQueryParams;
+ resultSet?: SQLResultSetV1;
}>();
+const sqlCheckStyle = useAppFeature("bb.feature.sql-editor.sql-check-style");
const { dark } = useSQLResultViewContext();
+const { execute } = useExecuteSQL();
+
+const viewMode = computed((): "SIMPLE" | "RICH" => {
+ if (sqlCheckStyle.value === "PREFLIGHT") {
+ if (!props.executeParams?.skipCheck) {
+ return "RICH";
+ }
+ }
+ return "SIMPLE";
+});
+const showRunAnywayButton = computed(() => {
+ const { resultSet } = props;
+ if (!resultSet) return false;
+ if (
+ resultSet.advices.some((advice) => advice.status === Advice_Status.ERROR)
+ ) {
+ return false;
+ }
+ return true;
+});
+
+const runAnyway = () => {
+ const params = props.executeParams;
+ if (!params) return;
+ execute({
+ ...params,
+ skipCheck: true,
+ });
+};
</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
index 0ad44a93d5..1590ae35c5 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -47,7 +47,11 @@
<EmptyView />
</template>
<template v-else-if="viewMode === 'ERROR'">
- <ErrorView :error="resultSet.error">
+ <ErrorView
+ :error="resultSet.error"
+ :execute-params="executeParams"
+ :result-set="resultSet"
+ >
<template #suffix>
<RequestQueryButton
v-if="
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
index 6eb64ee9dd..adad0c986d 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
@@ -15,8 +15,9 @@
database: database.name,
scene: 'query',
}"
- @update:content="handleChange"
- @select-content="handleChangeSelection"
+ @update:content="handleUpdateStatement"
+ @select-content="handleUpdateSelectedStatement"
+ @update:selection="handleUpdateSelection"
@ready="handleEditorReady"
/>
</div>
@@ -31,20 +32,23 @@ import type {
IStandaloneCodeEditor,
MonacoModule,
} from "@/components/MonacoEditor";
+import type { Selection as MonacoSelection } from "@/components/MonacoEditor";
import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";
import {
extensionNameOfLanguage,
formatEditorContent,
} from "@/components/MonacoEditor/utils";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
+import { useExecuteSQL } from "@/composables/useExecuteSQL";
import {
useUIStateStore,
useWorkSheetAndTabStore,
useSQLEditorTabStore,
useConnectionOfCurrentSQLEditorTab,
} from "@/store";
-import type { SQLDialect, SQLEditorQueryParams } from "@/types";
+import type { SQLDialect, SQLEditorQueryParams, SQLEditorTab } from "@/types";
import { dialectOfEngineV1 } from "@/types";
+import { Advice_Status, type Advice } from "@/types/proto/v1/sql_service";
import { useInstanceV1EditorLanguage } from "@/utils";
import { useSQLEditorContext } from "../../context";
@@ -58,6 +62,7 @@ const uiStateStore = useUIStateStore();
const { events: editorEvents } = useSQLEditorContext();
const { currentTab, isSwitchingTab } = storeToRefs(tabStore);
const pendingFormatContentCommand = ref(false);
+const { events: executeSQLEvents } = useExecuteSQL();
const content = computed(() => currentTab.value?.statement ?? "");
const advices = computed((): AdviceOption[] => {
@@ -65,19 +70,7 @@ const advices = computed((): AdviceOption[] => {
if (!tab) {
return [];
}
- return (
- Array.from(tab.queryContext?.results.values() || [])
- .map((result) => result?.advices || [])
- .flat() ?? []
- ).map((advice) => ({
- severity: "ERROR",
- message: advice.content,
- startLineNumber: advice.line,
- endLineNumber: advice.line,
- startColumn: advice.column,
- endColumn: advice.column,
- source: advice.detail,
- }));
+ return tab.editorState.advices;
});
const { instance, database } = useConnectionOfCurrentSQLEditorTab();
const language = useInstanceV1EditorLanguage(instance);
@@ -93,7 +86,7 @@ const filename = computed(() => {
return `${name}.${ext}`;
});
-const handleChange = (value: string) => {
+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) {
@@ -116,12 +109,23 @@ const handleChange = (value: string) => {
});
};
-const handleChangeSelection = (value: string) => {
+const handleUpdateSelectedStatement = (value: string) => {
tabStore.updateCurrentTab({
selectedStatement: value,
});
};
+const handleUpdateSelection = (selection: MonacoSelection | null) => {
+ const tab = currentTab.value;
+ if (!tab) return;
+ tabStore.updateCurrentTab({
+ editorState: {
+ ...tab.editorState,
+ selection,
+ },
+ });
+};
+
const handleSaveSheet = () => {
const tab = currentTab.value;
if (!tab) {
@@ -141,6 +145,7 @@ const runQueryAction = (explain = false) => {
statement,
engine: instance.value.engine,
explain,
+ selection: tab.editorState.selection,
});
uiStateStore.saveIntroStateByKey({
key: "data.query",
@@ -185,7 +190,61 @@ const handleEditorReady = (
{ immediate: true }
);
};
+const updateAdvices = (
+ tab: SQLEditorTab,
+ params: SQLEditorQueryParams,
+ advices: Advice[]
+) => {
+ const withOffset = (advice: Advice) => {
+ let line = advice.line;
+ let column = advice.column + 1;
+ const { selection } = params;
+ if (!selection) {
+ return { line, column };
+ }
+ if (
+ selection.endLineNumber > selection.startLineNumber ||
+ selection.endColumn > selection.startColumn
+ ) {
+ if (line === 1) {
+ column += selection.startColumn - 1;
+ }
+ line += selection.startLineNumber - 1;
+ }
+ return { line, column };
+ };
+ tab.editorState.advices = advices.map<AdviceOption>((advice) => {
+ const { line, column } = withOffset(advice);
+ const code = advice.code;
+ const source = [`L${line}:C${column - 1}`];
+ if (code > 0) {
+ source.unshift(`(${code})`);
+ }
+ if (advice.title) {
+ source.unshift(advice.title);
+ }
+ return {
+ severity: advice.status === Advice_Status.ERROR ? "ERROR" : "WARNING",
+ message: advice.content,
+ source: source.join(" "),
+ startLineNumber: line,
+ endLineNumber: line,
+ startColumn: column,
+ endColumn: column,
+ };
+ });
+};
+
useEmitteryEventListener(editorEvents, "format-content", () => {
pendingFormatContentCommand.value = true;
});
+
+useEmitteryEventListener(
+ executeSQLEvents,
+ "update:advices",
+ ({ tab, params, advices }) => {
+ if (tab.id !== currentTab.value?.id) return;
+ updateAdvices(tab, params, advices);
+ }
+);
</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
index 3840207b92..99eb2dac35 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
@@ -69,7 +69,7 @@ import {
useSQLEditorTabStore,
} from "@/store";
import type { SQLEditorConnection, SQLEditorQueryParams } from "@/types";
-import { instanceV1HasReadonlyMode } from "@/utils";
+import { instanceV1HasReadonlyMode, nextAnimationFrame } from "@/utils";
import {
EditorAction,
ExecutingHintModal,
@@ -109,6 +109,7 @@ const handleApplyStatement = async (
}
tab.value.statement = statement;
if (run) {
+ await nextAnimationFrame();
const database = useDatabaseV1Store().getDatabaseByName(
connection.database
);
@@ -117,6 +118,7 @@ const handleApplyStatement = async (
statement,
engine: database.instanceResource.engine,
explain: false,
+ selection: tab.value.editorState.selection,
});
}
};
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
index 363a82391c..342b00f836 100644
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue
@@ -119,6 +119,7 @@ const execute = (explain = false) => {
statement: props.sql,
engine: instance.value.engine,
explain,
+ selection: null,
});
};