Skip to content

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

feat: batch export in sql editor (#16305)

ecmadaoe70e369f5ecf
diff --git a/frontend/src/components/DataExportButton.vue b/frontend/src/components/DataExportButton.vue
index 9a94f6da70..b2cc1e3cb2 100644
--- a/frontend/src/components/DataExportButton.vue
+++ b/frontend/src/components/DataExportButton.vue
@@ -11,6 +11,7 @@
:quaternary="size === 'tiny'"
:size="size"
type="primary"
+ v-bind="$attrs"
:loading="state.isRequesting"
:disabled="state.isRequesting || disabled"
@click="handleClickExportButton"
@@ -19,7 +20,7 @@
<DownloadIcon class="h-4 w-4" />
</template>
<span v-if="size !== 'tiny'">
- {{ t("common.export") }}
+ {{ text }}
</span>
</NButton>
</template>
@@ -30,7 +31,7 @@
<Drawer v-if="viewMode === 'DRAWER'" v-model:show="state.showDrawer">
<DrawerContent
:title="$t('custom-approval.risk-rule.risk.namespace.data_export')"
- class="w-[30rem] max-w-[100vw] relative"
+ class="w-[50rem] max-w-[100vw] relative"
>
<template #default>
<NForm
@@ -39,6 +40,7 @@
:rules="rules"
label-placement="left"
>
+ <slot name="form" />
<NFormItem path="limit" :label="$t('export-data.export-rows')">
<MaxRowCountSelect v-model:value="formData.limit" />
</NFormItem>
@@ -54,6 +56,7 @@
</NRadioGroup>
</NFormItem>
<NFormItem
+ v-if="supportPassword"
path="password"
:label="$t('export-data.password-optional')"
>
@@ -74,7 +77,10 @@
:button-props="{
type: 'primary',
loading: state.isRequesting,
- disabled: formErrors.length > 0 || state.isRequesting,
+ disabled:
+ formErrors.length > 0 ||
+ state.isRequesting ||
+ !validate(formData),
}"
:errors="formErrors"
@click="tryExportViaForm"
@@ -113,6 +119,9 @@
<script lang="ts" setup>
import { asyncComputed } from "@vueuse/core";
+import dayjs from "dayjs";
+import saveAs from "file-saver";
+import JSZip from "jszip";
import { DownloadIcon } from "lucide-vue-next";
import type { FormInst, FormRules } from "naive-ui";
import {
@@ -126,8 +135,8 @@ import {
} from "naive-ui";
import type { BinaryLike } from "node:crypto";
import { computed, reactive, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
import { BBModal, BBTextField } from "@/bbkit";
+import { t } from "@/plugins/i18n";
import { pushNotification } from "@/store";
import { ExportFormat, exportFormatToJSON } from "@/types/proto/v1/common";
import { isNullOrUndefined } from "@/utils";
@@ -140,6 +149,11 @@ interface LocalState {
showModal: boolean;
}
+export type DownloadContent = Array<{
+ content: BinaryLike | Blob;
+ filename: string;
+}>;
+
export interface ExportOption {
limit: number;
format: ExportFormat;
@@ -151,14 +165,19 @@ const props = withDefaults(
size?: "small" | "tiny" | "medium" | "large";
disabled?: boolean;
supportFormats: ExportFormat[];
+ supportPassword?: boolean;
viewMode: "DRAWER" | "DROPDOWN";
- fileType: "zip" | "raw";
tooltip?: string;
+ text?: string;
+ validate?: (option: ExportOption) => boolean;
}>(),
{
size: "small",
disabled: false,
tooltip: undefined,
+ supportPassword: false,
+ text: () => t("common.export"),
+ validate: (_: ExportOption) => true,
}
);
@@ -171,12 +190,14 @@ const defaultFormData = (): ExportOption => ({
const emit = defineEmits<{
(
event: "export",
- options: ExportOption,
- download: (content: BinaryLike | Blob, filename: string) => void
+ option: {
+ resolve: (content: DownloadContent) => void;
+ reject: (reason?: any) => void;
+ options: ExportOption;
+ }
): Promise<void>;
}>();
-const { t } = useI18n();
const state = reactive<LocalState>({
isRequesting: false,
showDrawer: false,
@@ -201,6 +222,11 @@ const rules: FormRules = {
trigger: ["input", "blur"],
},
],
+ format: [
+ {
+ required: true,
+ },
+ ],
};
const exportDropdownOptions = computed(() => {
@@ -212,21 +238,21 @@ const exportDropdownOptions = computed(() => {
}));
});
-const tryExportViaDropdown = async (format: ExportFormat) => {
+const tryExportViaDropdown = (format: ExportFormat) => {
formData.value.format = format;
- if (props.fileType === "zip") {
+ if (props.supportPassword) {
state.showModal = true;
} else {
- await doExport();
+ doExport();
}
};
-const exportViaDropdown = async () => {
+const exportViaDropdown = () => {
state.showModal = false;
- await doExport();
+ doExport();
};
-const tryExportViaForm = async (e: MouseEvent) => {
+const tryExportViaForm = (e: MouseEvent) => {
e.preventDefault();
formRef.value?.validate((errors) => {
if (errors) return;
@@ -256,36 +282,48 @@ const handleClickExportButton = (e: MouseEvent) => {
state.showDrawer = true;
};
-const doExport = async () => {
+const doExport = () => {
if (state.isRequesting) {
return;
}
state.isRequesting = true;
const options = { ...formData.value };
- try {
- await emit(
- "export",
+
+ new Promise<DownloadContent>((resolve, reject) => {
+ return emit("export", {
+ resolve,
+ reject,
options,
- (content: BinaryLike | Blob, filename: string) => {
- doDownload(content, options, filename);
- }
- );
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: `Failed to export data`,
- description: JSON.stringify(error),
});
- } finally {
- state.isRequesting = false;
- state.showDrawer = false;
- }
+ })
+ .then((content: DownloadContent) => {
+ return doDownload(content, options);
+ })
+ .then(() => {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.success"),
+ description: t("audit-log.export-finished"),
+ });
+ })
+ .catch((error) => {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `Failed to export data`,
+ description: JSON.stringify(error),
+ });
+ })
+ .finally(() => {
+ state.isRequesting = false;
+ state.showDrawer = false;
+ });
};
const downloadFileAsZip = (options: ExportOption) => {
- return props.fileType === "zip" && !!options.password;
+ return !!options.password;
};
const getExportFileType = (format: ExportFormat) => {
@@ -301,10 +339,9 @@ const getExportFileType = (format: ExportFormat) => {
}
};
-const doDownload = async (
+const cnovertSingleFile = async (
content: BinaryLike | Blob,
- options: ExportOption,
- filename: string
+ options: ExportOption
) => {
const isZip = downloadFileAsZip(options);
const fileType = isZip
@@ -321,6 +358,21 @@ const doDownload = async (
type: fileType,
});
}
+ return blob;
+};
+
+const doDownloadSingleFile = async (
+ {
+ content,
+ filename,
+ }: {
+ content: BinaryLike | Blob;
+ filename: string;
+ },
+ options: ExportOption
+) => {
+ const blob = await cnovertSingleFile(content, options);
+ const isZip = downloadFileAsZip(options);
const url = window.URL.createObjectURL(blob);
const fileFormat = exportFormatToJSON(options.format).toLowerCase();
@@ -330,6 +382,23 @@ const doDownload = async (
link.click();
};
+const doDownload = async (content: DownloadContent, options: ExportOption) => {
+ if (content.length === 1) {
+ return doDownloadSingleFile(content[0], options);
+ }
+
+ const fileFormat = exportFormatToJSON(options.format).toLowerCase();
+ const zip = new JSZip();
+ for (const c of content) {
+ const blob = await cnovertSingleFile(c.content, options);
+ zip.file(`${c.filename}.${fileFormat}`, blob);
+ }
+
+ const zipFile = await zip.generateAsync({ type: "blob" });
+ const fileName = `download_${dayjs().format("YYYY-MM-DDTHH-mm-ss")}.zip`;
+ saveAs(zipFile, fileName);
+};
+
watch(
() => [state.showDrawer, state.showModal],
([showDrawer, showModal]) => {
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue
index ac8201cbf8..3267f3d6a9 100644
--- a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue
+++ b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue
@@ -6,6 +6,7 @@
:data="databaseList"
:striped="true"
:bordered="bordered"
+ :pagination="pagination"
:loading="loading"
:row-key="(data: ComposedDatabase) => data.name"
:checked-row-keys="props.selectedDatabaseNames"
@@ -50,6 +51,12 @@ const props = withDefaults(
selectedDatabaseNames?: string[];
keyword?: string;
rowClick?: (e: MouseEvent, val: ComposedDatabase) => void;
+ pagination?:
+ | false
+ | {
+ defaultPageSize: number;
+ disabled: boolean;
+ };
}>(),
{
mode: "ALL",
@@ -58,6 +65,7 @@ const props = withDefaults(
rowClickable: true,
keyword: undefined,
selectedDatabaseNames: () => [],
+ pagination: false,
}
);
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 3f1d7c78b4..9031f6c369 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1812,6 +1812,11 @@
"not-match": "Data source not match, expect {expect} but got {actual}."
}
},
+ "batch-export": {
+ "self": "Batch export",
+ "tooltip": "Select at most {max} databases to batch export latest query results",
+ "failed-for-db": "Failed to export data for {db}"
+ },
"execute-query": "Execute query",
"pending-query": "Pending query",
"executing-query": "Executing query",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 168ec0f82a..620795ad17 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1812,6 +1812,11 @@
"not-match": "La fuente de datos no coincide, se esperaba {expect} pero se obtuvo {actual}."
}
},
+ "batch-export": {
+ "self": "Exportación por lotes",
+ "tooltip": "Seleccione como máximo {max} bases de datos para exportar por lotes los resultados de las últimas consultas",
+ "failed-for-db": "No se pudieron exportar los datos de {db}"
+ },
"execute-query": "Ejecutar consulta",
"pending-query": "Consulta pendiente",
"executing-query": "Ejecutando consulta",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 02658595f1..be77e63660 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1812,6 +1812,11 @@
"not-match": "データ ソースが一致しません。{expect} を期待しましたが、{actual} を取得しました。"
}
},
+ "batch-export": {
+ "self": "一括エクスポート",
+ "tooltip": "最新のクエリ結果を一括エクスポートするには、最大 {max} 個のデータベースを選択してください",
+ "failed-for-db": "{db} のデータのエクスポートに失敗しました"
+ },
"execute-query": "クエリを実行する",
"pending-query": "保留中のクエリ",
"executing-query": "クエリの実行",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 442b292e78..c126aace9b 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1812,6 +1812,11 @@
"not-match": "Nguồn dữ liệu không khớp, mong đợi {expect} nhưng lại nhận được {actual}."
}
},
+ "batch-export": {
+ "self": "Xuất hàng loạt",
+ "tooltip": "Chọn tối đa {max} cơ sở dữ liệu để xuất hàng loạt kết quả truy vấn mới nhất",
+ "failed-for-db": "Không xuất được dữ liệu cho {db}"
+ },
"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",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index adce0c2376..7232e3d9ae 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1812,6 +1812,11 @@
"not-match": "数据源不匹配,预期为 {expect},但实际使用 {actual}。"
}
},
+ "batch-export": {
+ "self": "批量导出",
+ "tooltip": "最多选择 {max} 个数据库,批量导出最后一次执行的查询结果",
+ "failed-for-db": "无法导出 {db} 的数据"
+ },
"execute-query": "执行查询",
"pending-query": "待处理查询",
"executing-query": "执行查询",
diff --git a/frontend/src/store/modules/v1/auditLog.ts b/frontend/src/store/modules/v1/auditLog.ts
index 2d2e15a26e..8b9d031b50 100644
--- a/frontend/src/store/modules/v1/auditLog.ts
+++ b/frontend/src/store/modules/v1/auditLog.ts
@@ -49,10 +49,12 @@ export const useAuditLogStore = defineStore("audit_log", () => {
search,
format,
pageSize,
+ pageToken,
}: {
search: SearchAuditLogsParams;
format: ExportFormat;
pageSize: number;
+ pageToken: string;
}): Promise<{
content: BinaryLike | Blob;
nextPageToken: string;
@@ -63,6 +65,7 @@ export const useAuditLogStore = defineStore("audit_log", () => {
orderBy: search.order ? `create_time ${search.order}` : undefined,
format,
pageSize,
+ pageToken,
});
};
diff --git a/frontend/src/views/SettingWorkspaceAuditLog.vue b/frontend/src/views/SettingWorkspaceAuditLog.vue
index ae3a5fd0ae..ad38c50126 100644
--- a/frontend/src/views/SettingWorkspaceAuditLog.vue
+++ b/frontend/src/views/SettingWorkspaceAuditLog.vue
@@ -5,7 +5,6 @@
<template #searchbox-suffix>
<DataExportButton
size="medium"
- :file-type="'raw'"
:support-formats="[
ExportFormat.CSV,
ExportFormat.JSON,
@@ -40,14 +39,16 @@
<script lang="ts" setup>
import dayjs from "dayjs";
import { NEmpty } from "naive-ui";
-import type { BinaryLike } from "node:crypto";
import { reactive, computed, watch, ref } from "vue";
import type { ComponentExposed } from "vue-component-type-helpers";
import { useI18n } from "vue-i18n";
import AuditLogDataTable from "@/components/AuditLog/AuditLogDataTable.vue";
import AuditLogSearch from "@/components/AuditLog/AuditLogSearch";
import { buildSearchAuditLogParams } from "@/components/AuditLog/AuditLogSearch/utils";
-import type { ExportOption } from "@/components/DataExportButton.vue";
+import type {
+ ExportOption,
+ DownloadContent,
+} from "@/components/DataExportButton.vue";
import DataExportButton from "@/components/DataExportButton.vue";
import { FeatureAttention } from "@/components/FeatureGuard";
import PagedTable from "@/components/v2/Model/PagedTable.vue";
@@ -55,7 +56,6 @@ import {
featureToRef,
useAuditLogStore,
batchGetOrFetchProjects,
- pushNotification,
useUserStore,
} from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
@@ -145,32 +145,37 @@ const disableExportTip = computed(() => {
return "";
});
-const handleExport = async (
- options: ExportOption,
- callback: (content: BinaryLike | Blob, filename: string) => void
-) => {
+const handleExport = async ({
+ options,
+ resolve,
+ reject,
+}: {
+ options: ExportOption;
+ reject: (reason?: any) => void;
+ resolve: (content: DownloadContent) => void;
+}) => {
let pageToken = "";
let i = 0;
+ const contents: DownloadContent = [];
- while (i === 0 || pageToken !== "") {
- i++;
- const { content, nextPageToken } = await auditLogStore.exportAuditLogs({
- search: searchAuditLogs.value,
- format: options.format,
- pageSize: 10000,
- });
- pageToken = nextPageToken;
- callback(
- content,
- `audit-log${!pageToken && i === 1 ? "" : `.file${i}`}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`
- );
+ try {
+ while (i === 0 || pageToken !== "") {
+ i++;
+ const { content, nextPageToken } = await auditLogStore.exportAuditLogs({
+ search: searchAuditLogs.value,
+ format: options.format,
+ pageSize: 1,
+ pageToken,
+ });
+ pageToken = nextPageToken;
+ contents.push({
+ content,
+ filename: `audit-log.file${i}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`,
+ });
+ }
+ resolve(contents);
+ } catch (err) {
+ reject(err);
}
-
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.success"),
- description: t("audit-log.export-finished"),
- });
};
</script>
diff --git a/frontend/src/views/project/ProjectAuditLogDashboard.vue b/frontend/src/views/project/ProjectAuditLogDashboard.vue
index 9e66591814..39795035ba 100644
--- a/frontend/src/views/project/ProjectAuditLogDashboard.vue
+++ b/frontend/src/views/project/ProjectAuditLogDashboard.vue
@@ -5,7 +5,6 @@
<template #searchbox-suffix>
<DataExportButton
size="medium"
- :file-type="'raw'"
:support-formats="[
ExportFormat.CSV,
ExportFormat.JSON,
@@ -41,7 +40,6 @@
<script setup lang="ts">
import dayjs from "dayjs";
import { NEmpty } from "naive-ui";
-import type { BinaryLike } from "node:crypto";
import { computed, reactive, ref, watch } from "vue";
// https://github.com/vuejs/language-tools/issues/3206
import type { ComponentExposed } from "vue-component-type-helpers";
@@ -49,16 +47,14 @@ import { useI18n } from "vue-i18n";
import AuditLogDataTable from "@/components/AuditLog/AuditLogDataTable.vue";
import AuditLogSearch from "@/components/AuditLog/AuditLogSearch";
import { buildSearchAuditLogParams } from "@/components/AuditLog/AuditLogSearch/utils";
-import type { ExportOption } from "@/components/DataExportButton.vue";
+import type {
+ ExportOption,
+ DownloadContent,
+} from "@/components/DataExportButton.vue";
import DataExportButton from "@/components/DataExportButton.vue";
import { FeatureAttention } from "@/components/FeatureGuard";
import PagedTable from "@/components/v2/Model/PagedTable.vue";
-import {
- featureToRef,
- useAuditLogStore,
- pushNotification,
- useUserStore,
-} from "@/store";
+import { featureToRef, useAuditLogStore, useUserStore } from "@/store";
import { type SearchAuditLogsParams } from "@/types";
import type { AuditLog } from "@/types/proto/v1/audit_log_service";
import { ExportFormat } from "@/types/proto/v1/common";
@@ -151,32 +147,37 @@ const disableExportTip = computed(() => {
return "";
});
-const handleExport = async (
- options: ExportOption,
- callback: (content: BinaryLike | Blob, filename: string) => void
-) => {
+const handleExport = async ({
+ options,
+ resolve,
+ reject,
+}: {
+ options: ExportOption;
+ reject: (reason?: any) => void;
+ resolve: (content: DownloadContent) => void;
+}) => {
let pageToken = "";
let i = 0;
-
- while (i === 0 || pageToken !== "") {
- i++;
- const { content, nextPageToken } = await auditLogStore.exportAuditLogs({
- search: searchAuditLogs.value,
- format: options.format,
- pageSize: 10000,
- });
- pageToken = nextPageToken;
- callback(
- content,
- `audit-log${!pageToken && i === 1 ? "" : `.file${i}`}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`
- );
+ const contents: DownloadContent = [];
+
+ try {
+ while (i === 0 || pageToken !== "") {
+ i++;
+ const { content, nextPageToken } = await auditLogStore.exportAuditLogs({
+ search: searchAuditLogs.value,
+ format: options.format,
+ pageSize: 10000,
+ pageToken,
+ });
+ pageToken = nextPageToken;
+ contents.push({
+ content,
+ filename: `audit-log.file${i}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`,
+ });
+ }
+ resolve(contents);
+ } catch (err) {
+ reject(err);
}
-
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.success"),
- description: t("audit-log.export-finished"),
- });
};
</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
index bc01ca0e62..892d0b6ce1 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -91,7 +91,6 @@
<DataExportButton
v-if="result.allowExport"
size="small"
- :file-type="'zip'"
:disabled="props.result === null || isEmpty(props.result)"
:support-formats="[
ExportFormat.CSV,
@@ -100,8 +99,15 @@
ExportFormat.XLSX,
]"
:view-mode="'DRAWER'"
+ :support-password="true"
@export="handleExportBtnClick"
- />
+ >
+ <template #form>
+ <NFormItem :label="$t('common.database')">
+ <DatabaseInfo :database="database" />
+ </NFormItem>
+ </template>
+ </DataExportButton>
<NButton
v-else-if="allowToRequestExportData"
size="small"
@@ -181,6 +187,7 @@ import { useDebounceFn, useLocalStorage } from "@vueuse/core";
import dayjs from "dayjs";
import { isEmpty } from "lodash-es";
import { ExternalLinkIcon } from "lucide-vue-next";
+import { NFormItem } from "naive-ui";
import {
NButton,
NInput,
@@ -190,14 +197,17 @@ import {
type SelectOption,
NSelect,
} from "naive-ui";
-import type { BinaryLike } from "node:crypto";
import { v4 as uuidv4 } from "uuid";
import { computed, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { BBAttention } from "@/bbkit";
-import type { ExportOption } from "@/components/DataExportButton.vue";
+import type {
+ ExportOption,
+ DownloadContent,
+} from "@/components/DataExportButton.vue";
import DataExportButton from "@/components/DataExportButton.vue";
+import DatabaseInfo from "@/components/DatabaseInfo.vue";
import { DISMISS_PLACEHOLDER } from "@/plugins/ai/components/state";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
@@ -206,7 +216,6 @@ import {
useConnectionOfCurrentSQLEditorTab,
useSQLEditorStore,
useAppFeature,
- pushNotification,
usePolicyByParentAndType,
useStorageStore,
useSQLStore,
@@ -440,18 +449,15 @@ const pageSizeOptions = computed(() => {
}));
});
-const handleExportBtnClick = async (
- options: ExportOption,
- callback: (content: BinaryLike | Blob, filename: string) => void
-) => {
- // If props.database is specified and it's not unknown database
- // the query is executed on database level
- // otherwise the query is executed on instance level, we should use the
- // `instanceId` from the tab's connection attributes
- const databaseName =
- props.database && isValidDatabaseName(props.database.name)
- ? props.database.name
- : "";
+const handleExportBtnClick = async ({
+ options,
+ resolve,
+ reject,
+}: {
+ options: ExportOption;
+ reject: (reason?: any) => void;
+ resolve: (content: DownloadContent) => void;
+}) => {
// use props.params.statement which is the "snapshot" of the query statement
// not using props.result.statement because it might be rewritten by Query() API
const statement = props.params.statement;
@@ -460,7 +466,7 @@ const handleExportBtnClick = async (
try {
const content = await useSQLStore().exportData({
- name: databaseName,
+ name: props.database.name,
dataSourceId: props.params.connection.dataSourceId ?? "",
format: options.format,
statement,
@@ -469,17 +475,14 @@ const handleExportBtnClick = async (
password: options.password,
});
- callback(
- content,
- `export-data.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`
- );
+ resolve([
+ {
+ content,
+ filename: `${props.database.databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`,
+ },
+ ]);
} catch (e) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.error"),
- description: String(e),
- });
+ reject(e);
}
};
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
index eb67731067..eb2b0572c7 100644
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/BatchQuerySelect.vue
@@ -21,6 +21,49 @@
</template>
</NTooltip>
+ <DataExportButton
+ tertiary
+ size="small"
+ :support-formats="[
+ ExportFormat.CSV,
+ ExportFormat.JSON,
+ ExportFormat.SQL,
+ ExportFormat.XLSX,
+ ]"
+ style="margin-bottom: 0.5rem"
+ :view-mode="'DRAWER'"
+ :text="$t('sql-editor.batch-export.self')"
+ :tooltip="$t('sql-editor.batch-export.tooltip', { max: MAX_EXPORT })"
+ :validate="validateExport"
+ :support-password="true"
+ @export="handleExportBtnClick"
+ >
+ <template #form>
+ <div class="w-full mb-6 space-y-2">
+ <div>
+ <p class="textlabel">
+ {{ $t("database.select") }}
+ <RequiredStar />
+ </p>
+ <span class="textinfolabel">
+ {{ $t("sql-editor.batch-export.tooltip", { max: MAX_EXPORT }) }}
+ </span>
+ </div>
+ <DatabaseV1Table
+ :schemaless="true"
+ :mode="'PROJECT_SHORT'"
+ :database-list="databaseList"
+ :show-selection="true"
+ :pagination="{
+ defaultPageSize: MAX_EXPORT,
+ disabled: false,
+ }"
+ v-model:selected-database-names="selectedDatabaseNameList"
+ />
+ </div>
+ </template>
+ </DataExportButton>
+
<NScrollbar x-scrollable class="pb-2">
<div class="flex flex-row justify-start items-center gap-2">
<NButton
@@ -59,16 +102,33 @@
<script setup lang="ts">
import { useLocalStorage } from "@vueuse/core";
+import dayjs from "dayjs";
import { head } from "lodash-es";
import { EyeIcon, EyeOffIcon, CircleAlertIcon, XIcon } from "lucide-vue-next";
import { NButton, NTooltip, NScrollbar } from "naive-ui";
import { storeToRefs } from "pinia";
-import { computed, watch } from "vue";
+import { computed, watch, ref } from "vue";
+import type {
+ ExportOption,
+ DownloadContent,
+} from "@/components/DataExportButton.vue";
+import DataExportButton from "@/components/DataExportButton.vue";
+import RequiredStar from "@/components/RequiredStar.vue";
import { RichDatabaseName } from "@/components/v2";
-import { useDatabaseV1Store, useSQLEditorTabStore } from "@/store";
+import { DatabaseV1Table } from "@/components/v2/Model/DatabaseV1Table";
+import { t } from "@/plugins/i18n";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useSQLEditorTabStore,
+ useSQLStore,
+} from "@/store";
import type { ComposedDatabase, SQLEditorDatabaseQueryContext } from "@/types";
+import { ExportFormat } from "@/types/proto/v1/common";
import { hexToRgb } from "@/utils";
+const MAX_EXPORT = 20;
+
type BatchQueryItem = {
database: ComposedDatabase;
context: SQLEditorDatabaseQueryContext | undefined;
@@ -85,15 +145,31 @@ const emit = defineEmits<{
const tabStore = useSQLEditorTabStore();
const { currentTab: tab } = storeToRefs(tabStore);
const databaseStore = useDatabaseV1Store();
+const sqlStore = useSQLStore();
const showEmpty = useLocalStorage(
"bb.sql-editor.batch-query.show-empty-result-sets",
true
);
+const selectedDatabaseNameList = ref<string[]>([]);
+
const queriedDatabaseNames = computed(() =>
Array.from(tab.value?.databaseQueryContexts?.keys() || [])
);
+const databaseList = computed(() => {
+ return queriedDatabaseNames.value.map((name) =>
+ databaseStore.getDatabaseByName(name)
+ );
+});
+
+const validateExport = () => {
+ return (
+ selectedDatabaseNameList.value.length > 0 &&
+ selectedDatabaseNameList.value.length <= MAX_EXPORT
+ );
+};
+
const items = computed(() => {
return queriedDatabaseNames.value.map<BatchQueryItem>((name) => {
const database = databaseStore.getDatabaseByName(name);
@@ -178,4 +254,50 @@ const getBackgroundColorRgb = (database: ComposedDatabase) => {
borderTop: "3px solid",
};
};
+
+const handleExportBtnClick = async ({
+ options,
+ resolve,
+}: {
+ options: ExportOption;
+ reject: (reason?: any) => void;
+ resolve: (content: DownloadContent) => void;
+}) => {
+ const contents: DownloadContent = [];
+ for (const databaseName of selectedDatabaseNameList.value) {
+ const database = databaseStore.getDatabaseByName(databaseName);
+ const context = head(tab.value?.databaseQueryContexts?.get(databaseName));
+ if (!context) {
+ continue;
+ }
+ try {
+ const content = await sqlStore.exportData({
+ name: databaseName,
+ dataSourceId: context.params.connection.dataSourceId ?? "",
+ format: options.format,
+ statement: context.params.statement,
+ limit: options.limit,
+ admin: tabStore.currentTab?.mode === "ADMIN",
+ password: options.password,
+ });
+
+ contents.push({
+ content,
+ filename: `${database.databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}`,
+ });
+ } catch (e) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("sql-editor.batch-export.failed-for-db", {
+ db: databaseName,
+ }),
+ description: String(e),
+ });
+ }
+ }
+
+ resolve(contents);
+ selectedDatabaseNameList.value = [];
+};
</script>