Skip to content

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

chore: optimize close result tab (#16856)

ecmadao64785424fddc
diff --git a/frontend/src/components/AdvancedSearch/AdvancedSearch.vue b/frontend/src/components/AdvancedSearch/AdvancedSearch.vue
index 5d1acd8428..65edba0664 100644
--- a/frontend/src/components/AdvancedSearch/AdvancedSearch.vue
+++ b/frontend/src/components/AdvancedSearch/AdvancedSearch.vue
@@ -87,7 +87,6 @@ import { useElementSize } from "@vueuse/core";
import { cloneDeep, last } from "lodash-es";
import { FilterIcon } from "lucide-vue-next";
import { XIcon } from "lucide-vue-next";
-import { matchSorter } from "match-sorter";
import { NButton, NInput, type InputInst } from "naive-ui";
import scrollIntoView from "scroll-into-view-if-needed";
import { zindexable as vZindexable } from "vdirs";
@@ -186,7 +185,7 @@ const containerRef = ref<HTMLElement>();
const tagsContainerRef = ref<HTMLElement>();
const inputText = ref(props.params.query);
const inputRef = ref<InputInst>();
-const menuIndex = ref(0);
+const menuIndex = ref(-1);
const { width: containerWidth } = useElementSize(containerRef);
const focusedTagId = ref<SearchScopeId>();
@@ -299,26 +298,29 @@ const visibleScopeOptions = computed(() => {
const keyword = inputText.value.trim().replace(/:.*$/, "").toLowerCase();
if (!keyword) return availableScopeOptions.value;
- const filtered = matchSorter(availableScopeOptions.value, keyword, {
- keys: ["id", "title", "description"],
- });
-
- return filtered;
+ return availableScopeOptions.value.filter(
+ (option) =>
+ option.id.toLowerCase().includes(keyword) ||
+ option.title.toLowerCase().includes(keyword)
+ );
});
const visibleValueOptions = computed(() => {
if (!state.currentScope) return [];
- const keyword = currentValueForScope.value;
+ const keyword = currentValueForScope.value
+ .trim()
+ .replace(/:.*$/, "")
+ .toLowerCase();
if (!keyword || currentScopeOption.value?.search) {
return valueOptions.value;
}
- // Apply multiple segments of keyword splitted by whitespace
- const terms = keyword.split(/\s+/g);
- const filtered = terms.reduceRight((options, term) => {
- return matchSorter(options, term, { keys: ["value", "keywords"] });
- }, valueOptions.value);
+ const filtered = valueOptions.value.filter(
+ (option) =>
+ option.value.toLowerCase().includes(keyword) ||
+ option.keywords.some((key) => key.includes(keyword))
+ );
const currentValue = getValueFromSearchParams(
props.params,
@@ -568,6 +570,10 @@ const handleKeyUp = (e: KeyboardEvent) => {
// Press enter to select scope (dive into the next step)
// or select value
const index = menuIndex.value;
+ if (index < 0) {
+ hideMenu();
+ return;
+ }
if (state.menuView === "scope") {
const option = visibleScopeOptions.value[index];
if (option) {
@@ -637,14 +643,16 @@ watch(
() => state.menuView,
() => {
focusedTagId.value = undefined;
- menuIndex.value = 0;
+ menuIndex.value = -1;
if (state.menuView === "value" && state.currentScope) {
const value = getValueFromSearchParams(props.params, state.currentScope);
if (value) {
const index = valueOptions.value.findIndex(
(option) => option.value === value
);
- if (index >= 0) menuIndex.value = index;
+ if (index >= 0) {
+ menuIndex.value = index;
+ }
}
}
}
@@ -660,7 +668,6 @@ watch(visibleScopeOptions, (newOptions, oldOptions) => {
return;
}
}
- menuIndex.value = minmax(menuIndex.value, 0, newOptions.length - 1);
});
watch(visibleValueOptions, (newOptions, oldOptions) => {
diff --git a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
index 771a655838..0b0032c388 100644
--- a/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
+++ b/frontend/src/components/MonacoEditor/MonacoTextModelEditor.vue
@@ -62,7 +62,6 @@ import {
shallowRef,
onBeforeUnmount,
watch,
- watchEffect,
computed,
} from "vue";
import { BBSpin } from "@/bbkit";
@@ -249,12 +248,18 @@ onMounted(async () => {
: "";
emit("update:active-content", activeContent.value);
});
- watchEffect(() => {
- emit("select-content", selectedContent.value);
- });
- watchEffect(() => {
- emit("update:selection", selection.value);
- });
+ watch(
+ () => selectedContent.value,
+ () => {
+ emit("select-content", selectedContent.value);
+ }
+ );
+ watch(
+ () => selection.value,
+ () => {
+ emit("update:selection", selection.value);
+ }
+ );
} catch (ex) {
console.error("[MonacoEditor] initialize failed", ex);
}
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 1a0f4c30af..fe13b1779e 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -27,6 +27,7 @@ import type {
SQLEditorQueryParams,
SQLEditorConnection,
SQLEditorTab,
+ QueryContextStatus,
SQLEditorDatabaseQueryContext,
QueryDataSourceType,
} from "@/types";
@@ -192,6 +193,24 @@ const useExecuteSQL = () => {
return getValidDataSourceByPolicy(database, mode) ?? "";
};
+ const changeContextStatus = (
+ ctx: SQLEditorDatabaseQueryContext,
+ status: QueryContextStatus
+ ) => {
+ switch (status) {
+ case "EXECUTING":
+ ctx.abortController = new AbortController();
+ ctx.beginTimestampMS = Date.now();
+ break;
+ case "CANCELLED":
+ ctx.abortController?.abort();
+ break;
+ case "DONE":
+ break;
+ }
+ ctx.status = status;
+ };
+
const preExecute = async (params: SQLEditorQueryParams) => {
const now = Date.now();
if (
@@ -266,9 +285,7 @@ const useExecuteSQL = () => {
for (const [database, contexts] of databaseQueryContexts.entries()) {
if (!batchQueryDatabaseSet.has(database)) {
for (const context of contexts) {
- if (context.status === "EXECUTING") {
- context.abortController?.abort();
- }
+ changeContextStatus(context, "CANCELLED");
}
databaseQueryContexts.delete(database);
}
@@ -282,13 +299,15 @@ const useExecuteSQL = () => {
databaseQueryContexts.set(databaseName, []);
}
- if ((databaseQueryContexts.get(databaseName)?.length ?? 0) >= 10) {
- databaseQueryContexts.get(databaseName)?.pop();
+ if ((databaseQueryContexts.get(databaseName)?.length ?? 0) >= 50) {
+ const ctx = databaseQueryContexts.get(databaseName)?.pop();
+ if (ctx) {
+ changeContextStatus(ctx, "CANCELLED");
+ }
}
const database = dbStore.getDatabaseByName(databaseName);
-
- databaseQueryContexts.get(databaseName)?.unshift({
+ const context: SQLEditorDatabaseQueryContext = {
id: uuidv4(),
params: Object.assign(cloneDeep(params), {
connection: {
@@ -301,7 +320,8 @@ const useExecuteSQL = () => {
},
}),
status: "PENDING",
- });
+ };
+ databaseQueryContexts.get(databaseName)?.unshift(context);
}
};
@@ -323,13 +343,11 @@ const useExecuteSQL = () => {
return;
}
- context.abortController = new AbortController();
- context.status = "EXECUTING";
- context.beginTimestampMS = Date.now();
+ changeContextStatus(context, "EXECUTING");
const finish = (resultSet: SQLResultSetV1) => {
context.resultSet = resultSet;
- context.status = "DONE";
+ changeContextStatus(context, "DONE");
};
const abort = (error: string, advices: Advice[] = []) => {
@@ -343,6 +361,9 @@ const useExecuteSQL = () => {
};
const { abortController } = context;
+ if (!abortController) {
+ return;
+ }
const sqlStore = useSQLStore();
const checkBehavior = context.params.skipCheck
@@ -351,7 +372,7 @@ const useExecuteSQL = () => {
let checkResult: SQLCheckResult = { passed: true };
if (checkBehavior !== "SKIP") {
try {
- checkResult = await check(context.abortController, context.params);
+ checkResult = await check(abortController, context.params);
} catch (error) {
return abort(extractGrpcErrorMessage(error));
}
diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.ts
index 49a3d5d8dc..f3480281b8 100644
--- a/frontend/src/store/modules/sqlEditor/tab.ts
+++ b/frontend/src/store/modules/sqlEditor/tab.ts
@@ -308,6 +308,34 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
return contexts[index] || contexts[index - 1];
};
+ const batchRemoveDatabaseQueryContext = ({
+ database,
+ contextIds,
+ }: {
+ database: string;
+ contextIds: string[];
+ }) => {
+ const tab = tabById(currentTabId.value);
+ if (!tab || !tab.databaseQueryContexts) {
+ return;
+ }
+ if (!tab.databaseQueryContexts.has(database)) {
+ 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);
+ };
+
+ const deleteDatabaseQueryContext = (database: string) => {
+ const tab = tabById(currentTabId.value);
+ if (!tab || !tab.databaseQueryContexts) {
+ return;
+ }
+ tab.databaseQueryContexts.delete(database);
+ };
+
const updateDatabaseQueryContext = ({
database,
contextId,
@@ -445,6 +473,8 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {
updateBatchQueryContext,
updateDatabaseQueryContext,
removeDatabaseQueryContext,
+ batchRemoveDatabaseQueryContext,
+ deleteDatabaseQueryContext,
setCurrentTabId,
selectOrAddSimilarNewTab,
maybeInitProject,
diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.ts
index 478a40bb69..6c96632086 100644
--- a/frontend/src/types/sqlEditor/tab.ts
+++ b/frontend/src/types/sqlEditor/tab.ts
@@ -41,6 +41,12 @@ export type BatchQueryContext = {
dataSourceType?: QueryDataSourceType;
};
+// PENDING: ready, pending to request.
+// EXECUTING: requesting.
+// DONE: request finished.
+// CANCELLED: request cancelled.
+export type QueryContextStatus = "PENDING" | "EXECUTING" | "DONE" | "CANCELLED";
+
export type SQLEditorDatabaseQueryContext = {
id: string;
// we will generate a new abortController when status changed to EXECUTING.
@@ -51,7 +57,7 @@ export type SQLEditorDatabaseQueryContext = {
// EXECUTING: requesting.
// DONE: request finished.
// CANCELLED: request cancelled.
- status: "PENDING" | "EXECUTING" | "DONE" | "CANCELLED";
+ status: QueryContextStatus;
// beginTimestampMS will store the start request time when status changed to EXECUTING.
beginTimestampMS?: number;
// query result.
diff --git a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
index 018d5275c9..056ac54cf7 100644
--- a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
@@ -68,9 +68,9 @@
import { useDebounceFn } from "@vueuse/core";
import dayjs from "dayjs";
import { escape } from "lodash-es";
-import { NButton, useDialog } from "naive-ui";
-import { computed, h, reactive, watch } from "vue";
-import { useI18n } from "vue-i18n";
+import * as monaco from "monaco-editor";
+import { NButton } from "naive-ui";
+import { computed, reactive, watch, nextTick } from "vue";
import MaskSpinner from "@/components/misc/MaskSpinner.vue";
import { SearchBox } from "@/components/v2";
import { CopyButton } from "@/components/v2";
@@ -86,18 +86,16 @@ import {
type SQLEditorTab,
} from "@/types";
import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";
-import { getHighlightHTMLByKeyWords, defer } from "@/utils";
+import { getHighlightHTMLByKeyWords } from "@/utils";
interface State {
search: string;
loading: boolean;
}
-const { t } = useI18n();
const tabStore = useSQLEditorTabStore();
const editorStore = useSQLEditorStore();
const queryHistoryStore = useSQLEditorQueryHistoryStore();
-const $d = useDialog();
const state = reactive<State>({
search: "",
@@ -157,44 +155,6 @@ const titleOfQueryHistory = (history: QueryHistory) => {
);
};
-const confirmOverrideCurrentStatement = (): Promise<"CANCEL" | "OVERRIDE"> => {
- const d = defer<"CANCEL" | "OVERRIDE">();
- 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") }
- ),
- ];
- return h(
- "div",
- { class: "flex items-center justify-end gap-2" },
- buttons
- );
- },
- });
- d.promise.then(() => dialog.destroy());
- return d.promise;
-};
-
const handleQueryHistoryClick = async (queryHistory: QueryHistory) => {
const { statement } = queryHistory;
@@ -211,20 +171,27 @@ const handleQueryHistoryClick = async (queryHistory: QueryHistory) => {
);
};
const openInCurrentTab = async (tab: SQLEditorTab) => {
- if (!tab.statement) {
- tab.statement = statement;
- return;
- }
- const choice = await confirmOverrideCurrentStatement();
- if (choice === "CANCEL") {
- return;
- }
- if (choice === "OVERRIDE") {
+ 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({
- statement,
+ editorState: {
+ ...tab.editorState,
+ selection: selection,
+ },
});
- return;
- }
+ });
};
if (tab) {
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
index 877cb87d8e..0226c656e3 100644
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
@@ -21,7 +21,12 @@
<template #tab>
<NTooltip>
<template #trigger>
- <div class="flex items-center space-x-2">
+ <div
+ class="flex items-center space-x-2"
+ @contextmenu.stop.prevent="
+ handleContextMenuShow(context.id, $event)
+ "
+ >
<span>{{ tabName(context) }}</span>
<CircleAlertIcon
v-if="context.resultSet?.error"
@@ -59,6 +64,24 @@
/>
</NTabPane>
</NTabs>
+ <NDropdown
+ v-if="contextMenuState"
+ trigger="manual"
+ placement="bottom-start"
+ :show="true"
+ :x="contextMenuState?.x"
+ :y="contextMenuState?.y"
+ :options="contextMenuOptions"
+ @clickoutside="handleContextMenuClose"
+ @update:show="
+ (show: boolean) => {
+ if (!show) {
+ handleContextMenuClose();
+ }
+ }
+ "
+ @select="handleContextMenuSelect"
+ />
</div>
</template>
@@ -66,8 +89,9 @@
import dayjs from "dayjs";
import { head } from "lodash-es";
import { CircleAlertIcon, XIcon } from "lucide-vue-next";
-import { NTabs, NTabPane, NTooltip } from "naive-ui";
-import { computed, ref, watch } from "vue";
+import type { DropdownOption } from "naive-ui";
+import { NTabs, NTabPane, NTooltip, NDropdown } from "naive-ui";
+import { computed, ref, watch, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { BBSpin } from "@/bbkit";
import { BBAttention } from "@/bbkit";
@@ -81,6 +105,95 @@ const selectedDatabase = ref<ComposedDatabase>();
const tabStore = useSQLEditorTabStore();
const selectedTab = ref<string>();
const { t } = useI18n();
+const contextMenuState = ref<
+ | {
+ x: number;
+ y: number;
+ tabId: string;
+ }
+ | undefined
+>();
+
+const contextMenuOptions = computed((): DropdownOption[] => {
+ return [
+ {
+ key: "CLOSE",
+ label: t("sql-editor.tab.context-menu.actions.close"),
+ },
+ {
+ key: "CLOSE_OTHERS",
+ label: t("sql-editor.tab.context-menu.actions.close-others"),
+ },
+ {
+ key: "CLOSE_TO_THE_RIGHT",
+ label: t("sql-editor.tab.context-menu.actions.close-to-the-right"),
+ },
+ {
+ key: "CLOSE_ALL",
+ label: t("sql-editor.tab.context-menu.actions.close-all"),
+ },
+ ];
+});
+
+const handleContextMenuSelect = (action: string) => {
+ if (!contextMenuState.value) {
+ return;
+ }
+ switch (action) {
+ case "CLOSE":
+ handleCloseTab(contextMenuState.value.tabId);
+ break;
+ case "CLOSE_OTHERS":
+ tabStore.batchRemoveDatabaseQueryContext({
+ database: selectedDatabase.value?.name ?? "",
+ contextIds:
+ queryContexts.value
+ ?.filter((ctx) => ctx.id !== contextMenuState.value?.tabId)
+ .map((ctx) => ctx.id) ?? [],
+ });
+ selectedTab.value = contextMenuState.value?.tabId;
+ break;
+ case "CLOSE_TO_THE_RIGHT":
+ const index =
+ queryContexts.value?.findIndex(
+ (ctx) => ctx.id === contextMenuState.value?.tabId
+ ) ?? -1;
+ if (index < 0) {
+ return;
+ }
+ tabStore.batchRemoveDatabaseQueryContext({
+ database: selectedDatabase.value?.name ?? "",
+ contextIds:
+ queryContexts.value?.slice(index + 1).map((ctx) => ctx.id) ?? [],
+ });
+ selectedTab.value = contextMenuState.value?.tabId;
+ break;
+ case "CLOSE_ALL":
+ tabStore.deleteDatabaseQueryContext(selectedDatabase.value?.name ?? "");
+ selectedTab.value = undefined;
+ break;
+ }
+
+ handleContextMenuClose();
+};
+
+const handleContextMenuShow = (tabId: string, e: MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleContextMenuClose();
+ nextTick(() => {
+ const { pageX, pageY } = e;
+ contextMenuState.value = {
+ x: pageX,
+ y: pageY,
+ tabId,
+ };
+ });
+};
+
+const handleContextMenuClose = () => {
+ contextMenuState.value = undefined;
+};
const isBatchQuery = computed(
() =>
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
index 5a820e8fb4..93f28760db 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue
@@ -168,6 +168,16 @@ const getActiveStatement = () => {
return monacoEditorRef.value?.getActiveStatement() || tab.statement || "";
};
+watch(
+ () => tabStore.currentTab?.editorState.selection,
+ (selection) => {
+ if (!selection || !activeSQLEditorRef.value) {
+ return;
+ }
+ activeSQLEditorRef.value.setSelection(selection);
+ }
+);
+
const runQueryAction = ({
explain = false,
newTab = false,