Skip to content

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

feat: add file content preview modal with encoding selector (#11659)

boojack7b5ed4d02e59
diff --git a/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue
index 11885d0c8f..a508299413 100644
--- a/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/DatabaseGroupPrevEditorModal.vue
@@ -18,21 +18,11 @@
/>
</div>
<div class="flex flex-row justify-end items-center shrink-0">
- <NButton class="relative">
- <template #icon>
- <UploadIcon class="w-4 h-4 text-control-light" />
- </template>
- <template #default>
- {{ $t("issue.upload-sql") }}
- <input
- id="sql-file-input"
- type="file"
- accept=".sql,.txt,application/sql,text/plain"
- class="opacity-0 absolute inset-0"
- @change="handleUploadFile"
- />
- </template>
- </NButton>
+ <SQLUploadButton
+ @update:sql="(statement) => (state.editStatement = statement)"
+ >
+ {{ $t("issue.upload-sql") }}
+ </SQLUploadButton>
</div>
</div>
<div class="relative w-full h-96 border rounded overflow-clip">
@@ -68,7 +58,6 @@
</template>
<script lang="ts" setup>
-import { UploadIcon } from "lucide-vue-next";
import { NButton } from "naive-ui";
import type { PropType } from "vue";
import { computed, onMounted, reactive } from "vue";
@@ -76,9 +65,9 @@ import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { MonacoEditor } from "@/components/MonacoEditor";
import ActionConfirmModal from "@/components/SchemaEditorV1/Modals/ActionConfirmModal.vue";
-import { pushNotification, useDBGroupStore } from "@/store";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
+import { useDBGroupStore } from "@/store";
import type { ComposedDatabaseGroup, ComposedSchemaGroup } from "@/types";
-import { MAX_UPLOAD_FILE_SIZE_MB, readFileAsArrayBuffer } from "@/utils";
import { generateDatabaseGroupIssueRoute } from "@/utils/databaseGroup/issue";
interface LocalState {
@@ -156,49 +145,6 @@ const dismissModal = () => {
}
};
-const handleUploadFile = async (e: Event) => {
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
- }
-
- try {
- const { arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- const statement = decoder.decode(arrayBuffer);
- state.editStatement = statement;
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
- }
-
- cleanup();
-};
-
const handlePreviewIssue = async () => {
const issueRoute = generateDatabaseGroupIssueRoute(
props.issueType,
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
index a3b23d8bd3..ee9e550967 100644
--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
@@ -52,22 +52,12 @@
>
<div>{{ $t("sql-editor.self") }}</div>
<div class="flex flex-row justify-end items-center space-x-3">
- <NButton @click="onUploaderClick">
- <template #icon>
- <heroicons-outline:arrow-up-tray
- class="w-4 h-auto text-gray-500"
- />
- </template>
+ <SQLUploadButton
+ :loading="state.isUploadingFile"
+ @update:sql="(statement) => (state.editStatement = statement)"
+ >
{{ $t("issue.upload-sql") }}
- <input
- id="sql-file-input"
- ref="sqlFileUploader"
- type="file"
- accept=".sql,.txt,application/sql,text/plain"
- class="hidden"
- @change="handleUploadFile"
- />
- </NButton>
+ </SQLUploadButton>
<NButton @click="handleSyncSQLFromSchemaEditor">
<template #icon>
<heroicons-outline:arrow-path
@@ -135,6 +125,7 @@ import { computed, onMounted, h, reactive, ref, watch } from "vue";
import { I18nT, useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import ActionConfirmModal from "@/components/SchemaEditorV1/Modals/ActionConfirmModal.vue";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
import { databaseServiceClient } from "@/grpcweb";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
@@ -152,13 +143,7 @@ import { Engine } from "@/types/proto/v1/common";
import type { DatabaseMetadata } from "@/types/proto/v1/database_service";
import { DatabaseMetadataView } from "@/types/proto/v1/database_service";
import { TenantMode } from "@/types/proto/v1/project_service";
-import {
- MAX_UPLOAD_FILE_SIZE_MB,
- TinyTimer,
- defer,
- extractProjectResourceName,
- readFileAsArrayBuffer,
-} from "@/utils";
+import { TinyTimer, defer, extractProjectResourceName } from "@/utils";
import { MonacoEditor } from "../MonacoEditor";
import { provideSQLCheckContext } from "../SQLCheck";
import type { EditTarget, GenerateDiffDDLResult } from "../SchemaEditorLite";
@@ -178,6 +163,7 @@ interface LocalState {
isGeneratingDDL: boolean;
previewStatus: string;
targets: EditTarget[];
+ isUploadingFile: boolean;
}
const props = defineProps({
@@ -200,7 +186,6 @@ const emit = defineEmits<{
}>();
const schemaEditorRef = ref<InstanceType<typeof SchemaEditorLite>>();
-const sqlFileUploader = ref<HTMLInputElement | null>(null);
const { t } = useI18n();
const router = useRouter();
const state = reactive<LocalState>({
@@ -211,16 +196,13 @@ const state = reactive<LocalState>({
isGeneratingDDL: false,
previewStatus: "",
targets: [],
+ isUploadingFile: false,
});
const databaseV1Store = useDatabaseV1Store();
const notificationStore = useNotificationStore();
const { runSQLCheck } = provideSQLCheckContext();
const $dialog = useDialog();
-const onUploaderClick = () => {
- sqlFileUploader.value?.click();
-};
-
const allowPreviewIssue = computed(() => {
if (state.selectedTab === "schema-editor") {
// Always return true for schema editor to prevent huge calculation from schema editor.
@@ -407,47 +389,6 @@ const generateDiffDDLMap = async (silent: boolean) => {
return statementMap;
};
-const handleUploadFile = async (e: Event) => {
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
- }
-
- try {
- const { arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- state.editStatement = decoder.decode(arrayBuffer);
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
- }
- cleanup();
-};
-
const handlePreviewIssue = async () => {
if (state.previewStatus) {
return;
diff --git a/frontend/src/components/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vue b/frontend/src/components/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vue
index 81ef549166..5a2b5e34ba 100644
--- a/frontend/src/components/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vue
+++ b/frontend/src/components/Changelist/ChangelistDetail/AddChangePanel/form/RawSQLForm.vue
@@ -5,25 +5,17 @@
v-model:statement="statement"
:readonly="false"
class="flex-1 overflow-hidden relative"
- @upload="handleUploadEvent"
/>
</div>
</template>
<script setup lang="ts">
import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { pushNotification, useLocalSheetStore } from "@/store";
-import {
- MAX_UPLOAD_FILE_SIZE_MB,
- getSheetStatement,
- readFileAsArrayBuffer,
- setSheetStatement,
-} from "@/utils";
+import { useLocalSheetStore } from "@/store";
+import { getSheetStatement, setSheetStatement } from "@/utils";
import RawSQLEditor from "../../RawSQLEditor";
import { useAddChangeContext } from "../context";
-const { t } = useI18n();
const { changeFromRawSQL: change } = useAddChangeContext();
const sheet = computed(() => {
@@ -38,47 +30,4 @@ const statement = computed({
setSheetStatement(sheet.value, statement);
},
});
-
-const handleUploadEvent = async (e: Event) => {
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
- }
-
- try {
- const { filename, arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- statement.value = decoder.decode(arrayBuffer);
- sheet.value.title = filename;
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
- }
-
- cleanup();
-};
</script>
diff --git a/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue b/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue
index 4aa211aece..6dd06977b7 100644
--- a/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue
+++ b/frontend/src/components/Changelist/ChangelistDetail/RawSQLEditor/RawSQLEditor.vue
@@ -1,9 +1,12 @@
<template>
<div class="flex flex-col gap-y-2">
<div v-if="!readonly" class="flex justify-end">
- <UploadProgressButton :upload="handleUploadFile">
+ <SQLUploadButton
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatement"
+ >
{{ $t("issue.upload-sql") }}
- </UploadProgressButton>
+ </SQLUploadButton>
</div>
<div
@@ -24,13 +27,17 @@
<script setup lang="ts">
import { useElementSize } from "@vueuse/core";
-import { ref, watch } from "vue";
+import { reactive, ref, watch } from "vue";
import {
type IStandaloneCodeEditor,
type MonacoModule,
MonacoEditor,
} from "@/components/MonacoEditor";
-import UploadProgressButton from "@/components/misc/UploadProgressButton.vue";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
+
+interface LocalState {
+ isUploadingFile: boolean;
+}
defineProps<{
statement: string;
@@ -43,11 +50,19 @@ const emit = defineEmits<{
(event: "upload", e: Event): void;
}>();
+const state = reactive<LocalState>({
+ isUploadingFile: false,
+});
const editorWrapperRef = ref<HTMLDivElement>();
const { height: editorWrapperHeight } = useElementSize(editorWrapperRef);
-const handleUploadFile = async (event: Event) => {
- emit("upload", event);
+const handleUpdateStatement = async (statement: string) => {
+ try {
+ state.isUploadingFile = true;
+ emit("update:statement", statement);
+ } finally {
+ state.isUploadingFile = false;
+ }
};
const handleEditorReady = (
diff --git a/frontend/src/components/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vue b/frontend/src/components/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vue
index 3035f89c07..6160cee2af 100644
--- a/frontend/src/components/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vue
+++ b/frontend/src/components/Changelist/ChangelistDetail/RawSQLPanel/RawSQLPanel.vue
@@ -26,7 +26,6 @@
:readonly="!allowEdit"
:is-sheet-oversize="isSheetOversize"
class="flex-1 overflow-hidden relative"
- @upload="handleUploadEvent"
/>
</div>
<div
@@ -74,8 +73,6 @@ import {
getSheetStatement,
setSheetStatement,
getStatementSize,
- MAX_UPLOAD_FILE_SIZE_MB,
- readFileAsArrayBuffer,
} from "@/utils";
import RawSQLEditor from "../RawSQLEditor";
import { useChangelistDetailContext } from "../context";
@@ -136,48 +133,6 @@ const reset = () => {
}
};
-const handleUploadEvent = async (e: Event) => {
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
- }
-
- try {
- const { arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- statement.value = decoder.decode(arrayBuffer);
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
- }
-
- cleanup();
-};
-
const doSaveChange = async () => {
if (!sheet.value) {
return;
diff --git a/frontend/src/components/FileContentPreviewModal.vue b/frontend/src/components/FileContentPreviewModal.vue
new file mode 100644
index 0000000000..74e66708bf
--- /dev/null
+++ b/frontend/src/components/FileContentPreviewModal.vue
@@ -0,0 +1,145 @@
+<template>
+ <BBModal :title="$t('common.preview')" @close="$emit('cancel')">
+ <div class="w-144 py-1 flex flex-col justify-start items-start gap-2">
+ <div class="w-full flex flex-row justify-between items-center gap-4">
+ <p class="font-medium textlabel text-nowrap">
+ {{ $t("sql-editor.select-encoding") }}
+ </p>
+ <NSelect
+ v-model:value="state.encoding"
+ class="!w-auto"
+ filterable
+ :options="encodingOptions"
+ />
+ </div>
+ <div class="w-full overflow-hidden relative h-80 shrink-0">
+ <MonacoEditor
+ class="border w-full h-full"
+ :content="decodedText"
+ :readonly="true"
+ />
+ <NSpin v-if="isLoading" class="absolute inset-0" />
+ </div>
+ <div class="w-full flex justify-end space-x-2">
+ <NButton @click="$emit('cancel')">
+ {{ $t("common.cancel") }}
+ </NButton>
+ <NButton
+ type="primary"
+ :disabled="!allowConfirm"
+ :loading="isLoading"
+ @click="$emit('confirm', decodedText)"
+ >
+ {{ $t("common.confirm") }}
+ </NButton>
+ </div>
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { NSelect, NButton, NSpin } from "naive-ui";
+import { computed, reactive, ref, watch } from "vue";
+import { MonacoEditor } from "@/components/MonacoEditor";
+import { pushNotification } from "@/store";
+import { readFileAsArrayBuffer } from "@/utils";
+
+// Reference: https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings
+const ENCODINGS = [
+ "utf-8",
+ "ibm866",
+ "iso-8859-2",
+ "iso-8859-3",
+ "iso-8859-4",
+ "iso-8859-5",
+ "iso-8859-6",
+ "iso-8859-7",
+ "iso-8859-8",
+ "iso-8859-8i",
+ "iso-8859-10",
+ "iso-8859-13",
+ "iso-8859-14",
+ "iso-8859-15",
+ "iso-8859-16",
+ "koi8-r",
+ "koi8-u",
+ "macintosh",
+ "windows-874",
+ "windows-1250",
+ "windows-1251",
+ "windows-1252",
+ "windows-1253",
+ "windows-1254",
+ "windows-1255",
+ "windows-1256",
+ "windows-1257",
+ "windows-1258",
+ "x-mac-cyrillic",
+ "gbk",
+ "gb18030",
+ "hz-gb-2312",
+ "big5",
+ "euc-jp",
+ "iso-2022-jp",
+ "shift-jis",
+ "euc-kr",
+ "iso-2022-kr",
+ "utf-16be",
+ "utf-16le",
+];
+
+type Encoding = (typeof ENCODINGS)[number];
+
+interface LocalState {
+ encoding: Encoding;
+}
+
+const props = defineProps<{
+ file: File;
+}>();
+
+defineEmits<{
+ (event: "cancel"): void;
+ (event: "confirm", text: string): void;
+}>();
+
+const state = reactive<LocalState>({
+ encoding: "utf-8",
+});
+const isLoading = ref(true);
+const decodedText = ref<string>("");
+
+const allowConfirm = computed(() => {
+ return !isLoading.value;
+});
+
+const encodingOptions = computed(() =>
+ ENCODINGS.map((encoding) => ({
+ label: encoding,
+ value: encoding,
+ }))
+);
+
+watch(
+ [() => props.file, state],
+ async () => {
+ isLoading.value = true;
+ try {
+ const { arrayBuffer } = await readFileAsArrayBuffer(props.file);
+ const text = new TextDecoder(state.encoding).decode(arrayBuffer);
+ decodedText.value = text;
+ } catch (error) {
+ console.error(error);
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Failed to read file",
+ });
+ }
+ isLoading.value = false;
+ },
+ {
+ immediate: true,
+ }
+);
+</script>
diff --git a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
index 8c21b98a37..d9dcdea4ff 100644
--- a/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
+++ b/frontend/src/components/IssueV1/components/StatementSection/EditorView/EditorView.vue
@@ -38,9 +38,13 @@
v-model:value="formatOnSave"
:language="language"
/>
- <UploadProgressButton :upload="handleUploadFile" size="tiny">
+ <SQLUploadButton
+ size="tiny"
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatement"
+ >
{{ $t("issue.upload-sql") }}
- </UploadProgressButton>
+ </SQLUploadButton>
</template>
</template>
@@ -60,14 +64,14 @@
{{ $t("common.edit") }}
</NButton>
<!-- for oversized sheets, only allow to upload and overwrite the sheet -->
- <UploadProgressButton
+ <SQLUploadButton
v-else
- :upload="handleUploadAndOverwrite"
- :disabled="denyEditTaskReasons.length > 0"
size="tiny"
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatementAndOverwrite"
>
{{ $t("issue.upload-sql") }}
- </UploadProgressButton>
+ </SQLUploadButton>
</template>
<template #default>
<ErrorList :errors="denyEditTaskReasons" />
@@ -80,9 +84,13 @@
v-model:value="formatOnSave"
:language="language"
/>
- <UploadProgressButton :upload="handleUploadFile" size="tiny">
+ <SQLUploadButton
+ size="tiny"
+ :loading="state.isUploadingFile"
+ @update:sql="handleUpdateStatement"
+ >
{{ $t("issue.upload-sql") }}
- </UploadProgressButton>
+ </SQLUploadButton>
<NButton
v-if="state.isEditing"
size="tiny"
@@ -230,7 +238,7 @@ import {
import { MonacoEditor } from "@/components/MonacoEditor";
import { extensionNameOfLanguage } from "@/components/MonacoEditor/utils";
import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";
-import UploadProgressButton from "@/components/misc/UploadProgressButton.vue";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
import { rolloutServiceClient } from "@/grpcweb";
import { emitWindowEvent } from "@/plugins";
import {
@@ -254,8 +262,6 @@ import {
getStatementSize,
isDatabaseChangeRelatedIssue,
isDatabaseDataExportIssue,
- MAX_UPLOAD_FILE_SIZE_MB,
- readFileAsArrayBuffer,
} from "@/utils";
import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";
import FormatOnSaveCheckbox from "./FormatOnSaveCheckbox.vue";
@@ -582,111 +588,28 @@ const showOverwriteConfirmDialog = () => {
});
};
-const handleUploadAndOverwrite = async (e: Event) => {
- if (state.isUploadingFile) {
- return;
- }
+const handleUpdateStatementAndOverwrite = async (
+ statement: string,
+ filename: string
+) => {
try {
- state.isUploadingFile = true;
await showOverwriteConfirmDialog();
-
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
- }
-
- try {
- const { filename, arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- const statement = decoder.decode(arrayBuffer);
- state.isEditing = true;
- state.statement = statement;
- handleStatementChange(statement);
- if (sheet.value) {
- sheet.value.title = filename;
- }
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
- }
-
- cleanup();
- resetTempEditState();
- } finally {
- state.isUploadingFile = false;
+ } catch (error) {
+ return;
}
+
+ state.isEditing = true;
+ state.statement = statement;
+ await handleUpdateStatement(statement, filename);
};
-const handleUploadFile = async (e: Event) => {
+const handleUpdateStatement = async (statement: string, filename: string) => {
try {
state.isUploadingFile = true;
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
- }
-
- try {
- const { filename, arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- const statement = decoder.decode(arrayBuffer);
- handleStatementChange(statement);
- if (sheet.value) {
- sheet.value.title = filename;
- }
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
+ handleStatementChange(statement);
+ if (sheet.value) {
+ sheet.value.title = filename;
}
-
- cleanup();
resetTempEditState();
} finally {
state.isUploadingFile = false;
diff --git a/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue b/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue
index 5a47e55299..c7d38cba71 100644
--- a/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue
+++ b/frontend/src/components/SyncDatabaseSchema/RawSQLEditor.vue
@@ -32,22 +32,12 @@
v-if="!viewMode"
class="flex flex-row justify-end items-center space-x-3"
>
- <label
- for="sql-file-input"
- class="text-sm border px-3 leading-8 flex items-center rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"
+ <SQLUploadButton
+ :loading="state.isUploadingFile"
+ @update:sql="handleSQLUpload"
>
- <heroicons-outline:arrow-up-tray
- class="w-4 h-auto mr-1 text-gray-500"
- />
{{ $t("issue.upload-sql") }}
- <input
- id="sql-file-input"
- type="file"
- accept=".sql,.txt,application/sql,text/plain"
- class="hidden"
- @change="handleUploadFile"
- />
- </label>
+ </SQLUploadButton>
</div>
</div>
<BBAttention
@@ -77,11 +67,11 @@
import { useDebounceFn } from "@vueuse/core";
import { NSelect } from "naive-ui";
import { computed, onMounted, nextTick, reactive } from "vue";
-import { useI18n } from "vue-i18n";
import { MonacoEditor } from "@/components/MonacoEditor";
import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";
+import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";
import { ProjectSelect } from "@/components/v2";
-import { pushNotification, useSheetV1Store } from "@/store";
+import { useSheetV1Store } from "@/store";
import {
DEFAULT_PROJECT_V1_NAME,
UNKNOWN_ID,
@@ -93,8 +83,6 @@ import {
extractSheetUID,
getStatementSize,
getSheetStatement,
- readFileAsArrayBuffer,
- MAX_UPLOAD_FILE_SIZE_MB,
} from "@/utils";
import type { RawSQLState } from "./types";
@@ -102,6 +90,7 @@ interface LocalState {
projectId?: string;
engine: Engine;
editStatement: string;
+ isUploadingFile: boolean;
}
const props = defineProps<{
@@ -117,12 +106,12 @@ const emit = defineEmits<{
(event: "update", rawSQLState: RawSQLState): void;
}>();
-const { t } = useI18n();
const sheetStore = useSheetV1Store();
const state = reactive<LocalState>({
projectId: props.projectId,
engine: props.engine || Engine.MYSQL,
editStatement: props.statement || "",
+ isUploadingFile: false,
});
const availableEngines = computed(() => {
@@ -176,53 +165,23 @@ const handleEngineChange = () => {
});
};
-const handleUploadFile = async (e: Event) => {
- const target = e.target as HTMLInputElement;
- const file = (target.files || [])[0];
- const cleanup = () => {
- // Note that once selected a file, selecting the same file again will not
- // trigger <input type="file">'s change event.
- // So we need to do some cleanup stuff here.
- target.files = null;
- target.value = "";
- };
-
- if (!file) {
- return cleanup();
- }
- if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("issue.upload-sql-file-max-size-exceeded", {
- size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
- }),
- });
- return cleanup();
+const handleSQLUpload = async (statement: string, filename: string) => {
+ if (state.isUploadingFile) {
+ return;
}
+ state.isUploadingFile = true;
try {
- const { arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
- const decoder = new TextDecoder("utf-8");
- const statement = decoder.decode(arrayBuffer);
const sheet = await sheetStore.createSheet(DEFAULT_PROJECT_V1_NAME, {
- title: file.name,
+ title: filename,
content: new TextEncoder().encode(statement),
});
const sheetId = Number(extractSheetUID(sheet.name));
await handleStatementChange(statement);
update(sheetId);
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(error),
- });
+ } finally {
+ state.isUploadingFile = false;
}
-
- cleanup();
};
const handleStatementChange = (statement: string) => {
diff --git a/frontend/src/components/misc/DroppableTextarea.vue b/frontend/src/components/misc/DroppableTextarea.vue
index 811bc924fa..f26cca2344 100644
--- a/frontend/src/components/misc/DroppableTextarea.vue
+++ b/frontend/src/components/misc/DroppableTextarea.vue
@@ -119,7 +119,6 @@ const onDrop = async (files: File[] | FileList | null) => {
state.reading = true;
try {
const { arrayBuffer } = await readFileAsArrayBuffer(file);
- // TODO(steven): let user choose encoding.
const decoder = new TextDecoder("utf-8");
const statement = decoder.decode(arrayBuffer);
emit("update:value", statement);
diff --git a/frontend/src/components/misc/SQLUploadButton.vue b/frontend/src/components/misc/SQLUploadButton.vue
new file mode 100644
index 0000000000..d60a915377
--- /dev/null
+++ b/frontend/src/components/misc/SQLUploadButton.vue
@@ -0,0 +1,92 @@
+<template>
+ <NButton tag="div" v-bind="$attrs" @click="handleClick">
+ <template #icon>
+ <UploadIcon class="w-4 h-4" />
+ </template>
+
+ <span>
+ <slot />
+ </span>
+
+ <input
+ ref="inputRef"
+ type="file"
+ accept=".sql,.txt,application/sql,text/plain"
+ class="hidden"
+ @change="handleUpload"
+ />
+ </NButton>
+
+ <FileContentPreviewModal
+ v-if="selectedFile"
+ :file="selectedFile"
+ @cancel="cleanup"
+ @confirm="handleStatementConfirm"
+ />
+</template>
+
+<script lang="ts" setup>
+import { UploadIcon } from "lucide-vue-next";
+import { NButton } from "naive-ui";
+import { ref } from "vue";
+import { useI18n } from "vue-i18n";
+import FileContentPreviewModal from "@/components/FileContentPreviewModal.vue";
+import { pushNotification } from "@/store";
+import { MAX_UPLOAD_FILE_SIZE_MB } from "@/utils";
+
+const emit = defineEmits<{
+ (event: "update:sql", text: string, filename: string): void;
+}>();
+
+const { t } = useI18n();
+const inputRef = ref<HTMLInputElement>();
+const selectedFile = ref<File | null>(null);
+
+const handleClick = () => {
+ inputRef.value?.click();
+};
+
+const cleanup = () => {
+ selectedFile.value = null;
+ if (!inputRef.value) {
+ return;
+ }
+ inputRef.value.files = null;
+ inputRef.value.value = "";
+};
+
+const handleUpload = async (e: Event) => {
+ const target = e.target as HTMLInputElement;
+ const file = (target.files || [])[0];
+ const cleanup = () => {
+ // Note that once selected a file, selecting the same file again will not
+ // trigger <input type="file">'s change event.
+ // So we need to do some cleanup stuff here.
+ target.files = null;
+ target.value = "";
+ };
+
+ if (!file) {
+ return cleanup();
+ }
+ if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("issue.upload-sql-file-max-size-exceeded", {
+ size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
+ }),
+ });
+ return cleanup();
+ }
+
+ selectedFile.value = file;
+
+ cleanup();
+};
+
+const handleStatementConfirm = (statement: string) => {
+ emit("update:sql", statement, selectedFile.value!.name);
+ cleanup();
+};
+</script>
diff --git a/frontend/src/components/misc/UploadProgressButton.vue b/frontend/src/components/misc/UploadProgressButton.vue
deleted file mode 100644
index 10e0ab3eab..0000000000
--- a/frontend/src/components/misc/UploadProgressButton.vue
+++ /dev/null
@@ -1,89 +0,0 @@
-<template>
- <NButton
- :disabled="disabled"
- tag="div"
- style="--n-icon-margin: 3px"
- @click="handleClick"
- >
- <template #icon>
- <slot v-if="!uploading" name="icon">
- <heroicons-outline:arrow-up-tray class="w-4 h-4" />
- </slot>
- <template v-else>
- <NProgress
- v-if="percent > 0"
- type="circle"
- :percentage="percent"
- style="width: 1rem"
- >
- <span class="text-info scale-[66%]">
- {{ `${Math.round(percent)}%` }}
- </span>
- </NProgress>
- <BBSpin v-else :size="20" />
- </template>
- </template>
-
- <span>
- <slot v-if="!uploading" />
- <slot v-else name="uploading">
- {{ $t("common.uploading") }}
- </slot>
- </span>
-
- <input
- ref="inputRef"
- type="file"
- accept=".sql,.txt,application/sql,text/plain"
- class="hidden"
- @change="handleUpload"
- />
- </NButton>
-</template>
-
-<script lang="ts" setup>
-import { NButton, NProgress } from "naive-ui";
-import { computed, ref } from "vue";
-
-type Tick = (p: number) => void;
-
-const props = defineProps<{
- upload: (e: Event, tick: Tick) => Promise<any>;
- disabled?: boolean;
-}>();
-
-const inputRef = ref<HTMLInputElement>();
-const uploading = ref(false);
-const percent = ref(-1); // -1 to show a simple spinner instead of progress
-
-const disabled = computed(() => {
- return props.disabled || uploading.value;
-});
-
-const updatePercent = (p: number) => {
- percent.value = p;
-};
-
-const handleClick = () => {
- inputRef.value?.click();
-};
-
-const handleUpload = async (e: Event) => {
- uploading.value = true;
- percent.value = -1;
- try {
- await props.upload(e, updatePercent);
- } catch {
- // nothing
- } finally {
- uploading.value = false;
- percent.value = -1;
- if (inputRef.value) {
- // Clear the selected file.
- // Otherwise selecting the same file again will not trigger
- // change event
- inputRef.value.value = "";
- }
- }
-};
-</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ed0521a7bb..b4cddb4883 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2245,7 +2245,8 @@
"click-to-sync-now": "Click to sync now",
"sync-in-progress": "Sync in progress",
"create-a-worksheet": "Create a new worksheet",
- "select-a-database-to-start": "Select a database to start"
+ "select-a-database-to-start": "Select a database to start",
+ "select-encoding": "Select encoding"
},
"schema-editor": {
"self": "Schema Editor",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 7f1e389230..433d2c6fda 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2245,7 +2245,8 @@
"click-to-sync-now": "Haga clic para sincronizar ahora",
"sync-in-progress": "Sincronización en progreso",
"create-a-worksheet": "Crear una hoja de trabajo",
- "select-a-database-to-start": "Seleccione una base de datos para comenzar"
+ "select-a-database-to-start": "Seleccione una base de datos para comenzar",
+ "select-encoding": "Seleccionar codificación"
},
"schema-editor": {
"self": "Editor de esquema",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a0da936625..cc060256f4 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2245,7 +2245,8 @@
"click-to-sync-now": "今すぐ同期するにはクリックしてください",
"sync-in-progress": "同期中",
"create-a-worksheet": "ワークシートを作成する",
- "select-a-database-to-start": "開始するデータベースを選択してください"
+ "select-a-database-to-start": "開始するデータベースを選択してください",
+ "select-encoding": "エンコードを選択"
},
"schema-editor": {
"self": "スキーマエディター",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 38135352a0..8dd61f0d7d 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2245,7 +2245,8 @@
"click-to-sync-now": "Bấm để đồng bộ ngay",
"sync-in-progress": "Đang đồng bộ hóa",
"create-a-worksheet": "Tạo một bảng tính",
- "select-a-database-to-start": "Chọn cơ sở dữ liệu để bắt đầu"
+ "select-a-database-to-start": "Chọn cơ sở dữ liệu để bắt đầu",
+ "select-encoding": "Chọn mã hóa"
},
"schema-editor": {
"self": "Trình chỉnh sửa lược đồ",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 8a15bfb972..49e6f77042 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2245,7 +2245,8 @@
"click-to-sync-now": "点击立即同步",
"sync-in-progress": "正在同步",
"create-a-worksheet": "新建工作表",
- "select-a-database-to-start": "选择数据库以开始"
+ "select-a-database-to-start": "选择数据库以开始",
+ "select-encoding": "选择编码"
},
"schema-editor": {
"self": "Schema 编辑器",