Skip to content

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

feat(sql-editor): brand new sql editor tree (#8732)

Liu Ji5cbd7057a8a4
diff --git a/frontend/src/components/DatabaseDetail/SQLEditorButton.vue b/frontend/src/components/DatabaseDetail/SQLEditorButton.vue
index 1a2dd4d002..6dc321a96b 100644
--- a/frontend/src/components/DatabaseDetail/SQLEditorButton.vue
+++ b/frontend/src/components/DatabaseDetail/SQLEditorButton.vue
@@ -15,9 +15,9 @@
<script lang="ts" setup>
import { computed } from "vue";
-import { useConnectionTreeStore, useCurrentUserV1 } from "@/store";
+import { useCurrentUserV1, useSQLEditorTreeStore } from "@/store";
import type { Database } from "@/types";
-import { ConnectionTreeMode, DEFAULT_PROJECT_ID, UNKNOWN_ID } from "@/types";
+import { DEFAULT_PROJECT_ID, UNKNOWN_ID } from "@/types";
import { connectionSlug, hasWorkspacePermissionV1 } from "@/utils";
const props = withDefaults(
@@ -79,7 +79,12 @@ const gotoSQLEditor = () => {
}
// Set the default sidebar view of SQL Editor to "INSTANCE"
// since unassigned databases won't be listed in "PROJECT" view.
- useConnectionTreeStore().tree.mode = ConnectionTreeMode.INSTANCE;
+ useSQLEditorTreeStore().factorList = [
+ {
+ factor: "instance",
+ disabled: false,
+ },
+ ];
}
const url = `/sql-editor/${connectionSlug(database.instance, database)}`;
window.open(url);
diff --git a/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vue b/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vue
index b6f364814d..0d39b442c1 100644
--- a/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vue
+++ b/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vue
@@ -21,10 +21,9 @@
<script lang="ts" setup>
import { NTooltip } from "naive-ui";
import { computed } from "vue";
-import { useConnectionTreeStore, useCurrentUserV1 } from "@/store";
+import { useCurrentUserV1, useSQLEditorTreeStore } from "@/store";
import {
ComposedDatabase,
- ConnectionTreeMode,
DEFAULT_PROJECT_V1_NAME,
UNKNOWN_PROJECT_NAME,
} from "@/types";
@@ -93,7 +92,12 @@ const gotoSQLEditor = () => {
}
// Set the default sidebar view of SQL Editor to "INSTANCE"
// since unassigned databases won't be listed in "PROJECT" view.
- useConnectionTreeStore().tree.mode = ConnectionTreeMode.INSTANCE;
+ useSQLEditorTreeStore().factorList = [
+ {
+ factor: "instance",
+ disabled: false,
+ },
+ ];
}
const url = `/sql-editor/${connectionV1Slug(
database.instanceEntity,
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index a788d87702..b3f51ff7b0 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -3,7 +3,6 @@
</template>
<script lang="ts" setup>
-import { uniqBy } from "lodash-es";
import { onMounted, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
@@ -11,7 +10,6 @@ import {
useSQLEditorStore,
useTabStore,
pushNotification,
- useConnectionTreeStore,
useProjectV1Store,
useCurrentUserV1,
useSheetV1Store,
@@ -20,18 +18,11 @@ import {
useEnvironmentV1Store,
useUserStore,
} from "@/store";
+import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
import { usePolicyV1Store } from "@/store/modules/v1/policy";
import { useSettingV1Store } from "@/store/modules/v1/setting";
-import {
- Connection,
- ConnectionAtom,
- ConnectionTreeMode,
- CoreTabInfo,
- DEFAULT_PROJECT_V1_NAME,
- TabMode,
- UNKNOWN_USER_NAME,
-} from "@/types";
-import { ConnectionTreeState, UNKNOWN_ID } from "@/types";
+import { Connection, CoreTabInfo, TabMode, UNKNOWN_USER_NAME } from "@/types";
+import { UNKNOWN_ID } from "@/types";
import { State } from "@/types/proto/v1/common";
import {
PolicyType,
@@ -47,7 +38,6 @@ import {
isDatabaseV1Queryable,
getSuggestedTabNameFromConnection,
isSimilarTab,
- hasWorkspacePermissionV1,
} from "@/utils";
const route = useRoute();
@@ -59,16 +49,15 @@ const instanceStore = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
const policyV1Store = usePolicyV1Store();
const sqlEditorStore = useSQLEditorStore();
-const connectionTreeStore = useConnectionTreeStore();
+const treeStore = useSQLEditorTreeStore();
const tabStore = useTabStore();
const sheetV1Store = useSheetV1Store();
const prepareAccessControlPolicy = async () => {
- connectionTreeStore.accessControlPolicyList =
- await policyV1Store.fetchPolicies({
- policyType: PolicyType.WORKSPACE_IAM,
- resourceType: PolicyResourceType.WORKSPACE,
- });
+ treeStore.accessControlPolicyList = await policyV1Store.fetchPolicies({
+ policyType: PolicyType.WORKSPACE_IAM,
+ resourceType: PolicyResourceType.WORKSPACE,
+ });
await policyV1Store.fetchPolicies({
resourceType: PolicyResourceType.ENVIRONMENT,
policyType: PolicyType.DISABLE_COPY_DATA,
@@ -93,123 +82,12 @@ const prepareAccessibleDatabaseList = async () => {
db.syncState === State.ACTIVE &&
isDatabaseV1Queryable(db, currentUserV1.value)
);
- connectionTreeStore.tree.databaseList = databaseList;
-};
-
-const connectionTreeCache: Record<"instance" | "project", ConnectionAtom[]> = {
- project: [],
- instance: [],
-};
-
-const initializeConnectionTree = async () => {
- const build = (mode: ConnectionTreeMode): ConnectionAtom[] => {
- if (mode === ConnectionTreeMode.INSTANCE) {
- const { databaseList } = connectionTreeStore.tree;
- const instanceList = uniqBy(
- databaseList.map((db) => db.instanceEntity),
- (instance) => instance.uid
- );
- const tree = instanceList.map((instance) => {
- const node = connectionTreeStore.mapAtom(
- instance,
- "instance",
- undefined /* ROOT */
- );
- return node;
- });
-
- for (const instance of instanceList) {
- const instanceItem = tree.find(
- (item: ConnectionAtom) => item.id === instance.uid
- )!;
-
- instanceItem.children = databaseList
- .filter((db) => db.instanceEntity.uid === instance.uid)
- .map((db) => {
- const node = connectionTreeStore.mapAtom(
- db,
- "database",
- instanceItem
- );
- node.disabled = !isDatabaseV1Queryable(db, currentUserV1.value);
- if (node.disabled) {
- // If a database node is not accessible
- // it's not expandable either.
- node.isLeaf = true;
- }
- return node;
- });
- }
- return tree;
- } else {
- const databaseList = connectionTreeStore.tree.databaseList.filter(
- (db) => {
- return db.project !== DEFAULT_PROJECT_V1_NAME;
- }
- );
- const projectList = uniqBy(
- databaseList.map((db) => db.projectEntity),
- (project) => project.uid
- );
-
- const projectAtomList = projectList.map((project) => {
- const node = connectionTreeStore.mapAtom(
- project,
- "project",
- undefined /* ROOT */
- );
- return node;
- });
-
- projectAtomList.forEach((projectAtom) => {
- projectAtom.children = databaseList
- .filter((db) => db.projectEntity.uid === projectAtom.id)
- .map((db) => {
- const node = connectionTreeStore.mapAtom(
- db,
- "database",
- projectAtom
- );
- node.disabled = !isDatabaseV1Queryable(db, currentUserV1.value);
- if (node.disabled) {
- // If a database node is not accessible
- // it's not expandable either.
- node.isLeaf = true;
- }
- return node;
- });
- });
-
- return projectAtomList;
- }
- };
- connectionTreeCache.instance = build(ConnectionTreeMode.INSTANCE);
- connectionTreeCache.project = build(ConnectionTreeMode.PROJECT);
-
- if (connectionTreeStore.tree.mode === ConnectionTreeMode.INSTANCE) {
- if (
- !hasWorkspacePermissionV1(
- "bb.permission.workspace.manage-database",
- currentUserV1.value.userRole
- )
- ) {
- connectionTreeStore.tree.mode = ConnectionTreeMode.PROJECT;
- return;
- }
- }
- // Won't fetch tableList for every database here.
- // Will fetch them asynchronously only when a database node opens.
+ treeStore.databaseList = databaseList;
};
-const switchConnectionTree = () => {
- const tree = connectionTreeStore.tree;
- const mode = tree.mode;
- if (mode === ConnectionTreeMode.INSTANCE) {
- tree.data = connectionTreeCache.instance;
- } else {
- tree.data = connectionTreeCache.project;
- }
+const initializeTree = async () => {
+ treeStore.buildTree();
};
const prepareSheet = async () => {
@@ -316,17 +194,16 @@ const prepareConnectionSlug = async () => {
if (Number.isNaN(databaseId)) {
// connected to instance
- const connection = await connectionTreeStore.fetchConnectionByInstanceId(
+ const connection = await treeStore.fetchConnectionByInstanceId(
String(instanceId)
);
connect(connection);
} else {
// connected to db
- const connection =
- await connectionTreeStore.fetchConnectionByInstanceIdAndDatabaseId(
- String(instanceId),
- String(databaseId)
- );
+ const connection = await treeStore.fetchConnectionByInstanceIdAndDatabaseId(
+ String(instanceId),
+ String(databaseId)
+ );
connect(connection);
}
return true;
@@ -415,8 +292,9 @@ const syncURLWithConnection = () => {
onMounted(async () => {
await useUserStore().fetchUserList();
- if (connectionTreeStore.tree.state === ConnectionTreeState.UNSET) {
- connectionTreeStore.tree.state = ConnectionTreeState.LOADING;
+ if (treeStore.state === "UNSET") {
+ treeStore.state = "LOADING";
+
// Initialize project list state for iam policy.
await useProjectV1Store().fetchProjectList(true /* include archived */);
// Initialize environment list for composing.
@@ -426,22 +304,17 @@ onMounted(async () => {
await usePolicyV1Store().getOrFetchPolicyByName("policies/WORKSPACE_IAM");
await prepareAccessControlPolicy();
await prepareAccessibleDatabaseList();
- await initializeConnectionTree();
- connectionTreeStore.tree.state = ConnectionTreeState.LOADED;
- }
- watch(() => connectionTreeStore.tree.mode, switchConnectionTree, {
- immediate: true,
- });
+ await initializeTree();
+ treeStore.state = "READY";
+ }
watch(
() => currentUserV1.value.name,
(name) => {
if (name === UNKNOWN_USER_NAME) {
// Cleanup when user signed out
- connectionTreeStore.tree.data = [];
- connectionTreeStore.tree.state = ConnectionTreeState.UNSET;
-
+ treeStore.cleanup();
tabStore.reset();
}
}
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 91c3a329d3..896c1bda4d 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2064,7 +2064,8 @@
"select-database": "Select database below",
"description": "Batch query {count} additional databases under {project}."
},
- "executing-query": "Executing query"
+ "executing-query": "Executing query",
+ "grouping": "Grouping"
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 379bfe7c25..19655ac81b 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2060,7 +2060,8 @@
"select-database": "Seleccione la base de datos a continuación",
"description": "Consulta por lotes {count} bases de datos adicionales en {project}."
},
- "executing-query": "Ejecutando consulta"
+ "executing-query": "Ejecutando consulta",
+ "grouping": "Agrupamiento"
},
"schema-editor": {
"self": "Editor de esquema",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 2923b51fc6..c310e15ec6 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2059,7 +2059,8 @@
"select-database": "选择下面的数据库",
"description": "批量查询 {project} 下的 {count} 个数据库。"
},
- "executing-query": "执行查询"
+ "executing-query": "执行查询",
+ "grouping": "分组"
},
"schema-editor": {
"self": "Schema 编辑器",
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 6521a84277..047f425526 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -26,7 +26,6 @@ import {
useLegacyInstanceStore,
useRouterStore,
useDBSchemaV1Store,
- useConnectionTreeStore,
useOnboardingStateStore,
useTabStore,
useIdentityProviderStore,
@@ -40,6 +39,7 @@ import {
useChangeHistoryStore,
useChangelistStore,
useSchemaDesignStore,
+ useSQLEditorTreeStore,
} from "@/store";
import {
DEFAULT_PROJECT_ID,
@@ -1584,13 +1584,13 @@ router.beforeEach((to, from, next) => {
const databaseId = idFromSlug(databaseSlug);
if (Number.isNaN(databaseId)) {
// Connected to instance
- useConnectionTreeStore()
+ useSQLEditorTreeStore()
.fetchConnectionByInstanceId(String(instanceId))
.then(() => next())
.catch(() => next());
} else {
// Connected to db
- useConnectionTreeStore()
+ useSQLEditorTreeStore()
.fetchConnectionByInstanceIdAndDatabaseId(
String(instanceId),
String(databaseId)
diff --git a/frontend/src/store/modules/connectionTree.ts b/frontend/src/store/modules/connectionTree.ts
deleted file mode 100644
index d4b5403329..0000000000
--- a/frontend/src/store/modules/connectionTree.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-import { useLocalStorage } from "@vueuse/core";
-import { defineStore } from "pinia";
-import { reactive, ref, watch } from "vue";
-import {
- Connection,
- ConnectionAtom,
- ConnectionTreeMode,
- ConnectionAtomType,
- ComposedInstance,
- ComposedDatabase,
-} from "@/types";
-import { ConnectionTreeState, UNKNOWN_ID } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import {
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import { Policy } from "@/types/proto/v1/org_policy_service";
-import { Project } from "@/types/proto/v1/project_service";
-import { emptyConnection } from "@/utils";
-import {
- useDatabaseV1Store,
- useInstanceV1Store,
- useDBSchemaV1Store,
-} from "./v1";
-
-export const ROOT_NODE_ID = "ROOT";
-export const CONNECTION_TREE_DELIMITER = "->";
-
-// Normalize value, fallback to ConnectionTreeMode.PROJECT
-const normalizeConnectionTreeMode = (raw: string) => {
- if (raw === ConnectionTreeMode.INSTANCE) {
- return raw;
- }
- return ConnectionTreeMode.PROJECT;
-};
-
-export const useConnectionTreeStore = defineStore("connectionTree", () => {
- const treeModeInLocalStorage = useLocalStorage<ConnectionTreeMode>(
- "bb.sql-editor.default-connection-tree-mode",
- ConnectionTreeMode.PROJECT,
- {
- serializer: {
- read: normalizeConnectionTreeMode,
- write: normalizeConnectionTreeMode,
- },
- }
- );
-
- // states
- const accessControlPolicyList = ref<Policy[]>([]);
- const tree = reactive({
- databaseList: [] as ComposedDatabase[],
- data: [] as ConnectionAtom[],
- mode: treeModeInLocalStorage.value,
- state: ConnectionTreeState.UNSET,
- });
- const expandedTreeNodeKeys = ref<string[]>([]);
-
- // actions
- const fetchConnectionByInstanceIdAndDatabaseId = async (
- instanceId: string,
- databaseId: string
- ): Promise<Connection> => {
- try {
- const [db, _] = await Promise.all([
- useDatabaseV1Store().getOrFetchDatabaseByUID(databaseId),
- useInstanceV1Store().getOrFetchInstanceByUID(instanceId),
- ]);
- await useDBSchemaV1Store().getOrFetchTableList(db.name);
-
- return {
- instanceId,
- databaseId,
- };
- } catch {
- // Fallback to disconnected if error occurs such as 404.
- return { instanceId: String(UNKNOWN_ID), databaseId: String(UNKNOWN_ID) };
- }
- };
- const fetchConnectionByInstanceId = async (
- instanceId: string
- ): Promise<Connection> => {
- try {
- await useInstanceV1Store().getOrFetchInstanceByUID(instanceId);
-
- return {
- instanceId,
- databaseId: String(UNKNOWN_ID),
- };
- } catch {
- // Fallback to disconnected if error occurs such as 404.
- return { instanceId: String(UNKNOWN_ID), databaseId: String(UNKNOWN_ID) };
- }
- };
- // utilities
- const mapAtom = (
- item:
- | Project
- | ComposedInstance
- | ComposedDatabase
- | SchemaMetadata
- | TableMetadata,
- type: ConnectionAtomType,
- parent: ConnectionAtom | undefined,
- children?: ConnectionAtom[]
- ) => {
- const id = idForConnectionAtomItem(type, item, parent);
- const key = `${type}-${id}`;
- const connectionAtom: ConnectionAtom = {
- parentId: parent?.id ?? ROOT_NODE_ID,
- id,
- key,
- label:
- type === "project"
- ? (item as Project).title
- : type === "instance"
- ? (item as ComposedInstance).title
- : type === "database"
- ? (item as ComposedDatabase).databaseName
- : type === "schema"
- ? (item as SchemaMetadata).name
- : type === "table"
- ? (item as TableMetadata).name
- : "",
- type,
- isLeaf: type === "table",
- children,
- };
- return connectionAtom;
- };
-
- watch(
- () => tree.mode,
- (mode) => {
- treeModeInLocalStorage.value = mode;
- },
- { immediate: true }
- );
-
- return {
- accessControlPolicyList,
- tree,
- expandedTreeNodeKeys,
- fetchConnectionByInstanceIdAndDatabaseId,
- fetchConnectionByInstanceId,
- mapAtom,
- };
-});
-
-export const searchConnectionByName = (
- instanceId: string,
- databaseId: string,
- instanceName: string,
- databaseName: string
-): Connection => {
- const connection = emptyConnection();
- const store = useConnectionTreeStore();
-
- if (instanceId !== String(UNKNOWN_ID)) {
- // If we found instanceId and/or databaseId, use the IDs first.
- connection.instanceId = instanceId;
- if (databaseId !== String(UNKNOWN_ID)) {
- connection.databaseId = databaseId;
- }
-
- return connection;
- }
-
- // Search the instance and database by name otherwise.
- // Remain this part for legacy sheet support.
- const rootNodes = store.tree.data;
- for (let i = 0; i < rootNodes.length; i++) {
- const maybeInstanceNode = rootNodes[i];
- if (maybeInstanceNode.type !== "instance") {
- // Skip if we met dirty data.
- continue;
- }
- if (maybeInstanceNode.label === instanceName) {
- connection.instanceId = maybeInstanceNode.id;
- if (databaseName) {
- const { children = [] } = maybeInstanceNode;
- for (let j = 0; j < children.length; j++) {
- const maybeDatabaseNode = children[j];
- if (maybeDatabaseNode.type !== "database") {
- // Skip if we met dirty data.
- continue;
- }
- if (maybeDatabaseNode.label === databaseName) {
- connection.databaseId = maybeDatabaseNode.id;
- // Don't go further since we've found the databaseId
- break;
- }
- }
- }
- // Don't go further since we've found the instanceId
- break;
- }
- }
-
- return connection;
-};
-
-export const isConnectableAtom = (atom: ConnectionAtom): boolean => {
- if (atom.disabled) {
- return false;
- }
- if (atom.type === "database") {
- return true;
- }
- if (atom.type === "instance") {
- const instance = useInstanceV1Store().getInstanceByUID(atom.id);
- const { engine } = instance;
- return engine === Engine.MYSQL || engine === Engine.TIDB;
- }
- return false;
-};
-
-export const idForConnectionAtomItem = (
- type: ConnectionAtomType,
- item:
- | Project
- | ComposedInstance
- | ComposedDatabase
- | SchemaMetadata
- | TableMetadata,
- parent: ConnectionAtom | undefined
-) => {
- if (type === "project" || type === "instance" || type === "database") {
- const target = item as Project | ComposedInstance | ComposedDatabase;
- return target.uid;
- }
- if (type === "schema") {
- const target = item as SchemaMetadata;
- return [parent?.id ?? ROOT_NODE_ID, target.name].join(
- CONNECTION_TREE_DELIMITER
- );
- }
- if (type === "table") {
- const target = item as TableMetadata;
- return [parent?.id ?? ROOT_NODE_ID, target.name].join(
- CONNECTION_TREE_DELIMITER
- );
- }
-
- console.error("should never reach this line", type, item);
- return "";
-};
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index 9d1bcae11e..c282774fe4 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -14,7 +14,7 @@ export * from "./project";
export * from "./router";
export * from "./stage";
export * from "./sqlEditor";
-export * from "./connectionTree";
+export * from "./sqlEditorTree";
export * from "./tab";
export * from "./task";
export * from "./uistate";
diff --git a/frontend/src/store/modules/sqlEditorTree.ts b/frontend/src/store/modules/sqlEditorTree.ts
new file mode 100644
index 0000000000..35858cd0d6
--- /dev/null
+++ b/frontend/src/store/modules/sqlEditorTree.ts
@@ -0,0 +1,515 @@
+import { useLocalStorage } from "@vueuse/core";
+import { cloneDeep, head, orderBy, uniqBy } from "lodash-es";
+import { defineStore } from "pinia";
+import { v4 as uuidv4 } from "uuid";
+import { computed, reactive, ref, watch } from "vue";
+import {
+ ComposedDatabase,
+ ComposedInstance,
+ ComposedProject,
+ SQLEditorTreeFactor as Factor,
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeNodeTarget as NodeTarget,
+ SQLEditorTreeNodeType as NodeType,
+ SQLEditorTreeState as TreeState,
+ isValidSQLEditorTreeFactor as isValidFactor,
+ extractSQLEditorLabelFactor as extractLabelFactor,
+ unknownEnvironment,
+ UNKNOWN_ID,
+ SQLEditorTreeNodeMeta as NodeMeta,
+ ExpandableTreeNodeTypes,
+ RichSchemaMetadata,
+ RichTableMetadata,
+ SQLEditorTreeNodeType,
+ StatefulSQLEditorTreeFactor as StatefulFactor,
+ LeafTreeNodeTypes,
+ Connection,
+} from "@/types";
+import { Environment } from "@/types/proto/v1/environment_service";
+import { Policy } from "@/types/proto/v1/org_policy_service";
+import { emptyConnection, getSemanticLabelValue, groupBy } from "@/utils";
+import { useTabStore } from "./tab";
+import {
+ useDBSchemaV1Store,
+ useDatabaseV1Store,
+ useEnvironmentV1Store,
+ useInstanceV1Store,
+ useProjectV1Store,
+} from "./v1";
+
+export const ROOT_NODE_ID = "ROOT";
+// export const SQL_EDITOR_TREE_NODE_ID_DELIMITER = "->";
+
+const defaultFactorList = (): StatefulFactor[] => [
+ {
+ factor: "project",
+ disabled: false,
+ },
+];
+
+const factorListInLocalStorage = useLocalStorage<StatefulFactor[]>(
+ "bb.sql-editor.tree-factor-list",
+ defaultFactorList(),
+ {
+ serializer: {
+ read: (raw: string): StatefulFactor[] => {
+ try {
+ const array = JSON.parse(raw) as StatefulFactor[];
+ if (!Array.isArray(array)) {
+ throw new Error();
+ }
+ const factorList: StatefulFactor[] = [];
+ array.forEach((sf) => {
+ if (isValidFactor(sf.factor)) {
+ factorList.push({
+ factor: sf.factor,
+ disabled: !!sf.disabled,
+ });
+ }
+ });
+ if (factorList.length === 0) {
+ throw new Error();
+ }
+ return factorList;
+ } catch {
+ return defaultFactorList();
+ }
+ },
+ write: (factorList) => JSON.stringify(factorList),
+ },
+ }
+);
+
+export const useSQLEditorTreeStore = defineStore("SQL-Editor-Tree", () => {
+ const nodeListMapById = reactive(new Map<string, TreeNode[]>());
+ // states
+ const accessControlPolicyList = ref<Policy[]>([]);
+ const databaseList = ref<ComposedDatabase[]>([]);
+ const factorList = ref<StatefulFactor[]>(
+ cloneDeep(factorListInLocalStorage.value)
+ );
+ const filteredFactorList = computed(() => {
+ return factorList.value.filter((sf) => !sf.disabled).map((sf) => sf.factor);
+ });
+ const state = ref<TreeState>("UNSET");
+ const expandedKeys = ref<string[]>([]); // mixed factor type
+ const tree = ref<TreeNode[]>([]);
+
+ const collectNode = <T extends NodeType>(node: TreeNode<T>) => {
+ const { type, target } = node.meta;
+ const id = idForSQLEditorTreeNodeTarget(type, target);
+ const nodeList = nodeListMapById.get(id) ?? [];
+ nodeList.push(node);
+ nodeListMapById.set(id, nodeList);
+ };
+ const nodesByTarget = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+ ) => {
+ const id = idForSQLEditorTreeNodeTarget(type, target);
+ return nodeListMapById.get(id) ?? [];
+ };
+
+ const openNodesRecursively = (node: TreeNode, keys: Set<string>) => {
+ if (ExpandableTreeNodeTypes.includes(node.meta.type)) {
+ keys.add(node.key);
+ }
+ if (node.parent) {
+ openNodesRecursively(node.parent, keys);
+ }
+ };
+ const expandNodes = <T extends SQLEditorTreeNodeType>(
+ type: T,
+ target: NodeTarget<T>
+ ) => {
+ const nodes = nodesByTarget(type, target);
+ const keys = new Set(expandedKeys.value);
+ nodes.forEach((node) => {
+ keys.add(node.key);
+ });
+ expandedKeys.value = Array.from(keys);
+ };
+ const buildTree = () => {
+ nodeListMapById.clear();
+ tree.value = buildTreeImpl(databaseList.value, filteredFactorList.value);
+ const openingDatabaseList = resolveOpeningDatabaseListFromTabList();
+ const keys = new Set<string>();
+ // Recursively expand opening databases' parent nodes
+ openingDatabaseList.forEach((meta) => {
+ const db = meta.target;
+ const nodes = nodesByTarget("database", db);
+ nodes.forEach((node) => openNodesRecursively(node, keys));
+ });
+ const tab = useTabStore().currentTab;
+ // Expand current tab's connected database node
+ if (
+ tab.connection.databaseId &&
+ tab.connection.databaseId !== String(UNKNOWN_ID)
+ ) {
+ const db = useDatabaseV1Store().getDatabaseByUID(
+ tab.connection.databaseId
+ );
+ const node = head(nodesByTarget("database", db));
+ if (node) {
+ keys.add(node.key);
+ }
+ }
+ expandedKeys.value = Array.from(keys);
+ };
+ const fetchConnectionByInstanceIdAndDatabaseId = async (
+ instanceId: string,
+ databaseId: string
+ ): Promise<Connection> => {
+ try {
+ const [db, _] = await Promise.all([
+ useDatabaseV1Store().getOrFetchDatabaseByUID(databaseId),
+ useInstanceV1Store().getOrFetchInstanceByUID(instanceId),
+ ]);
+ await useDBSchemaV1Store().getOrFetchTableList(db.name);
+
+ return {
+ instanceId,
+ databaseId,
+ };
+ } catch {
+ // Fallback to disconnected if error occurs such as 404.
+ return { instanceId: String(UNKNOWN_ID), databaseId: String(UNKNOWN_ID) };
+ }
+ };
+ const fetchConnectionByInstanceId = async (
+ instanceId: string
+ ): Promise<Connection> => {
+ try {
+ await useInstanceV1Store().getOrFetchInstanceByUID(instanceId);
+
+ return {
+ instanceId,
+ databaseId: String(UNKNOWN_ID),
+ };
+ } catch {
+ // Fallback to disconnected if error occurs such as 404.
+ return { instanceId: String(UNKNOWN_ID), databaseId: String(UNKNOWN_ID) };
+ }
+ };
+ const cleanup = () => {
+ accessControlPolicyList.value = [];
+ databaseList.value = [];
+ tree.value = [];
+ expandedKeys.value = [];
+ factorList.value = defaultFactorList();
+ nodeListMapById.clear();
+ state.value = "UNSET";
+ };
+
+ watch(
+ factorList,
+ (factorList) => {
+ factorListInLocalStorage.value = factorList;
+ },
+ { immediate: true, deep: true }
+ );
+
+ return {
+ expandedKeys,
+ accessControlPolicyList,
+ databaseList,
+ factorList,
+ filteredFactorList,
+ state,
+ tree,
+ collectNode,
+ nodesByTarget,
+ expandNodes,
+ buildTree,
+ fetchConnectionByInstanceIdAndDatabaseId,
+ fetchConnectionByInstanceId,
+ cleanup,
+ };
+});
+
+export const searchConnectionByName = (
+ instanceId: string,
+ databaseId: string,
+ instanceName: string,
+ databaseName: string
+): Connection => {
+ const connection = emptyConnection();
+ const store = useSQLEditorTreeStore();
+
+ if (instanceId !== String(UNKNOWN_ID)) {
+ // If we found instanceId and/or databaseId, use the IDs first.
+ connection.instanceId = instanceId;
+ if (databaseId !== String(UNKNOWN_ID)) {
+ connection.databaseId = databaseId;
+ }
+
+ return connection;
+ }
+
+ // Search the instance and database by name otherwise.
+ // Remain this part for legacy sheet support.
+ const rootNodes = store.tree;
+ for (let i = 0; i < rootNodes.length; i++) {
+ const maybeInstanceNode = rootNodes[i];
+ if (maybeInstanceNode.meta.type !== "instance") {
+ // Skip if we met dirty data.
+ continue;
+ }
+ if (maybeInstanceNode.label === instanceName) {
+ connection.instanceId = (
+ maybeInstanceNode.meta.target as ComposedInstance
+ ).uid;
+ if (databaseName) {
+ const { children = [] } = maybeInstanceNode;
+ for (let j = 0; j < children.length; j++) {
+ const maybeDatabaseNode = children[j];
+ if (maybeDatabaseNode.meta.type !== "database") {
+ // Skip if we met dirty data.
+ continue;
+ }
+ if (maybeDatabaseNode.label === databaseName) {
+ connection.databaseId = (
+ maybeDatabaseNode.meta.target as ComposedDatabase
+ ).uid;
+ // Don't go further since we've found the databaseId
+ break;
+ }
+ }
+ }
+ // Don't go further since we've found the instanceId
+ break;
+ }
+ }
+
+ return connection;
+};
+
+export const keyForSQLEditorTreeNodeTarget = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+): string => {
+ let prefix: string = type;
+ if (type === "label") {
+ prefix = `label:${(target as NodeTarget<"label">).key}`;
+ }
+ return `${prefix}-${uuidv4()}`;
+};
+
+export const idForSQLEditorTreeNodeTarget = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+) => {
+ if (
+ type === "project" ||
+ type === "instance" ||
+ type === "environment" ||
+ type === "database"
+ ) {
+ return (
+ target as
+ | ComposedProject
+ | ComposedInstance
+ | Environment
+ | ComposedDatabase
+ ).name;
+ }
+ if (type === "schema") {
+ const { database, schema } = target as RichSchemaMetadata;
+ return `${database.name}/schemas/${schema.name || "-"}`;
+ }
+ if (type === "table") {
+ const { database, schema, table } = target as RichTableMetadata;
+ return `${database.name}/schemas/${schema.name || "-"}/tables/${
+ table.name
+ }`;
+ }
+ if (type === "label") {
+ const kv = target as NodeTarget<"label">;
+ return `labels/${kv.key}:${kv.value}`;
+ }
+ if (type === "dummy") {
+ const dummyType = (target as NodeTarget<"dummy">).type;
+ return `dummy-${dummyType}`;
+ }
+
+ throw new Error(
+ `should never reach this line, type=${type}, target=${target}, parent=${parent}`
+ );
+};
+
+const buildSubTree = (
+ databaseList: ComposedDatabase[],
+ parent: TreeNode | undefined,
+ factorList: Factor[],
+ factorIndex: number
+): TreeNode[] => {
+ if (factorIndex === factorList.length) {
+ // the last dimension is database nodes
+ return databaseList.map((db) => {
+ const node = mapTreeNodeByType("database", db, parent);
+ return node;
+ });
+ }
+
+ // group (project, instance, project, label) nodes
+ const nodes: TreeNode[] = [];
+ const factor = factorList[factorIndex];
+ const groups = groupBy(databaseList, (db) =>
+ getSemanticFactorValue(db, factor)
+ );
+ for (const [value, childrenDatabaseList] of groups) {
+ const groupNode = mapGroupNode(factor, value, parent);
+ groupNode.children = buildSubTree(
+ childrenDatabaseList,
+ groupNode,
+ factorList,
+ factorIndex + 1
+ );
+ nodes.push(groupNode);
+ }
+ return sortNodesIfNeeded(nodes, factor);
+};
+
+const sortNodesIfNeeded = (nodes: TreeNode[], factor: Factor) => {
+ if (factor === "environment") {
+ return orderBy(
+ nodes as TreeNode<"environment">[],
+ [(node) => node.meta.target.order],
+ ["asc"]
+ );
+ }
+
+ return nodes;
+};
+
+const buildTreeImpl = (
+ databaseList: ComposedDatabase[],
+ factorList: Factor[]
+): TreeNode[] => {
+ return buildSubTree(
+ databaseList,
+ undefined /* parent */,
+ factorList,
+ 0 /* factorIndex */
+ );
+};
+
+const mapGroupNode = (
+ factor: Factor,
+ value: string,
+ parent: TreeNode | undefined
+) => {
+ if (factor === "environment") {
+ const environment =
+ useEnvironmentV1Store().getEnvironmentByName(value) ??
+ unknownEnvironment();
+ return mapTreeNodeByType("environment", environment, parent);
+ }
+ if (factor === "instance") {
+ const instance = useInstanceV1Store().getInstanceByName(value);
+ return mapTreeNodeByType("instance", instance, parent);
+ }
+ if (factor === "project") {
+ const project = useProjectV1Store().getProjectByName(value);
+ return mapTreeNodeByType("project", project, parent);
+ }
+ // factor is label
+ const key = extractLabelFactor(factor);
+ if (key) {
+ return mapTreeNodeByType(
+ "label",
+ {
+ key,
+ value,
+ },
+ parent
+ );
+ }
+
+ throw new Error(
+ `mapGroupNode: should never reach this line. factor=${factor}, factorValue=${value}`
+ );
+};
+
+export const mapTreeNodeByType = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>,
+ parent: TreeNode | undefined,
+ overrides: Partial<TreeNode<T>> | undefined = undefined
+): TreeNode<T> => {
+ const key = keyForSQLEditorTreeNodeTarget(type, target);
+ const node: TreeNode<T> = {
+ key,
+ meta: { type, target },
+ parent,
+ label: readableTargetByType(type, target),
+ isLeaf: LeafTreeNodeTypes.includes(type),
+ ...overrides,
+ };
+
+ useSQLEditorTreeStore().collectNode(node);
+
+ return node;
+};
+
+const readableTargetByType = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+): string => {
+ if (type === "environment") {
+ return (target as Environment).title;
+ }
+ if (type === "project") {
+ return (target as ComposedProject).title;
+ }
+ if (type === "instance") {
+ return (target as ComposedInstance).title;
+ }
+ if (type === "database") {
+ return (target as ComposedDatabase).databaseName;
+ }
+ if (type === "schema") {
+ return (target as RichSchemaMetadata).schema.name;
+ }
+ if (type === "table") {
+ return (target as RichTableMetadata).table.name;
+ }
+ if (type === "dummy") {
+ // Use empty strings for dummy nodes to make them unsearchable
+ return "";
+ }
+ return (target as NodeTarget<"label">).value;
+};
+
+const getSemanticFactorValue = (db: ComposedDatabase, factor: Factor) => {
+ switch (factor) {
+ case "environment":
+ return db.instanceEntity.environment;
+ case "instance":
+ return db.instance;
+ case "project":
+ return db.project;
+ }
+
+ const key = extractLabelFactor(factor);
+ if (key) {
+ return getSemanticLabelValue(db, key);
+ }
+ console.error("should never reach this line", db, factor);
+ return "";
+};
+
+export const resolveOpeningDatabaseListFromTabList = () => {
+ const { tabList } = useTabStore();
+ return uniqBy(
+ tabList.flatMap<NodeMeta<"database">>((tab) => {
+ const { databaseId } = tab.connection;
+ if (databaseId !== String(UNKNOWN_ID)) {
+ const db = useDatabaseV1Store().getDatabaseByUID(databaseId);
+ return [{ type: "database", target: db }];
+ }
+ return [];
+ }),
+ (meta) => meta.target.name
+ );
+};
diff --git a/frontend/src/types/connectionTree.ts b/frontend/src/types/connectionTree.ts
deleted file mode 100644
index 86e71c9fbd..0000000000
--- a/frontend/src/types/connectionTree.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-export type ConnectionAtomType =
- | "project"
- | "instance"
- | "database"
- | "schema"
- | "table";
-
-export enum ConnectionTreeState {
- UNSET,
- LOADING,
- LOADED,
-}
-
-export enum ConnectionTreeMode {
- PROJECT = "project",
- INSTANCE = "instance",
-}
-
-export interface ConnectionAtom {
- parentId: string;
- id: string;
- key: string;
- label: string;
- type?: ConnectionAtomType;
- children?: ConnectionAtom[];
- disabled?: boolean;
- isLeaf?: boolean;
-}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index a833b3c28b..bb3b20face 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -29,7 +29,7 @@ export * from "./sqlAdvice";
export * from "./store";
export * from "./vcs";
export * from "./sqlEditor";
-export * from "./connectionTree";
+export * from "./sqlEditorTree";
export * from "./tab";
export * from "./sheet";
export * from "./sqlReview";
diff --git a/frontend/src/types/sqlEditorTree.ts b/frontend/src/types/sqlEditorTree.ts
new file mode 100644
index 0000000000..14c3276355
--- /dev/null
+++ b/frontend/src/types/sqlEditorTree.ts
@@ -0,0 +1,152 @@
+import { TreeOption } from "naive-ui";
+import { t } from "@/plugins/i18n";
+import { getCustomProjectTitle } from "@/utils/customTheme";
+import { Engine } from "./proto/v1/common";
+import { SchemaMetadata, TableMetadata } from "./proto/v1/database_service";
+import { Environment } from "./proto/v1/environment_service";
+import { ComposedDatabase, ComposedInstance, ComposedProject } from "./v1";
+
+export type SQLEditorTreeFactor =
+ | "project"
+ | "instance"
+ | "environment"
+ | `label:${string}`; // "label:xxxxx" to group by certain label key
+
+export type StatefulSQLEditorTreeFactor<F extends SQLEditorTreeFactor = any> = {
+ factor: F;
+ disabled: boolean;
+};
+
+export type SQLEditorTreeNodeType =
+ | "project"
+ | "instance"
+ | "environment"
+ | "database"
+ | "schema"
+ | "table"
+ | "label"
+ | "dummy"; // Dummy nodes to display "no tables" etc.
+
+export type RichSchemaMetadata = {
+ database: ComposedDatabase;
+ schema: SchemaMetadata;
+};
+export type RichTableMetadata = {
+ database: ComposedDatabase;
+ schema: SchemaMetadata;
+ table: TableMetadata;
+};
+
+export type SQLEditorTreeNodeTarget<T extends SQLEditorTreeNodeType = any> =
+ T extends "project"
+ ? ComposedProject
+ : T extends "instance"
+ ? ComposedInstance
+ : T extends "environment"
+ ? Environment
+ : T extends "database"
+ ? ComposedDatabase
+ : T extends "schema"
+ ? RichSchemaMetadata
+ : T extends "table"
+ ? RichTableMetadata
+ : T extends "label"
+ ? { key: string; value: string }
+ : T extends "dummy"
+ ? { type: SQLEditorTreeNodeType; error?: unknown }
+ : never;
+
+export type SQLEditorTreeState = "UNSET" | "LOADING" | "READY";
+
+export type SQLEditorTreeNodeMeta<T extends SQLEditorTreeNodeType = any> = {
+ type: T;
+ target: SQLEditorTreeNodeTarget<T>;
+};
+
+export type SQLEditorTreeNode<T extends SQLEditorTreeNodeType = any> =
+ TreeOption & {
+ meta: SQLEditorTreeNodeMeta<T>;
+ key: string;
+ parent?: SQLEditorTreeNode;
+ children?: SQLEditorTreeNode[];
+ };
+
+export const isValidSQLEditorTreeFactor = (
+ str: string
+): str is SQLEditorTreeFactor => {
+ if (str === "project") return true;
+ if (str === "instance") return true;
+ if (str === "environment") return true;
+ if (str.match(/^label:.+$/)) return true;
+ return false;
+};
+
+export const ExpandableTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
+ "instance",
+ "environment",
+ "project",
+ "label",
+] as const;
+
+export const ConnectableTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
+ "instance",
+ "database",
+] as const;
+
+export const LeafTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
+ "table",
+ "dummy",
+] as const;
+
+export const extractSQLEditorLabelFactor = (factor: string) => {
+ const matches = factor.match(/^label:(.+)$/);
+ if (!matches) return "";
+ return matches[1] ?? "";
+};
+
+export const readableSQLEditorTreeFactor = (
+ factor: SQLEditorTreeFactor,
+ labelPrefix: string | undefined = ""
+) => {
+ if (factor === "project") {
+ return getCustomProjectTitle();
+ }
+ if (factor === "environment") {
+ return t("common.environment");
+ }
+ if (factor === "instance") {
+ return t("common.instance");
+ }
+ const label = extractSQLEditorLabelFactor(factor);
+
+ return `${labelPrefix}${label}`;
+};
+
+export const isConnectableSQLEditorTreeNode = (
+ node: SQLEditorTreeNode
+): boolean => {
+ if (node.disabled) {
+ return false;
+ }
+ const { type, target } = node.meta;
+ if (type === "database") {
+ return true;
+ }
+ if (type === "instance") {
+ const instance = target as ComposedInstance;
+ const { engine } = instance;
+ return engine === Engine.MYSQL || engine === Engine.TIDB;
+ }
+ return false;
+};
+
+export const instanceOfSQLEditorTreeNode = (node: SQLEditorTreeNode) => {
+ const { type, target } = node.meta;
+ if (type === "instance") {
+ return target as ComposedInstance;
+ }
+ if (type === "database") {
+ return (target as ComposedDatabase).instanceEntity;
+ }
+ return undefined;
+};
diff --git a/frontend/src/utils/tab.ts b/frontend/src/utils/tab.ts
index 8ad590b71b..455d53a0f8 100644
--- a/frontend/src/utils/tab.ts
+++ b/frontend/src/utils/tab.ts
@@ -5,7 +5,6 @@ import type {
ComposedDatabase,
ComposedInstance,
Connection,
- ConnectionAtom,
CoreTabInfo,
TabInfo,
TabSheetType,
@@ -108,16 +107,6 @@ export const getSuggestedTabNameFromConnection = (conn: Connection) => {
return parts.join(" ");
};
-export const instanceOfConnectionAtom = (atom: ConnectionAtom) => {
- if (atom.type === "instance") {
- return useInstanceV1Store().getInstanceByUID(atom.id);
- }
- if (atom.type === "database") {
- return useDatabaseV1Store().getDatabaseByUID(atom.id).instanceEntity;
- }
- return undefined;
-};
-
export const isDisconnectedTab = (tab: TabInfo) => {
const { instanceId, databaseId } = tab.connection;
if (instanceId === String(UNKNOWN_ID)) {
diff --git a/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.ts b/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.ts
index ede5dc938e..2ccbf8ea96 100644
--- a/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.ts
+++ b/frontend/src/views/Changelist/ChangelistDetail/NavBar/export.ts
@@ -29,6 +29,7 @@ const zipFileForChangeHistory = async (
const name = change.source;
const { changeHistory, type, statement } =
await useChangeHistoryStore().exportChangeHistoryFullStatementByName(name);
+ console.log("export", change, changeHistory, type, statement.length);
if (changeHistory) {
if (changeHistory.status !== ChangeHistory_Status.DONE) {
return;
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
index 348c5cec34..ab9033c095 100644
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
@@ -1,77 +1,16 @@
<template>
- <div class="aside-panel h-full">
- <NTabs
- v-if="hasInstanceView"
- v-model:value="databaseTab"
- type="segment"
- size="small"
- class="primary-sidebar h-full"
- pane-style="height: calc(100% - 35px); padding: 0;"
- >
- <NTabPane name="projects" :tab="projectTitle">
- <DatabaseTree
- key="sql-editor-database-tree"
- v-model:search-pattern="searchPattern"
- />
- </NTabPane>
- <NTabPane name="instances" :tab="$t('common.instance')">
- <DatabaseTree
- key="sql-editor-database-tree"
- v-model:search-pattern="searchPattern"
- />
- </NTabPane>
- </NTabs>
- <div v-else class="primary-sidebar h-full">
- <DatabaseTree
- key="sql-editor-database-tree"
- v-model:search-pattern="searchPattern"
- />
+ <div class="aside-panel h-full flex flex-col overflow-hidden">
+ <GroupingBar />
+ <div class="flex-1 overflow-hidden">
+ <DatabaseTree v-model:search-pattern="searchPattern" />
</div>
</div>
</template>
<script lang="ts" setup>
-import { NTabs, NTabPane } from "naive-ui";
-import { computed, ref, watchEffect } from "vue";
-import { useConnectionTreeStore, useCurrentUserV1 } from "@/store";
-import { ConnectionTreeMode } from "@/types";
-import { hasWorkspacePermissionV1 } from "@/utils";
-import { getCustomProjectTitle } from "@/utils/customTheme";
+import { ref } from "vue";
import DatabaseTree from "./DatabaseTree.vue";
+import GroupingBar from "./GroupingBar";
-const currentUserV1 = useCurrentUserV1();
-const connectionTreeStore = useConnectionTreeStore();
const searchPattern = ref("");
-
-const databaseTab = ref<"projects" | "instances">(
- connectionTreeStore.tree.mode === ConnectionTreeMode.INSTANCE
- ? "instances"
- : "projects"
-);
-
-const projectTitle = computed(() => {
- return getCustomProjectTitle();
-});
-
-const hasInstanceView = computed((): boolean => {
- return hasWorkspacePermissionV1(
- "bb.permission.workspace.manage-database",
- currentUserV1.value.userRole
- );
-});
-
-watchEffect(() => {
- if (databaseTab.value === "projects") {
- connectionTreeStore.tree.mode = ConnectionTreeMode.PROJECT;
- }
- if (databaseTab.value === "instances") {
- connectionTreeStore.tree.mode = ConnectionTreeMode.INSTANCE;
- }
-});
</script>
-
-<style lang="postcss">
-.primary-sidebar .n-tabs-rail {
- @apply pt-1;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
index ee8a9865e8..8ca23e23b6 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
@@ -1,10 +1,9 @@
<template>
<div
- v-if="connectionTreeStore.tree.state === ConnectionTreeState.LOADED"
- class="databases-tree p-0.5 gap-y-1 h-full flex flex-col"
- :class="connectionTreeStore.tree.mode"
+ v-if="treeStore.state === 'READY'"
+ class="sql-editor-tree p-0.5 gap-y-1 h-full flex flex-col"
>
- <div class="databases-tree--input pt-1 px-2">
+ <div class="sql-editor-tree--input pt-1 px-2">
<NInput
size="small"
:value="searchPattern"
@@ -17,23 +16,21 @@
</template>
</NInput>
</div>
- <div class="databases-tree--tree flex-1 overflow-y-auto select-none">
+ <div class="sql-editor-tree--tree flex-1 overflow-y-auto select-none">
<NTree
ref="treeRef"
+ v-model:expanded-keys="treeStore.expandedKeys"
block-line
- :data="treeData"
- :pattern="mounted ? throttledSearchPattern : ''"
+ :data="treeStore.tree"
:show-irrelevant-nodes="false"
- :expand-on-click="true"
:selected-keys="selectedKeys"
- :expanded-keys="expandedTreeNodeKeysForCurrentTreeMode"
- :render-label="renderLabel"
- :render-prefix="renderPrefix"
+ :pattern="mounted ? throttledSearchPattern : ''"
+ :expand-on-click="true"
:node-props="nodeProps"
:virtual-scroll="true"
:theme-overrides="{ nodeHeight: '21px' }"
+ :render-label="renderLabel"
@load="handleLoadSubTree"
- @update:expanded-keys="updateExpandedKeys"
/>
</div>
@@ -55,42 +52,46 @@
<script lang="ts" setup>
import { useMounted, useThrottleFn } from "@vueuse/core";
+import { head } from "lodash-es";
import { NTree, NInput, NDropdown, DropdownOption, TreeOption } from "naive-ui";
-import { ref, computed, h, nextTick, watch } from "vue";
+import { ref, computed, nextTick, watch, h } from "vue";
import { useI18n } from "vue-i18n";
import {
- isConnectableAtom,
- useConnectionTreeStore,
useCurrentUserV1,
+ useDBSchemaV1Store,
useDatabaseV1Store,
useInstanceV1Store,
- useSQLEditorStore,
useIsLoggedIn,
+ useSQLEditorStore,
useTabStore,
- CONNECTION_TREE_DELIMITER,
- useDBSchemaV1Store,
} from "@/store";
-import type { ConnectionAtom, CoreTabInfo } from "@/types";
+import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import type {
+ ComposedDatabase,
+ ComposedInstance,
+ CoreTabInfo,
+ SQLEditorTreeNode,
+ SQLEditorTreeNodeTarget,
+} from "@/types";
import {
- ConnectionTreeMode,
- ConnectionTreeState,
+ ConnectableTreeNodeTypes,
TabMode,
UNKNOWN_ID,
+ instanceOfSQLEditorTreeNode,
+ isConnectableSQLEditorTreeNode,
} from "@/types";
-import { SchemaMetadata } from "@/types/proto/v1/database_service";
import {
emptyConnection,
getSuggestedTabNameFromConnection,
hasWorkspacePermissionV1,
- instanceV1HasReadonlyMode,
- instanceOfConnectionAtom,
+ instanceV1AllowsCrossDatabaseQuery,
instanceV1HasAlterSchema,
+ instanceV1HasReadonlyMode,
isDescendantOf,
isSimilarTab,
- instanceV1AllowsCrossDatabaseQuery,
} from "@/utils";
import { useSQLEditorContext } from "../context";
-import { Prefix, Label } from "./TreeNode";
+import { Label } from "./TreeNode";
import { fetchDatabaseSubTree } from "./common";
type Position = {
@@ -98,8 +99,8 @@ type Position = {
y: number;
};
-type DropdownOptionWithConnectionAtom = DropdownOption & {
- item: ConnectionAtom;
+type DropdownOptionWithTreeNode = DropdownOption & {
+ node: SQLEditorTreeNode;
};
const props = defineProps<{
@@ -111,14 +112,13 @@ defineEmits<{
}>();
const { t } = useI18n();
-
-const instanceStore = useInstanceV1Store();
-const databaseStore = useDatabaseV1Store();
-const connectionTreeStore = useConnectionTreeStore();
+const sqlEditorStore = useSQLEditorStore();
+const treeStore = useSQLEditorTreeStore();
const tabStore = useTabStore();
+const databaseStore = useDatabaseV1Store();
+const instanceStore = useInstanceV1Store();
const isLoggedIn = useIsLoggedIn();
-const currentUserV1 = useCurrentUserV1();
-const sqlEditorStore = useSQLEditorStore();
+const me = useCurrentUserV1();
const { selectedDatabaseSchemaByDatabaseName, events: editorEvents } =
useSQLEditorContext();
@@ -130,47 +130,48 @@ const dropdownPosition = ref<Position>({
x: 0,
y: 0,
});
-const dropdownContext = ref<ConnectionAtom>();
+const dropdownContext = ref<SQLEditorTreeNode>();
-const dropdownOptions = computed((): DropdownOptionWithConnectionAtom[] => {
- const atom = dropdownContext.value;
- if (!atom) {
+const dropdownOptions = computed((): DropdownOptionWithTreeNode[] => {
+ const node = dropdownContext.value;
+ if (!node) {
return [];
}
- if (atom.type === "project") {
+ const { type, target } = node.meta;
+ if (type === "project") {
return [];
} else {
// Don't show any context menu actions for disabled
// instances/databases
- if (atom.disabled) {
+ if (node.disabled) {
return [];
}
- const items: DropdownOptionWithConnectionAtom[] = [];
- if (isConnectableAtom(atom)) {
- const instance = instanceOfConnectionAtom(atom);
+ const items: DropdownOptionWithTreeNode[] = [];
+ if (isConnectableSQLEditorTreeNode(node)) {
+ const instance = instanceOfSQLEditorTreeNode(node);
if (instance && instanceV1HasReadonlyMode(instance)) {
items.push({
key: "connect",
label: t("sql-editor.connect"),
- item: atom,
+ node,
});
}
if (allowAdmin.value) {
items.push({
key: "connect-in-admin-mode",
label: t("sql-editor.connect-in-admin-mode"),
- item: atom,
+ node,
});
}
}
- if (atom.type === "database" && sqlEditorStore.mode === "BUNDLED") {
- const database = databaseStore.getDatabaseByUID(atom.id);
+ if (type === "database" && sqlEditorStore.mode === "BUNDLED") {
+ const database = target as ComposedDatabase;
if (instanceV1HasAlterSchema(database.instanceEntity)) {
items.push({
key: "alter-schema",
label: t("database.edit-schema"),
- item: atom,
+ node,
});
}
}
@@ -183,25 +184,30 @@ const selectedKeys = computed(() => {
const { instanceId, databaseId } = tabStore.currentTab.connection;
if (databaseId !== String(UNKNOWN_ID)) {
- const db = databaseStore.getDatabaseByUID(databaseId);
- const selected = selectedDatabaseSchemaByDatabaseName.value.get(db.name);
+ const database = databaseStore.getDatabaseByUID(databaseId);
+ const node = head(treeStore.nodesByTarget("database", database));
+ if (!node) return [];
+ const selected = selectedDatabaseSchemaByDatabaseName.value.get(
+ database.name
+ );
if (selected) {
const { schema, table } = selected;
- if (schema.name) {
- return [
- `table-${[db.uid, schema.name, table.name].join(
- CONNECTION_TREE_DELIMITER
- )}`,
- ];
- } else {
- return [
- `table-${[db.uid, table.name].join(CONNECTION_TREE_DELIMITER)}`,
- ];
+ const tableNode = head(
+ treeStore.nodesByTarget("table", {
+ database,
+ schema,
+ table,
+ })
+ );
+ if (tableNode) {
+ return [tableNode.key];
}
}
- return [`database-${databaseId}`];
+ return [node.key];
} else if (instanceId !== String(UNKNOWN_ID)) {
- return [`instance-${instanceId}`];
+ const instance = instanceStore.getInstanceByUID(instanceId);
+ const nodes = treeStore.nodesByTarget("instance", instance);
+ return nodes.map((node) => node.key);
}
return [];
});
@@ -209,12 +215,10 @@ const selectedKeys = computed(() => {
const allowAdmin = computed(() =>
hasWorkspacePermissionV1(
"bb.permission.workspace.admin-sql-editor",
- currentUserV1.value.userRole
+ me.value.userRole
)
);
-const treeData = computed(() => connectionTreeStore.tree.data);
-
const connect = (target: CoreTabInfo) => {
if (isSimilarTab(target, tabStore.currentTab)) {
// Don't go further if the connection doesn't change.
@@ -236,60 +240,51 @@ const connect = (target: CoreTabInfo) => {
};
const setConnection = (
- option: ConnectionAtom,
+ node: SQLEditorTreeNode,
extra: { sheetName?: string; mode: TabMode } = {
sheetName: undefined,
mode: TabMode.ReadOnly,
}
) => {
- if (option) {
- if (option.type === "schema" || option.type === "table") {
- // Should be handled in maybeSelectTable
- return;
- }
-
- if (option.type === "project") {
- // Not connectable to a project
+ if (node) {
+ const { type } = node.meta;
+ if (!ConnectableTreeNodeTypes.includes(type)) {
return;
}
-
- if (option.type === "instance") {
- const instance = instanceStore.getInstanceByUID(option.id);
+ if (type === "instance") {
+ const instance = node.meta.target as ComposedInstance;
if (!instanceV1AllowsCrossDatabaseQuery(instance)) {
return;
}
}
-
const target: CoreTabInfo = {
connection: emptyConnection(),
...extra,
};
const conn = target.connection;
-
// If selected item is instance node
- if (option.type === "instance") {
- conn.instanceId = option.id;
- } else if (option.type === "database") {
- // If selected item is database node
- const database = databaseStore.getDatabaseByUID(option.id);
+ if (type === "instance") {
+ const instance = node.meta.target as ComposedInstance;
+ conn.instanceId = instance.uid;
+ }
+ // If selected item is database node
+ if (type === "database") {
+ const database = node.meta.target as ComposedDatabase;
conn.instanceId = database.instanceEntity.uid;
conn.databaseId = database.uid;
}
-
connect(target);
}
};
// dynamic render the highlight keywords
const renderLabel = ({ option }: { option: TreeOption }) => {
- const atom = option as any as ConnectionAtom;
- return h(Label, { atom, keyword: props.searchPattern ?? "" });
-};
-
-// Render icons before nodes.
-const renderPrefix = ({ option }: { option: TreeOption }) => {
- const atom = option as any as ConnectionAtom;
- return h(Prefix, { atom });
+ const node = option as any as SQLEditorTreeNode;
+ return h(Label, {
+ node,
+ factors: treeStore.filteredFactorList,
+ keyword: props.searchPattern ?? "",
+ });
};
const handleSelect = (key: string) => {
@@ -297,19 +292,18 @@ const handleSelect = (key: string) => {
if (!option) {
return;
}
-
if (key === "alter-schema") {
+ const db = option.node.meta.target as ComposedDatabase;
editorEvents.emit("alter-schema", {
- databaseUID: option.item.id,
+ databaseUID: db.uid,
schema: "",
table: "",
});
} else if (key === "connect") {
- setConnection(option.item);
+ setConnection(option.node);
} else if (key === "connect-in-admin-mode") {
- setConnection(option.item, { mode: TabMode.Admin });
+ setConnection(option.node, { mode: TabMode.Admin });
}
-
showDropdown.value = false;
};
@@ -317,31 +311,9 @@ const handleClickoutside = () => {
showDropdown.value = false;
};
-const expandedTreeNodeKeysForCurrentTreeMode = computed(() => {
- const { tree, expandedTreeNodeKeys } = connectionTreeStore;
- switch (tree.mode) {
- case ConnectionTreeMode.INSTANCE:
- return expandedTreeNodeKeys.filter((key) => !key.startsWith("project-"));
- case ConnectionTreeMode.PROJECT:
- return expandedTreeNodeKeys.filter((key) => !key.startsWith("instance-"));
- }
- // Fallback to make TypeScript compiler happy
- return [];
-});
-
-const maybeExpandKey = (key: string) => {
- const keys = connectionTreeStore.expandedTreeNodeKeys;
- if (!keys.includes(key)) {
- keys.push(key);
- }
-};
-
-const maybeSelectTable = async (atom: ConnectionAtom) => {
- const parts = atom.id.split(CONNECTION_TREE_DELIMITER);
- if (parts.length < 2 || parts.length > 3) {
- return;
- }
- const database = databaseStore.getDatabaseByUID(parts[0]);
+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 = {
connection: {
@@ -352,60 +324,42 @@ const maybeSelectTable = async (atom: ConnectionAtom) => {
};
target.connection.instanceId = database.instanceEntity.uid;
target.connection.databaseId = database.uid;
-
connect(target);
await nextTick();
}
const databaseMetadata =
await useDBSchemaV1Store().getOrFetchDatabaseMetadata(database.name);
- let schemaMetadata: SchemaMetadata | undefined = undefined;
- if (parts.length === 2) {
- // database -> table
- schemaMetadata = databaseMetadata.schemas.find((s) => s.name === "");
- }
- if (parts.length === 3) {
- // database -> schema -> table
- const schema = parts[1];
- schemaMetadata = databaseMetadata.schemas.find((s) => s.name === schema);
- }
- if (!schemaMetadata) {
- return;
- }
- const table = parts[parts.length - 1];
- const tableMetadata = schemaMetadata.tables.find((t) => t.name === table);
- if (!tableMetadata) {
- return;
- }
selectedDatabaseSchemaByDatabaseName.value.set(database.name, {
db: database,
database: databaseMetadata,
- schema: schemaMetadata,
- table: tableMetadata,
+ schema,
+ table,
});
};
const nodeProps = ({ option }: { option: TreeOption }) => {
- const atom = option as any as ConnectionAtom;
+ const node = option as any as SQLEditorTreeNode;
return {
onClick(e: MouseEvent) {
- if (atom.disabled) return;
+ if (node.disabled) return;
if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {
+ const { type } = node.meta;
// Check if clicked on the content part.
// And ignore the fold/unfold arrow.
- if (atom.type === "instance" || atom.type === "database") {
- setConnection(atom);
+ if (type === "instance" || type === "database") {
+ setConnection(node);
}
- if (atom.type === "table") {
- maybeSelectTable(atom);
+ if (type === "table") {
+ maybeSelectTable(node);
}
}
},
onContextmenu(e: MouseEvent) {
e.preventDefault();
showDropdown.value = false;
- if (atom && atom.key) {
- dropdownContext.value = atom;
+ if (node && node.key) {
+ dropdownContext.value = node;
}
nextTick().then(() => {
@@ -414,43 +368,43 @@ const nodeProps = ({ option }: { option: TreeOption }) => {
dropdownPosition.value.y = e.clientY;
});
},
- "data-node-type": atom.type,
+ "data-node-type": node.type,
};
};
-const handleLoadSubTree = (node: TreeOption) => {
- const atom = node as any as ConnectionAtom;
- const type = atom.type;
+const handleLoadSubTree = (option: TreeOption) => {
+ const node = option as any as SQLEditorTreeNode;
+ const { type, target } = node.meta;
if (type === "database") {
- return fetchDatabaseSubTree(atom);
+ const request = fetchDatabaseSubTree(node);
+ request
+ .then(() => nextTick())
+ .then(() => treeStore.expandNodes(type, target));
+ return request;
}
return Promise.resolve();
};
-const updateExpandedKeys = (keys: string[]) => {
- connectionTreeStore.expandedTreeNodeKeys = keys;
-};
-
// When switching tabs, scroll the matched node into view if needed.
-const scrollToConnectedNode = (instanceId: string, databaseId: string) => {
- if (instanceId === String(UNKNOWN_ID) && databaseId === String(UNKNOWN_ID)) {
- return;
- }
- const tree = treeRef.value;
- if (!tree) {
- return;
- }
- const key =
- databaseId !== String(UNKNOWN_ID)
- ? `database-${databaseId}`
- : `instance-${instanceId}`;
-
- nextTick(() => {
- tree.scrollTo({
- key,
- });
- });
-};
+// const scrollToConnectedNode = (instanceId: string, databaseId: string) => {
+// if (instanceId === String(UNKNOWN_ID) && databaseId === String(UNKNOWN_ID)) {
+// return;
+// }
+// const tree = treeRef.value;
+// if (!tree) {
+// return;
+// }
+// const key =
+// databaseId !== String(UNKNOWN_ID)
+// ? `database-${databaseId}`
+// : `instance-${instanceId}`;
+
+// nextTick(() => {
+// tree.scrollTo({
+// key,
+// });
+// });
+// };
// Open corresponding tree node when the connection changed.
watch(
@@ -458,28 +412,28 @@ watch(
isLoggedIn,
() => tabStore.currentTab.connection.instanceId,
() => tabStore.currentTab.connection.databaseId,
- () => connectionTreeStore.tree.state,
+ () => treeStore.state,
],
([isLoggedIn, instanceId, databaseId, treeState]) => {
if (!isLoggedIn) {
// Don't go further and cleanup the state if we signed out.
- connectionTreeStore.expandedTreeNodeKeys = [];
+ treeStore.expandedKeys = [];
return;
}
- if (treeState !== ConnectionTreeState.LOADED) {
+ if (treeState !== "READY") {
return;
}
if (instanceId !== String(UNKNOWN_ID)) {
- maybeExpandKey(`instance-${instanceId}`);
+ const instance = instanceStore.getInstanceByUID(instanceId);
+ treeStore.expandNodes("instance", instance);
}
if (databaseId !== String(UNKNOWN_ID)) {
const db = databaseStore.getDatabaseByUID(databaseId);
- const projectId = db.projectEntity.uid;
- maybeExpandKey(`project-${projectId}`);
+ treeStore.expandNodes("database", db);
}
- scrollToConnectedNode(instanceId, databaseId);
+ // scrollToConnectedNode(instanceId, databaseId);
},
{ immediate: true }
);
@@ -498,37 +452,51 @@ watch(
immediate: true,
}
);
+
+watch(
+ selectedKeys,
+ (keys) => {
+ if (keys.length !== 1) return;
+ const key = keys[0];
+ nextTick(() => {
+ treeRef.value?.scrollTo({ key });
+ });
+ },
+ { immediate: true }
+);
</script>
-<style lang="postcss">
-.databases-tree .n-tree-node-content {
+<style lang="postcss" scoped>
+.sql-editor-tree :deep(.n-tree .v-vl) {
+ --n-node-content-height: 21px !important;
+}
+.sql-editor-tree :deep(.n-tree-node-content) {
@apply !pl-0 text-sm;
}
-.databases-tree .n-tree-node-wrapper {
+.sql-editor-tree :deep(.n-tree-node-wrapper) {
padding: 0;
}
-.databases-tree .n-tree-node-indent {
+.sql-editor-tree :deep(.n-tree-node-indent) {
width: 0.25rem;
}
-.databases-tree .n-tree-node-content__prefix {
+.sql-editor-tree :deep(.n-tree-node-content__prefix) {
@apply shrink-0 !mr-1;
}
-.databases-tree.project
- .n-tree-node[data-node-type="project"]
- .n-tree-node-content__prefix {
+.sql-editor-tree.project
+ :deep(.n-tree-node[data-node-type="project"] .n-tree-node-content__prefix) {
@apply hidden;
}
-.databases-tree .n-tree-node-content__text {
+.sql-editor-tree :deep(.n-tree-node-content__text) {
@apply truncate mr-1;
}
-.databases-tree .n-tree-node--pending {
+.sql-editor-tree :deep(.n-tree-node--pending) {
background-color: transparent !important;
}
-.databases-tree .n-tree-node--pending:hover {
+.sql-editor-tree :deep(.n-tree-node--pending:hover) {
background-color: var(--n-node-color-hover) !important;
}
-.databases-tree .n-tree-node--selected,
-.databases-tree .n-tree-node--selected:hover {
+.sql-editor-tree :deep(.n-tree-node--selected),
+.sql-editor-tree :deep(.n-tree-node--selected:hover) {
background-color: var(--n-node-color-active) !important;
}
</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue
new file mode 100644
index 0000000000..0e76e64a3a
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue
@@ -0,0 +1,51 @@
+<template>
+ <div class="px-0.5">
+ <NCheckbox
+ :checked="checked"
+ :disabled="disabled"
+ @update:checked="handleToggleChecked"
+ >
+ {{ readableSQLEditorTreeFactor(factor) }}
+ </NCheckbox>
+ </div>
+</template>
+<script lang="ts" setup>
+import { NCheckbox } from "naive-ui";
+import { storeToRefs } from "pinia";
+import { computed } from "vue";
+import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import {
+ SQLEditorTreeFactor as Factor,
+ readableSQLEditorTreeFactor,
+} from "@/types";
+
+const props = defineProps<{
+ factor: Factor;
+}>();
+const emit = defineEmits<{
+ (event: "toggle", on: boolean): void;
+}>();
+
+const treeStore = useSQLEditorTreeStore();
+const { factorList } = storeToRefs(treeStore);
+
+const allowRemove = computed(() => {
+ // Not allowed to remove the only one factor
+ return factorList.value.length > 1;
+});
+const checked = computed(() => {
+ return factorList.value.findIndex((sf) => sf.factor === props.factor) >= 0;
+});
+const disabled = computed(() => {
+ if (checked.value) {
+ if (!allowRemove.value) return true;
+ }
+ return false;
+});
+
+const handleToggleChecked = (on: boolean) => {
+ if (disabled.value) return;
+ if (on === checked.value) return;
+ emit("toggle", on);
+};
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
new file mode 100644
index 0000000000..d1b7fc3645
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
@@ -0,0 +1,68 @@
+<template>
+ <div class="bg-white flex flex-col gap-y-2 w-max p-2">
+ <FactorItem
+ v-for="(factor, i) in PRESET_FACTORS"
+ :key="i"
+ :factor="factor"
+ @toggle="toggle(factor, $event)"
+ />
+ <template v-if="labelFactors.length > 0">
+ <div class="text-control-placeholder font-medium">
+ {{ $t("common.labels") }}
+ </div>
+ <FactorItem
+ v-for="(factor, i) in labelFactors"
+ :key="i"
+ :factor="factor"
+ @toggle="toggle(factor, $event)"
+ />
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { cloneDeep, orderBy, uniq } from "lodash-es";
+import { storeToRefs } from "pinia";
+import { computed } from "vue";
+import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import { SQLEditorTreeFactor as Factor } from "@/types";
+import FactorItem from "./FactorItem.vue";
+
+const treeStore = useSQLEditorTreeStore();
+const { databaseList, factorList } = storeToRefs(treeStore);
+
+const PRESET_FACTORS: Factor[] = ["project", "instance", "environment"];
+
+const labelFactors = computed(() => {
+ return orderBy(
+ uniq(databaseList.value.flatMap((db) => Object.keys(db.labels))).map(
+ (key) => `label:${key}` as Factor
+ ),
+ [(key) => key],
+ ["asc"] // lexicographical order
+ );
+});
+
+const toggle = (factor: Factor, on: boolean) => {
+ const updatedList = cloneDeep(factorList.value);
+ const index = updatedList.findIndex((sf) => sf.factor === factor);
+ if (index >= 0) {
+ if (on) return; // no duplicated factors
+ updatedList.splice(index, 1);
+ } else {
+ if (!on) return; // nothing to remove
+ updatedList.push({
+ factor,
+ disabled: false,
+ });
+ }
+ if (updatedList.every((sf) => sf.disabled)) {
+ // When all left factors are disabled
+ // Enforce the first one to enable
+ updatedList[0].disabled = false;
+ }
+
+ factorList.value = updatedList;
+ treeStore.buildTree();
+};
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue
new file mode 100644
index 0000000000..17a58bee9f
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue
@@ -0,0 +1,72 @@
+<template>
+ <div
+ class="border px-2 relative rounded-sm group bg-white"
+ :class="
+ clickable ? 'cursor-pointer hover:bg-gray-100' : 'cursor-not-allowed'
+ "
+ @click.stop="handleClick"
+ >
+ <span class="leading-6" :class="factor.disabled && 'line-through'">
+ {{ readableSQLEditorTreeFactor(factor.factor) }}
+ </span>
+ <button
+ v-if="allowRemove"
+ class="hidden group-hover:flex bg-gray-100 absolute rounded-full top-0 right-0 hover:bg-gray-300 z-10 translate-x-[50%] translate-y-[-50%] w-3 h-3 items-center justify-center"
+ @click.stop="$emit('remove')"
+ >
+ <heroicons:x-mark class="w-2.5 h-2.5" />
+ </button>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { storeToRefs } from "pinia";
+import { computed } from "vue";
+import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import {
+ StatefulSQLEditorTreeFactor as StatefulFactor,
+ readableSQLEditorTreeFactor,
+} from "@/types";
+
+const props = defineProps<{
+ factor: StatefulFactor;
+}>();
+const emit = defineEmits<{
+ (event: "toggle-disabled"): void;
+ (event: "remove"): void;
+}>();
+const treeStore = useSQLEditorTreeStore();
+const { factorList, filteredFactorList } = storeToRefs(treeStore);
+
+const allowDisable = computed(() => {
+ // Disallow to disable the only one enabled factor
+ return filteredFactorList.value.length > 1;
+});
+
+const allowRemove = computed(() => {
+ if (factorList.value.length <= 1) {
+ // Disallow to remove the only one factor
+ return false;
+ }
+ const { factor } = props;
+ if (!factor.disabled) {
+ if (filteredFactorList.value.length <= 1) {
+ // Disallow to remove the only one enabled factor
+ return false;
+ }
+ }
+ return true;
+});
+
+const clickable = computed(() => {
+ if (props.factor.disabled) return true;
+ return allowDisable.value;
+});
+
+const handleClick = () => {
+ if (!clickable.value) {
+ return;
+ }
+ emit("toggle-disabled");
+};
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue
new file mode 100644
index 0000000000..84f10906a2
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue
@@ -0,0 +1,108 @@
+<template>
+ <div class="flex flex-row items-start min-h-[34px] pt-0.5 bg-gray-50">
+ <div class="flex-1">
+ <NTabs
+ v-if="viewMode === 'PRESET'"
+ :value="factorList[0].factor"
+ type="segment"
+ size="small"
+ class="grouping-bar--tabs"
+ @update:value="selectPresetFactor"
+ >
+ <NTab name="project">{{ $t("common.project") }}</NTab>
+ <NTab name="instance">{{ $t("common.instance") }}</NTab>
+ </NTabs>
+ <div
+ v-if="viewMode === 'CUSTOM'"
+ class="flex flex-row items-start text-sm"
+ >
+ <div class="text-control-light p-1 whitespace-nowrap leading-6">
+ {{ $t("sql-editor.grouping") }}
+ </div>
+ <div class="flex flex-row items-start flex-wrap p-1 gap-x-2 gap-y-2">
+ <FactorTag
+ v-for="(factor, i) in factorList"
+ :key="i"
+ :factor="factor"
+ :allow-disable="filteredFactorList.length > 1"
+ @toggle-disabled="toggleDisabled(factor, i)"
+ @remove="remove(factor, i)"
+ />
+ </div>
+ </div>
+ </div>
+
+ <div class="shrink-0 p-1">
+ <NPopover
+ raw
+ :show-arrow="false"
+ to="body"
+ placement="bottom-start"
+ trigger="click"
+ >
+ <template #trigger>
+ <NButton quaternary size="small" style="--n-padding: 0 5px">
+ <template #icon>
+ <heroicons:adjustments-horizontal
+ class="w-4 h-4"
+ :class="viewMode === 'CUSTOM' && 'text-accent'"
+ />
+ </template>
+ </NButton>
+ </template>
+ <template #default>
+ <FactorPanel />
+ </template>
+ </NPopover>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NButton, NPopover, NTab, NTabs } from "naive-ui";
+import { storeToRefs } from "pinia";
+import { computed } from "vue";
+import { useSQLEditorTreeStore } from "@/store/modules/sqlEditorTree";
+import { StatefulSQLEditorTreeFactor as StatefulFactor } from "@/types";
+import FactorPanel from "./FactorPanel.vue";
+import FactorTag from "./FactorTag.vue";
+
+const treeStore = useSQLEditorTreeStore();
+const { factorList, filteredFactorList } = storeToRefs(treeStore);
+
+const viewMode = computed((): "PRESET" | "CUSTOM" => {
+ if (factorList.value.length === 1) {
+ const factor = factorList.value[0].factor;
+ if (factor === "project" || factor === "instance") {
+ return "PRESET";
+ }
+ }
+ return "CUSTOM";
+});
+
+const toggleDisabled = (factor: StatefulFactor, index: number) => {
+ factor.disabled = !factor.disabled;
+ treeStore.buildTree();
+};
+
+const remove = (factor: StatefulFactor, index: number) => {
+ factorList.value.splice(index, 1);
+ treeStore.buildTree();
+};
+
+const selectPresetFactor = (factor: "project" | "instance") => {
+ factorList.value = [
+ {
+ factor,
+ disabled: false,
+ },
+ ];
+ treeStore.buildTree();
+};
+</script>
+
+<style lang="postcss" scoped>
+.grouping-bar--tabs :deep(.n-tabs-rail) {
+ @apply !bg-transparent;
+}
+</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/index.ts b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/index.ts
new file mode 100644
index 0000000000..c2b30ef26b
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GroupingBar/index.ts
@@ -0,0 +1,3 @@
+import GroupingBar from "./GroupingBar.vue";
+
+export default GroupingBar;
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue
new file mode 100644
index 0000000000..0819798449
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue
@@ -0,0 +1,64 @@
+<template>
+ <div class="flex items-center max-w-full overflow-hidden gap-x-1">
+ <InstanceV1EngineIcon
+ v-if="!hasInstanceContext"
+ :instance="database.instanceEntity"
+ />
+
+ <EnvironmentV1Name
+ v-if="
+ !hasEnvironmentContext ||
+ database.effectiveEnvironment !== database.instanceEntity.environment
+ "
+ :environment="database.effectiveEnvironmentEntity"
+ :link="false"
+ class="text-control-light"
+ />
+
+ <DatabaseIcon />
+
+ <span v-if="!hasProjectContext" class="text-control-light">
+ {{ database.projectEntity.key }}
+ </span>
+
+ <span class="flex-1 truncate">
+ <HighlightLabelText :text="database.databaseName" :keyword="keyword" />
+ <span v-if="!hasInstanceContext" class="text-control-light">
+ ({{ database.instanceEntity.title }})</span
+ >
+ </span>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import DatabaseIcon from "~icons/heroicons-outline/circle-stack";
+import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const database = computed(
+ () => (props.node as TreeNode<"database">).meta.target
+);
+
+const hasInstanceContext = computed(() => {
+ return props.factors.includes("instance");
+});
+
+const hasEnvironmentContext = computed(() => {
+ return props.factors.includes("environment");
+});
+
+const hasProjectContext = computed(() => {
+ return props.factors.includes("project");
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DummyNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/DummyNode.vue
new file mode 100644
index 0000000000..b54fb7d116
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/DummyNode.vue
@@ -0,0 +1,38 @@
+<template>
+ <NPopover :disabled="!error">
+ <template #trigger>
+ <span class="text-control-placeholder">{{ text }}</span>
+ </template>
+ <template #default>
+ <div class="text-error max-w-[20rem] break-words break-all">
+ {{ error }}
+ </div>
+ </template>
+ </NPopover>
+</template>
+
+<script setup lang="ts">
+import { NPopover } from "naive-ui";
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const { t } = useI18n();
+
+const error = computed(() => {
+ return (props.node as TreeNode<"dummy">).meta.target.error;
+});
+
+const text = computed(() => {
+ return `<${error.value ? t("common.error") : t("common.empty")}>`;
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/EnvironmentNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/EnvironmentNode.vue
new file mode 100644
index 0000000000..f0d5d7972d
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/EnvironmentNode.vue
@@ -0,0 +1,26 @@
+<template>
+ <div class="truncate leading-5">
+ <HighlightLabelText :text="environment.title" :keyword="keyword" />
+ <ProductionEnvironmentV1Icon :environment="environment" class="ml-1" />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { ProductionEnvironmentV1Icon } from "@/components/v2";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const environment = computed(
+ () => (props.node as TreeNode<"environment">).meta.target
+);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/HighlightLabelText.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/HighlightLabelText.vue
new file mode 100644
index 0000000000..9b425c1238
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/HighlightLabelText.vue
@@ -0,0 +1,24 @@
+<template>
+ <template v-if="!keyword.trim()">{{ text }}</template>
+ <!-- eslint-disable-next-line vue/no-v-html -->
+ <span v-else v-html="html" />
+</template>
+
+<script lang="ts" setup>
+import { escape } from "lodash-es";
+import { computed } from "vue";
+import { getHighlightHTMLByRegExp } from "@/utils";
+
+const props = defineProps<{
+ text: string;
+ keyword: string;
+}>();
+
+const html = computed(() => {
+ return getHighlightHTMLByRegExp(
+ escape(props.text),
+ escape(props.keyword.trim()),
+ false /* !caseSensitive */
+ );
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstanceNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstanceNode.vue
new file mode 100644
index 0000000000..866f1d8548
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstanceNode.vue
@@ -0,0 +1,40 @@
+<template>
+ <div class="flex items-center max-w-full overflow-hidden gap-x-1">
+ <InstanceV1EngineIcon :instance="instance" />
+ <EnvironmentV1Name
+ v-if="!hasEnvironmentContext"
+ :environment="instance.environmentEntity"
+ :link="false"
+ class="text-control-light"
+ />
+ <HighlightLabelText
+ :text="instance.title"
+ :keyword="keyword"
+ class="flex-1 truncate"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const instance = computed(
+ () => (props.node as TreeNode<"instance">).meta.target
+);
+
+const hasEnvironmentContext = computed(() => {
+ return props.factors.includes("environment");
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstancePrefix.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstancePrefix.vue
deleted file mode 100644
index 60b07db063..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstancePrefix.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<template>
- <InstanceV1EngineIcon :instance="instance" />
- <span class="text-sm" :class="[!disabled && 'text-control-light']">
- {{ environment.title }}
- </span>
-</template>
-
-<script setup lang="ts">
-import { InstanceV1EngineIcon } from "@/components/v2";
-import { ComposedInstance } from "@/types";
-import { Environment } from "@/types/proto/v1/environment_service";
-
-withDefaults(
- defineProps<{
- instance: ComposedInstance;
- environment: Environment;
- disabled?: boolean;
- }>(),
- {
- disabled: false,
- }
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
index a9fde68e17..ac0f0acc18 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
@@ -1,41 +1,50 @@
<template>
- <!-- eslint-disable-next-line vue/no-v-html -->
- <span :id="id" class="truncate" v-html="html" />
+ <template v-if="type === 'project'">
+ <ProjectNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'instance'">
+ <InstanceNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'environment'">
+ <EnvironmentNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'database'">
+ <DatabaseNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'schema'">
+ <SchemaNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'table'">
+ <TableNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'label'">
+ <LabelNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'dummy'">
+ <DummyNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
</template>
<script lang="ts" setup>
-import { escape } from "lodash-es";
import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { ConnectionAtom, DEFAULT_PROJECT_ID } from "@/types";
-import { getHighlightHTMLByRegExp } from "@/utils";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import DatabaseNode from "./DatabaseNode.vue";
+import DummyNode from "./DummyNode.vue";
+import EnvironmentNode from "./EnvironmentNode.vue";
+import InstanceNode from "./InstanceNode.vue";
+import LabelNode from "./LabelNode.vue";
+import ProjectNode from "./ProjectNode.vue";
+import SchemaNode from "./SchemaNode.vue";
+import TableNode from "./TableNode.vue";
const props = defineProps<{
- atom: ConnectionAtom;
+ node: TreeNode;
+ factors: Factor[];
keyword: string;
}>();
-const { t } = useI18n();
-// render an unique id for every node
-// for auto scroll to the node when tab switches
-const id = computed(() => {
- const { atom } = props;
- return `tree-node-label-${atom.type}-${atom.id}`;
-});
-
-const text = computed(() => {
- const { atom } = props;
- if (atom.type === "project" && atom.id === String(DEFAULT_PROJECT_ID)) {
- return t("database.unassigned-databases");
- }
- return atom.label;
-});
-
-const html = computed(() => {
- return getHighlightHTMLByRegExp(
- escape(text.value),
- escape(props.keyword.trim()),
- false /* !caseSensitive */
- );
-});
+const type = computed(() => props.node.meta.type);
</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/LabelNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/LabelNode.vue
new file mode 100644
index 0000000000..5289d87d64
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/LabelNode.vue
@@ -0,0 +1,31 @@
+<template>
+ <div class="truncate">
+ <span>{{ label.key }}</span>
+ <span class="mr-0.5">:</span>
+ <HighlightLabelText
+ v-if="label.value"
+ :text="label.value"
+ :keyword="keyword"
+ />
+ <span v-else class="text-control-placeholder">
+ {{ $t("label.empty-label-value") }}
+ </span>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const label = computed(() => (props.node as TreeNode<"label">).meta.target);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Prefix.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Prefix.vue
deleted file mode 100644
index f524765cd3..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Prefix.vue
+++ /dev/null
@@ -1,88 +0,0 @@
-<template>
- <template v-if="atom.type === 'project'">
- <!-- nothing -->
- </template>
- <template v-else-if="atom.type === 'instance'">
- <span class="flex items-center gap-x-1">
- <InstancePrefix
- :instance="instance"
- :environment="environment"
- :disabled="atom.disabled"
- />
- </span>
- </template>
- <template v-else-if="atom.type === 'database'">
- <span class="flex items-center gap-x-1">
- <InstancePrefix
- v-if="connectionTreeStore.tree.mode === ConnectionTreeMode.PROJECT"
- :instance="database.instanceEntity"
- :environment="environment"
- :disabled="atom.disabled"
- />
-
- <heroicons-outline:database class="w-4 h-4" />
- </span>
- </template>
- <template v-else-if="atom.type === 'schema'">
- <carbon:data-structured class="w-4 h-4" />
- </template>
- <template v-else-if="atom.type === 'table'">
- <heroicons-outline:table class="h-4 w-4" />
- </template>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import {
- useDatabaseV1Store,
- useInstanceV1Store,
- useEnvironmentV1Store,
- useConnectionTreeStore,
-} from "@/store";
-import {
- ConnectionAtom,
- unknownInstance,
- unknownDatabase,
- unknownEnvironment,
- ConnectionTreeMode,
-} from "@/types";
-import InstancePrefix from "./InstancePrefix.vue";
-
-const props = defineProps<{
- atom: ConnectionAtom;
-}>();
-
-const instanceStore = useInstanceV1Store();
-const databaseStore = useDatabaseV1Store();
-const environmentStore = useEnvironmentV1Store();
-const connectionTreeStore = useConnectionTreeStore();
-
-const instance = computed(() => {
- const { atom } = props;
- if (atom.type === "instance") {
- return instanceStore.getInstanceByUID(atom.id);
- }
-
- return unknownInstance();
-});
-
-const database = computed(() => {
- const { atom } = props;
- if (atom.type === "database") {
- return databaseStore.getDatabaseByUID(atom.id);
- }
- return unknownDatabase();
-});
-
-const environment = computed(() => {
- const { atom } = props;
- if (atom.type === "instance") {
- return instance.value.environmentEntity;
- }
- return (
- environmentStore.getEnvironmentByName(
- database.value.effectiveEnvironment
- ) ?? unknownEnvironment()
- );
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/ProjectNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/ProjectNode.vue
new file mode 100644
index 0000000000..f0ba9d0666
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/ProjectNode.vue
@@ -0,0 +1,30 @@
+<template>
+ <HighlightLabelText :text="text" :keyword="keyword" class="truncate" />
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+ DEFAULT_PROJECT_ID,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const { t } = useI18n();
+const project = computed(() => (props.node as TreeNode<"project">).meta.target);
+
+const text = computed(() => {
+ if (project.value.uid === String(DEFAULT_PROJECT_ID)) {
+ return t("database.unassigned-databases");
+ }
+ return project.value.title;
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/SchemaNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/SchemaNode.vue
new file mode 100644
index 0000000000..57f3e4ff6e
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/SchemaNode.vue
@@ -0,0 +1,28 @@
+<template>
+ <div class="flex items-center max-w-full overflow-hidden gap-x-1">
+ <SchemaIcon />
+ <HighlightLabelText
+ :text="target.schema.name"
+ :keyword="keyword"
+ class="flex-1 truncate"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import SchemaIcon from "~icons/heroicons-outline/view-columns";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const target = computed(() => (props.node as TreeNode<"schema">).meta.target);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Suffix.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Suffix.vue
deleted file mode 100644
index 9a9518725a..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Suffix.vue
+++ /dev/null
@@ -1,32 +0,0 @@
-<template>
- <heroicons-outline:link v-if="connected" class="w-4 h-4" />
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { useTabStore } from "@/store";
-import { ConnectionAtom, UNKNOWN_ID } from "@/types";
-
-const props = defineProps<{
- atom: ConnectionAtom;
-}>();
-
-const tabStore = useTabStore();
-
-const connected = computed(() => {
- const { instanceId, databaseId } = tabStore.currentTab.connection;
- const { atom } = props;
-
- if (atom.type === "database") {
- if (atom.id === databaseId) {
- return true;
- }
- }
- if (atom.type === "instance") {
- if (databaseId === String(UNKNOWN_ID) && atom.id === instanceId) {
- return true;
- }
- }
- return false;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/TableNode.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/TableNode.vue
new file mode 100644
index 0000000000..2578d87960
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/TableNode.vue
@@ -0,0 +1,28 @@
+<template>
+ <div class="flex items-center max-w-full overflow-hidden gap-x-1">
+ <TableIcon />
+ <HighlightLabelText
+ :text="target.table.name"
+ :keyword="keyword"
+ class="flex-1 truncate"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import TableIcon from "~icons/heroicons-outline/table-cells";
+import {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+const target = computed(() => (props.node as TreeNode<"table">).meta.target);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts b/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts
index 927cbcb67b..448927e184 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts
@@ -1,5 +1,3 @@
import Label from "./Label.vue";
-import Prefix from "./Prefix.vue";
-import Suffix from "./Suffix.vue";
-export { Prefix, Label, Suffix };
+export { Label };
diff --git a/frontend/src/views/sql-editor/AsidePanel/common.ts b/frontend/src/views/sql-editor/AsidePanel/common.ts
index 3570041c43..7646c3632a 100644
--- a/frontend/src/views/sql-editor/AsidePanel/common.ts
+++ b/frontend/src/views/sql-editor/AsidePanel/common.ts
@@ -1,42 +1,73 @@
-import {
- useConnectionTreeStore,
- useDatabaseV1Store,
- useDBSchemaV1Store,
-} from "@/store";
-import { ConnectionAtom } from "@/types";
+import { useDBSchemaV1Store } from "@/store";
+import { mapTreeNodeByType } from "@/store/modules/sqlEditorTree";
+import { ComposedDatabase, SQLEditorTreeNode } from "@/types";
+import { SchemaMetadata } from "@/types/proto/v1/database_service";
-export const fetchDatabaseSubTree = async (atom: ConnectionAtom) => {
- const uid = atom.id;
- const db = useDatabaseV1Store().getDatabaseByUID(uid);
- const databaseMetadata =
- await useDBSchemaV1Store().getOrFetchDatabaseMetadata(db.name);
- const { schemas } = databaseMetadata;
- if (schemas.length === 0) {
- // Empty database
- atom.children = [];
- return;
+const createDummyTableNode = (
+ parent: SQLEditorTreeNode,
+ error: unknown | undefined = undefined
+) => {
+ return mapTreeNodeByType(
+ "dummy",
+ {
+ type: "table",
+ error,
+ },
+ parent,
+ {
+ disabled: true,
+ }
+ );
+};
+
+const mapTableNodes = (
+ database: ComposedDatabase,
+ schema: SchemaMetadata,
+ parent: SQLEditorTreeNode
+) => {
+ const children = schema.tables.map((table) =>
+ mapTreeNodeByType("table", { database, schema, table }, parent)
+ );
+ if (children.length === 0) {
+ return [createDummyTableNode(parent)];
}
+ return children;
+};
+
+export const fetchDatabaseSubTree = async (
+ node: SQLEditorTreeNode<"database">
+) => {
+ try {
+ const database = node.meta.target;
+ const databaseMetadata =
+ await useDBSchemaV1Store().getOrFetchDatabaseMetadata(database.name);
+ const { schemas } = databaseMetadata;
+ if (schemas.length === 0) {
+ // Empty database
+ node.children = [createDummyTableNode(node)];
+ return;
+ }
- if (schemas.length === 1 && schemas[0].name === "") {
- // A single schema database, should render tables directly as a database
- // node's children
- atom.children = schemas[0].tables.map((table) =>
- useConnectionTreeStore().mapAtom(table, "table", atom)
- );
- return;
- } else {
- // Multiple schema database
- atom.children = schemas.map((schema) => {
- const schemaNode = useConnectionTreeStore().mapAtom(
- schema,
- "schema",
- atom
- );
- schemaNode.children = schema.tables.map((table) =>
- useConnectionTreeStore().mapAtom(table, "table", schemaNode)
- );
- return schemaNode;
- });
- return;
+ if (schemas.length === 1 && schemas[0].name === "") {
+ const schema = schemas[0];
+ // A single schema database, should render tables directly as a database
+ // node's children
+ node.children = mapTableNodes(database, schema, node);
+ return;
+ } else {
+ // Multiple schema database
+ node.children = schemas.map((schema) => {
+ const schemaNode = mapTreeNodeByType(
+ "schema",
+ { database, schema },
+ node
+ );
+ schemaNode.children = mapTableNodes(database, schema, schemaNode);
+ return schemaNode;
+ });
+ return;
+ }
+ } catch (error) {
+ node.children = [createDummyTableNode(node, error)];
}
};