Skip to content

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

feat(sql-editor): project-database view and several minor improvements (#4160)

Liu Jidf2196ba00b3
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
index a5f8151e9d..8ff57a8459 100644
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ b/frontend/src/components/ProvideSQLEditorContext.vue
@@ -18,12 +18,16 @@ import {
usePolicyStore,
useConnectionTreeStore,
} from "@/store";
-import type { Instance, Database, Connection, ConnectionAtom } from "@/types";
+import {
+ Database,
+ Connection,
+ ConnectionAtom,
+ ConnectionTreeMode,
+} from "@/types";
import { ConnectionTreeState, UNKNOWN_ID, DEFAULT_PROJECT_ID } from "@/types";
import {
emptyConnection,
idFromSlug,
- mapConnectionAtom,
sheetSlug as makeSheetSlug,
connectionSlug as makeConnectionSlug,
isSheetReadable,
@@ -35,7 +39,6 @@ import {
import { useI18n } from "vue-i18n";
type LocalState = {
- instanceList: Instance[];
databaseList: Database[];
};
@@ -44,7 +47,6 @@ const router = useRouter();
const { t } = useI18n();
const state = reactive<LocalState>({
- instanceList: [],
databaseList: [],
});
@@ -65,7 +67,7 @@ const prepareAccessControlPolicy = async () => {
);
};
-const prepareAccessibleConnectionByProject = async () => {
+const prepareAccessibleDatabaseList = async () => {
// It will also be called when user logout
if (currentUser.value.id === UNKNOWN_ID) {
return;
@@ -96,47 +98,80 @@ const prepareAccessibleConnectionByProject = async () => {
}
return true;
});
- state.instanceList = uniqBy(
- databaseList.map((db) => db.instance),
- (instance) => instance.id
- );
state.databaseList = databaseList;
};
-const prepareSQLEditorContext = async () => {
- let connectionTree: ConnectionAtom[] = [];
+const prepareConnectionTree = async () => {
+ if (connectionTreeStore.tree.mode === ConnectionTreeMode.INSTANCE) {
+ const { databaseList } = state;
+ const instanceList = uniqBy(
+ databaseList.map((db) => db.instance),
+ (instance) => instance.id
+ );
+ const connectionTree = instanceList.map((instance) => {
+ const node = connectionTreeStore.mapAtom(instance, "instance", 0);
+ return node;
+ });
- const { instanceList, databaseList } = state;
- const instanceMapper = mapConnectionAtom("instance", 0);
- connectionTree = instanceList.map((instance) => {
- const node = instanceMapper(instance);
- return node;
- });
+ for (const instance of instanceList) {
+ const instanceItem = connectionTree.find(
+ (item: ConnectionAtom) => item.id === instance.id
+ )!;
+
+ instanceItem.children = databaseList
+ .filter((db) => db.instance.id === instance.id)
+ .map((db) => {
+ const node = connectionTreeStore.mapAtom(db, "database", instance.id);
+ node.disabled = !isDatabaseAccessible(
+ db,
+ connectionTreeStore.accessControlPolicyList,
+ currentUser.value
+ );
+ if (node.disabled) {
+ // If a database node is not accessible
+ // it's not expandable either.
+ node.isLeaf = true;
+ }
+ return node;
+ });
+ }
+ connectionTreeStore.tree.data = connectionTree;
+ } else {
+ const { databaseList } = state;
+ const projectList = uniqBy(
+ databaseList.map((db) => db.project),
+ (project) => project.id
+ );
- for (const instance of instanceList) {
- const instanceItem = connectionTree.find(
- (item: ConnectionAtom) => item.id === instance.id
- )!;
-
- const databaseMapper = mapConnectionAtom("database", instance.id);
- instanceItem.children = databaseList
- .filter((db) => db.instance.id === instance.id)
- .map((db) => {
- const node = databaseMapper(db);
- node.disabled = !isDatabaseAccessible(
- db,
- connectionTreeStore.accessControlPolicyList,
- currentUser.value
- );
- if (node.disabled) {
- // If a database node is not accessible
- // it's not expandable either.
- node.isLeaf = true;
- }
- return node;
- });
+ const projectAtomList = projectList.map((project) => {
+ const node = connectionTreeStore.mapAtom(project, "project", 0);
+ return node;
+ });
- connectionTreeStore.tree.data = connectionTree;
+ projectAtomList.forEach((projectAtom) => {
+ projectAtom.children = databaseList
+ .filter((db) => db.project.id === projectAtom.id)
+ .map((db) => {
+ const node = connectionTreeStore.mapAtom(
+ db,
+ "database",
+ projectAtom.id
+ );
+ node.disabled = !isDatabaseAccessible(
+ db,
+ connectionTreeStore.accessControlPolicyList,
+ currentUser.value
+ );
+ if (node.disabled) {
+ // If a database node is not accessible
+ // it's not expandable either.
+ node.isLeaf = true;
+ }
+ return node;
+ });
+ });
+
+ connectionTreeStore.tree.data = projectAtomList;
}
// Won't fetch tableList for every database here.
@@ -330,11 +365,13 @@ onMounted(async () => {
if (connectionTreeStore.tree.state === ConnectionTreeState.UNSET) {
connectionTreeStore.tree.state = ConnectionTreeState.LOADING;
await prepareAccessControlPolicy();
- await prepareAccessibleConnectionByProject();
- await prepareSQLEditorContext();
+ await prepareAccessibleDatabaseList();
+ await prepareConnectionTree();
connectionTreeStore.tree.state = ConnectionTreeState.LOADED;
}
+ watch(() => connectionTreeStore.tree.mode, prepareConnectionTree);
+
watch(currentUser, (user) => {
if (user.id === UNKNOWN_ID) {
// Cleanup when user signed out
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 91c6fa676a..d39ce4f31d 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1431,7 +1431,8 @@
"admin-mode": {
"self": "Admin mode"
},
- "read-only-mode-not-allowed": "Instance {instance} is not accessible in read-only mode."
+ "read-only-mode-not-allowed": "Instance {instance} is not accessible in read-only mode.",
+ "run-selected": "Run selected"
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 7c04056564..8571f25054 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1431,7 +1431,8 @@
"admin-mode": {
"self": "管理员模式"
},
- "read-only-mode-not-allowed": "实例{instance}无法通过只读模式访问。"
+ "read-only-mode-not-allowed": "实例{instance}无法通过只读模式访问。",
+ "run-selected": "运行选中的语句"
},
"schema-editor": {
"self": "Schema 编辑器",
diff --git a/frontend/src/store/modules/connectionTree.ts b/frontend/src/store/modules/connectionTree.ts
index ded75c9da3..8ac4634b9a 100644
--- a/frontend/src/store/modules/connectionTree.ts
+++ b/frontend/src/store/modules/connectionTree.ts
@@ -6,18 +6,26 @@ import {
Connection,
Policy,
ConnectionAtom,
+ ConnectionTreeMode,
+ ConnectionAtomType,
+ Project,
+ Instance,
+ Database,
} from "@/types";
import { ConnectionTreeState, UNKNOWN_ID } from "@/types";
import { useDatabaseStore } from "./database";
import { useInstanceStore } from "./instance";
import { emptyConnection } from "@/utils";
import { useDBSchemaStore } from "./dbSchema";
+import { TableMetadata } from "@/types/proto/store/database";
+import { has, uniqueId } from "lodash-es";
export const useConnectionTreeStore = defineStore("connectionTree", () => {
// states
const accessControlPolicyList = ref<Policy[]>([]);
const tree = reactive({
data: [] as ConnectionAtom[],
+ mode: ConnectionTreeMode.PROJECT,
state: ConnectionTreeState.UNSET,
});
const expandedTreeNodeKeys = ref<string[]>([]);
@@ -68,6 +76,25 @@ export const useConnectionTreeStore = defineStore("connectionTree", () => {
return { instanceId: UNKNOWN_ID, databaseId: UNKNOWN_ID };
}
};
+ // utilities
+ const mapAtom = (
+ item: Project | Instance | Database | TableMetadata,
+ type: ConnectionAtomType,
+ parentId: number
+ ) => {
+ const id =
+ type !== "table" && has(item, "id") ? (item as any).id : uniqueId();
+ const key = `${type}-${id}`;
+ const connectionAtom: ConnectionAtom = {
+ parentId,
+ id,
+ key,
+ label: item.name,
+ type,
+ isLeaf: type === "table",
+ };
+ return connectionAtom;
+ };
return {
accessControlPolicyList,
@@ -76,6 +103,7 @@ export const useConnectionTreeStore = defineStore("connectionTree", () => {
selectedTableAtom,
fetchConnectionByInstanceIdAndDatabaseId,
fetchConnectionByInstanceId,
+ mapAtom,
};
});
diff --git a/frontend/src/types/connectionTree.ts b/frontend/src/types/connectionTree.ts
index c09de2c093..d0dc69296c 100644
--- a/frontend/src/types/connectionTree.ts
+++ b/frontend/src/types/connectionTree.ts
@@ -1,6 +1,11 @@
-import { InstanceId, DatabaseId } from "../types";
+import { InstanceId, DatabaseId, ProjectId } from "../types";
-export type ConnectionAtomType = "instance" | "database" | "table" | "view";
+export type ConnectionAtomType =
+ | "project"
+ | "instance"
+ | "database"
+ | "table"
+ | "view";
export enum ConnectionTreeState {
UNSET,
@@ -8,9 +13,14 @@ export enum ConnectionTreeState {
LOADED,
}
+export enum ConnectionTreeMode {
+ PROJECT = "project",
+ INSTANCE = "instance",
+}
+
export interface ConnectionAtom {
- parentId: InstanceId | DatabaseId;
- id: InstanceId | DatabaseId;
+ parentId: ProjectId | InstanceId | DatabaseId;
+ id: ProjectId | InstanceId | DatabaseId;
key: string;
label: string;
type?: ConnectionAtomType;
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 17ae1cce31..023776fe1f 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -17,7 +17,6 @@ export * from "./tab";
export * from "./task";
export * from "./principal";
export * from "./policy";
-export * from "./sql-editor";
export * from "./sheet";
export * from "./pev2";
export * from "./web-storage";
diff --git a/frontend/src/utils/sql-editor.ts b/frontend/src/utils/sql-editor.ts
deleted file mode 100644
index 1445874b38..0000000000
--- a/frontend/src/utils/sql-editor.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { has, uniqueId } from "lodash-es";
-import {
- ConnectionAtom,
- ConnectionAtomType,
- Database,
- Instance,
-} from "@/types";
-import { TableMetadata } from "@/types/proto/store/database";
-
-export const mapConnectionAtom =
- (
- type: ConnectionAtomType,
- parentId: number,
- overrides: Partial<ConnectionAtom> = {}
- ) =>
- (item: Instance | Database | TableMetadata) => {
- const atomId =
- type !== "table" && has(item, "id") ? (item as any).id : uniqueId();
- const connectionAtom: ConnectionAtom = {
- parentId,
- id: atomId,
- key: `${type}-${atomId}`,
- label: item.name,
- type,
- isLeaf: type === "table",
- ...overrides,
- };
- return connectionAtom;
- };
diff --git a/frontend/src/views/DatabaseDashboard.vue b/frontend/src/views/DatabaseDashboard.vue
index 8e16ff64ad..634896a108 100644
--- a/frontend/src/views/DatabaseDashboard.vue
+++ b/frontend/src/views/DatabaseDashboard.vue
@@ -7,7 +7,7 @@
/>
<div class="flex items-center space-x-4">
- <NTooltip>
+ <NTooltip v-if="canVisitUnassignedDatabases">
<template #trigger>
<router-link
:to="{
@@ -65,7 +65,11 @@ import {
UNKNOWN_ID,
DEFAULT_PROJECT_ID,
} from "../types";
-import { filterDatabaseByKeyword, sortDatabaseList } from "../utils";
+import {
+ filterDatabaseByKeyword,
+ hasWorkspacePermission,
+ sortDatabaseList,
+} from "../utils";
import { cloneDeep } from "lodash-es";
import {
useCurrentUser,
@@ -110,6 +114,13 @@ export default defineComponent({
const environmentList = useEnvironmentList(["NORMAL"]);
+ const canVisitUnassignedDatabases = computed(() => {
+ return hasWorkspacePermission(
+ "bb.permission.workspace.manage-database",
+ currentUser.value.role
+ );
+ });
+
onMounted(() => {
// Focus on the internal search field when mounted
searchField.value.$el.querySelector("#search").focus();
@@ -184,6 +195,7 @@ export default defineComponent({
filteredList,
selectEnvironment,
changeSearchText,
+ canVisitUnassignedDatabases,
};
},
});
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
index 2efe6a4f15..f60e0d1751 100644
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
@@ -1,13 +1,29 @@
<template>
<div class="aside-panel h-full">
- <n-tabs type="segment" default-value="databases" class="h-full">
- <n-tab-pane name="databases" :tab="$t('common.databases')">
+ <n-tabs v-model:value="tab" type="segment" class="h-full">
+ <n-tab-pane name="projects" :tab="$t('common.projects')">
<Splitpanes
horizontal
class="default-theme"
:dbl-click-splitter="false"
>
- <Pane :size="databasePaneSize"><DatabaseTree /></Pane>
+ <Pane :size="databasePaneSize">
+ <DatabaseTree />
+ </Pane>
+ <Pane :size="FULL_HEIGHT - databasePaneSize">
+ <TableSchema @close-pane="handleCloseTableSchemaPane" />
+ </Pane>
+ </Splitpanes>
+ </n-tab-pane>
+ <n-tab-pane name="instances" :tab="$t('common.instances')">
+ <Splitpanes
+ horizontal
+ class="default-theme"
+ :dbl-click-splitter="false"
+ >
+ <Pane :size="databasePaneSize">
+ <DatabaseTree />
+ </Pane>
<Pane :size="FULL_HEIGHT - databasePaneSize">
<TableSchema @close-pane="handleCloseTableSchemaPane" />
</Pane>
@@ -21,18 +37,23 @@
</template>
<script lang="ts" setup>
+import { computed, ref, watchEffect } from "vue";
import { isUndefined } from "lodash-es";
-import { computed } from "vue";
+
import { useConnectionTreeStore } from "@/store";
import DatabaseTree from "./DatabaseTree.vue";
import QueryHistoryContainer from "./QueryHistoryContainer.vue";
import TableSchema from "./TableSchema.vue";
import { Splitpanes, Pane } from "splitpanes";
+import { ConnectionTreeMode } from "@/types";
const FULL_HEIGHT = 100;
const DATABASE_PANE_SIZE = 60;
+const tab = ref<"projects" | "instances" | "history">("projects");
+
const connectionTreeStore = useConnectionTreeStore();
+
const databasePaneSize = computed(() => {
if (!isUndefined(connectionTreeStore.selectedTableAtom)) {
return DATABASE_PANE_SIZE;
@@ -43,6 +64,14 @@ const databasePaneSize = computed(() => {
const handleCloseTableSchemaPane = () => {
connectionTreeStore.selectedTableAtom = undefined;
};
+watchEffect(() => {
+ if (tab.value === "projects") {
+ connectionTreeStore.tree.mode = ConnectionTreeMode.PROJECT;
+ }
+ if (tab.value === "instances") {
+ connectionTreeStore.tree.mode = ConnectionTreeMode.INSTANCE;
+ }
+});
</script>
<style scoped>
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
index 8afeb08830..20b8a1a158 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
@@ -1,7 +1,7 @@
<template>
<div
v-if="connectionTreeStore.tree.state === ConnectionTreeState.LOADED"
- class="databases-tree p-2 space-y-2 h-full"
+ class="databases-tree p-2 space-y-2 h-full flex flex-col"
>
<div class="databases-tree--input">
<n-input
@@ -13,8 +13,8 @@
</template>
</n-input>
</div>
- <div class="databases-tree--tree overflow-y-auto">
- <n-tree
+ <div class="databases-tree--tree flex-1 overflow-y-auto">
+ <NTree
block-line
:data="treeData"
:pattern="searchPattern"
@@ -27,17 +27,18 @@
:on-load="loadSubTree"
:on-update:expanded-keys="updateExpandedKeys"
/>
- <n-dropdown
- placement="bottom-start"
- trigger="manual"
- :x="dropdownPosition.x"
- :y="dropdownPosition.y"
- :options="dropdownOptions"
- :show="showDropdown"
- :on-clickoutside="handleClickoutside"
- @select="handleSelect"
- />
</div>
+
+ <NDropdown
+ placement="bottom-start"
+ trigger="manual"
+ :x="dropdownPosition.x"
+ :y="dropdownPosition.y"
+ :options="dropdownOptions"
+ :show="showDropdown"
+ :on-clickoutside="handleClickoutside"
+ @select="handleSelect"
+ />
</div>
<div v-else class="flex justify-center items-center h-full">
<BBSpin :title="$t('sql-editor.loading-databases')" />
@@ -45,12 +46,10 @@
</template>
<script lang="ts" setup>
-import { escape } from "lodash-es";
-import type { DropdownOption } from "naive-ui";
import { ref, computed, h, nextTick, watch } from "vue";
+import { NTree, NDropdown, DropdownOption, TreeOption } from "naive-ui";
import { useI18n } from "vue-i18n";
import { stringify } from "qs";
-import ConnectedIcon from "~icons/heroicons-outline/lightning-bolt";
import type {
ConnectionAtom,
@@ -65,24 +64,18 @@ import {
useCurrentUser,
useDatabaseStore,
useDBSchemaStore,
- useInstanceStore,
useIsLoggedIn,
useTabStore,
} from "@/store";
import {
emptyConnection,
- getHighlightHTMLByKeyWords,
hasWorkspacePermission,
isDescendantOf,
isSimilarTab,
- mapConnectionAtom,
} from "@/utils";
import { generateTableItem } from "./utils";
import { scrollIntoViewIfNeeded } from "@/bbkit/BBUtil";
-import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";
-import HeroiconsOutlineDatabase from "~icons/heroicons-outline/database";
-import HeroiconsOutlineTable from "~icons/heroicons-outline/table";
-import ProtectedEnvironmentIcon from "@/components/Environment/ProtectedEnvironmentIcon.vue";
+import { Prefix, Label, Suffix } from "./TreeNode";
type Position = {
x: number;
@@ -95,7 +88,6 @@ type DropdownOptionWithConnectionAtom = DropdownOption & {
const { t } = useI18n();
-const instanceStore = useInstanceStore();
const databaseStore = useDatabaseStore();
const connectionTreeStore = useConnectionTreeStore();
const dbSchemaStore = useDBSchemaStore();
@@ -111,34 +103,39 @@ const dropdownPosition = ref<Position>({
});
const dropdownContext = ref<ConnectionAtom>();
const dropdownOptions = computed((): DropdownOptionWithConnectionAtom[] => {
- if (!dropdownContext.value) {
+ const atom = dropdownContext.value;
+ if (!atom) {
return [];
- } else if (dropdownContext.value.type === "table") {
+ }
+ if (atom.type === "project") {
+ return [];
+ }
+ if (atom.type === "table") {
return [
{
key: "alter-table",
label: t("sql-editor.alter-table"),
- item: dropdownContext.value,
+ item: atom,
},
];
} else {
// Don't show any context menu actions for disabled
// instances/databases
- if (dropdownContext.value.disabled) {
+ if (atom.disabled) {
return [];
}
const items = [
{
key: "connect",
label: t("sql-editor.connect"),
- item: dropdownContext.value,
+ item: atom,
},
];
if (allowAdmin.value) {
items.push({
key: "connect-in-admin-mode",
label: t("sql-editor.connect-in-admin-mode"),
- item: dropdownContext.value,
+ item: atom,
});
}
return items;
@@ -174,6 +171,11 @@ const setConnection = (
}
) => {
if (option) {
+ if (option.type === "project") {
+ // Not connectable to a project
+ return;
+ }
+
const target: CoreTabInfo = {
connection: emptyConnection(),
...extra,
@@ -194,17 +196,20 @@ const setConnection = (
conn.instanceId = option.id;
} else if (option.type === "database") {
// If selected item is database node
- const instanceId = option.parentId;
- conn.instanceId = instanceId;
- conn.databaseId = option.id;
+ const database = databaseStore.getDatabaseById(option.id);
+ conn.instanceId = database.instance.id;
+ conn.databaseId = database.id;
} else if (option.type === "table") {
// If selected item is table node
const databaseId = option.parentId;
- const databaseInfo = databaseStore.getDatabaseById(databaseId);
- const instanceId = databaseInfo.instance.id;
+ const database = databaseStore.getDatabaseById(databaseId);
+ const instanceId = database.instance.id;
conn.instanceId = instanceId;
conn.databaseId = databaseId;
- connectionTreeStore.selectedTableAtom = option;
+ if (database.instance.engine !== "MONGODB") {
+ // A MongoDB connection has no schema, so it shouldn't be clickable.
+ connectionTreeStore.selectedTableAtom = option;
+ }
}
connect();
@@ -213,94 +218,43 @@ const setConnection = (
// dynamic render the highlight keywords
// and render the selected table node in bold font
-const renderLabel = ({ option }: { option: ConnectionAtom }) => {
- const classes = ["truncate"];
- const emphasize = () => {
- classes.push("font-bold");
- };
- if (option.type === "table") {
- if (option === connectionTreeStore.selectedTableAtom) {
- 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,
- });
+const renderLabel = ({ option }: { option: TreeOption }) => {
+ const atom = option as any as ConnectionAtom;
+ return h(Label, { atom, keyword: searchPattern.value ?? "" });
};
// Render icons before nodes.
-const renderPrefix = ({ option }: { option: ConnectionAtom }) => {
- if (option.type === "instance") {
- const instanceId = option.id;
- const instance = instanceStore.getInstanceById(instanceId);
- const children = [
- h(InstanceEngineIcon, {
- instance,
- }),
- h(ProtectedEnvironmentIcon, {
- environment: instance.environment,
- class: "w-4 h-4 text-inherit",
- }),
- h(
- "span",
- {
- class: ["text-sm", !option.disabled && "text-gray-500"],
- },
- `(${instance.environment.name})`
- ),
- ];
-
- return h("span", { class: "flex items-center gap-x-1" }, children);
- } else if (option.type === "database") {
- return h(HeroiconsOutlineDatabase, {
- class: "w-4 h-4",
- });
- } else if (option.type === "table") {
- return h(HeroiconsOutlineTable, {
- class: "w-4 h-4",
- });
- }
- return null;
+const renderPrefix = ({ option }: { option: TreeOption }) => {
+ const atom = option as any as ConnectionAtom;
+ return h(Prefix, { atom });
};
// 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 renderSuffix = ({ option }: { option: TreeOption }) => {
+ const atom = option as any as ConnectionAtom;
+ return h(Suffix, { atom });
};
-const loadSubTree = async (item: ConnectionAtom): Promise<void> => {
+const loadSubTree = async (option: TreeOption): Promise<void> => {
+ const item = option as any as ConnectionAtom;
if (item.type === "database") {
+ const database = databaseStore.getDatabaseById(item.id);
const tableList = await dbSchemaStore.getOrFetchTableListByDatabaseId(
item.id as DatabaseId
);
- const mapper = mapConnectionAtom("table", item.id);
- item.children = tableList.map((table) => generateTableItem(mapper(table)));
+ item.children = tableList.map((table) => {
+ const node = generateTableItem(
+ connectionTreeStore.mapAtom(table, "table", item.id)
+ );
+ if (database.instance.engine === "MONGODB") {
+ node.disabled = true;
+ }
+
+ return node;
+ });
if (item.children.length === 0) {
// No tables in the db
item.isLeaf = true;
@@ -349,22 +303,34 @@ const handleClickoutside = () => {
showDropdown.value = false;
};
-const nodeProps = ({ option }: { option: ConnectionAtom }) => {
+const maybeExpandKey = (key: string) => {
+ const keys = connectionTreeStore.expandedTreeNodeKeys;
+ if (!keys.includes(key)) {
+ keys.push(key);
+ }
+};
+
+const nodeProps = ({ option }: { option: TreeOption }) => {
+ const atom = option as any as ConnectionAtom;
return {
onClick(e: MouseEvent) {
- if (option.disabled) return;
+ if (atom.disabled) return;
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);
+ if (atom.type === "project") {
+ maybeExpandKey(`project-${atom.id}`);
+ } else {
+ setConnection(atom);
+ }
}
},
onContextmenu(e: MouseEvent) {
e.preventDefault();
showDropdown.value = false;
- if (option && option.key) {
- dropdownContext.value = option;
+ if (atom && atom.key) {
+ dropdownContext.value = atom;
}
nextTick().then(() => {
@@ -416,18 +382,14 @@ watch(
return;
}
- const maybeExpandKey = (key: string) => {
- const keys = connectionTreeStore.expandedTreeNodeKeys;
- if (!keys.includes(key)) {
- keys.push(key);
- }
- };
-
if (instanceId !== UNKNOWN_ID) {
maybeExpandKey(`instance-${instanceId}`);
}
if (databaseId !== UNKNOWN_ID) {
maybeExpandKey(`database-${databaseId}`);
+ const db = databaseStore.getDatabaseById(databaseId);
+ const projectId = db.project.id;
+ maybeExpandKey(`project-${projectId}`);
}
scrollToConnectedNode(instanceId, databaseId);
@@ -436,7 +398,7 @@ watch(
);
</script>
-<style>
+<style postcss>
.databases-tree .n-tree-node-content__prefix {
@apply shrink-0 !mr-1;
}
@@ -454,9 +416,3 @@ watch(
background-color: var(--n-node-color-active) !important;
}
</style>
-
-<style scoped>
-.databases-tree--tree {
- height: calc(100% - 40px);
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
new file mode 100644
index 0000000000..849c23e143
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
@@ -0,0 +1,51 @@
+<template>
+ <!-- eslint-disable-next-line vue/no-v-html -->
+ <span :id="id" class="truncate" :class="classes" v-html="html" />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { escape } from "lodash-es";
+
+import { ConnectionAtom, DEFAULT_PROJECT_ID } from "@/types";
+import { useConnectionTreeStore } from "@/store";
+import { getHighlightHTMLByKeyWords } from "@/utils";
+
+const props = defineProps<{
+ atom: ConnectionAtom;
+ keyword: string;
+}>();
+const { t } = useI18n();
+const connectionTreeStore = useConnectionTreeStore();
+
+const classes = computed(() => {
+ const classes = ["truncate"];
+ const { atom } = props;
+ if (atom.type === "table") {
+ if (atom === connectionTreeStore.selectedTableAtom) {
+ classes.push("font-bold");
+ }
+ }
+ return classes;
+});
+
+// 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 === DEFAULT_PROJECT_ID) {
+ return t("database.unassigned-databases");
+ }
+ return atom.label;
+});
+
+const html = computed(() => {
+ return getHighlightHTMLByKeyWords(escape(text.value), escape(props.keyword));
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Prefix.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Prefix.vue
new file mode 100644
index 0000000000..ec369f36b5
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Prefix.vue
@@ -0,0 +1,76 @@
+<template>
+ <template v-if="atom.type === 'project'">
+ <!-- nothing -->
+ </template>
+ <template v-else-if="atom.type === 'instance'">
+ <span class="flex items-center gap-x-1">
+ <InstanceEngineIcon :instance="instance" />
+ <ProtectedEnvironmentIcon
+ :environment="instance.environment"
+ class="w-4 h-4 text-inherit"
+ />
+ <span class="text-sm" :class="[!atom.disabled && 'text-gray-500']">
+ {{ instance.environment.name }}
+ </span>
+ </span>
+ </template>
+ <template v-else-if="atom.type === 'database'">
+ <span class="flex items-center gap-x-1">
+ <template
+ v-if="connectionTreeStore.tree.mode === ConnectionTreeMode.PROJECT"
+ >
+ <ProtectedEnvironmentIcon
+ :environment="database.instance.environment"
+ class="w-4 h-4 text-inherit"
+ />
+ <span class="text-sm" :class="[!atom.disabled && 'text-gray-500']">
+ {{ database.instance.environment.name }}
+ </span>
+ </template>
+
+ <heroicons-outline:database class="w-4 h-4" />
+ </span>
+ </template>
+ <template v-else-if="atom.type === 'table'">
+ <heroicons-outline:table class="w-4 h-4" />
+ </template>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";
+import ProtectedEnvironmentIcon from "@/components/Environment/ProtectedEnvironmentIcon.vue";
+import { ConnectionAtom, unknown, ConnectionTreeMode } from "@/types";
+import {
+ useConnectionTreeStore,
+ useDatabaseStore,
+ useInstanceStore,
+} from "@/store";
+
+const props = defineProps<{
+ atom: ConnectionAtom;
+}>();
+
+const instanceStore = useInstanceStore();
+const databaseStore = useDatabaseStore();
+const connectionTreeStore = useConnectionTreeStore();
+
+const instance = computed(() => {
+ const { atom } = props;
+ if (atom.type === "instance") {
+ return instanceStore.getInstanceById(atom.id);
+ }
+
+ return unknown("INSTANCE");
+});
+
+const database = computed(() => {
+ const { atom } = props;
+ if (atom.type === "database") {
+ const database = databaseStore.getDatabaseById(atom.id);
+ return database;
+ }
+ return unknown("DATABASE");
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Suffix.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Suffix.vue
new file mode 100644
index 0000000000..accaaf87a4
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Suffix.vue
@@ -0,0 +1,33 @@
+<template>
+ <heroicons-outline:lightning-bolt v-if="connected" class="w-4 h-4" />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+
+import { ConnectionAtom, UNKNOWN_ID } from "@/types";
+import { useTabStore } from "@/store";
+
+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 === UNKNOWN_ID && atom.id === instanceId) {
+ return true;
+ }
+ }
+ return false;
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts b/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts
new file mode 100644
index 0000000000..8f9fae4987
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts
@@ -0,0 +1,5 @@
+import Prefix from "./Prefix.vue";
+import Label from "./Label.vue";
+import Suffix from "./Suffix.vue";
+
+export { Prefix, Label, Suffix };
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
index ce2ad06ffd..160724beaf 100644
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
@@ -6,7 +6,9 @@
:disabled="isEmptyStatement || isExecutingSQL"
@click="handleRunQuery"
>
- <mdi:play class="h-5 w-5" /> {{ $t("common.run") }} (⌘+⏎)
+ <mdi:play class="h-5 w-5" />
+ {{ showRunSelected ? $t("sql-editor.run-selected") : $t("common.run") }}
+ (⌘+⏎)
</NButton>
<NButton
:disabled="isEmptyStatement || isExecutingSQL"
@@ -99,6 +101,13 @@ const showSheetsFeature = computed(() => {
return tabStore.currentTab.mode === TabMode.ReadOnly;
});
+const showRunSelected = computed(() => {
+ return (
+ tabStore.currentTab.mode === TabMode.ReadOnly &&
+ !!tabStore.currentTab.selectedStatement
+ );
+});
+
const allowSave = computed(() => {
if (!showSheetsFeature.value) {
return false;
diff --git a/frontend/src/views/sql-editor/EditorCommon/TableView.vue b/frontend/src/views/sql-editor/EditorCommon/TableView.vue
index 40b0f655c5..5e1837f8ae 100644
--- a/frontend/src/views/sql-editor/EditorCommon/TableView.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/TableView.vue
@@ -10,6 +10,7 @@
>
<div class="flex flex-row justify-start items-center mr-2">
<NInput
+ v-if="showSearchFeature"
v-model:value="state.search"
class="max-w-xs"
type="text"
@@ -116,6 +117,13 @@ const state = reactive<State>({
search: "",
});
+const showSearchFeature = computed(() => {
+ const instance = instanceStore.getInstanceById(
+ tabStore.currentTab.connection.instanceId
+ );
+ return instance.engine !== "MONGODB";
+});
+
const naiveUIConfig = computed(() => {
if (props.dark) {
return { theme: darkTheme, themeOverrides: darkThemeOverrides.value };