Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: select single database group for query (#18430)
ecmadao80fcb24cf705
diff --git a/backend/api/v1/worksheet_service.go b/backend/api/v1/worksheet_service.goindex e1c693286b..feceebf52f 100644--- a/backend/api/v1/worksheet_service.go+++ b/backend/api/v1/worksheet_service.go@@ -254,14 +254,20 @@ func (s *WorksheetService) UpdateWorksheet(stringVisibility := string(visibility)worksheetPatch.Visibility = &stringVisibilitycase "database":- database, err := getDatabaseMessage(ctx, s.store, request.Worksheet.Database)- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to found database %v", request.Worksheet.Database))- }- if database == nil || database.Deleted {- return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %v not found", request.Worksheet.Database))+ if request.Worksheet.Database != "" {+ database, err := getDatabaseMessage(ctx, s.store, request.Worksheet.Database)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to found database %v", request.Worksheet.Database))+ }+ if database == nil || database.Deleted {+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("database %v not found", request.Worksheet.Database))+ }+ worksheetPatch.InstanceID, worksheetPatch.DatabaseName = &database.InstanceID, &database.DatabaseName+ } else {+ emptyStr := ""+ worksheetPatch.InstanceID = &emptyStr+ worksheetPatch.DatabaseName = &emptyStr}- worksheetPatch.InstanceID, worksheetPatch.DatabaseName = &database.InstanceID, &database.DatabaseNamedefault:return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid update mask path %q", path))}diff --git a/backend/store/worksheet.go b/backend/store/worksheet.goindex 2be44c8f84..ec08ee9e62 100644--- a/backend/store/worksheet.go+++ b/backend/store/worksheet.go@@ -144,6 +144,7 @@ func (s *Store) ListWorkSheets(ctx context.Context, find *FindWorkSheetMessage,var sheets []*WorkSheetMessagefor rows.Next() {var sheet WorkSheetMessage+ var instanceID, databaseName sql.NullStringvar payloadBytes []byteif err := rows.Scan(&sheet.UID,@@ -151,8 +152,8 @@ func (s *Store) ListWorkSheets(ctx context.Context, find *FindWorkSheetMessage,&sheet.CreatedAt,&sheet.UpdatedAt,&sheet.ProjectID,- &sheet.InstanceID,- &sheet.DatabaseName,+ &instanceID,+ &databaseName,&sheet.Title,&sheet.Statement,&sheet.Visibility,@@ -161,6 +162,12 @@ func (s *Store) ListWorkSheets(ctx context.Context, find *FindWorkSheetMessage,); err != nil {return nil, err}+ if instanceID.Valid {+ sheet.InstanceID = &instanceID.String+ }+ if databaseName.Valid {+ sheet.DatabaseName = &databaseName.String+ }var payload storepb.WorkSheetOrganizerPayloadif err := common.ProtojsonUnmarshaler.Unmarshal(payloadBytes, &payload); err != nil {@@ -291,10 +298,18 @@ func patchWorkSheetImpl(ctx context.Context, txn *sql.Tx, patch *PatchWorkSheetMset.Comma("visibility = ?", *v)}if v := patch.InstanceID; v != nil {- set.Comma("instance = ?", *v)+ if *v == "" {+ set.Comma("instance = ?", nil)+ } else {+ set.Comma("instance = ?", *v)+ }}if v := patch.DatabaseName; v != nil {- set.Comma("db_name = ?", *v)+ if *v == "" {+ set.Comma("db_name = ?", nil)+ } else {+ set.Comma("db_name = ?", *v)+ }}query, args, err := qb.Q().Space("UPDATE worksheet SET ? WHERE id = ?", set, patch.UID).ToSQL()diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vueindex acef9d7ab0..127b5b82b5 100644--- a/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vue+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vue@@ -10,7 +10,7 @@:row-key="(data: DatabaseGroup) => data.name":checked-row-keys="selectedDatabaseGroupNames":row-props="rowProps"- :pagination="{ pageSize: 20 }"+ :pagination="{ pageSize }":paginate-single-page="false"@update:checked-row-keys="(val) => $emit('update:selected-database-group-names', val as string[])@@ -41,10 +41,12 @@ const props = withDefaults(showSelection?: boolean;showExternalLink?: boolean;singleSelection?: boolean;+ pageSize?: number;selectedDatabaseGroupNames?: string[];}>(),{bordered: true,+ pageSize: 20,selectedDatabaseGroupNames: () => [],});@@ -77,13 +79,7 @@ const columnList = computed((): DatabaseGroupDataTableColumn[] => {width: 256,ellipsis: true,resizable: true,- render: (data) => {- return (- <div class="flex gap-x-2">- <span>{data.title}</span>- </div>- );- },+ render: (data) => data.title,},{key: "expression",diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex fa2166799e..d7b78f10d6 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -136,9 +136,7 @@ const initializeProject = async () => {};const switchWorksheet = async (sheetName: string) => {- const openedSheetTab = tabStore.openTabList.find(- (tab) => tab.worksheet == sheetName- );+ const openedSheetTab = tabStore.getTabByWorksheet(sheetName);const sheet = await worksheetStore.getOrFetchWorksheetByName(sheetName);if (!sheet) {diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.tsindex 8110da2612..5545e55151 100644--- a/frontend/src/composables/useExecuteSQL.ts+++ b/frontend/src/composables/useExecuteSQL.ts@@ -228,7 +228,7 @@ const useExecuteSQL = () => {dataSourceId: getDataSourceId(database,params.connection,- isBatch ? tab.batchQueryContext?.dataSourceType : undefined+ isBatch ? tab.batchQueryContext.dataSourceType : undefined),},}),diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex c485cdabe4..4aa8b19f2c 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2125,7 +2125,6 @@},"batch-query": {"batch": "Batch",- "select-database-group": "You can {select-database-group} to batch query","description": "Batch query {database} additional databases and {group} database groups under {project}.","show-or-hide-empty-query-results": "Show / hide empty query results","select-data-source": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex f38ce076e5..98dfb3045c 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2124,7 +2124,6 @@},"batch-query": {"batch": "Lote",- "select-database-group": "Puedes {select-database-group} realizar consultas por lotes","description": "Consulta por lotes {database} bases de datos adicionales y {group} grupos de bases de datos bajo {project}.","show-or-hide-empty-query-results": "Mostrar/ocultar resultados de consulta vacíos","select-data-source": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 15d510e404..ebac530d2f 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2124,7 +2124,6 @@},"batch-query": {"batch": "バッチ",- "select-database-group": "バッチクエリを実行するには{select-database-group}を使用します","description": "{project} の下の {database} 個の追加データベースと {group} 個のデータベース グループに対してバッチ クエリを実行します。","show-or-hide-empty-query-results": "空のクエリ結果の表示/非表示","select-data-source": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex f1de15da8a..08f0a8d031 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2124,7 +2124,6 @@},"batch-query": {"batch": "Hàng loạt",- "select-database-group": "Bạn có thể {select-database-group} để truy vấn hàng loạt","description": "Truy vấn hàng loạt {database} cơ sở dữ liệu bổ sung và {group} nhóm cơ sở dữ liệu trong {project}.","show-or-hide-empty-query-results": "Hiển thị / ẩn kết quả truy vấn trống","select-data-source": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b6bab347e2..2e80e2ce82 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2124,7 +2124,6 @@},"batch-query": {"batch": "批量",- "select-database-group": "您可以{select-database-group}进行批量查询","description": "批量查询 {project} 下的 {database} 个数据库和 {group} 个数据库组。","show-or-hide-empty-query-results": "显示/隐藏空查询结果","select-data-source": {diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.tsindex 5edab349e4..63e8fc45c0 100644--- a/frontend/src/store/modules/sqlEditor/tab.ts+++ b/frontend/src/store/modules/sqlEditor/tab.ts@@ -133,6 +133,10 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {});});+ const getTabByWorksheet = (worksheet: string) => {+ return openTabList.value.find((item) => item.worksheet === worksheet);+ };+const currentTab = computed(() => {const currId = currentTabId.value;if (!currId) return undefined;@@ -169,7 +173,10 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {* @param beside `true` to add the tab beside currentTab, `false` to add the tab to the last, default to `false`* @returns the tab*/- const addTab = (payload?: Partial<SQLEditorTab>, beside = false) => {+ const addTab = (+ payload?: Partial<SQLEditorTab>,+ beside = false+ ): SQLEditorTab => {const defaultTab: SQLEditorTab = {...defaultSQLEditorTab(),...omitBy(payload, isUndefined),@@ -247,17 +254,21 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {}};- const updateTab = (id: string, payload: Partial<SQLEditorTab>) => {+ const updateTab = (+ id: string,+ payload: Partial<SQLEditorTab>+ ): SQLEditorTab | undefined => {const tab = getTabById(id);if (!tab) return;Object.assign(tab, payload);upsertCache(tab);+ return tab;};const updateCurrentTab = (payload: Partial<SQLEditorTab>) => {const id = currentTabId.value;if (!id) return;- updateTab(id, payload);+ return updateTab(id, payload);};const updateBatchQueryContext = (payload: Partial<BatchQueryContext>) => {@@ -265,9 +276,8 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {if (!tab) {return;}- updateTab(tab.id, {+ return updateTab(tab.id, {batchQueryContext: {- databases: tab.batchQueryContext?.databases ?? [],dataSourceType:tab.batchQueryContext?.dataSourceType ?? DataSourceType.READ_ONLY,...tab.batchQueryContext,@@ -385,6 +395,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {project,initProject,getTabById,+ getTabByWorksheet,openTabList,currentTabId,currentTab,diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.tsindex 6144042c70..da75ce1c32 100644--- a/frontend/src/types/sqlEditor/tab.ts+++ b/frontend/src/types/sqlEditor/tab.ts@@ -78,7 +78,7 @@ export type SQLEditorTab = {string /* database or instance */,SQLEditorDatabaseQueryContext[]>;- batchQueryContext?: BatchQueryContext;+ batchQueryContext: BatchQueryContext;// extended fieldstreeState: {diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.tsindex e82927c441..298cc914a6 100644--- a/frontend/src/utils/sqlEditor.ts+++ b/frontend/src/utils/sqlEditor.ts@@ -44,6 +44,9 @@ export const defaultSQLEditorTab = (): SQLEditorTab => {selection: null,},viewState: defaultViewState(),+ batchQueryContext: {+ databases: [],+ },};};@@ -58,7 +61,7 @@ export const emptySQLEditorConnection = (): SQLEditorConnection => {};};-export const getConnectionForSQLEditorTab = (tab: SQLEditorTab) => {+export const getConnectionForSQLEditorTab = (tab?: SQLEditorTab) => {const target: {instance: InstanceResource | undefined;database: ComposedDatabase | undefined;@@ -66,6 +69,9 @@ export const getConnectionForSQLEditorTab = (tab: SQLEditorTab) => {instance: undefined,database: undefined,};+ if (!tab) {+ return target;+ }const { connection } = tab;if (connection.database) {const database = useDatabaseV1Store().getDatabaseByName(diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.tsindex 45f80862cf..f9f666662e 100644--- a/frontend/src/utils/v1/database.ts+++ b/frontend/src/utils/v1/database.ts@@ -4,7 +4,11 @@ import {instanceNamePrefix,} from "@/store/modules/v1/common";import type { ComposedDatabase, QueryPermission } from "@/types";-import { QueryPermissionQueryAny, UNKNOWN_ID } from "@/types";+import {+ isValidDatabaseName,+ QueryPermissionQueryAny,+ UNKNOWN_ID,+} from "@/types";import { hasWorkspacePermissionV2 } from "../iam";import { extractProjectResourceName } from "./project";@@ -52,6 +56,10 @@ export const isDatabaseV1Queryable = (schema?: string,table?: string): boolean => {+ if (!isValidDatabaseName(database.name)) {+ return false;+ }+if (permissions.some((permission) => hasWorkspacePermissionV2(permission))) {return true;}diff --git a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vueindex 7535b61366..76884f4920 100644--- a/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue+++ b/frontend/src/views/sql-editor/AsidePanel/WorksheetPane/SheetList/SheetTree.vue@@ -62,7 +62,6 @@</template><script setup lang="tsx">-import { create } from "@bufbuild/protobuf";import { useDebounceFn } from "@vueuse/core";import {NDropdown,@@ -86,10 +85,6 @@ import {useWorkSheetStore,} from "@/store";import { DEBOUNCE_SEARCH_DELAY } from "@/types";-import {- Worksheet_Visibility,- WorksheetSchema,-} from "@/types/proto-es/v1/worksheet_service_pb";import { defer, isDescendantOf } from "@/utils";import { useSQLEditorContext } from "@/views/sql-editor/context";import SharePopover from "@/views/sql-editor/EditorCommon/SharePopover.vue";@@ -132,7 +127,6 @@ const {selectedKeys,expandedKeys,editingNode,- isWorksheetCreator,batchUpdateWorksheetFolders,} = useSheetContext();const {@@ -275,9 +269,7 @@ const handleRenameNode = useDebounceFn(async () => {);// update tab title- const tab = tabStore.openTabList.find(- (t) => t.worksheet === editingNode.value?.node.worksheet?.name- );+ const tab = tabStore.getTabByWorksheet(worksheet.name);if (tab) {tabStore.updateTab(tab.id, {title: newTitle,@@ -398,7 +390,7 @@ const deleteWorksheets = async (worksheets: string[]) => {));for (const worksheet of worksheets) {- const tab = tabStore.openTabList.find((tab) => tab.worksheet === worksheet);+ const tab = tabStore.getTabByWorksheet(worksheet);if (tab) {tabStore.closeTab(tab.id);}@@ -527,25 +519,11 @@ const handleDuplicateSheet = async (worksheetName: string) => {closeOnEsc: true,async onPositiveClick() {dialogInstance.loading = true;- const newWorksheet = await worksheetV1Store.createWorksheet(- create(WorksheetSchema, {- title: worksheet.title,- project: worksheet.project,- content: worksheet.content,- database: worksheet.database,- visibility: Worksheet_Visibility.PRIVATE,- })- );- const isCreator = isWorksheetCreator(worksheet);- if (isCreator) {- await worksheetV1Store.upsertWorksheetOrganizer(- {- worksheet: newWorksheet.name,- folders: worksheet.folders,- },- ["folders"]- );- }+ await editorContext.createWorksheet({+ title: worksheet.title,+ folders: worksheet.folders,+ database: worksheet.database,+ });pushNotification({module: "bytebase",style: "INFO",diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/BatchQueryDatabaseGroupSelector.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/BatchQueryDatabaseGroupSelector.vuedeleted file mode 100644index fe2a35523b..0000000000--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/BatchQueryDatabaseGroupSelector.vue+++ /dev/null@@ -1,147 +0,0 @@-<template>- <NPopover- v-if="showBatchQuerySelector && hasBatchQueryFeature"- placement="bottom"- :disabled="!hasDatabaseGroupFeature"- trigger="click"- >- <template #trigger>- <NButton- size="small"- :type="- state.selectedDatabaseGroupNames.length > 0 && hasDatabaseGroupFeature- ? 'primary'- : 'default'- "- style="--n-padding: 0 5px"- @click="handleTriggerClick"- >- <span>{{ $t("database-group.select") }}</span>- <template #icon>- <BoxesIcon class="w-4 h-4" />- </template>- </NButton>- </template>- <div- class="max-w-[calc(100vw-10rem)] w-192 max-h-128 overflow-y-auto p-1 pb-2"- >- <div class="w-full flex flex-row justify-between items-center mb-3">- <p class="textinfolabel">- {{ $t("database-group.select") }}- </p>- <SearchBox- v-model:value="state.keyword"- :placeholder="$t('common.filter-by-name')"- />- </div>- <DatabaseGroupDataTable- :database-group-list="filteredDbGroupList"- :single-selection="false"- :show-selection="true"- :show-external-link="true"- :loading="!ready"- v-model:selected-database-group-names="state.selectedDatabaseGroupNames"- />- </div>- </NPopover>-- <FeatureModal- :feature="PlanFeature.FEATURE_DATABASE_GROUPS"- :open="state.showFeatureModal"- @cancel="state.showFeatureModal = false"- />-</template>--<script lang="ts" setup>-import { BoxesIcon } from "lucide-vue-next";-import { NButton, NPopover } from "naive-ui";-import { computed, reactive, watch } from "vue";-import DatabaseGroupDataTable from "@/components/DatabaseGroup/DatabaseGroupDataTable.vue";-import { FeatureModal } from "@/components/FeatureGuard";-import { SearchBox } from "@/components/v2";-import {- featureToRef,- useConnectionOfCurrentSQLEditorTab,- useDBGroupListByProject,- useSQLEditorStore,- useSQLEditorTabStore,-} from "@/store/modules";-import { isValidDatabaseName } from "@/types";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";--interface LocalState {- keyword: string;- showFeatureModal: boolean;- selectedDatabaseGroupNames: string[];-}--const tabStore = useSQLEditorTabStore();-const editorStore = useSQLEditorStore();--const state = reactive<LocalState>({- keyword: "",- showFeatureModal: false,- selectedDatabaseGroupNames: [],-});-// Save the stringified label key-value pairs.-const currentTab = computed(() => tabStore.currentTab);-const hasBatchQueryFeature = featureToRef(PlanFeature.FEATURE_BATCH_QUERY);-const hasDatabaseGroupFeature = featureToRef(- PlanFeature.FEATURE_DATABASE_GROUPS-);-const { database } = useConnectionOfCurrentSQLEditorTab();--const { dbGroupList, ready } = useDBGroupListByProject(- computed(() => editorStore.project),- DatabaseGroupView.FULL-);--const filteredDbGroupList = computed(() => {- const filter = state.keyword.trim().toLowerCase();- if (!filter) {- return dbGroupList.value;- }- return dbGroupList.value.filter((group) => {- return (- group.name.toLowerCase().includes(filter) ||- group.title.toLowerCase().includes(filter)- );- });-});--const showBatchQuerySelector = computed(() => {- const tab = currentTab.value;- return (- tab &&- // Only show entry when user connected to a database.- isValidDatabaseName(database.value.name) &&- tab.mode !== "ADMIN"- );-});--const handleTriggerClick = () => {- if (!hasDatabaseGroupFeature.value) {- state.showFeatureModal = true;- }-};--watch(- () => state.selectedDatabaseGroupNames,- () => {- tabStore.updateBatchQueryContext({- databaseGroups: state.selectedDatabaseGroupNames,- });- }-);--watch(- () => currentTab.value?.batchQueryContext?.databaseGroups,- (databaseGroups) => {- state.selectedDatabaseGroupNames = databaseGroups ?? [];- },- {- immediate: true,- }-);-</script>diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vueindex 9cf49c2519..78e03801b2 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue@@ -1,5 +1,5 @@<template>- <div class="sql-editor-tree gap-y-1 h-full flex flex-col relative">+ <div class="sql-editor-tree h-full relative"><div class="w-full px-4 mt-4" v-if="tabStore.supportBatchMode"><divclass="textinfolabel mb-2 w-full leading-4 flex flex-col items-start gap-x-1"@@ -8,33 +8,24 @@<FeatureBadge :feature="PlanFeature.FEATURE_BATCH_QUERY" />{{$t("sql-editor.batch-query.description", {- database: state.selectedDatabases.size,+ database: selectedDatabaseNames.length,group:- tabStore.currentTab?.batchQueryContext?.databaseGroups+ tabStore.currentTab?.batchQueryContext.databaseGroups?.length ?? 0,project: project.title,})}}</div>- <div class="flex items-center gap-x-1">- <i18n-t- v-if="hasDatabaseGroupFeature && tabStore.currentTab"- keypath="sql-editor.batch-query.select-database-group"- >- <template #select-database-group>- <BatchQueryDatabaseGroupSelector />- </template>- </i18n-t>- </div></div><divclass="w-full mt-1 flex flex-row justify-start items-start flex-wrap gap-2"><NTag- v-for="database in state.selectedDatabases"+ v-for="database in selectedDatabaseNames":key="database"- :closable="database !== tabStore.currentTab?.connection.database"- @close="() => handleUncheckDatabase(database)"+ :closable="true"+ :disabled="state.switchingConnection"+ @close="() => handleToggleDatabase(database, false)"><RichDatabaseName:database="databaseStore.getDatabaseByName(database)"@@ -45,6 +36,7 @@v-for="databaseGroupName in tabStore.currentTab?.batchQueryContext?.databaseGroups ?? []":key="databaseGroupName"+ :disabled="state.switchingConnection":database-group-name="databaseGroupName"@uncheck="handleUncheckDatabaseGroup"/>@@ -72,79 +64,103 @@</div></div><NDivider v-if="tabStore.currentTab" class="my-3!" />- <div class="flex flex-row gap-x-0.5 px-1 items-center">- <AdvancedSearch- v-model:params="state.params"- :autofocus="false"- :placeholder="$t('database.filter-database')"- :scope-options="scopeOptions"- :cache-query="false"- />- </div>- <div- ref="treeContainerElRef"- class="relative sql-editor-tree--tree flex-1 px-1 pb-1 text-sm select-none"- :data-height="treeContainerHeight"+ <NTabs+ v-model:value="state.selectionMode"+ type="line"+ animated+ size="small"+ class="px-4">- <template v-if="treeStore.state === 'READY'">- <NCheckbox- v-if="existEmptyEnvironment"- v-model:checked="state.showEmptyEnvironment"- >- {{ $t("sql-editor.show-empty-environments") }}- </NCheckbox>- <div- v-for="[environment, treeState] of treeByEnvironment.entries()"- :key="environment"- >+ <NTabPane name="DATABASE" :tab="$t('common.databases')">+ <div class="flex flex-col gap-y-1">+ <AdvancedSearch+ v-model:params="state.params"+ :autofocus="false"+ :placeholder="$t('database.filter-database')"+ :scope-options="scopeOptions"+ :cache-query="false"+ /><div- v-if="- !treeIsEmpty(treeState) ||- (state.showEmptyEnvironment &&- environment !== UNKNOWN_ENVIRONMENT_NAME)- "- class="flex flex-col gap-y-2 pt-2 pb-2"+ ref="treeContainerElRef"+ class="relative sql-editor-tree--tree flex-1 pb-1 text-sm select-none"+ :data-height="treeContainerHeight">- <NTree- :block-line="true"- :data="treeState.tree.value"- :show-irrelevant-nodes="false"- :selected-keys="selectedKeys"- :expand-on-click="true"- v-model:expanded-keys="treeState.expandedState.value.expandedKeys"- :node-props="nodeProps"- :theme-overrides="{ nodeHeight: '21px' }"- :render-label="renderLabel"- />- <div- v-if="- !!treeState.fetchDataState.value.nextPageToken &&- treeState.expandedState.value.expandedKeys.includes(- environment- ) &&- (!treeIsEmpty(treeState) ||- treeState.showMissingQueryDatabases.value)- "- class="w-full flex items-center justify-start pl-4"- >- <NButton- quaternary- :size="'small'"- :loading="treeState.fetchDataState.value.loading"- @click="- () =>- treeState- .fetchDatabases(filter)- .then(() => treeState.buildTree())- "+ <template v-if="treeStore.state === 'READY'">+ <NCheckbox+ v-if="existEmptyEnvironment"+ v-model:checked="state.showEmptyEnvironment"+ >+ {{ $t("sql-editor.show-empty-environments") }}+ </NCheckbox>+ <div+ v-for="[environment, treeState] of treeByEnvironment.entries()"+ :key="environment">- {{ $t("common.load-more") }}- </NButton>- </div>+ <div+ v-if="+ !treeIsEmpty(treeState) ||+ (state.showEmptyEnvironment &&+ environment !== UNKNOWN_ENVIRONMENT_NAME)+ "+ class="flex flex-col gap-y-2 pt-2 pb-2"+ >+ <NTree+ :block-line="true"+ :data="treeState.tree.value"+ :show-irrelevant-nodes="false"+ :selected-keys="selectedKeys"+ :expand-on-click="true"+ v-model:expanded-keys="treeState.expandedState.value.expandedKeys"+ :node-props="nodeProps"+ :theme-overrides="{ nodeHeight: '21px' }"+ :render-label="renderLabel"+ />+ <div+ v-if="+ !!treeState.fetchDataState.value.nextPageToken &&+ treeState.expandedState.value.expandedKeys.includes(+ environment+ ) &&+ (!treeIsEmpty(treeState) ||+ treeState.showMissingQueryDatabases.value)+ "+ class="w-full flex items-center justify-start pl-4"+ >+ <NButton+ quaternary+ :size="'small'"+ :loading="treeState.fetchDataState.value.loading"+ @click="+ () =>+ treeState+ .fetchDatabases(filter)+ .then(() => treeState.buildTree())+ "+ >+ {{ $t("common.load-more") }}+ </NButton>+ </div>+ </div>+ </div>+ </template></div></div>- </template>- </div>+ </NTabPane>+ <NTabPane name="DATABASE-GROUP" :tab="$t('common.database-group')" :disabled="!hasDatabaseGroupFeature || !hasBatchQueryFeature">+ <template #tab>+ <NTooltip :disabled="hasBatchQueryFeature && hasDatabaseGroupFeature">+ <template #trigger>+ {{ $t('common.database-group') }}+ </template>+ {{ $t("subscription.contact-to-upgrade") }}+ </NTooltip>+ </template>+ <DatabaseGroupTable+ :database-group-names="selectedDatabaseGroupNames"+ @update:database-group-names="onDatabaseGroupSelectionUpdate"+ />+ </NTabPane>+ </NTabs><NDropdownv-if="treeStore.state === 'READY'"@@ -158,7 +174,7 @@@select="handleDropdownSelect"/>- <DatabaseHoverPanel :offset-x="4" :offset-y="4" :margin="4" />+ <DatabaseHoverPanel :offset-x="10" :offset-y="4" :margin="4" /><MaskSpinner v-if="treeStore.state !== 'READY'" class="bg-white/75!"><span class="text-control text-sm">{{@@ -168,15 +184,16 @@</div><FeatureModal- :feature="PlanFeature.FEATURE_BATCH_QUERY"- :open="state.showFeatureModal"- @cancel="state.showFeatureModal = false"+ v-if="state.missingFeature"+ :feature="state.missingFeature"+ :open="!!state.missingFeature"+ @cancel="state.missingFeature = undefined"/></template><script lang="ts" setup>import { useElementSize } from "@vueuse/core";-import { isEqual } from "lodash-es";+import { cloneDeep } from "lodash-es";import { InfoIcon } from "lucide-vue-next";import {NButton,@@ -185,6 +202,8 @@ import {NDropdown,NRadio,NRadioGroup,+ NTabPane,+ NTabs,NTag,NTooltip,NTree,@@ -216,6 +235,7 @@ import {} from "@/store";import { instanceNamePrefix } from "@/store/modules/v1/common";import type {+ BatchQueryContext,ComposedDatabase,QueryDataSourceType,SQLEditorTreeNode,@@ -234,9 +254,9 @@ import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import type { SearchParams } from "@/utils";import {CommonFilterScopeIdList,- emptySQLEditorConnection,extractProjectResourceName,findAncestor,+ getConnectionForSQLEditorTab,getValueFromSearchParams,getValuesFromSearchParams,isDatabaseV1Queryable,@@ -245,7 +265,7 @@ import {} from "@/utils";import { useSQLEditorContext } from "../../context";import { setConnection, useDropdown } from "./actions";-import BatchQueryDatabaseGroupSelector from "./BatchQueryDatabaseGroupSelector.vue";+import DatabaseGroupTable from "./DatabaseGroupTable.vue";import DatabaseGroupTag from "./DatabaseGroupTag.vue";import {DatabaseHoverPanel,@@ -255,13 +275,18 @@ import { Label } from "./TreeNode";import { type TreeByEnvironment, useSQLEditorTreeByEnvironment } from "./tree";interface LocalState {- selectedDatabases: Set<string>;params: SearchParams;- showFeatureModal: boolean;+ missingFeature?: PlanFeature;showEmptyEnvironment: boolean;batchQueryDataSourceType?: QueryDataSourceType;+ selectionMode: "DATABASE" | "DATABASE-GROUP";+ switchingConnection: boolean;}+const props = defineProps<{+ show: boolean;+}>();+const treeStore = useSQLEditorTreeStore();const tabStore = useSQLEditorTabStore();const editorStore = useSQLEditorStore();@@ -300,16 +325,128 @@ const hasDatabaseGroupFeature = featureToRef();const state = reactive<LocalState>({- selectedDatabases: new Set(),params: {query: "",scopes: [],},- showFeatureModal: false,showEmptyEnvironment: false,batchQueryDataSourceType: DataSourceType.READ_ONLY,+ selectionMode: "DATABASE",+ switchingConnection: false,+});++const selectedDatabaseGroupNames = computed(+ () => tabStore.currentTab?.batchQueryContext.databaseGroups ?? []+);++const selectedDatabaseNames = computed(() => {+ const currentTab = tabStore.currentTab;+ const databases = currentTab?.batchQueryContext.databases ?? [];+ if (databases.length === 0 && selectedDatabaseGroupNames.value.length === 0) {+ if (currentTab?.connection.database) {+ databases.push(currentTab?.connection.database);+ }+ }+ return databases;});+watch(+ () => props.show,+ (show) => {+ if (show) {+ if (selectedDatabaseNames.value.length > 0) {+ state.selectionMode = "DATABASE";+ } else if (selectedDatabaseGroupNames.value.length > 0) {+ state.selectionMode = "DATABASE-GROUP";+ } else {+ state.selectionMode = "DATABASE";+ }+ }+ },+ { immediate: true }+);++const onBatchQueryContextChange = async (+ batchQueryContext: BatchQueryContext+) => {+ state.switchingConnection = true;++ try {+ const queryableDatabase = await getQueryableDatabase(batchQueryContext);+ const currentConnection = getConnectionForSQLEditorTab(tabStore.currentTab);++ if (+ !currentConnection.database?.name ||+ currentConnection.database?.name !== queryableDatabase?.name+ ) {+ // switch connection when:+ // - no connection+ // - no current tab+ // - current tab doesn't have valid connection+ // - or connection changed+ setConnection({+ database: queryableDatabase,+ mode: "WORKSHEET",+ newTab: false,+ context: editorContext,+ batchQueryContext,+ });+ } else {+ tabStore.updateBatchQueryContext(batchQueryContext);+ }+ } finally {+ state.switchingConnection = false;+ }+};++const getQueryableDatabase = async (batchQueryContext: BatchQueryContext) => {+ for (const databaseName of batchQueryContext.databases) {+ const database = databaseStore.getDatabaseByName(databaseName);+ if (isDatabaseV1Queryable(database)) {+ return database;+ }+ }++ for (const databaseGroupName of batchQueryContext.databaseGroups ?? []) {+ const databaseGroup = dbGroupStore.getDBGroupByName(databaseGroupName);+ for (const matchedDatabase of databaseGroup.matchedDatabases) {+ const database = await databaseStore.getOrFetchDatabaseByName(+ matchedDatabase.name+ );+ if (isDatabaseV1Queryable(database)) {+ return database;+ }+ }+ }+};++const onDatabaseSelectionUpdate = async (databases: string[]) => {+ const batchQueryContext: BatchQueryContext = cloneDeep({+ ...tabStore.currentTab?.batchQueryContext,+ databases,+ });+ await onBatchQueryContextChange(batchQueryContext);+};++const onDatabaseGroupSelectionUpdate = async (databaseGroups: string[]) => {+ if (databaseGroups.length > 0) {+ if (!hasBatchQueryFeature) {+ state.missingFeature = PlanFeature.FEATURE_BATCH_QUERY;+ return;+ }+ if (!hasDatabaseGroupFeature) {+ state.missingFeature = PlanFeature.FEATURE_DATABASE_GROUPS;+ return;+ }+ }++ const batchQueryContext: BatchQueryContext = cloneDeep({+ ...(tabStore.currentTab?.batchQueryContext ?? { databases: [] }),+ databaseGroups,+ });+ await onBatchQueryContextChange(batchQueryContext);+};+const flattenSelectedDatabasesFromGroup = computed(() => {const nameMap = new Map<string /* database name */,@@ -368,47 +505,35 @@ watch(if (!tabStore.currentTab) {return;}- const databases = tabStore.currentTab.batchQueryContext?.databases ?? [];- databases.push(tabStore.currentTab.connection.database);+ const databases = tabStore.currentTab.batchQueryContext.databases ?? [];await batchGetOrFetchDatabases(databases);- state.selectedDatabases = new Set(databases.filter(isValidDatabaseName));},{immediate: true,});-watch(- () => [...state.selectedDatabases],- (selectedDatabases) => {- // If the current tab is not connected to any database, we need to connect it to the first selected database.- if (- (!tabStore.currentTab ||- isEqual(emptySQLEditorConnection(), tabStore.currentTab.connection)) &&- selectedDatabases.length > 0- ) {- const database = databaseStore.getDatabaseByName(selectedDatabases[0]);- setConnection(database, {- newTab: false,- context: editorContext,- });+const handleToggleDatabase = async (database: string, check: boolean) => {+ let databases: string[] = [...selectedDatabaseNames.value];+ if (check) {+ if (!databases.includes(database)) {+ databases.push(database);}- tabStore.updateBatchQueryContext({- databases: selectedDatabases,- });+ if (databases.length > 1 && !hasBatchQueryFeature.value) {+ state.missingFeature = PlanFeature.FEATURE_BATCH_QUERY;+ return;+ }+ } else {+ databases = selectedDatabaseNames.value.filter((db) => db !== database);}-);--const handleUncheckDatabase = (database: string) => {- state.selectedDatabases.delete(database);+ await onDatabaseSelectionUpdate(databases);};-const handleUncheckDatabaseGroup = (databaseGroupName: string) => {- tabStore.updateBatchQueryContext({- databaseGroups: (- tabStore.currentTab?.batchQueryContext?.databaseGroups ?? []- ).filter((name) => name !== databaseGroupName),- });+const handleUncheckDatabaseGroup = async (databaseGroupName: string) => {+ const databaseGroups = selectedDatabaseGroupNames.value.filter(+ (name) => name !== databaseGroupName+ );+ await onDatabaseGroupSelectionUpdate(databaseGroups);};const scopeOptions = useCommonSearchScopeOptions([@@ -481,16 +606,20 @@ const connect = (node: SQLEditorTreeNode) => {if (!isDatabaseV1Queryable(database)) {return;}- setConnection(database, {++ const batchQueryDatabases = [+ ...selectedDatabaseGroupNames.value,+ database.name,+ ].filter(isValidDatabaseName);+ setConnection({+ database,mode: tabStore.currentTab?.mode,newTab: false,context: editorContext,+ batchQueryContext: {+ databases: [...new Set(batchQueryDatabases)],+ },});- if (tabStore.currentTab?.batchQueryContext?.databases.length === 1) {- tabStore.updateBatchQueryContext({- databases: [],- });- }showConnectionPanel.value = false;};@@ -505,16 +634,17 @@ const renderLabel = ({ option }: { option: TreeOption }) => {const checkedByGroup =flattenSelectedDatabasesFromGroup.value.get(databaseName);let checkTooltip = "";- if (tabStore.currentTab?.connection.database === databaseName) {- checkTooltip = t("sql-editor.current-connection");- } else if (!!checkedByGroup) {+ if (!!checkedByGroup) {checkTooltip = t("sql-editor.matched-in-group", { title: checkedByGroup });+ } else if (tabStore.currentTab?.connection.database === databaseName) {+ checkTooltip = t("sql-editor.current-connection");}return h(Label, {node,- checked: state.selectedDatabases.has(databaseName) || !!checkedByGroup,- checkDisabled: !!checkedByGroup,+ checked:+ selectedDatabaseNames.value.includes(databaseName) || !!checkedByGroup,+ checkDisabled: !!checkedByGroup || state.switchingConnection,checkTooltip,keyword: state.params.query,connected: connectedDatabases.value.has(databaseName),@@ -523,16 +653,9 @@ const renderLabel = ({ option }: { option: TreeOption }) => {return;}if (checked) {- if (state.selectedDatabases.size === 0) {- return connect(node);- }- if (!hasBatchQueryFeature.value) {- state.showFeatureModal = true;- return;- }- state.selectedDatabases.add(databaseName);+ handleToggleDatabase(databaseName, true);} else {- state.selectedDatabases.delete(databaseName);+ handleToggleDatabase(databaseName, false);}},});@@ -582,8 +705,8 @@ const nodeProps = ({ option }: { option: TreeOption }) => {return;}const bounding = wrapper.getBoundingClientRect();- hoverPosition.value.x = bounding.right;- hoverPosition.value.y = bounding.top;+ hoverPosition.value.x = bounding.left;+ hoverPosition.value.y = bounding.bottom;});}},diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTable.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTable.vuenew file mode 100644index 0000000000..da14d97de1--- /dev/null+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTable.vue@@ -0,0 +1,66 @@+<template>+ <div+ class="w-full"+ >+ <div class="w-full flex flex-row justify-between items-center mb-3">+ <p class="textinfolabel">+ {{ $t("database-group.select") }}+ </p>+ <SearchBox+ v-model:value="search"+ :placeholder="$t('common.filter-by-name')"+ />+ </div>+ <DatabaseGroupDataTable+ :database-group-list="filteredDbGroupList"+ :single-selection="false"+ :show-selection="true"+ :show-external-link="true"+ :page-size="100"+ :loading="!ready"+ :selected-database-group-names="databaseGroupNames"+ @update:selected-database-group-names="(groups) => $emit('update:databaseGroupNames', groups)"+ />+ </div>+</template>++<script lang="tsx" setup>+import { computed, ref } from "vue";+import DatabaseGroupDataTable from "@/components/DatabaseGroup/DatabaseGroupDataTable.vue";+import { SearchBox } from "@/components/v2";+import { useDBGroupListByProject, useSQLEditorStore } from "@/store/modules";+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";++defineProps<{+ databaseGroupNames: string[];+}>();++defineEmits<{+ (+ event: "update:databaseGroupNames",+ databaseGroupNames: string[]+ ): Promise<void>;+}>();++const editorStore = useSQLEditorStore();++const search = ref("");++const { dbGroupList, ready } = useDBGroupListByProject(+ computed(() => editorStore.project),+ DatabaseGroupView.FULL+);++const filteredDbGroupList = computed(() => {+ const filter = search.value.trim().toLowerCase();+ if (!filter) {+ return dbGroupList.value;+ }+ return dbGroupList.value.filter((group) => {+ return (+ group.name.toLowerCase().includes(filter) ||+ group.title.toLowerCase().includes(filter)+ );+ });+});+</script>\ No newline at end of filediff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vueindex a8b96f0739..5918ba0ef3 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vue@@ -1,8 +1,11 @@<template><NTooltip v-if="databaseGroup"><template #trigger>- <NTag closable @close="() => $emit('uncheck', databaseGroupName)">- {{ databaseGroup.title }}+ <NTag closable :disabled="disabled" @close="() => $emit('uncheck', databaseGroupName)">+ <div class="flex items-center gap-x-1">+ <BoxesIcon class="w-4" />+ {{ databaseGroup.title }}+ </div></NTag></template>{{ $t("common.database-group") }}@@ -10,6 +13,7 @@</template><script lang="tsx" setup>+import { BoxesIcon } from "lucide-vue-next";import { NTag, NTooltip } from "naive-ui";import { computed } from "vue";import { useDatabaseGroupByName } from "@/store";@@ -17,6 +21,7 @@ import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pbconst props = defineProps<{databaseGroupName: string;+ disabled: boolean;}>();defineEmits<{diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vueindex 626d13bcb7..e5a9a77133 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/TreeNode/DatabaseNode.vue@@ -1,13 +1,8 @@<template><div class="flex items-center max-w-full overflow-hidden gap-x-1">- <NTooltip v-if="tabStore.supportBatchMode" :disabled="!checkTooltip">+ <NTooltip v-if="tabStore.supportBatchMode" :disabled="!checkTooltip" :placement="'bottom-start'"><template #trigger>- <LinkIcon- v-if="tabStore.currentTab?.connection.database === database.name"- class="w-4 textinfolabel"- /><NCheckbox- v-else:checked="checked":disabled="checkDisabled || !canQuery"@click.stop.prevent=""@@ -42,7 +37,6 @@</template><script setup lang="ts">-import { LinkIcon } from "lucide-vue-next";import { NCheckbox, NTooltip } from "naive-ui";import { computed } from "vue";import { RichDatabaseName } from "@/components/v2";diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsxindex e44ae23948..555885e557 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/actions.tsx@@ -11,6 +11,7 @@ import { t } from "@/plugins/i18n";import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";import { useSQLEditorTabStore } from "@/store";import {+ type BatchQueryContext,type ComposedDatabase,DEFAULT_SQL_EDITOR_TAB_MODE,instanceOfSQLEditorTreeNode,@@ -75,7 +76,8 @@ export const useDropdown = () => {label: t("sql-editor.connect"),icon: () => <LinkIcon class="w-4 h-4" />,onSelect: () => {- setConnection(database, {+ setConnection({+ database,context: editorContext,newTab: false,});@@ -87,7 +89,8 @@ export const useDropdown = () => {label: t("sql-editor.connect-in-new-tab"),icon: () => <LinkIcon class="w-4 h-4" />,onSelect: () => {- setConnection(database, {+ setConnection({+ database,newTab: true,context: editorContext,});@@ -101,7 +104,8 @@ export const useDropdown = () => {label: t("sql-editor.connect-in-admin-mode"),icon: () => <WrenchIcon class="w-4 h-4" />,onSelect: () => {- setConnection(database, {+ setConnection({+ database,mode: "ADMIN",context: editorContext,newTab: false,@@ -170,32 +174,48 @@ export const useDropdown = () => {// setConnection will:// - when newTab == false && exist current tab: connect to the current tab// - otherwise create a new worksheet then open the tab-export const setConnection = (- database: ComposedDatabase,- options: {- mode?: TabMode;- newTab: boolean;- context: SQLEditorContext;- }-) => {+export const setConnection = (options: {+ database?: ComposedDatabase;+ mode?: TabMode;+ newTab: boolean;+ context: SQLEditorContext;+ batchQueryContext?: BatchQueryContext;+}) => {const {+ database,mode = DEFAULT_SQL_EDITOR_TAB_MODE,newTab = false,context,} = options;const connection: SQLEditorConnection = {- instance: database.instance,- database: database.name,+ instance: database?.instance ?? "",+ database: database?.name ?? "",};- setDefaultDataSourceForConn(connection, database);+ if (database) {+ setDefaultDataSourceForConn(connection, database);+ }const tabStore = useSQLEditorTabStore();+ const batchQueryContext: BatchQueryContext = Object.assign(+ { databases: [] },+ tabStore.currentTab?.batchQueryContext,+ options.batchQueryContext+ );+if (!newTab && tabStore.currentTab) {tabStore.updateCurrentTab({mode,connection,status: "DIRTY",+ batchQueryContext,});+ if (tabStore.currentTab.worksheet) {+ context.updateWorksheet({+ ...tabStore.currentTab,+ tabId: tabStore.currentTab.id,+ database: connection.database,+ });+ }context.asidePanelTab.value = "SCHEMA";} else {// create new worksheet and set connection@@ -206,7 +226,7 @@ export const setConnection = (}).then((tab) => {if (tab) {- tabStore.updateTab(tab.id, { mode });+ tabStore.updateTab(tab.id, { mode, batchQueryContext });context.asidePanelTab.value = "SCHEMA";}});diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPanel.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPanel.vueindex d53b75b034..1ffb163b27 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPanel.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPanel.vue@@ -33,7 +33,7 @@</template></NTooltip></template>- <ConnectionPane />+ <ConnectionPane :show="show" /></DrawerContent></Drawer></template>diff --git a/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue b/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vueindex 083f989049..f28e4c8fc5 100644--- a/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue+++ b/frontend/src/views/sql-editor/EditorCommon/SaveSheetModal.vue@@ -31,28 +31,21 @@</template><script lang="tsx" setup>-import { create } from "@bufbuild/protobuf";import { NButton, NInput } from "naive-ui";import { ref } from "vue";import { BBModal } from "@/bbkit";import RequiredStar from "@/components/RequiredStar.vue";import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";-import { useSQLEditorTabStore, useWorkSheetStore } from "@/store";+import { useWorkSheetStore } from "@/store";import type { SQLEditorTab } from "@/types";import { UNKNOWN_ID } from "@/types";-import {- type Worksheet,- Worksheet_Visibility,- WorksheetSchema,-} from "@/types/proto-es/v1/worksheet_service_pb";import { extractWorksheetUID } from "@/utils";import FolderForm from "@/views/sql-editor/AsidePanel/WorksheetPane/SheetList/FolderForm.vue";import { useSheetContextByView } from "@/views/sql-editor/Sheet";import { useSQLEditorContext } from "../context";-const tabStore = useSQLEditorTabStore();const worksheetV1Store = useWorkSheetStore();-const { events: editorEvents } = useSQLEditorContext();+const editorContext = useSQLEditorContext();const { getPwdForWorksheet } = useSheetContextByView("my");const folderFormRef = ref<InstanceType<typeof FolderForm>>();@@ -70,59 +63,35 @@ const doSaveSheet = async () => {if (!pendingEdit.value.rawTab) {return close();}- const { statement, worksheet, connection } = pendingEdit.value.rawTab;-if (pendingEdit.value.title === "") {return;}- const sheetId = Number(extractWorksheetUID(worksheet ?? ""));- let worksheetEntity: Worksheet | undefined;+ const {+ worksheet,+ connection,+ statement,+ id: tabId,+ } = pendingEdit.value.rawTab;+ const folders = folderFormRef.value?.folders ?? [];+ const sheetId = Number(extractWorksheetUID(worksheet ?? ""));if (sheetId !== UNKNOWN_ID) {- const currentSheet = worksheetV1Store.getWorksheetByName(worksheet);- if (!currentSheet) {- return;- }-- worksheetEntity = await worksheetV1Store.patchWorksheet(- {- ...currentSheet,- title: pendingEdit.value.title,- database: connection.database,- content: new TextEncoder().encode(statement),- },- ["title", "content", "database"]- );+ await editorContext.updateWorksheet({+ tabId,+ worksheet,+ title: pendingEdit.value.title,+ database: connection.database,+ statement,+ folders,+ });} else {- worksheetEntity = await worksheetV1Store.createWorksheet(- create(WorksheetSchema, {- title: pendingEdit.value.title,- project: tabStore.project,- content: new TextEncoder().encode(statement),- database: connection.database,- visibility: Worksheet_Visibility.PRIVATE,- })- );- }-- if (worksheetEntity) {- const folders = folderFormRef.value?.folders ?? [];- if (folders.length > 0) {- await worksheetV1Store.upsertWorksheetOrganizer(- {- worksheet: worksheetEntity.name,- starred: false,- folders,- },- ["folders"]- );- }-- tabStore.updateTab(pendingEdit.value.rawTab.id, {+ await editorContext.createWorksheet({+ tabId,title: pendingEdit.value.title,- status: "CLEAN",- worksheet: worksheetEntity.name,+ statement: pendingEdit.value.rawTab.statement,+ database: connection.database,+ folders,});}@@ -138,21 +107,25 @@ const close = () => {showModal.value = false;};-useEmitteryEventListener(editorEvents, "save-sheet", ({ tab, editTitle }) => {- pendingEdit.value = {- title: tab.title,- folder: "",- rawTab: tab,- };+useEmitteryEventListener(+ editorContext.events,+ "save-sheet",+ ({ tab, editTitle }) => {+ pendingEdit.value = {+ title: tab.title,+ folder: "",+ rawTab: tab,+ };- if (needShowModal(tab) || editTitle) {- const worksheet = worksheetV1Store.getWorksheetByName(tab.worksheet);- if (worksheet) {- pendingEdit.value.folder = getPwdForWorksheet(worksheet);+ if (needShowModal(tab) || editTitle) {+ const worksheet = worksheetV1Store.getWorksheetByName(tab.worksheet);+ if (worksheet) {+ pendingEdit.value.folder = getPwdForWorksheet(worksheet);+ }+ showModal.value = true;+ return;}- showModal.value = true;- return;+ doSaveSheet();}- doSaveSheet();-});+);</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vueindex fcb90eae58..05e5cd03de 100644--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue@@ -68,7 +68,7 @@<NScrollbar x-scrollable class="pb-2"><div class="flex flex-row justify-start items-center gap-2"><NButton- v-for="item in filteredItems"+ v-for="(item, index) in filteredItems":key="item.database.name"secondarystrong@@ -78,6 +78,9 @@...getBackgroundColorRgb(item.database),borderTop: selectedDatabase === item.database ? '3px solid' : '',}"+ @contextmenu.stop.prevent="+ contextMenuRef?.show(index, $event)+ "@click="$emit('update:selected-database', item.database)"><RichDatabaseName :database="item.database" />@@ -93,11 +96,12 @@</span><XIconclass="ml-1 text-gray-400 w-4 h-auto hover:text-gray-600"- @click.stop="handleCloseSingleResultView(item.database)"+ @click.stop="handleCloseSingleResultView(item)"/></NButton></div></NScrollbar>+ <ContextMenu ref="contextMenuRef" /></div></template>@@ -117,6 +121,7 @@ import DataExportButton from "@/components/DataExportButton.vue";import RequiredStar from "@/components/RequiredStar.vue";import { RichDatabaseName } from "@/components/v2";import { DatabaseV1Table } from "@/components/v2/Model/DatabaseV1Table";+import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";import { t } from "@/plugins/i18n";import {pushNotification,@@ -130,6 +135,8 @@ import type { ComposedDatabase, SQLEditorDatabaseQueryContext } from "@/types";import { ExportFormat } from "@/types/proto-es/v1/common_pb";import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";import { hexToRgb } from "@/utils";+import ContextMenu from "./ContextMenu.vue";+import { provideResultTabListContext } from "./context";const MAX_EXPORT = 20;@@ -153,6 +160,8 @@ const sqlStore = useSQLStore();const showEmpty = ref<boolean>(true);const policyStore = usePolicyV1Store();const { project } = storeToRefs(useSQLEditorStore());+const contextMenu = provideResultTabListContext();+const contextMenuRef = ref<InstanceType<typeof ContextMenu>>();const effectiveQueryDataPolicy = computed(() => {return policyStore.getEffectiveQueryDataPolicyForProject(project.value);@@ -225,15 +234,15 @@ const isDatabaseQueryFailed = (item: BatchQueryItem) => {);};-const handleCloseSingleResultView = (database: ComposedDatabase) => {- const contexts = tab.value?.databaseQueryContexts?.get(database.name);+const handleCloseSingleResultView = (item: BatchQueryItem) => {+ const contexts = tab.value?.databaseQueryContexts?.get(item.database.name);if (!contexts) {return;}for (const context of contexts) {context.abortController?.abort();}- tab.value?.databaseQueryContexts?.delete(database.name);+ tab.value?.databaseQueryContexts?.delete(item.database.name);};// Auto select a proper database when the databases are ready.@@ -311,4 +320,39 @@ const handleExportBtnClick = async ({resolve(contents);selectedDatabaseNameList.value = [];};++useEmitteryEventListener(+ contextMenu.events,+ "close-tab",+ async ({ index, action }) => {+ const max = items.value.length - 1;+ switch (action) {+ case "CLOSE": {+ handleCloseSingleResultView(items.value[index]);+ return;+ }+ case "CLOSE_OTHERS": {+ for (let i = max; i > index; i--) {+ handleCloseSingleResultView(items.value[i]);+ }+ for (let i = index - 1; i >= 0; i--) {+ handleCloseSingleResultView(items.value[i]);+ }+ return;+ }+ case "CLOSE_TO_THE_RIGHT": {+ for (let i = max; i > index; i--) {+ handleCloseSingleResultView(items.value[i]);+ }+ return;+ }+ case "CLOSE_ALL": {+ for (let i = max; i >= 0; i--) {+ handleCloseSingleResultView(items.value[i]);+ }+ return;+ }+ }+ }+);</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vuenew file mode 100644index 0000000000..b2866f5c02--- /dev/null+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ContextMenu.vue@@ -0,0 +1,85 @@+<template>+ <NDropdown+ v-if="state"+ trigger="manual"+ placement="bottom-start"+ :show="true"+ :x="state?.x"+ :y="state?.y"+ :options="options"+ @clickoutside="state = undefined"+ @update:show="handleUpdateShow"+ @select="handleSelect"+ />+</template>++<script setup lang="ts">+import type { DropdownOption } from "naive-ui";+import { NDropdown } from "naive-ui";+import { computed, nextTick } from "vue";+import { useI18n } from "vue-i18n";+import { type CloseTabAction, useResultTabListContext } from "./context";++const { t } = useI18n();+const { contextMenu: state, events } = useResultTabListContext();++const options = computed((): DropdownOption[] => {+ if (!state.value) {+ return [];+ }++ const CLOSE: DropdownOption = {+ key: "CLOSE",+ label: t("sql-editor.tab.context-menu.actions.close"),+ };+ const CLOSE_OTHERS: DropdownOption = {+ key: "CLOSE_OTHERS",+ label: t("sql-editor.tab.context-menu.actions.close-others"),+ };+ const CLOSE_TO_THE_RIGHT: DropdownOption = {+ key: "CLOSE_TO_THE_RIGHT",+ label: t("sql-editor.tab.context-menu.actions.close-to-the-right"),+ };+ const CLOSE_ALL: DropdownOption = {+ key: "CLOSE_ALL",+ label: t("sql-editor.tab.context-menu.actions.close-all"),+ };++ return [CLOSE, CLOSE_OTHERS, CLOSE_TO_THE_RIGHT, CLOSE_ALL];+});++const show = (index: number, e: MouseEvent) => {+ e.preventDefault();+ e.stopPropagation();+ state.value = undefined;+ nextTick(() => {+ const { pageX, pageY } = e;+ state.value = {+ x: pageX,+ y: pageY,+ index,+ };+ });+};++const hide = () => {+ state.value = undefined;+};++const handleUpdateShow = (show: boolean) => {+ if (!show) {+ hide();+ }+};++const handleSelect = (action: CloseTabAction) => {+ if (!state.value) return;+ const { index } = state.value;+ events.emit("close-tab", { index, action });+};++defineExpose({+ show,+ hide,+});+</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vueindex c62b653963..9768494623 100644--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue@@ -53,7 +53,7 @@{{$t("sql-editor.batch-query.select-data-source.not-match", {expect: getDataSourceTypeI18n(- tabStore.currentTab?.batchQueryContext?.dataSourceType+ tabStore.currentTab?.batchQueryContext.dataSourceType),actual: getDataSourceTypeI18n(dataSourceInContext(context)?.type),})@@ -259,7 +259,7 @@ const dataSourceInContext = (context: SQLEditorDatabaseQueryContext) => {// Memoize batch mode checkconst batchModeDataSourceType = computed(() => {if (!tabStore.isInBatchMode) return null;- return tabStore.currentTab?.batchQueryContext?.dataSourceType ?? null;+ return tabStore.currentTab?.batchQueryContext.dataSourceType ?? null;});const isMatchedDataSource = (context: SQLEditorDatabaseQueryContext) => {diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/context.ts b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/context.tsnew file mode 100644index 0000000000..d0424273c7--- /dev/null+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/context.ts@@ -0,0 +1,43 @@+import Emittery from "emittery";+import type { InjectionKey, Ref } from "vue";+import { inject, provide, ref } from "vue";++export type CloseTabAction =+ | "CLOSE"+ | "CLOSE_OTHERS"+ | "CLOSE_TO_THE_RIGHT"+ | "CLOSE_ALL";++type TabListEvents = Emittery<{+ "close-tab": { index: number; action: CloseTabAction };+}>;++export type TabListContextMenuState = {+ x: number;+ y: number;+ index: number;+};++export type TabListContext = {+ contextMenu: Ref<TabListContextMenuState | undefined>;+ events: TabListEvents;+};++export const KEY = Symbol(+ "bb.sql-editor.result-tab-list"+) as InjectionKey<TabListContext>;++export const useResultTabListContext = () => {+ return inject(KEY)!;+};++export const provideResultTabListContext = () => {+ const context: TabListContext = {+ contextMenu: ref(),+ events: new Emittery(),+ };++ provide(KEY, context);++ return context;+};diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.tsindex 02c097e32b..3966601e06 100644--- a/frontend/src/views/sql-editor/Sheet/context.ts+++ b/frontend/src/views/sql-editor/Sheet/context.ts@@ -563,9 +563,7 @@ export const openWorksheetByName = async ({}const tabStore = useSQLEditorTabStore();- const openingSheetTab = tabStore.openTabList.find(- (tab) => tab.worksheet === sheet.name- );+ const openingSheetTab = tabStore.getTabByWorksheet(sheet.name);if (openingSheetTab && !forceNewTab) {// Switch to a sheet tab if it's open already.diff --git a/frontend/src/views/sql-editor/TabList/TabItem/Label.vue b/frontend/src/views/sql-editor/TabList/TabItem/Label.vueindex 0e4da37733..21d9fb8671 100644--- a/frontend/src/views/sql-editor/TabList/TabItem/Label.vue+++ b/frontend/src/views/sql-editor/TabList/TabItem/Label.vue@@ -88,21 +88,16 @@ const confirmEdit = () => {tabStore.updateTab(tab.id, {title,- status: "DIRTY",});if (tab.worksheet) {- worksheetV1Store- .patchWorksheet(- create(WorksheetSchema, {- name: tab.worksheet,- title,- }),- ["title"]- )- .then(() => {- tab.status = "CLEAN";- });+ worksheetV1Store.patchWorksheet(+ create(WorksheetSchema, {+ name: tab.worksheet,+ title,+ }),+ ["title"]+ );}state.editing = false;diff --git a/frontend/src/views/sql-editor/TabList/TabList.vue b/frontend/src/views/sql-editor/TabList/TabList.vueindex 55ca3ee0a3..80561b4b08 100644--- a/frontend/src/views/sql-editor/TabList/TabList.vue+++ b/frontend/src/views/sql-editor/TabList/TabList.vue@@ -244,38 +244,41 @@ useEmitteryEventListener(await new Promise((r) => requestAnimationFrame(r));};- if (action === "CLOSE") {- await remove(tab);- return;- }const max = openTabList.length - 1;- if (action === "CLOSE_OTHERS") {- for (let i = max; i > index; i--) {- await remove(openTabList[i]);+ switch (action) {+ case "CLOSE": {+ await remove(tab);+ return;}- for (let i = index - 1; i >= 0; i--) {- await remove(openTabList[i]);+ case "CLOSE_OTHERS": {+ for (let i = max; i > index; i--) {+ await remove(openTabList[i]);+ }+ for (let i = index - 1; i >= 0; i--) {+ await remove(openTabList[i]);+ }+ return;}- return;- }- if (action === "CLOSE_TO_THE_RIGHT") {- for (let i = max; i > index; i--) {- await remove(openTabList[i]);+ case "CLOSE_TO_THE_RIGHT": {+ for (let i = max; i > index; i--) {+ await remove(openTabList[i]);+ }+ return;}- return;- }- if (action === "CLOSE_SAVED") {- for (let i = max; i >= 0; i--) {- const tab = openTabList[i];- if (tab.status === "CLEAN") {- await remove(tab);+ case "CLOSE_SAVED": {+ for (let i = max; i >= 0; i--) {+ const tab = openTabList[i];+ if (tab.status === "CLEAN") {+ await remove(tab);+ }}+ return;}- return;- }- if (action === "CLOSE_ALL") {- for (let i = max; i >= 0; i--) {- await remove(openTabList[i]);+ case "CLOSE_ALL": {+ for (let i = max; i >= 0; i--) {+ await remove(openTabList[i]);+ }+ return;}}}diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.tsindex 9fb75ab4bc..8d838eb047 100644--- a/frontend/src/views/sql-editor/context.ts+++ b/frontend/src/views/sql-editor/context.ts@@ -1,21 +1,25 @@import { create } from "@bufbuild/protobuf";import { useLocalStorage } from "@vueuse/core";import Emittery from "emittery";+import { isUndefined } from "lodash-es";import { type IRange } from "monaco-editor";import type { ComputedRef, InjectionKey, Ref } from "vue";import { computed, inject, nextTick, provide, ref } from "vue";import {useProjectV1Store,useSQLEditorStore,+ useSQLEditorTabStore,useWorkSheetStore,} from "@/store";import type { SQLEditorTab } from "@/types";import { isValidProjectName } from "@/types";import type { GetSchemaStringRequest_ObjectType } from "@/types/proto-es/v1/database_service_pb";import {+ type Worksheet,Worksheet_Visibility,WorksheetSchema,} from "@/types/proto-es/v1/worksheet_service_pb";+import { extractWorksheetConnection } from "@/utils";import { openWorksheetByName } from "@/views/sql-editor/Sheet";export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY";@@ -69,15 +73,21 @@ export type SQLEditorContext = {maybeSwitchProject: (project: string) => Promise<string | undefined>;handleEditorPanelResize: (size: number) => void;- createWorksheet: ({- title,- folders,- }: {+ createWorksheet: (options: {+ tabId?: string;title?: string;folders?: string[];statement?: string;database?: string;}) => Promise<SQLEditorTab | undefined>;+ updateWorksheet: (options: {+ tabId: string;+ worksheet: string;+ title: string;+ database: string;+ statement: string;+ folders?: string[];+ }) => Promise<Worksheet | undefined>;};export const KEY = Symbol(@@ -90,6 +100,7 @@ export const useSQLEditorContext = () => {export const provideSQLEditorContext = () => {const editorStore = useSQLEditorStore();+ const tabStore = useSQLEditorTabStore();const projectStore = useProjectV1Store();const worksheetStore = useWorkSheetStore();const showConnectionPanel = ref(false);@@ -114,12 +125,65 @@ export const provideSQLEditorContext = () => {};});+ const updateWorksheet = async ({+ tabId,+ worksheet,+ title,+ database,+ statement,+ folders,+ }: {+ tabId: string;+ worksheet: string;+ title: string;+ database: string;+ statement: string;+ folders?: string[];+ }) => {+ if (!worksheet) {+ return;+ }+ const currentSheet = worksheetStore.getWorksheetByName(worksheet);+ if (!currentSheet) {+ return;+ }++ const updated = await worksheetStore.patchWorksheet(+ {+ ...currentSheet,+ title,+ database,+ content: new TextEncoder().encode(statement),+ },+ ["title", "database", "content"]+ );+ if (updated && !isUndefined(folders)) {+ await worksheetStore.upsertWorksheetOrganizer(+ {+ worksheet: updated.name,+ folders: folders,+ },+ ["folders"]+ );+ }++ tabStore.updateTab(tabId, {+ status: "CLEAN",+ title: updated?.title,+ worksheet: updated?.name,+ });++ return updated;+ };+const createWorksheet = async ({+ tabId,title = "new worksheet",statement = "",folders = [],database = "",}: {+ tabId?: string;title?: string;statement?: string;folders?: string[];@@ -145,17 +209,27 @@ export const provideSQLEditorContext = () => {);}- const tab = await openWorksheetByName({- worksheet: newWorksheet.name,- forceNewTab: true,- });- nextTick(() => {- if (tab && !tab.connection?.database) {- showConnectionPanel.value = true;- }- });-- return tab;+ if (tabId) {+ const connection = await extractWorksheetConnection(newWorksheet);+ return tabStore.updateTab(tabId, {+ status: "CLEAN",+ title,+ statement,+ connection,+ worksheet: newWorksheet.name,+ });+ } else {+ const tab = await openWorksheetByName({+ worksheet: newWorksheet.name,+ forceNewTab: true,+ });+ nextTick(() => {+ if (tab && !tab.connection?.database) {+ showConnectionPanel.value = true;+ }+ });+ return tab;+ }};const context: SQLEditorContext = {@@ -190,6 +264,7 @@ export const provideSQLEditorContext = () => {aiPanelSize.value = 1 - size;},createWorksheet,+ updateWorksheet,};provide(KEY, context);