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: query lazy load & support database group in batch query (#16123)
ecmadaobd7fa0f7381f
diff --git a/frontend/src/components/DatabaseAndGroupSelector/DatabaseAndGroupSelector.vue b/frontend/src/components/DatabaseAndGroupSelector/DatabaseAndGroupSelector.vueindex e822f8721a..646d2c2a40 100644--- a/frontend/src/components/DatabaseAndGroupSelector/DatabaseAndGroupSelector.vue+++ b/frontend/src/components/DatabaseAndGroupSelector/DatabaseAndGroupSelector.vue@@ -19,7 +19,7 @@"/></NTabPane>- <NTabPane name="GROUP" :tab="$t('common.database-groups')">+ <NTabPane name="GROUP" :tab="$t('common.database-group')"><DatabaseGroupDataTable:database-group-list="dbGroupList":show-selection="true"diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vueindex 3adb40422d..8143a08966 100644--- a/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vue+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupDataTable.vue@@ -7,26 +7,22 @@:bordered="bordered":loading="loading":row-key="(data: ComposedDatabaseGroup) => data.name"- :checked-row-keys="Array.from(state.selectedDatabaseGroupNameList)"+ :checked-row-keys="selectedDatabaseGroupNames":row-props="rowProps":pagination="{ pageSize: 20 }":paginate-single-page="false"@update:checked-row-keys="- (val) => (state.selectedDatabaseGroupNameList = new Set(val as string[]))- "+ (val) => $emit('update:selected-database-group-names', val as string[])+ "/></template><script lang="tsx" setup>-import { NDataTable, type DataTableColumn } from "naive-ui";-import { computed, reactive, watch } from "vue";+import { NDataTable, NEllipsis, type DataTableColumn } from "naive-ui";+import { computed } from "vue";import { useI18n } from "vue-i18n";import type { ComposedDatabaseGroup } from "@/types";-interface LocalState {- selectedDatabaseGroupNameList: Set<string>;-}-type DatabaseGroupDataTableColumn = DataTableColumn<ComposedDatabaseGroup> & {hide?: boolean;};@@ -59,9 +55,6 @@ const emit = defineEmits<{}>();const { t } = useI18n();-const state = reactive<LocalState>({- selectedDatabaseGroupNameList: new Set(props.selectedDatabaseGroupNames),-});const columnList = computed((): DatabaseGroupDataTableColumn[] => {const rawColumnList: DatabaseGroupDataTableColumn[] = [@@ -106,7 +99,7 @@ const columnList = computed((): DatabaseGroupDataTableColumn[] => {if (!data.databaseExpr || data.databaseExpr.expression === "") {return <span class="textinfolabel italic">{t("common.empty")}</span>;}- return <span class="">{data.databaseExpr.expression}</span>;+ return <NEllipsis>{data.databaseExpr.expression}</NEllipsis>;},},];@@ -128,28 +121,21 @@ const rowProps = (databaseGroup: ComposedDatabaseGroup) => {}if (props.singleSelection) {- state.selectedDatabaseGroupNameList = new Set([databaseGroup.name]);+ emit("update:selected-database-group-names", [databaseGroup.name]);} else {const selectedDatabaseGroupNameList = new Set(- Array.from(state.selectedDatabaseGroupNameList)+ props.selectedDatabaseGroupNames);if (selectedDatabaseGroupNameList.has(databaseGroup.name)) {selectedDatabaseGroupNameList.delete(databaseGroup.name);} else {selectedDatabaseGroupNameList.add(databaseGroup.name);}- state.selectedDatabaseGroupNameList = selectedDatabaseGroupNameList;+ emit("update:selected-database-group-names", [+ ...selectedDatabaseGroupNameList,+ ]);}},};};--watch(- () => state.selectedDatabaseGroupNameList,- () => {- emit("update:selected-database-group-names", [- ...state.selectedDatabaseGroupNameList,- ]);- }-);</script>diff --git a/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportArchiveDownloadButton.vue b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportArchiveDownloadButton.vueindex c1cda8320b..de69f4ea44 100644--- a/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportArchiveDownloadButton.vue+++ b/frontend/src/components/IssueV1/components/HeaderSection/Actions/request/ExportArchiveDownloadButton.vue@@ -29,7 +29,7 @@ import { NButton } from "naive-ui";import { computed, reactive } from "vue";import { useIssueContext } from "@/components/IssueV1";import { issueServiceClient } from "@/grpcweb";-import { useExportData } from "@/store/modules/export";+import { useSQLStore } from "@/store";import { ExportFormat, exportFormatToJSON } from "@/types/proto/v1/common";import { IssueStatus } from "@/types/proto/v1/issue_service";import {@@ -63,7 +63,7 @@ const exportDataConfig = computed(() => {const downloadExportArchive = async () => {state.isExporting = true;- const content = await useExportData().exportData(+ const content = await useSQLStore().exportData(ExportRequest.fromPartial({name: issue.value.name,})diff --git a/frontend/src/composables/useExecuteSQL.ts b/frontend/src/composables/useExecuteSQL.tsindex 64c45822c8..b1e842a3c3 100644--- a/frontend/src/composables/useExecuteSQL.ts+++ b/frontend/src/composables/useExecuteSQL.ts@@ -1,17 +1,19 @@import Emittery from "emittery";import { head, isEmpty } from "lodash-es";import { Status } from "nice-grpc-common";+import { v4 as uuidv4 } from "uuid";import { markRaw, reactive } from "vue";import { sqlServiceClient } from "@/grpcweb";import { t } from "@/plugins/i18n";import {pushNotification,- useDatabaseV1Store,+ useDBGroupStore,useSQLEditorStore,useSQLEditorTabStore,useSQLStore,useSQLEditorQueryHistoryStore,useAppFeature,+ hasFeature,} from "@/store";import type {ComposedDatabase,@@ -19,9 +21,11 @@ import type {BBNotificationStyle,SQLEditorQueryParams,SQLEditorTab,+ SQLEditorDatabaseQueryContext,} from "@/types";import { isValidDatabaseName } from "@/types";import { Engine } from "@/types/proto/v1/common";+import { DatabaseGroupView } from "@/types/proto/v1/database_group_service";import {Advice,Advice_Status,@@ -29,7 +33,6 @@ import {CheckRequest_ChangeType,} from "@/types/proto/v1/sql_service";import {- emptySQLEditorTabQueryContext,ensureDataSourceSelection,hasPermissionToCreateChangeDatabaseIssue,} from "@/utils";@@ -55,7 +58,7 @@ const useExecuteSQL = () => {const state = reactive<{lastQueryTime?: number;}>({});- const databaseStore = useDatabaseV1Store();+ const dbGroupStore = useDBGroupStore();const tabStore = useSQLEditorTabStore();const sqlEditorStore = useSQLEditorStore();const queryHistoryStore = useSQLEditorQueryHistoryStore();@@ -82,11 +85,6 @@ const useExecuteSQL = () => {return false;}- if (tab.queryContext?.status === "EXECUTING") {- notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));- return false;- }-if (tabStore.isDisconnected) {notify("CRITICAL", t("sql-editor.select-connection"));return false;@@ -97,16 +95,14 @@ const useExecuteSQL = () => {return false;}- const emptyContext = emptySQLEditorTabQueryContext();- tab.queryContext = {- ...emptyContext,- status: "EXECUTING",- results: tab.queryContext?.results ?? emptyContext.results,- };+ if (!tab.databaseQueryContexts) {+ tab.databaseQueryContexts = new Map();+ }return true;};const check = async (+ abortController: AbortController,params: SQLEditorQueryParams): Promise<SQLCheckResult> => {const tab = tabStore.currentTab;@@ -114,7 +110,6 @@ const useExecuteSQL = () => {return { passed: false };}- const abortController = tab.queryContext?.abortController;if (!params) {return { passed: false };}@@ -169,14 +164,7 @@ const useExecuteSQL = () => {}};- const cleanup = () => {- const tab = tabStore.currentTab;- if (!tab) return;- if (!tab.queryContext) return;- tab.queryContext.status = "IDLE";- };-- const execute = async (params: SQLEditorQueryParams) => {+ const preExecute = async (params: SQLEditorQueryParams) => {const now = Date.now();if (state.lastQueryTime &&@@ -185,92 +173,143 @@ const useExecuteSQL = () => {return;}- if (!preflight(params)) {- return cleanup();- }-const tab = tabStore.currentTab;if (!tab) {- return cleanup();+ return;}const { mode } = tab;if (mode === "ADMIN") {- return cleanup();+ return;}- const queryContext = tab.queryContext!;- const batchQueryContext = tab.batchQueryContext;+ if (!preflight(params)) {+ return;+ }- const selectedDatabase = await databaseStore.getOrFetchDatabaseByName(- params.connection.database- );- const databaseName = isValidDatabaseName(selectedDatabase.name)- ? selectedDatabase.databaseName- : "";- const batchQueryDatabases: ComposedDatabase[] = [selectedDatabase];+ if (!isValidDatabaseName(params.connection.database)) {+ return;+ }++ const databaseQueryContexts = tab.databaseQueryContexts!;+ const batchQueryDatabaseSet = new Set<string /* database name */>([+ params.connection.database,+ ]);// Check if the user selects multiple databases to query.- if (- databaseName &&- batchQueryContext &&- batchQueryContext.databases.length > 0- ) {- for (const databaseResourceName of batchQueryContext.databases) {- if (databaseResourceName === selectedDatabase.name) {+ if (tab.batchQueryContext && hasFeature("bb.feature.batch-query")) {+ const { databases, databaseGroups } = tab.batchQueryContext;+ for (const databaseResourceName of databases) {+ if (!isValidDatabaseName(databaseResourceName)) {continue;}- const database =- await databaseStore.getOrFetchDatabaseByName(databaseResourceName);- batchQueryDatabases.push(database);+ if (batchQueryDatabaseSet.has(databaseResourceName)) {+ continue;+ }+ batchQueryDatabaseSet.add(databaseResourceName);}- }- const beginTimestampMS = Date.now();+ if (hasFeature("bb.feature.database-grouping")) {+ for (const databaseGroupName of databaseGroups) {+ try {+ const databaseGroup = await dbGroupStore.getOrFetchDBGroupByName(+ databaseGroupName,+ {+ skipCache: false,+ silent: true,+ view: DatabaseGroupView.DATABASE_GROUP_VIEW_FULL,+ }+ );+ for (const matchedDatabase of databaseGroup.matchedDatabases) {+ if (!isValidDatabaseName(matchedDatabase.name)) {+ continue;+ }+ if (batchQueryDatabaseSet.has(matchedDatabase.name)) {+ continue;+ }+ batchQueryDatabaseSet.add(matchedDatabase.name);+ }+ } catch {+ // skip+ }+ }+ }+ }- for (const database of queryContext.results.keys()) {- if (!batchQueryDatabases.find((db) => db.name === database)) {- queryContext.results.delete(database);+ for (const [database, contexts] of databaseQueryContexts.entries()) {+ if (!batchQueryDatabaseSet.has(database)) {+ for (const context of contexts) {+ if (context.status === "EXECUTING") {+ context.abortController?.abort();+ }+ }+ databaseQueryContexts.delete(database);}}- const unshiftQueryResult = (- database: string,- resultSet: SQLResultSetV1- ) => {- if (!queryContext.results.has(database)) {- queryContext.results.set(database, []);+ for (const databaseName of batchQueryDatabaseSet.values()) {+ if (!databaseQueryContexts.has(databaseName)) {+ databaseQueryContexts.set(databaseName, []);}- if (queryContext.results.get(database)!.length >= 10) {- queryContext.results.get(database)!.pop();++ if ((databaseQueryContexts.get(databaseName)?.length ?? 0) >= 10) {+ databaseQueryContexts.get(databaseName)?.pop();}- queryContext.results.get(database)!.unshift({++ databaseQueryContexts.get(databaseName)?.unshift({+ id: uuidv4(),params,- beginTimestampMS,- resultSet,+ status: "PENDING",});- };+ }+ };++ const runQuery = async (+ database: ComposedDatabase,+ context: SQLEditorDatabaseQueryContext+ ) => {+ if (context.status === "EXECUTING") {+ notify("INFO", t("common.tips"), t("sql-editor.can-not-execute-query"));+ return;+ }- const fail = (database: ComposedDatabase, resultSet: SQLResultSetV1) => {- unshiftQueryResult(database.name, resultSet);+ if (!isValidDatabaseName(database.name)) {+ notify(+ "CRITICAL",+ t("common.error"),+ t("sql-editor.invalid-database", { database: database.name })+ );+ return;+ }++ context.abortController = new AbortController();+ context.status = "EXECUTING";+ context.beginTimestampMS = Date.now();++ const finish = (resultSet: SQLResultSetV1) => {+ context.resultSet = resultSet;+ context.status = "DONE";};+const abort = (error: string, advices: Advice[] = []) => {- fail(batchQueryDatabases[0], {+ notify("WARN", t("sql-editor.request-cancelled"));+ return finish({error,results: [],advices,status: Status.ABORTED,});- return cleanup();};- const { abortController } = queryContext;-+ const { abortController } = context;const sqlStore = useSQLStore();- const checkBehavior = params.skipCheck ? "SKIP" : sqlCheckStyle.value;++ const checkBehavior = context.params.skipCheck+ ? "SKIP"+ : sqlCheckStyle.value;let checkResult: SQLCheckResult = { passed: true };if (checkBehavior !== "SKIP") {try {- checkResult = await check(params);+ checkResult = await check(context.abortController, context.params);} catch (error) {return abort(extractGrpcErrorMessage(error));}@@ -296,112 +335,104 @@ const useExecuteSQL = () => {}}- for (const database of batchQueryDatabases) {- if (abortController.signal.aborted) {- // Once any one of the batch queries is aborted, don't go further- // and mock an "Aborted" result for the rest queries.- fail(database, {- advices: [],- error: "AbortError: The user aborted a request.",- results: [],- status: Status.ABORTED,- });- continue;- }+ const instance = isValidDatabaseName(database.name)+ ? database.instance+ : context.params.connection.instance;+ const dataSourceId =+ ensureDataSourceSelection(+ instance === context.params.connection.instance+ ? context.params.connection.dataSourceId+ : undefined,+ database+ ) ?? "";++ if (!dataSourceId) {+ return finish({+ advices: [],+ error: t("sql-editor.no-data-source"),+ results: [],+ status: Status.NOT_FOUND,+ });+ }- try {- const instance = isValidDatabaseName(database.name)- ? database.instance- : params.connection.instance;- const dataSourceId =- ensureDataSourceSelection(- instance === params.connection.instance- ? params.connection.dataSourceId- : undefined,- database- ) ?? "";-- if (!dataSourceId) {- fail(database, {- advices: [],- error:- "No queriable data source. Please check the data source query policy on environment or project.",- results: [],- status: Status.NOT_FOUND,- });- continue;- }+ if (abortController.signal.aborted) {+ // Once any one of the batch queries is aborted, don't go further+ // and mock an "Aborted" result for the rest queries.+ return finish({+ advices: [],+ error: t("sql-editor.request-aborted"),+ results: [],+ status: Status.ABORTED,+ });+ }- const resultSet = await sqlStore.query(- {- name: database.name,- dataSourceId: dataSourceId,- statement: params.statement,- limit: sqlEditorStore.resultRowsLimit,- explain: params.explain,- schema: params.connection.schema,- container: params.connection.table,- queryOption: {- redisRunCommandsOn: sqlEditorStore.redisCommandOption,- },- },- abortController.signal- );-- if (- database.instanceResource.engine === Engine.MONGODB ||- database.instanceResource.engine === Engine.COSMOSDB- ) {- flattenNoSQLResult(resultSet);- }+ const resultSet = await sqlStore.query(+ {+ name: database.name,+ dataSourceId: dataSourceId,+ statement: context.params.statement,+ limit: sqlEditorStore.resultRowsLimit,+ explain: context.params.explain,+ schema: context.params.connection.schema,+ container: context.params.connection.table,+ queryOption: {+ redisRunCommandsOn: sqlEditorStore.redisCommandOption,+ },+ },+ abortController.signal+ );- if (checkBehavior === "NOTIFICATION") {- notifyAdvices(checkResult.advices ?? []);- }+ // After all the queries are executed, we update the tab with the latest query result map.+ // Refresh the query history list when the query executed successfully+ // (with or without warnings).+ queryHistoryStore.resetPageToken({+ project: sqlEditorStore.project,+ database: database.name,+ });+ queryHistoryStore+ .fetchQueryHistoryList({+ project: sqlEditorStore.project,+ database: database.name,+ })+ .catch(() => {+ /* nothing */+ });- if (resultSet.error) {- // The error message should be consistent with the one from the backend.- if (isOnlySelectError(resultSet)) {- const database = databaseStore.getDatabaseByName(- params.connection.database- );+ if (+ database.instanceResource.engine === Engine.MONGODB ||+ database.instanceResource.engine === Engine.COSMOSDB+ ) {+ flattenNoSQLResult(resultSet);+ }- // Show a tips to navigate to issue creation- // if the user is allowed to create issue in the project.- if (hasPermissionToCreateChangeDatabaseIssue(database)) {- sqlEditorStore.isShowExecutingHint = true;- sqlEditorStore.executingHintDatabase = database;- cleanup();- }- fail(database, resultSet);- } else {- fail(database, resultSet);- }- } else {- unshiftQueryResult(database.name, markRaw(resultSet));- // After all the queries are executed, we update the tab with the latest query result map.- // Refresh the query history list when the query executed successfully- // (with or without warnings).- queryHistoryStore.resetPageToken({- project: sqlEditorStore.project,- database: database.name,- });- queryHistoryStore.fetchQueryHistoryList({- project: sqlEditorStore.project,- database: database.name,- });+ if (checkBehavior === "NOTIFICATION") {+ notifyAdvices(checkResult.advices ?? []);+ }++ if (resultSet.error) {+ // The error message should be consistent with the one from the backend.+ if (isOnlySelectError(resultSet)) {+ // Show a tips to navigate to issue creation+ // if the user is allowed to create issue in the project.+ if (hasPermissionToCreateChangeDatabaseIssue(database)) {+ sqlEditorStore.isShowExecutingHint = true;+ sqlEditorStore.executingHintDatabase = database;}- } catch (error: any) {- fail(database, error.response?.data?.message ?? String(error));}+ return finish(resultSet);}- cleanup();+ return finish(markRaw(resultSet));+ };++ const execute = async (params: SQLEditorQueryParams) => {+ return preExecute(params);};return {events,execute,+ runQuery,};};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 42289e1c22..705c1f9aae 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -183,7 +183,7 @@"expiration": "Expiration","configure": "Configure","groups": "Groups",- "database-groups": "Database Groups",+ "database-group": "Database Group | Database Groups","members": "Members","warehouse": "Warehouse","schedule": "Schedule",@@ -1735,6 +1735,10 @@"to-enable-admin-mode": "to enable the admin mode","notify-empty-statement": "Please input your SQL statements in the editor","can-not-execute-query": "Cannot execute query when loading data.",+ "invalid-database": "Invalid database {database}",+ "request-cancelled": "Request cancelled",+ "request-aborted": "User aborted the request",+ "no-data-source": "No queriable data source. Please check the data source query policy on environment or project.","rows": "row | rows","vertical-display": "Vertical display","no-history-found": "No history found",@@ -1799,9 +1803,12 @@},"batch-query": {"batch": "Batch",- "description": "Batch query {count} additional databases under {project}.",+ "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"},+ "execute-query": "Execute query",+ "pending-query": "Pending query","executing-query": "Executing query","request-query": "Request query","copy-success": "Copy success",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex f08583ed99..0c9632de92 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -183,7 +183,7 @@"expiration": "Expiración","configure": "Configurar","groups": "Grupos",- "database-groups": "Grupo de bases de datos",+ "database-group": "Grupo de bases de datos | Grupos de bases de datos","members": "Miembros","warehouse": "Almacén","schedule": "Horario",@@ -1735,6 +1735,10 @@"to-enable-admin-mode": "para habilitar el modo administrador","notify-empty-statement": "Ingrese sus declaraciones SQL en el editor","can-not-execute-query": "No se puede ejecutar la consulta al cargar datos.",+ "invalid-database": "Base de datos no válida {database}",+ "request-cancelled": "Solicitud cancelada",+ "request-aborted": "El usuario abortó la solicitud",+ "no-data-source": "No se puede consultar ninguna fuente de datos. Consulte la política de consulta de fuentes de datos del entorno o proyecto.","rows": "fila | filas","vertical-display": "Pantalla vertical","no-history-found": "No se encontró historial",@@ -1799,9 +1803,12 @@},"batch-query": {"batch": "Lote",- "description": "Consulta por lotes {count} bases de datos adicionales en {project}.",+ "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"},+ "execute-query": "Ejecutar consulta",+ "pending-query": "Consulta pendiente","executing-query": "Ejecutando consulta","request-query": "Solicitar consulta","copy-success": "Copiado al portapapeles",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e36270f4cc..2a26288a65 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -183,7 +183,7 @@"expiration": "有効期限","configure": "設定","groups": "グループ",- "database-groups": "データベースのグループ化",+ "database-group": "データベースグループ | データベースグループ","members": "メンバー","warehouse": "倉庫","schedule": "プラン",@@ -1735,6 +1735,10 @@"to-enable-admin-mode": "管理者モードを有効にするには","notify-empty-statement": "エディターに SQL ステートメントを入力してください","can-not-execute-query": "データのロード中にクエリを実行できません",+ "invalid-database": "無効なデータベース {database}",+ "request-cancelled": "リクエストはキャンセルされました",+ "request-aborted": "ユーザーがリクエストを中止しました",+ "no-data-source": "クエリ可能なデータソースがありません。環境またはプロジェクトのデータソースクエリポリシーを確認してください。","rows": "記録","vertical-display": "縦型表示","no-history-found": "まだ履歴がありません",@@ -1799,9 +1803,12 @@},"batch-query": {"batch": "バッチ",- "description": "{project} の下にある {count} データベースをバッチクエリします。",+ "select-database-group": "バッチクエリを実行するには{select-database-group}を使用します",+ "description": "{project} の下の {database} 個の追加データベースと {group} 個のデータベース グループに対してバッチ クエリを実行します。","show-or-hide-empty-query-results": "空のクエリ結果の表示/非表示"},+ "execute-query": "クエリを実行する",+ "pending-query": "保留中のクエリ","executing-query": "クエリの実行","request-query": "リクエストクエリ","copy-success": "正常にコピーされました",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 852df7d6eb..dc4d835a78 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -183,7 +183,7 @@"expiration": "Hết hạn","configure": "Cấu hình","groups": "Nhóm",- "database-groups": "Nhóm cơ sở dữ liệu",+ "database-group": "Nhóm cơ sở dữ liệu | Nhóm cơ sở dữ liệu","members": "Thành viên","warehouse": "Kho","schedule": "Lịch trình",@@ -1735,6 +1735,10 @@"to-enable-admin-mode": "để bật chế độ quản trị","notify-empty-statement": "Vui lòng nhập câu lệnh SQL của bạn vào trình soạn thảo","can-not-execute-query": "Không thể thực hiện truy vấn khi đang tải dữ liệu.",+ "invalid-database": "Cơ sở dữ liệu không hợp lệ {database}",+ "request-cancelled": "Yêu cầu đã bị hủy",+ "request-aborted": "Người dùng đã hủy yêu cầu",+ "no-data-source": "Không có nguồn dữ liệu có thể truy vấn. Vui lòng kiểm tra chính sách truy vấn nguồn dữ liệu trên môi trường hoặc dự án.","rows": "dòng | dòng","vertical-display": "Hiển thị dọc","no-history-found": "Không tìm thấy lịch sử",@@ -1799,9 +1803,12 @@},"batch-query": {"batch": "Hàng loạt",- "description": "Truy vấn hàng loạt {count} cơ sở dữ liệu bổ sung trong {project}.",+ "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"},+ "execute-query": "Thực hiện truy vấn",+ "pending-query": "Đang chờ truy vấn","executing-query": "Đang thực hiện truy vấn","request-query": "Yêu cầu truy vấn","copy-success": "Sao chép thành công",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex e960a9227f..81dfd5f7b9 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -183,7 +183,7 @@"expiration": "过期时间","configure": "配置","groups": "分组",- "database-groups": "数据库分组",+ "database-group": "数据库分组","members": "成员","warehouse": "仓库","schedule": "计划",@@ -1735,6 +1735,10 @@"to-enable-admin-mode": "来开启管理员模式","notify-empty-statement": "请在编辑器中输入 SQL 语句","can-not-execute-query": "加载数据时无法执行查询",+ "invalid-database": "数据库 {database} 无效",+ "request-cancelled": "请求已取消",+ "request-aborted": "用户中止了请求",+ "no-data-source": "没有可查询的数据源。请检查环境或项目的数据源查询策略。","rows": "条记录","vertical-display": "竖向展示","no-history-found": "暂无历史记录",@@ -1799,9 +1803,12 @@},"batch-query": {"batch": "批量",- "description": "批量查询 {project} 下的 {count} 个数据库。",+ "select-database-group": "您可以{select-database-group}进行批量查询",+ "description": "批量查询 {project} 下的 {database} 个数据库和 {group} 个数据库组。","show-or-hide-empty-query-results": "显示/隐藏空查询结果"},+ "execute-query": "执行查询",+ "pending-query": "待处理查询","executing-query": "执行查询","request-query": "请求查询","copy-success": "复制成功",@@ -2451,7 +2458,7 @@"condition": {"self": "条件"},- "select": "选择数据库组",+ "select": "选择数据库分组","no-matched-databases": "没有匹配的数据库"},"export-center": {diff --git a/frontend/src/store/modules/dbGroup.ts b/frontend/src/store/modules/dbGroup.tsindex 17c0c6c3fa..e9e380a545 100644--- a/frontend/src/store/modules/dbGroup.ts+++ b/frontend/src/store/modules/dbGroup.ts@@ -2,7 +2,7 @@ import { computedAsync } from "@vueuse/core";import { head } from "lodash-es";import { defineStore } from "pinia";import type { MaybeRef } from "vue";-import { computed, ref, unref, watchEffect } from "vue";+import { computed, ref, unref, watch, watchEffect } from "vue";import { databaseGroupServiceClient } from "@/grpcweb";import type { ConditionGroupExpr } from "@/plugins/cel";import {@@ -378,3 +378,24 @@ export const useDatabaseInGroupFilter = (};return { isPreparingDatabaseGroups, databaseFilter };};++export const useDatabaseGroupByName = (name: MaybeRef<string>) => {+ const store = useDBGroupStore();+ const ready = ref(true);+ watch(+ () => unref(name),+ (name) => {+ ready.value = false;+ store.getOrFetchDBGroupByName(name).then(() => {+ ready.value = true;+ });+ },+ { immediate: true }+ );+ const databaseGroup = computed(() => store.getDBGroupByName(unref(name)));++ return {+ databaseGroup,+ ready,+ };+};diff --git a/frontend/src/store/modules/export.ts b/frontend/src/store/modules/export.tsdeleted file mode 100644index 1b149f579d..0000000000--- a/frontend/src/store/modules/export.ts+++ /dev/null@@ -1,15 +0,0 @@-import { useSQLStore } from "@/store";-import type { ExportRequest } from "@/types/proto/v1/sql_service";--export const useExportData = () => {- const sqlStore = useSQLStore();-- const exportData = async (params: ExportRequest) => {- const { content } = await sqlStore.exportData(params);- return content;- };-- return {- exportData,- };-};diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.tsindex a707133d95..8c390a9759 100644--- a/frontend/src/store/modules/sqlEditor/tab.ts+++ b/frontend/src/store/modules/sqlEditor/tab.ts@@ -7,6 +7,7 @@ import type {SQLEditorConnection,CoreSQLEditorTab,SQLEditorTab,+ SQLEditorDatabaseQueryContext,} from "@/types";import { DEFAULT_SQL_EDITOR_TAB_MODE, isValidDatabaseName } from "@/types";import {@@ -246,6 +247,33 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {if (!id) return;updateTab(id, payload);};++ const updateQueryContext = ({+ database,+ contextId,+ context,+ }: {+ database: string;+ contextId: string;+ context: Partial<SQLEditorDatabaseQueryContext>;+ }) => {+ const tab = tabById(currentTabId.value);+ if (!tab || !tab.databaseQueryContexts) {+ return;+ }+ if (!tab.databaseQueryContexts.has(database)) {+ return;+ }+ const target = tab.databaseQueryContexts+ .get(database)+ ?.find((c) => c.id === contextId);+ if (!target) {+ return;+ }+ Object.assign(target, context);+ return target;+ };+const setCurrentTabId = (id: string) => {currentTabId.value = id;};@@ -381,6 +409,7 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {removeTab,updateTab,updateCurrentTab,+ updateQueryContext,setCurrentTabId,selectOrAddSimilarNewTab,maybeInitProject,diff --git a/frontend/src/store/modules/v1/sql.ts b/frontend/src/store/modules/v1/sql.tsindex 7712ed623f..61602289b7 100644--- a/frontend/src/store/modules/v1/sql.ts+++ b/frontend/src/store/modules/v1/sql.ts@@ -8,7 +8,7 @@ import type { ExportRequest, QueryRequest } from "@/types/proto/v1/sql_service";import { Advice, Advice_Status } from "@/types/proto/v1/sql_service";import { extractGrpcErrorMessage } from "@/utils/grpcweb";-const getSqlReviewReports = (err: unknown): Advice[] => {+export const getSqlReviewReports = (err: unknown): Advice[] => {const advices: Advice[] = [];if (err instanceof RichClientError) {for (const extra of err.extra) {@@ -66,10 +66,11 @@ export const useSQLStore = defineStore("sql", () => {};const exportData = async (params: ExportRequest) => {- return await sqlServiceClient.export(params, {+ const { content } = await sqlServiceClient.export(params, {// Won't jump to 403 page when permission denied.ignoredCodes: [Status.PERMISSION_DENIED],});+ return content;};return {diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.tsindex dc2b04e893..abf996d30c 100644--- a/frontend/src/types/sqlEditor/tab.ts+++ b/frontend/src/types/sqlEditor/tab.ts@@ -17,21 +17,27 @@ export type BatchQueryContext = {// databases is used to store the selected database names.// Format: instances/{instance}/databases/{database}databases: string[];-};-export type SQLEditorTabQueryContext = {- beginTimestampMS: number;- abortController: AbortController;- status: "IDLE" | "EXECUTING";+ // databaseGroups is used to store the selected database group names for batch request.+ // Format: projects/{project}/databaseGroups/{databaseGroup}+ databaseGroups: string[];+};- results: Map<- string /* database or instance */,- {- params: SQLEditorQueryParams;- beginTimestampMS: number;- resultSet: SQLResultSetV1;- }[]- >;+export type SQLEditorDatabaseQueryContext = {+ id: string;+ // we will generate a new abortController when status changed to EXECUTING.+ abortController?: AbortController;+ // request params in the history.+ params: SQLEditorQueryParams;+ // PENDING: ready, pending to request.+ // EXECUTING: requesting.+ // DONE: request finished.+ // CANCELLED: request cancelled.+ status: "PENDING" | "EXECUTING" | "DONE" | "CANCELLED";+ // beginTimestampMS will store the start request time when status changed to EXECUTING.+ beginTimestampMS?: number;+ // query result.+ resultSet?: SQLResultSetV1;};export type SQLEditorTab = {@@ -47,7 +53,10 @@ export type SQLEditorTab = {// SQL query related fields// won't be saved to localStorage- queryContext?: SQLEditorTabQueryContext;+ databaseQueryContexts?: Map<+ string /* database or instance */,+ SQLEditorDatabaseQueryContext[]+ >;batchQueryContext?: BatchQueryContext;// extended fieldsdiff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.tsindex ba4c063bda..5cf8aa7ac2 100644--- a/frontend/src/utils/sqlEditor.ts+++ b/frontend/src/utils/sqlEditor.ts@@ -12,7 +12,6 @@ import type {CoreSQLEditorTab,SQLEditorConnection,SQLEditorTab,- SQLEditorTabQueryContext,} from "@/types";import {DEFAULT_SQL_EDITOR_TAB_MODE,@@ -169,13 +168,6 @@ export const tryConnectToCoreSQLEditorTab = (tabStore.updateCurrentTab(tab);};-export const emptySQLEditorTabQueryContext = (): SQLEditorTabQueryContext => ({- beginTimestampMS: Date.now(),- abortController: new AbortController(),- status: "IDLE",- results: new Map(),-});-export const getAdminDataSourceRestrictionOfDatabase = (database: ComposedDatabase) => {diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vueindex 1b6b288d3b..b4ebedca8e 100644--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue+++ b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue@@ -84,11 +84,6 @@ const show = computed(() => {state.value !== undefined &&position.value.x !== 0 &&position.value.y !== 0;- // TODO(ed):- // if (show && state.value?.view) {- // const comment = state.value.view.comment;- // if (!comment) return false;- // }return show;});diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/BatchQueryDatabaseGroupSelector.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/BatchQueryDatabaseGroupSelector.vuenew file mode 100644index 0000000000..76bfcc898c--- /dev/null+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/BatchQueryDatabaseGroupSelector.vue@@ -0,0 +1,151 @@+<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"+ :loading="!ready"+ v-model:selected-database-group-names="state.selectedDatabaseGroupNames"+ />+ </div>+ </NPopover>++ <FeatureModal+ feature="bb.feature.database-grouping"+ :open="state.showFeatureModal"+ @cancel="state.showFeatureModal = false"+ />+</template>++<script lang="ts" setup>+import { BoxesIcon } from "lucide-vue-next";+import { NPopover, NButton } 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,+ useAppFeature,+ useConnectionOfCurrentSQLEditorTab,+ useSQLEditorStore,+ useSQLEditorTabStore,+ useDBGroupListByProject,+} from "@/store/modules";+import { isValidDatabaseName } from "@/types";++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("bb.feature.batch-query");+const hasDatabaseGroupFeature = featureToRef("bb.feature.database-grouping");+const disallowBatchQuery = useAppFeature(+ "bb.feature.sql-editor.disallow-batch-query"+);+const { database } = useConnectionOfCurrentSQLEditorTab();++const { dbGroupList, ready } = useDBGroupListByProject(+ computed(() => editorStore.project)+);++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(() => {+ if (disallowBatchQuery.value) {+ return false;+ }+ 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.updateCurrentTab({+ batchQueryContext: {+ databases: tabStore.currentTab?.batchQueryContext?.databases ?? [],+ 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 da92db4f18..1143922949 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue@@ -7,10 +7,21 @@<FeatureBadge feature="bb.feature.batch-query" />{{$t("sql-editor.batch-query.description", {- count: state.selectedDatabases.size,+ database: state.selectedDatabases.size,+ group:+ tabStore.currentTab?.batchQueryContext?.databaseGroups.length ??+ 0,project: project.title,})}}+ <i18n-t+ v-if="hasDatabaseGroupFeature && tabStore.currentTab"+ keypath="sql-editor.batch-query.select-database-group"+ >+ <template #select-database-group>+ <BatchQueryDatabaseGroupSelector />+ </template>+ </i18n-t></div><divclass="w-full mt-1 flex flex-row justify-start items-start flex-wrap gap-2"@@ -18,16 +29,25 @@<NTagv-for="database in state.selectedDatabases":key="database"- closable+ :closable="database !== tabStore.currentTab?.connection.database"@close="() => handleUncheckDatabase(database)"><RichDatabaseName:database="databaseStore.getDatabaseByName(database)"/></NTag>+ <template v-if="hasDatabaseGroupFeature">+ <DatabaseGroupTag+ v-for="databaseGroupName in tabStore.currentTab?.batchQueryContext+ ?.databaseGroups ?? []"+ :key="databaseGroupName"+ :database-group-name="databaseGroupName"+ @uncheck="handleUncheckDatabaseGroup"+ />+ </template></div></div>- <NDivider class="!my-3" />+ <NDivider v-if="tabStore.currentTab" class="!my-3" /><div class="flex flex-row gap-x-0.5 px-1 items-center"><AdvancedSearchv-model:params="state.params"@@ -141,7 +161,7 @@ import MaskSpinner from "@/components/misc/MaskSpinner.vue";import { RichDatabaseName } from "@/components/v2";import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";import {- hasFeature,+ featureToRef,batchGetOrFetchDatabases,useProjectV1Store,useDatabaseV1Store,@@ -174,6 +194,8 @@ import {} from "@/utils";import type { SearchParams } from "@/utils";import { useSQLEditorContext } from "../../context";+import BatchQueryDatabaseGroupSelector from "./BatchQueryDatabaseGroupSelector.vue";+import DatabaseGroupTag from "./DatabaseGroupTag.vue";import {DatabaseHoverPanel,provideHoverStateContext,@@ -194,9 +216,8 @@ const editorStore = useSQLEditorStore();const databaseStore = useDatabaseV1Store();const projectStore = useProjectV1Store();-const hasBatchQueryFeature = computed(() =>- hasFeature("bb.feature.batch-query")-);+const hasBatchQueryFeature = featureToRef("bb.feature.batch-query");+const hasDatabaseGroupFeature = featureToRef("bb.feature.database-grouping");const state = reactive<LocalState>({selectedDatabases: new Set(),@@ -247,6 +268,8 @@ watch(tabStore.updateCurrentTab({batchQueryContext: {databases: selectedDatabases,+ databaseGroups:+ tabStore.currentTab?.batchQueryContext?.databaseGroups ?? [],},});}@@ -256,6 +279,17 @@ const handleUncheckDatabase = (database: string) => {state.selectedDatabases.delete(database);};+const handleUncheckDatabaseGroup = (databaseGroupName: string) => {+ tabStore.updateCurrentTab({+ batchQueryContext: {+ databases: tabStore.currentTab?.batchQueryContext?.databases ?? [],+ databaseGroups: (+ tabStore.currentTab?.batchQueryContext?.databaseGroups ?? []+ ).filter((name) => name !== databaseGroupName),+ },+ });+};+const scopeOptions = useCommonSearchScopeOptions([...CommonFilterScopeIdList,"database-label",@@ -376,6 +410,7 @@ const nodeProps = ({ option }: { option: TreeOption }) => {tabStore.updateCurrentTab({batchQueryContext: {databases: [],+ databaseGroups: [],},});showConnectionPanel.value = false;diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vuenew file mode 100644index 0000000000..312990ea7e--- /dev/null+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/DatabaseGroupTag.vue@@ -0,0 +1,28 @@+<template>+ <NTooltip v-if="databaseGroup">+ <template #trigger>+ <NTag closable @close="() => $emit('uncheck', databaseGroupName)">+ {{ databaseGroup.title }}+ </NTag>+ </template>+ {{ $t("common.database-group") }}+ </NTooltip>+</template>++<script lang="tsx" setup>+import { NTag, NTooltip } from "naive-ui";+import { computed } from "vue";+import { useDatabaseGroupByName } from "@/store";++const props = defineProps<{+ databaseGroupName: string;+}>();++defineEmits<{+ (event: "uncheck", databaseGroupName: string): void;+}>();++const { databaseGroup } = useDatabaseGroupByName(+ computed(() => props.databaseGroupName)+);+</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vue b/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vueindex 3b32a15873..312df9df22 100644--- a/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vue+++ b/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vue@@ -21,10 +21,7 @@"class="flex flex-row items-center text-main">- <NPopover- v-if="(currentTab.batchQueryContext?.databases.length ?? 0) > 1"- placement="bottom"- >+ <NPopover v-if="isBatchRequest" placement="bottom"><template #trigger><SquareStackIcon class="w-4 h-4 mr-1 text-accent" /></template>@@ -61,12 +58,14 @@import { ChevronRightIcon, SquareStackIcon } from "lucide-vue-next";import { NButton, NPopover } from "naive-ui";import { storeToRefs } from "pinia";+import { computed } from "vue";import { DatabaseIcon } from "@/components/Icon";import { InstanceV1EngineIcon, EnvironmentV1Name } from "@/components/v2";import {useConnectionOfCurrentSQLEditorTab,useSQLEditorStore,useSQLEditorTabStore,+ hasFeature,} from "@/store";import { isValidDatabaseName, isValidInstanceName } from "@/types";import { useSQLEditorContext } from "../context";@@ -84,6 +83,24 @@ const changeConnection = () => {defineProps<{disabled?: boolean;}>();++const isBatchRequest = computed(() => {+ if (!currentTab.value) {+ return false;+ }+ if (!hasFeature("bb.feature.batch-query")) {+ return false;+ }+ const { batchQueryContext } = currentTab.value;+ if (!batchQueryContext) {+ return false;+ }+ const { databaseGroups, databases } = batchQueryContext;+ if (!hasFeature("bb.feature.database-grouping")) {+ return databases.length > 1;+ }+ return databaseGroups.length > 0 || databases.length > 1;+});</script><style lang="postcss" scoped>diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex 8db28a1ee9..05963c5193 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -214,9 +214,6 @@ const isEmptyStatement = computed(() => {}return tab.statement === "";});-const isExecutingSQL = computed(- () => currentTab.value?.queryContext?.status === "EXECUTING"-);const { instance } = useConnectionOfCurrentSQLEditorTab();const { t } = useI18n();@@ -238,7 +235,6 @@ const queryTip = computed(() => {const allowQuery = computed(() => {if (isDisconnected.value) return false;if (isEmptyStatement.value) return false;- if (isExecutingSQL.value) return false;if (instance.value.engine === Engine.COSMOSDB) {return !!currentTab.value?.connection.table;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vueindex 413c2ba1fa..ce42830f4a 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue@@ -24,7 +24,7 @@</div><PostgresError v-if="resultSet" :result-set="resultSet" /><div v-if="showRunAnywayButton">- <NButton size="small" type="primary" @click="runAnyway">+ <NButton size="small" type="warning" @click="runAnyway">{{ $t("sql-editor.run-anyway") }}</NButton></div>@@ -37,7 +37,6 @@ import { NButton } from "naive-ui";import { Status } from "nice-grpc-common";import { storeToRefs } from "pinia";import { computed } from "vue";-import { useExecuteSQL } from "@/composables/useExecuteSQL";import { useAppFeature, useSQLEditorTabStore } from "@/store";import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";import { DatabaseChangeMode } from "@/types/proto/v1/setting_service";@@ -52,10 +51,13 @@ const props = defineProps<{resultSet?: SQLResultSetV1;}>();+const emit = defineEmits<{+ (event: "execute", params: SQLEditorQueryParams): void;+}>();+const sqlCheckStyle = useAppFeature("bb.feature.sql-editor.sql-check-style");const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());const { dark } = useSQLResultViewContext();-const { execute } = useExecuteSQL();const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");const showRunAnywayButton = computed(() => {@@ -76,7 +78,7 @@ const showRunAnywayButton = computed(() => {const runAnyway = () => {const params = props.executeParams;if (!params) return;- execute({+ emit("execute", {...params,skipCheck: true,});diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vueindex fdd6cfb717..e90d1323d0 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue@@ -11,6 +11,7 @@:error="resultSet.results[0]?.error":execute-params="executeParams":result-set="resultSet"+ @execute="$emit('execute', $event)"/><SingleResultViewV1v-else@@ -30,21 +31,29 @@<NTabPanev-for="(result, i) in filteredResults":key="i"- :name="tabName(result, i)"+ :name="tabName(i)"class="flex-1 flex flex-col overflow-hidden"><template #tab>- <span>{{ tabName(result, i) }}</span>- <Info- v-if="result.error"- class="ml-2 text-yellow-600 w-4 h-auto"- />+ <NTooltip>+ <template #trigger>+ <div class="flex items-center space-x-2">+ <span>{{ tabName(i) }}</span>+ <Info+ v-if="result.error"+ class="text-yellow-600 w-4 h-auto"+ />+ </div>+ </template>+ {{ result.statement }}+ </NTooltip></template><ErrorViewv-if="result.error":error="result.error":execute-params="executeParams":result-set="resultSet"+ @execute="$emit('execute', $event)"/><SingleResultViewV1v-else@@ -64,6 +73,7 @@:error="resultSet.error":execute-params="executeParams":result-set="resultSet"+ @execute="$emit('execute', $event)"><template #suffix><RequestQueryButton@@ -106,7 +116,13 @@<script lang="ts" setup>import { Info } from "lucide-vue-next";-import { darkTheme, NConfigProvider, NTabs, NTabPane } from "naive-ui";+import {+ darkTheme,+ NConfigProvider,+ NTabs,+ NTabPane,+ NTooltip,+} from "naive-ui";import { Status } from "nice-grpc-common";import { computed, ref, toRef } from "vue";import { useI18n } from "vue-i18n";@@ -128,7 +144,6 @@ import type {DatabaseResource,} from "@/types";import { PolicyType } from "@/types/proto/v1/org_policy_service";-import type { QueryResult } from "@/types/proto/v1/sql_service";import { hasWorkspacePermissionV2 } from "@/utils";import DetailPanel from "./DetailPanel";import EmptyView from "./EmptyView.vue";@@ -142,21 +157,24 @@ type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";const props = withDefaults(defineProps<{- executeParams?: SQLEditorQueryParams;- database?: ComposedDatabase;+ executeParams: SQLEditorQueryParams;+ database: ComposedDatabase;resultSet?: SQLResultSetV1;loading?: boolean;dark?: boolean;}>(),{executeParams: undefined,- database: undefined,resultSet: undefined,loading: false,dark: false,});+defineEmits<{+ (event: "execute", params: SQLEditorQueryParams): void;+}>();+const { t } = useI18n();const policyStore = usePolicyV1Store();const { instance, database: connectedDatabase } =@@ -232,7 +250,7 @@ const showPlaceholder = computed(() => {return false;});-const tabName = (result: QueryResult, index: number) => {+const tabName = (index: number) => {return `${t("common.query")} #${index + 1}`;};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vueindex d061ce9b92..fb0e17fc60 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue@@ -200,8 +200,8 @@ import {pushNotification,usePolicyByParentAndType,useStorageStore,+ useSQLStore,} from "@/store";-import { useExportData } from "@/store/modules/export";import type { ComposedDatabase, SQLEditorQueryParams } from "@/types";import {DEBOUNCE_SEARCH_DELAY,@@ -450,7 +450,7 @@ const handleExportBtnClick = async (const limit = options.limit ?? (admin ? 0 : editorStore.resultRowsLimit);try {- const content = await useExportData().exportData({+ const content = await useSQLStore().exportData({name: database,// TODO(lj): support data source id similar to queries.dataSourceId: "",diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vueindex 7c02a3d978..07ea2c14b2 100644--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue@@ -9,7 +9,7 @@tertiarysize="small":type="showEmpty ? 'primary' : 'default'"- style="--n-padding: 6px"+ style="--n-padding: 6px; margin-bottom: 0.5rem"@click="showEmpty = !showEmpty"><EyeIcon v-if="showEmpty" class="w-4 h-4" />@@ -59,19 +59,23 @@<script setup lang="ts">import { useLocalStorage } from "@vueuse/core";-import { head, last } from "lodash-es";+import { head } from "lodash-es";import { EyeIcon, EyeOffIcon, InfoIcon, XIcon } from "lucide-vue-next";import { NButton, NTooltip, NScrollbar } from "naive-ui";import { storeToRefs } from "pinia";-import { computed, watch } from "vue";+import { computed, watch, watchEffect } from "vue";import { RichDatabaseName } from "@/components/v2";-import { useDatabaseV1Store, useSQLEditorTabStore } from "@/store";-import type { ComposedDatabase, SQLResultSetV1 } from "@/types";+import {+ useDatabaseV1Store,+ useSQLEditorTabStore,+ batchGetOrFetchDatabases,+} from "@/store";+import type { ComposedDatabase, SQLEditorDatabaseQueryContext } from "@/types";import { hexToRgb } from "@/utils";type BatchQueryItem = {database: ComposedDatabase;- resultSet: SQLResultSetV1 | undefined;+ context: SQLEditorDatabaseQueryContext | undefined;};const props = defineProps<{@@ -91,27 +95,36 @@ const showEmpty = useLocalStorage();const queriedDatabaseNames = computed(() =>- Array.from(tab.value?.queryContext?.results.keys() || [])+ Array.from(tab.value?.databaseQueryContexts?.keys() || []));+watchEffect(async () => {+ await batchGetOrFetchDatabases(queriedDatabaseNames.value);+});+const items = computed(() => {return queriedDatabaseNames.value.map<BatchQueryItem>((name) => {const database = databaseStore.getDatabaseByName(name);- const result = last(tab.value?.queryContext?.results.get(name));- return { database, resultSet: result?.resultSet };+ const context = head(tab.value?.databaseQueryContexts?.get(name));+ return { database, context };});});const isEmptyQueryItem = (item: BatchQueryItem) => {- if (!item.resultSet) {+ if (!item.context) {return true;}- if (item.resultSet.error) {+ if (item.context.resultSet?.error) {// Failed queries have empty result sets, but should not be recognized// as empty result sets.return false;}- return item.resultSet.results.every((result) => result.rows.length === 0);+ if (item.context.status !== "DONE") {+ return false;+ }+ return item.context.resultSet?.results.every(+ (result) => result.rows.length === 0+ );};const filteredItems = computed(() => {@@ -132,13 +145,20 @@ const showEmptySwitch = computed(() => {const isDatabaseQueryFailed = (item: BatchQueryItem) => {// If there is any error in the result set, we consider the query failed.return (- item.resultSet?.error ||- item.resultSet?.results.find((result) => result.error)+ item.context?.resultSet?.error ||+ item.context?.resultSet?.results.find((result) => result.error));};const handleCloseSingleResultView = (database: ComposedDatabase) => {- tab.value?.queryContext?.results.delete(database.name || "");+ const contexts = tab.value?.databaseQueryContexts?.get(database.name);+ if (!contexts) {+ return;+ }+ for (const context of contexts) {+ context.abortController?.abort();+ }+ tab.value?.databaseQueryContexts?.delete(database.name);};// Auto select a proper database when the databases are ready.diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vuenew file mode 100644index 0000000000..a649513ea6--- /dev/null+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue@@ -0,0 +1,111 @@+<template>+ <template v-if="context.status === 'EXECUTING'">+ <div+ class="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80"+ >+ <div class="flex items-center gap-x-1">+ <BBSpin :size="20" class="mr-1" />+ <span>{{ $t("sql-editor.executing-query") }}</span>+ <span>-</span>+ <!-- use mono font to prevent the UI jitters frequently -->+ <span class="font-mono">{{ queryElapsedTime }}</span>+ </div>+ <div>+ <NButton size="small" @click="cancelQuery">+ {{ $t("common.cancel") }}+ </NButton>+ </div>+ </div>+ </template>+ <template v-else-if="context.status === 'CANCELLED'">+ <div+ class="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80"+ >+ <NButton size="small" @click="() => execQuery(context.params)">+ {{ $t("sql-editor.execute-query") }}+ </NButton>+ </div>+ </template>+ <ResultViewV1+ v-else+ class="w-full h-auto grow"+ :execute-params="context.params"+ :database="database"+ :context="context"+ :result-set="context.resultSet"+ @execute="execQuery"+ />+</template>++<script lang="tsx" setup>+import { useTimestamp } from "@vueuse/core";+import { NButton } from "naive-ui";+import { computed, watch } from "vue";+import { BBSpin } from "@/bbkit";+import { useExecuteSQL } from "@/composables/useExecuteSQL";+import { useSQLEditorTabStore } from "@/store";+import type {+ SQLEditorDatabaseQueryContext,+ SQLEditorQueryParams,+} from "@/types";+import type { ComposedDatabase } from "@/types";+import { ResultViewV1 } from "../../EditorCommon/";++const props = defineProps<{+ database: ComposedDatabase;+ context: SQLEditorDatabaseQueryContext;+}>();++const executeSQL = useExecuteSQL();+const tabStore = useSQLEditorTabStore();++const loading = computed(() => props.context.status === "EXECUTING");++const currentTimestampMS = useTimestamp();+const queryElapsedTime = computed(() => {+ if (!loading.value) {+ return "";+ }+ const beginMS = props.context.beginTimestampMS;+ if (!beginMS) {+ return "";+ }+ const elapsedMS = currentTimestampMS.value - beginMS;+ return `${(elapsedMS / 1000).toFixed(1)}s`;+});++const cancelQuery = () => {+ props.context.abortController?.abort();+ tabStore.updateQueryContext({+ database: props.database.name,+ contextId: props.context.id,+ context: {+ status: "CANCELLED",+ },+ });+};++watch(+ [() => props.database, () => props.context.status],+ async ([database, status]) => {+ if (status === "PENDING") {+ await executeSQL.runQuery(database, props.context);+ }+ },+ { immediate: true, deep: true }+);++const execQuery = async (params: SQLEditorQueryParams) => {+ const context = tabStore.updateQueryContext({+ database: props.database.name,+ contextId: props.context.id,+ context: {+ params,+ },+ });+ if (!context) {+ return;+ }+ await executeSQL.runQuery(props.database, context);+};+</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vueindex b9792206a9..c3af7396b8 100644--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue@@ -2,131 +2,94 @@<divclass="relative w-full h-full flex flex-col justify-start items-start z-10 overflow-x-hidden">- <template v-if="loading">- <div- class="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80"+ <BatchQuerySelect v-model:selected-database="selectedDatabase" />+ <NTabs+ v-if="selectedDatabase && queryContexts"+ type="card"+ size="small"+ class="flex-1 flex flex-col overflow-hidden px-2"+ :class="isBatchQuery ? 'pt-0' : 'pt-2'"+ style="--n-tab-padding: 4px 12px"+ v-model:value="selectedTab"+ >+ <NTabPane+ v-for="(context, i) in queryContexts"+ :key="i"+ :name="context.id"+ class="flex-1 flex flex-col overflow-hidden">- <div class="flex items-center gap-x-1">- <BBSpin :size="20" class="mr-1" />- <span>{{ $t("sql-editor.executing-query") }}</span>- <span>-</span>- <!-- use mono font to prevent the UI jitters frequently -->- <span class="font-mono">{{ queryElapsedTime }}</span>- </div>- <div>- <NButton size="small" @click="cancelQuery">- {{ $t("common.cancel") }}- </NButton>- </div>- </div>- </template>- <template v-else>- <BatchQuerySelect v-model:selected-database="selectedDatabase" />- <template v-if="selectedResults.length === 0">- <div- class="w-full h-full flex flex-col justify-center items-center text-sm"- >- <span>{{ $t("sql-editor.table-empty-placeholder") }}</span>- </div>- </template>- <NTabs- v-else- type="card"- size="small"- class="flex-1 flex flex-col overflow-hidden px-2"- :class="isBatchQuery ? 'pt-0' : 'pt-2'"- style="--n-tab-padding: 4px 12px"- v-model:value="selectedTab"- >- <NTabPane- v-for="(result, i) in selectedResults"- :key="i"- :name="result.beginTimestampMS"- class="flex-1 flex flex-col overflow-hidden"- >- <template #tab>- <span>{{ tabName(result.beginTimestampMS) }}</span>- <Info- v-if="result.resultSet.error"- class="ml-2 text-yellow-600 w-4 h-auto"- />- </template>- <ResultViewV1- class="w-full h-auto grow"- :execute-params="result.params"- :database="selectedDatabase"- :result-set="result.resultSet"- />- </NTabPane>- </NTabs>- </template>+ <template #tab>+ <NTooltip>+ <template #trigger>+ <div class="flex items-center space-x-2">+ <span>{{ tabName(context) }}</span>+ <Info+ v-if="context.resultSet?.error"+ class="text-yellow-600 w-4 h-auto"+ />+ <BBSpin v-if="context.status === 'EXECUTING'" :size="10" />+ </div>+ </template>+ {{ context.params.statement }}+ </NTooltip>+ </template>+ <DatabaseQueryContext+ class="w-full h-auto grow"+ :database="selectedDatabase"+ :context="context"+ />+ </NTabPane>+ </NTabs></div></template><script lang="ts" setup>-import { useTimestamp } from "@vueuse/core";import dayjs from "dayjs";import { head } from "lodash-es";import { Info } from "lucide-vue-next";-import { NButton, NTabs, NTabPane } from "naive-ui";+import { NTabs, NTabPane, NTooltip } from "naive-ui";import { computed, ref, watch } from "vue";+import { useI18n } from "vue-i18n";import { BBSpin } from "@/bbkit";import { useSQLEditorTabStore } from "@/store";-import type { ComposedDatabase } from "@/types";-import { ResultViewV1 } from "../../EditorCommon/";+import type { ComposedDatabase, SQLEditorDatabaseQueryContext } from "@/types";import BatchQuerySelect from "./BatchQuerySelect.vue";+import DatabaseQueryContext from "./DatabaseQueryContext.vue";-const tabStore = useSQLEditorTabStore();const selectedDatabase = ref<ComposedDatabase>();-const selectedTab = ref<number>();+const tabStore = useSQLEditorTabStore();+const selectedTab = ref<string>();+const { t } = useI18n();++const isBatchQuery = computed(+ () =>+ Array.from(tabStore.currentTab?.databaseQueryContexts?.keys() || [])+ .length > 1+);-const selectedResults = computed(() => {- return (- tabStore.currentTab?.queryContext?.results.get(- selectedDatabase.value?.name || ""- ) ?? []+const queryContexts = computed(() => {+ const contexts = tabStore.currentTab?.databaseQueryContexts?.get(+ selectedDatabase.value?.name ?? "");+ return contexts;});-const tabName = (beginTimestampMS: number) => {- return dayjs(beginTimestampMS).format("YYYY-MM-DD HH:mm:ss");+const tabName = (context: SQLEditorDatabaseQueryContext) => {+ switch (context.status) {+ case "PENDING":+ return t("sql-editor.pending-query");+ case "EXECUTING":+ return t("sql-editor.executing-query");+ default:+ return dayjs(context.beginTimestampMS).format("YYYY-MM-DD HH:mm:ss");+ }};watch(- () => selectedResults.value,- (results) => {- selectedTab.value = head(results)?.beginTimestampMS;+ () => head(queryContexts.value)?.id,+ (id) => {+ selectedTab.value = id;},- { deep: true }-);--const loading = computed(- () => tabStore.currentTab?.queryContext?.status === "EXECUTING"+ { immediate: true });-const currentTimestampMS = useTimestamp();-const queryElapsedTime = computed(() => {- if (!loading.value) {- return "";- }- const tab = tabStore.currentTab;- if (!tab) {- return "";- }- const beginMS = tabStore.currentTab?.queryContext?.beginTimestampMS;- if (!beginMS) {- return "";- }- const elapsedMS = currentTimestampMS.value - beginMS;- return `${(elapsedMS / 1000).toFixed(1)}s`;-});--const isBatchQuery = computed(- () =>- Array.from(tabStore.currentTab?.queryContext?.results.keys() || []).length >- 1-);--const cancelQuery = () => {- tabStore.currentTab?.queryContext?.abortController.abort();-};</script>