Skip to content

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

feat(frontend): use export v1 API in sql editor (#6532)

Liu Ji023124e5abe7
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue
index 421821e52b..65e5939fc1 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultView.vue
@@ -4,9 +4,12 @@
class="relative flex flex-col justify-start items-start p-2"
:class="dark && 'dark bg-dark-bg'"
>
- <template v-if="resultSet && !showPlaceholder">
+ <template v-if="executeParams && resultSet && !showPlaceholder">
<template v-if="viewMode === 'SINGLE-RESULT'">
- <SingleResultView :result="resultSet.resultList[0]" />
+ <SingleResultView
+ :params="executeParams"
+ :result="resultSet.resultList[0]"
+ />
</template>
<template v-else-if="viewMode === 'MULTI-RESULT'">
<NTabs
@@ -20,7 +23,7 @@
:name="tabName(result, i)"
class="flex-1 flex flex-col overflow-hidden"
>
- <SingleResultView :result="result" />
+ <SingleResultView :params="executeParams" :result="result" />
</NTabPane>
</NTabs>
</template>
@@ -56,13 +59,26 @@ 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 { SingleSQLResult, SQLResultSet } from "@/types";
+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,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
index 4037d2b350..696bf6f182 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue
@@ -4,9 +4,12 @@
class="relative flex flex-col justify-start items-start p-2"
:class="dark && 'dark bg-dark-bg'"
>
- <template v-if="resultSet && !showPlaceholder">
+ <template v-if="executeParams && resultSet && !showPlaceholder">
<template v-if="viewMode === 'SINGLE-RESULT'">
- <SingleResultViewV1 :result="resultSet.results[0]" />
+ <SingleResultViewV1
+ :params="executeParams"
+ :result="resultSet.results[0]"
+ />
</template>
<template v-else-if="viewMode === 'MULTI-RESULT'">
<NTabs
@@ -20,7 +23,7 @@
:name="tabName(result, i)"
class="flex-1 flex flex-col overflow-hidden"
>
- <SingleResultViewV1 :result="result" />
+ <SingleResultViewV1 :params="executeParams" :result="result" />
</NTabPane>
</NTabs>
</template>
@@ -56,7 +59,7 @@ import { darkTheme, NConfigProvider, NTabs, NTabPane } from "naive-ui";
import { darkThemeOverrides } from "@/../naive-ui.config";
import SingleResultViewV1 from "./SingleResultViewV1.vue";
import EmptyView from "./EmptyView.vue";
-import { SQLResultSetV1 } from "@/types";
+import { ExecuteConfig, ExecuteOption, SQLResultSetV1 } from "@/types";
import { provideSQLResultViewContext } from "./context";
import ErrorView from "./ErrorView.vue";
import { QueryResult } from "@/types/proto/v1/sql_service";
@@ -64,6 +67,14 @@ import { QueryResult } from "@/types/proto/v1/sql_service";
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<SQLResultSetV1>,
default: undefined,
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue
index 6f97a70a1e..ab42f341f7 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultView.vue
@@ -49,7 +49,7 @@
:options="exportDropdownOptions"
@select="handleExportBtnClick"
>
- <NButton>
+ <NButton :loading="isExportingData" :disabled="isExportingData">
<template #icon>
<heroicons-outline:download class="h-5 w-5" />
</template>
@@ -107,10 +107,14 @@ import {
useVueTable,
} from "@tanstack/vue-table";
import { isEmpty } from "lodash-es";
-import { unparse } from "papaparse";
-import dayjs from "dayjs";
-import { SingleSQLResult, UNKNOWN_ID } from "@/types";
+import {
+ ExecuteConfig,
+ ExecuteOption,
+ SingleSQLResult,
+ TabMode,
+ UNKNOWN_ID,
+} from "@/types";
import {
createExplainToken,
hasWorkspacePermissionV1,
@@ -132,6 +136,7 @@ import ErrorView from "./ErrorView.vue";
import { useSQLResultViewContext } from "./context";
import { Engine } from "@/types/proto/v1/common";
import { useRouter } from "vue-router";
+import { useExportData } from "./useExportData";
type LocalState = {
search: string;
@@ -142,6 +147,11 @@ 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;
}>();
@@ -158,6 +168,7 @@ const instanceStore = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
const currentUserV1 = useCurrentUserV1();
const dataTable = ref<InstanceType<typeof DataTable>>();
+const { isExportingData, exportData } = useExportData();
const viewMode = computed((): ViewMode => {
const { result } = props;
@@ -245,12 +256,12 @@ table.setPageSize(DEFAULT_PAGE_SIZE);
const exportDropdownOptions = computed(() => [
{
label: t("sql-editor.download-as-csv"),
- key: "csv",
+ key: "CSV",
disabled: props.result === null || isEmpty(props.result),
},
{
label: t("sql-editor.download-as-json"),
- key: "json",
+ key: "JSON",
disabled: props.result === null || isEmpty(props.result),
},
]);
@@ -271,7 +282,7 @@ const showRequestExportButton = computed(() => {
);
});
-const handleExportBtnClick = (format: "csv" | "json") => {
+const handleExportBtnClick = (format: "CSV" | "JSON") => {
if (!allowToExportData.value) {
pushNotification({
module: "bytebase",
@@ -281,43 +292,22 @@ const handleExportBtnClick = (format: "csv" | "json") => {
return;
}
- let rawText = "";
-
- if (format === "csv") {
- const csvFields = columns.value.map((col) => col.header as string);
- const csvData = data.value.map((d) => {
- const temp: any[] = [];
- for (const k in d) {
- temp.push(d[k]);
- }
- return temp;
- });
-
- rawText = unparse({
- fields: csvFields,
- data: csvData,
- });
- } else {
- const objects = [];
- for (const item of data.value) {
- const object = {} as any;
- for (let i = 0; i < columns.value.length; i++) {
- object[columns.value[i].header as string] = item[i];
- }
- objects.push(object);
- }
- rawText = JSON.stringify(objects);
- }
-
- const encodedUri = encodeURI(`data:text/${format};charset=utf-8,${rawText}`);
- const formattedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");
- // Example filename: `mysheet-2022-03-23T09-54-21.json`
- const filename = `${tabStore.currentTab.name}-${formattedDateString}`;
- const link = document.createElement("a");
-
- link.download = `${filename}.${format}`;
- link.href = encodedUri;
- link.click();
+ 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 handleGotoRequestExportPage = () => {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
index 9767b87f47..51b887e77b 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue
@@ -49,7 +49,7 @@
:options="exportDropdownOptions"
@select="handleExportBtnClick"
>
- <NButton>
+ <NButton :loading="isExportingData" :disabled="isExportingData">
<template #icon>
<heroicons-outline:download class="h-5 w-5" />
</template>
@@ -107,8 +107,6 @@ import {
useVueTable,
} from "@tanstack/vue-table";
import { isEmpty } from "lodash-es";
-import { unparse } from "papaparse";
-import dayjs from "dayjs";
import {
createExplainToken,
@@ -132,8 +130,15 @@ import ErrorView from "./ErrorView.vue";
import { useSQLResultViewContext } from "./context";
import { Engine } from "@/types/proto/v1/common";
import { QueryResult } from "@/types/proto/v1/sql_service";
-import { SQLResultSetV1, UNKNOWN_ID } from "@/types";
+import {
+ ExecuteConfig,
+ ExecuteOption,
+ SQLResultSetV1,
+ TabMode,
+ UNKNOWN_ID,
+} from "@/types";
import { useRouter } from "vue-router";
+import { useExportData } from "./useExportData";
type LocalState = {
search: string;
@@ -144,6 +149,11 @@ const PAGE_SIZES = [20, 50, 100];
const DEFAULT_PAGE_SIZE = 50;
const props = defineProps<{
+ params: {
+ query: string;
+ config: ExecuteConfig;
+ option?: Partial<ExecuteOption> | undefined;
+ };
result: QueryResult;
}>();
@@ -160,6 +170,7 @@ const instanceStore = useInstanceV1Store();
const databaseStore = useDatabaseV1Store();
const currentUserV1 = useCurrentUserV1();
const dataTable = ref<InstanceType<typeof DataTable>>();
+const { isExportingData, exportData } = useExportData();
const viewMode = computed((): ViewMode => {
const { result } = props;
@@ -260,17 +271,17 @@ table.setPageSize(DEFAULT_PAGE_SIZE);
const exportDropdownOptions = computed(() => [
{
label: t("sql-editor.download-as-csv"),
- key: "csv",
+ key: "CSV",
disabled: props.result === null || isEmpty(props.result),
},
{
label: t("sql-editor.download-as-json"),
- key: "json",
+ key: "JSON",
disabled: props.result === null || isEmpty(props.result),
},
]);
-const handleExportBtnClick = (format: "csv" | "json") => {
+const handleExportBtnClick = (format: "CSV" | "JSON") => {
if (!allowToExportData.value) {
pushNotification({
module: "bytebase",
@@ -280,43 +291,22 @@ const handleExportBtnClick = (format: "csv" | "json") => {
return;
}
- let rawText = "";
-
- if (format === "csv") {
- const csvFields = columns.value.map((col) => col.header as string);
- const csvData = data.value.map((d) => {
- const temp: any[] = [];
- for (const k in d) {
- temp.push(d[k]);
- }
- return temp;
- });
-
- rawText = unparse({
- fields: csvFields,
- data: csvData,
- });
- } else {
- const objects = [];
- for (const item of data.value) {
- const object = {} as any;
- for (let i = 0; i < columns.value.length; i++) {
- object[columns.value[i].header as string] = item[i];
- }
- objects.push(object);
- }
- rawText = JSON.stringify(objects);
- }
-
- const encodedUri = encodeURI(`data:text/${format};charset=utf-8,${rawText}`);
- const formattedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");
- // Example filename: `mysheet-2022-03-23T09-54-21.json`
- const filename = `${tabStore.currentTab.name}-${formattedDateString}`;
- const link = document.createElement("a");
-
- link.download = `${filename}.${format}`;
- link.href = encodedUri;
- link.click();
+ 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 => {
diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts
new file mode 100644
index 0000000000..9ea7b2ef85
--- /dev/null
+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/useExportData.ts
@@ -0,0 +1,65 @@
+import { ref } from "vue";
+
+import { getExportRequestFormat, pushNotification, useSQLStore } from "@/store";
+import { extractDatabaseResourceName } from "@/utils";
+import dayjs from "dayjs";
+
+export type ExportDataParams = {
+ format: "CSV" | "JSON";
+ statement: string;
+ limit: number;
+ database: string; // instances/{instance}/databases/{database}
+ instance: string; // instances/{instance}
+};
+
+export const useExportData = () => {
+ const isExportingData = ref(false);
+ const sqlStore = useSQLStore();
+
+ const exportData = async (params: ExportDataParams) => {
+ isExportingData.value = true;
+
+ try {
+ const connectionDatabase = params.database
+ ? extractDatabaseResourceName(params.database).database
+ : "";
+
+ const { content } = await sqlStore.exportData({
+ name: params.instance,
+ connectionDatabase,
+ statement: params.statement,
+ limit: params.limit,
+ format: getExportRequestFormat(params.format),
+ });
+
+ const blob = new Blob([content], {
+ type: params.format === "CSV" ? "text/csv" : "application/json",
+ });
+ const url = window.URL.createObjectURL(blob);
+
+ const fileExt = params.format.toLowerCase();
+ const formattedDateString = dayjs(new Date()).format(
+ "YYYY-MM-DDTHH-mm-ss"
+ );
+ const filename = `export-data-${formattedDateString}`;
+ const link = document.createElement("a");
+ link.download = `${filename}.${fileExt}`;
+ link.href = url;
+ link.click();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `Failed to export data`,
+ description: JSON.stringify(error),
+ });
+ } finally {
+ isExportingData.value = false;
+ }
+ };
+
+ return {
+ isExportingData,
+ exportData,
+ };
+};
diff --git a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
index 3b85996eca..229b5ce511 100644
--- a/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
+++ b/frontend/src/views/sql-editor/ResultPanel/ResultPanel.vue
@@ -1,6 +1,7 @@
<template>
<ResultViewV1
class="w-full h-full"
+ :execute-params="executeParams"
:result-set="resultSet"
:loading="loading"
/>
@@ -15,5 +16,6 @@ import { useTabStore } from "@/store";
const tabStore = useTabStore();
const resultSet = computed(() => tabStore.currentTab.sqlResultSet);
+const executeParams = computed(() => tabStore.currentTab.executeParams);
const loading = computed(() => tabStore.currentTab.isExecutingSQL);
</script>
diff --git a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue
index 4e42531285..97a8984326 100644
--- a/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue
+++ b/frontend/src/views/sql-editor/TerminalPanel/TerminalPanel.vue
@@ -29,8 +29,9 @@
@clear-screen="handleClearScreen"
/>
<ResultView
- v-if="query.queryResult"
+ v-if="query.executeParams && query.queryResult"
class="max-h-[20rem] flex-1 flex flex-col overflow-hidden"
+ :execute-params="query.executeParams"
:result-set="query.queryResult"
:loading="query.status === 'RUNNING'"
:dark="true"