Skip to content

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

chore(sql-editor): add search history in database tree (#10077)

boojackad86afb6c102
diff --git a/frontend/src/utils/tab.ts b/frontend/src/utils/tab.ts
index 455d53a0f8..b2a127005e 100644
--- a/frontend/src/utils/tab.ts
+++ b/frontend/src/utils/tab.ts
@@ -1,6 +1,6 @@
import dayjs from "dayjs";
import { v1 as uuidv1 } from "uuid";
-import { useDatabaseV1Store, useInstanceV1Store } from "@/store";
+import { useDatabaseV1Store, useInstanceV1Store, useTabStore } from "@/store";
import type {
ComposedDatabase,
ComposedInstance,
@@ -119,3 +119,24 @@ export const isDisconnectedTab = (tab: TabInfo) => {
}
return databaseId === String(UNKNOWN_ID);
};
+
+export const tryConnectToCoreTab = (tab: CoreTabInfo) => {
+ const tabStore = useTabStore();
+ if (isSimilarTab(tab, tabStore.currentTab)) {
+ // Don't go further if the connection doesn't change.
+ return;
+ }
+ if (tabStore.currentTab.isFreshNew) {
+ // If the current tab is "fresh new", update its connection directly.
+ tabStore.updateCurrentTab(tab);
+ } else {
+ // Otherwise select or add a new tab and set its connection
+ const name = getSuggestedTabNameFromConnection(tab.connection);
+ tabStore.selectOrAddSimilarTab(
+ tab,
+ false /* beside */,
+ name /* defaultTabName */
+ );
+ tabStore.updateCurrentTab(tab);
+ }
+};
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
index ab9033c095..ac2785bea9 100644
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
@@ -2,15 +2,12 @@
<div class="aside-panel h-full flex flex-col overflow-hidden">
<GroupingBar />
<div class="flex-1 overflow-hidden">
- <DatabaseTree v-model:search-pattern="searchPattern" />
+ <DatabaseTree />
</div>
</div>
</template>
<script lang="ts" setup>
-import { ref } from "vue";
import DatabaseTree from "./DatabaseTree.vue";
import GroupingBar from "./GroupingBar";
-
-const searchPattern = ref("");
</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
index 6aa0da5912..2937ea2830 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
@@ -3,19 +3,7 @@
v-if="treeStore.state === 'READY'"
class="sql-editor-tree p-0.5 gap-y-1 h-full flex flex-col"
>
- <div class="sql-editor-tree--input pt-1 px-2">
- <NInput
- size="small"
- :value="searchPattern"
- :placeholder="$t('sql-editor.search-databases')"
- :clearable="true"
- @update:value="$emit('update:search-pattern', $event)"
- >
- <template #prefix>
- <heroicons-outline:search class="h-5 w-5 text-gray-300" />
- </template>
- </NInput>
- </div>
+ <SearchBox v-model:searchPattern="searchPattern" />
<div
ref="treeContainerElRef"
class="sql-editor-tree--tree flex-1 pb-1 text-sm overflow-hidden select-none"
@@ -28,7 +16,7 @@
:data="treeStore.tree"
:show-irrelevant-nodes="false"
:selected-keys="selectedKeys"
- :pattern="mounted ? throttledSearchPattern : ''"
+ :pattern="mounted ? searchPattern : ''"
:expand-on-click="true"
:node-props="nodeProps"
:virtual-scroll="true"
@@ -65,9 +53,9 @@
</template>
<script lang="ts" setup>
-import { useElementSize, useMounted, useThrottleFn } from "@vueuse/core";
+import { useElementSize, useMounted } from "@vueuse/core";
import { head } from "lodash-es";
-import { NTree, NInput, NDropdown, DropdownOption, TreeOption } from "naive-ui";
+import { NTree, NDropdown, DropdownOption, TreeOption } from "naive-ui";
import { storeToRefs } from "pinia";
import { ref, computed, nextTick, watch, h } from "vue";
import { useI18n } from "vue-i18n";
@@ -110,11 +98,13 @@ import {
instanceV1HasAlterSchema,
instanceV1HasReadonlyMode,
isDescendantOf,
- isSimilarTab,
+ tryConnectToCoreTab,
wrapSQLIdentifier,
} from "@/utils";
import { useSQLEditorContext } from "../context";
import DatabaseHoverPanel from "./DatabaseHoverPanel.vue";
+import SearchBox from "./SearchBox/index.vue";
+import useSearchHistory from "./SearchBox/useSearchHistory";
import { Label } from "./TreeNode";
import { fetchDatabaseSubTree } from "./common";
import { provideHoverStateContext } from "./hover-state";
@@ -128,14 +118,6 @@ type DropdownOptionWithTreeNode = DropdownOption & {
node: SQLEditorTreeNode;
};
-const props = defineProps<{
- searchPattern?: string;
-}>();
-
-defineEmits<{
- (event: "update:search-pattern", keyword: string): void;
-}>();
-
const { t } = useI18n();
const { pageMode } = storeToRefs(useActuatorV1Store());
const treeStore = useSQLEditorTreeStore();
@@ -148,6 +130,7 @@ const me = useCurrentUserV1();
const { executeReadonly } = useExecuteSQL();
const { selectedDatabaseSchemaByDatabaseName, events: editorEvents } =
useSQLEditorContext();
+const searchHistory = useSearchHistory();
const { node: hoverNode, update: updateHoverNode } = provideHoverStateContext();
const hoverPanelPosition = ref<Position>({
x: 0,
@@ -164,7 +147,7 @@ const { height: treeContainerHeight } = useElementSize(
}
);
const treeRef = ref<InstanceType<typeof NTree>>();
-const throttledSearchPattern = ref(props.searchPattern);
+const searchPattern = ref("");
const showDropdown = ref(false);
const dropdownPosition = ref<Position>({
x: 0,
@@ -272,26 +255,6 @@ const allowAdmin = computed(() =>
)
);
-const connect = (target: CoreTabInfo) => {
- if (isSimilarTab(target, tabStore.currentTab)) {
- // Don't go further if the connection doesn't change.
- return;
- }
- if (tabStore.currentTab.isFreshNew) {
- // If the current tab is "fresh new", update its connection directly.
- tabStore.updateCurrentTab(target);
- } else {
- // Otherwise select or add a new tab and set its connection
- const name = getSuggestedTabNameFromConnection(target.connection);
- tabStore.selectOrAddSimilarTab(
- target,
- /* beside */ false,
- /* defaultTabName */ name
- );
- tabStore.updateCurrentTab(target);
- }
-};
-
const setConnection = (
node: SQLEditorTreeNode,
extra: { sheetName?: string; mode: TabMode } = {
@@ -310,11 +273,11 @@ const setConnection = (
return;
}
}
- const target: CoreTabInfo = {
+ const coreTab: CoreTabInfo = {
connection: emptyConnection(),
...extra,
};
- const conn = target.connection;
+ const conn = coreTab.connection;
// If selected item is instance node
if (type === "instance") {
const instance = node.meta.target as ComposedInstance;
@@ -326,7 +289,7 @@ const setConnection = (
conn.instanceId = database.instanceEntity.uid;
conn.databaseId = database.uid;
}
- connect(target);
+ tryConnectToCoreTab(coreTab);
}
};
@@ -336,7 +299,7 @@ const renderLabel = ({ option }: { option: TreeOption }) => {
return h(Label, {
node,
factors: treeStore.filteredFactorList,
- keyword: props.searchPattern ?? "",
+ keyword: searchPattern.value ?? "",
});
};
@@ -368,16 +331,16 @@ const maybeSelectTable = async (node: SQLEditorTreeNode) => {
const target = node.meta.target as SQLEditorTreeNodeTarget<"table">;
const { database, schema, table } = target;
if (database.uid !== tabStore.currentTab.connection.databaseId) {
- const target: CoreTabInfo = {
+ const coreTab: CoreTabInfo = {
connection: {
instanceId: database.instanceEntity.uid,
databaseId: database.uid,
},
mode: TabMode.ReadOnly,
};
- target.connection.instanceId = database.instanceEntity.uid;
- target.connection.databaseId = database.uid;
- connect(target);
+ coreTab.connection.instanceId = database.instanceEntity.uid;
+ coreTab.connection.databaseId = database.uid;
+ tryConnectToCoreTab(coreTab);
await nextTick();
}
@@ -400,16 +363,16 @@ const maybeSelectExternalTable = async (node: SQLEditorTreeNode) => {
const target = node.meta.target as SQLEditorTreeNodeTarget<"external-table">;
const { database, schema, externalTable } = target;
if (database.uid !== tabStore.currentTab.connection.databaseId) {
- const target: CoreTabInfo = {
+ const coreTab: CoreTabInfo = {
connection: {
instanceId: database.instanceEntity.uid,
databaseId: database.uid,
},
mode: TabMode.ReadOnly,
};
- target.connection.instanceId = database.instanceEntity.uid;
- target.connection.databaseId = database.uid;
- connect(target);
+ coreTab.connection.instanceId = database.instanceEntity.uid;
+ coreTab.connection.databaseId = database.uid;
+ tryConnectToCoreTab(coreTab);
await nextTick();
}
@@ -510,6 +473,15 @@ const nodeProps = ({ option }: { option: TreeOption }) => {
if (type === "external-table") {
maybeSelectExternalTable(node);
}
+
+ // If the search pattern is not empty, append the selected database name to
+ // the search history.
+ if (searchPattern.value) {
+ if (type === "database") {
+ const database = node.meta.target as ComposedDatabase;
+ searchHistory.appendSearchResult(database.name);
+ }
+ }
}
},
onContextmenu(e: MouseEvent) {
@@ -607,21 +579,6 @@ watch(
{ immediate: true }
);
-watch(
- () => props.searchPattern,
- useThrottleFn(
- (searchPattern: string | undefined) => {
- throttledSearchPattern.value = searchPattern;
- },
- 100,
- true /* trailing */,
- true /* leading */
- ),
- {
- immediate: true,
- }
-);
-
watch(
selectedKeys,
(keys) => {
diff --git a/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue b/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue
new file mode 100644
index 0000000000..ed75960d74
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue
@@ -0,0 +1,131 @@
+<template>
+ <div class="w-full pt-2 px-2">
+ <NAutoComplete
+ size="small"
+ clear-after-select
+ blur-after-select
+ :clearable="true"
+ :value="searchPattern"
+ :placeholder="$t('sql-editor.search-databases')"
+ :options="autoCompleteOptions"
+ :render-label="renderLabel"
+ :get-show="getOptionShow"
+ @update:value="$emit('update:search-pattern', $event || '')"
+ @select="handleDatabaseSelect"
+ >
+ <template #prefix>
+ <SearchIcon class="w-4 h-auto text-gray-300" />
+ </template>
+ </NAutoComplete>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { SearchIcon } from "lucide-vue-next";
+import { NAutoComplete, SelectOption } from "naive-ui";
+import { computed, watchEffect, h } from "vue";
+import { useI18n } from "vue-i18n";
+import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";
+import { useDatabaseV1Store } from "@/store";
+import { CoreTabInfo, TabMode } from "@/types";
+import { emptyConnection, tryConnectToCoreTab } from "@/utils";
+import useSearchHistory from "./useSearchHistory";
+
+const props = defineProps<{
+ searchPattern: string;
+}>();
+
+defineEmits<{
+ (event: "update:search-pattern", keyword: string): void;
+}>();
+
+const { t } = useI18n();
+const databaseStore = useDatabaseV1Store();
+const { searchHistory } = useSearchHistory();
+
+const getOptionShow = () => {
+ if (autoCompleteOptions.value[0].children.length === 0) {
+ return false;
+ }
+ return true;
+};
+
+const autoCompleteOptions = computed(() => {
+ const databaseNames = searchHistory.value;
+ return [
+ {
+ type: "group",
+ key: "recent",
+ label: t("common.recent"),
+ children: databaseNames
+ .filter((databaseName) => {
+ const database = databaseStore.getDatabaseByName(databaseName);
+ return (
+ database &&
+ database.name
+ .toLowerCase()
+ .includes((props.searchPattern || "").toLowerCase())
+ );
+ })
+ .slice(0, 5) // Only show 5 recent databases.
+ .map<SelectOption>((databaseName) => {
+ return {
+ label: databaseName,
+ value: databaseName,
+ };
+ }),
+ },
+ ];
+});
+
+const renderLabel = (option: SelectOption) => {
+ if (option.type === "group") {
+ return h("div", { class: "w-full text-sm text-gray-400" }, [option.label]);
+ }
+
+ const database = databaseStore.getDatabaseByName(option.value as string);
+ return h(
+ "div",
+ {
+ class: "w-full flex items-center gap-x-1",
+ },
+ [
+ h(InstanceV1EngineIcon, {
+ instance: database.instanceEntity,
+ }),
+ h(EnvironmentV1Name, {
+ environment: database.effectiveEnvironmentEntity,
+ link: false,
+ class: "text-control-light",
+ }),
+ h("span", {}, database.databaseName),
+ ]
+ );
+};
+
+const handleDatabaseSelect = (databaseName: string) => {
+ const database = databaseStore.getDatabaseByName(databaseName);
+ const coreTab: CoreTabInfo = {
+ connection: {
+ ...emptyConnection(),
+ instanceId: database.instanceEntity.uid,
+ databaseId: database.uid,
+ },
+ sheetName: undefined,
+ mode: TabMode.ReadOnly,
+ };
+ tryConnectToCoreTab(coreTab);
+};
+
+watchEffect(async () => {
+ for (const databaseName of searchHistory.value) {
+ const database = await databaseStore.getOrFetchDatabaseByName(
+ databaseName,
+ true /* silent */
+ );
+ if (!database) {
+ continue;
+ }
+ }
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SearchBox/useSearchHistory.ts b/frontend/src/views/sql-editor/AsidePanel/SearchBox/useSearchHistory.ts
new file mode 100644
index 0000000000..ebbfbe6cf6
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SearchBox/useSearchHistory.ts
@@ -0,0 +1,23 @@
+import { useLocalStorage } from "@vueuse/core";
+import { uniq } from "lodash-es";
+
+const useSearchHistory = () => {
+ const searchHistory = useLocalStorage<string[]>(
+ "sql-editor-search-result-history",
+ []
+ );
+
+ const appendSearchResult = (databaseName: string) => {
+ if (!databaseName) {
+ return;
+ }
+ searchHistory.value = uniq([databaseName, ...searchHistory.value]);
+ };
+
+ return {
+ searchHistory,
+ appendSearchResult,
+ };
+};
+
+export default useSearchHistory;