Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: new Table/Column interface for UI editor (#3748)
boojack29dec9ab6358
diff --git a/api/database.go b/api/database.goindex 4c249b47f4..dcfa6d7464 100644--- a/api/database.go+++ b/api/database.go@@ -149,8 +149,7 @@ type CreateTableContext struct {// AlterTableContext is the edit database context to alter a table.type AlterTableContext struct {- TableID int `json:"tableId"`- Name string `json:"name"`+ Name string `json:"name"`// ColumnNameList should be the final order of columns in UI editor and is used to confirm column positions.ColumnNameList []string `json:"columnNameList"`@@ -168,8 +167,7 @@ type RenameTableContext struct {// DropTableContext is the edit database context to drop a table.type DropTableContext struct {- TableID int `json:"tableId"`- Name string `json:"name"`+ Name string `json:"name"`}// AddColumnContext is the create/alter table context to add a column.diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex df08b5b7d7..da84ccd493 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -77,8 +77,7 @@<script lang="ts" setup>import dayjs from "dayjs";-import { head, isEqual } from "lodash-es";-import { useDialog } from "naive-ui";+import { head } from "lodash-es";import { onMounted, PropType, reactive, ref } from "vue";import { useRouter } from "vue-router";import {@@ -86,12 +85,10 @@ import {DatabaseEdit,DatabaseId,SQLDialect,- TabContext,- UIEditorTabType,UNKNOWN_ID,} from "@/types";import { allowGhostMigration } from "@/utils";-import { useDatabaseStore, useTableStore, useUIEditorStore } from "@/store";+import { useDatabaseStore, useUIEditorStore } from "@/store";import { diffTableList } from "@/utils/UIEditor/diffTable";import UIEditor from "@/components/UIEditor/UIEditor.vue";import GhostDialog from "./GhostDialog.vue";@@ -124,9 +121,7 @@ const state = reactive<LocalState>({editStatement: "",});const editorStore = useUIEditorStore();-const tableStore = useTableStore();const databaseStore = useDatabaseStore();-const dialog = useDialog();const ghostDialog = ref<InstanceType<typeof GhostDialog>>();const databaseList = props.databaseIdList.map((databaseId) => {@@ -194,16 +189,13 @@ const handleSyncSQLFromUIEditor = async () => {const fetchDatabaseEditMapWithUIEditor = async () => {const databaseEditList: DatabaseEdit[] = [];for (const database of editorStore.databaseList) {- const originTableList = await tableStore.getOrFetchTableListByDatabaseId(- database.id+ const originTableList = editorStore.originTableList.filter(+ (table) => table.databaseId === database.id);- const updatedTableList = (- await editorStore.getOrFetchTableListByDatabaseId(database.id)- ).filter((table) => !editorStore.droppedTableList.includes(table));- const diffTableListResult = diffTableList(- originTableList,- updatedTableList+ const tableList = await editorStore.getOrFetchTableListByDatabaseId(+ database.id);+ const diffTableListResult = diffTableList(originTableList, tableList);if (diffTableListResult.createTableList.length > 0 ||diffTableListResult.alterTableList.length > 0 ||@@ -227,28 +219,6 @@ const fetchDatabaseEditMapWithUIEditor = async () => {return databaseEditMap;};-const unsavedDialogWarning = (): Promise<- "Close" | "NegativeClick" | "PositiveClick"-> => {- return new Promise((resolve) => {- dialog.warning({- title: "Confirm to continue",- content: "There are unsaved changes. Are you sure confirm to continue?",- negativeText: "Discard",- positiveText: "Save",- onClose: () => {- resolve("Close");- },- onNegativeClick: () => {- resolve("NegativeClick");- },- onPositiveClick: () => {- resolve("PositiveClick");- },- });- });-};-const handlePreviewIssue = async () => {const projectId = head(databaseList)?.projectId || UNKNOWN_ID;if (projectId === UNKNOWN_ID) {@@ -286,30 +256,6 @@ const handlePreviewIssue = async () => {if (state.selectedTab === "raw-sql") {query.sql = state.editStatement;} else {- // Check whether tabs saved.- const unsavedTabList: TabContext[] = [];- for (const tab of editorStore.tabList) {- if (tab.type === UIEditorTabType.TabForTable) {- if (!isEqual(tab.tableCache, tab.table)) {- unsavedTabList.push(tab);- }- }- }- if (unsavedTabList.length > 0) {- const action = await unsavedDialogWarning();- if (action === "NegativeClick") {- for (const unsavedTab of unsavedTabList) {- editorStore.discardTabChanges(unsavedTab);- }- } else if (action === "PositiveClick") {- for (const unsavedTab of unsavedTabList) {- editorStore.saveTab(unsavedTab);- }- } else {- return;- }- }-const databaseEditMap = await fetchDatabaseEditMapWithUIEditor();const databaseIdList = Array.from(databaseEditMap.keys());if (databaseIdList.length > 0) {diff --git a/frontend/src/components/UIEditor/DatabaseTree.vue b/frontend/src/components/UIEditor/DatabaseTree.vueindex 5e929e07b3..6b0a6ac786 100644--- a/frontend/src/components/UIEditor/DatabaseTree.vue+++ b/frontend/src/components/UIEditor/DatabaseTree.vue@@ -41,30 +41,23 @@<TableNameModalv-if="state.tableNameModalContext !== undefined":database-id="state.tableNameModalContext.databaseId"- :table="state.tableNameModalContext.table"+ :table-name="state.tableNameModalContext.tableName"@close="state.tableNameModalContext = undefined"/></template><script lang="ts" setup>-import { cloneDeep, escape, isEqual, isUndefined } from "lodash-es";+import { escape, isEqual, isUndefined } from "lodash-es";import { TreeOption, NEllipsis, NInput } from "naive-ui";import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";import { useI18n } from "vue-i18n";import scrollIntoView from "scroll-into-view-if-needed";-import {- DatabaseId,- InstanceId,- Table,- TableId,- UIEditorTabType,- UNKNOWN_ID,-} from "@/types";+import { DatabaseId, InstanceId, UIEditorTabType } from "@/types";+import { Table } from "@/types/UIEditor";import {useUIEditorStore,generateUniqueTabId,useInstanceStore,- useTableStore,} from "@/store";import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";import InstanceEngineIcon from "@/components/InstanceEngineIcon.vue";@@ -95,8 +88,7 @@ interface TreeNodeForTable extends BaseTreeNode {type: "table";instanceId: InstanceId;databaseId: DatabaseId;- tableId: TableId;- table: Table;+ tableName: string;}type TreeNode = TreeNodeForInstance | TreeNodeForDatabase | TreeNodeForTable;@@ -112,14 +104,13 @@ interface LocalState {shouldRelocateTreeNode: boolean;tableNameModalContext?: {databaseId: DatabaseId;- table: Table | undefined;+ tableName: string | undefined;};}const { t } = useI18n();const editorStore = useUIEditorStore();const instanceStore = useInstanceStore();-const tableStore = useTableStore();const state = reactive<LocalState>({shouldRelocateTreeNode: false,});@@ -144,15 +135,24 @@ const contextMenuOptions = computed(() => {return [];}- if (treeNode?.type === "database") {+ if (treeNode.type === "database") {const options = [];options.push({key: "create-table",label: t("ui-editor.actions.create-table"),});return options;- } else if (treeNode?.type === "table") {- const isDropped = editorStore.droppedTableList.includes(treeNode.table);+ } else if (treeNode.type === "table") {+ const table = editorStore.tableList.find(+ (table) =>+ table.databaseId === treeNode.databaseId &&+ table.newName === treeNode.tableName+ );+ if (!table) {+ return [];+ }++ const isDropped = table.status === "dropped";const options = [];if (isDropped) {options.push({@@ -252,7 +252,7 @@ watch([tableList.value, databaseDataLoadedSet.value], () => {const databaseTableList: Table[] = [];for (const table of tableList.value) {- if (table.database.id === database.id) {+ if (table.databaseId === database.id) {databaseTableList.push(table);}}@@ -264,14 +264,13 @@ watch([tableList.value, databaseDataLoadedSet.value], () => {databaseTreeNode.children = databaseTableList.map((table) => {return {type: "table",- key: `t-${table.database.id}-${table.id}-${table.name}`,- label: table.name,+ key: `t-${table.databaseId}-${table.newName}`,+ label: table.newName,children: [],isLeaf: true,instanceId: database.instance.id,databaseId: database.id,- tableId: table.id,- table: table,+ tableName: table.newName,};});}@@ -295,7 +294,7 @@ watch(if (!expandedKeysRef.value.includes(databaseTreeNodeKey)) {expandedKeysRef.value.push(databaseTreeNodeKey);}- const tableTreeNodeKey = `t-${currentTab.databaseId}-${currentTab.tableId}-${currentTab.tableCache.name}`;+ const tableTreeNodeKey = `t-${currentTab.databaseId}-${currentTab.tableName}`;selectedKeysRef.value = [tableTreeNodeKey];}@@ -359,17 +358,22 @@ const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {const additionalClassList: string[] = ["select-none"];if (treeNode.type === "table") {- if (treeNode.tableId === UNKNOWN_ID) {+ const table = editorStore.tableList.find(+ (table) =>+ table.databaseId === treeNode.databaseId &&+ table.newName === treeNode.tableName+ ) as Table;++ if (table.status === "created") {additionalClassList.push("text-green-700");+ } else if (table.status === "dropped") {+ additionalClassList.push("text-red-700 line-through");} else {- const originTable = tableStore.getTableByDatabaseIdAndTableId(- treeNode.databaseId,- treeNode.tableId+ const originTable = editorStore.originTableList.find(+ (item) =>+ item.databaseId === table.databaseId && item.oldName === table.oldName);- const isDropped = editorStore.droppedTableList.includes(treeNode.table);- if (isDropped) {- additionalClassList.push("text-red-700 line-through");- } else if (!isEqual(originTable, treeNode.table)) {+ if (!isEqual(originTable, table)) {additionalClassList.push("text-yellow-700");}}@@ -434,7 +438,7 @@ const loadSubTree = async (treeNode: TreeNode) => {databaseId);if (tableList.length === 0) {- treeNode.children = undefined;+ treeNode.children = [];treeNode.isLeaf = true;}}@@ -460,22 +464,18 @@ const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {expandedKeysRef.value.push(treeNode.key);}} else if (treeNode.type === "database") {+ await loadSubTree(treeNode);editorStore.addTab({id: generateUniqueTabId(),type: UIEditorTabType.TabForDatabase,databaseId: treeNode.databaseId,});} else if (treeNode.type === "table") {- const databaseId = treeNode.databaseId;- const tableId = treeNode.tableId;-editorStore.addTab({id: generateUniqueTabId(),type: UIEditorTabType.TabForTable,- databaseId: databaseId,- tableId: tableId,- table: treeNode.table,- tableCache: cloneDeep(treeNode.table),+ databaseId: treeNode.databaseId,+ tableName: treeNode.tableName,});}@@ -521,23 +521,25 @@ const handleContextMenuDropdownSelect = async (key: string) => {await loadSubTree(treeNode);state.tableNameModalContext = {databaseId: treeNode.databaseId,- table: undefined,+ tableName: undefined,};}} else if (treeNode?.type === "table") {+ const table = editorStore.tableList.find(+ (table) =>+ table.databaseId === treeNode.databaseId &&+ table.newName === treeNode.tableName+ ) as Table;+if (key === "rename") {state.tableNameModalContext = {databaseId: treeNode.databaseId,- table: treeNode.table,+ tableName: table.newName,};} else if (key === "drop") {- editorStore.dropTable(treeNode.table);+ editorStore.dropTable(table);} else if (key === "restore") {- editorStore.restoreTable(- treeNode.databaseId,- treeNode.tableId,- treeNode.label- );+ editorStore.restoreTable(table);}}contextMenu.showDropdown = false;diff --git a/frontend/src/components/UIEditor/Modals/TableNameModal.vue b/frontend/src/components/UIEditor/Modals/TableNameModal.vueindex cea7d76a14..0d0d985561 100644--- a/frontend/src/components/UIEditor/Modals/TableNameModal.vue+++ b/frontend/src/components/UIEditor/Modals/TableNameModal.vue@@ -31,14 +31,18 @@<script lang="ts" setup>import { computed, PropType, reactive } from "vue";-import { DatabaseId, Table, UNKNOWN_ID, UIEditorTabType } from "@/types";+import { useI18n } from "vue-i18n";+import { DatabaseId, UNKNOWN_ID, UIEditorTabType, unknown } from "@/types";+import { TableTabContext } from "@/types/UIEditor";import {useUIEditorStore,useNotificationStore,generateUniqueTabId,} from "@/store";-import { cloneDeep } from "lodash-es";-import { useI18n } from "vue-i18n";+import {+ transformColumnDataToColumn,+ transformTableDataToTable,+} from "@/utils/UIEditor/transform";const tableNameFieldRegexp = /^\S+$/;@@ -51,8 +55,8 @@ const props = defineProps({type: Number as PropType<DatabaseId>,default: UNKNOWN_ID,},- table: {- type: Object as PropType<Table | undefined>,+ tableName: {+ type: String as PropType<string | undefined>,default: undefined,},});@@ -65,11 +69,11 @@ const { t } = useI18n();const editorStore = useUIEditorStore();const notificationStore = useNotificationStore();const state = reactive<LocalState>({- tableName: props.table?.name || "",+ tableName: props.tableName || "",});const isCreatingTable = computed(() => {- return props.table === undefined;+ return props.tableName === undefined;});const handleTableNameChange = (event: Event) => {@@ -90,7 +94,7 @@ const handleConfirmButtonClick = async () => {const tableList = await editorStore.getOrFetchTableListByDatabaseId(databaseId);- const tableNameList = tableList.map((table) => table.name);+ const tableNameList = tableList.map((table) => table.newName);if (tableNameList.includes(state.tableName)) {notificationStore.pushNotification({module: "bytebase",@@ -101,26 +105,41 @@ const handleConfirmButtonClick = async () => {}if (isCreatingTable.value) {- const table = editorStore.createNewTable(props.databaseId);- table.name = state.tableName;+ const unknownTable = unknown("TABLE");+ const unknownColumn = unknown("COLUMN");+ unknownColumn.name = "id";+ unknownColumn.type = "int";+ unknownColumn.comment = "ID";++ const table = transformTableDataToTable(unknownTable);+ table.databaseId = databaseId;+ table.oldName = state.tableName;+ table.newName = state.tableName;+ table.status = "created";+ const column = transformColumnDataToColumn(unknownColumn);+ column.status = "created";+ table.columnList.push(column);+ editorStore.tableList.push(table);editorStore.addTab({id: generateUniqueTabId(),type: UIEditorTabType.TabForTable,databaseId: props.databaseId,- tableId: table.id,- table: table,- tableCache: cloneDeep(table),+ tableName: table.newName,});dismissModal();} else {- const originTable = editorStore.tableList.find(- (item) => item === props.table+ const table = editorStore.tableList.find(+ (table) =>+ table.databaseId === databaseId && table.newName === props.tableName);- if (originTable) {- originTable.name = state.tableName;- const tab = editorStore.getTableTabByTable(originTable);+ if (table) {+ const tab = editorStore.findTab(+ table.databaseId,+ table.newName+ ) as TableTabContext;+ table.newName = state.tableName;if (tab) {- tab.tableCache.name = originTable.name;+ tab.tableName = table.newName;}}dismissModal();diff --git a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vueindex 603d00a39b..54f48c5031 100644--- a/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue+++ b/frontend/src/components/UIEditor/Panels/DatabaseEditor.vue@@ -62,16 +62,21 @@<!-- table body --><div class="w-full"><div- v-for="(table, index) in tableListRef"- :key="`${index}-${table.id}`"+ v-for="(table, index) in tableList"+ :key="`${index}-${table.newName}`"class="grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] text-sm even:bg-gray-50"+ :class="+ isDroppedTable(table) && 'text-red-700 !bg-red-50 opacity-70'+ "><div class="table-body-item-container"><NEllipsis- class="w-full cursor-pointer hover:text-accent"- @click="handleTableItemClick(table)"- >{{ table.name }}</NEllipsis+ class="w-full cursor-pointer leading-6 my-2 hover:text-accent">+ <span @click="handleTableItemClick(table)">+ {{ table.newName }}+ </span>+ </NEllipsis></div><div class="table-body-item-container">{{ table.rowCount }}@@ -89,7 +94,7 @@{{ table.comment }}</div><div class="w-full flex justify-start items-center">- <n-tooltip trigger="hover">+ <n-tooltip v-if="!isDroppedTable(table)" trigger="hover"><template #trigger><heroicons:trashclass="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"@@ -98,6 +103,15 @@</template><span>{{ $t("ui-editor.actions.drop-table") }}</span></n-tooltip>+ <n-tooltip v-else trigger="hover">+ <template #trigger>+ <heroicons:arrow-uturn-left+ class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"+ @click="handleRestoreTable(table)"+ />+ </template>+ <span>{{ $t("ui-editor.actions.restore") }}</span>+ </n-tooltip></div></div></div>@@ -133,32 +147,26 @@<TableNameModalv-if="state.tableNameModalContext !== undefined":database-id="state.tableNameModalContext.databaseId"- :table="state.tableNameModalContext.table"+ :table-name="state.tableNameModalContext.tableName"@close="state.tableNameModalContext = undefined"/></template><script lang="ts" setup>-import { cloneDeep } from "lodash-es";import { NEllipsis } from "naive-ui";-import { computed, reactive, ref, watch } from "vue";+import { computed, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import {generateUniqueTabId,useDatabaseStore,- useTableStore,useUIEditorStore,} from "@/store";-import {- DatabaseId,- DatabaseTabContext,- Table,- UIEditorTabType,-} from "@/types";+import { DatabaseId, DatabaseTabContext, UIEditorTabType } from "@/types";+import { Table } from "@/types/UIEditor";import { bytesToString } from "@/utils";-import { diffTableList } from "@/utils/UIEditor/diffTable";import HighlightCodeBlock from "@/components/HighlightCodeBlock";import TableNameModal from "../Modals/TableNameModal.vue";+import { diffTableList } from "@/utils/UIEditor/diffTable";type TabType = "table-list" | "er-diagram" | "raw-sql";@@ -168,14 +176,13 @@ interface LocalState {statement: string;tableNameModalContext?: {databaseId: DatabaseId;- table: Table | undefined;+ tableName: string | undefined;};}const { t } = useI18n();const editorStore = useUIEditorStore();const databaseStore = useDatabaseStore();-const tableStore = useTableStore();const state = reactive<LocalState>({selectedTab: "table-list",isFetchingDDL: false,@@ -183,7 +190,10 @@ const state = reactive<LocalState>({});const currentTab = editorStore.currentTab as DatabaseTabContext;const database = databaseStore.getDatabaseById(currentTab.databaseId);-const tableListRef = ref<Table[]>([]);++const tableList = computed(() => {+ return editorStore.tableList;+});const tableHeaderList = computed(() => {return [{@@ -213,32 +223,16 @@ const tableHeaderList = computed(() => {];});-watch(- [editorStore.tableList, editorStore.droppedTableList],- async () => {- const tableList = await editorStore.getOrFetchTableListByDatabaseId(- database.id- );- tableListRef.value = tableList.filter(- (table) => !editorStore.droppedTableList.includes(table)- );- },- {- immediate: true,- }-);-watch(() => state.selectedTab,async () => {if (state.selectedTab === "raw-sql") {state.isFetchingDDL = true;- const originTableList = await tableStore.getOrFetchTableListByDatabaseId(- database.id+ const originTableList = editorStore.originTableList.filter(+ (table) => table.databaseId === database.id);- const updatedTableList = (- await editorStore.getOrFetchTableListByDatabaseId(database.id)- ).filter((table) => !editorStore.droppedTableList.includes(table));+ const updatedTableList =+ await editorStore.getOrFetchTableListByDatabaseId(database.id);const diffTableListResult = diffTableList(originTableList,updatedTableList@@ -265,6 +259,10 @@ watch(});+const isDroppedTable = (table: Table) => {+ return table.status === "dropped";+};+const handleChangeTab = (tab: TabType) => {state.selectedTab = tab;};@@ -272,7 +270,7 @@ const handleChangeTab = (tab: TabType) => {const handleCreateNewTable = () => {state.tableNameModalContext = {databaseId: database.id,- table: undefined,+ tableName: undefined,};};@@ -281,15 +279,17 @@ const handleTableItemClick = (table: Table) => {id: generateUniqueTabId(),type: UIEditorTabType.TabForTable,databaseId: database.id,- tableId: table.id,- table: table,- tableCache: cloneDeep(table),+ tableName: table.newName,});};const handleDropTable = (table: Table) => {editorStore.dropTable(table);};++const handleRestoreTable = (table: Table) => {+ editorStore.restoreTable(table);+};</script><style scoped>diff --git a/frontend/src/components/UIEditor/Panels/TableEditor.vue b/frontend/src/components/UIEditor/Panels/TableEditor.vueindex 640d9e31a9..b81a9eb12f 100644--- a/frontend/src/components/UIEditor/Panels/TableEditor.vue+++ b/frontend/src/components/UIEditor/Panels/TableEditor.vue@@ -24,22 +24,22 @@</div><template v-if="state.selectedTab === 'column-list'">- <!-- column table --><div class="w-full py-2 flex flex-row justify-between items-center"><div><buttonclass="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="isDroppedTable"@click="handleAddColumn"><heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />{{ $t("ui-editor.actions.add-column") }}</button></div>- <div>+ <div class="w-auto flex flex-row justify-end items-center space-x-3"><button- v-if="table.id !== UNKNOWN_ID"+ v-if="state.tableCache.status !== 'created'"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="allowResetTable"+ :disabled="!allowResetTable"@click="handleDiscardChanges"><heroicons-solid:arrow-uturn-left@@ -49,13 +49,15 @@</button></div></div>++ <!-- column table --><divclass="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"><!-- column table header --><divclass="sticky top-0 z-10 grid grid-cols-[repeat(4,_minmax(0,_1fr))_112px_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"- :class="tableCache.columnList.length > 0 && 'border-b'"+ :class="state.tableCache.columnList.length > 0 && 'border-b'"><spanv-for="header in columnHeaderList"@@ -68,13 +70,18 @@<!-- column table body --><div class="w-full"><div- v-for="(column, index) in tableCache.columnList"- :key="`${index}-${column.id}`"+ v-for="(column, index) in state.tableCache.columnList"+ :key="`${index}-${column.oldName}`"class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_112px_32px] gr text-sm even:bg-gray-50"+ :class="+ isDroppedColumn(column) &&+ 'text-red-700 cursor-not-allowed !bg-red-50 opacity-70'+ "><div class="table-body-item-container"><input- v-model="column.name"+ v-model="column.newName"+ :disabled="disableAlterColumn(column)"placeholder="column name"class="column-field-input"type="text"@@ -85,12 +92,14 @@><inputv-model="column.type"+ :disabled="disableAlterColumn(column)"placeholder="column type"class="column-field-input !pr-8"type="text"/><NDropdowntrigger="click"+ :disabled="disableAlterColumn(column)":options="dataTypeOptions"@select="(dataType: string) => (column.type = dataType)">@@ -104,6 +113,7 @@<div class="table-body-item-container"><inputv-model="column.default"+ :disabled="disableAlterColumn(column)"placeholder="column default value"class="column-field-input"type="text"@@ -112,6 +122,7 @@<div class="table-body-item-container"><inputv-model="column.comment"+ :disabled="disableAlterColumn(column)"placeholder="comment"class="column-field-input"type="text"@@ -123,18 +134,34 @@<BBCheckboxclass="ml-3":value="column.nullable"+ :disabled="disableAlterColumn(column)"@toggle="(value) => (column.nullable = value)"/></div><div class="w-full flex justify-start items-center">- <n-tooltip trigger="hover">+ <n-tooltip v-if="!isDroppedColumn(column)" trigger="hover"><template #trigger>- <heroicons:trash- class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"- @click="handleRemoveColumn(column)"- />+ <button+ :disabled="isDroppedTable"+ class="text-gray-500 cursor-pointer hover:opacity-80"+ @click="handleDropColumn(column)"+ >+ <heroicons:trash class="w-4 h-auto" />+ </button></template>- <span>Drop Column</span>+ <span>{{ $t("ui-editor.actions.drop-column") }}</span>+ </n-tooltip>+ <n-tooltip v-else trigger="hover">+ <template #trigger>+ <button+ class="text-gray-500 cursor-pointer hover:opacity-80"+ :disabled="isDroppedTable"+ @click="handleRestoreColumn(column)"+ >+ <heroicons:arrow-uturn-left class="w-4 h-auto" />+ </button>+ </template>+ <span>{{ $t("ui-editor.actions.restore") }}</span></n-tooltip></div></div>@@ -167,16 +194,18 @@</template><script lang="ts" setup>-import { isEqual } from "lodash-es";+import { cloneDeep, isEqual } from "lodash-es";import { computed, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import { useDebounceFn } from "@vueuse/core";-import { useTableStore, useUIEditorStore } from "@/store/modules";-import { TableTabContext, Column, UNKNOWN_ID, DatabaseEdit } from "@/types";+import { useDatabaseStore, useUIEditorStore } from "@/store/modules";+import { TableTabContext, unknown } from "@/types";import { BBCheckbox, BBSpin } from "@/bbkit";import { getDataTypeSuggestionList } from "@/utils";import { diffTableList } from "@/utils/UIEditor/diffTable";import HighlightCodeBlock from "@/components/HighlightCodeBlock";+import { Column, DatabaseEdit, Table } from "@/types/UIEditor";+import { transformColumnDataToColumn } from "@/utils/UIEditor/transform";type TabType = "column-list" | "raw-sql";@@ -184,19 +213,27 @@ interface LocalState {selectedTab: TabType;isFetchingDDL: boolean;statement: string;+ tableCache: Table;}const { t } = useI18n();+const editorStore = useUIEditorStore();+const databaseStore = useDatabaseStore();+const currentTab = editorStore.currentTab as TableTabContext;const state = reactive<LocalState>({selectedTab: "column-list",isFetchingDDL: false,statement: "",+ tableCache: cloneDeep(editorStore.getTableWithTableTab(currentTab) as Table),+});++const table = computed(+ () => editorStore.getTableWithTableTab(currentTab) as Table+);++const isDroppedTable = computed(() => {+ return state.tableCache.status === "dropped";});-const editorStore = useUIEditorStore();-const tableStore = useTableStore();-const currentTab = editorStore.currentTab as TableTabContext;-const table = currentTab.table;-const tableCache = currentTab.tableCache;const columnHeaderList = computed(() => {return [@@ -224,58 +261,59 @@ const columnHeaderList = computed(() => {});const dataTypeOptions = computed(() => {- return getDataTypeSuggestionList(tableCache.database.instance.engine).map(- (dataType) => {- return {- label: dataType,- key: dataType,- };- }- );+ const database = databaseStore.getDatabaseById(state.tableCache.databaseId);+ return getDataTypeSuggestionList(database.instance.engine).map((dataType) => {+ return {+ label: dataType,+ key: dataType,+ };+ });});const allowResetTable = computed(() => {- const originTable = tableStore.getTableByDatabaseIdAndTableId(- currentTab.databaseId,- currentTab.tableId- );+ if (state.tableCache.status === "created") {+ return false;+ }- return isEqual(table, originTable);+ const originTable = editorStore.originTableList.find(+ (item) =>+ item.databaseId === state.tableCache.databaseId &&+ item.oldName === state.tableCache.oldName+ );+ return !isEqual(originTable, state.tableCache) || isDroppedTable;});-watch([tableCache], () => {- handleSaveChanges();+watch(+ () => state.tableCache,+ () => {+ handleSaveChanges();+ },+ {+ deep: true,+ }+);++watch([table.value], () => {+ state.tableCache.newName = table.value.newName;});watch(() => state.selectedTab,async () => {if (state.selectedTab === "raw-sql") {+ const originTable = editorStore.originTableList.find(+ (item) =>+ item.databaseId === state.tableCache.databaseId &&+ item.oldName === state.tableCache.oldName+ );+ const diffTableListResult = diffTableList(+ originTable ? [originTable] : [],+ [state.tableCache]+ );const databaseEdit: DatabaseEdit = {- databaseId: table.database.id,- createTableList: [],- alterTableList: [],- renameTableList: [],- dropTableList: [],+ databaseId: state.tableCache.databaseId,+ ...diffTableListResult,};- if (table.id === UNKNOWN_ID) {- const diffTableListResult = diffTableList([], [table]);- databaseEdit.createTableList = diffTableListResult.createTableList;- } else {- const originTable = tableStore.getTableByDatabaseIdAndTableId(- table.database.id,- table.id- );- const isDropped = editorStore.droppedTableList.includes(table);- if (isDropped) {- const diffTableListResult = diffTableList([originTable], []);- databaseEdit.dropTableList = diffTableListResult.dropTableList;- } else {- const diffTableListResult = diffTableList([originTable], [table]);- databaseEdit.alterTableList = diffTableListResult.alterTableList;- databaseEdit.renameTableList = diffTableListResult.renameTableList;- }- }state.isFetchingDDL = true;try {const statement = await editorStore.postDatabaseEdit(databaseEdit);@@ -288,32 +326,60 @@ watch(});+const isDroppedColumn = (column: Column): boolean => {+ return column.status === "dropped";+};++const disableAlterColumn = (column: Column): boolean => {+ return isDroppedTable.value || isDroppedColumn(column);+};+const handleChangeTab = (tab: TabType) => {state.selectedTab = tab;};const handleSaveChanges = useDebounceFn(async () => {- editorStore.saveTab(currentTab);+ const table = editorStore.getTableWithTableTab(currentTab) as Table;+ table.columnList = cloneDeep(state.tableCache.columnList);}, 500);const handleAddColumn = () => {- tableCache.columnList.push({- id: UNKNOWN_ID,- name: "",- type: "",- nullable: false,- comment: "",- } as Column);+ const column = transformColumnDataToColumn(unknown("COLUMN"));+ column.status = "created";+ state.tableCache.columnList.push(column);};-const handleRemoveColumn = (column: Column) => {- tableCache.columnList = tableCache.columnList.filter(- (item) => item !== column- );+const handleDropColumn = (column: Column) => {+ if (column.status === "created") {+ state.tableCache.columnList = state.tableCache.columnList.filter(+ (item) => item !== column+ );+ } else {+ column.status = "dropped";+ }+};++const handleRestoreColumn = (column: Column) => {+ if (column.status === "created") {+ return;+ }++ delete column.status;};const handleDiscardChanges = () => {- editorStore.discardTabChanges(currentTab);+ if (state.tableCache.status === "created") {+ return;+ }++ state.tableCache.newName = state.tableCache.oldName;+ state.tableCache.columnList = cloneDeep(state.tableCache.originColumnList);+ delete state.tableCache.status;++ const table = editorStore.getTableWithTableTab(currentTab) as Table;+ table.newName = table.oldName;+ table.columnList = cloneDeep(table.columnList);+ delete table.status;};</script>@@ -325,6 +391,6 @@ const handleDiscardChanges = () => {@apply w-full h-10 box-border p-px pr-2 relative;}.column-field-input {- @apply w-full pr-1 box-border border-transparent text-ellipsis rounded bg-transparent text-sm placeholder:italic placeholder:text-gray-400 focus:bg-white focus:text-black;+ @apply w-full pr-1 box-border border-transparent truncate select-none rounded bg-transparent text-sm placeholder:italic placeholder:text-gray-400 focus:bg-white focus:text-black;}</style>diff --git a/frontend/src/components/UIEditor/TabsContainer.vue b/frontend/src/components/UIEditor/TabsContainer.vueindex 3b089633af..fbcfe75527 100644--- a/frontend/src/components/UIEditor/TabsContainer.vue+++ b/frontend/src/components/UIEditor/TabsContainer.vue@@ -47,11 +47,10 @@ import { isEqual } from "lodash-es";import { NEllipsis } from "naive-ui";import { computed, nextTick, ref, watch } from "vue";import scrollIntoView from "scroll-into-view-if-needed";-import { useTableStore, useUIEditorStore } from "@/store";-import { TabContext, UIEditorTabType, UNKNOWN_ID } from "@/types";+import { useUIEditorStore } from "@/store";+import { TabContext, UIEditorTabType } from "@/types";const editorStore = useUIEditorStore();-const tableStore = useTableStore();const tabsContainerRef = ref();const tabList = computed(() => {return Array.from(editorStore.tabState.tabMap.values());@@ -78,18 +77,23 @@ watch(const getTabComputedClassList = (tab: TabContext) => {if (tab.type === UIEditorTabType.TabForTable) {- if (editorStore.droppedTableList.includes(tab.table)) {+ const table = editorStore.getTableWithTableTab(tab);+ if (!table) {+ return [];+ }++ if (table.status === "dropped") {return ["text-red-700", "line-through"];}- if (tab.table.id === UNKNOWN_ID) {+ if (table.status === "created") {return ["text-green-700"];}- const originTable = tableStore.getTableByDatabaseIdAndTableId(- tab.databaseId,- tab.tableId+ const originTable = editorStore.originTableList.find(+ (item) =>+ item.databaseId === table.databaseId && item.oldName === table.oldName);- if (!isEqual(tab.table, originTable)) {+ if (!isEqual(originTable, table)) {return ["text-yellow-700"];}}@@ -104,7 +108,7 @@ const getTabName = (tab: TabContext) => {);return `${database?.name || "unknown database"}`;} else if (tab.type === UIEditorTabType.TabForTable) {- return `${tab.table.name}`;+ return `${tab.tableName}`;} else {// Should never reach here.return "unknown structure";diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex e59225d6a4..6a936f1d30 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1408,6 +1408,7 @@"raw-sql": "SQL 语句","actions": {"create-table": "新建表",+ "rename": "重命名","drop-table": "删除表","drop": "删除","restore": "恢复",@@ -1435,7 +1436,7 @@"type": "类型","default": "默认值","comment": "注释",- "nullable": "是否可为空"+ "is-nullable": "是否可为空"},"nothing-changed": "无任何改动","message": {diff --git a/frontend/src/store/modules/UIEditor.ts b/frontend/src/store/modules/UIEditor.tsindex e1c60badd8..0d63508418 100644--- a/frontend/src/store/modules/UIEditor.ts+++ b/frontend/src/store/modules/UIEditor.ts@@ -3,18 +3,16 @@ import { defineStore } from "pinia";import { cloneDeep, isUndefined, uniqueId } from "lodash-es";import {DatabaseId,- TableId,- Table,Database,- unknown,- UNKNOWN_ID,TabContext,UIEditorState,UIEditorTabType,TableTabContext,DatabaseEdit,} from "@/types";+import { Table } from "@/types/UIEditor";import { useDatabaseStore, useTableStore } from "./";+import { transformTableDataToTable } from "@/utils/UIEditor/transform";export const generateUniqueTabId = () => {return uniqueId();@@ -27,8 +25,8 @@ const getDefaultUIEditorState = (): UIEditorState => {currentTabId: "",},databaseList: [],+ originTableList: [],tableList: [],- droppedTableList: [],};};@@ -62,7 +60,8 @@ export const useUIEditorStore = defineStore("UIEditor", {}if (item.type === UIEditorTabType.TabForTable &&- item.table === (tab as TableTabContext).table+ item.databaseId === tab.databaseId &&+ item.tableName === (tab as TableTabContext).tableName) {return true;}@@ -83,26 +82,8 @@ export const useUIEditorStore = defineStore("UIEditor", {if (tab.type === UIEditorTabType.TabForDatabase) {// Edit database metadata is not allowed.} else if (tab.type === UIEditorTabType.TabForTable) {- tab.table.name = tab.tableCache.name;- tab.table.columnList = cloneDeep(tab.tableCache.columnList);- }- },- discardTabChanges(tab: TabContext) {- if (tab.type === UIEditorTabType.TabForDatabase) {- // Edit database metadata is not allowed.- } else if (tab.type === UIEditorTabType.TabForTable) {- if (tab.tableId === UNKNOWN_ID) {- return;- }-- const originTable = useTableStore().getTableByDatabaseIdAndTableId(- tab.databaseId,- tab.tableId- );- tab.table.name = originTable.name;- tab.table.columnList = cloneDeep(originTable.columnList);- tab.tableCache.name = tab.table.name;- tab.tableCache.columnList = cloneDeep(tab.table.columnList);+ // tab.table.name = tab.tableCache.name;+ // tab.table.columnList = cloneDeep(tab.tableCache.columnList);}},setCurrentTab(tabId: string) {@@ -132,14 +113,30 @@ export const useUIEditorStore = defineStore("UIEditor", {}this.tabState.tabMap.delete(tabId);},- getTableTabByTable(table: Table): TableTabContext | undefined {- const tab = this.tabList.find((item) => {- if (item.type === UIEditorTabType.TabForTable && item.table === table) {+ findTab(databaseId: DatabaseId, tableName?: string) {+ let tabType = UIEditorTabType.TabForDatabase;+ if (tableName !== undefined) {+ tabType = UIEditorTabType.TabForTable;+ }++ const tab = this.tabList.find((tab) => {+ if (tab.type !== tabType || tab.databaseId !== databaseId) {+ return false;+ }++ if (tab.type === UIEditorTabType.TabForDatabase) {+ return true;+ } else if (+ tab.type === UIEditorTabType.TabForTable &&+ tab.tableName === tableName+ ) {return true;}+return false;});- return tab as TableTabContext;++ return tab;},async fetchDatabaseList(databaseIdList: DatabaseId[]) {const databaseList: Database[] = [];@@ -155,78 +152,46 @@ export const useUIEditorStore = defineStore("UIEditor", {async getOrFetchTableListByDatabaseId(databaseId: DatabaseId) {const tableList: Table[] = [];for (const table of this.tableList) {- if (table.database.id === databaseId) {+ if (table.databaseId === databaseId) {tableList.push(table);}}if (tableList.length === 0) {- const tableListData = cloneDeep(- await useTableStore().fetchTableListByDatabaseId(databaseId)+ const tableDataList = await useTableStore().fetchTableListByDatabaseId(+ databaseId+ );+ const transformTableList = tableDataList.map((tableData) =>+ transformTableDataToTable(tableData));- tableList.push(...tableListData);- this.tableList.push(...tableListData);++ tableList.push(...transformTableList);+ this.originTableList.push(...transformTableList);+ this.tableList.push(...cloneDeep(transformTableList));}return tableList;},- // createNewTable creates a temp table with databaseId.- // Its ID is UNKNOWN_ID and name should be an unique temp name.- createNewTable(databaseId: DatabaseId) {- const table = unknown("TABLE");- const databaseTableList = this.tableList.filter(- (table) => table.database.id === databaseId- );- const databaseTableNameList = databaseTableList.map(- (table) => table.name+ getTableWithTableTab(tab: TableTabContext) {+ return this.tableList.find(+ (table) =>+ table.databaseId === tab.databaseId && table.newName === tab.tableName);- let tableNameUniqueIndex =- databaseTableList.filter((table) => table.id === UNKNOWN_ID).length + 1;- let tableName = `untitled_table_${tableNameUniqueIndex}`;- while (databaseTableNameList.includes(tableName)) {- tableNameUniqueIndex++;- tableName = `untitled_table_${tableNameUniqueIndex}`;- }-- const database = useDatabaseStore().getDatabaseById(databaseId);- table.id = UNKNOWN_ID;- table.name = tableName;- table.database = database;- table.columnList = [];-- // generate a default column.- const unknownColumn = unknown("COLUMN");- unknownColumn.name = "id";- unknownColumn.type = "int";- unknownColumn.comment = "ID";- table.columnList.push(unknownColumn);-- this.tableList.push(table);- return table;},dropTable(table: Table) {const index = this.tableList.findIndex((item) => item === table);- if (table.id === UNKNOWN_ID) {+ if (table.status === "created") {this.tableList.splice(index, 1);// Close tab for new table.- const tab = this.tabList.find(- (tab) =>- tab.type === UIEditorTabType.TabForTable && tab.table === table- );+ const tab = this.findTab(table.databaseId, table.newName);if (tab) {this.closeTab(tab.id);}} else {- this.droppedTableList.push(table);+ table.status = "dropped";}},- restoreTable(databaseId: DatabaseId, tableId: TableId, tableName: string) {- const index = this.droppedTableList.findIndex(- (table) =>- table.database.id === databaseId &&- table.id === tableId &&- table.name === tableName- );- this.droppedTableList.splice(index, 1);+ restoreTable(table: Table) {+ delete table.status;},async postDatabaseEdit(databaseEdit: DatabaseEdit) {const stmt = (diff --git a/frontend/src/types/UIEditor.ts b/frontend/src/types/UIEditor.tsindex 986afd049e..c02256d653 100644--- a/frontend/src/types/UIEditor.ts+++ b/frontend/src/types/UIEditor.ts@@ -1,4 +1,40 @@-import { Database, DatabaseId, Table, TableId } from ".";+import { Database, DatabaseId, TableEngineType, TableType } from ".";++type TableOrColumnStatus = "created" | "dropped";++export interface Column {+ // Related fields+ databaseId: DatabaseId;++ // Domain specific fields+ oldName: string;+ newName: string;+ type: string;+ nullable: boolean;+ comment: string;+ default?: string;++ status?: TableOrColumnStatus;+}++export interface Table {+ // Related fields+ databaseId: DatabaseId;++ // Domain specific fields+ oldName: string;+ newName: string;+ type: TableType;+ engine: TableEngineType;+ collation: string;+ rowCount: number;+ dataSize: number;+ comment: string;+ columnList: Column[];+ originColumnList: Column[];++ status?: TableOrColumnStatus;+}export enum UIEditorTabType {TabForDatabase = "database",@@ -17,11 +53,7 @@ export interface TableTabContext {id: string;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;+ tableName: string;}export type TabContext = DatabaseTabContext | TableTabContext;@@ -34,8 +66,8 @@ export interface UIEditorState {currentTabId?: TabId;};databaseList: Database[];+ originTableList: Table[];tableList: Table[];- droppedTableList: Table[];}/**diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.tsindex b442cb77f3..f41db7f509 100644--- a/frontend/src/types/common.ts+++ b/frontend/src/types/common.ts@@ -551,10 +551,10 @@ const makeUnknown = (type: ResourceType) => {createdTs: 0,updaterId: UNKNOWN_PRINCIPAL.id,updatedTs: 0,- name: "<<Unknown table>>",+ name: "",position: 0,nullable: false,- type: "Unknown type",+ type: "",characterSet: "",collation: "",comment: "",diff --git a/frontend/src/utils/UIEditor/diffColumn.test.ts b/frontend/src/utils/UIEditor/diffColumn.test.tsindex 15d2c2c4a3..236e4ce861 100644--- a/frontend/src/utils/UIEditor/diffColumn.test.ts+++ b/frontend/src/utils/UIEditor/diffColumn.test.ts@@ -1,17 +1,16 @@import { expect, it } from "vitest";import {AddColumnContext,- Column,DropColumnContext,ChangeColumnContext,} from "@/types";-import { UNKNOWN_ID } from "@/types/const";+import { Column } from "@/types/UIEditor";import { diffColumnList } from "./diffColumn";it("diff add column list", () => {const testList: {originColumnList: Column[];- targetColumnList: Column[];+ columnList: Column[];wanted: {addColumnList: AddColumnContext[];changeColumnList: ChangeColumnContext[];@@ -20,16 +19,15 @@ it("diff add column list", () => {}[] = [{originColumnList: [],- targetColumnList: [+ columnList: [{- id: UNKNOWN_ID,- name: "id",+ oldName: "id",+ newName: "id",type: "int",- characterSet: "",- collation: "",comment: "",nullable: false,default: undefined,+ status: "created",} as Column,],wanted: {@@ -37,11 +35,11 @@ it("diff add column list", () => {{name: "id",type: "int",- characterSet: "",- collation: "",comment: "",nullable: false,default: undefined,+ characterSet: "",+ collation: "",},],changeColumnList: [],@@ -51,7 +49,7 @@ it("diff add column list", () => {];for (const test of testList) {- const result = diffColumnList(test.originColumnList, test.targetColumnList);+ const result = diffColumnList(test.originColumnList, test.columnList);expect(result).toStrictEqual(test.wanted);}});@@ -59,7 +57,7 @@ it("diff add column list", () => {it("diff modify column list", () => {const testList: {originColumnList: Column[];- targetColumnList: Column[];+ columnList: Column[];wanted: {addColumnList: AddColumnContext[];changeColumnList: ChangeColumnContext[];@@ -69,23 +67,19 @@ it("diff modify column list", () => {{originColumnList: [{- id: 1,- name: "id",+ oldName: "id",+ newName: "id",type: "int",- characterSet: "",- collation: "",comment: "",nullable: true,default: undefined,} as Column,],- targetColumnList: [+ columnList: [{- id: 1,- name: "id",+ oldName: "id",+ newName: "id",type: "varchar",- characterSet: "",- collation: "",comment: "",nullable: false,default: undefined,@@ -98,11 +92,11 @@ it("diff modify column list", () => {oldName: "id",newName: "id",type: "varchar",- characterSet: "",- collation: "",comment: "",nullable: false,default: undefined,+ characterSet: "",+ collation: "",},],dropColumnList: [],@@ -111,7 +105,7 @@ it("diff modify column list", () => {];for (const test of testList) {- const result = diffColumnList(test.originColumnList, test.targetColumnList);+ const result = diffColumnList(test.originColumnList, test.columnList);expect(result).toStrictEqual(test.wanted);}});@@ -119,7 +113,7 @@ it("diff modify column list", () => {it("diff drop column list", () => {const testList: {originColumnList: Column[];- targetColumnList: Column[];+ columnList: Column[];wanted: {addColumnList: AddColumnContext[];changeColumnList: ChangeColumnContext[];@@ -129,17 +123,25 @@ it("diff drop column list", () => {{originColumnList: [{- id: 1,- name: "id",+ oldName: "id",+ newName: "id",type: "int",- characterSet: "",- collation: "",comment: "",nullable: true,default: undefined,} as Column,],- targetColumnList: [],+ columnList: [+ {+ oldName: "id",+ newName: "id",+ type: "int",+ comment: "",+ nullable: true,+ default: undefined,+ status: "dropped",+ } as Column,+ ],wanted: {addColumnList: [],changeColumnList: [],@@ -153,7 +155,7 @@ it("diff drop column list", () => {];for (const test of testList) {- const result = diffColumnList(test.originColumnList, test.targetColumnList);+ const result = diffColumnList(test.originColumnList, test.columnList);expect(result).toStrictEqual(test.wanted);}});@@ -161,7 +163,7 @@ it("diff drop column list", () => {it("diff column list", () => {const testList: {originColumnList: Column[];- targetColumnList: Column[];+ columnList: Column[];wanted: {addColumnList: AddColumnContext[];changeColumnList: ChangeColumnContext[];@@ -171,66 +173,64 @@ it("diff column list", () => {{originColumnList: [{- id: 1,- name: "id",+ oldName: "id",+ newName: "id",type: "int",- characterSet: "",- collation: "",comment: "",nullable: true,default: undefined,} as Column,{- id: 2,- name: "name",+ oldName: "name",+ newName: "name",type: "varchar",- characterSet: "",- collation: "",comment: "",nullable: true,default: undefined,} as Column,{- id: 3,- name: "city",+ oldName: "city",+ newName: "city",type: "varchar",- characterSet: "",- collation: "",comment: "",nullable: true,default: undefined,} as Column,],- targetColumnList: [+ columnList: [{- id: 1,- name: "id",+ oldName: "id",+ newName: "id",type: "int",- characterSet: "",- collation: "",comment: "this is id",nullable: true,default: undefined,} as Column,{- id: 2,- name: "name",+ oldName: "name",+ newName: "name",type: "varchar",- characterSet: "",- collation: "",comment: "",nullable: false,default: "",} as Column,{- id: UNKNOWN_ID,- name: "birthday",+ oldName: "city",+ newName: "city",+ type: "varchar",+ comment: "",+ nullable: true,+ default: undefined,+ status: "dropped",+ } as Column,+ {+ oldName: "birthday",+ newName: "birthday",type: "varchar",- characterSet: "",- collation: "",comment: "",nullable: false,default: "",+ status: "created",} as Column,],wanted: {@@ -277,7 +277,7 @@ it("diff column list", () => {];for (const test of testList) {- const result = diffColumnList(test.originColumnList, test.targetColumnList);+ const result = diffColumnList(test.originColumnList, test.columnList);expect(result).toStrictEqual(test.wanted);}});diff --git a/frontend/src/utils/UIEditor/diffColumn.ts b/frontend/src/utils/UIEditor/diffColumn.tsindex 320ec4a84e..013b7fd6a2 100644--- a/frontend/src/utils/UIEditor/diffColumn.ts+++ b/frontend/src/utils/UIEditor/diffColumn.ts@@ -1,11 +1,10 @@-import { isEqual, isUndefined } from "lodash-es";+import { isEqual, isUndefined, omit } from "lodash-es";import type {AddColumnContext,- Column,DropColumnContext,ChangeColumnContext,} from "@/types";-import { UNKNOWN_ID } from "@/types/const";+import { Column } from "@/types/UIEditor";import {transformColumnToAddColumnContext,transformColumnToChangeColumnContext,@@ -15,29 +14,28 @@ import {// Including addColumnList, modifyColumnList and dropColumnList.export const diffColumnList = (originColumnList: Column[],- targetColumnList: Column[]+ columnList: Column[]) => {- const targetColumnIdList = targetColumnList.map((column) => column.id);-const addColumnContextList: AddColumnContext[] = [];- for (const column of targetColumnList) {- if (column.id === UNKNOWN_ID) {- addColumnContextList.push(transformColumnToAddColumnContext(column));- }+ const addedColumnList = columnList.filter(+ (column) => column.status === "created"+ );+ for (const column of addedColumnList) {+ addColumnContextList.push(transformColumnToAddColumnContext(column));}const changeColumnContextList: ChangeColumnContext[] = [];- for (const column of targetColumnList) {- if (column.id === UNKNOWN_ID) {- continue;- }+ const changedColumnList = columnList.filter(+ (column) => column.status === undefined+ );+ for (const column of changedColumnList) {const originColumn = originColumnList.find(- (originColumn) => originColumn.id === column.id+ (originColumn) => originColumn.oldName === column.oldName);if (isUndefined(originColumn)) {continue;}- if (!isEqual(originColumn, column)) {+ if (!isEqual(omit(originColumn, "status"), omit(column, "status"))) {changeColumnContextList.push(transformColumnToChangeColumnContext(originColumn, column));@@ -45,12 +43,13 @@ export const diffColumnList = (}const dropColumnContextList: DropColumnContext[] = [];- for (const column of originColumnList) {- if (!targetColumnIdList.includes(column.id)) {- dropColumnContextList.push({- name: column.name,- });- }+ const droppedColumnList = columnList.filter(+ (column) => column.status === "dropped"+ );+ for (const column of droppedColumnList) {+ dropColumnContextList.push({+ name: column.oldName,+ });}return {diff --git a/frontend/src/utils/UIEditor/diffTable.test.ts b/frontend/src/utils/UIEditor/diffTable.test.tsindex eca751f625..0dbcf6b37a 100644--- a/frontend/src/utils/UIEditor/diffTable.test.ts+++ b/frontend/src/utils/UIEditor/diffTable.test.ts@@ -1,11 +1,11 @@import { expect, it } from "vitest";import {- Table,DropTableContext,CreateTableContext,AlterTableContext,RenameTableContext,} from "@/types";+import { Table } from "@/types/UIEditor";import { UNKNOWN_ID } from "@/types/const";import { diffTableList } from "./diffTable";@@ -24,25 +24,27 @@ it("diff create table list", () => {originTableList: [],targetTableList: [{- id: UNKNOWN_ID,- name: "user",+ oldName: "user",+ newName: "user",type: "BASE TABLE",engine: "InnoDB",collation: "",comment: "",+ originColumnList: [],columnList: [{id: UNKNOWN_ID,- name: "id",+ oldName: "id",+ newName: "id",type: "int",- characterSet: "",- collation: "",comment: "",nullable: false,default: undefined,+ status: "created",},],- } as Table,+ status: "created",+ } as any as Table,],wanted: {createTableList: [@@ -93,16 +95,16 @@ it("diff alter table list", () => {{originTableList: [{- // Temp table id for testing.- id: 1,- name: "user",+ oldName: "user",+ newName: "user",type: "BASE TABLE",engine: "InnoDB",collation: "",comment: "",columnList: [{- name: "id",+ oldName: "id",+ newName: "id",type: "int",characterSet: "",collation: "",@@ -111,19 +113,20 @@ it("diff alter table list", () => {default: undefined,},],- } as Table,+ } as any as Table,],targetTableList: [{- id: 1,- name: "user",+ oldName: "user",+ newName: "user",type: "BASE TABLE",engine: "InnoDB",collation: "",comment: "",columnList: [{- name: "id",+ oldName: "id",+ newName: "id",type: "int",characterSet: "",collation: "",@@ -132,17 +135,18 @@ it("diff alter table list", () => {default: undefined,},{- id: UNKNOWN_ID,- name: "email",+ oldName: "email",+ newName: "email",type: "varchar",characterSet: "",collation: "",comment: "",nullable: false,default: undefined,+ status: "created",},],- } as Table,+ } as any as Table,],wanted: {createTableList: [],@@ -191,7 +195,30 @@ it("diff drop table list", () => {originTableList: [{id: 1,- name: "user",+ oldName: "user",+ newName: "user",+ type: "BASE TABLE",+ engine: "InnoDB",+ collation: "",+ comment: "",+ columnList: [+ {+ name: "id",+ type: "int",+ characterSet: "",+ collation: "",+ comment: "",+ nullable: false,+ default: undefined,+ },+ ],+ } as any as Table,+ ],+ targetTableList: [+ {+ id: 1,+ oldName: "user",+ newName: "user",type: "BASE TABLE",engine: "InnoDB",collation: "",@@ -207,9 +234,9 @@ it("diff drop table list", () => {default: undefined,},],- } as Table,+ status: "dropped",+ } as any as Table,],- targetTableList: [],wanted: {createTableList: [],alterTableList: [],diff --git a/frontend/src/utils/UIEditor/diffTable.ts b/frontend/src/utils/UIEditor/diffTable.tsindex 5709335cca..800960e7de 100644--- a/frontend/src/utils/UIEditor/diffTable.ts+++ b/frontend/src/utils/UIEditor/diffTable.ts@@ -1,49 +1,54 @@-import { isEqual, isUndefined } from "lodash-es";+import { isEqual, isUndefined, omit } from "lodash-es";import type {AlterTableContext,CreateTableContext,DropTableContext,RenameTableContext,- Table,} from "@/types";-import { UNKNOWN_ID } from "@/types/const";+import { Table } from "@/types/UIEditor";import { transformTableToCreateTableContext } from "./transform";import { diffColumnList } from "./diffColumn";// diffTableList gets the difference between table object list.// Including createTableList, alterTableList and dropTableList.-// * createTableList: the table with UNKNOWN_ID in targetTableList will be considered as new table;-// * alterTableList: table with the same id but not equal in originTableList and targetTableList;-// * dropTableList: table is in originTableList instead of targetTableList.-export const diffTableList = (- originTableList: Table[],- targetTableList: Table[]-) => {- const targetTableIdList = targetTableList.map((table) => table.id);-+// * createTableList: the table with UNKNOWN_ID in tableList will be considered as new table;+// * alterTableList: table with the same id but not equal in originTableList and tableList;+// * dropTableList: table is in originTableList instead of tableList.+export const diffTableList = (originTableList: Table[], tableList: Table[]) => {const createTableContextList: CreateTableContext[] = [];- for (const table of targetTableList) {- if (table.id === UNKNOWN_ID) {- const createTableContext = transformTableToCreateTableContext(table);- const diffColumnListResult = diffColumnList([], table.columnList);- createTableContext.addColumnList = diffColumnListResult.addColumnList;- createTableContextList.push(createTableContext);- }+ const createdTableList = tableList.filter(+ (table) => table.status === "created"+ );+ for (const table of createdTableList) {+ const createTableContext = transformTableToCreateTableContext(table);+ const diffColumnListResult = diffColumnList([], table.columnList);+ createTableContext.addColumnList = diffColumnListResult.addColumnList;+ createTableContextList.push(createTableContext);}const alterTableContextList: AlterTableContext[] = [];const renameTableContextList: RenameTableContext[] = [];- for (const table of targetTableList) {- if (table.id === UNKNOWN_ID) {- continue;- }+ const changedTableList = tableList.filter(+ (table) => table.status === undefined+ );+ for (const table of changedTableList) {const originTable = originTableList.find(- (originTable) => originTable.id === table.id+ (originTable) =>+ originTable.databaseId === table.databaseId &&+ originTable.oldName === table.oldName);if (isUndefined(originTable)) {continue;}- if (!isEqual(originTable, table)) {++ if (!isEqual(omit(originTable, "status"), omit(table, "status"))) {+ if (table.newName !== table.oldName) {+ renameTableContextList.push({+ oldName: table.oldName,+ newName: table.newName,+ });+ }+const columnListDiffResult = diffColumnList(originTable.columnList,table.columnList@@ -54,27 +59,21 @@ export const diffTableList = (columnListDiffResult.dropColumnList.length > 0) {alterTableContextList.push({- name: originTable.name,+ name: originTable.newName,...columnListDiffResult,});}-- if (originTable.name !== table.name) {- renameTableContextList.push({- oldName: originTable.name,- newName: table.name,- });- }}}const dropTableContextList: DropTableContext[] = [];- for (const table of originTableList) {- if (!targetTableIdList.includes(table.id)) {- dropTableContextList.push({- name: table.name,- });- }+ const droppedTableList = tableList.filter(+ (table) => table.status === "dropped"+ );+ for (const table of droppedTableList) {+ dropTableContextList.push({+ name: table.oldName,+ });}return {diff --git a/frontend/src/utils/UIEditor/transform.ts b/frontend/src/utils/UIEditor/transform.tsindex 59b3de6172..c6691b8dde 100644--- a/frontend/src/utils/UIEditor/transform.ts+++ b/frontend/src/utils/UIEditor/transform.ts@@ -1,23 +1,56 @@+import { cloneDeep, defaultTo } from "lodash-es";import {- Column,AddColumnContext,- Table,CreateTableContext,ChangeColumnContext,+ Column as ColumnData,+ Table as TableData,} from "@/types";-import { defaultTo } from "lodash-es";+import { Column, Table } from "@/types/UIEditor";++export const transformTableDataToTable = (tableData: TableData): Table => {+ const columnList = tableData.columnList.map((columnData) =>+ transformColumnDataToColumn(columnData)+ );++ return {+ databaseId: tableData.database.id,+ oldName: tableData.name,+ newName: tableData.name,+ type: tableData.type,+ engine: tableData.engine,+ collation: tableData.collation,+ rowCount: tableData.rowCount,+ dataSize: tableData.dataSize,+ comment: tableData.comment,+ originColumnList: columnList,+ columnList: cloneDeep(columnList),+ };+};++export const transformColumnDataToColumn = (columnData: ColumnData): Column => {+ return {+ databaseId: columnData.databaseId,+ oldName: columnData.name,+ newName: columnData.name,+ type: columnData.type,+ nullable: columnData.nullable,+ comment: columnData.comment,+ default: columnData.default,+ };+};export const transformColumnToAddColumnContext = (column: Column): AddColumnContext => {return {- name: defaultTo(column.name, ""),+ name: defaultTo(column.newName, ""),type: defaultTo(column.type, ""),- characterSet: defaultTo(column.characterSet, ""),- collation: defaultTo(column.collation, ""),comment: defaultTo(column.comment, ""),nullable: defaultTo(column.nullable, false),default: defaultTo(column.default, undefined),+ characterSet: "",+ collation: "",};};@@ -26,14 +59,14 @@ export const transformColumnToChangeColumnContext = (column: Column): ChangeColumnContext => {return {- oldName: defaultTo(originColumn.name, ""),- newName: defaultTo(column.name, ""),+ oldName: defaultTo(originColumn.oldName, ""),+ newName: defaultTo(column.newName, ""),type: defaultTo(column.type, ""),- characterSet: defaultTo(column.characterSet, ""),- collation: defaultTo(column.collation, ""),comment: defaultTo(column.comment, ""),nullable: defaultTo(column.nullable, false),default: defaultTo(column.default, undefined),+ characterSet: "",+ collation: "",};};@@ -41,14 +74,14 @@ export const transformTableToCreateTableContext = (table: Table): CreateTableContext => {return {- name: defaultTo(table.name, ""),+ name: defaultTo(table.newName, ""),type: defaultTo(table.type, ""),engine: defaultTo(table.engine, ""),- // As we don't have a CharacterSet field in table model,- // set it as an empty string for now.- characterSet: "",collation: defaultTo(table.collation, ""),comment: defaultTo(table.comment, ""),addColumnList: [],+ // As we don't have a CharacterSet field in table model,+ // set it as an empty string for now.+ characterSet: "",};};