Skip to content

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

chore: add download as SQL option in SQL Editor (#6889)

boojacke0aeb9a4888e
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 569ad97990..6ad9f7d233 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1702,8 +1702,7 @@
"loading-data": "Loading Data...",
"table-empty-placeholder": "Click Run to execute the query.",
"no-rows-found": "No rows found",
- "download-as-csv": "Download as CSV",
- "download-as-json": "Download as JSON",
+ "download-as-file": "Download as {file}",
"only-select-allowed": "Only {select} statements are allowed to execute.",
"want-to-action": "If you want to {want}, click the {action} button and submit an issue.",
"table-schema-placeholder": "Select a table to see its schema",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 4202c06c00..41fc6a2433 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1702,8 +1702,7 @@
"loading-data": "Cargando datos...",
"table-empty-placeholder": "Haga clic en Ejecutar para ejecutar la consulta.",
"no-rows-found": "No se encontraron filas",
- "download-as-csv": "Descargar como CSV",
- "download-as-json": "Descargar como JSON",
+ "download-as-file": "Descargar como {file}",
"only-select-allowed": "Solo se permiten declaraciones {select} para ejecutar.",
"want-to-action": "Si desea {want}, haga clic en el botón {action} y envíe una incidencia.",
"table-schema-placeholder": "Seleccione una tabla para ver su esquema",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 8a635771b3..37cafae374 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1697,8 +1697,7 @@
"loading-data": "加载数据中...",
"table-empty-placeholder": "点击 ”运行“ 执行查询",
"no-rows-found": "暂无数据",
- "download-as-csv": "下载为 CSV 格式",
- "download-as-json": "下载为 JSON 格式",
+ "download-as-file": "下载为 {file} 格式",
"only-select-allowed": "只允许执行 {select} 语句",
"want-to-action": "如果您想要{action},点击“{action}”按钮并提交一个工单。",
"table-schema-placeholder": "选择一个表进行查看 Schema",
diff --git a/frontend/src/store/modules/v1/sql.ts b/frontend/src/store/modules/v1/sql.ts
index 7b6a73e468..b95bbef16f 100644
--- a/frontend/src/store/modules/v1/sql.ts
+++ b/frontend/src/store/modules/v1/sql.ts
@@ -61,3 +61,14 @@ export const getExportRequestFormat = (
return ExportRequest_Format.FORMAT_UNSPECIFIED;
}
};
+
+export const getExportFileType = (format: "CSV" | "JSON" | "SQL") => {
+ switch (format) {
+ case "CSV":
+ return "text/csv";
+ case "JSON":
+ return "application/json";
+ case "SQL":
+ return "application/sql";
+ }
+};
diff --git a/frontend/src/views/ExportCenter/ExportDataButton.vue b/frontend/src/views/ExportCenter/ExportDataButton.vue
index 9e59a364f2..e10f02084b 100644
--- a/frontend/src/views/ExportCenter/ExportDataButton.vue
+++ b/frontend/src/views/ExportCenter/ExportDataButton.vue
@@ -37,6 +37,7 @@ import { NButton } from "naive-ui";
import { ExportRecord } from "./types";
import { reactive } from "vue";
import {
+ getExportFileType,
getExportRequestFormat,
pushNotification,
useProjectIamPolicyStore,
@@ -80,8 +81,7 @@ const handleExportData = async () => {
});
const blob = new Blob([content], {
- type:
- exportRecord.exportFormat === "CSV" ? "text/csv" : "application/json",
+ type: getExportFileType(exportRecord.exportFormat),
});
const url = window.URL.createObjectURL(blob);
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue
deleted file mode 100644
index 65e5939fc1..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue
+++ /dev/null
@@ -1,137 +0,0 @@
-<template>
- <NConfigProvider
- v-bind="naiveUIConfig"
- class="relative flex flex-col justify-start items-start p-2"
- :class="dark && 'dark bg-dark-bg'"
- >
- <template v-if="executeParams && resultSet && !showPlaceholder">
- <template v-if="viewMode === 'SINGLE-RESULT'">
- <SingleResultView
- :params="executeParams"
- :result="resultSet.resultList[0]"
- />
- </template>
- <template v-else-if="viewMode === 'MULTI-RESULT'">
- <NTabs
- type="card"
- size="small"
- class="flex-1 flex flex-col overflow-hidden"
- >
- <NTabPane
- v-for="(result, i) in resultSet.resultList"
- :key="i"
- :name="tabName(result, i)"
- class="flex-1 flex flex-col overflow-hidden"
- >
- <SingleResultView :params="executeParams" :result="result" />
- </NTabPane>
- </NTabs>
- </template>
- <template v-else-if="viewMode === 'EMPTY'">
- <EmptyView />
- </template>
- <template v-else-if="viewMode === 'ERROR'">
- <ErrorView :error="resultSet.error" />
- </template>
- </template>
-
- <div
- v-if="showPlaceholder"
- 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="!resultSet">
- {{ $t("sql-editor.table-empty-placeholder") }}
- </template>
- </div>
- </NConfigProvider>
-</template>
-
-<script lang="ts" setup>
-import { computed, PropType, toRef } from "vue";
-import { useI18n } from "vue-i18n";
-import { darkTheme, NConfigProvider, NTabs, NTabPane } from "naive-ui";
-
-import { darkThemeOverrides } from "@/../naive-ui.config";
-import SingleResultView from "./SingleResultView.vue";
-import EmptyView from "./EmptyView.vue";
-import {
- ExecuteConfig,
- ExecuteOption,
- SingleSQLResult,
- SQLResultSet,
-} from "@/types";
-import { provideSQLResultViewContext } from "./context";
-import ErrorView from "./ErrorView.vue";
-
-type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";
-
-const props = defineProps({
- executeParams: {
- type: Object as PropType<{
- query: string;
- config: ExecuteConfig;
- option?: Partial<ExecuteOption> | undefined;
- }>,
- default: undefined,
- },
- resultSet: {
- type: Object as PropType<SQLResultSet>,
- default: undefined,
- },
- loading: {
- type: Boolean,
- default: false,
- },
- dark: {
- type: Boolean,
- default: false,
- },
-});
-
-const { t } = useI18n();
-
-const viewMode = computed((): ViewMode => {
- const { resultSet } = props;
- if (!resultSet) {
- return "EMPTY";
- }
- const { resultList, error } = resultSet;
- if (error) {
- return "ERROR";
- }
- if (resultList.length === 0) {
- return "EMPTY";
- }
- if (resultList.length === 1) {
- return "SINGLE-RESULT";
- }
- return "MULTI-RESULT";
-});
-
-const naiveUIConfig = computed(() => {
- if (props.dark) {
- return { theme: darkTheme, themeOverrides: darkThemeOverrides.value };
- }
- return {};
-});
-
-const showPlaceholder = computed(() => {
- if (viewMode.value === "ERROR") return false;
- if (!props.resultSet) return true;
- if (props.loading) return true;
- return false;
-});
-
-const tabName = (result: SingleSQLResult, index: number) => {
- return `${t("common.query")} #${index + 1}`;
-};
-
-provideSQLResultViewContext({
- dark: toRef(props, "dark"),
-});
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue
deleted file mode 100644
index 63e2f10cbc..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue
+++ /dev/null
@@ -1,357 +0,0 @@
-<template>
- <template v-if="viewMode === 'RESULT'">
- <div
- class="w-full shrink-0 flex flex-row justify-between items-center mb-2 overflow-x-auto"
- >
- <div class="flex flex-row justify-start items-center mr-2 shrink-0">
- <NInput
- v-if="showSearchFeature"
- v-model:value="state.search"
- class="!max-w-[8rem] sm:!max-w-xs"
- type="text"
- :placeholder="t('sql-editor.search-results')"
- >
- <template #prefix>
- <heroicons-outline:search class="h-5 w-5 text-gray-300" />
- </template>
- </NInput>
- <span class="ml-2 whitespace-nowrap text-sm text-gray-500">{{
- `${data.length} ${t("sql-editor.rows", data.length)}`
- }}</span>
- <span
- v-if="data.length === RESULT_ROWS_LIMIT"
- class="ml-2 whitespace-nowrap text-sm text-gray-500"
- >
- <span>-</span>
- <span class="ml-2">{{ $t("sql-editor.rows-upper-limit") }}</span>
- </span>
- </div>
- <div class="flex justify-between items-center gap-x-3">
- <NPagination
- v-if="showPagination"
- :simple="true"
- :item-count="table.getCoreRowModel().rows.length"
- :page="table.getState().pagination.pageIndex + 1"
- :page-size="table.getState().pagination.pageSize"
- @update-page="handleChangePage"
- />
- <NButton
- v-if="showVisualizeButton"
- text
- type="primary"
- @click="visualizeExplain"
- >
- {{ $t("sql-editor.visualize-explain") }}
- </NButton>
- <NDropdown
- v-if="showExportButton"
- trigger="hover"
- :options="exportDropdownOptions"
- @select="handleExportBtnClick"
- >
- <NButton :loading="isExportingData" :disabled="isExportingData">
- <template #icon>
- <heroicons-outline:download class="h-5 w-5" />
- </template>
- {{ t("common.export") }}
- </NButton>
- </NDropdown>
- <NButton
- v-if="showRequestExportButton"
- @click="state.showRequestExportPanel = true"
- >
- {{ $t("quick-action.request-export") }}
- </NButton>
- </div>
- </div>
-
- <div class="flex-1 w-full flex flex-col overflow-y-auto">
- <DataTable
- ref="dataTable"
- :table="table"
- :columns="columns"
- :data="data"
- :sensitive="sensitive"
- :keyword="state.search"
- />
- </div>
- </template>
- <template v-else-if="viewMode === 'AFFECTED-ROWS'">
- <div
- class="text-md font-normal flex items-center gap-x-1"
- :class="[
- dark ? 'text-[var(--color-matrix-green-hover)]' : 'text-control-light',
- ]"
- >
- <span>{{ result.data[2][0][0] }}</span>
- <span>rows affected</span>
- </div>
- </template>
- <template v-else-if="viewMode === 'EMPTY'">
- <EmptyView />
- </template>
- <template v-else-if="viewMode === 'ERROR'">
- <ErrorView :error="result.error" />
- </template>
-
- <RequestExportPanel
- v-if="state.showRequestExportPanel"
- :database-id="currentTab.connection.databaseId"
- :statement="currentTab.statement"
- @close="state.showRequestExportPanel = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { computed, reactive, ref } from "vue";
-import { NPagination } from "naive-ui";
-import { useI18n } from "vue-i18n";
-import { debouncedRef } from "@vueuse/core";
-import {
- ColumnDef,
- getCoreRowModel,
- getPaginationRowModel,
- useVueTable,
-} from "@tanstack/vue-table";
-import { isEmpty } from "lodash-es";
-
-import {
- ExecuteConfig,
- ExecuteOption,
- SingleSQLResult,
- TabMode,
- UNKNOWN_ID,
-} from "@/types";
-import {
- createExplainToken,
- hasWorkspacePermissionV1,
- instanceV1HasStructuredQueryResult,
-} from "@/utils";
-import {
- useInstanceV1Store,
- useTabStore,
- RESULT_ROWS_LIMIT,
- useCurrentUserIamPolicy,
- pushNotification,
- useDatabaseV1Store,
- featureToRef,
- useCurrentUserV1,
-} from "@/store";
-import DataTable from "./DataTable";
-import EmptyView from "./EmptyView.vue";
-import ErrorView from "./ErrorView.vue";
-import { useSQLResultViewContext } from "./context";
-import { Engine } from "@/types/proto/v1/common";
-import { useExportData } from "./useExportData";
-import RequestExportPanel from "@/components/Issue/panel/RequestExportPanel/index.vue";
-
-type LocalState = {
- search: string;
- showRequestExportPanel: boolean;
-};
-type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";
-
-const PAGE_SIZES = [20, 50, 100];
-const DEFAULT_PAGE_SIZE = 50;
-
-const props = defineProps<{
- params: {
- query: string;
- config: ExecuteConfig;
- option?: Partial<ExecuteOption> | undefined;
- };
- result: SingleSQLResult;
-}>();
-
-const state = reactive<LocalState>({
- search: "",
- showRequestExportPanel: false,
-});
-
-const { dark } = useSQLResultViewContext();
-
-const { t } = useI18n();
-const tabStore = useTabStore();
-const instanceStore = useInstanceV1Store();
-const databaseStore = useDatabaseV1Store();
-const currentUserV1 = useCurrentUserV1();
-const dataTable = ref<InstanceType<typeof DataTable>>();
-const { isExportingData, exportData } = useExportData();
-const currentTab = computed(() => tabStore.currentTab);
-
-const viewMode = computed((): ViewMode => {
- const { result } = props;
- if (result.error) {
- return "ERROR";
- }
- const columnNames = result.data?.[0];
- if (columnNames?.length === 0) {
- return "EMPTY";
- }
- if (columnNames?.length === 1 && columnNames[0] === "Affected Rows") {
- return "AFFECTED-ROWS";
- }
- return "RESULT";
-});
-
-const showSearchFeature = computed(() => {
- const instance = instanceStore.getInstanceByUID(
- tabStore.currentTab.connection.instanceId
- );
- return instanceV1HasStructuredQueryResult(instance);
-});
-
-const allowToExportData = computed(() => {
- const database = databaseStore.getDatabaseByUID(
- tabStore.currentTab.connection.databaseId
- );
- return useCurrentUserIamPolicy().allowToExportDatabaseV1(database);
-});
-
-// use a debounced value to improve performance when typing rapidly
-const keyword = debouncedRef(
- computed(() => state.search),
- 200
-);
-
-const columns = computed(() => {
- if (!props.result.data) {
- return [];
- }
- const columns = props.result.data[0];
- return columns.map<ColumnDef<string[]>>((col, index) => ({
- id: `${col}@${index}`,
- accessorFn: (item) => item[index],
- header: col,
- }));
-});
-
-const data = computed(() => {
- if (!props.result.data) {
- return [];
- }
-
- const data = props.result.data[2];
- const search = keyword.value.trim().toLowerCase();
- let temp = data;
- if (search) {
- temp = data.filter((item) => {
- return item.some((col) => String(col).toLowerCase().includes(search));
- });
- }
- return temp;
-});
-
-const sensitive = computed(() => {
- if (!props.result.data) {
- return [];
- }
- return props.result.data[3] ?? [];
-});
-
-const table = useVueTable<string[]>({
- get data() {
- return data.value;
- },
- get columns() {
- return columns.value;
- },
- getCoreRowModel: getCoreRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
-});
-
-table.setPageSize(DEFAULT_PAGE_SIZE);
-
-const exportDropdownOptions = computed(() => [
- {
- label: t("sql-editor.download-as-csv"),
- key: "CSV",
- disabled: props.result === null || isEmpty(props.result),
- },
- {
- label: t("sql-editor.download-as-json"),
- key: "JSON",
- disabled: props.result === null || isEmpty(props.result),
- },
-]);
-
-const showExportButton = computed(() => {
- if (!featureToRef("bb.feature.dba-workflow").value) {
- return true;
- }
- return hasWorkspacePermissionV1(
- "bb.permission.workspace.manage-database",
- currentUserV1.value.userRole
- );
-});
-
-const showRequestExportButton = computed(() => {
- return (
- featureToRef("bb.feature.dba-workflow").value && !showExportButton.value
- );
-});
-
-const handleExportBtnClick = (format: "CSV" | "JSON") => {
- if (!allowToExportData.value) {
- pushNotification({
- module: "bytebase",
- style: "INFO",
- title: "You don't have permission to export data.",
- });
- return;
- }
-
- const { instanceId, databaseId } = tabStore.currentTab.connection;
- const instance = instanceStore.getInstanceByUID(instanceId).name;
- const database =
- databaseId === String(UNKNOWN_ID)
- ? ""
- : databaseStore.getDatabaseByUID(databaseId).name;
- const statement = props.params.query;
- const limit =
- tabStore.currentTab.mode === TabMode.Admin ? 0 : RESULT_ROWS_LIMIT;
- exportData({
- database,
- instance,
- format,
- statement,
- limit,
- });
-};
-
-const showVisualizeButton = computed((): boolean => {
- const instance = instanceStore.getInstanceByUID(
- tabStore.currentTab.connection.instanceId
- );
- const databaseType = instance.engine;
- const { executeParams } = tabStore.currentTab;
- return databaseType === Engine.POSTGRES && !!executeParams?.option?.explain;
-});
-
-const visualizeExplain = () => {
- try {
- const { executeParams, queryResult } = tabStore.currentTab;
- if (!executeParams || !queryResult) return;
-
- const statement = executeParams.query || "";
- if (!statement) return;
-
- const lines: string[][] = queryResult.resultList[0].data[2];
- const explain = lines.map((line) => line[0]).join("\n");
- if (!explain) return;
-
- const token = createExplainToken(statement, explain);
-
- window.open(`/explain-visualizer.html?token=${token}`, "_blank");
- } catch {
- // nothing
- }
-};
-
-const showPagination = computed(() => data.value.length > PAGE_SIZES[0]);
-
-const handleChangePage = (page: number) => {
- table.setPageIndex(page - 1);
- dataTable.value?.scrollTo(0, 0);
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
index 4f666f5f35..b41584a809 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -326,18 +326,23 @@ table.setPageSize(DEFAULT_PAGE_SIZE);
const exportDropdownOptions = computed(() => [
{
- label: t("sql-editor.download-as-csv"),
+ label: t("sql-editor.download-as-file", { file: "CSV" }),
key: "CSV",
disabled: props.result === null || isEmpty(props.result),
},
{
- label: t("sql-editor.download-as-json"),
+ label: t("sql-editor.download-as-file", { file: "JSON" }),
key: "JSON",
disabled: props.result === null || isEmpty(props.result),
},
+ {
+ label: t("sql-editor.download-as-file", { file: "SQL" }),
+ key: "SQL",
+ disabled: props.result === null || isEmpty(props.result),
+ },
]);
-const handleExportBtnClick = (format: "CSV" | "JSON") => {
+const handleExportBtnClick = (format: "CSV" | "JSON" | "SQL") => {
if (!allowToExportData.value) {
pushNotification({
module: "bytebase",
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts
index f80de16e82..2a2a3030ba 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts
@@ -1,4 +1,3 @@
-import ResultView from "./ResultView.vue";
import ResultViewV1 from "./ResultViewV1.vue";
-export { ResultView, ResultViewV1 };
+export { ResultViewV1 };
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts
index 9ea7b2ef85..28b5315de3 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts
@@ -1,11 +1,16 @@
import { ref } from "vue";
-import { getExportRequestFormat, pushNotification, useSQLStore } from "@/store";
+import {
+ getExportFileType,
+ getExportRequestFormat,
+ pushNotification,
+ useSQLStore,
+} from "@/store";
import { extractDatabaseResourceName } from "@/utils";
import dayjs from "dayjs";
export type ExportDataParams = {
- format: "CSV" | "JSON";
+ format: "CSV" | "JSON" | "SQL";
statement: string;
limit: number;
database: string; // instances/{instance}/databases/{database}
@@ -33,7 +38,7 @@ export const useExportData = () => {
});
const blob = new Blob([content], {
- type: params.format === "CSV" ? "text/csv" : "application/json",
+ type: getExportFileType(params.format),
});
const url = window.URL.createObjectURL(blob);