Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: add UI editor entry with dev guard (#3606)
boojackb63602651f69
diff --git a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vueindex 8347a06560..2338d28d36 100644--- a/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue+++ b/frontend/src/components/AlterSchemaPrepForm/AlterSchemaPrepForm.vue@@ -146,6 +146,12 @@/><GhostDialog ref="ghostDialog" />++ <SchemaEditorModal+ v-if="state.showSchemaEditorModal"+ :database-id-list="flattenSelectedDatabaseIdList"+ @close="state.showSchemaEditorModal = false"+ /></template><script lang="ts" setup>@@ -165,15 +171,12 @@ import {Repository,UNKNOWN_ID,} from "@/types";-import { allowGhostMigration, sortDatabaseList } from "@/utils";-import ProjectStandardView, {- State as ProjectStandardState,-} from "./ProjectStandardView.vue";-import ProjectTenantView, {- State as ProjectTenantState,-} from "./ProjectTenantView.vue";-import { State as CommonTenantState } from "./CommonTenantView.vue";-import GhostDialog from "./GhostDialog.vue";+import {+ allowGhostMigration,+ allowUsingUIEditor,+ isDev,+ sortDatabaseList,+} from "@/utils";import {hasFeature,useCurrentUser,@@ -182,14 +185,23 @@ import {useProjectStore,useRepositoryStore,} from "@/store";+import ProjectStandardView, {+ State as ProjectStandardState,+} from "./ProjectStandardView.vue";+import ProjectTenantView, {+ State as ProjectTenantState,+} from "./ProjectTenantView.vue";+import { State as CommonTenantState } from "./CommonTenantView.vue";+import GhostDialog from "./GhostDialog.vue";+import SchemaEditorModal from "./SchemaEditorModal.vue";type LocalState = ProjectStandardState &ProjectTenantState &CommonTenantState & {project?: Project;- showFeatureModal: boolean;searchText: string;- selectedDatabaseIdList: Set<number>;+ showSchemaEditorModal: boolean;+ showFeatureModal: boolean;};const props = defineProps({@@ -229,24 +241,13 @@ const state = reactive<LocalState>({selectedDatabaseIdListForEnvironment: new Map(),tenantProjectId: undefined,selectedDatabaseName: undefined,+ selectedDatabaseIdListForTenantMode: new Set<number>(),deployingTenantDatabaseList: [],- showFeatureModal: false,searchText: "",- selectedDatabaseIdList: new Set<number>(),+ showSchemaEditorModal: false,+ showFeatureModal: false,});-const isDatabaseSelected = (database: Database): boolean => {- return state.selectedDatabaseIdList.has(database.id);-};--const toggleDatabaseSelection = (database: Database, on: boolean) => {- if (on) {- state.selectedDatabaseIdList.add(database.id);- } else {- state.selectedDatabaseIdList.delete(database.id);- }-};-// Returns true if alter schema, false if change data.const isAlterSchema = computed((): boolean => {return props.type === "bb.issue.database.schema.update";@@ -329,11 +330,15 @@ const isUsingGhostMigration = async (databaseList: Database[]) => {// Also works when single db selected.const generateMultiDb = async () => {const selectedDatabaseIdList = [...flattenSelectedDatabaseIdList.value];-const selectedDatabaseList = selectedDatabaseIdList.map((id) => databaseList.value.find((db) => db.id === id)!);+ if (isDev() && allowUsingUIEditor(selectedDatabaseList)) {+ state.showSchemaEditorModal = true;+ return;+ }+const mode = await isUsingGhostMigration(selectedDatabaseList);if (mode === false) {return;@@ -372,7 +377,7 @@ const showGenerateTenant = computed(() => {const allowGenerateTenant = computed(() => {if (isTenantProject.value && state.alterType === "MULTI_DB") {- if (state.selectedDatabaseIdList.size === 0) {+ if (state.selectedDatabaseIdListForTenantMode.size === 0) {return false;}}@@ -389,6 +394,18 @@ const allowGenerateTenant = computed(() => {return true;});+const isDatabaseSelected = (database: Database): boolean => {+ return state.selectedDatabaseIdListForTenantMode.has(database.id);+};++const toggleDatabaseSelection = (database: Database, on: boolean) => {+ if (on) {+ state.selectedDatabaseIdListForTenantMode.add(database.id);+ } else {+ state.selectedDatabaseIdListForTenantMode.delete(database.id);+ }+};+const generateTenant = async () => {if (!hasFeature("bb.feature.multi-tenancy")) {state.showFeatureModal = true;@@ -416,14 +433,16 @@ const generateTenant = async () => {} else {const databaseList: Database[] = [];const databaseStore = useDatabaseStore();- for (const databaseId of state.selectedDatabaseIdList) {+ for (const databaseId of state.selectedDatabaseIdListForTenantMode) {databaseList.push(databaseStore.getDatabaseById(databaseId));}query.name = generateIssueName(databaseList.map((database) => database.name),false);- query.databaseList = Array.from(state.selectedDatabaseIdList).join(",");+ query.databaseList = Array.from(+ state.selectedDatabaseIdListForTenantMode+ ).join(",");}router.push({diff --git a/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue b/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vueindex ab4e6b29e4..658335fb85 100644--- a/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue+++ b/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue@@ -141,6 +141,7 @@ import { useOverrideSubtitle } from "@/bbkit/BBModal.vue";export type State = {selectedDatabaseName: string | undefined;+ selectedDatabaseIdListForTenantMode: Set<DatabaseId>;deployingTenantDatabaseList: DatabaseId[];};diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vuenew file mode 100644index 0000000000..685e34ae7d--- /dev/null+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -0,0 +1,335 @@+<template>+ <BBModal+ :title="'Alter Schema'"+ class="ui-editor-modal-container !w-320 !max-w-[calc(100%-80px)]"+ @close="dismissModal"+ >+ <div+ class="w-full flex flex-row justify-start items-center border-b border-b-gray-300"+ >+ <button+ class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none"+ :class="+ state.selectedTab === 'ui-editor' &&+ 'bg-white border-gray-300 text-gray-800'+ "+ @click="handleChangeTab('ui-editor')"+ >+ UI Editor+ </button>+ <button+ class="-mb-px px-3 leading-9 rounded-t-md text-sm text-gray-500 border border-b-0 border-transparent cursor-pointer select-none"+ :class="+ state.selectedTab === 'raw-sql' &&+ 'bg-white border-gray-300 text-gray-800'+ "+ @click="handleChangeTab('raw-sql')"+ >+ Raw SQL+ </button>+ </div>+ <div class="w-full h-144 border-b mb-4">+ <UIEditor+ v-show="state.selectedTab === 'ui-editor'"+ :database-id-list="props.databaseIdList"+ />+ <div+ v-show="state.selectedTab === 'raw-sql'"+ class="w-full h-full grid grid-rows-[50px,_1fr] overflow-y-auto"+ >+ <div+ class="w-full h-full pl-3 shrink-0 flex flex-row justify-between items-center"+ >+ <div>SQL Editor</div>+ <div>+ <button+ class="text-sm border px-3 leading-8 rounded cursor-pointer hover:bg-gray-100"+ @click="handleSyncSQLFromUIEditor"+ >+ Sync SQL from UI Editor+ </button>+ </div>+ </div>+ <MonacoEditor+ ref="editorRef"+ class="w-full h-full border border-b-0"+ data-label="bb-issue-sql-editor"+ :value="state.editStatement"+ :auto-focus="false"+ :dialect="(databaseEngineType as SQLDialect)"+ @change="onStatementChange"+ />+ </div>+ </div>+ <div class="flex items-center justify-end">+ <button type="button" class="btn-normal py-2 px-4" @click="dismissModal">+ {{ $t("common.cancel") }}+ </button>+ <button+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"+ @click="handlePreviewIssue"+ >+ {{ $t("database.ui-editor.preview-issue") }}+ </button>+ </div>+ </BBModal>++ <!-- Select DDL mode for MySQL -->+ <GhostDialog ref="ghostDialog" />+</template>++<script lang="ts" setup>+import dayjs from "dayjs";+import { head } from "lodash-es";+import { onMounted, PropType, reactive, ref } from "vue";+import { useRouter } from "vue-router";+import {+ Database,+ DatabaseEdit,+ DatabaseId,+ SQLDialect,+ UNKNOWN_ID,+} from "@/types";+import { allowGhostMigration } from "@/utils";+import { useDatabaseStore, useTableStore, useUIEditorStore } from "@/store";+import { diffTableList } from "@/utils/UIEditor/diffTable";+import UIEditor from "@/components/UIEditor/UIEditor.vue";+import GhostDialog from "./GhostDialog.vue";++type TabType = "raw-sql" | "ui-editor";++interface LocalState {+ selectedTab: TabType;+ editStatement: string;+}++const props = defineProps({+ databaseIdList: {+ type: Array as PropType<DatabaseId[]>,+ required: true,+ },+});++const emit = defineEmits<{+ (event: "close"): void;+}>();++const router = useRouter();+const state = reactive<LocalState>({+ selectedTab: "ui-editor",+ editStatement: "",+});+const editorStore = useUIEditorStore();+const tableStore = useTableStore();+const databaseStore = useDatabaseStore();+const ghostDialog = ref<InstanceType<typeof GhostDialog>>();++const databaseList = props.databaseIdList.map((databaseId) => {+ return databaseStore.getDatabaseById(databaseId);+});+const databaseEngineType = databaseList.reduce(+ (engine: string, database: Database) => {+ if (engine === "") {+ engine = database.instance.engine;+ } else {+ engine = database.instance.engine === engine ? engine : "unknown";+ }+ return engine;+ },+ ""+);++onMounted(() => {+ if (databaseList.length === 0 || databaseEngineType === "unknown") {+ emit("close");+ return;+ }+});++const handleChangeTab = (tab: TabType) => {+ state.selectedTab = tab;+};++const onStatementChange = (value: string) => {+ state.editStatement = value;+};++const dismissModal = () => {+ emit("close");+};++// 'normal' -> normal migration+// 'online' -> online migration+// false -> user clicked cancel button+const isUsingGhostMigration = async (databaseList: Database[]) => {+ // Gh-ost is not available for tenant mode yet.+ if (databaseList.some((db) => db.project.tenantMode === "TENANT")) {+ return "normal";+ }++ // check if all selected databases supports gh-ost+ if (allowGhostMigration(databaseList)) {+ // open the dialog to ask the user+ const { result, mode } = await ghostDialog.value!.open();+ if (!result) {+ return false; // return false when user clicked the cancel button+ }+ return mode;+ }++ // fallback to normal+ return "normal";+};++const handleSyncSQLFromUIEditor = async () => {+ const statement = await fetchDDLStatementWithUIEditor();+ state.editStatement = statement;+};++const fetchDDLStatementWithUIEditor = async () => {+ const databaseEditList: DatabaseEdit[] = [];+ for (const database of editorStore.databaseList) {+ const originTableList = await tableStore.getOrFetchTableListByDatabaseId(+ database.id+ );+ const updatedTableList = (+ await editorStore.getOrFetchTableListByDatabaseId(database.id)+ ).filter((table) => !editorStore.droppedTableList.includes(table));+ const diffTableListResult = diffTableList(+ originTableList,+ updatedTableList+ );+ if (+ diffTableListResult.createTableList.length > 0 ||+ diffTableListResult.alterTableList.length > 0 ||+ diffTableListResult.renameTableList.length > 0 ||+ diffTableListResult.dropTableList.length > 0+ ) {+ databaseEditList.push({+ databaseId: database.id,+ ...diffTableListResult,+ });+ }+ }++ const statmentList = [];+ if (databaseEditList.length > 0) {+ const databaseIdList: DatabaseId[] = [];+ for (const databaseEdit of databaseEditList) {+ databaseIdList.push(databaseEdit.databaseId);+ const statement = await editorStore.postDatabaseEdit(databaseEdit);+ statmentList.push(statement);+ }+ }+ return statmentList.join("\n");+};++const handlePreviewIssue = async () => {+ const projectId = head(databaseList)?.projectId || UNKNOWN_ID;+ if (projectId === UNKNOWN_ID) {+ console.error("project unknown");+ return;+ }++ const mode = await isUsingGhostMigration(databaseList);+ if (mode === false) {+ return;+ }+ const isGhostMode = mode === "online";+ const query: Record<string, any> = {+ template: "bb.issue.database.schema.update",+ name: generateIssueName(+ databaseList.map((db) => db.name),+ isGhostMode+ ),+ project: projectId,+ databaseList: props.databaseIdList.join(","),+ };+ if (isGhostMode) {+ query.ghost = 1;+ }++ if (state.selectedTab === "raw-sql") {+ query.sql = state.editStatement;+ } else {+ const databaseEditList: DatabaseEdit[] = [];+ for (const database of editorStore.databaseList) {+ const originTableList = await tableStore.getOrFetchTableListByDatabaseId(+ database.id+ );+ const updatedTableList = (+ await editorStore.getOrFetchTableListByDatabaseId(database.id)+ ).filter((table) => !editorStore.droppedTableList.includes(table));+ const diffTableListResult = diffTableList(+ originTableList,+ updatedTableList+ );+ if (+ diffTableListResult.createTableList.length > 0 ||+ diffTableListResult.alterTableList.length > 0 ||+ diffTableListResult.renameTableList.length > 0 ||+ diffTableListResult.dropTableList.length > 0+ ) {+ databaseEditList.push({+ databaseId: database.id,+ ...diffTableListResult,+ });+ }+ }++ if (databaseEditList.length > 0) {+ const databaseIdList: DatabaseId[] = [];+ const statmentList = [];+ for (const databaseEdit of databaseEditList) {+ databaseIdList.push(databaseEdit.databaseId);+ const statement = await editorStore.postDatabaseEdit(databaseEdit);+ statmentList.push(statement);+ }+ query.databaseList = databaseIdList.join(",");+ query.name = generateIssueName(+ databaseList+ .filter((database) => databaseIdList.includes(database.id))+ .map((db) => db.name),+ isGhostMode+ );+ query.sql = statmentList.join("\n");+ }+ }++ router.push({+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query,+ });+};++const generateIssueName = (+ databaseNameList: string[],+ isOnlineMode: boolean+) => {+ const issueNameParts: string[] = [];+ if (databaseNameList.length === 1) {+ issueNameParts.push(`[${databaseNameList[0]}]`);+ } else {+ issueNameParts.push(`[${databaseNameList.length} databases]`);+ }+ if (isOnlineMode) {+ issueNameParts.push("Online schema change");+ } else {+ issueNameParts.push(`Alter schema`);+ }+ const datetime = dayjs().format("@MM-DD HH:mm");+ const tz = "UTC" + dayjs().format("ZZ");+ issueNameParts.push(`${datetime} ${tz}`);++ return issueNameParts.join(" ");+};+</script>++<style>+.ui-editor-modal-container > .modal-container {+ @apply w-full h-full overflow-auto;+}+</style>diff --git a/frontend/src/components/UIEditor/DatabaseTree.vue b/frontend/src/components/UIEditor/DatabaseTree.vueindex deeb6a8ad8..f2a2e446aa 100644--- a/frontend/src/components/UIEditor/DatabaseTree.vue+++ b/frontend/src/components/UIEditor/DatabaseTree.vue@@ -91,6 +91,7 @@ interface TreeNodeForTable extends BaseTreeNode {instanceId: InstanceId;databaseId: DatabaseId;tableId: TableId;+ table: Table;}type TreeNode = TreeNodeForInstance | TreeNodeForDatabase | TreeNodeForTable;@@ -140,12 +141,7 @@ const contextMenuOptions = computed(() => {});return options;} else if (treeNode?.type === "table") {- const table = editorStore.findTable(- treeNode.tableId,- treeNode.label,- treeNode.databaseId- );- const isDropped = editorStore.droppedTableList.includes(table as Table);+ const isDropped = editorStore.droppedTableList.includes(treeNode.table);const options = [];if (isDropped) {options.push({@@ -237,6 +233,7 @@ watch(tableList.value, () => {instanceId: database.instance.id,databaseId: database.id,tableId: table.id,+ table: table,};});}@@ -315,16 +312,10 @@ const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {treeNode.databaseId,treeNode.tableId);- const table = editorStore.findTable(- treeNode.tableId,- treeNode.label,- treeNode.databaseId- );-- const isDropped = editorStore.droppedTableList.includes(table as Table);+ const isDropped = editorStore.droppedTableList.includes(treeNode.table);if (isDropped) {additionalClassList.push("text-red-700 line-through");- } else if (!isEqual(originTable, table)) {+ } else if (!isEqual(originTable, treeNode.table)) {additionalClassList.push("text-yellow-700");}}@@ -400,6 +391,7 @@ const loadSubTree = async (treeNode: TreeNode) => {instanceId: instanceId,databaseId: databaseId,tableId: table.id,+ table: table,};});}@@ -434,18 +426,14 @@ const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {} else if (treeNode.type === "table") {const databaseId = treeNode.databaseId as any;const tableId = treeNode.tableId as any;- const table = editorStore.findTable(- tableId,- treeNode.label || "",- databaseId- ) as Table;editorStore.addTab({id: generateUniqueTabId(),type: UIEditorTabType.TabForTable,databaseId: databaseId,tableId: tableId,- tableCache: cloneDeep(table),+ table: treeNode.table,+ tableCache: cloneDeep(treeNode.table),});}@@ -480,16 +468,13 @@ const handleContextMenuDropdownSelect = async (key: string) => {type: UIEditorTabType.TabForTable,databaseId: treeNode.databaseId,tableId: table.id,+ table: table,tableCache: cloneDeep(table),});}} else if (treeNode?.type === "table") {if (key === "drop") {- editorStore.dropTable(- treeNode.databaseId,- treeNode.tableId,- treeNode.label- );+ editorStore.dropTable(treeNode.table);} else if (key === "restore") {editorStore.restoreTable(treeNode.databaseId,diff --git a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vueindex 896463061c..ed875819b4 100644--- a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue+++ b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue@@ -67,11 +67,12 @@:key="`${index}-${table.id}`"class="grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] text-sm even:bg-gray-50">- <div- class="table-body-item-container cursor-pointer hover:opacity-80"- @click="handleTableItemClick(table)"- >- {{ table.name }}+ <div class="table-body-item-container">+ <span+ class="cursor-pointer hover:opacity-60"+ @click="handleTableItemClick(table)"+ >{{ table.name }}</span+ ></div><div class="table-body-item-container">{{ table.rowCount }}@@ -118,10 +119,10 @@</div><template v-else><HighlightCodeBlock- v-if="state.ddlStatement !== ''"+ v-if="state.statement !== ''"class="text-sm px-3 py-2 whitespace-pre-wrap break-all"language="sql"- :code="state.ddlStatement"+ :code="state.statement"></HighlightCodeBlock><span v-else class="px-3 my-2 italic">Nothing changed</span></template>@@ -147,7 +148,7 @@ type TabType = "list" | "er-diagram" | "raw-sql";interface LocalState {selectedTab: TabType;isFetchingDDL: boolean;- ddlStatement: string;+ statement: string;}const editorStore = useUIEditorStore();@@ -156,7 +157,7 @@ const tableStore = useTableStore();const state = reactive<LocalState>({selectedTab: "list",isFetchingDDL: false,- ddlStatement: "",+ statement: "",});const currentTab = editorStore.currentTab as DatabaseTabContext;const database = databaseStore.getDatabaseById(currentTab.databaseId);@@ -223,6 +224,7 @@ watch(if (diffTableListResult.createTableList.length > 0 ||diffTableListResult.alterTableList.length > 0 ||+ diffTableListResult.renameTableList.length > 0 ||diffTableListResult.dropTableList.length > 0) {const databaseEdit = {@@ -230,7 +232,7 @@ watch(...diffTableListResult,};const statement = await editorStore.postDatabaseEdit(databaseEdit);- state.ddlStatement = statement;+ state.statement = statement;}state.isFetchingDDL = false;}@@ -248,6 +250,7 @@ const handleCreateNewTable = () => {type: UIEditorTabType.TabForTable,databaseId: database.id,tableId: table.id,+ table: table,tableCache: cloneDeep(table),});};@@ -258,12 +261,13 @@ const handleTableItemClick = (table: Table) => {type: UIEditorTabType.TabForTable,databaseId: database.id,tableId: table.id,+ table: table,tableCache: cloneDeep(table),});};const handleDropTable = (table: Table) => {- editorStore.dropTable(table.database.id, table.id, table.name);+ editorStore.dropTable(table);};</script>@@ -272,6 +276,6 @@ const handleDropTable = (table: Table) => {@apply py-2 px-3;}.table-body-item-container {- @apply w-full box-border p-px pl-3 pr-4 relative leading-8;+ @apply w-full box-border p-px pl-3 pr-4 relative leading-9;}</style>diff --git a/frontend/src/components/UIEditor/Panels/TableEditor.vue b/frontend/src/components/UIEditor/Panels/TableEditor.vueindex 306b7368ae..daec5d8b6e 100644--- a/frontend/src/components/UIEditor/Panels/TableEditor.vue+++ b/frontend/src/components/UIEditor/Panels/TableEditor.vue@@ -11,13 +11,7 @@<inputv-model="tableCache.name"placeholder=""- :disabled="tableCache.id !== UNKNOWN_ID"- class="w-full leading-6 px-2 py-1 rounded border text-sm"- :class="- tableCache.id === UNKNOWN_ID- ? 'border-gray-200'- : 'border-transparent'- "+ class="w-full leading-6 px-2 py-1 rounded border border-gray-200 text-sm"type="text"/></div>@@ -80,9 +74,8 @@<div class="table-body-item-container"><inputv-model="column.name"- :disabled="column.id !== UNKNOWN_ID"placeholder="column name"- class="w-full box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ class="column-field-input"type="text"/></div>@@ -92,7 +85,7 @@<inputv-model="column.type"placeholder="column type"- class="w-full pr-8 box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ class="pr-8 column-field-input"type="text"/><NDropdown@@ -100,7 +93,7 @@:options="dataTypeOptions"@select="(dataType: string) => (column.type = dataType)">- <button class="absolute right-6">+ <button class="absolute right-5"><heroicons-solid:chevron-up-downclass="w-4 h-auto text-gray-400"/>@@ -120,7 +113,7 @@<inputv-model="column.default"placeholder="column default value"- class="w-full box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ class="column-field-input"type="text"/></div>@@ -128,7 +121,7 @@<inputv-model="column.comment"placeholder="comment"- class="w-full box-border border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400"+ class="column-field-input"type="text"/></div>@@ -160,10 +153,13 @@<div><div class="flex flex-row items-center space-x-2"><button- class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:bg-gray-100"+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="!allowSave"@click="handleDiscardChanges">- <heroicons-outline:trash class="w-4 h-auto mr-1 text-gray-400" />+ <heroicons-solid:arrow-uturn-left+ class="w-4 h-auto mr-1 text-gray-400"+ />Discard changes</button><button@@ -188,18 +184,15 @@ import {useTableStore,useUIEditorStore,} from "@/store/modules";-import {- TableTabContext,- Column,- UNKNOWN_ID,- Table,- DatabaseEdit,-} from "@/types";+import { TableTabContext, Column, UNKNOWN_ID, DatabaseEdit } from "@/types";import { BBCheckbox, BBSpin } from "@/bbkit";import { getDataTypeSuggestionList } from "@/utils";import { diffTableList } from "@/utils/UIEditor/diffTable";import HighlightCodeBlock from "@/components/HighlightCodeBlock";+const columnNameFieldRegexp = /\S+/;+const columnTypeFieldRegexp = /\S+/;+interface LocalState {isFetchingDDL: boolean;ddlStatement: string;@@ -213,12 +206,8 @@ const editorStore = useUIEditorStore();const tableStore = useTableStore();const notificationStore = useNotificationStore();const currentTab = editorStore.currentTab as TableTabContext;+const table = currentTab.table;const tableCache = currentTab.tableCache;-const table = editorStore.findTable(- tableCache.id,- tableCache.name,- tableCache.database.id-) as Table;const allowSave = computed(() => {return !isEqual(tableCache, table);@@ -284,6 +273,25 @@ const handleSaveChanges = async () => {return;}+ for (const column of tableCache.columnList) {+ if (!columnNameFieldRegexp.test(column.name)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Invalid column name",+ });+ return;+ }+ if (!columnTypeFieldRegexp.test(column.type)) {+ notificationStore.pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Invalid column type",+ });+ return;+ }+ }+table.name = tableCache.name;table.columnList = cloneDeep(tableCache.columnList);};@@ -311,18 +319,19 @@ const handleDiscardChanges = () => {const handlePreviewDDLStatement = async () => {const databaseEdit: DatabaseEdit = {- databaseId: tableCache.database.id,+ databaseId: table.database.id,createTableList: [],alterTableList: [],+ renameTableList: [],dropTableList: [],};if (table.id === UNKNOWN_ID) {- const diffTableListResult = diffTableList([], [tableCache]);+ const diffTableListResult = diffTableList([], [table]);databaseEdit.createTableList = diffTableListResult.createTableList;} else {const originTable = tableStore.getTableByDatabaseIdAndTableId(- tableCache.database.id,- tableCache.id+ table.database.id,+ table.id);const isDropped = editorStore.droppedTableList.includes(table);if (isDropped) {@@ -331,6 +340,7 @@ const handlePreviewDDLStatement = async () => {} else {const diffTableListResult = diffTableList([originTable], [table]);databaseEdit.alterTableList = diffTableListResult.alterTableList;+ databaseEdit.renameTableList = diffTableListResult.renameTableList;}}state.isFetchingDDL = true;@@ -347,4 +357,7 @@ const handlePreviewDDLStatement = async () => {.table-body-item-container {@apply w-full box-border p-px pr-2 relative;}+.column-field-input {+ @apply w-full box-border rounded border-none bg-transparent text-sm focus:bg-white focus:text-black placeholder:italic placeholder:text-gray-400;+}</style>diff --git a/frontend/src/components/UIEditor/TabsContainer.vue b/frontend/src/components/UIEditor/TabsContainer.vueindex e59d9361cd..e93ac6e413 100644--- a/frontend/src/components/UIEditor/TabsContainer.vue+++ b/frontend/src/components/UIEditor/TabsContainer.vue@@ -27,7 +27,7 @@</span><NEllipsisclass="text-sm w-24"- :class="checkTabSaved(tab) ? '' : 'italic'"+ :class="checkTabSaved(tab) ? '' : 'text-yellow-700 italic'">{{ getTabName(tab) }}</NEllipsis></div>diff --git a/frontend/src/components/UIEditor/UIEditor.vue b/frontend/src/components/UIEditor/UIEditor.vueindex 9bfa670df9..b2b5457ff2 100644--- a/frontend/src/components/UIEditor/UIEditor.vue+++ b/frontend/src/components/UIEditor/UIEditor.vue@@ -62,6 +62,9 @@ const currentTab = computed(() => {});onMounted(async () => {+ // Reset UI editor state before fetching latest data when mounted.+ editorStore.$reset();+// Prepare instance and database data.const databaseIdList = props.databaseIdList;const databaseList = await editorStore.fetchDatabaseList(databaseIdList);diff --git a/frontend/src/store/modules/UIEditor.ts b/frontend/src/store/modules/UIEditor.tsindex ebd01f6d6a..70deb4e5fe 100644--- a/frontend/src/store/modules/UIEditor.ts+++ b/frontend/src/store/modules/UIEditor.ts@@ -38,53 +38,53 @@ export const useUIEditorStore = defineStore("UIEditor", {},getters: {currentTab(state) {+ if (isUndefined(state.tabState.currentTabId)) {+ return undefined;+ }return state.tabState.tabMap.get(state.tabState.currentTabId);},+ tabList(state) {+ return Array.from(state.tabState.tabMap.values());+ },},actions: {- getTabById(tabId: string) {- return this.tabState.tabMap.get(tabId);- },- // getTabByDatabaseIdAndTableName gets tab by database id and table name.- // * tableName is used to position those new tables with UNKNOWN_ID.- getTabByDatabaseIdAndTableName(databaseId: DatabaseId, tableName?: string) {- const wantedTabType = isUndefined(tableName)- ? UIEditorTabType.TabForDatabase- : UIEditorTabType.TabForTable;- for (const [_, tab] of this.tabState.tabMap) {- if (tab.type === wantedTabType && tab.databaseId === databaseId) {- if (wantedTabType === UIEditorTabType.TabForTable) {- if ((tab as TableTabContext).tableCache.name === tableName) {- return tab;- }- } else {- return tab;- }- }- }- return undefined;- },addTab(tab: TabContext, setAsCurrentTab = true) {- const tabTemp = this.getTabByDatabaseIdAndTableName(- tab.databaseId,- tab.type === UIEditorTabType.TabForTable- ? tab.tableCache.name- : undefined- );- if (!isUndefined(tabTemp)) {- tab = tabTemp;+ const tabCache = this.tabList.find((item) => {+ if (item.type !== tab.type) {+ return false;+ }++ if (+ item.type === UIEditorTabType.TabForDatabase &&+ item.databaseId === tab.databaseId+ ) {+ return true;+ }+ if (+ item.type === UIEditorTabType.TabForTable &&+ item.table === (tab as TableTabContext).table+ ) {+ return true;+ }+ return false;+ });++ if (tabCache !== undefined) {+ tab = tabCache;} else {this.tabState.tabMap.set(tab.id, tab);}+if (setAsCurrentTab) {this.setCurrentTab(tab.id);}},setCurrentTab(tabId: string) {- if (isUndefined(this.getTabById(tabId))) {- return;+ if (isUndefined(this.tabState.tabMap.get(tabId))) {+ this.tabState.currentTabId = undefined;+ } else {+ this.tabState.currentTabId = tabId;}- this.tabState.currentTabId = tabId;},closeTab(tabId: string) {const tabList = Array.from(this.tabState.tabMap.values());@@ -134,15 +134,6 @@ export const useUIEditorStore = defineStore("UIEditor", {}return tableList;},- // findTable tries to find the table from the table list including existing tables and created tables.- findTable(tableId: TableId, tableName: string, databaseId: DatabaseId) {- return this.tableList.find(- (table) =>- table.id === tableId &&- table.name === tableName &&- table.database.id === databaseId- );- },// createNewTable creates a temp table with databaseId.// Its ID is UNKNOWN_ID and name should be an unique temp name.createNewTable(databaseId: DatabaseId) {@@ -177,21 +168,17 @@ export const useUIEditorStore = defineStore("UIEditor", {this.tableList.push(table);return table;},- dropTable(databaseId: DatabaseId, tableId: TableId, tableName: string) {- const index = this.tableList.findIndex(- (table) =>- table.database.id === databaseId &&- table.id === tableId &&- table.name === tableName- );- const table = this.tableList[index];+ dropTable(table: Table) {+ const index = this.tableList.findIndex((item) => item === table);if (table.id === UNKNOWN_ID) {this.tableList.splice(index, 1);} else {this.droppedTableList.push(table);}- const tab = this.getTabByDatabaseIdAndTableName(databaseId, tableName);+ const tab = this.tabList.find(+ (tab) => tab.type === UIEditorTabType.TabForTable && tab.table === table+ );if (tab) {this.closeTab(tab.id);}diff --git a/frontend/src/types/UIEditor.ts b/frontend/src/types/UIEditor.tsindex d1c94f6a44..986afd049e 100644--- a/frontend/src/types/UIEditor.ts+++ b/frontend/src/types/UIEditor.ts@@ -18,6 +18,8 @@ export interface TableTabContext {type: UIEditorTabType.TabForTable;databaseId: DatabaseId;tableId: TableId;+ // Save the reference for those new tables.+ table: Table;// Save the editing table cache in tab.tableCache: Table;}@@ -29,7 +31,7 @@ type TabId = string;export interface UIEditorState {tabState: {tabMap: Map<TabId, TabContext>;- currentTabId: TabId;+ currentTabId?: TabId;};databaseList: Database[];tableList: Table[];diff --git a/frontend/src/utils/UIEditor/index.ts b/frontend/src/utils/UIEditor/index.tsindex e01dcbb482..82e4fd75bf 100644--- a/frontend/src/utils/UIEditor/index.ts+++ b/frontend/src/utils/UIEditor/index.ts@@ -10,13 +10,13 @@ export const allowUsingUIEditor = (databaseList: Database[]): boolean => {export const getDataTypeSuggestionList = (engineType: EngineType = "MYSQL") => {if (engineType === "MYSQL") {return [- "bigint",- "binary",- "blob",+ "bit",+ "bool","boolean","char","date",- "enum",+ "datetime",+ "double","int","json","varchar(255)",