Skip to content

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

feat(sql-editor): redesign sql editor left sidebar and database list (#11385)

Liu Ji1809bc653574
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
index abdeff9126..a08766ccea 100644
--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
@@ -554,6 +554,7 @@ const handlePreviewIssue = async () => {
} else {
router.push(routeInfo);
}
+ cleanup();
};
const generateIssueName = (
diff --git a/frontend/src/components/v2/Form/SearchBox.vue b/frontend/src/components/v2/Form/SearchBox.vue
index 1ea3d2599e..3c993fde71 100644
--- a/frontend/src/components/v2/Form/SearchBox.vue
+++ b/frontend/src/components/v2/Form/SearchBox.vue
@@ -9,12 +9,13 @@
@update:value="$emit('update:value', $event)"
>
<template #prefix>
- <heroicons-outline:search class="h-4 w-4 text-control-placeholder" />
+ <SearchIcon class="w-4 h-auto text-gray-300" />
</template>
</NInput>
</template>
<script lang="ts" setup>
+import { SearchIcon } from "lucide-vue-next";
import { NInput } from "naive-ui";
import { computed, onMounted, ref, useAttrs } from "vue";
import { useI18n } from "vue-i18n";
diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.ts
index 50c9404d68..eb2006e964 100644
--- a/frontend/src/composables/useExecuteSQL.ts
+++ b/frontend/src/composables/useExecuteSQL.ts
@@ -1,8 +1,8 @@
import { isEmpty } from "lodash-es";
import { Status } from "nice-grpc-common";
import { markRaw } from "vue";
-import { useI18n } from "vue-i18n";
import { parseSQL } from "@/components/MonacoEditor/sqlParser";
+import { t } from "@/plugins/i18n";
import {
pushNotification,
useCurrentUserV1,
@@ -30,7 +30,6 @@ import {
} from "@/utils";
const useExecuteSQL = () => {
- const { t } = useI18n();
const currentUser = useCurrentUserV1();
const databaseStore = useDatabaseV1Store();
const tabStore = useSQLEditorTabStore();
diff --git a/frontend/src/layouts/SQLEditorLayout.vue b/frontend/src/layouts/SQLEditorLayout.vue
index ead8fd8e61..7a0a6e5229 100644
--- a/frontend/src/layouts/SQLEditorLayout.vue
+++ b/frontend/src/layouts/SQLEditorLayout.vue
@@ -32,7 +32,6 @@ import {
PolicyResourceType,
PolicyType,
} from "@/types/proto/v1/org_policy_service";
-import { provideSecondarySidebarContext } from "@/views/sql-editor/SecondarySidebar";
import { provideSheetContext } from "@/views/sql-editor/Sheet";
import { provideSQLEditorContext } from "@/views/sql-editor/context";
@@ -43,7 +42,6 @@ const pageMode = usePageMode();
provideSQLEditorContext();
// provide context for sheets
provideSheetContext();
-provideSecondarySidebarContext();
const showBanners = computed(() => {
return pageMode.value === "BUNDLED";
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 1731491416..29b51b9999 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -274,7 +274,8 @@
"baseline": "Baseline",
"project-member": "Project member",
"leave-without-saving": "Leave without saving?",
- "configure-now": "Configure now"
+ "configure-now": "Configure now",
+ "connection": "Connection"
},
"error-page": {
"go-back-home": "Go back home"
@@ -2250,7 +2251,15 @@
"previous-row": "Previous row",
"next-row": "Next row",
"copy-success": "Copy success",
- "missing-permission-to-load-db-metadata": "Missing required permissions to load metadata of db {db}."
+ "missing-permission-to-load-db-metadata": "Missing required permissions to load metadata of db {db}.",
+ "connect-in-new-tab": "Connect in new tab",
+ "copy-name": "Copy name",
+ "copy-select-statement": "Copy SELECT statement",
+ "preview-table-data": "Preview table data",
+ "view-table-detail": "View table detail",
+ "view-database-detail": "View database detail",
+ "copy-all-column-names": "Copy all column names",
+ "view-schema-text": "View schema text"
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 4bf10b5a70..8da7a531ed 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -274,7 +274,8 @@
"baseline": "Base",
"project-member": "Miembro del proyecto",
"leave-without-saving": "¿Salir sin ahorrar?",
- "configure-now": "Configurar ahora"
+ "configure-now": "Configurar ahora",
+ "connection": "Conexión"
},
"error-page": {
"go-back-home": "Volver al inicio"
@@ -2250,7 +2251,15 @@
"previous-row": "Fila anterior",
"next-row": "siguiente fila",
"copy-success": "Copiado al portapapeles",
- "missing-permission-to-load-db-metadata": "Faltan los permisos necesarios para cargar metadatos de db {db}."
+ "missing-permission-to-load-db-metadata": "Faltan los permisos necesarios para cargar metadatos de db {db}.",
+ "connect-in-new-tab": "Conéctate en una nueva pestaña",
+ "copy-name": "Copiar nombre",
+ "copy-select-statement": "Copiar declaración SELECT",
+ "preview-table-data": "Vista previa de datos de la tabla",
+ "view-table-detail": "Ver detalle de la tabla",
+ "view-database-detail": "Ver detalle de la base de datos",
+ "copy-all-column-names": "Copiar todos los nombres de las columnas",
+ "view-schema-text": "Ver texto del esquema"
},
"schema-editor": {
"self": "Editor de esquema",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 1d503a51f7..6fef845057 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -274,7 +274,8 @@
"baseline": "ベースライン",
"project-member": "プロジェクトメンバー",
"leave-without-saving": "保存せずに終了しますか?",
- "configure-now": "今すぐ設定する"
+ "configure-now": "今すぐ設定する",
+ "connection": "繋がり"
},
"error-page": {
"go-back-home": "ホームに戻る"
@@ -2250,7 +2251,15 @@
"previous-row": "前の行",
"next-row": "次の行",
"copy-success": "コピーが成功しました",
- "missing-permission-to-load-db-metadata": "データベース {db} のメタデータをロードするために必要な権限がありません。"
+ "missing-permission-to-load-db-metadata": "データベース {db} のメタデータをロードするために必要な権限がありません。",
+ "connect-in-new-tab": "新しいタブで接続する",
+ "copy-name": "名前をコピーする",
+ "copy-select-statement": "SELECT ステートメントをコピーする",
+ "preview-table-data": "テーブルデータのプレビュー",
+ "view-table-detail": "テーブルの詳細を表示する",
+ "view-database-detail": "データベースの詳細を表示する",
+ "copy-all-column-names": "すべての列名をコピーします",
+ "view-schema-text": "スキーマテキストの表示"
},
"schema-editor": {
"self": "スキーマエディター",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 7ba026bc3a..2cabfbbd10 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -274,7 +274,8 @@
"baseline": "Đường cơ sở",
"project-member": "Thành viên dự án",
"leave-without-saving": "Rời đi mà không lưu?",
- "configure-now": "Cấu hình ngay bây giờ"
+ "configure-now": "Cấu hình ngay bây giờ",
+ "connection": "Sự liên quan"
},
"error-page": {
"go-back-home": "Trở về nhà"
@@ -2250,7 +2251,15 @@
"previous-row": "Hàng trước",
"next-row": "Hàng tiếp theo",
"copy-success": "Sao chép thành công",
- "missing-permission-to-load-db-metadata": "Thiếu quyền cần thiết để tải siêu dữ liệu của db {db}."
+ "missing-permission-to-load-db-metadata": "Thiếu quyền cần thiết để tải siêu dữ liệu của db {db}.",
+ "connect-in-new-tab": "Kết nối trong tab mới",
+ "copy-name": "Sao chép tên",
+ "copy-select-statement": "Sao chép câu lệnh CHỌN",
+ "preview-table-data": "Xem trước dữ liệu bảng",
+ "view-table-detail": "Xem chi tiết bảng",
+ "view-database-detail": "Xem chi tiết cơ sở dữ liệu",
+ "copy-all-column-names": "Sao chép tất cả tên cột",
+ "view-schema-text": "Xem văn bản lược đồ"
},
"schema-editor": {
"self": "Trình chỉnh sửa lược đồ",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 1f168e2d01..d4aeddaca4 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -274,7 +274,8 @@
"baseline": "基线",
"project-member": "项目成员",
"leave-without-saving": "不保存变动?",
- "configure-now": "现在配置"
+ "configure-now": "现在配置",
+ "connection": "连接"
},
"error-page": {
"go-back-home": "回到主页"
@@ -2250,7 +2251,15 @@
"previous-row": "上一行",
"next-row": "下一行",
"copy-success": "复制成功",
- "missing-permission-to-load-db-metadata": "缺少加载数据库 {db} 元数据所需的权限。"
+ "missing-permission-to-load-db-metadata": "缺少加载数据库 {db} 元数据所需的权限。",
+ "connect-in-new-tab": "在新选项卡中连接",
+ "copy-name": "复制名称",
+ "copy-select-statement": "复制 SELECT 语句",
+ "preview-table-data": "预览表数据",
+ "view-table-detail": "查看表详情",
+ "view-database-detail": "查看数据库详情",
+ "copy-all-column-names": "复制所有列名",
+ "view-schema-text": "查看文本 Schema"
},
"schema-editor": {
"self": "Schema 编辑器",
diff --git a/frontend/src/store/modules/sqlEditor/tree.ts b/frontend/src/store/modules/sqlEditor/tree.ts
index dccb983b15..5ef17d4a9f 100644
--- a/frontend/src/store/modules/sqlEditor/tree.ts
+++ b/frontend/src/store/modules/sqlEditor/tree.ts
@@ -1,5 +1,5 @@
import { useLocalStorage } from "@vueuse/core";
-import { cloneDeep, isFunction, orderBy } from "lodash-es";
+import { cloneDeep, orderBy } from "lodash-es";
import { defineStore, storeToRefs } from "pinia";
import { v4 as uuidv4 } from "uuid";
import { computed, reactive, ref, watch } from "vue";
@@ -12,13 +12,7 @@ import type {
SQLEditorTreeNodeTarget as NodeTarget,
SQLEditorTreeNodeType as NodeType,
SQLEditorTreeState as TreeState,
- RichSchemaMetadata,
- RichTableMetadata,
StatefulSQLEditorTreeFactor as StatefulFactor,
- RichViewMetadata,
- TextTarget,
- RichPartitionTableMetadata,
- RichExternalTableMetadata,
} from "@/types";
import {
isValidSQLEditorTreeFactor as isValidFactor,
@@ -181,7 +175,7 @@ export const useSQLEditorTreeStore = defineStore("sqlEditorTree", () => {
databaseList,
factorList,
filteredFactorList,
- currentProject: currentProject,
+ currentProject,
state,
tree,
collectNode,
@@ -220,46 +214,10 @@ export const idForSQLEditorTreeNodeTarget = <T extends NodeType>(
| 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 === "external-table") {
- const { database, schema, externalTable } =
- target as RichExternalTableMetadata;
- return `${database.name}/schemas/${schema.name || "-"}/externalTables/${
- externalTable.name
- }`;
- }
- if (type === "partition-table") {
- const { database, schema, table, partition } =
- target as RichPartitionTableMetadata;
- return `${database.name}/schemas/${schema.name || "-"}/tables/${
- table.name
- }/partitions/${partition.name}`;
- }
- if (type === "view") {
- const { database, schema, view } = target as RichViewMetadata;
- return `${database.name}/schemas/${schema.name || "-"}/views/${view.name}`;
- }
if (type === "label") {
const kv = target as NodeTarget<"label">;
return `labels/${kv.key}:${kv.value}`;
}
- if (type === "expandable-text") {
- const { text, id, type } = target as NodeTarget<"expandable-text">;
- return `texts-${type}/${id}/${typeof text === "function" ? text() : text}`;
- }
- if (type === "dummy") {
- const { type, id } = target as NodeTarget<"dummy">;
- return `dummy-${type}/${id}`;
- }
throw new Error(
`should never reach this line, type=${type}, target=${target}, parent=${parent}`
@@ -418,30 +376,6 @@ const readableTargetByType = <T extends NodeType>(
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 === "external-table") {
- return (target as RichExternalTableMetadata).externalTable.name;
- }
- if (type === "partition-table") {
- return (target as RichPartitionTableMetadata).partition.name;
- }
- if (type === "view") {
- return (target as RichViewMetadata).view.name;
- }
- if (type === "expandable-text") {
- const { text, searchable } = target as TextTarget<true>;
- if (!searchable) return "";
- return isFunction(text) ? text() : text;
- }
- if (type === "dummy") {
- // Use empty strings for dummy nodes to make them unsearchable
- return "";
- }
return (target as NodeTarget<"label">).value;
};
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 22a3fbbf84..6c1f29d59a 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -41,5 +41,6 @@ export * from "./setting";
export * from "./changeHistory";
export * from "./semanticTypes";
export * from "./iam";
+export * from "./misc";
export * from "./v1";
diff --git a/frontend/src/types/misc.ts b/frontend/src/types/misc.ts
new file mode 100644
index 0000000000..d6f2f2ad4b
--- /dev/null
+++ b/frontend/src/types/misc.ts
@@ -0,0 +1,4 @@
+export type Position = {
+ x: number;
+ y: number;
+};
diff --git a/frontend/src/types/sqlEditor/tree.ts b/frontend/src/types/sqlEditor/tree.ts
index c3e0d271f9..eb52bd1ec4 100644
--- a/frontend/src/types/sqlEditor/tree.ts
+++ b/frontend/src/types/sqlEditor/tree.ts
@@ -1,15 +1,6 @@
import type { TreeOption } from "naive-ui";
-import type { RenderFunction } from "vue";
import { t } from "@/plugins/i18n";
import { useSQLEditorTreeStore } from "@/store";
-import { Engine } from "../proto/v1/common";
-import type {
- ExternalTableMetadata,
- SchemaMetadata,
- TableMetadata,
- TablePartitionMetadata,
- ViewMetadata,
-} from "../proto/v1/database_service";
import type { Environment } from "../proto/v1/environment_service";
import type {
ComposedDatabase,
@@ -33,58 +24,12 @@ export type SQLEditorTreeNodeType =
| "instance"
| "environment"
| "database"
- | "schema"
- | "table"
- | "external-table"
- | "label"
- | "view"
- | "partition-table"
- | "expandable-text" // Text nodes to display "Tables / Views / Functions / Triggers" etc.
- | "dummy"; // Dummy nodes to display "<Empty>" etc.
-
-export type RichSchemaMetadata = {
- database: ComposedDatabase;
- schema: SchemaMetadata;
-};
-export type RichTableMetadata = {
- database: ComposedDatabase;
- schema: SchemaMetadata;
- table: TableMetadata;
-};
-export type RichExternalTableMetadata = {
- database: ComposedDatabase;
- schema: SchemaMetadata;
- externalTable: ExternalTableMetadata;
-};
-export type RichPartitionTableMetadata = {
- database: ComposedDatabase;
- schema: SchemaMetadata;
- table: TableMetadata;
- parentPartition?: TablePartitionMetadata;
- partition: TablePartitionMetadata;
-};
-export type RichViewMetadata = {
- database: ComposedDatabase;
- schema: SchemaMetadata;
- view: ViewMetadata;
-};
-export type TextTarget<E extends boolean> = {
- expandable: E;
- id: string;
- type: SQLEditorTreeNodeType;
- text: string | (() => string);
- render?: RenderFunction;
- searchable?: boolean;
-};
+ | "label";
+
export type LabelTarget = {
key: string;
value: string;
};
-export type DummyTarget = {
- id: string;
- type: SQLEditorTreeNodeType;
- error?: unknown;
-};
export type SQLEditorTreeNodeTarget<T extends SQLEditorTreeNodeType = any> =
T extends "project"
@@ -95,23 +40,9 @@ export type SQLEditorTreeNodeTarget<T extends SQLEditorTreeNodeType = any> =
? Environment
: T extends "database"
? ComposedDatabase
- : T extends "schema"
- ? RichSchemaMetadata
- : T extends "table"
- ? RichTableMetadata
- : T extends "external-table"
- ? RichExternalTableMetadata
- : T extends "partition-table"
- ? RichPartitionTableMetadata
- : T extends "view"
- ? RichViewMetadata
- : T extends "label"
- ? LabelTarget
- : T extends "expandable-text"
- ? TextTarget<true>
- : T extends "dummy"
- ? DummyTarget
- : never;
+ : T extends "label"
+ ? LabelTarget
+ : never;
export type SQLEditorTreeState = "UNSET" | "LOADING" | "READY";
@@ -140,25 +71,17 @@ export const isValidSQLEditorTreeFactor = (
export const ExpandableTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
"instance",
- "database",
- "schema",
"environment",
"project",
- "table",
- "external-table",
- "partition-table",
- "expandable-text",
"label",
] as const;
export const ConnectableTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
- "instance",
"database",
] as const;
export const LeafTreeNodeTypes: readonly SQLEditorTreeNodeType[] = [
- "view",
- "dummy",
+ "database",
] as const;
export const extractSQLEditorLabelFactor = (factor: string) => {
@@ -196,16 +119,8 @@ export const isConnectableSQLEditorTreeNode = (
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;
+ const { type } = node.meta;
+ return type === "database";
};
export const instanceOfSQLEditorTreeNode = (node: SQLEditorTreeNode) => {
diff --git a/frontend/src/utils/collections.ts b/frontend/src/utils/collections.ts
index a174f753fc..fd7d4b19d8 100644
--- a/frontend/src/utils/collections.ts
+++ b/frontend/src/utils/collections.ts
@@ -35,3 +35,17 @@ export const upsertArray = <T>(array: T[], item: T) => {
array.push(item);
}
};
+
+export const sortByDictionary = <T, K>(
+ array: T[],
+ dictionary: K[],
+ mapper: (item: T) => K
+) => {
+ array.sort((a, b) => {
+ let orderA = dictionary.indexOf(mapper(a));
+ let orderB = dictionary.indexOf(mapper(b));
+ if (orderA < 0) orderA = Number.MAX_VALUE;
+ if (orderB < 0) orderB = Number.MAX_VALUE;
+ return orderA - orderB;
+ });
+};
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
index 826646cb81..573d881cf5 100644
--- a/frontend/src/utils/sqlEditor.ts
+++ b/frontend/src/utils/sqlEditor.ts
@@ -116,9 +116,14 @@ export const isDisconnectedSQLEditorTab = (tab: SQLEditorTab) => {
export const tryConnectToCoreSQLEditorTab = (
tab: CoreSQLEditorTab,
- overrideTitle = true
+ overrideTitle = true,
+ newTab = false
) => {
const tabStore = useSQLEditorTabStore();
+ if (newTab) {
+ tabStore.addTab({}, true);
+ }
+
const currentTab = tabStore.currentTab;
if (currentTab) {
if (isSimilarSQLEditorTab(tab, currentTab)) {
diff --git a/frontend/src/utils/v1/sql.ts b/frontend/src/utils/v1/sql.ts
index 6300a423ca..2fb2768bfc 100644
--- a/frontend/src/utils/v1/sql.ts
+++ b/frontend/src/utils/v1/sql.ts
@@ -78,6 +78,10 @@ export const generateSimpleSelectAllStatement = (
table: string,
limit: number
) => {
+ if (engine === Engine.MONGODB) {
+ return `db["${table}"].find().limit(${limit});`;
+ }
+
const schemaAndTable = generateSchemaAndTableNameInSQL(engine, schema, table);
if (engine === Engine.MSSQL) {
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
index 5d8470b480..cf54b81d78 100644
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
@@ -1,8 +1,8 @@
<template>
- <div class="aside-panel h-full flex flex-col overflow-hidden">
+ <div class="h-full flex flex-col overflow-hidden">
<div
v-if="!strictProject"
- class="flex flex-row items-center gap-x-1 px-1 pt-1"
+ class="flex flex-row items-center gap-x-1 px-1 py-1 border-b"
>
<ProjectSelect
style="width: 100%"
@@ -14,8 +14,17 @@
@update:project="handleSwitchProject"
/>
</div>
- <div class="flex-1 overflow-hidden pt-1">
- <DatabaseTree />
+
+ <div class="flex-1 flex flex-row overflow-hidden">
+ <div class="h-full border-r shrink-0">
+ <GutterBar />
+ </div>
+ <div class="h-full flex-1 flex flex-col pt-1 overflow-hidden">
+ <ConnectionPane v-if="asidePanelTab === 'CONNECTION'" />
+ <WorksheetPane v-if="asidePanelTab === 'WORKSHEET'" />
+ <SchemaPane v-if="asidePanelTab === 'SCHEMA'" />
+ <HistoryPane v-if="asidePanelTab === 'HISTORY'" />
+ </div>
</div>
</div>
</template>
@@ -31,11 +40,15 @@ import {
} from "@/store";
import { UNKNOWN_ID } from "@/types";
import { useSQLEditorContext } from "../context";
-import DatabaseTree from "./DatabaseTree.vue";
+import ConnectionPane from "./ConnectionPane";
+import GutterBar from "./GutterBar";
+import HistoryPane from "./HistoryPane";
+import SchemaPane from "./SchemaPane";
+import WorksheetPane from "./WorksheetPane";
const editorStore = useSQLEditorStore();
const treeStore = useSQLEditorTreeStore();
-const { events } = useSQLEditorContext();
+const { events, asidePanelTab } = useSQLEditorContext();
const { project, projectContextReady, strictProject } =
storeToRefs(editorStore);
@@ -65,6 +78,6 @@ const handleSwitchProject = (uid: string | undefined) => {
<style lang="postcss" scoped>
.project-select :deep(.n-base-selection) {
- --n-height: 30px !important;
+ --n-height: 25px !important;
}
</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/ConnectionPane.vue
new file mode 100644
index 0000000000..36c69e99ef
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/ConnectionPane.vue
@@ -0,0 +1,363 @@
+<template>
+ <div class="sql-editor-tree gap-y-1 h-full flex flex-col relative">
+ <div class="flex flex-row gap-x-0.5 px-1 items-center">
+ <SearchBox v-model:searchPattern="searchPattern" class="flex-1" />
+ <GroupingBar class="shrink-0" />
+ </div>
+ <div
+ ref="treeContainerElRef"
+ class="sql-editor-tree--tree flex-1 px-1 pb-1 text-sm overflow-hidden select-none"
+ :data-height="treeContainerHeight"
+ >
+ <NTree
+ v-if="treeStore.state === 'READY'"
+ ref="treeRef"
+ v-model:expanded-keys="expandedKeys"
+ :block-line="true"
+ :data="treeStore.tree"
+ :show-irrelevant-nodes="false"
+ :selected-keys="selectedKeys"
+ :pattern="mounted ? searchPattern : ''"
+ :expand-on-click="true"
+ :node-props="nodeProps"
+ :virtual-scroll="true"
+ :theme-overrides="{ nodeHeight: '21px' }"
+ :render-label="renderLabel"
+ />
+ </div>
+
+ <NDropdown
+ v-if="treeStore.state === 'READY'"
+ placement="bottom-start"
+ trigger="manual"
+ :x="dropdownPosition.x"
+ :y="dropdownPosition.y"
+ :options="dropdownOptions"
+ :show="showDropdown"
+ :on-clickoutside="handleDropdownClickoutside"
+ @select="handleDropdownSelect"
+ />
+
+ <DatabaseHoverPanel :offset-x="4" :offset-y="4" :margin="4" />
+
+ <MaskSpinner v-if="treeStore.state !== 'READY'" class="!bg-white/75">
+ <span class="text-control text-sm">{{
+ $t("sql-editor.loading-databases")
+ }}</span>
+ </MaskSpinner>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { useElementSize, useMounted } from "@vueuse/core";
+import { head } from "lodash-es";
+import { NTree, NDropdown, type TreeOption } from "naive-ui";
+import { ref, computed, nextTick, watch, h } from "vue";
+import MaskSpinner from "@/components/misc/MaskSpinner.vue";
+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
+import {
+ useDatabaseV1Store,
+ useInstanceV1Store,
+ useIsLoggedIn,
+ useSQLEditorTabStore,
+ resolveOpeningDatabaseListFromSQLEditorTabList,
+ useSQLEditorTreeStore,
+ idForSQLEditorTreeNodeTarget,
+ useConnectionOfCurrentSQLEditorTab,
+} from "@/store";
+import type {
+ ComposedDatabase,
+ SQLEditorTreeNode,
+ SQLEditorTreeNodeTarget,
+ SQLEditorTreeNodeType,
+} from "@/types";
+import { ExpandableTreeNodeTypes, UNKNOWN_ID } from "@/types";
+import { findAncestor, isDescendantOf } from "@/utils";
+import { useSQLEditorContext } from "../../context";
+import {
+ DatabaseHoverPanel,
+ provideHoverStateContext,
+} from "./DatabaseHoverPanel";
+import GroupingBar from "./GroupingBar";
+import SearchBox from "./SearchBox/index.vue";
+import useSearchHistory from "./SearchBox/useSearchHistory";
+import { Label } from "./TreeNode";
+import { setConnection, useDropdown } from "./actions";
+
+const treeStore = useSQLEditorTreeStore();
+const tabStore = useSQLEditorTabStore();
+const databaseStore = useDatabaseV1Store();
+const instanceStore = useInstanceV1Store();
+const isLoggedIn = useIsLoggedIn();
+const { events: editorEvents } = useSQLEditorContext();
+const searchHistory = useSearchHistory();
+const {
+ state: hoverState,
+ position: hoverPosition,
+ update: updateHoverNode,
+} = provideHoverStateContext();
+const {
+ show: showDropdown,
+ context: dropdownContext,
+ position: dropdownPosition,
+ options: dropdownOptions,
+ handleSelect: handleDropdownSelect,
+ handleClickoutside: handleDropdownClickoutside,
+} = useDropdown();
+
+const mounted = useMounted();
+const treeContainerElRef = ref<HTMLElement>();
+const { height: treeContainerHeight } = useElementSize(
+ treeContainerElRef,
+ undefined,
+ {
+ box: "content-box",
+ }
+);
+const treeRef = ref<InstanceType<typeof NTree>>();
+const searchPattern = ref("");
+
+// Highlight the current tab's connection node.
+const selectedKeys = computed(() => {
+ const connection = tabStore.currentTab?.connection;
+ if (!connection) {
+ return [];
+ }
+
+ if (connection.database) {
+ const database = databaseStore.getDatabaseByName(connection.database);
+ const node = head(treeStore.nodesByTarget("database", database));
+ if (!node) return [];
+ return [node.key];
+ } else if (connection.instance) {
+ const instance = instanceStore.getInstanceByName(connection.instance);
+ const nodes = treeStore.nodesByTarget("instance", instance);
+ return nodes.map((node) => node.key);
+ }
+ return [];
+});
+const expandedKeys = ref<string[]>([]);
+const upsertExpandedKeys = (key: string) => {
+ if (expandedKeys.value.includes(key)) {
+ return;
+ }
+ expandedKeys.value.push(key);
+};
+const expandNode = (
+ node: SQLEditorTreeNode | undefined,
+ keys?: Set<string>
+) => {
+ if (!node) {
+ return;
+ }
+ if (ExpandableTreeNodeTypes.includes(node.meta.type)) {
+ if (keys) {
+ keys.add(node.key);
+ } else {
+ upsertExpandedKeys(node.key);
+ }
+ }
+};
+const expandNodeRecursively = (
+ node: SQLEditorTreeNode | undefined,
+ keys?: Set<string>
+) => {
+ if (!node) {
+ return;
+ }
+ expandNode(node, keys);
+
+ if (node.parent) {
+ expandNodeRecursively(node.parent, keys);
+ }
+};
+const expandNodesByType = <T extends SQLEditorTreeNodeType>(
+ type: T,
+ target: SQLEditorTreeNodeTarget<T>
+) => {
+ const nodes = treeStore.nodesByTarget(type, target);
+
+ nodes.forEach((node) => {
+ expandNodeRecursively(node);
+ });
+
+ return nodes;
+};
+
+// dynamic render the highlight keywords
+const renderLabel = ({ option }: { option: TreeOption }) => {
+ const node = option as any as SQLEditorTreeNode;
+ return h(Label, {
+ node,
+ factors: treeStore.filteredFactorList,
+ keyword: searchPattern.value ?? "",
+ });
+};
+
+const nodeProps = ({ option }: { option: TreeOption }) => {
+ const node = option as any as SQLEditorTreeNode;
+ return {
+ onClick(e: MouseEvent) {
+ 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 (type === "database") {
+ setConnection(node);
+ }
+
+ // If the search pattern is not empty, append the selected database name to
+ // the search history.
+ if (searchPattern.value) {
+ if (type === "database") {
+ const database = node.meta.target as ComposedDatabase;
+ searchHistory.appendSearchResult(database.name);
+ }
+ }
+ }
+ },
+ onContextmenu(e: MouseEvent) {
+ e.preventDefault();
+ showDropdown.value = false;
+ if (node && node.key) {
+ dropdownContext.value = node;
+ }
+
+ nextTick().then(() => {
+ showDropdown.value = true;
+ dropdownPosition.value.x = e.clientX;
+ dropdownPosition.value.y = e.clientY;
+ });
+ },
+ onmouseenter(e: MouseEvent) {
+ if (node.meta.type === "database") {
+ if (hoverState.value) {
+ updateHoverNode({ node }, "before", 0 /* overrideDelay */);
+ } else {
+ updateHoverNode({ node }, "before");
+ }
+ nextTick().then(() => {
+ // Find the node element and put the database panel to the right corner
+ // of the node
+ const wrapper = findAncestor(e.target as HTMLElement, ".n-tree-node");
+ if (!wrapper) {
+ updateHoverNode(undefined, "after", 0 /* overrideDelay */);
+ return;
+ }
+ const bounding = wrapper.getBoundingClientRect();
+ hoverPosition.value.x = bounding.right;
+ hoverPosition.value.y = bounding.top;
+ });
+ }
+ },
+ onmouseleave() {
+ updateHoverNode(undefined, "after");
+ },
+ // attrs below for trouble-shooting
+ "data-node-meta-type": node.meta.type,
+ "data-node-meta-id": idForSQLEditorTreeNodeTarget(
+ node.meta.type,
+ node.meta.target
+ ),
+ "data-node-key": node.key,
+ };
+};
+
+// Open corresponding tree node when the connection changed.
+const { instance, database } = useConnectionOfCurrentSQLEditorTab();
+watch(
+ [isLoggedIn, instance, database, () => treeStore.state],
+ ([isLoggedIn, instance, database, treeState]) => {
+ if (!isLoggedIn) {
+ // Don't go further and cleanup the state if we signed out.
+ // treeStore.expandedKeys = [];
+ expandedKeys.value = [];
+ return;
+ }
+
+ if (treeState !== "READY") {
+ return;
+ }
+ if (instance.uid !== String(UNKNOWN_ID)) {
+ expandNodesByType("instance", instance);
+ }
+ if (database.uid !== String(UNKNOWN_ID)) {
+ expandNodesByType("project", database.projectEntity);
+ expandNodesByType("database", database);
+ }
+ },
+ { immediate: true }
+);
+
+watch(
+ selectedKeys,
+ (keys) => {
+ if (keys.length !== 1) return;
+ const key = keys[0];
+ nextTick(() => {
+ treeRef.value?.scrollTo({ key });
+ });
+ },
+ { immediate: true }
+);
+
+useEmitteryEventListener(editorEvents, "tree-ready", async () => {
+ await nextTick();
+ const openingDatabaseList = resolveOpeningDatabaseListFromSQLEditorTabList();
+ const keys = new Set<string>();
+ // Recursively expand opening databases' parent nodes
+ openingDatabaseList.forEach((meta) => {
+ const db = meta.target;
+ const nodes = treeStore.nodesByTarget("database", db);
+ nodes.forEach((node) => expandNodeRecursively(node.parent, keys));
+ });
+ const tab = tabStore.currentTab;
+ // Expand current tab's connected database node
+ if (tab && tab.connection.database) {
+ const db = useDatabaseV1Store().getDatabaseByName(tab.connection.database);
+ const node = head(treeStore.nodesByTarget("database", db));
+ if (node) {
+ keys.add(node.key);
+ }
+ }
+ expandedKeys.value = Array.from(keys);
+});
+</script>
+
+<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;
+}
+.sql-editor-tree :deep(.n-tree-node-wrapper) {
+ padding: 0;
+}
+.sql-editor-tree :deep(.n-tree-node-indent) {
+ width: 0.25rem;
+}
+.sql-editor-tree :deep(.n-tree-node-content__prefix) {
+ @apply shrink-0 !mr-1;
+}
+.sql-editor-tree.project
+ :deep(.n-tree-node[data-node-type="project"] .n-tree-node-content__prefix) {
+ @apply hidden;
+}
+.sql-editor-tree :deep(.n-tree-node-content__text) {
+ @apply truncate mr-1;
+}
+.sql-editor-tree :deep(.n-tree-node--pending) {
+ background-color: transparent !important;
+}
+.sql-editor-tree :deep(.n-tree-node--pending:hover) {
+ background-color: var(--n-node-color-hover) !important;
+}
+.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;
+ font-weight: 500;
+}
+</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.vue
similarity index 71%
rename from frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.vue
index 03d93cc1c9..946e5227b9 100644
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseHoverPanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.vue
@@ -1,13 +1,13 @@
<template>
<div
- v-show="database"
+ v-show="show && database"
ref="popoverRef"
v-zindexable="{ enabled: true }"
class="fixed border border-gray-100 rounded bg-white p-2 shadow transition-all text-sm"
:class="!show && 'pointer-events-none'"
:style="{
- left: `${x}px`,
- top: `${y}px`,
+ left: `${displayPosition.x}px`,
+ top: `${displayPosition.y}px`,
}"
>
<template v-if="database">
@@ -64,7 +64,7 @@
</template>
<script setup lang="ts">
-import { onClickOutside, useEventListener } from "@vueuse/core";
+import { onClickOutside, useElementSize, useEventListener } from "@vueuse/core";
import { zindexable as vZindexable } from "vdirs";
import { computed, ref } from "vue";
import {
@@ -73,13 +73,14 @@ import {
ProjectV1Name,
} from "@/components/v2";
import { useSQLEditorTreeStore } from "@/store";
-import type { ComposedDatabase } from "@/types";
+import type { Position, SQLEditorTreeNodeTarget } from "@/types";
+import { minmax } from "@/utils";
import { useHoverStateContext } from "./hover-state";
const props = defineProps<{
- database: ComposedDatabase | undefined;
- x: number;
- y: number;
+ offsetX: number;
+ offsetY: number;
+ margin: number;
}>();
const emit = defineEmits<{
@@ -87,24 +88,48 @@ const emit = defineEmits<{
}>();
const treeStore = useSQLEditorTreeStore();
-const { node, update } = useHoverStateContext();
+const { state, position, update } = useHoverStateContext();
const popoverRef = ref<HTMLDivElement>();
onClickOutside(popoverRef, (e) => {
emit("click-outside", e);
});
+const { height: popoverHeight } = useElementSize(popoverRef, undefined, {
+ box: "border-box",
+});
const show = computed(
- () => props.database !== undefined && props.x !== 0 && props.y !== 0
+ () =>
+ state.value !== undefined &&
+ position.value.x !== 0 &&
+ position.value.y !== 0
);
+const database = computed(() => {
+ if (!state.value?.node) return undefined;
+ const { type, target } = state.value.node.meta;
+ if (type !== "database") return undefined;
+ return target as SQLEditorTreeNodeTarget<"database">;
+});
const hasProjectContext = computed(() => {
return !!treeStore.currentProject;
});
+const displayPosition = computed(() => {
+ const p: Position = {
+ x: position.value.x + props.offsetX,
+ y: position.value.y + props.offsetY,
+ };
+ const yMin = props.margin;
+ const yMax = window.innerHeight - popoverHeight.value - props.margin;
+ p.y = minmax(p.y, yMin, yMax);
+
+ return p;
+});
+
useEventListener(popoverRef, "mouseenter", () => {
// Reset the value immediately to cancel other pending setting values
- update(node.value, "before", 0 /* overrideDelay */);
+ update(state.value, "before", 0 /* overrideDelay */);
});
useEventListener(popoverRef, "mouseleave", () => {
update(undefined, "before");
diff --git a/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/hover-state.ts b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/hover-state.ts
new file mode 100644
index 0000000000..9668b65010
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/hover-state.ts
@@ -0,0 +1,19 @@
+import type { SQLEditorTreeNode } from "@/types";
+import {
+ useHoverStateContext as _useHoverStateContext,
+ provideHoverStateContext as _provideHoverStateContext,
+} from "../../hover-state";
+
+export const KEY = "connection-pane";
+
+export type HoverState = {
+ node?: SQLEditorTreeNode;
+};
+
+export const useHoverStateContext = () => {
+ return _useHoverStateContext<HoverState>(KEY);
+};
+
+export const provideHoverStateContext = () => {
+ return _provideHoverStateContext<HoverState>(KEY);
+};
diff --git a/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/index.ts b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/index.ts
new file mode 100644
index 0000000000..c3ebae71c9
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/DatabaseHoverPanel/index.ts
@@ -0,0 +1,5 @@
+import DatabaseHoverPanel from "./DatabaseHoverPanel.vue";
+
+export * from "./hover-state";
+export { DatabaseHoverPanel };
+export default DatabaseHoverPanel;
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorItem.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorItem.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorItem.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorPanel.vue
similarity index 96%
rename from frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorPanel.vue
index 3dd6ede890..a11b662340 100644
--- a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorPanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorPanel.vue
@@ -27,7 +27,7 @@ import { storeToRefs } from "pinia";
import { computed } from "vue";
import { useSQLEditorTreeStore } from "@/store";
import type { SQLEditorTreeFactor as Factor } from "@/types";
-import { useSQLEditorContext } from "../../context";
+import { useSQLEditorContext } from "@/views/sql-editor/context";
import FactorItem from "./FactorItem.vue";
import FactorTags from "./FactorTags.vue";
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorTag.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTag.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorTag.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTags.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorTags.vue
similarity index 94%
rename from frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTags.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorTags.vue
index 829f1b7711..0cd9c796b1 100644
--- a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/FactorTags.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/FactorTags.vue
@@ -15,7 +15,7 @@
import { storeToRefs } from "pinia";
import { useSQLEditorTreeStore } from "@/store";
import type { StatefulSQLEditorTreeFactor as StatefulFactor } from "@/types";
-import { useSQLEditorContext } from "../../context";
+import { useSQLEditorContext } from "@/views/sql-editor/context";
import FactorTag from "./FactorTag.vue";
const treeStore = useSQLEditorTreeStore();
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/GroupingBar.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/GroupingBar/GroupingBar.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/GroupingBar.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/GroupingBar/index.ts b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/index.ts
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/GroupingBar/index.ts
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/GroupingBar/index.ts
diff --git a/frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/SearchBox/index.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/SearchBox/index.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/SearchBox/index.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/SearchBox/useSearchHistory.ts b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/SearchBox/useSearchHistory.ts
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/SearchBox/useSearchHistory.ts
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/SearchBox/useSearchHistory.ts
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/DatabaseNode.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/DatabaseNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/DatabaseNode.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/EnvironmentNode.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/EnvironmentNode.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/EnvironmentNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/EnvironmentNode.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/HighlightLabelText.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/HighlightLabelText.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/HighlightLabelText.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/HighlightLabelText.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/InstanceNode.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/InstanceNode.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/InstanceNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/InstanceNode.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/Label.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/Label.vue
new file mode 100644
index 0000000000..7296947f74
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/Label.vue
@@ -0,0 +1,38 @@
+<template>
+ <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 === 'label'">
+ <LabelNode :node="node" :factors="factors" :keyword="keyword" />
+ </template>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import type {
+ SQLEditorTreeNode as TreeNode,
+ SQLEditorTreeFactor as Factor,
+} from "@/types";
+import DatabaseNode from "./DatabaseNode.vue";
+import EnvironmentNode from "./EnvironmentNode.vue";
+import InstanceNode from "./InstanceNode.vue";
+import LabelNode from "./LabelNode.vue";
+import ProjectNode from "./ProjectNode.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ factors: Factor[];
+ keyword: string;
+}>();
+
+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/ConnectionPane/TreeNode/LabelNode.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/LabelNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/LabelNode.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/ProjectNode.vue b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/ProjectNode.vue
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/ProjectNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/ProjectNode.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/index.ts
similarity index 100%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/index.ts
rename to frontend/src/views/sql-editor/AsidePanel/ConnectionPane/TreeNode/index.ts
diff --git a/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/actions.tsx b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/actions.tsx
new file mode 100644
index 0000000000..d6133fccc5
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/actions.tsx
@@ -0,0 +1,183 @@
+import {
+ ExternalLinkIcon,
+ LinkIcon,
+ SquarePenIcon,
+ WrenchIcon,
+} from "lucide-vue-next";
+import type { DropdownOption } from "naive-ui";
+import { computed, ref } from "vue";
+import { useRouter } from "vue-router";
+import { t } from "@/plugins/i18n";
+import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
+import { useCurrentUserV1, usePageMode } from "@/store";
+import {
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ instanceOfSQLEditorTreeNode,
+ isConnectableSQLEditorTreeNode,
+ type ComposedDatabase,
+ type CoreSQLEditorTab,
+ type Position,
+ type SQLEditorTabMode as TabMode,
+ type SQLEditorTreeNode as TreeNode,
+} from "@/types";
+import {
+ emptySQLEditorConnection,
+ extractInstanceResourceName,
+ extractProjectResourceName,
+ hasWorkspacePermissionV2,
+ instanceV1HasAlterSchema,
+ instanceV1HasReadonlyMode,
+ tryConnectToCoreSQLEditorTab,
+} from "@/utils";
+import { useSQLEditorContext } from "../../context";
+
+type DropdownOptionWithTreeNode = DropdownOption & {
+ onSelect: () => void;
+};
+
+export const useDropdown = () => {
+ const router = useRouter();
+ const { events: editorEvents } = useSQLEditorContext();
+ const pageMode = usePageMode();
+
+ const show = ref(false);
+ const position = ref<Position>({
+ x: 0,
+ y: 0,
+ });
+ const context = ref<TreeNode>();
+
+ const me = useCurrentUserV1();
+ const allowAdmin = computed(() =>
+ hasWorkspacePermissionV2(me.value, "bb.instances.adminExecute")
+ );
+
+ const options = computed((): DropdownOptionWithTreeNode[] => {
+ const node = context.value;
+ if (!node) {
+ return [];
+ }
+ const { type, target } = node.meta;
+ if (type === "project") {
+ return [];
+ } else {
+ // Don't show any context menu actions for disabled
+ // instances/databases
+ if (node.disabled) {
+ return [];
+ }
+
+ const items: DropdownOptionWithTreeNode[] = [];
+
+ if (isConnectableSQLEditorTreeNode(node)) {
+ const instance = instanceOfSQLEditorTreeNode(node);
+ if (instance && instanceV1HasReadonlyMode(instance)) {
+ items.push({
+ key: "connect",
+ label: t("sql-editor.connect"),
+ icon: () => <LinkIcon class="w-4 h-4" />,
+ onSelect: () => setConnection(node),
+ });
+ items.push({
+ key: "connect-in-new-tab",
+ label: t("sql-editor.connect-in-new-tab"),
+ icon: () => <LinkIcon class="w-4 h-4" />,
+ onSelect: () =>
+ setConnection(
+ node,
+ { sheet: "", mode: DEFAULT_SQL_EDITOR_TAB_MODE },
+ /* newTab */ true
+ ),
+ });
+ }
+ if (allowAdmin.value) {
+ items.push({
+ key: "connect-in-admin-mode",
+ label: t("sql-editor.connect-in-admin-mode"),
+ icon: () => <WrenchIcon class="w-4 h-4" />,
+ onSelect: () => setConnection(node, { sheet: "", mode: "ADMIN" }),
+ });
+ }
+ }
+ if (pageMode.value === "BUNDLED") {
+ if (type === "database") {
+ const database = target as ComposedDatabase;
+ items.push({
+ key: "view-database-detail",
+ label: t("sql-editor.view-database-detail"),
+ icon: () => <ExternalLinkIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const route = router.resolve({
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(database.project),
+ instanceId: extractInstanceResourceName(database.instance),
+ databaseName: database.databaseName,
+ },
+ });
+ const url = route.href;
+ window.open(url, "_blank");
+ },
+ });
+ if (instanceV1HasAlterSchema(database.instanceEntity)) {
+ items.push({
+ key: "alter-schema",
+ label: t("database.edit-schema"),
+ icon: () => <SquarePenIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const db = node.meta.target as ComposedDatabase;
+ editorEvents.emit("alter-schema", {
+ databaseUID: db.uid,
+ schema: "",
+ table: "",
+ });
+ },
+ });
+ }
+ }
+ }
+ return items;
+ }
+ });
+
+ const handleSelect = (key: string) => {
+ const option = options.value.find((item) => item.key === key);
+ if (!option) {
+ return;
+ }
+ option.onSelect();
+ show.value = false;
+ };
+
+ const handleClickoutside = () => {
+ show.value = false;
+ };
+
+ return { show, position, context, options, handleSelect, handleClickoutside };
+};
+
+export const setConnection = (
+ node: TreeNode<"database">,
+ extra: { sheet: string; mode: TabMode } = {
+ sheet: "",
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ },
+ newTab = false
+) => {
+ if (!node) {
+ return;
+ }
+ if (!isConnectableSQLEditorTreeNode(node)) {
+ // one more guard
+ return;
+ }
+ const coreTab: CoreSQLEditorTab = {
+ connection: emptySQLEditorConnection(),
+ ...extra,
+ };
+ const conn = coreTab.connection;
+ const database = node.meta.target as ComposedDatabase;
+ conn.instance = database.instance;
+ conn.database = database.name;
+ tryConnectToCoreSQLEditorTab(coreTab, /* overrideTitle */ true, newTab);
+};
diff --git a/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/index.ts
new file mode 100644
index 0000000000..a0b290cb40
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/ConnectionPane/index.ts
@@ -0,0 +1,3 @@
+import ConnectionPane from "./ConnectionPane.vue";
+
+export default ConnectionPane;
diff --git a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue b/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
deleted file mode 100644
index df78a3f72f..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/DatabaseTree.vue
+++ /dev/null
@@ -1,871 +0,0 @@
-<template>
- <div
- v-if="treeStore.state === 'READY'"
- class="sql-editor-tree gap-y-1 h-full flex flex-col"
- >
- <div class="flex flex-row gap-x-0.5 px-1 items-center">
- <SearchBox v-model:searchPattern="searchPattern" class="flex-1" />
- <GroupingBar class="shrink-0" />
- </div>
- <div
- ref="treeContainerElRef"
- class="sql-editor-tree--tree flex-1 px-1 pb-1 text-sm overflow-hidden select-none"
- :data-height="treeContainerHeight"
- >
- <NTree
- ref="treeRef"
- v-model:expanded-keys="expandedKeys"
- :block-line="true"
- :data="treeStore.tree"
- :show-irrelevant-nodes="false"
- :selected-keys="selectedKeys"
- :pattern="mounted ? searchPattern : ''"
- :expand-on-click="true"
- :node-props="nodeProps"
- :virtual-scroll="true"
- :theme-overrides="{ nodeHeight: '21px' }"
- :render-label="renderLabel"
- @load="handleLoadSubTree"
- />
- </div>
-
- <NDropdown
- placement="bottom-start"
- trigger="manual"
- :x="dropdownPosition.x"
- :y="dropdownPosition.y"
- :options="dropdownOptions"
- :show="showDropdown"
- :on-clickoutside="handleClickoutside"
- @select="handleSelect"
- />
-
- <DatabaseHoverPanel
- :database="hoverNode?.meta.target as ComposedDatabase"
- :x="hoverPanelPosition.x"
- :y="hoverPanelPosition.y"
- class="ml-3"
- />
- </div>
- <div v-else class="flex justify-center items-center h-full space-x-2">
- <BBSpin />
- <span class="text-control text-sm">{{
- $t("sql-editor.loading-databases")
- }}</span>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { useElementSize, useMounted, useClipboard } from "@vueuse/core";
-import { head } from "lodash-es";
-import {
- NTree,
- NDropdown,
- type DropdownOption,
- type TreeOption,
-} from "naive-ui";
-import { storeToRefs } from "pinia";
-import { ref, computed, nextTick, watch, h } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
-import {
- useActuatorV1Store,
- useCurrentUserV1,
- useDBSchemaV1Store,
- useDatabaseV1Store,
- useInstanceV1Store,
- useIsLoggedIn,
- pushNotification,
- useSQLEditorTabStore,
- resolveOpeningDatabaseListFromSQLEditorTabList,
- useSQLEditorTreeStore,
- idForSQLEditorTreeNodeTarget,
- useConnectionOfCurrentSQLEditorTab,
-} from "@/store";
-import type {
- ComposedDatabase,
- ComposedInstance,
- CoreSQLEditorTab,
- RichTableMetadata,
- SQLEditorTabMode,
- SQLEditorTreeNode,
- SQLEditorTreeNodeTarget,
- SQLEditorTreeNodeType,
-} from "@/types";
-import {
- ConnectableTreeNodeTypes,
- DEFAULT_SQL_EDITOR_TAB_MODE,
- ExpandableTreeNodeTypes,
- UNKNOWN_ID,
- instanceOfSQLEditorTreeNode,
- isConnectableSQLEditorTreeNode,
- languageOfEngineV1,
-} from "@/types";
-import {
- findAncestor,
- hasWorkspacePermissionV2,
- instanceV1AllowsCrossDatabaseQuery,
- instanceV1HasAlterSchema,
- instanceV1HasReadonlyMode,
- isDescendantOf,
- generateSimpleSelectAllStatement,
- tryConnectToCoreSQLEditorTab,
- emptySQLEditorConnection,
- suggestedTabTitleForSQLEditorConnection,
- extractProjectResourceName,
- extractInstanceResourceName,
-} from "@/utils";
-import { useSQLEditorContext } from "../context";
-import DatabaseHoverPanel from "./DatabaseHoverPanel.vue";
-import GroupingBar from "./GroupingBar";
-import SearchBox from "./SearchBox/index.vue";
-import useSearchHistory from "./SearchBox/useSearchHistory";
-import { Label } from "./TreeNode";
-import { fetchDatabaseSubTree } from "./common";
-import { provideHoverStateContext } from "./hover-state";
-
-type Position = {
- x: number;
- y: number;
-};
-
-type DropdownOptionWithTreeNode = DropdownOption & {
- onSelect: () => void;
-};
-
-const { t } = useI18n();
-const router = useRouter();
-const { pageMode } = storeToRefs(useActuatorV1Store());
-const treeStore = useSQLEditorTreeStore();
-const tabStore = useSQLEditorTabStore();
-const databaseStore = useDatabaseV1Store();
-const instanceStore = useInstanceV1Store();
-const dbSchemaV1Store = useDBSchemaV1Store();
-const isLoggedIn = useIsLoggedIn();
-const me = useCurrentUserV1();
-const { executeReadonly } = useExecuteSQL();
-const { selectedDatabaseSchemaByDatabaseName, events: editorEvents } =
- useSQLEditorContext();
-const searchHistory = useSearchHistory();
-const { node: hoverNode, update: updateHoverNode } = provideHoverStateContext();
-const hoverPanelPosition = ref<Position>({
- x: 0,
- y: 0,
-});
-
-const mounted = useMounted();
-const treeContainerElRef = ref<HTMLElement>();
-const { height: treeContainerHeight } = useElementSize(
- treeContainerElRef,
- undefined,
- {
- box: "content-box",
- }
-);
-const treeRef = ref<InstanceType<typeof NTree>>();
-const searchPattern = ref("");
-const showDropdown = ref(false);
-const dropdownPosition = ref<Position>({
- x: 0,
- y: 0,
-});
-const dropdownContext = ref<SQLEditorTreeNode>();
-
-const dropdownOptions = computed((): DropdownOptionWithTreeNode[] => {
- const node = dropdownContext.value;
- if (!node) {
- return [];
- }
- const { type, target } = node.meta;
- if (type === "project") {
- return [];
- } else {
- // Don't show any context menu actions for disabled
- // instances/databases
- if (node.disabled) {
- return [];
- }
-
- const items: DropdownOptionWithTreeNode[] = [];
-
- if (isConnectableSQLEditorTreeNode(node)) {
- const instance = instanceOfSQLEditorTreeNode(node);
- if (instance && instanceV1HasReadonlyMode(instance)) {
- items.push({
- key: "connect",
- label: t("sql-editor.connect"),
- onSelect: () => setConnection(node),
- });
- }
- if (allowAdmin.value) {
- items.push({
- key: "connect-in-admin-mode",
- label: t("sql-editor.connect-in-admin-mode"),
- onSelect: () => setConnection(node, { sheet: "", mode: "ADMIN" }),
- });
- }
- }
- if (pageMode.value === "BUNDLED") {
- if (type === "database") {
- const database = target as ComposedDatabase;
- if (instanceV1HasAlterSchema(database.instanceEntity)) {
- items.push({
- key: "alter-schema",
- label: t("database.edit-schema"),
- onSelect: () => {
- const db = node.meta.target as ComposedDatabase;
- editorEvents.emit("alter-schema", {
- databaseUID: db.uid,
- schema: "",
- table: "",
- });
- },
- });
- }
- } else if (type === "table") {
- const { database, schema, table } = target as RichTableMetadata;
- items.push({
- key: "copy-url",
- label: t("sql-editor.copy-url"),
- onSelect: () => {
- const { copy, copied } = useClipboard({
- source: computed(() => {
- const route = router.resolve({
- name: SQL_EDITOR_DATABASE_MODULE,
- params: {
- project: extractProjectResourceName(database.project),
- instance: extractInstanceResourceName(database.instance),
- database: database.databaseName,
- },
- query: {
- table: table.name,
- schema: schema.name,
- },
- });
- return new URL(route.href, window.location.origin).href;
- }),
- legacy: true,
- });
- copy().then(() => {
- if (copied.value) {
- pushNotification({
- module: "bytebase",
- style: "INFO",
- title: t("common.copied"),
- });
- }
- });
- },
- });
- }
- }
- return items;
- }
-});
-
-// Highlight the current tab's connection node.
-const selectedKeys = computed(() => {
- const connection = tabStore.currentTab?.connection;
- if (!connection) {
- return [];
- }
-
- if (connection.database) {
- const database = databaseStore.getDatabaseByName(connection.database);
- const node = head(treeStore.nodesByTarget("database", database));
- if (!node) return [];
- const selected = selectedDatabaseSchemaByDatabaseName.value.get(
- database.name
- );
- if (selected) {
- const { schema, table, externalTable } = selected;
- if (table) {
- const tableNode = head(
- treeStore.nodesByTarget("table", {
- database,
- schema,
- table,
- })
- );
- if (tableNode) {
- return [tableNode.key];
- }
- } else if (externalTable) {
- const externalTableNode = head(
- treeStore.nodesByTarget("external-table", {
- database,
- schema,
- externalTable,
- })
- );
- if (externalTableNode) {
- return [externalTableNode.key];
- }
- }
- }
- return [node.key];
- } else if (connection.instance) {
- const instance = instanceStore.getInstanceByName(connection.instance);
- const nodes = treeStore.nodesByTarget("instance", instance);
- return nodes.map((node) => node.key);
- }
- return [];
-});
-const expandedKeys = ref<string[]>([]);
-const upsertExpandedKeys = (key: string) => {
- if (expandedKeys.value.includes(key)) {
- return;
- }
- expandedKeys.value.push(key);
-};
-const expandNode = (
- node: SQLEditorTreeNode | undefined,
- keys?: Set<string>
-) => {
- if (!node) {
- return;
- }
- if (ExpandableTreeNodeTypes.includes(node.meta.type)) {
- if (keys) {
- keys.add(node.key);
- } else {
- upsertExpandedKeys(node.key);
- }
- }
-};
-const expandNodeRecursively = (
- node: SQLEditorTreeNode | undefined,
- keys?: Set<string>
-) => {
- if (!node) {
- return;
- }
- expandNode(node, keys);
-
- if (node.parent) {
- expandNodeRecursively(node.parent, keys);
- }
-};
-const expandNodesByType = <T extends SQLEditorTreeNodeType>(
- type: T,
- target: SQLEditorTreeNodeTarget<T>
-) => {
- const nodes = treeStore.nodesByTarget(type, target);
-
- nodes.forEach((node) => {
- expandNodeRecursively(node);
- });
-
- return nodes;
-};
-const allowAdmin = computed(() =>
- hasWorkspacePermissionV2(me.value, "bb.instances.adminExecute")
-);
-
-const setConnection = (
- node: SQLEditorTreeNode,
- extra: { sheet: string; mode: SQLEditorTabMode } = {
- sheet: "",
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- }
-) => {
- if (node) {
- const { type } = node.meta;
- if (!ConnectableTreeNodeTypes.includes(type)) {
- return;
- }
- if (type === "instance") {
- const instance = node.meta.target as ComposedInstance;
- if (!instanceV1AllowsCrossDatabaseQuery(instance)) {
- return;
- }
- }
- const coreTab: CoreSQLEditorTab = {
- connection: emptySQLEditorConnection(),
- ...extra,
- };
- const conn = coreTab.connection;
- // If selected item is instance node
- if (type === "instance") {
- const instance = node.meta.target as ComposedInstance;
- conn.instance = instance.name;
- }
- // If selected item is database node
- if (type === "database") {
- const database = node.meta.target as ComposedDatabase;
- conn.instance = database.instance;
- conn.database = database.name;
- }
- tryConnectToCoreSQLEditorTab(coreTab);
- }
-};
-
-// dynamic render the highlight keywords
-const renderLabel = ({ option }: { option: TreeOption }) => {
- const node = option as any as SQLEditorTreeNode;
- return h(Label, {
- node,
- factors: treeStore.filteredFactorList,
- keyword: searchPattern.value ?? "",
- });
-};
-
-const handleSelect = (key: string) => {
- const option = dropdownOptions.value.find((item) => item.key === key);
- if (!option) {
- return;
- }
- option.onSelect();
- showDropdown.value = false;
-};
-
-const handleClickoutside = () => {
- showDropdown.value = false;
-};
-
-const maybeSelectTable = async (node: SQLEditorTreeNode) => {
- const target = node.meta.target as SQLEditorTreeNodeTarget<"table">;
- const { database, schema, table } = target;
- if (
- !tabStore.currentTab ||
- tabStore.currentTab.connection.database !== database.name
- ) {
- const coreTab: CoreSQLEditorTab = {
- connection: {
- instance: database.instance,
- database: database.name,
- schema: schema.name,
- table: table.name,
- },
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- sheet: "",
- };
- tryConnectToCoreSQLEditorTab(coreTab);
- await nextTick();
- }
-
- const tableMetadata = await dbSchemaV1Store.getOrFetchTableMetadata({
- database: database.name,
- schema: schema.name,
- table: table.name,
- });
- const databaseMetadata = dbSchemaV1Store.getDatabaseMetadata(database.name);
-
- selectedDatabaseSchemaByDatabaseName.value.set(database.name, {
- db: database,
- database: databaseMetadata,
- schema,
- table: tableMetadata,
- });
-
- if (tabStore.currentTab) {
- tabStore.updateCurrentTab({
- connection: {
- ...tabStore.currentTab.connection,
- schema: schema.name,
- table: table.name,
- },
- });
- }
-};
-
-const maybeSelectExternalTable = async (node: SQLEditorTreeNode) => {
- const target = node.meta.target as SQLEditorTreeNodeTarget<"external-table">;
- const { database, schema, externalTable } = target;
-
- if (
- !tabStore.currentTab ||
- tabStore.currentTab.connection.database !== database.name
- ) {
- const coreTab: CoreSQLEditorTab = {
- connection: {
- instance: database.instance,
- database: database.name,
- },
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- sheet: "",
- };
- tryConnectToCoreSQLEditorTab(coreTab);
- await nextTick();
- }
-
- const databaseMetadata = dbSchemaV1Store.getDatabaseMetadata(database.name);
- selectedDatabaseSchemaByDatabaseName.value.set(database.name, {
- db: database,
- database: databaseMetadata,
- schema,
- externalTable,
- });
-};
-
-const selectAllFromTableOrView = async (node: SQLEditorTreeNode) => {
- const { type, target } = (node as SQLEditorTreeNode<"table" | "view">).meta;
- const { database } = target;
- const { engine } = database.instanceEntity;
- const LIMIT = 50; // default pagesize of SQL Editor
-
- const language = languageOfEngineV1(engine);
- if (language === "redis") {
- return; // not supported
- }
- const schema = target.schema.name;
- const tableOrViewName =
- type === "table"
- ? (target as SQLEditorTreeNodeTarget<"table">).table.name
- : type === "view"
- ? (target as SQLEditorTreeNodeTarget<"view">).view.name
- : "";
- if (!tableOrViewName) {
- return;
- }
-
- const runQuery = async (statement: string) => {
- const tab: CoreSQLEditorTab = {
- connection: {
- instance: database.instance,
- database: database.name,
- schema,
- table: tableOrViewName,
- },
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- sheet: "",
- };
- if (
- tabStore.currentTab &&
- (tabStore.currentTab.status === "NEW" || !tabStore.currentTab.sheet)
- ) {
- // If the current tab is "fresh new" or unsaved, update its connection directly.
- tabStore.updateCurrentTab({
- ...tab,
- title: suggestedTabTitleForSQLEditorConnection(tab.connection),
- status: "DIRTY",
- statement,
- });
- } else {
- // Otherwise select or add a new tab and set its connection
- tabStore.addTab(
- {
- ...tab,
- title: suggestedTabTitleForSQLEditorConnection(tab.connection),
- statement,
- status: "DIRTY",
- },
- /* beside */ true
- );
- }
- await nextTick();
- executeReadonly({
- statement,
- connection: { ...tab.connection },
- explain: false,
- engine: database.instanceEntity.engine,
- });
- };
-
- if (language === "javascript" && type === "table") {
- // mongodb
- const query = `db["${tableOrViewName}"].find().limit(${LIMIT});`;
- runQuery(query);
- return;
- }
-
- if (type === "table") {
- maybeSelectTable(node);
- }
-
- const query = generateSimpleSelectAllStatement(
- engine,
- schema,
- tableOrViewName,
- LIMIT
- );
- runQuery(query);
-};
-
-const nodeProps = ({ option }: { option: TreeOption }) => {
- const node = option as any as SQLEditorTreeNode;
- return {
- onClick(e: MouseEvent) {
- 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 (type === "instance" || type === "database") {
- setConnection(node);
- }
- if (type === "table" || type === "partition-table") {
- maybeSelectTable(node);
- }
- if (type === "external-table") {
- maybeSelectExternalTable(node);
- }
-
- // If the search pattern is not empty, append the selected database name to
- // the search history.
- if (searchPattern.value) {
- if (type === "database") {
- const database = node.meta.target as ComposedDatabase;
- searchHistory.appendSearchResult(database.name);
- }
- }
- }
- },
- onContextmenu(e: MouseEvent) {
- e.preventDefault();
- showDropdown.value = false;
- if (node && node.key) {
- dropdownContext.value = node;
- }
-
- nextTick().then(() => {
- showDropdown.value = true;
- dropdownPosition.value.x = e.clientX;
- dropdownPosition.value.y = e.clientY;
- });
- },
- onmouseenter(e: MouseEvent) {
- if (node.meta.type === "database") {
- if (hoverNode.value) {
- updateHoverNode(node, "before", 0 /* overrideDelay */);
- } else {
- updateHoverNode(node, "before");
- }
- nextTick().then(() => {
- // Find the node element and put the database panel to the right corner
- // of the node
- const wrapper = findAncestor(e.target as HTMLElement, ".n-tree-node");
- if (!wrapper) {
- updateHoverNode(undefined, "after", 0 /* overrideDelay */);
- return;
- }
- const bounding = wrapper.getBoundingClientRect();
- hoverPanelPosition.value.x = bounding.right;
- hoverPanelPosition.value.y = bounding.top;
- });
- }
- },
- onmouseleave() {
- updateHoverNode(undefined, "after");
- },
- ondblclick() {
- if (node.meta.type === "table" || node.meta.type === "view") {
- selectAllFromTableOrView(node);
- }
- },
- // attrs below for trouble-shooting
- "data-node-meta-type": node.meta.type,
- "data-node-meta-id": idForSQLEditorTreeNodeTarget(
- node.meta.type,
- node.meta.target
- ),
- "data-node-key": node.key,
- };
-};
-
-const handleLoadSubTree = (option: TreeOption) => {
- const node = option as any as SQLEditorTreeNode;
- const { type } = node.meta;
- if (type === "database") {
- const request = fetchDatabaseSubTree(node);
- request
- .then(() => nextTick())
- .then(() => {
- if ((node.children?.length ?? 0) > 0) {
- expandNode(node);
- if (expandSchemaAndTableNodes(node)) {
- // if a specified schema node is expanded we stop here
- return;
- }
- // we expand the first schema node otherwise
- expandFirstSchemaNode(node);
- }
- });
- return request;
- }
- return Promise.resolve();
-};
-
-/**
- * returns true if successfully expanded, false if not expanded
- */
-const expandSchemaAndTableNodes = (
- databaseNode: SQLEditorTreeNode<"database">
-): boolean => {
- const tab = tabStore.currentTab;
- if (!tab) {
- return false;
- }
- const { database, schema, table } = tab.connection;
- const db = databaseNode.meta.target;
- if (db.name !== database) {
- return false;
- }
- const schemaMetadata = dbSchemaV1Store.getSchemaByName(db.name, schema ?? "");
- if (!schemaMetadata) {
- return false;
- }
-
- const schemaNode = databaseNode.children?.find(
- (
- node: SQLEditorTreeNode
- ): node is
- | SQLEditorTreeNode<"schema">
- | SQLEditorTreeNode<"expandable-text"> => {
- if (node.meta.type === "schema") {
- return (
- (node.meta.target as SQLEditorTreeNodeTarget<"schema">).schema
- .name === schemaMetadata.name
- );
- }
- if (node.meta.type === "expandable-text") {
- return schemaMetadata.name === "";
- }
- return false;
- }
- );
-
- if (!schemaNode) {
- return false;
- }
- expandNode(schemaNode);
- if (schemaNode.meta.type === "schema") {
- // a schema node contains a "Tables" `expandable-text` node
- // so we should also expand the first child
- expandNode(head(schemaNode.children));
- }
-
- if (!table) {
- return true;
- }
- const tableMetadata = dbSchemaV1Store.getTableByName(db.name, table, schema);
- if (!tableMetadata) {
- return true;
- }
-
- const databaseMetadata = dbSchemaV1Store.getDatabaseMetadata(db.name);
- selectedDatabaseSchemaByDatabaseName.value.set(db.name, {
- db: db,
- database: databaseMetadata,
- schema: schemaMetadata,
- table: tableMetadata,
- });
- return true;
-};
-
-/**
- * returns true if successfully expanded, false if not expanded
- */
-const expandFirstSchemaNode = (
- databaseNode: SQLEditorTreeNode<"database">,
- keys?: Set<string>
-) => {
- const firstChild = head(databaseNode.children) as SQLEditorTreeNode;
- expandNode(firstChild);
- if (firstChild && firstChild.meta.type === "schema") {
- // a schema node contains a "Tables" `expandable-text` node
- // so we should also expand the first child
- expandNode(head(firstChild.children));
- }
-};
-
-// Open corresponding tree node when the connection changed.
-const { instance, database } = useConnectionOfCurrentSQLEditorTab();
-watch(
- [isLoggedIn, instance, database, () => treeStore.state],
- ([isLoggedIn, instance, database, treeState]) => {
- if (!isLoggedIn) {
- // Don't go further and cleanup the state if we signed out.
- // treeStore.expandedKeys = [];
- expandedKeys.value = [];
- return;
- }
-
- if (treeState !== "READY") {
- return;
- }
- if (instance.uid !== String(UNKNOWN_ID)) {
- expandNodesByType("instance", instance);
- }
- if (database.uid !== String(UNKNOWN_ID)) {
- expandNodesByType("project", database.projectEntity);
- expandNodesByType("database", database);
- }
- },
- { immediate: true }
-);
-
-watch(
- selectedKeys,
- (keys) => {
- if (keys.length !== 1) return;
- const key = keys[0];
- nextTick(() => {
- treeRef.value?.scrollTo({ key });
- });
- },
- { immediate: true }
-);
-
-useEmitteryEventListener(editorEvents, "tree-ready", async () => {
- await nextTick();
- const openingDatabaseList = resolveOpeningDatabaseListFromSQLEditorTabList();
- const keys = new Set<string>();
- // Recursively expand opening databases' parent nodes
- openingDatabaseList.forEach((meta) => {
- const db = meta.target;
- const nodes = treeStore.nodesByTarget("database", db);
- nodes.forEach((node) => expandNodeRecursively(node.parent, keys));
- });
- const tab = tabStore.currentTab;
- // Expand current tab's connected database node
- if (tab && tab.connection.database) {
- const db = useDatabaseV1Store().getDatabaseByName(tab.connection.database);
- const node = head(treeStore.nodesByTarget("database", db));
- if (node) {
- keys.add(node.key);
- }
- }
- expandedKeys.value = Array.from(keys);
-});
-</script>
-
-<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;
-}
-.sql-editor-tree :deep(.n-tree-node-wrapper) {
- padding: 0;
-}
-.sql-editor-tree :deep(.n-tree-node-indent) {
- width: 0.25rem;
-}
-.sql-editor-tree :deep(.n-tree-node-content__prefix) {
- @apply shrink-0 !mr-1;
-}
-.sql-editor-tree.project
- :deep(.n-tree-node[data-node-type="project"] .n-tree-node-content__prefix) {
- @apply hidden;
-}
-.sql-editor-tree :deep(.n-tree-node-content__text) {
- @apply truncate mr-1;
-}
-.sql-editor-tree :deep(.n-tree-node--pending) {
- background-color: transparent !important;
-}
-.sql-editor-tree :deep(.n-tree-node--pending:hover) {
- background-color: var(--n-node-color-hover) !important;
-}
-.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;
- font-weight: 500;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue b/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue
new file mode 100644
index 0000000000..8763be6869
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue
@@ -0,0 +1,84 @@
+<template>
+ <div class="h-full flex flex-col items-stretch justify-between text-sm pb-1">
+ <div class="divide-y border-b">
+ <TabItem tab="CONNECTION" @click="handleClickTab('CONNECTION')" />
+ <TabItem tab="WORKSHEET" @click="handleClickTab('WORKSHEET')" />
+ <TabItem
+ tab="SCHEMA"
+ :disabled="!showSchemaPane"
+ @click="handleClickTab('SCHEMA')"
+ />
+ <TabItem tab="HISTORY" @click="handleClickTab('HISTORY')" />
+ </div>
+
+ <OpenAIButton class="self-center" />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { storeToRefs } from "pinia";
+import { computed, watch } from "vue";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useCurrentUserV1,
+ useSQLEditorTabStore,
+} from "@/store";
+import { UNKNOWN_ID } from "@/types";
+import { hasProjectPermissionV2, instanceV1HasAlterSchema } from "@/utils";
+import { useSQLEditorContext, type AsidePanelTab } from "../../context";
+import OpenAIButton from "../OpenAIButton.vue";
+import TabItem from "./TabItem.vue";
+
+const me = useCurrentUserV1();
+const { currentTab, isDisconnected } = storeToRefs(useSQLEditorTabStore());
+const { asidePanelTab } = useSQLEditorContext();
+const { instance, database } = useConnectionOfCurrentSQLEditorTab();
+
+const isSchemalessInstance = computed(() => {
+ if (instance.value.uid === String(UNKNOWN_ID)) {
+ return false;
+ }
+
+ return !instanceV1HasAlterSchema(instance.value);
+});
+
+const showSchemaPane = computed(() => {
+ if (!currentTab.value) {
+ return false;
+ }
+ if (isDisconnected.value) {
+ return false;
+ }
+
+ if (isSchemalessInstance.value) {
+ return false;
+ }
+ if (database.value.uid === String(UNKNOWN_ID)) {
+ return false;
+ }
+
+ return hasProjectPermissionV2(
+ database.value.projectEntity,
+ me.value,
+ "bb.databases.getSchema"
+ );
+});
+
+const handleClickTab = (target: AsidePanelTab) => {
+ if (target === "SCHEMA" && !showSchemaPane.value) {
+ return;
+ }
+
+ asidePanelTab.value = target;
+};
+
+watch(
+ showSchemaPane,
+ (show) => {
+ if (!show && asidePanelTab.value === "SCHEMA") {
+ asidePanelTab.value = "WORKSHEET";
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue b/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue
new file mode 100644
index 0000000000..c3d3809143
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue
@@ -0,0 +1,63 @@
+<template>
+ <NTooltip placement="right" :delay="300" :disabled="disabled">
+ <template #trigger>
+ <div class="px-2 py-3 select-none" :class="classes" v-bind="$attrs">
+ <LinkIcon v-if="tab === 'CONNECTION'" class="w-4 h-4" />
+ <FileCodeIcon v-else-if="tab === 'WORKSHEET'" class="w-4 h-4" />
+ <DatabaseIcon v-else-if="tab === 'SCHEMA'" class="w-4 h-4" />
+ <HistoryIcon v-else-if="tab === 'HISTORY'" class="w-4 h-4" />
+ <span v-else></span>
+ </div>
+ </template>
+ <template #default>
+ {{ text }}
+ </template>
+ </NTooltip>
+</template>
+
+<script setup lang="ts">
+import { LinkIcon, FileCodeIcon, HistoryIcon } from "lucide-vue-next";
+import { NTooltip } from "naive-ui";
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import DatabaseIcon from "@/components/Icon/DatabaseIcon.vue";
+import { useSQLEditorContext, type AsidePanelTab } from "../../context";
+
+const props = defineProps<{
+ tab: AsidePanelTab;
+ disabled?: boolean;
+}>();
+
+const { t } = useI18n();
+const { asidePanelTab } = useSQLEditorContext();
+
+const classes = computed(() => {
+ const classes: string[] = [];
+ if (props.disabled) {
+ classes.push("text-main/30 bg-gray-100/30 cursor-not-allowed");
+ } else {
+ classes.push("cursor-pointer");
+ if (props.tab === asidePanelTab.value) {
+ classes.push("bg-accent/10");
+ } else {
+ classes.push("bg-white");
+ }
+ }
+ return classes;
+});
+
+const text = computed(() => {
+ switch (props.tab) {
+ case "CONNECTION":
+ return t("common.connection");
+ case "WORKSHEET":
+ return t("sheet.sheet");
+ case "SCHEMA":
+ return t("common.schema");
+ case "HISTORY":
+ return t("common.history");
+ }
+ console.assert(false, "should never reach this line");
+ return "";
+});
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/GutterBar/index.ts b/frontend/src/views/sql-editor/AsidePanel/GutterBar/index.ts
new file mode 100644
index 0000000000..840d765ac2
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/GutterBar/index.ts
@@ -0,0 +1,3 @@
+import GutterBar from "./GutterBar.vue";
+
+export default GutterBar;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryConnectionIcon.vue b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryConnectionIcon.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryConnectionIcon.vue
rename to frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryConnectionIcon.vue
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
similarity index 91%
rename from frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue
rename to frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
index bdfdb4d00e..3970fd55c9 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/HistoryTabPane.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/HistoryPane.vue
@@ -1,18 +1,13 @@
<!-- eslint-disable vue/no-v-html -->
<template>
- <div
- class="relative py-0.5 w-full h-full flex flex-col justify-start items-start"
- >
- <div class="w-full px-2 pt-1.5">
- <NInput
+ <div class="relative w-full h-full flex flex-col justify-start items-start">
+ <div class="w-full px-1">
+ <SearchBox
v-model:value="state.search"
size="small"
:placeholder="$t('sql-editor.search-history')"
- >
- <template #prefix>
- <heroicons-outline:search class="h-5 w-5 text-gray-300" />
- </template>
- </NInput>
+ style="max-width: 100%"
+ />
</div>
<div class="w-full flex flex-col justify-start items-start overflow-y-auto">
<div
@@ -51,12 +46,10 @@
{{ notifyMessage }}
</div>
- <div
+ <MaskSpinner
v-show="isFetching && queryHistoryList.length === 0"
- class="absolute w-full h-full flex justify-center items-center"
- >
- <BBSpin :title="$t('common.loading')" />
- </div>
+ class="!bg-white/75"
+ />
</div>
</template>
@@ -67,6 +60,8 @@ import { escape } from "lodash-es";
import { storeToRefs } from "pinia";
import { computed, onMounted, reactive } from "vue";
import { useI18n } from "vue-i18n";
+import MaskSpinner from "@/components/misc/MaskSpinner.vue";
+import { SearchBox } from "@/components/v2";
import {
pushNotification,
useSQLEditorQueryHistoryStore,
diff --git a/frontend/src/views/sql-editor/AsidePanel/HistoryPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/index.ts
new file mode 100644
index 0000000000..5414a30964
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/HistoryPane/index.ts
@@ -0,0 +1,3 @@
+import HistoryPane from "./HistoryPane.vue";
+
+export default HistoryPane;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue b/frontend/src/views/sql-editor/AsidePanel/OpenAIButton.vue
similarity index 98%
rename from frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue
rename to frontend/src/views/sql-editor/AsidePanel/OpenAIButton.vue
index e4fe9c8516..fb81674d81 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/OpenAIButton.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/OpenAIButton.vue
@@ -38,7 +38,7 @@ import type { ButtonProps } from "naive-ui";
import { NButton, NTooltip } from "naive-ui";
import { computed } from "vue";
import { useSettingV1Store, useSQLEditorTabStore } from "@/store";
-import { useSQLEditorContext } from "../../context";
+import { useSQLEditorContext } from "../context";
const tabStore = useSQLEditorTabStore();
const settingV1Store = useSettingV1Store();
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ColumnInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ColumnInfo.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ColumnInfo.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ColumnInfo.vue
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ExternalTableInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ExternalTableInfo.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ExternalTableInfo.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ExternalTableInfo.vue
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/HoverPanel.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue
similarity index 79%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/HoverPanel.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue
index da4fd46587..9ea0c6a2d0 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/HoverPanel.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue
@@ -5,8 +5,8 @@
class="fixed border border-gray-100 rounded bg-white p-2 shadow transition-[top] text-sm"
:class="[show ? 'visible' : ' invisible pointer-events-none']"
:style="{
- left: `${position.x - popoverWidth + offsetX}px`,
- top: `${position.y + offsetY}px`,
+ left: `${displayPosition.x}px`,
+ top: `${displayPosition.y}px`,
}"
>
<template v-if="state">
@@ -46,15 +46,18 @@
import { onClickOutside, useElementSize, useEventListener } from "@vueuse/core";
import { zindexable as vZindexable } from "vdirs";
import { computed, ref } from "vue";
+import type { Position } from "@/types";
+import { minmax } from "@/utils";
import ColumnInfo from "./ColumnInfo.vue";
import ExternalTableInfo from "./ExternalTableInfo.vue";
import TableInfo from "./TableInfo.vue";
import ViewInfo from "./ViewInfo.vue";
import { useHoverStateContext } from "./hover-state";
-defineProps<{
+const props = defineProps<{
offsetX: number;
offsetY: number;
+ margin: number;
}>();
const emit = defineEmits<{
@@ -67,7 +70,7 @@ const popoverRef = ref<HTMLDivElement>();
onClickOutside(popoverRef, (e) => {
emit("click-outside", e);
});
-const { width: popoverWidth } = useElementSize(popoverRef, undefined, {
+const { height: popoverHeight } = useElementSize(popoverRef, undefined, {
box: "border-box",
});
@@ -78,6 +81,18 @@ const show = computed(
position.value.y !== 0
);
+const displayPosition = computed(() => {
+ const p: Position = {
+ x: position.value.x + props.offsetX,
+ y: position.value.y + props.offsetY,
+ };
+ const yMin = props.margin;
+ const yMax = window.innerHeight - popoverHeight.value - props.margin;
+ p.y = minmax(p.y, yMin, yMax);
+
+ return p;
+});
+
useEventListener(popoverRef, "mouseenter", () => {
// Reset the value immediately to cancel other pending setting values
update(state.value, "before", 0 /* overrideDelay */);
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/InfoItem.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/InfoItem.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/InfoItem.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/InfoItem.vue
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/TableInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TableInfo.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/TableInfo.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TableInfo.vue
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ViewInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ViewInfo.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/ViewInfo.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ViewInfo.vue
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts
new file mode 100644
index 0000000000..855d48091a
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts
@@ -0,0 +1,33 @@
+import type { ComposedDatabase } from "@/types";
+import type {
+ ColumnMetadata,
+ DatabaseMetadata,
+ ExternalTableMetadata,
+ SchemaMetadata,
+ TableMetadata,
+ ViewMetadata,
+} from "@/types/proto/v1/database_service";
+import {
+ useHoverStateContext as _useHoverStateContext,
+ provideHoverStateContext as _provideHoverStateContext,
+} from "../../hover-state";
+
+export const KEY = "schema-pane";
+
+export type HoverState = {
+ db: ComposedDatabase;
+ database: DatabaseMetadata;
+ schema: SchemaMetadata;
+ table?: TableMetadata;
+ externalTable?: ExternalTableMetadata;
+ view?: ViewMetadata;
+ column?: ColumnMetadata;
+};
+
+export const useHoverStateContext = () => {
+ return _useHoverStateContext<HoverState>(KEY);
+};
+
+export const provideHoverStateContext = () => {
+ return _provideHoverStateContext<HoverState>(KEY);
+};
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/index.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/index.ts
similarity index 99%
rename from frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/index.ts
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/index.ts
index fc94dc1e7c..05d40406b8 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/index.ts
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/index.ts
@@ -1,5 +1,6 @@
import HoverPanel from "./HoverPanel.vue";
-export default HoverPanel;
export * from "./hover-state";
+
export { HoverPanel };
+export default HoverPanel;
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
new file mode 100644
index 0000000000..444c5be5f6
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
@@ -0,0 +1,291 @@
+<template>
+ <div class="gap-y-1 h-full flex flex-col relative">
+ <div class="px-1">
+ <SearchBox
+ v-model:value="searchPattern"
+ size="small"
+ style="width: 100%; max-width: 100%"
+ />
+ </div>
+
+ <div
+ ref="treeContainerElRef"
+ class="schema-tree flex-1 px-1 pb-1 text-sm overflow-hidden select-none"
+ :data-height="treeContainerHeight"
+ >
+ <NTree
+ v-if="tree"
+ ref="treeRef"
+ :default-expanded-keys="defaultExpandedKeys"
+ :selected-keys="selectedKeys"
+ :block-line="true"
+ :data="tree"
+ :show-irrelevant-nodes="false"
+ :pattern="mounted ? searchPattern : ''"
+ :expand-on-click="true"
+ :virtual-scroll="true"
+ :node-props="nodeProps"
+ :theme-overrides="{ nodeHeight: '21px' }"
+ :render-label="renderLabel"
+ />
+ </div>
+
+ <NDropdown
+ v-if="!isFetchingMetadata"
+ placement="bottom-start"
+ trigger="manual"
+ :x="dropdownPosition.x"
+ :y="dropdownPosition.y"
+ :options="dropdownOptions"
+ :show="showDropdown"
+ :on-clickoutside="handleDropdownClickoutside"
+ @select="handleDropdownSelect"
+ />
+
+ <MaskSpinner v-if="isFetchingMetadata" class="!bg-white/75" />
+
+ <HoverPanel :offset-x="4" :offset-y="0" :margin="4" />
+
+ <BBModal :show="!!schemaViewer" @close="schemaViewer = undefined">
+ <template v-if="schemaViewer" #title>
+ <RichDatabaseName :database="schemaViewer.database" />
+ </template>
+ <TableSchemaViewer
+ v-if="schemaViewer"
+ style="width: calc(100vw - 12rem); height: calc(100vh - 12rem)"
+ v-bind="schemaViewer"
+ />
+ </BBModal>
+ </div>
+</template>
+
+<script setup lang="tsx">
+import { computedAsync, useElementSize, useMounted } from "@vueuse/core";
+import { NDropdown, type TreeOption } from "naive-ui";
+import { storeToRefs } from "pinia";
+import { computed, nextTick, ref, watch } from "vue";
+import { BBModal } from "@/bbkit";
+import TableSchemaViewer from "@/components/TableSchemaViewer.vue";
+import MaskSpinner from "@/components/misc/MaskSpinner.vue";
+import { RichDatabaseName, SearchBox } from "@/components/v2";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDBSchemaV1Store,
+ useSQLEditorTabStore,
+} from "@/store";
+import { UNKNOWN_ID } from "@/types";
+import { DatabaseMetadataView } from "@/types/proto/v1/database_service";
+import { findAncestor, isDescendantOf } from "@/utils";
+import { useSQLEditorContext } from "../../context";
+import { provideHoverStateContext } from "./HoverPanel";
+import HoverPanel from "./HoverPanel";
+import { Label } from "./TreeNode";
+import { selectAllFromTableOrView, useDropdown } from "./actions";
+import {
+ type NodeTarget,
+ type TreeNode,
+ buildDatabaseSchemaTree,
+} from "./common";
+
+const mounted = useMounted();
+const treeContainerElRef = ref<HTMLElement>();
+const { height: treeContainerHeight } = useElementSize(
+ treeContainerElRef,
+ undefined,
+ {
+ box: "content-box",
+ }
+);
+const searchPattern = ref("");
+const { schemaViewer } = useSQLEditorContext();
+const {
+ state: hoverState,
+ position: hoverPosition,
+ update: updateHoverState,
+} = provideHoverStateContext();
+const {
+ show: showDropdown,
+ context: dropdownContext,
+ position: dropdownPosition,
+ options: dropdownOptions,
+ handleSelect: handleDropdownSelect,
+ handleClickoutside: handleDropdownClickoutside,
+} = useDropdown();
+const { currentTab } = storeToRefs(useSQLEditorTabStore());
+const { connection, database } = useConnectionOfCurrentSQLEditorTab();
+const isFetchingMetadata = ref(false);
+const metadata = computedAsync(
+ async () => {
+ const db = database.value;
+ if (db.uid === String(UNKNOWN_ID)) return null;
+ const metadata = await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
+ database: db.name,
+ view: DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL,
+ });
+ return metadata;
+ },
+ /* default */ null,
+ {
+ evaluating: isFetchingMetadata,
+ }
+);
+const tree = computed(() => {
+ if (isFetchingMetadata.value) return null;
+ if (!metadata.value) return null;
+ return [buildDatabaseSchemaTree(database.value, metadata.value)];
+});
+const defaultExpandedKeys = computed(() => {
+ if (!tree.value) return [];
+ const keys: string[] = [];
+ const collect = (node: TreeNode) => {
+ keys.push(node.key);
+ node.children?.forEach((child) => walk(child as TreeNode));
+ };
+ const walk = (node: TreeNode) => {
+ const { type } = node.meta;
+ if (type === "database" || type === "schema") {
+ collect(node);
+ } else if (type === "expandable-text") {
+ const { mockType } = node.meta.target as NodeTarget<"expandable-text">;
+ if (mockType === "table" || mockType === "view") {
+ collect(node);
+ }
+ }
+ };
+ walk(tree.value[0]);
+ return keys;
+});
+const nodeProps = ({ option }: { option: TreeOption }) => {
+ const node = option as any as TreeNode;
+ return {
+ onClick(e: MouseEvent) {
+ if (node.disabled) return;
+
+ if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {
+ const { type, target } = node.meta;
+ // Check if clicked on the content part.
+ // And ignore the fold/unfold arrow.
+ const tab = currentTab.value;
+ if (tab) {
+ if (type === "table" || type === "column") {
+ if ("table" in target) {
+ const { schema, table } = target as NodeTarget<"table">;
+ tab.connection.schema = schema.name;
+ tab.connection.table = table.name;
+ }
+ }
+ }
+ }
+ },
+ ondblclick() {
+ if (node.meta.type === "table" || node.meta.type === "view") {
+ selectAllFromTableOrView(node);
+ }
+ },
+ onmouseenter(e: MouseEvent) {
+ const { type } = node.meta;
+ if (
+ type === "table" ||
+ type === "external-table" ||
+ type === "column" ||
+ type === "view"
+ ) {
+ const target = node.meta.target as NodeTarget<
+ "table" | "external-table" | "column" | "view"
+ >;
+ if (hoverState.value) {
+ updateHoverState(target, "before", 0 /* overrideDelay */);
+ } else {
+ updateHoverState(target, "before");
+ }
+ nextTick().then(() => {
+ // Find the node element and put the database panel to the right corner
+ // of the node
+ const wrapper = findAncestor(e.target as HTMLElement, ".n-tree-node");
+ if (!wrapper) {
+ updateHoverState(undefined, "after", 0 /* overrideDelay */);
+ return;
+ }
+ const bounding = wrapper.getBoundingClientRect();
+ hoverPosition.value.x = bounding.right;
+ hoverPosition.value.y = bounding.top;
+ });
+ }
+ },
+ onmouseleave() {
+ updateHoverState(undefined, "after");
+ },
+ oncontextmenu(e: MouseEvent) {
+ e.preventDefault();
+ showDropdown.value = false;
+ if (node && node.key) {
+ dropdownContext.value = node;
+ }
+
+ nextTick().then(() => {
+ showDropdown.value = true;
+ dropdownPosition.value.x = e.clientX;
+ dropdownPosition.value.y = e.clientY;
+ });
+ },
+ // attrs below for trouble-shooting
+ "data-node-meta-type": node.meta.type,
+ "data-node-key": node.key,
+ };
+};
+
+// dynamic render the highlight keywords
+const renderLabel = ({ option }: { option: TreeOption }) => {
+ const node = option as any as TreeNode;
+ return <Label node={node} keyword={searchPattern.value} />;
+};
+
+const selectedKeys = computed(() => {
+ const db = database.value;
+ if (db.uid === String(UNKNOWN_ID)) return [];
+ const { schema, table } = connection.value;
+ if (!table) return [];
+ return [`${db.name}/schemas/${schema}/tables/${table}`];
+});
+
+watch(tree, () => {
+ showDropdown.value = false;
+ dropdownContext.value = undefined;
+});
+</script>
+
+<style lang="postcss" scoped>
+.schema-tree :deep(.n-tree .v-vl) {
+ --n-node-content-height: 21px !important;
+}
+.schema-tree :deep(.n-tree-node-content) {
+ @apply !pl-0 text-sm;
+}
+.schema-tree :deep(.n-tree-node-wrapper) {
+ padding: 0;
+}
+.schema-tree :deep(.n-tree-node-indent) {
+ width: 0.5rem;
+}
+.schema-tree :deep(.n-tree-node-content__prefix) {
+ @apply shrink-0 !mr-1;
+}
+.schema-tree.project
+ :deep(.n-tree-node[data-node-type="project"] .n-tree-node-content__prefix) {
+ @apply hidden;
+}
+.schema-tree :deep(.n-tree-node-content__text) {
+ @apply truncate mr-1;
+}
+.schema-tree :deep(.n-tree-node--pending) {
+ background-color: transparent !important;
+}
+.schema-tree :deep(.n-tree-node--pending:hover) {
+ background-color: var(--n-node-color-hover) !important;
+}
+.schema-tree :deep(.n-tree-node--selected),
+.schema-tree :deep(.n-tree-node--selected:hover) {
+ background-color: var(--n-node-color-active) !important;
+ font-weight: 500;
+}
+</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ColumnNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ColumnNode.vue
new file mode 100644
index 0000000000..e048705507
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ColumnNode.vue
@@ -0,0 +1,22 @@
+<template>
+ <div class="flex items-center max-w-full overflow-hidden gap-x-1">
+ <HighlightLabelText
+ :text="target.column.name"
+ :keyword="keyword"
+ class="flex-1 truncate"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import type { TreeNode } from "../common";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ keyword: string;
+}>();
+
+const target = computed(() => (props.node as TreeNode<"column">).meta.target);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DatabaseNode.vue
new file mode 100644
index 0000000000..3868e15213
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DatabaseNode.vue
@@ -0,0 +1,25 @@
+<template>
+ <div class="flex items-center max-w-full overflow-hidden gap-x-1">
+ <InstanceV1EngineIcon :instance="database.instanceEntity" />
+
+ <span class="flex-1 truncate">
+ <HighlightLabelText :text="database.databaseName" :keyword="keyword" />
+ </span>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { InstanceV1EngineIcon } from "@/components/v2";
+import type { TreeNode } from "../common";
+import HighlightLabelText from "./HighlightLabelText.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ keyword: string;
+}>();
+
+const database = computed(
+ () => (props.node as TreeNode<"database">).meta.target.db
+);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DummyNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DummyNode.vue
similarity index 79%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/DummyNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DummyNode.vue
index a2f6540698..2466c90521 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/DummyNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DummyNode.vue
@@ -15,21 +15,17 @@
import { NPopover } from "naive-ui";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import type { TreeNode } from "../common";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
const { t } = useI18n();
const error = computed(() => {
- return (props.node as TreeNode<"dummy">).meta.target.error;
+ return (props.node as TreeNode<"error">).meta.target.error;
});
const text = computed(() => {
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/ExternalTableNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ExternalTableNode.vue
similarity index 83%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/ExternalTableNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ExternalTableNode.vue
index cc67212fee..529af8a707 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/ExternalTableNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ExternalTableNode.vue
@@ -12,15 +12,11 @@
<script setup lang="ts">
import { computed } from "vue";
import { TableIcon } from "@/components/Icon";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import type { TreeNode } from "../common";
import HighlightLabelText from "./HighlightLabelText.vue";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/HighlightLabelText.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/HighlightLabelText.vue
new file mode 100644
index 0000000000..31fb8fa6af
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/HighlightLabelText.vue
@@ -0,0 +1,24 @@
+<template>
+ <span v-if="!keyword.trim()" v-bind="$attrs">{{ text }}</span>
+ <!-- eslint-disable-next-line vue/no-v-html -->
+ <span v-else v-bind="$attrs" 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/SchemaPane/TreeNode/Label.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/Label.vue
new file mode 100644
index 0000000000..34f8eac90b
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/Label.vue
@@ -0,0 +1,50 @@
+<template>
+ <template v-if="type === 'database'">
+ <DatabaseNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'schema'">
+ <SchemaNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'table'">
+ <TableNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'external-table'">
+ <ExternalTableNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'column'">
+ <ColumnNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'partition-table'">
+ <PartitionTableNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'view'">
+ <ViewNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'expandable-text'">
+ <TextNode :node="node" :keyword="keyword" />
+ </template>
+ <template v-if="type === 'error'">
+ <DummyNode :node="node" :keyword="keyword" />
+ </template>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import type { TreeNode } from "../common";
+import ColumnNode from "./ColumnNode.vue";
+import DatabaseNode from "./DatabaseNode.vue";
+import DummyNode from "./DummyNode.vue";
+import ExternalTableNode from "./ExternalTableNode.vue";
+import PartitionTableNode from "./PartitionTableNode.vue";
+import SchemaNode from "./SchemaNode.vue";
+import TableNode from "./TableNode.vue";
+import TextNode from "./TextNode.vue";
+import ViewNode from "./ViewNode.vue";
+
+const props = defineProps<{
+ node: TreeNode;
+ keyword: string;
+}>();
+
+const type = computed(() => props.node.meta.type);
+</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/PartitionTableNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PartitionTableNode.vue
similarity index 83%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/PartitionTableNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PartitionTableNode.vue
index d747002cad..771f1e43cf 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/PartitionTableNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PartitionTableNode.vue
@@ -12,15 +12,11 @@
<script setup lang="ts">
import { computed } from "vue";
import { TableIcon } from "@/components/Icon";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import type { TreeNode } from "../common";
import HighlightLabelText from "./HighlightLabelText.vue";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/SchemaNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SchemaNode.vue
similarity index 73%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/SchemaNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SchemaNode.vue
index f20045e1fe..0403d8f234 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/SchemaNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SchemaNode.vue
@@ -11,16 +11,12 @@
<script setup lang="ts">
import { computed } from "vue";
-import SchemaIcon from "~icons/heroicons-outline/view-columns";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import { SchemaIcon } from "@/components/Icon";
+import type { TreeNode } from "../common";
import HighlightLabelText from "./HighlightLabelText.vue";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/TableNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TableNode.vue
similarity index 82%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/TableNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TableNode.vue
index f27f888132..d1fb623535 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/TableNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TableNode.vue
@@ -12,15 +12,11 @@
<script setup lang="ts">
import { computed } from "vue";
import { TableIcon } from "@/components/Icon";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import type { TreeNode } from "../common";
import HighlightLabelText from "./HighlightLabelText.vue";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/TextNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TextNode.vue
similarity index 80%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/TextNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TextNode.vue
index 51283b9566..93c15471c0 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/TextNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TextNode.vue
@@ -1,5 +1,8 @@
<template>
- <div class="flex flex-row items-center gap-x-1">
+ <div
+ class="flex flex-row items-center gap-x-1"
+ :data-mock-type="target.mockType"
+ >
<TableIcon
v-if="type === 'table' || type === 'external-table'"
class="w-4"
@@ -14,14 +17,10 @@
import { isFunction } from "lodash-es";
import { computed } from "vue";
import { TableIcon, ViewIcon } from "@/components/Icon";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import type { TreeNode } from "../common";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
@@ -30,7 +29,7 @@ const target = computed(() => {
});
const type = computed(() => {
- return target.value.type;
+ return target.value.mockType;
});
const text = computed(() => {
const { text } = target.value;
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/ViewNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ViewNode.vue
similarity index 82%
rename from frontend/src/views/sql-editor/AsidePanel/TreeNode/ViewNode.vue
rename to frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ViewNode.vue
index 7e75de292f..c7dae4fa23 100644
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/ViewNode.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ViewNode.vue
@@ -12,15 +12,11 @@
<script setup lang="ts">
import { computed } from "vue";
import { ViewIcon } from "@/components/Icon";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
+import type { TreeNode } from "../common";
import HighlightLabelText from "./HighlightLabelText.vue";
const props = defineProps<{
node: TreeNode;
- factors: Factor[];
keyword: string;
}>();
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/index.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/index.ts
new file mode 100644
index 0000000000..448927e184
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/index.ts
@@ -0,0 +1,3 @@
+import Label from "./Label.vue";
+
+export { Label };
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
new file mode 100644
index 0000000000..3ccdce6ce8
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
@@ -0,0 +1,333 @@
+import {
+ CodeIcon,
+ CopyIcon,
+ ExternalLinkIcon,
+ LinkIcon,
+ SquarePenIcon,
+} from "lucide-vue-next";
+import type { DropdownOption } from "naive-ui";
+import { computed, nextTick, ref } from "vue";
+import { useRouter } from "vue-router";
+import TableIcon from "@/components/Icon/TableIcon.vue";
+import { useExecuteSQL } from "@/composables/useExecuteSQL";
+import { t } from "@/plugins/i18n";
+import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
+import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
+import { pushNotification, usePageMode, useSQLEditorTabStore } from "@/store";
+import {
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ type ComposedDatabase,
+ type CoreSQLEditorTab,
+ type Position,
+} from "@/types";
+import { Engine } from "@/types/proto/v1/common";
+import {
+ extractInstanceResourceName,
+ extractProjectResourceName,
+ generateSimpleSelectAllStatement,
+ instanceV1HasAlterSchema,
+ sortByDictionary,
+ suggestedTabTitleForSQLEditorConnection,
+ toClipboard,
+} from "@/utils";
+import { useSQLEditorContext } from "../../context";
+import type { NodeTarget, TreeNode } from "./common";
+
+type DropdownOptionWithTreeNode = DropdownOption & {
+ onSelect: () => void;
+};
+const SELECT_ALL_LIMIT = 50; // default pagesize of SQL Editor
+
+export const useDropdown = () => {
+ const router = useRouter();
+ const { events: editorEvents, schemaViewer } = useSQLEditorContext();
+ const pageMode = usePageMode();
+
+ const show = ref(false);
+ const position = ref<Position>({
+ x: 0,
+ y: 0,
+ });
+ const context = ref<TreeNode>();
+
+ const options = computed((): DropdownOptionWithTreeNode[] => {
+ const node = context.value;
+ if (!node) {
+ return [];
+ }
+ const { type, target } = node.meta;
+
+ // Don't show any context menu actions for disabled nodes
+ if (node.disabled) {
+ return [];
+ }
+
+ const items: DropdownOptionWithTreeNode[] = [];
+ if (type === "table" || type === "view") {
+ const schema = (target as NodeTarget<"table" | "view">).schema.name;
+ const tableOrView = tableOrViewNameForNode(node);
+ items.push({
+ key: "copy-name",
+ label: t("sql-editor.copy-name"),
+ icon: () => <CopyIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const name = schema ? `${schema}.${tableOrView}` : tableOrView;
+ copyToClipboard(name);
+ },
+ });
+ if (type === "table") {
+ const { db, schema, table } = target as NodeTarget<"table">;
+ items.push({
+ key: "copy-url",
+ label: t("sql-editor.copy-url"),
+ icon: () => <LinkIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const route = router.resolve({
+ name: SQL_EDITOR_DATABASE_MODULE,
+ params: {
+ project: extractProjectResourceName(db.project),
+ instance: extractInstanceResourceName(db.instance),
+ database: db.databaseName,
+ },
+ query: {
+ table: table.name,
+ schema: schema.name,
+ },
+ });
+ const url = new URL(route.href, window.location.origin).href;
+ copyToClipboard(url);
+ },
+ });
+
+ items.push({
+ key: "copy-all-column-names",
+ label: t("sql-editor.copy-all-column-names"),
+ icon: () => <CopyIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const names = table.columns.map((col) => col.name).join(", ");
+ copyToClipboard(names);
+ },
+ });
+
+ items.push({
+ key: "view-schema-text",
+ label: t("sql-editor.view-schema-text"),
+ icon: () => <CodeIcon class="w-4 h-4" />,
+ onSelect: () => {
+ schemaViewer.value = {
+ database: db,
+ schema: schema.name,
+ table: table.name,
+ };
+ },
+ });
+ }
+ if (targetSupportsSelectAll(target)) {
+ items.push({
+ key: "copy-select-statement",
+ label: t("sql-editor.copy-select-statement"),
+ icon: () => <CopyIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const statement = generateSimpleSelectAllStatement(
+ engineForTarget(target),
+ schema,
+ tableOrView,
+ SELECT_ALL_LIMIT
+ );
+ copyToClipboard(statement);
+ },
+ });
+ items.push({
+ key: "preview-table-data",
+ label: t("sql-editor.preview-table-data"),
+ icon: () => <TableIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const statement = generateSimpleSelectAllStatement(
+ engineForTarget(target),
+ schema,
+ tableOrView,
+ SELECT_ALL_LIMIT
+ );
+ runQuery(
+ (target as NodeTarget<"database">).db,
+ schema,
+ tableOrView,
+ statement
+ );
+ },
+ });
+ }
+ if (type === "table" && pageMode.value === "BUNDLED") {
+ const { db, schema, table } = target as NodeTarget<"table">;
+ items.push({
+ key: "view-table-detail",
+ label: t("sql-editor.view-table-detail"),
+ icon: () => <ExternalLinkIcon class="w-4 h-4" />,
+ onSelect: () => {
+ const route = router.resolve({
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(db.project),
+ instanceId: extractInstanceResourceName(db.instance),
+ databaseName: db.databaseName,
+ },
+ query: {
+ schema: schema.name ? schema.name : undefined,
+ table: table.name,
+ },
+ });
+ const url = route.href;
+ window.open(url, "_blank");
+ },
+ });
+
+ if (instanceV1HasAlterSchema(db.instanceEntity)) {
+ items.push({
+ key: "edit-schema",
+ label: t("database.edit-schema"),
+ icon: () => <SquarePenIcon class="w-4 h-4" />,
+ onSelect: () => {
+ editorEvents.emit("alter-schema", {
+ databaseUID: db.uid,
+ schema: schema.name,
+ table: table.name,
+ });
+ },
+ });
+ }
+ }
+ }
+ const ORDERS = [
+ "copy-name",
+ "copy-all-column-names",
+ "copy-select-statement",
+ "preview-table-data",
+ "view-schema-text",
+ "view-table-detail",
+ "edit-schema",
+ "copy-url",
+ ];
+ sortByDictionary(items, ORDERS, (item) => item.key as string);
+ return items;
+ });
+
+ const handleSelect = (key: string) => {
+ const option = options.value.find((item) => item.key === key);
+ if (!option) {
+ return;
+ }
+ option.onSelect();
+ show.value = false;
+ };
+
+ const handleClickoutside = () => {
+ show.value = false;
+ };
+
+ return { show, position, context, options, handleSelect, handleClickoutside };
+};
+
+const tableOrViewNameForNode = (node: TreeNode) => {
+ const { type, target } = node.meta;
+ return type === "table"
+ ? (target as NodeTarget<"table">).table.name
+ : type === "view"
+ ? (target as NodeTarget<"view">).view.name
+ : "";
+};
+
+const engineForTarget = (target: NodeTarget) => {
+ return (target as NodeTarget<"database">).db.instanceEntity.engine;
+};
+
+const targetSupportsSelectAll = (target: NodeTarget) => {
+ const engine = engineForTarget(target);
+ if (engine === Engine.REDIS) {
+ return false;
+ }
+ return true;
+};
+
+const copyToClipboard = (content: string) => {
+ toClipboard(content).then(() => {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.copied"),
+ });
+ });
+};
+
+const runQuery = async (
+ database: ComposedDatabase,
+ schema: string,
+ tableOrViewName: string,
+ statement: string
+) => {
+ const tabStore = useSQLEditorTabStore();
+ const { executeReadonly } = useExecuteSQL();
+ const tab: CoreSQLEditorTab = {
+ connection: {
+ instance: database.instance,
+ database: database.name,
+ schema,
+ table: tableOrViewName,
+ },
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ sheet: "",
+ };
+ if (
+ tabStore.currentTab &&
+ (tabStore.currentTab.status === "NEW" || !tabStore.currentTab.sheet)
+ ) {
+ // If the current tab is "fresh new" or unsaved, update its connection directly.
+ tabStore.updateCurrentTab({
+ ...tab,
+ title: suggestedTabTitleForSQLEditorConnection(tab.connection),
+ status: "DIRTY",
+ statement,
+ });
+ } else {
+ // Otherwise select or add a new tab and set its connection
+ tabStore.addTab(
+ {
+ ...tab,
+ title: suggestedTabTitleForSQLEditorConnection(tab.connection),
+ statement,
+ status: "DIRTY",
+ },
+ /* beside */ true
+ );
+ }
+ await nextTick();
+ executeReadonly({
+ statement,
+ connection: { ...tab.connection },
+ explain: false,
+ engine: database.instanceEntity.engine,
+ });
+};
+
+export const selectAllFromTableOrView = async (node: TreeNode) => {
+ const { target } = (node as TreeNode<"table" | "view">).meta;
+ if (!targetSupportsSelectAll(target)) {
+ return;
+ }
+
+ const schema = target.schema.name;
+ const tableOrViewName = tableOrViewNameForNode(node);
+ if (!tableOrViewName) {
+ return;
+ }
+
+ const { db } = target;
+ const { engine } = db.instanceEntity;
+
+ const query = generateSimpleSelectAllStatement(
+ engine,
+ schema,
+ tableOrViewName,
+ SELECT_ALL_LIMIT
+ );
+ runQuery(db, schema, tableOrViewName, query);
+};
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/common.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/common.ts
new file mode 100644
index 0000000000..90e8a90e36
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/common.ts
@@ -0,0 +1,474 @@
+import type { TreeOption } from "naive-ui";
+import { v1 as uuidv1 } from "uuid";
+import type { RenderFunction } from "vue";
+import { t } from "@/plugins/i18n";
+import type { ComposedDatabase } from "@/types";
+import type {
+ ColumnMetadata,
+ DatabaseMetadata,
+ ExternalTableMetadata,
+ SchemaMetadata,
+ TableMetadata,
+ TablePartitionMetadata,
+ ViewMetadata,
+} from "@/types/proto/v1/database_service";
+
+export type NodeType =
+ | "database"
+ | "schema"
+ | "table"
+ | "external-table"
+ | "view"
+ | "partition-table"
+ | "column"
+ | "expandable-text" // Text nodes to display "Tables / Views / Functions / Triggers" etc.
+ | "error"; // Error nodes to display "<Empty>" or "Cannot fetch ..." etc.
+
+export type RichDatabaseMetadata = {
+ db: ComposedDatabase;
+ database: DatabaseMetadata;
+};
+export type RichSchemaMetadata = RichDatabaseMetadata & {
+ schema: SchemaMetadata;
+};
+export type RichTableMetadata = RichSchemaMetadata & {
+ table: TableMetadata;
+};
+export type RichExternalTableMetadata = RichSchemaMetadata & {
+ externalTable: ExternalTableMetadata;
+};
+export type RichColumnMetadata = (
+ | RichSchemaMetadata
+ | RichPartitionTableMetadata
+) & {
+ column: ColumnMetadata;
+};
+export type RichPartitionTableMetadata = RichTableMetadata & {
+ parentPartition?: TablePartitionMetadata;
+ partition: TablePartitionMetadata;
+};
+export type RichViewMetadata = RichSchemaMetadata & {
+ view: ViewMetadata;
+};
+export type TextTarget<E extends boolean = any, S extends boolean = any> = {
+ expandable: E;
+ id: string;
+ mockType?: NodeType; // mock as a node type if needed
+ text: () => string;
+ render?: RenderFunction;
+ searchable?: S;
+};
+export type ErrorTarget = TextTarget<false, false> & {
+ error?: unknown;
+};
+
+export type NodeTarget<T extends NodeType = NodeType> = T extends "database"
+ ? RichDatabaseMetadata
+ : T extends "schema"
+ ? RichSchemaMetadata
+ : T extends "table"
+ ? RichTableMetadata
+ : T extends "external-table"
+ ? RichExternalTableMetadata
+ : T extends "column"
+ ? RichColumnMetadata
+ : T extends "partition-table"
+ ? RichPartitionTableMetadata
+ : T extends "view"
+ ? RichViewMetadata
+ : T extends "expandable-text"
+ ? TextTarget<true, any>
+ : T extends "error"
+ ? ErrorTarget
+ : never;
+
+export type TreeState = "UNSET" | "LOADING" | "READY";
+
+export type NodeMeta<T extends NodeType = NodeType> = {
+ type: T;
+ target: NodeTarget<T>;
+};
+
+export type TreeNode<T extends NodeType = NodeType> = TreeOption & {
+ key: string;
+ meta: NodeMeta<T>;
+ parent?: TreeNode;
+ children?: TreeNode[];
+};
+
+export const ExpandableNodeTypes: readonly NodeType[] = [
+ "database",
+ "schema",
+ "table",
+ "external-table",
+ "partition-table",
+ "expandable-text",
+] as const;
+export const LeafNodeTypes: readonly NodeType[] = [
+ "column",
+ "view",
+ "error",
+] as const;
+
+export const keyForNodeTarget = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+): string => {
+ if (type === "database") {
+ const { db } = target as NodeTarget<"database">;
+ return db.name;
+ }
+ if (type === "schema") {
+ const { db, schema } = target as NodeTarget<"schema">;
+ return [db.name, `schemas/${schema.name}`].join("/");
+ }
+ if (type === "table") {
+ const { db, schema, table } = target as NodeTarget<"table">;
+ return [db.name, `schemas/${schema.name}`, `tables/${table.name}`].join(
+ "/"
+ );
+ }
+ if (type === "external-table") {
+ const { db, schema, externalTable } =
+ target as NodeTarget<"external-table">;
+ return [
+ db.name,
+ `schemas/${schema.name}`,
+ `externalTables/${externalTable.externalServerName}/${externalTable.externalDatabaseName}/${externalTable.name}`,
+ ].join("/");
+ }
+ if (type === "column") {
+ const parentKey =
+ "table" in target
+ ? keyForNodeTarget("table", target as NodeTarget<"table">)
+ : keyForNodeTarget(
+ "external-table",
+ target as NodeTarget<"external-table">
+ );
+ const { column } = target as NodeTarget<"column">;
+ return [parentKey, `columns/${column.name}`].join("/");
+ }
+ if (type === "partition-table") {
+ const { db, schema, parentPartition, partition } =
+ target as NodeTarget<"partition-table">;
+ return [
+ db.name,
+ `schemas/${schema.name}`,
+ `partitionTables/${parentPartition?.name ?? ""}/${partition.name}`,
+ ].join("/");
+ }
+ if (type === "view") {
+ const { db, schema, view } = target as NodeTarget<"view">;
+ return [db.name, `schemas/${schema.name}`, `views/${view.name}`].join("/");
+ }
+ if (type === "expandable-text") {
+ const { id } = target as NodeTarget<"expandable-text">;
+ return `expandableTexts/${id}`;
+ }
+ if (type === "error") {
+ const { id } = target as NodeTarget<"error">;
+ return `errors/${id}`;
+ }
+ console.assert(false, "should never reach this line");
+ return "";
+};
+
+const readableTextForNodeTarget = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>
+): string => {
+ if (type === "database") {
+ return (target as NodeTarget<"database">).db.databaseName;
+ }
+ if (type === "schema") {
+ return (target as RichSchemaMetadata).schema.name;
+ }
+ if (type === "table") {
+ return (target as RichTableMetadata).table.name;
+ }
+ if (type === "external-table") {
+ return (target as RichExternalTableMetadata).externalTable.name;
+ }
+ if (type === "column") {
+ return (target as RichColumnMetadata).column.name;
+ }
+ if (type === "partition-table") {
+ return (target as RichPartitionTableMetadata).partition.name;
+ }
+ if (type === "view") {
+ return (target as RichViewMetadata).view.name;
+ }
+ if (type === "expandable-text") {
+ const { text, searchable } = target as TextTarget;
+ if (!searchable) return "";
+ return text();
+ }
+ if (type === "error") {
+ // Use empty strings for error nodes to make them unsearchable
+ return "";
+ }
+ console.assert(false, "should never reach this line");
+ return "";
+};
+
+const isLeafNodeType = (type: NodeType) => {
+ return LeafNodeTypes.includes(type);
+};
+
+export const mapTreeNodeByType = <T extends NodeType>(
+ type: T,
+ target: NodeTarget<T>,
+ parent: TreeNode | undefined,
+ overrides: Partial<TreeNode<T>> | undefined = undefined
+): TreeNode<T> => {
+ const key = keyForNodeTarget(type, target);
+ const node: TreeNode<T> = {
+ key,
+ meta: { type, target },
+ parent,
+ label: readableTextForNodeTarget(type, target),
+ isLeaf: isLeafNodeType(type),
+ ...overrides,
+ };
+
+ return node;
+};
+
+const createDummyNode = (
+ type: "column" | "table" | "view",
+ parent: TreeNode,
+ error: unknown | undefined = undefined
+) => {
+ return mapTreeNodeByType(
+ "error",
+ {
+ id: `${parent.key}/${uuidv1()}`,
+ expandable: false,
+ mockType: type,
+ error,
+ text: () => "",
+ },
+ parent,
+ {
+ disabled: true,
+ }
+ );
+};
+const createExpandableTextNode = (
+ type: NodeType,
+ parent: TreeNode,
+ text: () => string,
+ render?: RenderFunction
+) => {
+ return mapTreeNodeByType(
+ "expandable-text",
+ {
+ id: `${parent.key}/${uuidv1()}`,
+ mockType: type,
+ expandable: true,
+ text,
+ render,
+ },
+ parent
+ );
+};
+const mapColumnNodes = (
+ target: NodeTarget<"table"> | NodeTarget<"external-table">,
+ columns: ColumnMetadata[],
+ parent: TreeNode
+) => {
+ if (columns.length === 0) {
+ // Create a "<Empty>" columns node placeholder
+ return [createDummyNode("column", parent)];
+ }
+
+ const children = columns.map((column) => {
+ const node = mapTreeNodeByType("column", { ...target, column }, parent);
+ return node;
+ });
+ return children;
+};
+const mapTableNodes = (target: NodeTarget<"schema">, parent: TreeNode) => {
+ const { schema } = target;
+ const children = schema.tables.map((table) => {
+ const node = mapTreeNodeByType("table", { ...target, table }, parent);
+ // Map table columns
+ node.children = mapColumnNodes(node.meta.target, table.columns, node);
+
+ // Map table-level partitions.
+ if (table.partitions.length > 0) {
+ for (const partition of table.partitions) {
+ const subnode = mapTreeNodeByType(
+ "partition-table",
+ { ...node.meta.target, partition },
+ node
+ );
+ if (partition.subpartitions.length > 0) {
+ subnode.isLeaf = false;
+ subnode.children = mapPartitionTableNodes(partition, subnode);
+ } else {
+ subnode.isLeaf = true;
+ }
+ node.children.push(subnode);
+ }
+ }
+ return node;
+ });
+ if (children.length === 0) {
+ return [createDummyNode("table", parent)];
+ }
+ return children;
+};
+const mapExternalTableNodes = (
+ target: NodeTarget<"schema">,
+ parent: TreeNode
+) => {
+ const { schema } = target;
+ const children = schema.externalTables.map((externalTable) => {
+ const node = mapTreeNodeByType(
+ "external-table",
+ { ...target, externalTable },
+ parent
+ );
+
+ // columns
+ node.children = mapColumnNodes(
+ node.meta.target,
+ externalTable.columns,
+ node
+ );
+
+ return node;
+ });
+ return children;
+};
+// Map partition-table-level partitions.
+const mapPartitionTableNodes = (
+ parentPartition: TablePartitionMetadata,
+ parent: TreeNode<"partition-table">
+) => {
+ const children = parentPartition.subpartitions.map((partition) => {
+ const node = mapTreeNodeByType(
+ "partition-table",
+ {
+ ...parent.meta.target,
+ parentPartition,
+ partition,
+ },
+ parent
+ );
+ if (partition.subpartitions.length > 0) {
+ node.isLeaf = false;
+ node.children = mapPartitionTableNodes(partition, node);
+ } else {
+ node.isLeaf = true;
+ }
+ return node;
+ });
+ return children;
+};
+const mapViewNodes = (
+ target: NodeTarget<"schema">,
+ parent: TreeNode<"expandable-text">
+) => {
+ const { schema } = target;
+ const children = schema.views.map((view) =>
+ mapTreeNodeByType("view", { ...target, view }, parent)
+ );
+ if (children.length === 0) {
+ return [createDummyNode("view", parent)];
+ }
+ return children;
+};
+const buildSchemaNodeChildren = (
+ target: NodeTarget<"schema">,
+ parent: TreeNode<"schema"> | TreeNode<"database">
+) => {
+ const { schema } = target;
+ if (
+ schema.tables.length === 0 &&
+ schema.externalTables.length === 0 &&
+ schema.views.length === 0
+ ) {
+ return [createDummyNode("table", parent)];
+ }
+
+ const children: TreeNode[] = [];
+
+ // Always show "Tables" node
+ // If no tables, show "<Empty>"
+ const tablesNode = createExpandableTextNode("table", parent, () =>
+ t("db.tables")
+ );
+ tablesNode.children = mapTableNodes(target, tablesNode);
+ children.push(tablesNode);
+
+ // Only show "External Tables" node if the schema do have external tables.
+ if (schema.externalTables.length > 0) {
+ const externalTablesNode = createExpandableTextNode(
+ "external-table",
+ parent,
+ () => t("db.external-tables")
+ );
+ externalTablesNode.children = mapExternalTableNodes(
+ target,
+ externalTablesNode
+ );
+ children.push(externalTablesNode);
+ }
+
+ // Only show "Views" node if the schema do have views.
+ if (schema.views.length > 0) {
+ const viewsNode = createExpandableTextNode("view", parent, () =>
+ t("db.views")
+ );
+ viewsNode.children = mapViewNodes(target, viewsNode);
+ children.push(viewsNode);
+ }
+ return children;
+};
+export const buildDatabaseSchemaTree = (
+ database: ComposedDatabase,
+ metadata: DatabaseMetadata
+) => {
+ const root = mapTreeNodeByType(
+ "database",
+ {
+ db: database,
+ database: metadata,
+ },
+ /* parent */ undefined
+ );
+ const { schemas } = metadata;
+ if (schemas.length === 0) {
+ // Empty database, show "<Empty>"
+ root.children = [createDummyNode("table", root)];
+ return root;
+ }
+
+ if (schemas.length === 1 && schemas[0].name === "") {
+ const schema = schemas[0];
+ // A single schema database, should render tables as views directly as a database
+ // node's children
+ root.children = buildSchemaNodeChildren(
+ { ...root.meta.target, schema },
+ root
+ );
+ } else {
+ // Multiple schema database
+ root.children = schemas.map((schema) => {
+ const schemaNode = mapTreeNodeByType(
+ "schema",
+ { ...root.meta.target, schema },
+ root
+ );
+
+ schemaNode.children = buildSchemaNodeChildren(
+ schemaNode.meta.target,
+ schemaNode
+ );
+ return schemaNode;
+ });
+ }
+ return root;
+};
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/index.ts
new file mode 100644
index 0000000000..0c3be82414
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/index.ts
@@ -0,0 +1,3 @@
+import SchemaPane from "./SchemaPane.vue";
+
+export default SchemaPane;
diff --git a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue b/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
deleted file mode 100644
index c427f39b0f..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/TreeNode/Label.vue
+++ /dev/null
@@ -1,66 +0,0 @@
-<template>
- <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 === 'external-table'">
- <ExternalTableNode :node="node" :factors="factors" :keyword="keyword" />
- </template>
- <template v-if="type === 'partition-table'">
- <PartitionTableNode :node="node" :factors="factors" :keyword="keyword" />
- </template>
- <template v-if="type === 'view'">
- <ViewNode :node="node" :factors="factors" :keyword="keyword" />
- </template>
- <template v-if="type === 'expandable-text'">
- <TextNode :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 { computed } from "vue";
-import type {
- SQLEditorTreeNode as TreeNode,
- SQLEditorTreeFactor as Factor,
-} from "@/types";
-import DatabaseNode from "./DatabaseNode.vue";
-import DummyNode from "./DummyNode.vue";
-import EnvironmentNode from "./EnvironmentNode.vue";
-import ExternalTableNode from "./ExternalTableNode.vue";
-import InstanceNode from "./InstanceNode.vue";
-import LabelNode from "./LabelNode.vue";
-import PartitionTableNode from "./PartitionTableNode.vue";
-import ProjectNode from "./ProjectNode.vue";
-import SchemaNode from "./SchemaNode.vue";
-import TableNode from "./TableNode.vue";
-import TextNode from "./TextNode.vue";
-import ViewNode from "./ViewNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- factors: Factor[];
- keyword: string;
-}>();
-
-const type = computed(() => props.node.meta.type);
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetList.vue
similarity index 96%
rename from frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue
rename to frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetList.vue
index a8879821cd..c45456872a 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/SheetList.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetList.vue
@@ -1,17 +1,14 @@
<template>
- <div class="flex flex-col h-full py-1 gap-y-2">
+ <div class="flex flex-col h-full py-1 gap-y-2 relative">
<div class="flex items-center gap-x-1 px-1 pt-1">
- <NInput
+ <SearchBox
v-model:value="keyword"
size="small"
:disabled="isLoading"
:placeholder="$t('sheet.search-sheets')"
:clearable="true"
- >
- <template #prefix>
- <heroicons-outline:search class="h-5 w-5 text-gray-300" />
- </template>
- </NInput>
+ style="max-width: 100%"
+ />
<NButton
quaternary
style="--n-padding: 0 5px; --n-height: 28px"
@@ -23,7 +20,7 @@
</NButton>
</div>
<div
- class="flex-1 flex flex-col h-full overflow-y-auto sheet-tree"
+ class="flex-1 flex flex-col h-full overflow-y-auto sheet-tree px-1"
@scroll="dropdown = undefined"
>
<NTree
@@ -42,9 +39,6 @@
:node-props="nodeProps"
:virtual-scroll="false"
/>
- <div v-if="isLoading" class="flex flex-col items-center py-8">
- <BBSpin />
- </div>
<Dropdown
v-if="dropdown && isSheetItem(dropdown.item)"
@@ -61,6 +55,8 @@
}"
@dismiss="dropdown = undefined"
/>
+
+ <MaskSpinner v-if="isLoading" class="!bg-white/75" />
</div>
</div>
</template>
@@ -68,15 +64,17 @@
<script lang="ts" setup>
import { orderBy, escape } from "lodash-es";
import type { TreeOption } from "naive-ui";
-import { NButton, NInput, NTree, NEllipsis } from "naive-ui";
+import { NButton, NTree, NEllipsis } from "naive-ui";
import { storeToRefs } from "pinia";
import scrollIntoView from "scroll-into-view-if-needed";
import { computed, nextTick, onMounted, ref, watch, h } from "vue";
import { useI18n } from "vue-i18n";
+import MaskSpinner from "@/components/misc/MaskSpinner.vue";
import {
InstanceV1EngineIcon,
ProjectV1Name,
DatabaseV1Name,
+ SearchBox,
} from "@/components/v2";
import {
useWorkSheetAndTabStore,
@@ -241,7 +239,7 @@ const renderSuffix = ({ option }: { option: TreeOption }) => {
child.push(h(UnsavedPrefix));
} else {
const tab = tabStore.tabList.find((tab) => tab.sheet === item.target.name);
- if (tab?.status === "CLEAN") {
+ if (!tab || tab.status === "CLEAN") {
child.push(
h(Dropdown, {
sheet: item.target,
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/UnsavedPrefix.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/UnsavedPrefix.vue
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/UnsavedPrefix.vue
rename to frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/UnsavedPrefix.vue
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/common.ts b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/common.ts
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/common.ts
rename to frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/common.ts
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/index.ts b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/index.ts
similarity index 100%
rename from frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetList/index.ts
rename to frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/index.ts
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/WorksheetPane.vue
similarity index 95%
rename from frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue
rename to frontend/src/views/sql-editor/AsidePanel/WorksheetPane/WorksheetPane.vue
index 4c49346e7f..2d36537697 100644
--- a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/SheetTabPane.vue
+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/WorksheetPane.vue
@@ -2,8 +2,9 @@
<NTabs
v-model:value="sheetTab"
size="small"
- class="bb-sql-editor--sheet-tab-pane--tabs h-full pt-1.5 px-1"
+ class="bb-sql-editor--sheet-tab-pane--tabs h-full pt-0"
pane-style="height: calc(100% - 29px); padding: 0;"
+ tab-style="padding-top: 0;"
justify-content="start"
>
<NTabPane name="my" :tab="$t('sheet.mine')">
diff --git a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/index.ts
new file mode 100644
index 0000000000..15419c1525
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/index.ts
@@ -0,0 +1,3 @@
+import WorksheetPane from "./WorksheetPane.vue";
+
+export default WorksheetPane;
diff --git a/frontend/src/views/sql-editor/AsidePanel/common.ts b/frontend/src/views/sql-editor/AsidePanel/common.ts
deleted file mode 100644
index 6498aba718..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/common.ts
+++ /dev/null
@@ -1,290 +0,0 @@
-import type { RenderFunction } from "vue";
-import { t } from "@/plugins/i18n";
-import {
- pushNotification,
- useCurrentUserV1,
- useDBSchemaV1Store,
- mapTreeNodeByType,
-} from "@/store";
-import type {
- ComposedDatabase,
- SQLEditorTreeNode,
- SQLEditorTreeNodeType,
- TextTarget,
-} from "@/types";
-import type {
- SchemaMetadata,
- TableMetadata,
- TablePartitionMetadata,
-} from "@/types/proto/v1/database_service";
-import { hasProjectPermissionV2 } from "@/utils";
-
-const createDummyNode = (
- type: "table" | "view",
- parent: SQLEditorTreeNode,
- error: unknown | undefined = undefined
-) => {
- return mapTreeNodeByType(
- "dummy",
- {
- id: parent.key,
- type,
- error,
- },
- parent,
- {
- disabled: true,
- }
- );
-};
-const createExpandableTextNode = (
- type: SQLEditorTreeNodeType,
- parent: SQLEditorTreeNode,
- text: TextTarget<true>["text"],
- render?: RenderFunction
-) => {
- return mapTreeNodeByType(
- "expandable-text",
- {
- id: parent.key,
- type,
- expandable: true,
- text,
- render,
- },
- parent
- );
-};
-
-const mapTableNodes = (
- database: ComposedDatabase,
- schema: SchemaMetadata,
- parent: SQLEditorTreeNode
-) => {
- const children = schema.tables.map((table) => {
- const node = mapTreeNodeByType(
- "table",
- { database, schema, table },
- parent
- );
-
- // Map table-level partitions.
- if (table.partitions.length > 0) {
- node.isLeaf = false;
- node.children = [];
- for (const partition of table.partitions) {
- const subnode = mapTreeNodeByType(
- "partition-table",
- { database, schema, table, partition },
- node
- );
- if (partition.subpartitions.length > 0) {
- subnode.isLeaf = false;
- subnode.children = mapPartitionTableNodes(
- database,
- schema,
- table,
- partition,
- subnode
- );
- } else {
- subnode.isLeaf = true;
- }
- node.children.push(subnode);
- }
- } else {
- node.isLeaf = true;
- }
- return node;
- });
- if (children.length === 0) {
- return [createDummyNode("table", parent)];
- }
- return children;
-};
-
-const mapExternalTableNodes = (
- database: ComposedDatabase,
- schema: SchemaMetadata,
- parent: SQLEditorTreeNode
-) => {
- const children = schema.externalTables.map((externalTable) => {
- const node = mapTreeNodeByType(
- "external-table",
- { database, schema, externalTable },
- parent
- );
-
- node.isLeaf = true;
- return node;
- });
- return children;
-};
-
-// Map partition-table-level partitions.
-const mapPartitionTableNodes = (
- database: ComposedDatabase,
- schema: SchemaMetadata,
- table: TableMetadata,
- parentPartition: TablePartitionMetadata,
- parent: SQLEditorTreeNode
-) => {
- const children = parentPartition.subpartitions.map((partition) => {
- const node = mapTreeNodeByType(
- "partition-table",
- {
- database,
- schema,
- table,
- parentPartition,
- partition: partition,
- },
- parent
- );
- if (partition.subpartitions.length > 0) {
- node.isLeaf = false;
- node.children = mapPartitionTableNodes(
- database,
- schema,
- table,
- partition,
- node
- );
- } else {
- node.isLeaf = true;
- }
- return node;
- });
- return children;
-};
-
-const mapViewNodes = (
- database: ComposedDatabase,
- schema: SchemaMetadata,
- parent: SQLEditorTreeNode
-) => {
- const children = schema.views.map((view) =>
- mapTreeNodeByType(
- "view",
- {
- database,
- schema,
- view,
- },
- parent
- )
- );
- if (children.length === 0) {
- return [createDummyNode("view", parent)];
- }
- return children;
-};
-
-const buildSchemaNodeChildren = (
- database: ComposedDatabase,
- schema: SchemaMetadata,
- parent: SQLEditorTreeNode
-) => {
- if (schema.tables.length === 0 && schema.views.length === 0) {
- return [createDummyNode("table", parent)];
- }
-
- const children: SQLEditorTreeNode[] = [];
-
- // Always show "Tables" node
- // If no tables, show "<Empty>"
- const tablesNode = createExpandableTextNode("table", parent, () =>
- t("db.tables")
- );
- tablesNode.children = mapTableNodes(database, schema, tablesNode);
- children.push(tablesNode);
-
- // Only show "External Tables" node if the schema do have external tables.
- if (schema.externalTables.length > 0) {
- const externalTablesNode = createExpandableTextNode(
- "external-table",
- parent,
- () => t("db.external-tables")
- );
- externalTablesNode.children = mapExternalTableNodes(
- database,
- schema,
- externalTablesNode
- );
- children.push(externalTablesNode);
- }
-
- // Only show "Views" node if the schema do have views.
- if (schema.views.length > 0) {
- const viewsNode = createExpandableTextNode("view", parent, () =>
- t("db.views")
- );
- viewsNode.children = mapViewNodes(database, schema, viewsNode);
- children.push(viewsNode);
- }
- return children;
-};
-
-export const fetchDatabaseSubTree = async (
- node: SQLEditorTreeNode<"database">
-) => {
- const me = useCurrentUserV1();
- if (
- !hasProjectPermissionV2(
- node.meta.target.projectEntity,
- me.value,
- "bb.databases.getSchema"
- )
- ) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("sql-editor.missing-permission-to-load-db-metadata", {
- db: node.meta.target.databaseName,
- }),
- });
- node.children = [];
- node.isLeaf = true;
- return;
- }
-
- try {
- const database = node.meta.target;
- const databaseMetadata =
- await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
- database: database.name,
- skipCache: false,
- });
-
- const { schemas } = databaseMetadata;
- if (schemas.length === 0) {
- // Empty database, show "<Empty>"
- node.children = [createDummyNode("table", node)];
- return;
- }
-
- if (schemas.length === 1 && schemas[0].name === "") {
- const schema = schemas[0];
- // A single schema database, should render tables as views directly as a database
- // node's children
- node.children = buildSchemaNodeChildren(database, schema, node);
- return;
- } else {
- // Multiple schema database
- node.children = schemas.map((schema) => {
- const schemaNode = mapTreeNodeByType(
- "schema",
- { database, schema },
- node
- );
-
- schemaNode.children = buildSchemaNodeChildren(database, schema, node);
- return schemaNode;
- });
- return;
- }
- } catch (error) {
- console.warn("[fetchDatabaseSubTree]", error);
- node.children = [createDummyNode("table", node, error)];
- }
-};
diff --git a/frontend/src/views/sql-editor/AsidePanel/hover-state.ts b/frontend/src/views/sql-editor/AsidePanel/hover-state.ts
index 5d55742189..fcae69ec61 100644
--- a/frontend/src/views/sql-editor/AsidePanel/hover-state.ts
+++ b/frontend/src/views/sql-editor/AsidePanel/hover-state.ts
@@ -1,37 +1,37 @@
-import type { InjectionKey, Ref } from "vue";
-import { inject, provide } from "vue";
+import type { Ref } from "vue";
+import { inject, provide, ref } from "vue";
import { useDelayedValue } from "@/composables/useDelayedValue";
-import type { SQLEditorTreeNode } from "@/types";
+import type { Position } from "@/types";
-type UpdateFn = ReturnType<
- typeof useDelayedValue<SQLEditorTreeNode | undefined>
->["update"];
+type UpdateFn<T> = ReturnType<typeof useDelayedValue<T | undefined>>["update"];
-export type HoverStateContext = {
- node: Ref<SQLEditorTreeNode | undefined>;
- update: UpdateFn;
+export type HoverStateContext<S> = {
+ state: Ref<S | undefined>;
+ position: Ref<Position>;
+ update: UpdateFn<S>;
};
-export const KEY = Symbol(
- "bb.sql-editor.tree.hover-state"
-) as InjectionKey<HoverStateContext>;
-
-export const useHoverStateContext = () => {
- return inject(KEY)!;
+export const useHoverStateContext = <S>(key: string) => {
+ const KEY = `bb.sql-editor.${key}.hover-state`;
+ return inject(KEY)! as HoverStateContext<S>;
};
-export const provideHoverStateContext = () => {
- const { value: node, update } = useDelayedValue<
- SQLEditorTreeNode | undefined
- >(undefined, {
+export const provideHoverStateContext = <S>(key: string) => {
+ const { value: state, update } = useDelayedValue<S | undefined>(undefined, {
delayBefore: 500,
delayAfter: 500,
});
- const context: HoverStateContext = {
- node,
+ const position = ref<Position>({
+ x: 0,
+ y: 0,
+ });
+ const context: HoverStateContext<S> = {
+ state,
+ position,
update,
};
+ const KEY = `bb.sql-editor.${key}.hover-state`;
provide(KEY, context);
return context;
diff --git a/frontend/src/views/sql-editor/AsidePanel/index.ts b/frontend/src/views/sql-editor/AsidePanel/index.ts
new file mode 100644
index 0000000000..b86004546d
--- /dev/null
+++ b/frontend/src/views/sql-editor/AsidePanel/index.ts
@@ -0,0 +1,3 @@
+import AsidePanel from "./AsidePanel.vue";
+
+export default AsidePanel;
diff --git a/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue b/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
index 3ca0978d9f..8c9af7f1ef 100644
--- a/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
@@ -6,13 +6,14 @@
:disabled="isDisconnected"
@click="enterAdminMode"
>
- <heroicons-outline:wrench class="-ml-1" />
+ <WrenchIcon class="-ml-1 w-4 h-4" />
<span class="ml-1"> {{ $t("sql-editor.admin-mode.self") }} </span>
</NButton>
</template>
<script lang="ts" setup>
import { last } from "lodash-es";
+import { WrenchIcon } from "lucide-vue-next";
import { storeToRefs } from "pinia";
import { computed, nextTick, unref } from "vue";
import {
diff --git a/frontend/src/views/sql-editor/SQLEditorPage.vue b/frontend/src/views/sql-editor/SQLEditorPage.vue
index 1f7845558f..d3faa08185 100644
--- a/frontend/src/views/sql-editor/SQLEditorPage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorPage.vue
@@ -51,28 +51,8 @@
:dbl-click-splitter="false"
>
<Pane class="flex flex-row overflow-hidden">
- <div class="h-full flex-1 overflow-hidden">
- <Splitpanes
- vertical
- class="default-theme"
- :dbl-click-splitter="false"
- >
- <Pane>
- <EditorPanel v-if="isDisconnected || allowReadonlyMode" />
- <ReadonlyModeNotSupported v-else />
- </Pane>
- <Pane
- v-if="showSecondarySidebar && windowWidth >= 1024"
- :size="25"
- >
- <SecondarySidebar />
- </Pane>
- </Splitpanes>
- </div>
-
- <div v-if="windowWidth >= 1024" class="h-full border-l shrink-0">
- <SecondaryGutterBar />
- </div>
+ <EditorPanel v-if="isDisconnected || allowReadonlyMode" />
+ <ReadonlyModeNotSupported v-else />
</Pane>
<Pane
v-if="!isDisconnected && allowReadonlyMode"
@@ -143,15 +123,10 @@ import {
instanceV1HasReadonlyMode,
} from "@/utils";
import AccessDenied from "./AccessDenied.vue";
-import AsidePanel from "./AsidePanel/AsidePanel.vue";
+import AsidePanel from "./AsidePanel";
import EditorPanel from "./EditorPanel/EditorPanel.vue";
import ReadonlyModeNotSupported from "./ReadonlyModeNotSupported.vue";
import ResultPanel from "./ResultPanel";
-import {
- default as SecondarySidebar,
- useSecondarySidebarContext,
-} from "./SecondarySidebar";
-import { SecondaryGutterBar } from "./SecondarySidebar";
import { useSheetContext } from "./Sheet";
import SheetPanel from "./SheetPanel";
import TabList from "./TabList";
@@ -177,7 +152,6 @@ const actuatorStore = useActuatorV1Store();
const tabStore = useSQLEditorTabStore();
const { events: editorEvents } = useSQLEditorContext();
const { showPanel: showSheetPanel } = useSheetContext();
-const { show: showSecondarySidebar } = useSecondarySidebarContext();
const { currentTab, isDisconnected } = storeToRefs(tabStore);
const showQuickstart = computed(() => actuatorStore.pageMode === "BUNDLED");
@@ -264,10 +238,6 @@ useEmitteryEventListener(
.splitpanes.default-theme .splitpanes__splitter:hover::after {
@apply bg-white opacity-100;
}
-
-.secondary-sidebar-gutter .n-tabs-wrapper {
- @apply pt-0;
-}
</style>
<style scoped lang="postcss">
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/index.ts b/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/index.ts
deleted file mode 100644
index af1dd2a122..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/HistoryTabPane/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import HistoryTabPane from "./HistoryTabPane.vue";
-
-export default HistoryTabPane;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/InfoTabPane.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/InfoTabPane.vue
deleted file mode 100644
index d8c56dc04b..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/InfoTabPane.vue
+++ /dev/null
@@ -1,7 +0,0 @@
-<template>
- <SchemaPanel />
-</template>
-
-<script setup lang="ts">
-import SchemaPanel from "./SchemaPanel";
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/AlterSchemaButton.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/AlterSchemaButton.vue
deleted file mode 100644
index a90b18ca2b..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/AlterSchemaButton.vue
+++ /dev/null
@@ -1,58 +0,0 @@
-<template>
- <NTooltip
- v-if="allowAlterSchema"
- trigger="hover"
- :delay="500"
- :animated="false"
- >
- <template #trigger>
- <NButton
- quaternary
- size="tiny"
- class="!px-1"
- v-bind="$attrs"
- @click="emit('click')"
- >
- <heroicons-outline:pencil-alt class="w-4 h-4" />
- </NButton>
- </template>
- {{ $t("database.edit-schema") }}
- </NTooltip>
-</template>
-
-<script lang="ts" setup>
-import { NButton } from "naive-ui";
-import { computed } from "vue";
-import { useCurrentUserV1 } from "@/store";
-import { UNKNOWN_ID, type ComposedDatabase } from "@/types";
-import type {
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import {
- hasPermissionToCreateChangeDatabaseIssue,
- instanceV1HasAlterSchema,
-} from "@/utils";
-
-const props = defineProps<{
- database: ComposedDatabase;
- schema?: SchemaMetadata;
- table?: TableMetadata;
-}>();
-
-const emit = defineEmits<{
- (event: "click"): void;
-}>();
-
-const me = useCurrentUserV1();
-
-const allowAlterSchema = computed(() => {
- if (props.database.uid === String(UNKNOWN_ID)) {
- return false;
- }
- return (
- instanceV1HasAlterSchema(props.database.instanceEntity) &&
- hasPermissionToCreateChangeDatabaseIssue(props.database, me.value)
- );
-});
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ColumnList.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ColumnList.vue
deleted file mode 100644
index 7a55a35e53..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ColumnList.vue
+++ /dev/null
@@ -1,119 +0,0 @@
-<template>
- <div class="overflow-hidden">
- <VirtualList
- :items="filteredColumnList"
- :key-field="`name`"
- :item-resizable="true"
- :item-size="24"
- >
- <template #default="{ item: column }: VirtualListItem">
- <div
- class="bb-column-list--column-item flex items-start mx-3 px-1 gap-2 cursor-pointer hover:bg-control-bg-hover/50"
- @mouseenter="handleMouseEnter($event, column)"
- @mouseleave="handleMouseLeave($event, column)"
- >
- <NEllipsis class="max-w-2/3">
- <!-- eslint-disable vue/no-v-html -->
- <span
- class="text-sm leading-6 text-gray-600whitespace-pre-wrap break-words flex-2 min-w-[4rem]"
- v-html="renderColumnName(column)"
- />
- </NEllipsis>
- <NEllipsis
- class="shrink-0 max-w-1/2 text-right text-sm leading-6 text-gray-400 flex-1 min-w-[4rem]"
- >
- {{ column.type }}
- </NEllipsis>
- </div>
- </template>
- </VirtualList>
- </div>
-</template>
-
-<script setup lang="ts">
-import { escape } from "lodash-es";
-import { NEllipsis } from "naive-ui";
-import { computed, nextTick } from "vue";
-import { VirtualList } from "vueuc";
-import type { ComposedDatabase } from "@/types";
-import type {
- ColumnMetadata,
- DatabaseMetadata,
- SchemaMetadata,
-} from "@/types/proto/v1/database_service";
-import { findAncestor, getHighlightHTMLByRegExp } from "@/utils";
-import { useHoverStateContext } from "./HoverPanel";
-import { useSchemaPanelContext } from "./context";
-
-export type VirtualListItem = {
- item: ColumnMetadata;
- index: number;
-};
-
-const props = defineProps<{
- db: ComposedDatabase;
- database: DatabaseMetadata;
- schema: SchemaMetadata;
- columns: ColumnMetadata[];
-}>();
-
-const {
- state: hoverState,
- position: hoverPosition,
- update: updateHoverState,
-} = useHoverStateContext();
-const { keyword } = useSchemaPanelContext();
-const filteredColumnList = computed(() => {
- const kw = keyword.value.toLowerCase().trim();
- if (!kw) {
- return props.columns;
- }
- return props.columns.filter((column) => {
- return column.name.toLowerCase().includes(kw);
- });
-});
-
-const renderColumnName = (column: ColumnMetadata) => {
- if (!keyword.value.trim()) {
- return column.name;
- }
-
- return getHighlightHTMLByRegExp(
- escape(column.name),
- escape(keyword.value.trim()),
- false /* !caseSensitive */
- );
-};
-
-const handleMouseEnter = (e: MouseEvent, column: ColumnMetadata) => {
- const { db, database, schema } = props;
- if (hoverState.value) {
- updateHoverState(
- { db, database, schema, column },
- "before",
- 0 /* overrideDelay */
- );
- } else {
- updateHoverState({ db, database, schema, column }, "before");
- }
- nextTick().then(() => {
- // Find the node element and put the database panel to the top-left corner
- // of the node
- const wrapper = findAncestor(
- e.target as HTMLElement,
- ".bb-column-list--column-item"
- );
- if (!wrapper) {
- updateHoverState(undefined, "after", 0 /* overrideDelay */);
- return;
- }
- const bounding = wrapper.getBoundingClientRect();
- hoverPosition.value.x = bounding.left;
- hoverPosition.value.y = bounding.top;
- });
-};
-
-const handleMouseLeave = (e: MouseEvent, column: ColumnMetadata) => {
- updateHoverState(undefined, "after");
-};
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/DatabaseSchema.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/DatabaseSchema.vue
deleted file mode 100644
index 25866783c3..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/DatabaseSchema.vue
+++ /dev/null
@@ -1,115 +0,0 @@
-<template>
- <div v-if="databaseMetadata" class="h-full overflow-hidden flex flex-col">
- <div class="flex items-center justify-between px-2 py-1 border-b gap-x-1">
- <div
- class="flex items-center flex-1 truncate"
- :class="[headerClickable && 'cursor-pointer']"
- @click="handleClickHeader"
- >
- <heroicons-outline:database class="h-4 w-4 mr-1 flex-shrink-0" />
- <span class="text-sm truncate">{{ database.databaseName }}</span>
- </div>
- <div class="flex justify-end gap-x-0.5">
- <HideInStandaloneMode>
- <ExternalLinkButton
- v-if="database.uid !== String(UNKNOWN_ID)"
- :link="databaseV1Url(database)"
- :tooltip="$t('common.detail')"
- />
- </HideInStandaloneMode>
- <HideInStandaloneMode>
- <AlterSchemaButton
- :database="database"
- @click="
- editorEvents.emit('alter-schema', {
- databaseUID: database.uid,
- schema: '',
- table: '',
- })
- "
- />
- </HideInStandaloneMode>
- </div>
- </div>
-
- <TableList
- class="flex-1 w-full py-1"
- :db="database"
- :database="databaseMetadata"
- :schema-list="availableSchemas"
- :row-clickable="rowClickable"
- @select-table="(schema, table) => $emit('select-table', schema, table)"
- @select-external-table="
- (schema, externalTable) =>
- $emit('select-external-table', schema, externalTable)
- "
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { useCurrentUserV1 } from "@/store";
-import { UNKNOWN_ID, type ComposedDatabase } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import type {
- DatabaseMetadata,
- ExternalTableMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import { databaseV1Url, isTableQueryable } from "@/utils";
-import { useSQLEditorContext } from "@/views/sql-editor/context";
-import AlterSchemaButton from "./AlterSchemaButton.vue";
-import ExternalLinkButton from "./ExternalLinkButton.vue";
-import TableList from "./TableList.vue";
-
-const props = defineProps<{
- database: ComposedDatabase;
- databaseMetadata: DatabaseMetadata;
- headerClickable: boolean;
-}>();
-
-const emit = defineEmits<{
- (e: "click-header"): void;
- (e: "select-table", schema: SchemaMetadata, table: TableMetadata): void;
- (
- e: "select-external-table",
- schema: SchemaMetadata,
- externalTable: ExternalTableMetadata
- ): void;
-}>();
-
-const { events: editorEvents } = useSQLEditorContext();
-const currentUser = useCurrentUserV1();
-
-const engine = computed(() => props.database.instanceEntity.engine);
-
-const rowClickable = computed(() => engine.value !== Engine.MONGODB);
-
-const availableSchemas = computed(() => {
- const schemas = props.databaseMetadata.schemas
- .map((schema) => {
- return {
- ...schema,
- tables: schema.tables.filter((table) => {
- return isTableQueryable(
- props.database,
- schema.name,
- table.name,
- currentUser.value
- );
- }),
- };
- })
- .filter((schema) => {
- return schema.tables.length !== 0;
- });
- return schemas;
-});
-
-const handleClickHeader = () => {
- if (!props.headerClickable) return;
- emit("click-header");
-};
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ExternalLinkButton.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ExternalLinkButton.vue
deleted file mode 100644
index 49a5b1def7..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ExternalLinkButton.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<template>
- <NTooltip trigger="hover" :delay="500" :animated="false">
- <template #trigger>
- <NButton quaternary size="tiny" class="!px-1" v-bind="$attrs" @click="go">
- <heroicons-outline:external-link class="w-4 h-4" />
- </NButton>
- </template>
- {{ tooltip }}
- </NTooltip>
-</template>
-
-<script lang="ts" setup>
-import { NButton } from "naive-ui";
-
-const props = defineProps<{
- link: string;
- tooltip: string;
-}>();
-
-const go = () => {
- window.open(props.link, "_blank");
-};
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ExternalTableSchema.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ExternalTableSchema.vue
deleted file mode 100644
index 5f422d5f20..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/ExternalTableSchema.vue
+++ /dev/null
@@ -1,43 +0,0 @@
-<template>
- <div class="overflow-hidden flex flex-col">
- <div class="flex items-center justify-between pl-4 pr-2 py-1 border-b">
- <div
- class="flex items-center flex-1 truncate cursor-pointer"
- @click="emit('close')"
- >
- <heroicons-outline:table class="h-4 w-4 mr-1 flex-shrink-0" />
- <span v-if="schema.name" class="text-sm">{{ schema.name }}.</span>
- <span class="text-sm">{{ externalTable.name }}</span>
- </div>
- </div>
-
- <ColumnList
- :db="db"
- :database="database"
- :schema="schema"
- :columns="externalTable.columns"
- class="w-full flex-1 py-1"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import type { ComposedDatabase } from "@/types";
-import type {
- DatabaseMetadata,
- ExternalTableMetadata,
- SchemaMetadata,
-} from "@/types/proto/v1/database_service";
-import ColumnList from "./ColumnList.vue";
-
-defineProps<{
- db: ComposedDatabase;
- database: DatabaseMetadata;
- schema: SchemaMetadata;
- externalTable: ExternalTableMetadata;
-}>();
-
-const emit = defineEmits<{
- (e: "close"): void;
-}>();
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/hover-state.ts b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/hover-state.ts
deleted file mode 100644
index 0ea2d6085d..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/HoverPanel/hover-state.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { InjectionKey, Ref } from "vue";
-import { inject, provide, ref } from "vue";
-import { useDelayedValue } from "@/composables/useDelayedValue";
-import type { ComposedDatabase } from "@/types";
-import type {
- ColumnMetadata,
- DatabaseMetadata,
- ExternalTableMetadata,
- SchemaMetadata,
- TableMetadata,
- ViewMetadata,
-} from "@/types/proto/v1/database_service";
-
-type UpdateFn = ReturnType<typeof useDelayedValue<any>>["update"];
-
-type Position = {
- x: number;
- y: number;
-};
-
-export type HoverState = {
- db: ComposedDatabase;
- database: DatabaseMetadata;
- schema: SchemaMetadata;
- table?: TableMetadata;
- externalTable?: ExternalTableMetadata;
- view?: ViewMetadata;
- column?: ColumnMetadata;
-};
-
-export type HoverStateContext = {
- state: Ref<HoverState | undefined>;
- position: Ref<Position>;
- update: UpdateFn;
-};
-
-export const KEY = Symbol(
- "bb.sql-editor.schema-panel.hover-state"
-) as InjectionKey<HoverStateContext>;
-
-export const useHoverStateContext = () => {
- return inject(KEY)!;
-};
-
-export const provideHoverStateContext = () => {
- const { value: state, update } = useDelayedValue<HoverState | undefined>(
- undefined,
- {
- delayBefore: 500,
- delayAfter: 500,
- }
- );
- const position = ref<Position>({
- x: 0,
- y: 0,
- });
- const context: HoverStateContext = {
- state,
- position,
- update,
- };
-
- provide(KEY, context);
-
- return context;
-};
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue
deleted file mode 100644
index b91d8a07b2..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/SchemaPanel.vue
+++ /dev/null
@@ -1,158 +0,0 @@
-<template>
- <div class="flex flex-col h-full py-0.5 gap-y-1">
- <div class="flex items-center gap-x-1 px-2 pt-1.5">
- <NInput
- v-model:value="keyword"
- size="small"
- :placeholder="$t('common.filter-by-name')"
- :clearable="true"
- >
- <template #prefix>
- <heroicons-outline:search class="h-5 w-5 text-gray-300" />
- </template>
- </NInput>
- </div>
-
- <div class="w-full h-full relative overflow-hidden">
- <template v-if="databaseMetadata && !isLoading">
- <DatabaseSchema
- :database="database"
- :database-metadata="databaseMetadata"
- :header-clickable="selected !== undefined"
- @click-header="selected = undefined"
- @select-table="handleSelectTable"
- @select-external-table="handleSelectExternalTable"
- />
- <Transition name="slide-up">
- <template v-if="selected">
- <TableSchema
- v-if="selected.table"
- class="absolute bottom-0 w-full h-[calc(100%-33px)] bg-white"
- :db="database"
- :database="databaseMetadata"
- :schema="selected.schema"
- :table="selected.table"
- @close="selected = undefined"
- />
- <ExternalTableSchema
- v-else-if="selected.externalTable"
- class="absolute bottom-0 w-full h-[calc(100%-33px)] bg-white"
- :db="database"
- :database="databaseMetadata"
- :schema="selected.schema"
- :external-table="selected.externalTable"
- @close="selected = undefined"
- />
- </template>
- </Transition>
- </template>
-
- <div
- v-else
- class="absolute inset-0 bg-white/50 flex flex-col items-center justify-center"
- >
- <BBSpin />
- </div>
- </div>
-
- <HoverPanel :offset-x="-24" :offset-y="0" />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { asyncComputed } from "@vueuse/core";
-import { computed, ref } from "vue";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
-} from "@/store";
-import type {
- SchemaMetadata,
- TableMetadata,
- ExternalTableMetadata,
-} from "@/types/proto/v1/database_service";
-import { DatabaseMetadataView } from "@/types/proto/v1/database_service";
-import { useSQLEditorContext } from "@/views/sql-editor/context";
-import DatabaseSchema from "./DatabaseSchema.vue";
-import ExternalTableSchema from "./ExternalTableSchema.vue";
-import { provideHoverStateContext, HoverPanel } from "./HoverPanel";
-import TableSchema from "./TableSchema.vue";
-import { provideSchemaPanelContext } from "./context";
-
-const { selectedDatabaseSchemaByDatabaseName } = useSQLEditorContext();
-
-const dbSchemaStore = useDBSchemaV1Store();
-const { database } = useConnectionOfCurrentSQLEditorTab();
-const { keyword } = provideSchemaPanelContext();
-provideHoverStateContext();
-
-const isLoading = ref(false);
-const databaseMetadata = asyncComputed(
- async () => {
- const { name } = database.value;
- const databaseMetadata = await dbSchemaStore.getOrFetchDatabaseMetadata({
- database: name,
- view: DatabaseMetadataView.DATABASE_METADATA_VIEW_FULL,
- skipCache: false,
- });
- return databaseMetadata;
- },
- undefined,
- {
- evaluating: isLoading,
- }
-);
-
-const selected = computed({
- get() {
- return selectedDatabaseSchemaByDatabaseName.value.get(database.value.name);
- },
- set(selected) {
- if (!selected) {
- selectedDatabaseSchemaByDatabaseName.value.delete(database.value.name);
- } else {
- selectedDatabaseSchemaByDatabaseName.value.set(
- database.value.name,
- selected
- );
- }
- },
-});
-
-const handleSelectTable = async (
- schema: SchemaMetadata,
- table: TableMetadata
-) => {
- const tableMetadata = await dbSchemaStore.getOrFetchTableMetadata({
- database: database.value.name,
- schema: schema.name,
- table: table.name,
- });
- const databaseMetadata = useDBSchemaV1Store().getDatabaseMetadata(
- database.value.name
- );
-
- selected.value = {
- db: database.value,
- database: databaseMetadata,
- schema,
- table: tableMetadata,
- };
-};
-
-const handleSelectExternalTable = async (
- schema: SchemaMetadata,
- externalTable: ExternalTableMetadata
-) => {
- const databaseMetadata = useDBSchemaV1Store().getDatabaseMetadata(
- database.value.name
- );
-
- selected.value = {
- db: database.value,
- database: databaseMetadata,
- schema,
- externalTable,
- };
-};
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vue
deleted file mode 100644
index 0f35226c5e..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/StringifyMetadataButton.vue
+++ /dev/null
@@ -1,36 +0,0 @@
-<template>
- <NPopover
- trigger="click"
- placement="bottom-end"
- @update:show="(show: boolean) => show"
- >
- <template #trigger>
- <NButton quaternary size="tiny" class="!px-1" v-bind="$attrs">
- <CodeIcon class="w-4 h-4" />
- </NButton>
- </template>
- <TableSchemaViewer
- class="!w-[32rem] !h-[20rem]"
- :database="database"
- :schema="schema?.name"
- :table="table?.name"
- />
- </NPopover>
-</template>
-
-<script lang="ts" setup>
-import { CodeIcon } from "lucide-vue-next";
-import { NButton, NPopover } from "naive-ui";
-import TableSchemaViewer from "@/components/TableSchemaViewer.vue";
-import type { ComposedDatabase } from "@/types";
-import type {
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-
-defineProps<{
- database: ComposedDatabase;
- schema?: SchemaMetadata;
- table?: TableMetadata;
-}>();
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/TableList.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/TableList.vue
deleted file mode 100644
index 97463fd970..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/TableList.vue
+++ /dev/null
@@ -1,224 +0,0 @@
-<template>
- <div class="flex flex-col overflow-hidden">
- <VirtualList
- :items="filteredTableOrViewList"
- :key-field="`key`"
- :item-resizable="true"
- :item-size="24"
- >
- <template #default="{ item, index }: VirtualListItem">
- <div
- class="w-full text-sm leading-6 px-1"
- :class="`bb-table-list--item`"
- :data-key="item.key"
- :data-index="index"
- @mouseenter="handleMouseEnter($event, item)"
- @mouseleave="handleMouseLeave($event, item)"
- >
- <div
- class="w-full flex items-center text-gray-600 rounded-sm px-1"
- :class="
- rowClickable && ['hover:bg-control-bg-hover/50', 'cursor-pointer']
- "
- @click="handleClickItem(item)"
- >
- <TableIcon
- v-if="item.table || item.externalTable"
- class="w-4 h-4 mr-1 shrink-0"
- />
- <ViewIcon v-if="item.view" class="w-4 h-4 mr-1 shrink-0" />
- <!-- eslint-disable vue/no-v-html -->
- <div
- class="flex-1 truncate"
- :title="renderItemLabel(item)"
- v-html="renderItem(item)"
- />
- </div>
- </div>
- </template>
- </VirtualList>
- </div>
-</template>
-
-<script setup lang="ts">
-import { escape } from "lodash-es";
-import { computed, nextTick } from "vue";
-import { VirtualList } from "vueuc";
-import { TableIcon, ViewIcon } from "@/components/Icon";
-import type { ComposedDatabase } from "@/types";
-import type {
- DatabaseMetadata,
- ExternalTableMetadata,
- SchemaMetadata,
- TableMetadata,
- ViewMetadata,
-} from "@/types/proto/v1/database_service";
-import { findAncestor, getHighlightHTMLByRegExp } from "@/utils";
-import { useHoverStateContext } from "./HoverPanel";
-import { useSchemaPanelContext } from "./context";
-
-export type SchemaAndTableOrExternalTableOrView = {
- key: string;
- schema: SchemaMetadata;
- table?: TableMetadata;
- externalTable?: ExternalTableMetadata;
- view?: ViewMetadata;
-};
-
-export type VirtualListItem = {
- item: SchemaAndTableOrExternalTableOrView;
- index: number;
-};
-
-const props = defineProps<{
- db: ComposedDatabase;
- database: DatabaseMetadata;
- schemaList: SchemaMetadata[];
- rowClickable?: boolean;
-}>();
-
-const emit = defineEmits<{
- (e: "select-table", schema: SchemaMetadata, table: TableMetadata): void;
- (
- e: "select-external-table",
- schema: SchemaMetadata,
- externalTable: ExternalTableMetadata
- ): void;
-}>();
-
-const { keyword } = useSchemaPanelContext();
-const {
- state: hoverState,
- position: hoverPosition,
- update: updateHoverState,
-} = useHoverStateContext();
-
-const flattenTableOrViewList = computed(() => {
- const { schemaList } = props;
- const tables = schemaList.flatMap((schema) => {
- return schema.tables.map<SchemaAndTableOrExternalTableOrView>((table) => ({
- key: `schemas/${schema.name}/tables/${table.name}`,
- schema,
- table,
- }));
- });
- const externalTables = schemaList.flatMap((schema) => {
- return schema.externalTables.map<SchemaAndTableOrExternalTableOrView>(
- (externalTable) => ({
- key: `schemas/${schema.name}/externalTables/${externalTable.name}`,
- schema,
- externalTable,
- })
- );
- });
- const views = schemaList.flatMap((schema) => {
- return schema.views.map<SchemaAndTableOrExternalTableOrView>((view) => ({
- key: `schemas/${schema.name}/views/${view.name}`,
- schema,
- view,
- }));
- });
- return [...tables, ...externalTables, ...views];
-});
-
-const filteredTableOrViewList = computed(() => {
- const kw = keyword.value.toLowerCase().trim();
- if (!kw) {
- return flattenTableOrViewList.value;
- }
- return flattenTableOrViewList.value.filter(({ schema, table, view }) => {
- return (
- schema.name.toLowerCase().includes(kw) ||
- table?.name.toLowerCase().includes(kw) ||
- view?.name.toLowerCase().includes(kw)
- );
- });
-});
-
-const handleClickItem = (item: SchemaAndTableOrExternalTableOrView) => {
- if (!props.rowClickable) {
- return;
- }
- const { schema, table, externalTable } = item;
- if (table) {
- emit("select-table", schema, table);
- } else if (externalTable) {
- emit("select-external-table", schema, externalTable);
- }
-};
-
-const renderItemLabel = (item: SchemaAndTableOrExternalTableOrView) => {
- const parts: string[] = [];
- const { schema, table, externalTable, view } = item;
- const name = table?.name ?? externalTable?.name ?? view?.name ?? "";
- if (!name) return undefined;
- if (schema.name) {
- parts.push(`${schema.name}.`);
- }
- parts.push(name);
- return parts.join("");
-};
-
-const renderItem = (item: SchemaAndTableOrExternalTableOrView) => {
- const parts: string[] = [];
- const { schema, table, externalTable, view } = item;
- const name = table?.name ?? externalTable?.name ?? view?.name ?? "";
- if (!name) return null;
- if (schema.name) {
- parts.push(`${schema.name}.`);
- }
- parts.push(name);
- if (!keyword.value.trim()) {
- return parts.join("");
- }
-
- return getHighlightHTMLByRegExp(
- escape(parts.join("")),
- escape(keyword.value.trim()),
- false /* !caseSensitive */
- );
-};
-
-const handleMouseEnter = (
- e: MouseEvent,
- item: SchemaAndTableOrExternalTableOrView
-) => {
- const { db, database } = props;
- const { schema, table, externalTable, view } = item;
-
- if (hoverState.value) {
- updateHoverState(
- { db, database, schema, table, externalTable, view },
- "before",
- 0 /* overrideDelay */
- );
- } else {
- updateHoverState(
- { db, database, schema, table, externalTable, view },
- "before"
- );
- }
- nextTick().then(() => {
- // Find the node element and put the database panel to the top-left corner
- // of the node
- const wrapper = findAncestor(
- e.target as HTMLElement,
- ".bb-table-list--item"
- );
- if (!wrapper) {
- updateHoverState(undefined, "after", 0 /* overrideDelay */);
- return;
- }
- const bounding = wrapper.getBoundingClientRect();
- hoverPosition.value.x = bounding.left;
- hoverPosition.value.y = bounding.top;
- });
-};
-
-const handleMouseLeave = (
- e: MouseEvent,
- item: SchemaAndTableOrExternalTableOrView
-) => {
- updateHoverState(undefined, "after");
-};
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/TableSchema.vue b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/TableSchema.vue
deleted file mode 100644
index 35d3554bc4..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/TableSchema.vue
+++ /dev/null
@@ -1,99 +0,0 @@
-<template>
- <div class="overflow-hidden flex flex-col">
- <div class="flex items-center justify-between pl-4 pr-2 py-1 border-b">
- <div
- class="flex items-center flex-1 truncate cursor-pointer"
- @click="emit('close')"
- >
- <heroicons-outline:table class="h-4 w-4 mr-1 flex-shrink-0" />
- <span v-if="schema.name" class="text-sm">{{ schema.name }}.</span>
- <span class="text-sm truncate">{{ table.name }}</span>
- </div>
-
- <div class="flex justify-end gap-x-0.5">
- <StringifyMetadataButton
- v-if="showStringifyMetadataButton"
- :database="db"
- :schema="schema"
- :table="table"
- />
- <HideInStandaloneMode>
- <ExternalLinkButton
- v-if="db.uid !== String(UNKNOWN_ID)"
- :link="tableDetailLink"
- :tooltip="$t('common.detail')"
- />
- <AlterSchemaButton
- :database="db"
- :schema="schema"
- :table="table"
- @click="
- editorEvents.emit('alter-schema', {
- databaseUID: db.uid,
- schema: schema.name,
- table: table.name,
- })
- "
- />
- </HideInStandaloneMode>
- </div>
- </div>
-
- <ColumnList
- :db="db"
- :database="database"
- :schema="schema"
- :columns="table.columns"
- class="w-full flex-1 py-1"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { stringify } from "qs";
-import { computed } from "vue";
-import { UNKNOWN_ID, type ComposedDatabase } from "@/types";
-import { Engine } from "@/types/proto/v1/common";
-import type {
- DatabaseMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
-import { databaseV1Url } from "@/utils";
-import { useSQLEditorContext } from "@/views/sql-editor/context";
-import AlterSchemaButton from "./AlterSchemaButton.vue";
-import ColumnList from "./ColumnList.vue";
-import ExternalLinkButton from "./ExternalLinkButton.vue";
-import StringifyMetadataButton from "./StringifyMetadataButton.vue";
-
-const props = defineProps<{
- db: ComposedDatabase;
- database: DatabaseMetadata;
- schema: SchemaMetadata;
- table: TableMetadata;
-}>();
-
-const emit = defineEmits<{
- (e: "close"): void;
-}>();
-
-const { events: editorEvents } = useSQLEditorContext();
-
-const tableDetailLink = computed((): string => {
- const { db: database, schema, table } = props;
- const query: Record<string, string> = {
- table: table.name,
- };
- if (schema.name) {
- query.schema = schema.name;
- }
- const url = `${databaseV1Url(database)}?${stringify(query)}`;
-
- return url;
-});
-
-const showStringifyMetadataButton = computed(() => {
- const engine = props.db.instanceEntity.engine;
- return [Engine.MYSQL, Engine.POSTGRES, Engine.TIDB].includes(engine);
-});
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/context.ts b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/context.ts
deleted file mode 100644
index 08f79f1aef..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/context.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { InjectionKey, Ref } from "vue";
-import { inject, provide, ref } from "vue";
-
-export type SchemaPanelContext = {
- keyword: Ref<string>;
-};
-
-export const KEY = Symbol(
- "bb.sql-editor.schema-panel"
-) as InjectionKey<SchemaPanelContext>;
-
-export const useSchemaPanelContext = () => {
- return inject(KEY)!;
-};
-
-export const provideSchemaPanelContext = () => {
- const context: SchemaPanelContext = {
- keyword: ref(""),
- };
-
- provide(KEY, context);
-
- return context;
-};
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/index.ts b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/index.ts
deleted file mode 100644
index 0715cc5e56..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/SchemaPanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import SchemaPanel from "./SchemaPanel.vue";
-
-export default SchemaPanel;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/index.ts b/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/index.ts
deleted file mode 100644
index 7ad7e5e4d9..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/InfoTabPane/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import InfoTabPane from "./InfoTabPane.vue";
-
-export default InfoTabPane;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue b/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue
deleted file mode 100644
index 586e1b4825..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/SecondaryGutterBar.vue
+++ /dev/null
@@ -1,124 +0,0 @@
-<template>
- <div class="h-full flex flex-col items-stretch justify-between text-sm pb-1">
- <div class="divide-y border-b">
- <div
- v-if="showInfoPane"
- class="gutter-bar--tab writing-vertical-rl"
- :class="[activeTab === 'INFO' && 'gutter-bar--tab-active']"
- @click="handleClickTab('INFO')"
- >
- {{ $t("common.info") }}
- </div>
- <div
- class="gutter-bar--tab writing-vertical-rl"
- :class="[activeTab === 'SHEET' && 'gutter-bar--tab-active']"
- @click="handleClickTab('SHEET')"
- >
- {{ $t("sheet.sheet") }}
- </div>
- <div
- class="gutter-bar--tab writing-vertical-rl"
- :class="[activeTab === 'HISTORY' && 'gutter-bar--tab-active']"
- @click="handleClickTab('HISTORY')"
- >
- {{ $t("common.history") }}
- </div>
- </div>
-
- <OpenAIButton class="self-center" />
- </div>
-</template>
-
-<script setup lang="ts">
-import { storeToRefs } from "pinia";
-import { computed, watch } from "vue";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useCurrentUserV1,
- useSQLEditorTabStore,
-} from "@/store";
-import { UNKNOWN_ID } from "@/types";
-import { hasProjectPermissionV2, instanceV1HasAlterSchema } from "@/utils";
-import type { TabView } from "../context";
-import { useSecondarySidebarContext } from "../context";
-import OpenAIButton from "./OpenAIButton.vue";
-
-const { show, tab } = useSecondarySidebarContext();
-
-const me = useCurrentUserV1();
-const activeTab = computed(() => {
- if (!show.value) {
- return undefined;
- }
- return tab.value;
-});
-
-const tabStore = useSQLEditorTabStore();
-const { currentTab, isDisconnected } = storeToRefs(tabStore);
-const { instance, database } = useConnectionOfCurrentSQLEditorTab();
-
-const isSchemalessInstance = computed(() => {
- if (!currentTab.value) {
- return false;
- }
- if (isDisconnected.value) {
- return false;
- }
- if (instance.value.uid === String(UNKNOWN_ID)) {
- return false;
- }
-
- return !instanceV1HasAlterSchema(instance.value);
-});
-
-const showInfoPane = computed(() => {
- if (!currentTab.value) {
- return false;
- }
- if (isDisconnected.value) {
- return false;
- }
-
- if (isSchemalessInstance.value) {
- return false;
- }
- if (database.value.uid === String(UNKNOWN_ID)) {
- return false;
- }
-
- return hasProjectPermissionV2(
- database.value.projectEntity,
- me.value,
- "bb.databases.getSchema"
- );
-});
-
-const handleClickTab = (target: TabView) => {
- if (target === activeTab.value) {
- show.value = false;
- return;
- }
-
- tab.value = target;
- show.value = true;
-};
-
-watch(
- showInfoPane,
- (show) => {
- if (!show && tab.value === "INFO") {
- tab.value = "SHEET";
- }
- },
- { immediate: true }
-);
-</script>
-
-<style lang="postcss" scoped>
-.gutter-bar--tab {
- @apply px-1 py-4 bg-white cursor-pointer select-none;
-}
-.gutter-bar--tab.gutter-bar--tab-active {
- @apply bg-gray-100;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/index.ts b/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/index.ts
deleted file mode 100644
index 106d8c9b16..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/SecondaryGutterBar/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import SecondaryGutterBar from "./SecondaryGutterBar.vue";
-
-export default SecondaryGutterBar;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SecondarySidebar.vue b/frontend/src/views/sql-editor/SecondarySidebar/SecondarySidebar.vue
deleted file mode 100644
index 3dcd4b66f5..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/SecondarySidebar.vue
+++ /dev/null
@@ -1,16 +0,0 @@
-<template>
- <div class="h-full">
- <InfoTabPane v-if="tab === 'INFO'" />
- <SheetTabPane v-if="tab === 'SHEET'" />
- <HistoryTabPane v-if="tab === 'HISTORY'" />
- </div>
-</template>
-
-<script setup lang="ts">
-import HistoryTabPane from "./HistoryTabPane";
-import InfoTabPane from "./InfoTabPane";
-import SheetTabPane from "./SheetTabPane";
-import { useSecondarySidebarContext } from "./context";
-
-const { tab } = useSecondarySidebarContext();
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/index.ts b/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/index.ts
deleted file mode 100644
index 55a7037ee0..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/SheetTabPane/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import SheetTabPane from "./SheetTabPane.vue";
-
-export default SheetTabPane;
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/ToggleSecondarySidebarButton.vue b/frontend/src/views/sql-editor/SecondarySidebar/ToggleSecondarySidebarButton.vue
deleted file mode 100644
index 8fba8c75ca..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/ToggleSecondarySidebarButton.vue
+++ /dev/null
@@ -1,20 +0,0 @@
-<template>
- <NButton
- size="small"
- style="--n-height: 24px; --n-padding: 0 4px"
- :type="showSecondarySidebar ? 'info' : 'default'"
- ghost
- @click="showSecondarySidebar = !showSecondarySidebar"
- >
- <template #icon>
- <heroicons:view-columns />
- </template>
- </NButton>
-</template>
-
-<script setup lang="ts">
-import { NButton } from "naive-ui";
-import { useSecondarySidebarContext } from "./context";
-
-const { show: showSecondarySidebar } = useSecondarySidebarContext();
-</script>
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/context.ts b/frontend/src/views/sql-editor/SecondarySidebar/context.ts
deleted file mode 100644
index 1c70d6f873..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/context.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import Emittery from "emittery";
-import type { InjectionKey, Ref } from "vue";
-import { inject, provide, ref } from "vue";
-
-type SecondarySidebarEvents = Emittery<{
- // nothing by now
-}>;
-
-export type TabView = "INFO" | "SHEET" | "HISTORY";
-
-export type SecondarySidebarContext = {
- show: Ref<boolean>; // Whether to show the panel
- tab: Ref<TabView>;
-
- events: SecondarySidebarEvents;
-};
-
-export const KEY = Symbol(
- "bb.sql-editor.secondary-sidebar"
-) as InjectionKey<SecondarySidebarContext>;
-
-export const useSecondarySidebarContext = () => {
- return inject(KEY)!;
-};
-
-export const provideSecondarySidebarContext = () => {
- const context: SecondarySidebarContext = {
- show: ref(true),
- tab: ref("INFO"),
- events: new Emittery(),
- };
-
- provide(KEY, context);
-
- return context;
-};
diff --git a/frontend/src/views/sql-editor/SecondarySidebar/index.ts b/frontend/src/views/sql-editor/SecondarySidebar/index.ts
deleted file mode 100644
index 81c106e85a..0000000000
--- a/frontend/src/views/sql-editor/SecondarySidebar/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import SecondaryGutterBar from "./SecondaryGutterBar";
-import SecondarySidebar from "./SecondarySidebar.vue";
-import ToggleSecondarySidebarButton from "./ToggleSecondarySidebarButton.vue";
-
-export * from "./context";
-export { ToggleSecondarySidebarButton, SecondaryGutterBar };
-export default SecondarySidebar;
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
index 9b76e17798..7083f99cb8 100644
--- a/frontend/src/views/sql-editor/context.ts
+++ b/frontend/src/views/sql-editor/context.ts
@@ -3,12 +3,8 @@ import type { InjectionKey, Ref } from "vue";
import { inject, provide, ref } from "vue";
import { useSQLEditorStore } from "@/store";
import type { ComposedDatabase, SQLEditorTab } from "@/types";
-import type {
- DatabaseMetadata,
- ExternalTableMetadata,
- SchemaMetadata,
- TableMetadata,
-} from "@/types/proto/v1/database_service";
+
+export type AsidePanelTab = "CONNECTION" | "SCHEMA" | "WORKSHEET" | "HISTORY";
type SQLEditorEvents = Emittery<{
"save-sheet": { tab: SQLEditorTab; editTitle?: boolean };
@@ -24,18 +20,16 @@ type SQLEditorEvents = Emittery<{
};
}>;
-export type SelectedDatabaseSchema = {
- db: ComposedDatabase;
- database: DatabaseMetadata;
- schema: SchemaMetadata;
- table?: TableMetadata;
- externalTable?: ExternalTableMetadata;
-};
-
export type SQLEditorContext = {
+ asidePanelTab: Ref<AsidePanelTab>;
showAIChatBox: Ref<boolean>;
- selectedDatabaseSchemaByDatabaseName: Ref<
- Map<string, SelectedDatabaseSchema>
+ schemaViewer: Ref<
+ | {
+ database: ComposedDatabase;
+ schema?: string;
+ table?: string;
+ }
+ | undefined
>;
events: SQLEditorEvents;
@@ -54,8 +48,9 @@ export const useSQLEditorContext = () => {
export const provideSQLEditorContext = () => {
const editorStore = useSQLEditorStore();
const context: SQLEditorContext = {
+ asidePanelTab: ref("WORKSHEET"),
showAIChatBox: ref(false),
- selectedDatabaseSchemaByDatabaseName: ref(new Map()),
+ schemaViewer: ref(undefined),
events: new Emittery(),
maybeSwitchProject: (project) => {
diff --git a/frontend/tsconfig.vitest.json b/frontend/tsconfig.vitest.json
index 30025f0fb3..90bb941886 100644
--- a/frontend/tsconfig.vitest.json
+++ b/frontend/tsconfig.vitest.json
@@ -1,5 +1,6 @@
{
"extends": "./tsconfig.app.json",
+ "includes": ["src/**/__tests__/*"],
"exclude": [],
"compilerOptions": {
"composite": true,
@@ -9,6 +10,10 @@
"lib": ["WebWorker", "ES2022"],
"types": ["node", "jsdom", "unplugin-icons/types/vue", "vite/client"],
"jsx": "preserve",
- "jsxImportSource": "vue"
+ "jsxImportSource": "vue",
+ "paths": {
+ "@/*": ["./src/*"],
+ "@sql-lsp/*": ["./src/plugins/sql-lsp/*"]
+ }
}
}