Skip to content

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

feat: support upload large size sql file with sheet (#3938)

boojackaa3dd976e0b0
diff --git a/frontend/src/components/Issue/IssueTaskStatementPanel.vue b/frontend/src/components/Issue/IssueTaskStatementPanel.vue
index 1ae0e14951..2b2ddad2fe 100644
--- a/frontend/src/components/Issue/IssueTaskStatementPanel.vue
+++ b/frontend/src/components/Issue/IssueTaskStatementPanel.vue
@@ -23,7 +23,8 @@
</div>
<div class="space-x-2 flex items-center">
- <template v-if="create">
+ <template v-if="create || state.editing">
+ <!-- mt-0.5 is to prevent jiggling between switching edit/none-edit -->
<label class="mt-0.5 mr-2 inline-flex items-center gap-1">
<input
v-model="formatOnSave"
@@ -32,6 +33,28 @@
/>
<span class="textlabel">{{ $t("issue.format-on-save") }}</span>
</label>
+ <button
+ v-if="state.editing && allowUploadSheetForTask"
+ type="button"
+ class="cursor-pointer border border-control-border rounded text-control bg-control-bg hover:bg-control-bg-hover disabled:bg-control-bg-hover disabled:cursor-not-allowed disabled:opacity-60 text-sm font-normal focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2"
+ :disabled="state.isUploadingFile"
+ >
+ <label
+ for="sql-file-with-sheet-input"
+ class="px-3 py-1 w-full flex flex-row justify-center items-center cursor-pointer"
+ :class="state.isUploadingFile && 'cursor-wait'"
+ >
+ <heroicons-outline:document-text class="w-4 h-auto mr-1" />
+ {{ $t("issue.upload-sql-as-sheet") }}
+ <input
+ id="sql-file-with-sheet-input"
+ type="file"
+ accept=".sql,.txt,application/sql,text/plain"
+ class="hidden"
+ @change="handleUploadLocalFileAsSheet"
+ />
+ </label>
+ </button>
<button
v-if="state.editing"
type="button"
@@ -48,82 +71,66 @@
type="file"
accept=".sql,.txt,application/sql,text/plain"
class="hidden"
- @change="handleUploadFile"
+ @change="handleUploadLocalFile"
/>
</label>
</button>
</template>
- <template v-else>
+
+ <button
+ v-if="shouldShowStatementEditButton"
+ type="button"
+ class="btn-icon"
+ @click.prevent="beginEdit"
+ >
+ <heroicons-solid:pencil class="h-5 w-5" />
+ </button>
+ <template v-else-if="!create">
+ <button
+ v-if="state.editing"
+ type="button"
+ class="px-3 py-1 cursor-pointer border border-control-border rounded text-control bg-control-bg hover:bg-control-bg-hover text-sm font-normal focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2"
+ :disabled="!allowSaveSQL"
+ @click.prevent="saveEdit"
+ >
+ {{ $t("common.save") }}
+ </button>
+ <button
+ v-if="state.editing"
+ type="button"
+ class="px-3 py-1 cursor-pointer rounded text-control hover:bg-control-bg-hover text-sm font-normal focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2"
+ @click.prevent="cancelEdit"
+ >
+ {{ $t("common.cancel") }}
+ </button>
+ </template>
+
+ <template
+ v-if="!create && (issue as Issue).project.workflowType === 'VCS'"
+ >
+ <!--
+ Show a virtual pencil icon in VCS workflow which opens a guide
+ when clicked.
+ -->
<button
- v-if="allowEditStatement && !state.editing"
type="button"
class="btn-icon"
- @click.prevent="beginEdit"
+ @click.prevent="state.showVCSGuideModal = true"
>
- <!-- Heroicon name: solid/pencil -->
- <!-- Use h-5 to avoid flickering when show/hide icon -->
<heroicons-solid:pencil class="h-5 w-5" />
</button>
- <template v-if="state.editing">
- <!-- mt-0.5 is to prevent jiggling between switching edit/none-edit -->
- <label class="mt-0.5 mr-2 inline-flex items-center gap-1">
- <input
- v-model="formatOnSave"
- type="checkbox"
- class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
- />
- <span class="textlabel">{{ $t("issue.format-on-save") }}</span>
- </label>
- <button
- v-if="state.editing"
- type="button"
- class="mt-0.5 px-3 border border-control-border rounded-sm text-control bg-control-bg hover:bg-control-bg-hover text-sm leading-5 font-normal focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2 relative"
- >
- {{ $t("issue.upload-sql") }}
- <input
- type="file"
- accept=".sql,.txt,application/sql,text/plain"
- class="absolute inset-0 z-1 opacity-0"
- @change="handleUploadFile"
- />
- </button>
- <button
- v-if="state.editing"
- type="button"
- class="mt-0.5 px-3 border border-control-border rounded-sm text-control bg-control-bg hover:bg-control-bg-hover disabled:bg-control-bg disabled:opacity-50 disabled:cursor-not-allowed text-sm leading-5 font-normal focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2"
- :disabled="!allowSaveSQL"
- @click.prevent="saveEdit"
- >
- {{ $t("common.save") }}
- </button>
- <button
- v-if="state.editing"
- type="button"
- class="mt-0.5 px-3 rounded-sm text-control hover:bg-control-bg-hover disabled:bg-control-bg disabled:opacity-50 disabled:cursor-not-allowed text-sm leading-5 font-normal focus:ring-control focus:outline-none focus-visible:ring-2 focus:ring-offset-2"
- @click.prevent="cancelEdit"
- >
- {{ $t("common.cancel") }}
- </button>
- </template>
- <template v-if="issue.project.workflowType === 'VCS'">
- <!--
- Show a virtual pencil icon in VCS workflow which opens a guide
- when clicked.
- -->
- <button
- type="button"
- class="btn-icon"
- @click.prevent="state.showVCSGuideModal = true"
- >
- <heroicons-solid:pencil class="h-5 w-5" />
- </button>
- </template>
</template>
<IssueRollbackButton />
</div>
</div>
<label class="sr-only">{{ $t("common.sql-statement") }}</label>
+ <BBAttention
+ v-if="isTaskHasSheetId"
+ :class="'my-2'"
+ :style="`WARN`"
+ :title="$t('issue.statement-from-sheet-warning')"
+ />
<div
class="whitespace-pre-wrap mt-2 w-full overflow-hidden"
:class="state.editing ? 'border-t border-x' : 'border-t border-x'"
@@ -133,7 +140,7 @@
class="w-full h-auto max-h-[360px]"
data-label="bb-issue-sql-editor"
:value="state.editStatement"
- :readonly="!state.editing"
+ :readonly="!state.editing || !allowEditStatement || isTaskHasSheetId"
:auto-focus="false"
:dialect="dialect"
@change="onStatementChange"
@@ -168,331 +175,81 @@
</BBModal>
</template>
-<script lang="ts">
-import {
- onMounted,
- reactive,
- watch,
- defineComponent,
- computed,
- ref,
- Ref,
- nextTick,
-} from "vue";
+<script lang="ts" setup>
import { useDialog } from "naive-ui";
+import { onMounted, reactive, watch, computed, ref, nextTick } from "vue";
import { useI18n } from "vue-i18n";
-
import {
pushNotification,
useDBSchemaStore,
useRepositoryStore,
+ useSheetStore,
useUIStateStore,
} from "@/store";
-import { useIssueLogic } from "./logic";
-import MonacoEditor from "../MonacoEditor/MonacoEditor.vue";
+import { useIssueLogic, TaskTypeWithSheetId, sheetIdOfTask } from "./logic";
import type {
Database,
Issue,
Repository,
SQLDialect,
Task,
+ TaskCreate,
TaskId,
} from "@/types";
import { baseDirectoryWebUrl, UNKNOWN_ID } from "@/types";
import { TableMetadata } from "@/types/proto/database";
+import MonacoEditor from "../MonacoEditor/MonacoEditor.vue";
import IssueRollbackButton from "./IssueRollbackButton.vue";
+import { isUndefined } from "lodash-es";
interface LocalState {
editing: boolean;
editStatement: string;
showVCSGuideModal: boolean;
+ isUploadingFile: boolean;
}
+type LocalEditState = Pick<LocalState, "editing" | "editStatement">;
+
const EDITOR_MIN_HEIGHT = {
READONLY: 0, // not limited to keep the UI compact
EDITABLE: 120, // ~= 6 lines, a reasonable size to start writing SQL
};
-const MAX_UPLOAD_FILE_SIZE_MB = 1;
-
-export default defineComponent({
- name: "IssueTaskStatementPanel",
- components: {
- MonacoEditor,
- IssueRollbackButton,
- },
- props: {
- sqlHint: {
- required: false,
- type: String,
- default: undefined,
- },
- },
- setup(props, { emit }) {
- const {
- issue,
- create,
- allowEditStatement,
- selectedDatabase,
- selectedStatement: statement,
- updateStatement,
- allowApplyStatementToOtherTasks,
- applyStatementToOtherTasks,
- } = useIssueLogic();
-
- const { t } = useI18n();
- const uiStateStore = useUIStateStore();
- const dbSchemaStore = useDBSchemaStore();
-
- const state = reactive<LocalState>({
- editing: false,
- editStatement: statement.value,
- showVCSGuideModal: false,
- });
- useTempEditState(state);
-
- const editorRef = ref<InstanceType<typeof MonacoEditor>>();
- const overrideSQLDialog = useDialog();
-
- const dialect = computed((): SQLDialect => {
- const db = selectedDatabase.value;
- if (db?.instance.engine === "POSTGRES") {
- return "postgresql";
- }
- // fallback to mysql dialect anyway
- return "mysql";
- });
-
- const formatOnSave = computed({
- get: () => uiStateStore.issueFormatStatementOnSave,
- set: (value: boolean) =>
- uiStateStore.setIssueFormatStatementOnSave(value),
- });
-
- const { databaseList, tableList } = useDatabaseAndTableList();
-
- onMounted(() => {
- if (create.value) {
- state.editing = true;
- }
- });
-
- // Reset the edit state after creating the issue.
- watch(create, (curNew, prevNew) => {
- if (!curNew && prevNew) {
- if (formatOnSave.value) {
- editorRef.value?.formatEditorContent();
- }
- state.editing = false;
- updateEditorHeight();
- }
- });
-
- watch(statement, (cur) => {
- state.editStatement = cur;
- });
-
- const handleUpdateEditorAutoCompletionContext = async () => {
- const databaseMap: Map<Database, TableMetadata[]> = new Map();
- for (const database of databaseList.value) {
- const tableList = await dbSchemaStore.getOrFetchTableListByDatabaseId(
- database.id
- );
- databaseMap.set(database, tableList);
- }
- editorRef.value?.setEditorAutoCompletionContext(databaseMap);
- };
-
- const handleMonacoEditorReady = () => {
- handleUpdateEditorAutoCompletionContext();
- updateEditorHeight();
- };
-
- watch([databaseList, tableList], () => {
- handleUpdateEditorAutoCompletionContext();
- });
-
- const updateEditorHeight = () => {
- const contentHeight =
- editorRef.value?.editorInstance?.getContentHeight() as number;
- let actualHeight = contentHeight;
- if (state.editing && actualHeight < EDITOR_MIN_HEIGHT.EDITABLE) {
- actualHeight = EDITOR_MIN_HEIGHT.EDITABLE;
- }
- editorRef.value?.setEditorContentHeight(actualHeight);
- };
-
- const beginEdit = () => {
- state.editStatement = statement.value;
- state.editing = true;
- };
-
- const saveEdit = () => {
- if (formatOnSave.value) {
- editorRef.value?.formatEditorContent();
- }
- updateStatement(state.editStatement, () => {
- state.editing = false;
- });
- };
-
- const cancelEdit = () => {
- state.editStatement = statement.value;
- state.editing = false;
- };
-
- const allowSaveSQL = computed((): boolean => {
- if (state.editStatement === "") {
- // Not allowed if the statement is empty.
- return false;
- }
- if (state.editStatement === statement.value) {
- // Not allowed if the statement is not modified.
- return false;
- }
-
- // Allowed to save otherwise
- return true;
- });
-
- const handleUploadFile = (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 fr = new FileReader();
- fr.onload = () => {
- const sql = fr.result as string;
- if (state.editStatement) {
- // Show a confirm dialog before replacing if the editing statement
- // is not empty
- overrideSQLDialog.create({
- positiveText: t("common.confirm"),
- negativeText: t("common.cancel"),
- title: t("issue.override-current-statement"),
- onNegativeClick: () => {
- // nothing to do
- },
- onPositiveClick: () => {
- onStatementChange(sql);
- },
- });
- } else {
- onStatementChange(sql);
- }
- };
- fr.onerror = (e) => {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: `Read file error`,
- description: String(fr.error),
- });
- return;
- };
- fr.readAsText(file);
-
- cleanup();
- };
-
- const onStatementChange = (value: string) => {
- state.editStatement = value;
- if (create.value) {
- // If we are creating an issue, emit the event immediately when every
- // time the user types.
- updateStatement(state.editStatement);
- }
-
- updateEditorHeight();
- };
-
- const goToVCS = () => {
- const issueEntity = issue.value as Issue;
- useRepositoryStore()
- .fetchRepositoryByProjectId(issueEntity.project.id)
- .then((repository: Repository) => {
- window.open(
- baseDirectoryWebUrl(repository, {
- DB_NAME: selectedDatabase.value?.name,
- ENV_NAME: selectedDatabase.value?.instance.environment.name,
- }),
- "_blank"
- );
-
- state.showVCSGuideModal = false;
- });
- };
-
- return {
- issue: issue as Ref<Issue>,
- create,
- allowEditStatement,
- statement,
- allowApplyStatementToOtherTasks,
- dialect,
- formatOnSave,
- state,
- editorRef,
- updateStatement,
- applyStatementToOtherTasks,
- beginEdit,
- saveEdit,
- cancelEdit,
- allowSaveSQL,
- handleUploadFile,
- onStatementChange,
- goToVCS,
- handleMonacoEditorReady,
- };
+defineProps({
+ sqlHint: {
+ required: false,
+ type: String,
+ default: undefined,
},
});
-const useDatabaseAndTableList = () => {
- const { selectedDatabase } = useIssueLogic();
- const dbSchemaStore = useDBSchemaStore();
-
- const databaseList = computed(() => {
- if (selectedDatabase.value) return [selectedDatabase.value];
- return [];
- });
-
- watch(
- databaseList,
- (list) => {
- list.forEach((db) => dbSchemaStore.getOrFetchDatabaseMetadataById(db.id));
- },
- { immediate: true }
- );
-
- const tableList = computed(() => {
- return databaseList.value
- .map((item) => dbSchemaStore.getTableListByDatabaseId(item.id))
- .flat();
- });
-
- return { databaseList, tableList };
-};
-
-type LocalEditState = Pick<LocalState, "editing" | "editStatement">;
+const {
+ issue,
+ create,
+ allowEditStatement,
+ selectedDatabase,
+ selectedStatement: statement,
+ selectedTask,
+ updateStatement,
+ updateSheetId,
+ allowApplyStatementToOtherTasks,
+ applyStatementToOtherTasks,
+} = useIssueLogic();
+
+const { t } = useI18n();
+const overrideSQLDialog = useDialog();
+const uiStateStore = useUIStateStore();
+const dbSchemaStore = useDBSchemaStore();
+const sheetStore = useSheetStore();
+const editorRef = ref<InstanceType<typeof MonacoEditor>>();
+
+const state = reactive<LocalState>({
+ editing: false,
+ editStatement: statement.value,
+ showVCSGuideModal: false,
+ isUploadingFile: false,
+});
const useTempEditState = (state: LocalState) => {
const { create, selectedTask, selectedStatement } = useIssueLogic();
@@ -581,4 +338,322 @@ const useTempEditState = (state: LocalState) => {
{ immediate: true }
);
};
+
+useTempEditState(state);
+
+const dialect = computed((): SQLDialect => {
+ const db = selectedDatabase.value;
+ if (db?.instance.engine === "POSTGRES") {
+ return "postgresql";
+ }
+ // fallback to mysql dialect anyway
+ return "mysql";
+});
+
+const formatOnSave = computed({
+ get: () => uiStateStore.issueFormatStatementOnSave,
+ set: (value: boolean) => uiStateStore.setIssueFormatStatementOnSave(value),
+});
+
+const allowUploadSheetForTask = computed(() => {
+ const task = selectedTask.value;
+ return TaskTypeWithSheetId.includes(task.type);
+});
+
+const isTaskHasSheetId = computed(() => {
+ if (!allowUploadSheetForTask.value) {
+ return false;
+ }
+
+ const task = selectedTask.value;
+ if (create.value) {
+ return !isUndefined((task as TaskCreate).sheetId);
+ }
+ return !isUndefined(sheetIdOfTask(task as Task));
+});
+
+const shouldShowStatementEditButton = computed(() => {
+ if (create.value) {
+ return false;
+ }
+ // For those task with sheet, it's readonly.
+ if (isTaskHasSheetId.value) {
+ return false;
+ }
+ if (state.editing) {
+ return false;
+ }
+
+ return allowEditStatement;
+});
+
+onMounted(() => {
+ if (create.value) {
+ state.editing = true;
+ }
+});
+
+// Reset the edit state after creating the issue.
+watch(create, (curNew, prevNew) => {
+ if (!curNew && prevNew) {
+ if (formatOnSave.value) {
+ editorRef.value?.formatEditorContent();
+ }
+ state.editing = false;
+ updateEditorHeight();
+ }
+});
+
+watch(statement, (cur) => {
+ state.editStatement = cur;
+});
+
+const beginEdit = () => {
+ state.editStatement = statement.value;
+ state.editing = true;
+};
+
+const saveEdit = () => {
+ if (formatOnSave.value) {
+ editorRef.value?.formatEditorContent();
+ }
+ updateStatement(state.editStatement, () => {
+ state.editing = false;
+ });
+};
+
+const cancelEdit = () => {
+ state.editStatement = statement.value;
+ state.editing = false;
+};
+
+const allowSaveSQL = computed((): boolean => {
+ if (state.editStatement === "") {
+ // Not allowed if the statement is empty.
+ return false;
+ }
+ if (state.editStatement === statement.value) {
+ // Not allowed if the statement is not modified.
+ return false;
+ }
+
+ // Allowed to save otherwise
+ return true;
+});
+
+const handleUploadFileEvent = (
+ event: Event,
+ maxFileSizeMB: number
+): Promise<{
+ filename: string;
+ content: string;
+}> => {
+ return new Promise((resolve) => {
+ const target = event.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) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "File not found",
+ });
+ cleanup();
+ return;
+ }
+ if (file.size > maxFileSizeMB * 1024 * 1024) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("issue.upload-sql-file-max-size-exceeded", {
+ size: `${maxFileSizeMB}MB`,
+ }),
+ });
+ cleanup();
+ return;
+ }
+
+ const fr = new FileReader();
+ fr.onload = async () => {
+ const content = fr.result as string;
+ resolve({
+ filename: file.name,
+ content: content,
+ });
+ };
+ fr.onerror = () => {
+ pushNotification({
+ module: "bytebase",
+ style: "WARN",
+ title: "Read file error",
+ description: String(fr.error),
+ });
+ };
+ fr.readAsText(file);
+ cleanup();
+ });
+};
+
+const handleUploadLocalFile = async (event: Event) => {
+ const { content: statement } = await handleUploadFileEvent(event, 1);
+ if (state.editStatement) {
+ // Show a confirm dialog before replacing if the editing statement
+ // is not empty
+ overrideSQLDialog.create({
+ positiveText: t("common.confirm"),
+ negativeText: t("common.cancel"),
+ title: t("issue.override-current-statement"),
+ onNegativeClick: () => {
+ // nothing to do
+ },
+ onPositiveClick: () => {
+ updateStatement(statement);
+ },
+ });
+ } else {
+ updateStatement(statement);
+ }
+};
+
+const handleUploadLocalFileAsSheet = async (event: Event) => {
+ if (!allowUploadSheetForTask.value || !selectedDatabase.value) {
+ return;
+ }
+
+ state.isUploadingFile = true;
+ const projectId = selectedDatabase.value.projectId;
+ const { filename, content: statement } = await handleUploadFileEvent(
+ event,
+ 100
+ );
+
+ const uploadStatementAsSheet = async (statement: string) => {
+ const sheet = await sheetStore.createSheet({
+ projectId: projectId,
+ name: filename,
+ statement: statement,
+ visibility: "PRIVATE",
+ payload: {},
+ });
+
+ // TODO(steven): maybe return the sliced statement from backend?
+ const statementSlice = statement.slice(0, 40 * 1024);
+ updateSheetId(sheet.id);
+ updateStatement(statementSlice);
+ state.isUploadingFile = false;
+ if (selectedTask.value) updateEditorHeight();
+ };
+
+ if (state.editStatement) {
+ // Show a confirm dialog before replacing if the editing statement
+ // is not empty
+ overrideSQLDialog.create({
+ positiveText: t("common.confirm"),
+ negativeText: t("common.cancel"),
+ title: t("issue.override-current-statement"),
+ onNegativeClick: () => {
+ // nothing to do
+ },
+ onPositiveClick: () => {
+ uploadStatementAsSheet(statement);
+ },
+ });
+ } else {
+ uploadStatementAsSheet(statement);
+ }
+};
+
+const goToVCS = () => {
+ const issueEntity = issue.value as Issue;
+ useRepositoryStore()
+ .fetchRepositoryByProjectId(issueEntity.project.id)
+ .then((repository: Repository) => {
+ window.open(
+ baseDirectoryWebUrl(repository, {
+ DB_NAME: selectedDatabase.value?.name,
+ ENV_NAME: selectedDatabase.value?.instance.environment.name,
+ }),
+ "_blank"
+ );
+
+ state.showVCSGuideModal = false;
+ });
+};
+
+const onStatementChange = (value: string) => {
+ state.editStatement = value;
+ if (create.value) {
+ // If we are creating an issue, emit the event immediately when every
+ // time the user types.
+ updateStatement(state.editStatement);
+ }
+
+ if (selectedTask.value) updateEditorHeight();
+};
+
+// Handle and update monaco editor auto completion context.
+const useDatabaseAndTableList = () => {
+ const { selectedDatabase } = useIssueLogic();
+ const dbSchemaStore = useDBSchemaStore();
+
+ const databaseList = computed(() => {
+ if (selectedDatabase.value) return [selectedDatabase.value];
+ return [];
+ });
+
+ watch(
+ databaseList,
+ (list) => {
+ list.forEach((db) => dbSchemaStore.getOrFetchDatabaseMetadataById(db.id));
+ },
+ { immediate: true }
+ );
+
+ const tableList = computed(() => {
+ return databaseList.value
+ .map((item) => dbSchemaStore.getTableListByDatabaseId(item.id))
+ .flat();
+ });
+
+ return { databaseList, tableList };
+};
+
+const { databaseList, tableList } = useDatabaseAndTableList();
+
+const handleUpdateEditorAutoCompletionContext = async () => {
+ const databaseMap: Map<Database, TableMetadata[]> = new Map();
+ for (const database of databaseList.value) {
+ const tableList = await dbSchemaStore.getOrFetchTableListByDatabaseId(
+ database.id
+ );
+ databaseMap.set(database, tableList);
+ }
+ editorRef.value?.setEditorAutoCompletionContext(databaseMap);
+};
+
+const updateEditorHeight = () => {
+ const contentHeight =
+ editorRef.value?.editorInstance?.getContentHeight() as number;
+ let actualHeight = contentHeight;
+ if (state.editing && actualHeight < EDITOR_MIN_HEIGHT.EDITABLE) {
+ actualHeight = EDITOR_MIN_HEIGHT.EDITABLE;
+ }
+ editorRef.value?.setEditorContentHeight(actualHeight);
+};
+
+const handleMonacoEditorReady = () => {
+ handleUpdateEditorAutoCompletionContext();
+ updateEditorHeight();
+};
+
+watch([databaseList, tableList], () => {
+ handleUpdateEditorAutoCompletionContext();
+});
</script>
diff --git a/frontend/src/components/Issue/logic/GhostModeProvider.ts b/frontend/src/components/Issue/logic/GhostModeProvider.ts
index 97e968a124..de03866af1 100644
--- a/frontend/src/components/Issue/logic/GhostModeProvider.ts
+++ b/frontend/src/components/Issue/logic/GhostModeProvider.ts
@@ -4,6 +4,7 @@ import { provideIssueLogic, useIssueLogic } from "./index";
import {
flattenTaskList,
maybeFormatStatementOnSave,
+ TaskTypeWithSheetId,
TaskTypeWithStatement,
useCommonLogic,
} from "./common";
@@ -17,6 +18,7 @@ import {
MigrationContext,
TaskId,
TaskPatch,
+ SheetId,
} from "@/types";
import { useDatabaseStore, useTaskStore } from "@/store";
@@ -150,6 +152,30 @@ export default defineComponent({
}
};
+ const updateSheetId = (sheetId: SheetId) => {
+ if (!create.value) {
+ return;
+ }
+
+ if (isTenantMode.value) {
+ // For tenant deploy mode, we apply the sheetId to all stages and all tasks
+ const allTaskList = flattenTaskList<TaskCreate>(issue.value);
+ allTaskList.forEach((task) => {
+ if (TaskTypeWithSheetId.includes(task.type)) {
+ task.sheetId = sheetId;
+ }
+ });
+
+ const issueCreate = issue.value as IssueCreate;
+ const context = issueCreate.createContext as MigrationContext;
+ // We also apply it back to the CreateContext
+ context.detailList.forEach((detail) => (detail.sheetId = sheetId));
+ } else {
+ const task = selectedTask.value as TaskCreate;
+ task.sheetId = sheetId;
+ }
+ };
+
const doCreate = () => {
const issueCreate = cloneDeep(issue.value as IssueCreate);
@@ -230,6 +256,7 @@ export default defineComponent({
allowApplyStatementToOtherTasks,
applyStatementToOtherTasks,
updateStatement,
+ updateSheetId,
};
provideIssueLogic(logic);
return logic;
diff --git a/frontend/src/components/Issue/logic/IssueLogic.ts b/frontend/src/components/Issue/logic/IssueLogic.ts
index 674de007e3..9b5cdd5940 100644
--- a/frontend/src/components/Issue/logic/IssueLogic.ts
+++ b/frontend/src/components/Issue/logic/IssueLogic.ts
@@ -1,3 +1,4 @@
+import { Ref } from "vue";
import { IssueTemplate } from "@/plugins";
import {
Database,
@@ -7,6 +8,7 @@ import {
IssueStatus,
Pipeline,
Project,
+ SheetId,
Stage,
StageCreate,
Task,
@@ -15,7 +17,6 @@ import {
TaskPatch,
TaskStatus,
} from "@/types";
-import { Ref } from "vue";
type IssueLogic = {
// base params
@@ -61,6 +62,7 @@ type IssueLogic = {
newStatement: string,
postUpdated?: (updatedTask: Task) => void
) => any;
+ updateSheetId: (sheetId: SheetId) => void;
allowApplyStatementToOtherTasks: Ref<boolean>;
applyStatementToOtherTasks: (statement: string) => any;
doCreate(): any;
diff --git a/frontend/src/components/Issue/logic/TenantModeProvider.ts b/frontend/src/components/Issue/logic/TenantModeProvider.ts
index f7748c87f9..d9881579a0 100644
--- a/frontend/src/components/Issue/logic/TenantModeProvider.ts
+++ b/frontend/src/components/Issue/logic/TenantModeProvider.ts
@@ -8,6 +8,7 @@ import {
TaskCreate,
TaskDatabaseSchemaUpdatePayload,
MigrationContext,
+ SheetId,
} from "@/types";
import {
errorAssertion,
@@ -83,6 +84,23 @@ export default defineComponent({
}
};
+ const updateSheetId = (sheetId: SheetId) => {
+ if (!create.value) {
+ return;
+ }
+
+ // For tenant deploy mode, we apply the sheetId to all stages and all tasks
+ const allTaskList = flattenTaskList<TaskCreate>(issue.value);
+ allTaskList.forEach((task) => {
+ task.sheetId = sheetId;
+ });
+
+ const issueCreate = issue.value as IssueCreate;
+ const context = issueCreate.createContext as MigrationContext;
+ // We also apply it back to the CreateContext
+ context.detailList.forEach((detail) => (detail.sheetId = sheetId));
+ };
+
// We are never allowed to "apply statement to other stages" in tenant mode.
const allowApplyStatementToOtherTasks = computed(() => false);
@@ -106,6 +124,7 @@ export default defineComponent({
allowEditStatement,
selectedStatement,
updateStatement,
+ updateSheetId,
allowApplyStatementToOtherTasks,
applyStatementToOtherTasks: errorAssertion,
doCreate,
diff --git a/frontend/src/components/Issue/logic/common.ts b/frontend/src/components/Issue/logic/common.ts
index 4e8b30e9d3..aa95de4e8b 100644
--- a/frontend/src/components/Issue/logic/common.ts
+++ b/frontend/src/components/Issue/logic/common.ts
@@ -30,6 +30,8 @@ import {
MigrationType,
TaskDatabaseSchemaBaselinePayload,
DatabaseId,
+ TaskDatabaseSchemaUpdateGhostSyncPayload,
+ SheetId,
} from "@/types";
import { useIssueLogic } from "./index";
import { isDev, taskCheckRunSummary } from "@/utils";
@@ -179,19 +181,30 @@ export const useCommonLogic = () => {
}
};
+ const updateSheetId = (sheetId: SheetId) => {
+ if (!create.value) {
+ return;
+ }
+
+ const task = selectedTask.value as TaskCreate;
+ task.sheetId = sheetId;
+ };
+
const doCreate = () => {
const issueCreate = cloneDeep(issue.value as IssueCreate);
// for standard issue pipeline (1 * 1 or M * 1)
// copy user edited tasks back to issue.createContext
- const taskList = flattenTaskList<TaskCreate>(issueCreate);
- const detailList: MigrationDetail[] = taskList.map((task) => {
- const db = databaseStore.getDatabaseById(task.databaseId!);
- return {
- migrationType: getMigrationTypeFromTask(task),
- databaseId: task.databaseId!,
- statement: maybeFormatStatementOnSave(task.statement, db),
- earliestAllowedTs: task.earliestAllowedTs,
+ const taskCreateList = flattenTaskList<TaskCreate>(issueCreate);
+ const detailList: MigrationDetail[] = taskCreateList.map((taskCreate) => {
+ const db = databaseStore.getDatabaseById(taskCreate.databaseId!);
+ const migrationDetail: MigrationDetail = {
+ migrationType: getMigrationTypeFromTask(taskCreate),
+ databaseId: taskCreate.databaseId,
+ statement: maybeFormatStatementOnSave(taskCreate.statement, db),
+ sheetId: taskCreate.sheetId,
+ earliestAllowedTs: taskCreate.earliestAllowedTs,
};
+ return migrationDetail;
});
issueCreate.createContext = {
@@ -207,6 +220,7 @@ export const useCommonLogic = () => {
allowEditStatement,
initialTaskListStatement,
updateStatement,
+ updateSheetId,
doCreate,
};
};
@@ -226,11 +240,19 @@ const getMigrationTypeFromTask = (task: Task | TaskCreate) => {
export const TaskTypeWithStatement: TaskType[] = [
"bb.task.general",
"bb.task.database.create",
+ "bb.task.database.data.update",
"bb.task.database.schema.baseline",
"bb.task.database.schema.update",
"bb.task.database.schema.update-sdl",
"bb.task.database.schema.update.ghost.sync",
+];
+
+// TaskTypeWithSheetId should be a subset of TaskTypeWithStatement.
+export const TaskTypeWithSheetId: TaskType[] = [
"bb.task.database.data.update",
+ "bb.task.database.schema.update",
+ "bb.task.database.schema.update-sdl",
+ "bb.task.database.schema.update.ghost.sync",
];
export const IssueTypeWithStatement: IssueType[] = [
@@ -317,6 +339,38 @@ export const statementOfTask = (task: Task) => {
}
};
+export const sheetIdOfTask = (task: Task) => {
+ switch (task.type) {
+ case "bb.task.database.create":
+ return (
+ ((task as Task).payload as TaskDatabaseCreatePayload).sheetId ||
+ undefined
+ );
+ case "bb.task.database.schema.update":
+ return (
+ ((task as Task).payload as TaskDatabaseSchemaUpdatePayload).sheetId ||
+ undefined
+ );
+ case "bb.task.database.schema.update-sdl":
+ return (
+ ((task as Task).payload as TaskDatabaseSchemaUpdateSDLPayload)
+ .sheetId || undefined
+ );
+ case "bb.task.database.data.update":
+ return (
+ ((task as Task).payload as TaskDatabaseDataUpdatePayload).sheetId ||
+ undefined
+ );
+ case "bb.task.database.schema.update.ghost.sync":
+ return (
+ ((task as Task).payload as TaskDatabaseSchemaUpdateGhostSyncPayload)
+ .sheetId || undefined
+ );
+ default:
+ return undefined;
+ }
+};
+
export const isTaskEditable = (task: Task): boolean => {
if (task.status === "PENDING_APPROVAL" || task.status === "FAILED") {
return true;
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 8cef0e0462..f94359918c 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -558,6 +558,8 @@
"edit-sql-statement-in-vcs": "This project has enabled VCS based version control. Please modify the SQL file in the corresponding Git repository, and commit it to create a new issue.",
"edit-sql-statement": "Edit SQL statement",
"upload-sql": "Upload SQL",
+ "upload-sql-as-sheet": "Upload SQL as Sheet",
+ "statement-from-sheet-warning": "The current SQL statement comes from a sheet. It is read-only and only part of it is displayed.",
"override-current-statement": "Override current SQL statement",
"upload-sql-file-max-size-exceeded": "Max file size ({size}) exceeded.",
"waiting-earliest-allowed-time": "Will run after {time}",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 6117839de0..6516c7410a 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -558,6 +558,8 @@
"edit-sql-statement-in-vcs": "该项目开启了基于 VCS 的版本管理。请在对应的 Git 仓库修改 SQL 文件并提交,开启新的工单。",
"edit-sql-statement": "编辑 SQL 语句",
"upload-sql": "上传 SQL",
+ "upload-sql-as-sheet": "上传 SQL 至工作表",
+ "statement-from-sheet-warning": "当前的 SQL 语句来自一个工作表。它是只读的且只显示了部分内容。",
"override-current-statement": "覆盖当前的 SQL 语句",
"upload-sql-file-max-size-exceeded": "上传文件大小不能超过 {size}。",
"waiting-earliest-allowed-time": "将于 {time} 之后执行",
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index 0bdf91f918..4ab926d591 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -502,6 +502,7 @@ const makeUnknown = (type: ResourceType) => {
type: "SQL",
starred: false,
pinned: false,
+ payload: {},
};
const UNKNOWN_SQL_REVIEW_POLICY: SQLReviewPolicy = {
diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.ts
index 33cf99979e..e623689915 100644
--- a/frontend/src/types/issue.ts
+++ b/frontend/src/types/issue.ts
@@ -5,6 +5,7 @@ import {
IssueId,
PrincipalId,
ProjectId,
+ SheetId,
TaskId,
} from "./id";
import { Pipeline, PipelineCreate } from "./pipeline";
@@ -47,9 +48,10 @@ export type CreateDatabaseContext = {
export type MigrationDetail = {
migrationType: MigrationType;
- databaseId?: DatabaseId;
statement: string;
+ sheetId?: SheetId;
earliestAllowedTs: number;
+ databaseId?: DatabaseId;
};
export type UpdateSchemaGhostDetail = MigrationDetail & {
diff --git a/frontend/src/types/pipeline/task.ts b/frontend/src/types/pipeline/task.ts
index 41791276b0..310aeb68b8 100644
--- a/frontend/src/types/pipeline/task.ts
+++ b/frontend/src/types/pipeline/task.ts
@@ -6,6 +6,7 @@ import {
InstanceId,
IssueId,
ProjectId,
+ SheetId,
TaskId,
TaskRunId,
} from "../id";
@@ -47,6 +48,7 @@ export type TaskEarliestAllowedTimePayload = {
export type TaskDatabaseCreatePayload = {
projectId: ProjectId;
statement: string;
+ sheetId: SheetId;
databaseName: string;
characterSet: string;
collation: string;
@@ -60,16 +62,19 @@ export type TaskDatabaseSchemaBaselinePayload = {
export type TaskDatabaseSchemaUpdatePayload = {
statement: string;
+ sheetId: SheetId;
pushEvent?: VCSPushEvent;
};
export type TaskDatabaseSchemaUpdateSDLPayload = {
statement: string;
+ sheetId: SheetId;
pushEvent?: VCSPushEvent;
};
export type TaskDatabaseSchemaUpdateGhostSyncPayload = {
statement: string;
+ sheetId: SheetId;
pushEvent?: VCSPushEvent;
};
@@ -97,6 +102,7 @@ export type TaskDatabasePITRDeletePayload = {
export type TaskDatabaseDataUpdatePayload = {
statement: string;
+ sheetId: SheetId;
pushEvent?: VCSPushEvent;
rollbackStatement: string;
rollbackFromIssueId: IssueId;
@@ -174,6 +180,8 @@ export type TaskCreate = {
instanceId: InstanceId;
databaseId?: DatabaseId;
statement: string;
+ // statement and sheet ID should be mutually exclusive.
+ sheetId?: SheetId;
databaseName?: string;
characterSet?: string;
collation?: string;