Skip to content

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

feat(sql-editor): database tree improvement (#2856)

Liu Ji5f067a766642
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index fdff1ee317..10e7e2b9c9 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -16,13 +16,8 @@ import {
useInstanceStore,
pushNotification,
} from "@/store";
-import {
- Instance,
- Database,
- ConnectionAtom,
- UNKNOWN_ID,
- DEFAULT_PROJECT_ID,
-} from "@/types";
+import type { Instance, Database, ConnectionAtom } from "@/types";
+import { ConnectionTreeState, UNKNOWN_ID, DEFAULT_PROJECT_ID } from "@/types";
import {
emptyConnection,
idFromSlug,
@@ -90,7 +85,7 @@ const prepareSQLEditorContext = async () => {
.filter((db) => db.instance.id === instance.id)
.map(mapConnectionAtom("database", instance.id));
- sqlEditorStore.setConnectionTree(connectionTree);
+ sqlEditorStore.connectionTree.data = connectionTree;
}
// Won't fetch tableList for every database here.
@@ -135,7 +130,6 @@ const prepareSheet = async () => {
isSaved: true,
connection: {
...emptyConnection(),
- projectId: sheet.database?.projectId || DEFAULT_PROJECT_ID,
instanceId: sheet.database?.instanceId || UNKNOWN_ID,
databaseId: sheet.databaseId || UNKNOWN_ID,
},
@@ -238,10 +232,19 @@ const syncURLWithConnection = () => {
};
onMounted(async () => {
- sqlEditorStore.isLoadingTree = true;
- await prepareAccessibleConnectionByProject();
- await prepareSQLEditorContext();
- sqlEditorStore.isLoadingTree = false;
+ if (sqlEditorStore.connectionTree.state === ConnectionTreeState.UNSET) {
+ sqlEditorStore.connectionTree.state = ConnectionTreeState.LOADING;
+ await prepareAccessibleConnectionByProject();
+ await prepareSQLEditorContext();
+ sqlEditorStore.connectionTree.state = ConnectionTreeState.LOADED;
+ }
+
+ watch(currentUser, (user) => {
+ if (user.id === UNKNOWN_ID) {
+ sqlEditorStore.connectionTree.data = [];
+ sqlEditorStore.connectionTree.state = ConnectionTreeState.UNSET;
+ }
+ });
await setConnectionFromQuery();
await sqlEditorStore.fetchQueryHistoryList();
diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.ts
index 16b2b83ca6..babf05bfe5 100644
--- a/frontend/src/store/modules/sqlEditor.ts
+++ b/frontend/src/store/modules/sqlEditor.ts
@@ -2,7 +2,6 @@ import { defineStore } from "pinia";
import dayjs from "dayjs";
import type {
SQLEditorState,
- ConnectionAtom,
QueryInfo,
DatabaseId,
QueryHistory,
@@ -10,6 +9,7 @@ import type {
Connection,
ActivitySQLEditorQueryPayload,
} from "@/types";
+import { ConnectionTreeState } from "@/types";
import { UNKNOWN_ID, unknown } from "@/types";
import { useActivityStore } from "./activity";
import { useDatabaseStore } from "./database";
@@ -20,9 +20,12 @@ import { useTabStore } from "./tab";
export const useSQLEditorStore = defineStore("sqlEditor", {
state: (): SQLEditorState => ({
- connectionTree: [],
+ connectionTree: {
+ data: [],
+ state: ConnectionTreeState.UNSET,
+ },
+ expandedTreeNodeKeys: [],
selectedTable: unknown("TABLE"),
- isLoadingTree: false,
isShowExecutingHint: false,
shouldFormatContent: false,
// Related data and status
@@ -35,9 +38,6 @@ export const useSQLEditorStore = defineStore("sqlEditor", {
setSQLEditorState(payload: Partial<SQLEditorState>) {
Object.assign(this, payload);
},
- setConnectionTree(payload: ConnectionAtom[]) {
- this.connectionTree = payload;
- },
setShouldFormatContent(payload: boolean) {
this.shouldFormatContent = payload;
},
diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.ts
index e4ac3847ea..a491eeaf51 100644
--- a/frontend/src/types/store.ts
+++ b/frontend/src/types/store.ts
@@ -190,13 +190,22 @@ export interface LabelState {
labelList: Label[];
}
+export enum ConnectionTreeState {
+ UNSET,
+ LOADING,
+ LOADED,
+}
+
export interface SQLEditorState {
- connectionTree: ConnectionAtom[];
+ connectionTree: {
+ data: ConnectionAtom[];
+ state: ConnectionTreeState;
+ };
+ expandedTreeNodeKeys: string[];
selectedTable: Table;
shouldFormatContent: boolean;
queryHistoryList: QueryHistory[];
isFetchingQueryHistory: boolean;
- isLoadingTree: boolean;
isFetchingSheet: boolean;
isShowExecutingHint: boolean;
}
diff --git a/frontend/src/utils/dom.ts b/frontend/src/utils/dom.ts
new file mode 100644
index 0000000000..672a0459a9
--- /dev/null
+++ b/frontend/src/utils/dom.ts
@@ -0,0 +1,12 @@
+export const isDescendantOf = (
+ node: Element | null | undefined,
+ selector: string
+) => {
+ while (node) {
+ if (node.matches(selector)) {
+ return true;
+ }
+ node = node.parentElement;
+ }
+ return false;
+};
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index e578c7e090..e525a2beca 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -19,3 +19,4 @@ export * from "./principal";
export * from "./sql-editor";
export * from "./sheet";
export * from "./pev2";
+export * from "./dom";
diff --git a/frontend/src/utils/util.ts b/frontend/src/utils/util.ts
index b4d48eddc6..9c284ec63e 100644
--- a/frontend/src/utils/util.ts
+++ b/frontend/src/utils/util.ts
@@ -156,6 +156,7 @@ export function getStringCookie(name: string): string {
}
export function getHighlightHTMLByKeyWords(s: string, k: string) {
+ if (!k) return s;
return s.replaceAll(k, `<b class="text-accent">${k}</b>`);
}
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
index 76c913f520..cf9c08232d 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
@@ -1,6 +1,6 @@
<template>
<div
- v-if="!sqlEditorStore.isLoadingTree"
+ v-if="sqlEditorStore.connectionTree.state === ConnectionTreeState.LOADED"
class="databases-tree p-2 space-y-2 h-full"
>
<div class="databases-tree--input">
@@ -16,14 +16,15 @@
<div class="databases-tree--tree overflow-y-scroll">
<n-tree
block-line
- expand-on-click
:data="treeData"
:pattern="searchPattern"
- :default-expanded-keys="defaultExpandedKeys"
:selected-keys="selectedKeys"
+ :expanded-keys="sqlEditorStore.expandedTreeNodeKeys"
:render-label="renderLabel"
+ :render-suffix="renderSuffix"
:node-props="nodeProps"
:on-load="loadSubTree"
+ :on-update:expanded-keys="updateExpandedKeys"
/>
<n-dropdown
placement="bottom-start"
@@ -44,15 +45,17 @@
<script lang="ts" setup>
import { escape } from "lodash-es";
-import { DropdownOption } from "naive-ui";
-import { ref, computed, h, nextTick, onMounted, watch } from "vue";
+import type { DropdownOption } from "naive-ui";
+import { ref, computed, h, nextTick, watch } from "vue";
import { useI18n } from "vue-i18n";
import { stringify } from "qs";
+import ConnectedIcon from "~icons/heroicons-outline/lightning-bolt";
-import { ConnectionAtom, UNKNOWN_ID } from "@/types";
+import type { ConnectionAtom, DatabaseId, InstanceId } from "@/types";
+import { ConnectionTreeState, UNKNOWN_ID } from "@/types";
import {
useDatabaseStore,
- useInstanceStore,
+ useIsLoggedIn,
useSQLEditorStore,
useTableStore,
useTabStore,
@@ -60,10 +63,12 @@ import {
import {
emptyConnection,
getHighlightHTMLByKeyWords,
+ isDescendantOf,
isSameConnection,
mapConnectionAtom,
} from "@/utils";
-import { generateInstanceNode, generateTableItem } from "./utils";
+import { generateTableItem } from "./utils";
+import { scrollIntoViewIfNeeded } from "@/bbkit/BBUtil";
type Position = {
x: number;
@@ -76,34 +81,19 @@ type DropdownOptionWithConnectionAtom = DropdownOption & {
const { t } = useI18n();
-const instanceStore = useInstanceStore();
const databaseStore = useDatabaseStore();
const sqlEditorStore = useSQLEditorStore();
const tableStore = useTableStore();
const tabStore = useTabStore();
+const isLoggedIn = useIsLoggedIn();
-const defaultExpandedKeys = ref<string[]>([]);
const searchPattern = ref();
const showDropdown = ref(false);
const dropdownPosition = ref<Position>({
x: 0,
y: 0,
});
-const selectedKeys = ref<string[] | number[]>([]);
const dropdownContext = ref<ConnectionAtom>();
-
-onMounted(() => {
- const { instanceId, databaseId } = tabStore.currentTab.connection;
- const keys: string[] = [];
- if (instanceId !== UNKNOWN_ID) {
- keys.push(`instance-${instanceId}`);
- }
- if (databaseId !== UNKNOWN_ID) {
- keys.push(`database-${databaseId}`);
- }
- defaultExpandedKeys.value = keys;
-});
-
const dropdownOptions = computed((): DropdownOptionWithConnectionAtom[] => {
if (!dropdownContext.value) {
return [];
@@ -126,21 +116,19 @@ const dropdownOptions = computed((): DropdownOptionWithConnectionAtom[] => {
}
});
-const generateTreeData = () => {
- return sqlEditorStore.connectionTree.map((item) =>
- generateInstanceNode(item, instanceStore)
- );
-};
-
-const treeData = ref<ConnectionAtom[]>([]);
+// Highlight the current tab's connection node.
+const selectedKeys = computed(() => {
+ const { instanceId, databaseId } = tabStore.currentTab.connection;
+ if (databaseId !== UNKNOWN_ID) {
+ return [`database-${databaseId}`];
+ }
+ if (instanceId !== UNKNOWN_ID) {
+ return [`instance-${instanceId}`];
+ }
+ return [];
+});
-watch(
- () => sqlEditorStore.connectionTree,
- () => {
- treeData.value = generateTreeData();
- },
- { immediate: true }
-);
+const treeData = computed(() => sqlEditorStore.connectionTree.data);
const setConnection = (option: ConnectionAtom) => {
if (option) {
@@ -188,27 +176,64 @@ const setConnection = (option: ConnectionAtom) => {
};
// dynamic render the highlight keywords
+// and render the selected table node in bold font
const renderLabel = ({ option }: { option: ConnectionAtom }) => {
- const renderLabelHTML = searchPattern.value
- ? h("span", {
- innerHTML: getHighlightHTMLByKeyWords(
- escape(option.label),
- escape(searchPattern.value)
- ),
- class: "truncate",
- })
- : escape(option.label);
-
- return renderLabelHTML;
+ const classes = ["truncate"];
+ const emphasize = () => {
+ classes.push("font-bold");
+ };
+
+ if (option.type === "table") {
+ if (option.id === sqlEditorStore.selectedTable.id) {
+ emphasize();
+ }
+ }
+
+ return h("span", {
+ // render an unique id for every node
+ // for auto scroll to the node when tab switches
+ id: `tree-node-label-${option.type}-${option.id}`,
+ innerHTML: getHighlightHTMLByKeyWords(
+ escape(option.label),
+ escape(searchPattern.value)
+ ),
+ class: classes,
+ });
+};
+
+// Render a 'connected' icon in the right of the node
+// if it matches the current tab's connection
+const renderSuffix = ({ option }: { option: ConnectionAtom }) => {
+ const renderConnectedIcon = () => {
+ return h(ConnectedIcon, {
+ class: "w-4 h-4",
+ });
+ };
+ const { instanceId, databaseId } = tabStore.currentTab.connection;
+ if (option.type === "database") {
+ if (option.id === databaseId) {
+ return renderConnectedIcon();
+ }
+ }
+ if (option.type === "instance") {
+ if (databaseId === UNKNOWN_ID && option.id === instanceId) {
+ return renderConnectedIcon();
+ }
+ }
};
-const loadSubTree = async (item: ConnectionAtom) => {
- const mapper = mapConnectionAtom("table", item.id);
+const loadSubTree = async (item: ConnectionAtom): Promise<void> => {
if (item.type === "database") {
const tableList = await useTableStore().fetchTableListByDatabaseId(item.id);
+ const mapper = mapConnectionAtom("table", item.id);
item.children = tableList.map((table) => generateTableItem(mapper(table)));
- return;
+ if (item.children.length === 0) {
+ // No tables in the db
+ item.isLeaf = true;
+ // TODO: this might be a little bit confusing
+ // Better add a dummy "no tables" node in the future
+ }
}
};
@@ -249,19 +274,20 @@ const handleClickoutside = () => {
showDropdown.value = false;
};
-const nodeProps = (info: { option: ConnectionAtom }) => {
- const { option } = info;
-
+const nodeProps = ({ option }: { option: ConnectionAtom }) => {
return {
onClick(e: MouseEvent) {
- setConnection(option);
+ if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {
+ // Check if clicked on the content part.
+ // And ignore the fold/unfold arrow.
+ setConnection(option);
+ }
},
onContextmenu(e: MouseEvent) {
e.preventDefault();
showDropdown.value = false;
if (option && option.key) {
dropdownContext.value = option;
- selectedKeys.value = [option.key as string];
}
nextTick().then(() => {
@@ -272,21 +298,79 @@ const nodeProps = (info: { option: ConnectionAtom }) => {
},
};
};
+
+const updateExpandedKeys = (keys: string[]) => {
+ sqlEditorStore.expandedTreeNodeKeys = keys;
+};
+
+// When switching tabs, scroll the matched node into view if needed.
+const scrollToConnectedNode = (
+ instanceId: InstanceId,
+ databaseId: DatabaseId
+) => {
+ if (instanceId === UNKNOWN_ID && databaseId === UNKNOWN_ID) {
+ return;
+ }
+ let id: string;
+ if (databaseId === UNKNOWN_ID) {
+ id = `tree-node-label-instance-${instanceId}`;
+ } else {
+ id = `tree-node-label-database-${databaseId}`;
+ }
+ nextTick(() => {
+ const elem = document.getElementById(id);
+ if (elem) {
+ scrollIntoViewIfNeeded(elem);
+ }
+ });
+};
+
+// Open corresponding tree node when the connection changed.
+watch(
+ [
+ isLoggedIn,
+ () => tabStore.currentTab.connection.instanceId,
+ () => tabStore.currentTab.connection.databaseId,
+ ],
+ ([isLoggedIn, instanceId, databaseId]) => {
+ if (!isLoggedIn) {
+ // Don't go further and cleanup the state if we signed out.
+ sqlEditorStore.expandedTreeNodeKeys = [];
+ return;
+ }
+
+ const maybeExpandKey = (key: string) => {
+ const keys = sqlEditorStore.expandedTreeNodeKeys;
+ if (!keys.includes(key)) {
+ keys.push(key);
+ }
+ };
+
+ if (instanceId !== UNKNOWN_ID) {
+ maybeExpandKey(`instance-${instanceId}`);
+ }
+ if (databaseId !== UNKNOWN_ID) {
+ maybeExpandKey(`database-${databaseId}`);
+ }
+
+ scrollToConnectedNode(instanceId, databaseId);
+ },
+ { immediate: true, flush: "pre" }
+);
</script>
<style>
-.n-tree-node-content__prefix {
+.databases-tree .n-tree-node-content__prefix {
@apply shrink-0;
}
-.n-tree-node-content__text {
+.databases-tree .n-tree-node-content__text {
@apply truncate mr-1;
}
-.n-tree-node-content__suffix {
- display: none !important;
+.databases-tree .n-tree-node--pending {
+ background-color: transparent !important;
}
-
-.n-tree-node:hover .n-tree-node-content__suffix {
- display: block !important;
+.databases-tree .n-tree-node--pending:hover {
+ background-color: var(--n-node-color-hover) !important;
}
</style>
diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json
index fb2cf934ff..629bf7efb3 100644
--- a/frontend/tsconfig.json
+++ b/frontend/tsconfig.json
@@ -51,7 +51,7 @@
"unplugin-icons/types/vue",
"vite/client"
] /* Type declaration files to be included in compilation. */,
- "lib": ["WebWorker"],
+ "lib": ["WebWorker", "ES2022"],
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */