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(schema-editor): support to edit foreign key (#4016)
boojack77add1b745c0
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex 2d0594f7f6..18ddc3b89a 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -1,7 +1,7 @@<template><BBModal:title="$t('database.alter-schema')"- class="schema-editor-modal-container !w-320 h-auto overflow-auto !max-w-[calc(100%-40px)] !max-h-[calc(100%-40px)]"+ class="schema-editor-modal-container !w-[96rem] h-auto overflow-auto !max-w-[calc(100%-40px)] !max-h-[calc(100%-40px)]":esc-closable="false"@close="dismissModal">@@ -527,7 +527,7 @@ watch(<style>.schema-editor-modal-container > .modal-container {- @apply w-full h-160 overflow-auto grid;+ @apply w-full h-[46rem] overflow-auto grid;grid-template-rows: min-content 1fr min-content;}</style>diff --git a/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue b/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vuenew file mode 100644index 0000000000..28935bfbc1--- /dev/null+++ b/frontend/src/components/SchemaEditor/Modals/EditColumnForeignKeyModal.vue@@ -0,0 +1,229 @@+<template>+ <BBModal+ :title="$t('schema-editor.edit-foreign-key')"+ class="shadow-inner outline outline-gray-200"+ @close="dismissModal"+ >+ <div class="w-72">+ <p class="mb-2">{{ $t("schema-editor.select-reference-table") }}</p>+ <BBSelect+ :selected-item="selectedTable"+ :item-list="tableList"+ :placeholder="$t('schema-editor.table.select')"+ :show-prefix-item="true"+ @select-item="(table: Table) => state.referencedTable = table.newName"+ >+ <template #menuItem="{ item: table }">+ {{ table.newName }}+ </template>+ </BBSelect>+ </div>+ <div class="w-72">+ <p class="mt-4 mb-2">{{ $t("schema-editor.select-reference-column") }}</p>+ <BBSelect+ :selected-item="selectedColumn"+ :item-list="columnList"+ :placeholder="$t('schema-editor.column.select')"+ :show-prefix-item="true"+ @select-item="(column: Column) => state.referencedColumn = column.newName"+ >+ <template #menuItem="{ item }">+ {{ item.newName }}+ </template>+ </BBSelect>+ </div>+ <div+ class="w-full flex items-center justify-between mt-6 space-x-2 pr-1 pb-1"+ >+ <div class="flex items-center justify-start">+ <button+ v-if="foreignKey !== undefined"+ type="button"+ class="btn-danger"+ @click="handleRemoveFKButtonClick"+ >+ Remove+ </button>+ </div>+ <div class="flex items-center justify-end space-x-2">+ <button type="button" class="btn-normal" @click="dismissModal">+ {{ $t("common.cancel") }}+ </button>+ <button class="btn-primary" @click="handleConfirmButtonClick">+ {{ $t("common.save") }}+ </button>+ </div>+ </div>+ </BBModal>+</template>++<script lang="ts" setup>+import { isUndefined } from "lodash-es";+import { computed, onMounted, PropType, reactive, ref, watch } from "vue";+import { DatabaseId, UNKNOWN_ID } from "@/types";+import { useSchemaEditorStore } from "@/store";+import { Column, Schema, Table } from "@/types/schemaEditor/atomType";++interface LocalState {+ referencedSchema?: string;+ referencedTable?: string;+ referencedColumn?: string;+}++const props = defineProps({+ databaseId: {+ type: Number as PropType<DatabaseId>,+ default: UNKNOWN_ID,+ },+ schemaName: {+ type: String as PropType<string>,+ default: "",+ },+ tableName: {+ type: String as PropType<string>,+ default: "",+ },+ column: {+ required: true,+ type: Object as PropType<Column>,+ },+});++const emit = defineEmits<{+ (event: "close"): void;+}>();++const editorStore = useSchemaEditorStore();+const state = reactive<LocalState>({+ referencedSchema: props.schemaName,+});++const schema = computed(() => {+ return editorStore.getSchema(props.databaseId, props.schemaName) as Schema;+});++const foreignKeyList = computed(() => {+ return schema.value?.foreignKeyList.filter(+ (pk) => pk.table === props.tableName+ );+});++const tableList = computed(() => {+ return (+ editorStore.getSchema(props.databaseId, state.referencedSchema || "")+ ?.tableList || []+ ).filter((table: Table) => table.newName !== props.tableName);+});++const selectedTable = computed(() => {+ return tableList.value.find(+ (table) => table.newName === state.referencedTable+ );+});++const columnList = computed(() => {+ return (+ tableList.value+ .find((item) => item.newName === state.referencedTable)+ ?.columnList.filter(+ (column) =>+ column.type.toUpperCase() === props.column.type.toUpperCase()+ ) || []+ );+});++const selectedColumn = computed(() => {+ return columnList.value.find(+ (column) => column.newName === state.referencedColumn+ );+});++const foreignKey = computed(() => {+ for (const fk of foreignKeyList.value) {+ const foundIndex = fk.columnList.findIndex(+ (columnRef) => columnRef.value === props.column+ );+ if (foundIndex > -1) {+ return fk;+ }+ }+ return undefined;+});++onMounted(() => {+ if (foreignKey.value) {+ const foundIndex = foreignKey.value.columnList.findIndex(+ (columnRef) => columnRef.value === props.column+ );+ if (foundIndex > -1) {+ state.referencedSchema = foreignKey.value.referencedSchema;+ state.referencedTable = foreignKey.value.referencedTable;+ state.referencedColumn = foreignKey.value.referencedColumns[foundIndex];+ }+ }+});++watch(+ () => state.referencedTable,+ () => {+ const found = columnList.value.find(+ (column) => column.newName === state.referencedColumn+ );+ if (!found) {+ state.referencedColumn = undefined;+ }+ }+);++const handleRemoveFKButtonClick = async () => {+ if (isUndefined(foreignKey.value)) {+ return;+ }++ const column = schema.value.tableList+ .find((table) => table.newName === props.tableName)+ ?.columnList.find((column) => column === props.column) as Column;+ const index = foreignKey.value.columnList.findIndex(+ (columnRef) => columnRef.value === column+ );+ if (index > -1) {+ foreignKey.value.referencedColumns.splice(index, 1);+ foreignKey.value.columnList.splice(index, 1);+ dismissModal();+ }+};++const handleConfirmButtonClick = async () => {+ if (+ isUndefined(state.referencedSchema) ||+ isUndefined(state.referencedTable) ||+ isUndefined(state.referencedColumn)+ ) {+ return;+ }++ const column = schema.value.tableList+ .find((table) => table.newName === props.tableName)+ ?.columnList.find((column) => column === props.column) as Column;++ if (isUndefined(foreignKey.value)) {+ const fk = {+ name: "",+ table: props.tableName,+ columnList: [ref(column)],+ referencedSchema: state.referencedSchema,+ referencedTable: state.referencedTable,+ referencedColumns: [state.referencedColumn],+ };+ schema.value.foreignKeyList.push(fk);+ } else {+ foreignKey.value.referencedColumns.push(state.referencedColumn);+ foreignKey.value.columnList.push(ref(column));+ }+ dismissModal();+};++const dismissModal = () => {+ emit("close");+};+</script>diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vueindex 1d53e0d0ff..4f083d79fa 100644--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue+++ b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue@@ -56,7 +56,7 @@><!-- column table header --><div- class="sticky top-0 z-10 grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_112px)_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400"+ class="sticky top-0 z-10 grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] w-full text-sm leading-6 select-none bg-gray-50 text-gray-400":class="table.columnList.length > 0 && 'border-b'"><span@@ -72,7 +72,7 @@<divv-for="(column, index) in table.columnList":key="`${index}-${column.oldName}`"- class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_112px)_32px] gr text-sm even:bg-gray-50"+ class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] gr text-sm even:bg-gray-50":class="isDroppedColumn(column) &&'text-red-700 cursor-not-allowed !bg-red-50 opacity-70'@@ -162,6 +162,27 @@@toggle="(value) => setColumnPrimaryKey(column, value)"/></div>+ <div+ class="table-body-item-container foreign-key-field flex justify-start items-center"+ >+ <span+ v-if="checkColumnHasForeignKey(column)"+ class="column-field-text !w-auto"+ >+ {{ getReferencedForeignKeyName(column) }}+ </span>+ <span+ v-else+ class="column-field-text italic text-gray-400 !w-auto"+ >EMPTY</span+ >+ <span+ class="foreign-key-edit-button hidden cursor-pointer hover:opacity-80"+ @click="handleEditColumnForeignKey(column)"+ >+ <heroicons:pencil-square class="w-4 h-auto text-gray-400" />+ </span>+ </div><div class="w-full flex justify-start items-center"><n-tooltip v-if="!isDroppedColumn(column)" trigger="hover"><template #trigger>@@ -215,10 +236,19 @@</template></div></div>++ <EditColumnForeignKeyModal+ v-if="state.showEditColumnForeignKeyModal && editForeignKeyColumn"+ :database-id="currentTab.databaseId"+ :schema-name="schema.name"+ :table-name="table.newName"+ :column="editForeignKeyColumn"+ @close="state.showEditColumnForeignKeyModal = false"+ /></template><script lang="ts" setup>-import { cloneDeep } from "lodash-es";+import { cloneDeep, isUndefined, flatten } from "lodash-es";import { computed, reactive, ref, watch } from "vue";import { useI18n } from "vue-i18n";import { useNotificationStore, useSchemaEditorStore } from "@/store/modules";@@ -231,12 +261,14 @@ import {Schema,convertColumnMetadataToColumn,PrimaryKey,+ ForeignKey,} from "@/types/schemaEditor/atomType";import { getDataTypeSuggestionList } from "@/utils";import { BBCheckbox, BBSpin } from "@/bbkit";import HighlightCodeBlock from "@/components/HighlightCodeBlock";import { isTableChanged } from "../utils/table";import { diffSchema } from "@/utils/schemaEditor/diffSchema";+import EditColumnForeignKeyModal from "../Modals/EditColumnForeignKeyModal.vue";type TabType = "column-list" | "raw-sql";@@ -244,6 +276,7 @@ interface LocalState {selectedTab: TabType;isFetchingDDL: boolean;statement: string;+ showEditColumnForeignKeyModal: boolean;}const { t } = useI18n();@@ -257,6 +290,7 @@ const state = reactive<LocalState>({selectedTab: "column-list",isFetchingDDL: false,statement: "",+ showEditColumnForeignKeyModal: false,});const table = ref(editorStore.getTableWithTableTab(currentTab) as Table);@@ -270,6 +304,13 @@ const primaryKey = computed(() => {(pk) => pk.table === currentTab.tableName) as PrimaryKey;});+const foreignKeyList = computed(() => {+ return schema.value.foreignKeyList.filter(+ (pk) => pk.table === currentTab.tableName+ ) as ForeignKey[];+});++const editForeignKeyColumn = ref<Column>();const isDroppedTable = computed(() => {return table.value.status === "dropped";@@ -315,12 +356,19 @@ const columnHeaderList = computed(() => {key: "primary",label: t("schema-editor.column.primary"),},+ {+ key: "foreign_key",+ label: "Foreign Key",+ },];});+const databaseEngine = computed(() => {+ return databaseSchema.database.instance.engine;+});+const dataTypeOptions = computed(() => {- const database = databaseSchema.database;- return getDataTypeSuggestionList(database.instance.engine).map((dataType) => {+ return getDataTypeSuggestionList(databaseEngine.value).map((dataType) => {return {label: dataType,key: dataType,@@ -394,6 +442,38 @@ const isColumnPrimaryKey = (column: Column): boolean => {return false;};+const checkColumnHasForeignKey = (column: Column): boolean => {+ const columnRefList = flatten(+ foreignKeyList.value.map((fk) => fk.columnList)+ );+ const find = columnRefList.find((columnRef) => columnRef.value === column);+ return find !== undefined;+};++const getReferencedForeignKeyName = (column: Column) => {+ if (!checkColumnHasForeignKey(column)) {+ return;+ }+ const fk = foreignKeyList.value.find(+ (fk) =>+ fk.columnList.find((columnRef) => columnRef.value === column) !==+ undefined+ );+ const index = fk?.columnList.findIndex(+ (columnRef) => columnRef.value === column+ );++ if (isUndefined(fk) || isUndefined(index) || index < 0) {+ return;+ }+ const referColumnName = fk.referencedColumns[index];+ if (databaseEngine.value === "MYSQL") {+ return `${fk.referencedTable}(${referColumnName})`;+ } else {+ return `${fk.referencedSchema}.${fk.referencedTable}(${referColumnName})`;+ }+};+const isDroppedColumn = (column: Column): boolean => {return column.status === "dropped";};@@ -434,11 +514,19 @@ const handleColumnDefaultFieldChange = (}};+const handleEditColumnForeignKey = (column: Column) => {+ editForeignKeyColumn.value = column;+ state.showEditColumnForeignKeyModal = true;+};+const handleDropColumn = (column: Column) => {if (column.status === "created") {table.value.columnList = table.value.columnList.filter((item) => item !== column);+ primaryKey.value.columnList = primaryKey.value.columnList.filter(+ (item) => item.value !== column+ );} else {column.status = "dropped";}@@ -485,6 +573,31 @@ const handleDiscardChanges = () => {primaryKey.value.columnList.push(ref(column));}}++ schema.value.foreignKeyList = schema.value.foreignKeyList.filter(+ (fk) => fk.table !== table.value.newName+ );+ const originForeignKeyList =+ originSchema?.foreignKeyList.filter(+ (fk) => fk.table === table.value.newName+ ) || [];+ for (const originForeignKey of originForeignKeyList) {+ const tempForeignKey: ForeignKey = {+ ...cloneDeep(originForeignKey),+ columnList: [],+ };+ const originColumnNameList = originForeignKey.columnList.map(+ (columnRef) => columnRef.value.oldName+ );+ for (const column of table.value.columnList) {+ if (originColumnNameList.includes(column.oldName)) {+ tempForeignKey.columnList.push(ref(column));+ }+ }+ if (tempForeignKey.columnList.length > 0) {+ schema.value.foreignKeyList.push(tempForeignKey);+ }+ }};</script>@@ -498,4 +611,10 @@ const handleDiscardChanges = () => {.column-field-input {@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;}+.column-field-text {+ @apply w-full pl-3 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;+}+.foreign-key-field:hover .foreign-key-edit-button {+ @apply block;+}</style>diff --git a/frontend/src/components/SchemaEditor/utils/table.ts b/frontend/src/components/SchemaEditor/utils/table.tsindex b847ed0ae5..fcb2696114 100644--- a/frontend/src/components/SchemaEditor/utils/table.ts+++ b/frontend/src/components/SchemaEditor/utils/table.ts@@ -1,6 +1,7 @@+import { isEqual } from "lodash-es";import { useSchemaEditorStore } from "@/store";import { DatabaseId } from "@/types";-import { isEqual } from "lodash-es";+import { ForeignKey } from "@/types/schemaEditor/atomType";export const isTableChanged = (databaseId: DatabaseId,@@ -15,16 +16,55 @@ export const isTableChanged = ((item) => item.oldName === table?.oldName);const originPrimaryKeyColumnList = originSchema?.primaryKeyList- .find((pk) => pk.table === tableName)+ .find((pk) => pk.table === table?.oldName)?.columnList.map((columnRef) => columnRef.value).sort();const primaryKeyColumnList = schema?.primaryKeyList.find((pk) => pk.table === tableName)?.columnList.map((columnRef) => columnRef.value).sort();+ const originForeignKeyList =+ originSchema?.foreignKeyList.filter((pk) => pk.table === table?.oldName) ||+ [];+ const foreignKeyList =+ schema?.foreignKeyList.filter((pk) => pk.table === tableName) || [];return (!isEqual(originTable, table) ||- !isEqual(originPrimaryKeyColumnList, primaryKeyColumnList)+ !isEqual(originPrimaryKeyColumnList, primaryKeyColumnList) ||+ !isEqualForeignKeyList(originForeignKeyList, foreignKeyList)+ );+};++export const isEqualForeignKeyList = (+ originForeignKeyList: ForeignKey[],+ foreignKeyList: ForeignKey[]+) => {+ if (originForeignKeyList.length !== foreignKeyList.length) {+ return false;+ }+ for (let i = 0; i < foreignKeyList.length; i++) {+ if (!isEqualForeignKey(originForeignKeyList[i], foreignKeyList[i])) {+ return false;+ }+ }+ return true;+};++export const isEqualForeignKey = (+ originForeignKey?: ForeignKey,+ foreignKey?: ForeignKey+) => {+ return isEqual(+ {+ ...originForeignKey,+ columnList: originForeignKey?.columnList.map(+ (columnRef) => columnRef.value+ ),+ },+ {+ ...foreignKey,+ columnList: foreignKey?.columnList.map((columnRef) => columnRef.value),+ });};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 93ce33604d..39f0721682 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1448,10 +1448,12 @@},"table-list": "Table List","table": {+ "select": "Select table","name": "Table Name"},"column-list": "Column List","column": {+ "select": "Select column","name": "Name","type": "Type","default": "Default",@@ -1471,7 +1473,10 @@"title": "Confirm to close","description": "Are you sure you want to close the panel? Your changes will be lost."},- "tenant-mode-tips": "Changes will be applied to all selected tenant databases after clicking \"Preview issue\"."+ "tenant-mode-tips": "Changes will be applied to all selected tenant databases after clicking \"Preview issue\".",+ "edit-foreign-key": "Edit foreign key",+ "select-reference-table": "Select a table to reference to",+ "select-reference-column": "Select a column to reference to"},"label": {"empty-label-value": "<Empty Value>",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 76afd88114..88a7c2d3ea 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1449,10 +1449,12 @@},"table-list": "表","table": {+ "select": "选择表","name": "表名"},"column-list": "列","column": {+ "select": "选择列","name": "名称","type": "类型","default": "默认值",@@ -1472,7 +1474,10 @@"title": "确定关闭?","description": "关闭后更改将会丢失。"},- "tenant-mode-tips": "点击“预览工单”后,当前更改将会应用于所有选定的租户数据库。"+ "tenant-mode-tips": "点击“预览工单”后,当前更改将会应用于所有选定的租户数据库。",+ "edit-foreign-key": "修改外键",+ "select-reference-table": "选择外键的表",+ "select-reference-column": "选择外键的列"},"label": {"empty-label-value": "<空值>",diff --git a/frontend/src/store/modules/schemaEditor.ts b/frontend/src/store/modules/schemaEditor.tsindex 14e30c6b41..1d78372447 100644--- a/frontend/src/store/modules/schemaEditor.ts+++ b/frontend/src/store/modules/schemaEditor.ts@@ -16,6 +16,7 @@ import {convertSchemaMetadataToSchema,Table,} from "@/types/schemaEditor/atomType";+import { SchemaMetadata } from "@/types/proto/store/database";import { useDatabaseStore, useDBSchemaStore } from ".";export const generateUniqueTabId = () => {@@ -172,6 +173,12 @@ export const useSchemaEditorStore = defineStore("SchemaEditor", {const schemaList = schemaMetadataList.map((schemaMetadata) =>convertSchemaMetadataToSchema(schemaMetadata));+ if (schemaList.length === 0 && database.instance.engine === "MYSQL") {+ schemaList.push(+ convertSchemaMetadataToSchema(SchemaMetadata.fromPartial({}))+ );+ }+this.databaseSchemaById.set(databaseId, {database: database,schemaList: schemaList,diff --git a/frontend/src/types/schemaEditor/atomType.ts b/frontend/src/types/schemaEditor/atomType.tsindex 86746f0999..0ecebc7b9d 100644--- a/frontend/src/types/schemaEditor/atomType.ts+++ b/frontend/src/types/schemaEditor/atomType.ts@@ -3,7 +3,7 @@ import {ColumnMetadata,SchemaMetadata,TableMetadata,-} from "../proto/database";+} from "../proto/store/database";type TableOrColumnStatus = "normal" | "created" | "dropped";@@ -36,9 +36,10 @@ export interface PrimaryKey {}export interface ForeignKey {- schema: string;+ // Should be an unique name.+ name: string;table: string;- columnList: string[];+ columnList: Ref<Column>[];referencedSchema: string;referencedTable: string;referencedColumns: string[];@@ -115,14 +116,31 @@ export const convertSchemaMetadataToSchema = (primaryKeyList.push(primaryKey);for (const foreignKeyMetadata of tableMetadata.foreignKeys) {- foreignKeyList.push({- schema: schemaMetadata.name,+ // TODO(steven): remove this after backend return unique fk.+ if (+ foreignKeyList.map((fk) => fk.name).includes(foreignKeyMetadata.name)+ ) {+ continue;+ }++ const fk: ForeignKey = {table: tableMetadata.name,- columnList: foreignKeyMetadata.columns,+ name: foreignKeyMetadata.name,+ columnList: [],referencedSchema: foreignKeyMetadata.referencedSchema,referencedTable: foreignKeyMetadata.referencedTable,referencedColumns: foreignKeyMetadata.referencedColumns,- });+ };++ for (const columnName of foreignKeyMetadata.columns) {+ const column = table.columnList.find(+ (column) => column.oldName === columnName+ );+ if (column) {+ fk.columnList.push(ref(column));+ }+ }+ foreignKeyList.push(fk);}}diff --git a/frontend/src/types/schemaEditor/index.ts b/frontend/src/types/schemaEditor/index.tsindex dde7711633..e51e9ce14d 100644--- a/frontend/src/types/schemaEditor/index.ts+++ b/frontend/src/types/schemaEditor/index.ts@@ -61,6 +61,7 @@ export interface CreateTableContext {addColumnList: AddColumnContext[];primaryKeyList: string[];+ addForeignKeyList: AddForeignKeyContext[];}export interface AlterTableContext {@@ -71,6 +72,8 @@ export interface AlterTableContext {dropColumnList: DropColumnContext[];dropPrimaryKey: boolean;primaryKeyList?: string[];+ dropForeignKeyList: string[];+ addForeignKeyList: AddForeignKeyContext[];}export interface RenameTableContext {@@ -107,6 +110,12 @@ export interface DropColumnContext {name: string;}+export interface AddForeignKeyContext {+ columnList: string[];+ referencedTable: string;+ referencedColumnList: string[];+}+/*** Type definition for DatabaseEdit validation API message.*/diff --git a/frontend/src/types/store.ts b/frontend/src/types/store.tsindex 1ea023ba41..a0ae535218 100644--- a/frontend/src/types/store.ts+++ b/frontend/src/types/store.ts@@ -48,7 +48,7 @@ import { Label } from "./label";import { ReleaseInfo } from "./actuator";import type { DebugLog } from "@/types/debug";import type { AuditLog } from "@/types/auditLog";-import { DatabaseMetadata } from "./proto/database";+import { DatabaseMetadata } from "./proto/store/database";export interface ActuatorState {serverInfo?: ServerInfo;diff --git a/frontend/src/utils/schemaEditor/diffSchema.ts b/frontend/src/utils/schemaEditor/diffSchema.tsindex 4572859f62..4731f47b88 100644--- a/frontend/src/utils/schemaEditor/diffSchema.ts+++ b/frontend/src/utils/schemaEditor/diffSchema.ts@@ -1,11 +1,15 @@+import {+ isEqualForeignKeyList,+ isEqualForeignKey,+} from "@/components/SchemaEditor/utils/table";import {AlterTableContext,CreateTableContext,DropTableContext,RenameTableContext,} from "@/types";-import { Schema } from "@/types/schemaEditor/atomType";-import { isEqual } from "lodash-es";+import { Column, ForeignKey, Schema } from "@/types/schemaEditor/atomType";+import { isEqual, isUndefined } from "lodash-es";import { diffColumnList } from "./diffColumn";import { transformTableToCreateTableContext } from "./transform";@@ -22,6 +26,20 @@ export const diffSchema = (originSchema: Schema, schema: Schema) => {schema.primaryKeyList.find((pk) => pk.table === createTableContext.name)?.columnList.map((columnRef) => columnRef.value.newName) ?? [];+ const foreignKeyList = schema.foreignKeyList.filter(+ (fk) => fk.table === createTableContext.name+ );+ for (const foreignKey of foreignKeyList) {+ if (foreignKey.columnList.length > 0) {+ createTableContext.addForeignKeyList.push({+ columnList: foreignKey.columnList.map(+ (columnRef) => columnRef.value.newName+ ),+ referencedTable: foreignKey.referencedTable,+ referencedColumnList: foreignKey.referencedColumns,+ });+ }+ }createTableContextList.push(createTableContext);}@@ -35,16 +53,25 @@ export const diffSchema = (originSchema: Schema, schema: Schema) => {(originTable) => originTable.oldName === table.oldName);const originPrimaryKey = originSchema?.primaryKeyList- .find((pk) => pk.table === table.newName)+ .find((pk) => pk.table === table.oldName)?.columnList.map((columnRef) => columnRef.value).sort();const primaryKey = schema?.primaryKeyList.find((pk) => pk.table === table.newName)- ?.columnList.map((columnRef) => columnRef.value)+ ?.columnList.filter((column) => column.value.status !== "dropped")+ .map((columnRef) => columnRef.value).sort();+ const originForeignKeyList = originSchema.foreignKeyList.filter(+ (fk) => fk.table === table.newName+ );+ const foreignKeyList = schema.foreignKeyList.filter(+ (fk) => fk.table === table.newName+ );+if (!isEqual(originTable, table) ||- !isEqual(originPrimaryKey, primaryKey)+ !isEqual(originPrimaryKey, primaryKey) ||+ !isEqualForeignKeyList(originForeignKeyList, foreignKeyList)) {if (table.newName !== table.oldName) {renameTableContextList.push({@@ -59,6 +86,7 @@ export const diffSchema = (originSchema: Schema, schema: Schema) => {);if (!isEqual(originPrimaryKey, primaryKey) ||+ !isEqualForeignKeyList(originForeignKeyList, foreignKeyList) ||columnListDiffResult.addColumnList.length > 0 ||columnListDiffResult.changeColumnList.length > 0 ||columnListDiffResult.dropColumnList.length > 0@@ -67,15 +95,19 @@ export const diffSchema = (originSchema: Schema, schema: Schema) => {name: table.newName,...columnListDiffResult,dropPrimaryKey: false,+ dropForeignKeyList: [],+ addForeignKeyList: [],};- if (!isEqual(originPrimaryKey, primaryKey)) {- if (originPrimaryKey?.length !== 0) {- alterTableContext.dropPrimaryKey = true;- }- alterTableContext.primaryKeyList = primaryKey?.map(- (column) => column.newName- );- }+ composePrimaryKeyWithAlterTableContext(+ originPrimaryKey || [],+ primaryKey || [],+ alterTableContext+ );+ composeForeignKeyWithAlterTableContext(+ originForeignKeyList || [],+ foreignKeyList || [],+ alterTableContext+ );alterTableContextList.push(alterTableContext);}}@@ -98,3 +130,50 @@ export const diffSchema = (originSchema: Schema, schema: Schema) => {dropTableList: dropTableContextList,};};++const composePrimaryKeyWithAlterTableContext = (+ originPrimaryKey: Column[],+ primaryKey: Column[],+ alterTableContext: AlterTableContext+) => {+ const droppedColumnNameList = alterTableContext.dropColumnList.map(+ (column) => column.name+ );+ const filterOriginPrimaryKey = originPrimaryKey.filter(+ (column) => !droppedColumnNameList.includes(column.oldName)+ );+ if (!isEqual(filterOriginPrimaryKey, primaryKey)) {+ if (originPrimaryKey.length !== 0) {+ alterTableContext.dropPrimaryKey = true;+ }+ alterTableContext.primaryKeyList = primaryKey.map(+ (column) => column.newName+ );+ }+};++const composeForeignKeyWithAlterTableContext = (+ originForeignKeyList: ForeignKey[],+ foreignKeyList: ForeignKey[],+ alterTableContext: AlterTableContext+) => {+ for (let i = 0; i < foreignKeyList.length; i++) {+ const originForeignKey = originForeignKeyList[i];+ const foreignKey = foreignKeyList[i];++ if (!isEqualForeignKey(originForeignKey, foreignKey)) {+ if (!isUndefined(originForeignKey)) {+ alterTableContext.dropForeignKeyList.push(originForeignKey.name);+ }+ if (foreignKey.columnList.length > 0) {+ alterTableContext.addForeignKeyList.push({+ columnList: foreignKey.columnList.map(+ (columnRef) => columnRef.value.newName+ ),+ referencedTable: foreignKey.referencedTable,+ referencedColumnList: foreignKey.referencedColumns,+ });+ }+ }+ }+};diff --git a/frontend/src/utils/schemaEditor/index.ts b/frontend/src/utils/schemaEditor/index.tsindex 319412710a..b4a080f6e7 100644--- a/frontend/src/utils/schemaEditor/index.ts+++ b/frontend/src/utils/schemaEditor/index.ts@@ -1,9 +1,13 @@import { Database, EngineType } from "@/types";+import { isDev } from "../util";// Only allow using Schema Editor with MySQL.export const allowUsingSchemaEditor = (databaseList: Database[]): boolean => {return databaseList.every((db) => {- return db.instance.engine === "MYSQL";+ return (+ db.instance.engine === "MYSQL" ||+ (isDev() && db.instance.engine === "POSTGRES")+ );});};diff --git a/frontend/src/utils/schemaEditor/transform.ts b/frontend/src/utils/schemaEditor/transform.tsindex b840059ec3..c408837ff5 100644--- a/frontend/src/utils/schemaEditor/transform.ts+++ b/frontend/src/utils/schemaEditor/transform.ts@@ -46,6 +46,7 @@ export const transformTableToCreateTableContext = (comment: defaultTo(table.comment, ""),addColumnList: [],primaryKeyList: [],+ addForeignKeyList: [],// As we don't have a CharacterSet field in table model,// set it as an empty string for now.characterSet: "",