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: implement query multi databases in the standard mode of sql editor (#8568)
boojack6fab838f1151
diff --git a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vueindex e838e21bc0..b134eb589f 100644--- a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue+++ b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue@@ -1,6 +1,6 @@<template>- <div class="mb-2 flex flex-row items-center">- <span class="text-lg mr-2">{{ $t("common.databases") }}</span>+ <div v-if="!hideTitle" class="mb-2 flex flex-row items-center">+ <span class="text-base mr-2">{{ $t("common.databases") }}</span><BBLoader v-show="loading" class="opacity-60" /></div><div@@ -78,11 +78,20 @@><NEllipsis class="text-sm" line-clamp="1">{{ database.databaseName }}- ({{ database.effectiveEnvironmentEntity.title }})</NEllipsis>- <div class="flex flex-row justify-end items-center shrink-0">- <NEllipsis class="ml-1 text-sm text-gray-400" line-clamp="1">- <InstanceV1Name :instance="database.instanceEntity" :link="false" />+ <div class="flex-1 flex flex-row justify-end items-center shrink-0">+ <FeatureBadge+ feature="bb.feature.database-grouping"+ custom-class="mr-2"+ :instance="database.instanceEntity"+ />+ <InstanceV1EngineIcon :instance="database.instanceEntity" />+ <NEllipsis+ class="ml-1 text-sm text-gray-400 max-w-[124px]"+ line-clamp="1"+ >+ ({{ database.effectiveEnvironmentEntity.title }})+ {{ database.instanceEntity.title }}</NEllipsis></div></div>@@ -103,9 +112,10 @@ interface LocalState {}defineProps<{- loading: boolean;matchedDatabaseList: ComposedDatabase[];unmatchedDatabaseList: ComposedDatabase[];+ loading?: boolean;+ hideTitle?: boolean;}>();const state = reactive<LocalState>({diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.tsindex 478fa5c63d..293be4594e 100644--- a/frontend/src/composables/useExecuteSQL.ts+++ b/frontend/src/composables/useExecuteSQL.ts@@ -10,7 +10,13 @@ import {useCurrentUserV1,useDatabaseV1Store,} from "@/store";-import { ExecuteConfig, ExecuteOption, SQLResultSetV1 } from "@/types";+import {+ ComposedDatabase,+ ExecuteConfig,+ ExecuteOption,+ SQLResultSetV1,+ UNKNOWN_ID,+} from "@/types";import {Advice_Status,advice_StatusToJSON,@@ -88,94 +94,154 @@ const useExecuteSQL = () => {selectStatement = `EXPLAIN ${selectStatement}`;}- const fail = (result: SQLResultSetV1) => {- tabStore.updateTab(tab.id, {- sqlResultSet: {- error: result.error,- results: [],- advices: result.advices,- status: result.status,- allowExport: false,- },- executeParams: {- query,- config,- option,- },+ const batchQueryContext = tab.batchQueryContext;+ const selectedDatabase = useDatabaseV1Store().getDatabaseByUID(+ tab.connection.databaseId+ );+ const databaseName =+ selectedDatabase.uid === String(UNKNOWN_ID)+ ? ""+ : selectedDatabase.databaseName;+ const batchQueryDatabases: ComposedDatabase[] = [selectedDatabase];++ // Check if the user selects multiple databases to query.+ if (+ databaseName &&+ batchQueryContext &&+ batchQueryContext.selectedLabels.length > 0+ ) {+ const databases = useDatabaseV1Store().databaseListByProject(+ selectedDatabase.project+ );+ for (const database of databases) {+ if (database.name === selectedDatabase.name) {+ continue;+ }+ const matched = batchQueryContext.selectedLabels.find((labelString) => {+ // Filter out the environment label.+ const keys = Object.keys(database.labels).filter((key) => {+ return key !== "bb.environment";+ });+ return keys+ .map((key) => {+ return {+ key,+ value: database.labels[key],+ };+ })+ .find((label) => {+ return `${label.key}-${label.value}` === labelString;+ });+ });+ if (matched) {+ batchQueryDatabases.push(database);+ }+ }+ }++ const databaseQueryResultMap = new Map<string, SQLResultSetV1>();+ for (const database of batchQueryDatabases) {+ databaseQueryResultMap.set(database.name, {+ error: "",+ results: [],+ advices: [],+ allowExport: false,});+ }+ tabStore.updateCurrentTab({+ databaseQueryResultMap,+ });- cleanup();+ const fail = (database: ComposedDatabase, result: SQLResultSetV1) => {+ databaseQueryResultMap.set(database.name, {+ error: result.error,+ results: [],+ advices: result.advices,+ status: result.status,+ allowExport: false,+ });};- try {- const sqlResultSet = await sqlEditorStore.executeQuery({- statement: selectStatement,- });- // TODO(steven): use BBModel instead of notify to show the advice from SQL review.- let adviceStatus: "SUCCESS" | "ERROR" | "WARNING" = "SUCCESS";- let adviceNotifyMessage = "";- for (const advice of sqlResultSet.advices) {- if (advice.status === Advice_Status.SUCCESS) {- continue;- }+ for (const database of batchQueryDatabases) {+ const isUnknownDatabase = database.uid === String(UNKNOWN_ID);+ try {+ const sqlResultSet = await sqlEditorStore.executeQuery({+ instanceId: isUnknownDatabase+ ? tab.connection.instanceId+ : database.instanceEntity.uid,+ databaseName: isUnknownDatabase ? "" : database.databaseName,+ statement: selectStatement,+ });+ let adviceStatus: "SUCCESS" | "ERROR" | "WARNING" = "SUCCESS";+ let adviceNotifyMessage = "";+ for (const advice of sqlResultSet.advices) {+ if (advice.status === Advice_Status.SUCCESS) {+ continue;+ }++ if (advice.status === Advice_Status.ERROR) {+ adviceStatus = "ERROR";+ } else if (adviceStatus !== "ERROR") {+ adviceStatus = "WARNING";+ }- if (advice.status === Advice_Status.ERROR) {- adviceStatus = "ERROR";- } else if (adviceStatus !== "ERROR") {- adviceStatus = "WARNING";+ adviceNotifyMessage += `${advice_StatusToJSON(advice.status)}: ${+ advice.title+ }\n`;+ if (advice.content) {+ adviceNotifyMessage += `${advice.content}\n`;+ }}- adviceNotifyMessage += `${advice_StatusToJSON(advice.status)}: ${- advice.title- }\n`;- if (advice.content) {- adviceNotifyMessage += `${advice.content}\n`;+ if (adviceStatus !== "SUCCESS") {+ const notifyStyle = adviceStatus === "ERROR" ? "CRITICAL" : "WARN";+ notify(+ notifyStyle,+ t("sql-editor.sql-review-result"),+ adviceNotifyMessage+ );}- }- if (adviceStatus !== "SUCCESS") {- const notifyStyle = adviceStatus === "ERROR" ? "CRITICAL" : "WARN";- notify(- notifyStyle,- t("sql-editor.sql-review-result"),- adviceNotifyMessage- );- }- if (sqlResultSet.error) {- // The error message should be consistent with the one from the backend.- if (- sqlResultSet.error === "Support SELECT sql statement only" &&- sqlResultSet.status === Status.INVALID_ARGUMENT- ) {- const { databaseId } = tab.connection;- const database = databaseStore.getDatabaseByUID(databaseId);- // Only show the warning if the database is alterable.- // AKA, the current user has the permission to alter the database.- if (isDatabaseV1Alterable(database, currentUser.value)) {- sqlEditorStore.setSQLEditorState({- isShowExecutingHint: true,- });- return cleanup();+ if (sqlResultSet.error) {+ // The error message should be consistent with the one from the backend.+ if (+ sqlResultSet.error === "Support SELECT sql statement only" &&+ sqlResultSet.status === Status.INVALID_ARGUMENT+ ) {+ const { databaseId } = tab.connection;+ const database = databaseStore.getDatabaseByUID(databaseId);+ // Only show the warning if the database is alterable.+ // AKA, the current user has the permission to alter the database.+ if (isDatabaseV1Alterable(database, currentUser.value)) {+ sqlEditorStore.setSQLEditorState({+ isShowExecutingHint: true,+ });+ cleanup();+ }+ } else {+ fail(database, sqlResultSet);}+ } else {+ databaseQueryResultMap.set(database.name, markRaw(sqlResultSet));}- return fail(sqlResultSet);+ } catch (error: any) {+ fail(database, error.response?.data?.message ?? String(error));}-- tabStore.updateTab(tab.id, {- sqlResultSet: markRaw(sqlResultSet),- executeParams: {- query,- config,- option,- },- });- // Refresh the query history list when the query executed successfully- // (with or without warnings).- sqlEditorStore.fetchQueryHistoryList();- cleanup();- } catch (error: any) {- fail(error.response?.data?.message ?? String(error));}++ // After all the queries are executed, we update the tab with the latest query result map.+ tabStore.updateTab(tab.id, {+ databaseQueryResultMap: databaseQueryResultMap,+ executeParams: {+ query,+ config,+ option,+ },+ });+ // Refresh the query history list when the query executed successfully+ // (with or without warnings).+ sqlEditorStore.fetchQueryHistoryList();+ cleanup();};return {diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 56bf0c5944..cab5da4a00 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2048,7 +2048,10 @@}}},- "filter-by-name": "Filter by name"+ "filter-by-name": "Filter by name",+ "batch-query": {+ "description": "Batch query additional databases with the same label values."+ }},"schema-editor": {"self": "Schema Editor",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex f56af28065..afb1107fe5 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2044,7 +2044,10 @@}}},- "filter-by-name": "Filtrar por nombre"+ "filter-by-name": "Filtrar por nombre",+ "batch-query": {+ "description": "Consulta por lotes bases de datos adicionales con los mismos valores de etiqueta."+ }},"schema-editor": {"self": "Editor de esquema",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 7e01ba2a4a..36c2045e90 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2043,7 +2043,10 @@}}},- "filter-by-name": "根据名称过滤"+ "filter-by-name": "根据名称过滤",+ "batch-query": {+ "description": "批量查询具有相同标签值的其他数据库。"+ }},"schema-editor": {"self": "Schema 编辑器",diff --git a/frontend/src/store/modules/sqlEditor.ts b/frontend/src/store/modules/sqlEditor.tsindex 1ecc4b4c7f..2c1a549a42 100644--- a/frontend/src/store/modules/sqlEditor.ts+++ b/frontend/src/store/modules/sqlEditor.ts@@ -6,9 +6,7 @@ import {ActivitySQLEditorQueryPayload,} from "@/types";import { UNKNOWN_ID } from "@/types";-import { useTabStore } from "./tab";import { useInstanceV1Store, useSQLStore, useActivityV1Store } from "./v1";-import { useDatabaseV1Store } from "./v1/database";// set the limit to 1000 temporarily to avoid the query timeout and page crashexport const RESULT_ROWS_LIMIT = 1000;@@ -37,15 +35,17 @@ export const useSQLEditorStore = defineStore("sqlEditor", {setIsFetchingQueryHistory(payload: boolean) {this.isFetchingQueryHistory = payload;},- async executeQuery({ statement }: Pick<QueryInfo, "statement">) {- const { instanceId, databaseId } = useTabStore().currentTab.connection;- const database = useDatabaseV1Store().getDatabaseByUID(databaseId);- const databaseName =- database.uid === String(UNKNOWN_ID) ? "" : database.databaseName;- const instance = useInstanceV1Store().getInstanceByUID(instanceId);+ async executeQuery({+ instanceId,+ databaseName,+ statement,+ }: Pick<QueryInfo, "instanceId" | "databaseName" | "statement">) {+ const instance = useInstanceV1Store().getInstanceByUID(+ String(instanceId)+ );const response = await useSQLStore().queryReadonly({name: instance.name,- connectionDatabase: databaseName,+ connectionDatabase: databaseName || "",statement,limit: RESULT_ROWS_LIMIT,});diff --git a/frontend/src/store/modules/tab.ts b/frontend/src/store/modules/tab.tsindex 1e4a5ea5d7..5fbf07743d 100644--- a/frontend/src/store/modules/tab.ts+++ b/frontend/src/store/modules/tab.ts@@ -32,6 +32,7 @@ const PERSISTENT_TAB_FIELDS = ["statement","sheetName","mode",+ "batchQueryContext",] as const;type PersistentTabInfo = Pick<TabInfo, typeof PERSISTENT_TAB_FIELDS[number]>;@@ -155,6 +156,7 @@ export const useTabStore = defineStore("tab", () => {() => tab.name,() => tab.sheetName,() => tab.statement,+ () => tab.batchQueryContext,];watch(dirtyFields, () => {tab.isFreshNew = false;diff --git a/frontend/src/store/modules/v1/webTerminal.ts b/frontend/src/store/modules/v1/webTerminal.tsindex 5e110b62b0..609bb98c1b 100644--- a/frontend/src/store/modules/v1/webTerminal.ts+++ b/frontend/src/store/modules/v1/webTerminal.ts@@ -209,6 +209,7 @@ const createStreamingQueryController = (tab: TabInfo) => {events.emit("result", {error: "",advices: [],+ allowExport: false,...response,});},diff --git a/frontend/src/types/tab.ts b/frontend/src/types/tab.tsindex 8b6c77cf9f..8b6e6e1bae 100644--- a/frontend/src/types/tab.ts+++ b/frontend/src/types/tab.ts@@ -25,6 +25,10 @@ export type TabSheetType =export type EditMode = "SQL-EDITOR" | "CHAT-TO-SQL";+export interface BatchQueryContext {+ selectedLabels: string[];+}+export interface TabInfo {id: string;name: string;@@ -42,8 +46,13 @@ export interface TabInfo {};isExecutingSQL: boolean;sheetName?: string;- sqlResultSet?: SQLResultSetV1;isFreshNew?: boolean;+ // batchQueryContext saves the context of batch query, including the selected labels.+ batchQueryContext?: BatchQueryContext;+ // databaseQueryResultMap is used to store the query result of each database.+ // It's used for the case that the user selects multiple databases to query.+ // The key is the databaseName. Format: instances/{instance}/databases/{database}+ databaseQueryResultMap?: Map<string, SQLResultSetV1>;}export type CoreTabInfo = Pick<TabInfo, "connection" | "sheetName" | "mode">;diff --git a/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vue b/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vuenew file mode 100644index 0000000000..cafdeec581--- /dev/null+++ b/frontend/src/views/sql-editor/EditorCommon/BatchQueryDatabasesSelector.vue@@ -0,0 +1,159 @@+<template>+ <NPopover placement="bottom" trigger="click">+ <template #trigger>+ <div+ class="!ml-2 w-6 h-6 p-1 cursor-pointer rounded hover:opacity-80"+ :class="+ selectedLabelsValue.length > 0+ ? 'text-accent bg-blue-50 shadow'+ : 'text-gray-600'+ "+ >+ <Layers class="w-4 h-auto" />+ </div>+ </template>+ <div class="w-128">+ <p class="text-gray-500 mb-1">+ {{ $t("sql-editor.batch-query.description") }}+ </p>+ <div class="w-full grid grid-cols-3 gap-2 py-1">+ <div class="col-span-1">+ <NCheckboxGroup v-model:value="selectedLabelsValue">+ <NCheckbox+ v-for="label in labels"+ :key="`${label.key}-${label.value}`"+ :value="`${label.key}-${label.value}`"+ :label="`${getFormattedLabelKey(label.key)}:${label.value}`"+ >+ </NCheckbox>+ </NCheckboxGroup>+ </div>+ <div class="col-span-2">+ <MatchedDatabaseView+ :hide-title="true"+ :matched-database-list="matchedDatabases"+ :unmatched-database-list="unmatchedDatabases"+ />+ </div>+ </div>+ </div>+ </NPopover>+</template>++<script lang="ts" setup>+import { upperFirst } from "lodash-es";+import { Layers } from "lucide-vue-next";+import { NCheckboxGroup, NCheckbox, NPopover } from "naive-ui";+import { computed, ref, watch } from "vue";+import MatchedDatabaseView from "@/components/DatabaseGroup/MatchedDatabaseView.vue";+import {+ useCurrentUserIamPolicy,+ useDatabaseV1ByUID,+ useDatabaseV1Store,+ useTabStore,+} from "@/store/modules";++const databaseStore = useDatabaseV1Store();+const tabStore = useTabStore();+const currentUserIamPolicy = useCurrentUserIamPolicy();+// Save the stringified label key-value pairs.+const currentTab = computed(() => tabStore.currentTab);+const connection = computed(() => currentTab.value.connection);+const selectedLabelsValue = ref<string[]>([]);++const { database: selectedDatabase } = useDatabaseV1ByUID(+ computed(() => String(connection.value.databaseId))+);++const project = computed(() => selectedDatabase.value.projectEntity);++const databases = computed(() => {+ return databaseStore.databaseListByProject(project.value.name);+});++const filteredDatabaseList = computed(() => {+ return (+ databases.value+ // Don't show the currently selected database.+ .filter((db) => db.uid !== selectedDatabase.value.uid)+ // Only show databases that the user has permission to query.+ .filter((db) => currentUserIamPolicy.allowToQueryDatabaseV1(db))+ // Only show databases that have at least one label.+ .filter((db) => getFilteredDatabaseLabels(db.labels).length > 0)+ );+});++const labels = computed(() => {+ return filteredDatabaseList.value+ .map((db) => {+ return getFilteredDatabaseLabels(db.labels);+ })+ .flat();+});++const getFilteredDatabaseLabels = (labels: { [key: string]: string }) => {+ // Filter out the environment label.+ const keys = Object.keys(labels).filter((key) => {+ return key !== "bb.environment";+ });+ return keys.map((key) => {+ return {+ key,+ value: labels[key],+ };+ });+};++const matchedDatabases = computed(() => {+ return filteredDatabaseList.value.filter((db) => {+ return selectedLabelsValue.value.find((labelString) => {+ // Filter out the environment label.+ const keys = Object.keys(db.labels).filter((key) => {+ return key !== "bb.environment";+ });+ return keys+ .map((key) => {+ return {+ key,+ value: db.labels[key],+ };+ })+ .find((label) => {+ return `${label.key}-${label.value}` === labelString;+ });+ });+ });+});++const unmatchedDatabases = computed(() => {+ return filteredDatabaseList.value.filter((db) => {+ return matchedDatabases.value.indexOf(db) === -1;+ });+});++const getFormattedLabelKey = (labelKey: string) => {+ if (labelKey.startsWith("bb.")) {+ return upperFirst(labelKey.substring(3));+ }+ return upperFirst(labelKey);+};++watch(selectedLabelsValue, () => {+ tabStore.updateCurrentTab({+ batchQueryContext: {+ selectedLabels: selectedLabelsValue.value,+ },+ });+});++watch(+ () => currentTab.value.batchQueryContext?.selectedLabels,+ () => {+ selectedLabelsValue.value =+ currentTab.value.batchQueryContext?.selectedLabels || [];+ },+ {+ immediate: true,+ }+);+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue b/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vueindex 3bb17ffdb7..18d2983a13 100644--- a/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ConnectionPathBar.vue@@ -63,6 +63,13 @@<heroicons-outline:database /><span class="ml-2">{{ selectedDatabaseV1.databaseName }}</span></div>++ <div+ v-if="showBatchQuerySelector"+ class="relative ml-2 flex items-center"+ >+ <BatchQueryDatabasesSelector />+ </div></label></div>@@ -104,7 +111,9 @@ import {import { TabMode, UNKNOWN_ID } from "@/types";import { EnvironmentTier } from "@/types/proto/v1/environment_service";import { DataSourceType } from "@/types/proto/v1/instance_service";+import { TenantMode } from "@/types/proto/v1/project_service";import { hasWorkspacePermissionV1, instanceV1Slug } from "@/utils";+import BatchQueryDatabasesSelector from "./BatchQueryDatabasesSelector.vue";const router = useRouter();const tabStore = useTabStore();@@ -119,6 +128,8 @@ const { database: selectedDatabaseV1 } = useDatabaseV1ByUID(computed(() => String(connection.value.databaseId)));+const selectedProject = computed(() => selectedDatabaseV1.value.projectEntity);+const selectedEnvironment = computed(() => {return connection.value.databaseId === `${UNKNOWN_ID}`? selectedInstance.value.environmentEntity@@ -153,6 +164,14 @@ const showReadonlyDatasourceHint = computed(() => {);});+const showBatchQuerySelector = computed(() => {+ return (+ selectedProject.value.tenantMode === TenantMode.TENANT_MODE_ENABLED &&+ // TODO(steven): implement batch query in admin mode.+ currentTab.value.mode !== TabMode.Admin+ );+});+const currentUserV1 = useCurrentUserV1();const allowManageInstance = computed(() => {return hasWorkspacePermissionV1(diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vueindex c85efc6254..1eeb92e37a 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue@@ -8,6 +8,7 @@<template v-if="viewMode === 'SINGLE-RESULT'"><SingleResultViewV1:params="executeParams"+ :sql-result-set="resultSet":result="resultSet.results[0]":set-index="0"/>@@ -26,6 +27,7 @@><SingleResultViewV1:params="executeParams"+ :sql-result-set="resultSet":result="result":set-index="i"/>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vueindex d519de9066..cee34b5b26 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue@@ -192,6 +192,7 @@ const props = defineProps<{config: ExecuteConfig;option?: Partial<ExecuteOption> | undefined;};+ sqlResultSet: SQLResultSetV1;result: QueryResult;setIndex: number;}>();@@ -255,7 +256,7 @@ const allowToExportData = computed(() => {return true;}- return currentTab.value.sqlResultSet?.allowExport || false;+ return props.sqlResultSet?.allowExport || false;});// use a debounced value to improve performance when typing rapidly@@ -352,13 +353,13 @@ const showVisualizeButton = computed((): boolean => {const visualizeExplain = () => {try {- const { executeParams, sqlResultSet } = tabStore.currentTab;- if (!executeParams || !sqlResultSet) return;+ const { executeParams } = tabStore.currentTab;+ if (!executeParams || !props.sqlResultSet) return;const statement = executeParams.query || "";if (!statement) return;- const explain = explainFromSQLResultSetV1(sqlResultSet);+ const explain = explainFromSQLResultSetV1(props.sqlResultSet);if (!explain) return;const token = createExplainToken(statement, explain);diff --git a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vueindex 622af11efe..6ef2fd0704 100644--- a/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue+++ b/frontend/src/views/sql-editor/EditorPanel/SQLEditor.vue@@ -64,7 +64,11 @@ const editorRef = ref<InstanceType<typeof MonacoEditor>>();const sqlCode = computed(() => tabStore.currentTab.statement);const advices = computed((): AdviceOption[] => {- return (tabStore.currentTab.sqlResultSet?.advices ?? []).map((advice) => ({+ return (+ Array.from(tabStore.currentTab?.databaseQueryResultMap?.values() || [])+ .map((result) => result?.advices || [])+ .flat() ?? []+ ).map((advice) => ({severity: "ERROR",message: advice.detail,startLineNumber: advice.line,@@ -120,12 +124,13 @@ const handleChange = (value: string) => {if (value === tabStore.currentTab.statement) {return;}+ // Clear old advices when the statement is changed.+ tabStore.currentTab.databaseQueryResultMap?.forEach((result) => {+ result.advices = [];+ });tabStore.updateCurrentTab({statement: value,isSaved: false,- sqlResultSet: Object.assign({}, tabStore.currentTab.sqlResultSet, {- advices: [],- }),});};diff --git a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vueindex 11a8aff1f4..39161affcb 100644--- a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue+++ b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue@@ -1,20 +1,95 @@<template>- <ResultViewV1- class="w-full h-full"- :execute-params="executeParams"- :result-set="resultSet"- :loading="loading"- />+ <div+ class="absolute inset-0 flex flex-col justify-center items-center z-10"+ :class="loading && 'bg-white/80 dark:bg-black/80'"+ >+ <template v-if="loading">+ <BBSpin />+ {{ $t("sql-editor.loading-data") }}+ </template>+ <template v-else-if="!selectedResultSet">+ {{ $t("sql-editor.table-empty-placeholder") }}+ </template>+ <template v-else>+ <div class="w-full flex flex-row justify-start items-center p-2 gap-2">+ <NTooltip+ v-for="database in databases"+ :key="database.name"+ trigger="hover"+ >+ <template #trigger>+ <NButton+ :type="selectedDatabase === database ? 'primary' : 'default'"+ @click="selectedDatabase = database"+ >+ <InstanceV1EngineIcon+ :instance="database.instanceEntity"+ :tooltip="false"+ />+ <span class="mx-2 opacity-60">{{+ database.effectiveEnvironmentEntity.title+ }}</span>+ <span>{{ database.databaseName }}</span>+ <Info+ v-if="isDatabaseQueryFailed(database)"+ class="ml-2 text-yellow-600 w-4 h-auto"+ />+ </NButton>+ </template>+ {{ database.instanceEntity.title }}+ </NTooltip>+ </div>+ <ResultViewV1+ class="w-full h-full"+ :execute-params="executeParams"+ :result-set="selectedResultSet"+ />+ </template>+ </div></template><script lang="ts" setup>-import { computed } from "vue";-import { useTabStore } from "@/store";+import { head } from "lodash-es";+import { Info } from "lucide-vue-next";+import { NButton, NTooltip } from "naive-ui";+import { computed, ref, watch } from "vue";+import { useDatabaseV1Store, useTabStore } from "@/store";+import { ComposedDatabase } from "@/types";import { ResultViewV1 } from "../EditorCommon/";const tabStore = useTabStore();+const databaseStore = useDatabaseV1Store();+const selectedDatabase = ref<ComposedDatabase>();-const resultSet = computed(() => tabStore.currentTab.sqlResultSet);+const queriedDatabaseNames = computed(() =>+ Array.from(tabStore.currentTab.databaseQueryResultMap?.keys() || [])+);+const databases = computed(() => {+ return queriedDatabaseNames.value.map((databaseName) => {+ return databaseStore.getDatabaseByName(databaseName);+ });+});+const selectedResultSet = computed(() => {+ return tabStore.currentTab.databaseQueryResultMap?.get(+ selectedDatabase.value?.name || ""+ );+});const executeParams = computed(() => tabStore.currentTab.executeParams);const loading = computed(() => tabStore.currentTab.isExecutingSQL);++const isDatabaseQueryFailed = (database: ComposedDatabase) => {+ return tabStore.currentTab.databaseQueryResultMap?.get(database.name || "")+ ?.error;+};++// Auto select the first database when the databases are ready.+watch(+ () => databases.value,+ () => {+ selectedDatabase.value = head(databases.value);+ },+ {+ immediate: true,+ }+);</script>diff --git a/frontend/src/views/sql-editor/SQLEditorPage.vue b/frontend/src/views/sql-editor/SQLEditorPage.vueindex 4f6b2cd1b5..f147f3b963 100644--- a/frontend/src/views/sql-editor/SQLEditorPage.vue+++ b/frontend/src/views/sql-editor/SQLEditorPage.vue@@ -75,7 +75,7 @@<SecondaryGutterBar /></div></Pane>- <Pane v-if="!isDisconnected" :size="40">+ <Pane v-if="!isDisconnected" class="relative" :size="40"><ResultPanel /></Pane></Splitpanes>