Skip to content

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

feat: edit primary key in schema editor (#3996)

boojack152cbad233df
diff --git a/api/database.go b/api/database.go
index bdca86950c..bf105313ef 100644
--- a/api/database.go
+++ b/api/database.go
@@ -158,7 +158,9 @@ type AlterTableContext struct {
AddColumnList []*AddColumnContext `json:"addColumnList"`
ChangeColumnList []*ChangeColumnContext `json:"changeColumnList"`
DropColumnList []*DropColumnContext `json:"dropColumnList"`
- PrimaryKeyList *[]string `json:"primaryKeyList"`
+ // TODO(steven): diff schemas in backend, so we don't need this flag.
+ DropPrimaryKey bool `json:"dropPrimaryKey"`
+ PrimaryKeyList *[]string `json:"primaryKeyList"`
}
// RenameTableContext is the edit database context to rename a table.
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
index 2600bc3cc2..2d0594f7f6 100644
--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue
@@ -145,7 +145,7 @@ import {
useProjectStore,
useSchemaEditorStore,
} from "@/store";
-import { diffTableList } from "@/utils/schemaEditor/diffTable";
+import { diffSchema } from "@/utils/schemaEditor/diffSchema";
import { validateDatabaseEdit } from "@/utils/schemaEditor/validate";
import BBBetaBadge from "@/bbkit/BBBetaBadge.vue";
import SchemaEditor from "@/components/SchemaEditor/SchemaEditor.vue";
@@ -291,23 +291,25 @@ const getDatabaseEditListWithSchemaEditor = () => {
continue;
}
- const originTableList = databaseSchema.originSchemaList
- .map((schema) => schema.tableList)
- .flat();
- const tableList = databaseSchema.schemaList
- .map((schema) => schema.tableList)
- .flat();
- const diffTableListResult = diffTableList(originTableList, tableList);
- if (
- diffTableListResult.createTableList.length > 0 ||
- diffTableListResult.alterTableList.length > 0 ||
- diffTableListResult.renameTableList.length > 0 ||
- diffTableListResult.dropTableList.length > 0
- ) {
- databaseEditList.push({
- databaseId: database.id,
- ...diffTableListResult,
- });
+ for (const schema of databaseSchema.schemaList) {
+ const originSchema = databaseSchema.originSchemaList.find(
+ (schema) => schema.name === schema.name
+ );
+ if (!originSchema) {
+ continue;
+ }
+ const diffSchemaResult = diffSchema(originSchema, schema);
+ if (
+ diffSchemaResult.createTableList.length > 0 ||
+ diffSchemaResult.alterTableList.length > 0 ||
+ diffSchemaResult.renameTableList.length > 0 ||
+ diffSchemaResult.dropTableList.length > 0
+ ) {
+ databaseEditList.push({
+ databaseId: database.id,
+ ...diffSchemaResult,
+ });
+ }
}
}
return databaseEditList;
diff --git a/frontend/src/components/SchemaEditor/DatabaseTree.vue b/frontend/src/components/SchemaEditor/DatabaseTree.vue
index 0b1491d8ca..6c1aef3b11 100644
--- a/frontend/src/components/SchemaEditor/DatabaseTree.vue
+++ b/frontend/src/components/SchemaEditor/DatabaseTree.vue
@@ -48,7 +48,7 @@
</template>
<script lang="ts" setup>
-import { escape, isEqual, isUndefined } from "lodash-es";
+import { escape, 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";
@@ -66,6 +66,7 @@ import TableNameModal from "./Modals/TableNameModal.vue";
import DatabaseIcon from "~icons/heroicons-outline/database";
import TableIcon from "~icons/heroicons-outline/table";
import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";
+import { isTableChanged } from "./utils/table";
interface BaseTreeNode extends TreeOption {
key: string;
@@ -457,12 +458,13 @@ const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {
} else if (table.status === "dropped") {
additionalClassList.push("text-red-700 line-through");
} else {
- const originTable = editorStore.getOriginTable(
- treeNode.databaseId,
- treeNode.schemaName,
- treeNode.tableName
- );
- if (!isEqual(originTable, table)) {
+ if (
+ isTableChanged(
+ treeNode.databaseId,
+ treeNode.schemaName,
+ treeNode.tableName
+ )
+ ) {
additionalClassList.push("text-yellow-700");
}
}
diff --git a/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue b/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue
index 960d84804f..49b0584ed4 100644
--- a/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue
+++ b/frontend/src/components/SchemaEditor/Modals/TableNameModal.vue
@@ -43,6 +43,7 @@ import { ColumnMetadata, TableMetadata } from "@/types/proto/database";
import {
convertColumnMetadataToColumn,
convertTableMetadataToTable,
+ Schema,
} from "@/types/schemaEditor/atomType";
const tableNameFieldRegexp = /^\S+$/;
@@ -96,12 +97,10 @@ const handleConfirmButtonClick = async () => {
}
const databaseId = props.databaseId;
- const tableList =
- editorStore.databaseSchemaById
- .get(databaseId)
- ?.schemaList.find((schema) => schema.name === props.schemaName)
- ?.tableList ?? [];
- const tableNameList = tableList.map((table) => table.newName);
+ const schema = editorStore.databaseSchemaById
+ .get(databaseId)
+ ?.schemaList.find((schema) => schema.name === props.schemaName) as Schema;
+ const tableNameList = schema.tableList.map((table) => table.newName);
if (tableNameList.includes(state.tableName)) {
notificationStore.pushNotification({
module: "bytebase",
@@ -127,7 +126,11 @@ const handleConfirmButtonClick = async () => {
column.status = "created";
table.columnList.push(column);
- tableList.push(table);
+ schema.tableList.push(table);
+ schema.primaryKeyList.push({
+ table: table.newName,
+ columnList: [],
+ });
editorStore.addTab({
id: generateUniqueTabId(),
type: SchemaEditorTabType.TabForTable,
@@ -143,14 +146,23 @@ const handleConfirmButtonClick = async () => {
props.tableName ?? ""
);
if (table) {
+ table.newName = state.tableName;
+
+ // TODO(steven): use reactive Ref.
+ // Update reference objects.
const tab = editorStore.findTab(
databaseId,
table.newName
) as TableTabContext;
- table.newName = state.tableName;
if (tab) {
tab.tableName = table.newName;
}
+ const primaryKey = schema.primaryKeyList.find(
+ (pk) => pk.table === props.tableName
+ );
+ if (primaryKey) {
+ primaryKey.table = table.newName;
+ }
}
dismissModal();
}
diff --git a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue
index 838ede90d2..b8f4606f58 100644
--- a/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue
+++ b/frontend/src/components/SchemaEditor/Panels/DatabaseEditor.vue
@@ -173,12 +173,13 @@ import {
DatabaseTabContext,
DatabaseSchema,
SchemaEditorTabType,
+ DatabaseEdit,
} from "@/types";
import { Table } from "@/types/schemaEditor/atomType";
import { bytesToString } from "@/utils";
+import { diffSchema } from "@/utils/schemaEditor/diffSchema";
import HighlightCodeBlock from "@/components/HighlightCodeBlock";
import TableNameModal from "../Modals/TableNameModal.vue";
-import { diffTableList } from "@/utils/schemaEditor/diffTable";
import SchemaDiagram from "@/components/SchemaDiagram";
type TabType = "table-list" | "schema-diagram" | "raw-sql";
@@ -252,42 +253,49 @@ watch(
async () => {
if (state.selectedTab === "raw-sql") {
state.isFetchingDDL = true;
- const originTableList = databaseSchema.originSchemaList
- .map((schema) => schema.tableList)
- .flat();
- const updatedTableList = schemaList
- .map((schema) => schema.tableList)
- .flat();
- const diffTableListResult = diffTableList(
- originTableList,
- updatedTableList
- );
- if (
- diffTableListResult.createTableList.length > 0 ||
- diffTableListResult.alterTableList.length > 0 ||
- diffTableListResult.renameTableList.length > 0 ||
- diffTableListResult.dropTableList.length > 0
- ) {
- const databaseEdit = {
- databaseId: database.id,
- ...diffTableListResult,
- };
- const databaseEditResult = await editorStore.postDatabaseEdit(
- databaseEdit
+ const databaseEditList: DatabaseEdit[] = [];
+ for (const schema of databaseSchema.schemaList) {
+ const originSchema = databaseSchema.originSchemaList.find(
+ (schema) => schema.name === schema.name
);
- if (databaseEditResult.validateResultList.length > 0) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Invalid request",
- description: databaseEditResult.validateResultList
- .map((result) => result.message)
- .join("\n"),
+ if (!originSchema) {
+ continue;
+ }
+ const diffSchemaResult = diffSchema(originSchema, schema);
+ if (
+ diffSchemaResult.createTableList.length > 0 ||
+ diffSchemaResult.alterTableList.length > 0 ||
+ diffSchemaResult.renameTableList.length > 0 ||
+ diffSchemaResult.dropTableList.length > 0
+ ) {
+ databaseEditList.push({
+ databaseId: database.id,
+ ...diffSchemaResult,
});
- state.statement = "";
- return;
}
- state.statement = databaseEditResult.statement;
+ }
+
+ if (databaseEditList.length > 0) {
+ const statementList: string[] = [];
+ for (const databaseEdit of databaseEditList) {
+ const databaseEditResult = await editorStore.postDatabaseEdit(
+ databaseEdit
+ );
+ if (databaseEditResult.validateResultList.length > 0) {
+ notificationStore.pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Invalid request",
+ description: databaseEditResult.validateResultList
+ .map((result) => result.message)
+ .join("\n"),
+ });
+ state.statement = "";
+ return;
+ }
+ statementList.push(databaseEditResult.statement);
+ }
+ state.statement = statementList.join("\n");
}
state.isFetchingDDL = false;
}
diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
index 03630e97ad..50c9983c62 100644
--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
+++ b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
@@ -37,7 +37,7 @@
</div>
<div class="w-auto flex flex-row justify-end items-center space-x-3">
<button
- v-if="state.tableCache.status !== 'created'"
+ v-if="table.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"
@click="handleDiscardChanges"
@@ -56,8 +56,8 @@
>
<!-- column table header -->
<div
- class="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="state.tableCache.columnList.length > 0 && 'border-b'"
+ 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="table.columnList.length > 0 && 'border-b'"
>
<span
v-for="header in columnHeaderList"
@@ -70,9 +70,9 @@
<!-- column table body -->
<div class="w-full">
<div
- v-for="(column, index) in state.tableCache.columnList"
+ v-for="(column, index) in table.columnList"
:key="`${index}-${column.oldName}`"
- class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_112px_32px] gr text-sm even:bg-gray-50"
+ class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_112px)_32px] gr text-sm even:bg-gray-50"
:class="
isDroppedColumn(column) &&
'text-red-700 cursor-not-allowed !bg-red-50 opacity-70'
@@ -116,7 +116,7 @@
<input
v-model="column.default"
:disabled="disableAlterColumn(column)"
- :placeholder="column.default === undefined ? 'NULL' : ''"
+ :placeholder="column.default === undefined ? 'NULL' : 'EMPTY'"
class="column-field-input !pr-8"
type="text"
/>
@@ -152,6 +152,16 @@
@toggle="(value) => (column.nullable = !value)"
/>
</div>
+ <div
+ class="table-body-item-container flex justify-start items-center"
+ >
+ <BBCheckbox
+ class="ml-3"
+ :value="isColumnPrimaryKey(column)"
+ :disabled="disableAlterColumn(column)"
+ @toggle="(value) => setColumnPrimaryKey(column, value)"
+ />
+ </div>
<div class="w-full flex justify-start items-center">
<n-tooltip v-if="!isDroppedColumn(column)" trigger="hover">
<template #trigger>
@@ -208,10 +218,9 @@
</template>
<script lang="ts" setup>
-import { cloneDeep, isEqual } from "lodash-es";
-import { computed, reactive, watch } from "vue";
+import { cloneDeep } from "lodash-es";
+import { computed, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import { useDebounceFn } from "@vueuse/core";
import { useNotificationStore, useSchemaEditorStore } from "@/store/modules";
import { TableTabContext } from "@/types";
import { ColumnMetadata } from "@/types/proto/database";
@@ -219,12 +228,15 @@ import { DatabaseEdit } from "@/types/schemaEditor";
import {
Column,
Table,
+ Schema,
convertColumnMetadataToColumn,
+ PrimaryKey,
} from "@/types/schemaEditor/atomType";
import { getDataTypeSuggestionList } from "@/utils";
-import { diffTableList } from "@/utils/schemaEditor/diffTable";
import { BBCheckbox, BBSpin } from "@/bbkit";
import HighlightCodeBlock from "@/components/HighlightCodeBlock";
+import { isTableChanged } from "../utils/table";
+import { diffSchema } from "@/utils/schemaEditor/diffSchema";
type TabType = "column-list" | "raw-sql";
@@ -232,7 +244,6 @@ interface LocalState {
selectedTab: TabType;
isFetchingDDL: boolean;
statement: string;
- tableCache: Table;
}
const { t } = useI18n();
@@ -246,26 +257,36 @@ 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 table = ref(editorStore.getTableWithTableTab(currentTab) as Table);
+const schema = computed(() => {
+ return databaseSchema.schemaList.find(
+ (schema) => schema.name === currentTab.schemaName
+ ) as Schema;
+});
+const primaryKey = computed(() => {
+ return schema.value.primaryKeyList.find(
+ (pk) => pk.table === currentTab.tableName
+ ) as PrimaryKey;
+});
const isDroppedTable = computed(() => {
- return state.tableCache.status === "dropped";
+ return table.value.status === "dropped";
});
const allowResetTable = computed(() => {
- if (state.tableCache.status === "created") {
+ if (table.value.status === "created") {
return false;
}
- const originTable = databaseSchema.originSchemaList
- .find((schema) => schema.name === currentTab.schemaName)
- ?.tableList.find((table) => table.oldName === state.tableCache.oldName);
- return !isEqual(originTable, state.tableCache) || isDroppedTable.value;
+ return (
+ isTableChanged(
+ currentTab.databaseId,
+ currentTab.schemaName,
+ currentTab.tableName
+ ) || isDroppedTable.value
+ );
});
const columnHeaderList = computed(() => {
@@ -290,6 +311,10 @@ const columnHeaderList = computed(() => {
key: "nullable",
label: t("schema-editor.column.not-null"),
},
+ {
+ key: "primary",
+ label: t("schema-editor.column.primary"),
+ },
];
});
@@ -304,48 +329,39 @@ const dataTypeOptions = computed(() => {
});
const dataDefaultOptions = [
- // TODO(steven): support set default field with EMPTY.
- // {
- // label: "EMPTY",
- // key: "EMPTY",
- // },
{
label: "NULL",
key: "NULL",
},
-];
-
-watch(
- () => state.tableCache,
- () => {
- handleSaveChanges();
- },
{
- deep: true,
- }
-);
-
-watch([table.value], () => {
- state.tableCache.newName = table.value.newName;
- state.tableCache.status = table.value.status;
-});
+ label: "EMPTY",
+ key: "EMPTY",
+ },
+];
watch(
() => state.selectedTab,
async () => {
if (state.selectedTab === "raw-sql") {
- const originTable = editorStore.getOriginTable(
+ const originSchema = editorStore.getOriginSchema(
currentTab.databaseId,
- currentTab.schemaName,
- state.tableCache.oldName
- );
- const diffTableListResult = diffTableList(
- originTable ? [originTable] : [],
- [state.tableCache]
- );
+ currentTab.schemaName
+ ) as Schema;
+ const diffSchemaResult = diffSchema(originSchema, schema.value);
const databaseEdit: DatabaseEdit = {
databaseId: currentTab.databaseId,
- ...diffTableListResult,
+ createTableList: diffSchemaResult.createTableList.filter(
+ (context) => context.name === table.value.newName
+ ),
+ alterTableList: diffSchemaResult.alterTableList.filter(
+ (context) => context.name === table.value.newName
+ ),
+ renameTableList: diffSchemaResult.renameTableList.filter(
+ (context) => context.newName === table.value.newName
+ ),
+ dropTableList: diffSchemaResult.dropTableList.filter(
+ (context) => context.name === table.value.oldName
+ ),
};
state.isFetchingDDL = true;
const databaseEditResult = await editorStore.postDatabaseEdit(
@@ -369,6 +385,15 @@ watch(
}
);
+const isColumnPrimaryKey = (column: Column): boolean => {
+ for (const columnRef of primaryKey.value.columnList) {
+ if (columnRef.value === column) {
+ return true;
+ }
+ }
+ return false;
+};
+
const isDroppedColumn = (column: Column): boolean => {
return column.status === "dropped";
};
@@ -377,19 +402,25 @@ const disableAlterColumn = (column: Column): boolean => {
return isDroppedTable.value || isDroppedColumn(column);
};
+const setColumnPrimaryKey = (column: Column, isPrimaryKey: boolean) => {
+ if (isPrimaryKey) {
+ primaryKey.value?.columnList.push(ref(column));
+ } else {
+ const index = primaryKey.value?.columnList.findIndex(
+ (columnRef) => columnRef.value === column
+ );
+ primaryKey.value?.columnList.splice(index, 1);
+ }
+};
+
const handleChangeTab = (tab: TabType) => {
state.selectedTab = tab;
};
-const handleSaveChanges = useDebounceFn(async () => {
- const table = editorStore.getTableWithTableTab(currentTab) as Table;
- table.columnList = cloneDeep(state.tableCache.columnList);
-}, 500);
-
const handleAddColumn = () => {
const column = convertColumnMetadataToColumn(ColumnMetadata.fromPartial({}));
column.status = "created";
- state.tableCache.columnList.push(column);
+ table.value.columnList.push(column);
};
const handleColumnDefaultFieldChange = (
@@ -398,12 +429,14 @@ const handleColumnDefaultFieldChange = (
) => {
if (defaultString === "NULL") {
column.default = undefined;
+ } else if (defaultString === "EMPTY") {
+ column.default = "";
}
};
const handleDropColumn = (column: Column) => {
if (column.status === "created") {
- state.tableCache.columnList = state.tableCache.columnList.filter(
+ table.value.columnList = table.value.columnList.filter(
(item) => item !== column
);
} else {
@@ -420,24 +453,38 @@ const handleRestoreColumn = (column: Column) => {
};
const handleDiscardChanges = () => {
- if (state.tableCache.status === "created") {
+ if (table.value.status === "created") {
return;
}
+ const originSchema = editorStore.getOriginSchema(
+ currentTab.databaseId,
+ currentTab.schemaName
+ );
const originTable = editorStore.getOriginTable(
currentTab.databaseId,
currentTab.schemaName,
- state.tableCache.oldName
+ table.value.oldName
);
- state.tableCache.newName = state.tableCache.oldName;
- state.tableCache.columnList = cloneDeep(originTable?.columnList ?? []);
- state.tableCache.status = "normal";
+ table.value.newName = table.value.oldName;
+ table.value.columnList = cloneDeep(originTable?.columnList ?? []);
+ table.value.status = "normal";
- const table = editorStore.getTableWithTableTab(currentTab) as Table;
- table.newName = table.oldName;
- table.columnList = cloneDeep(table.columnList);
- table.status = "normal";
+ // TODO(steven): use reactive Ref.
+ // Update reference objects.
+ currentTab.tableName = table.value.newName;
+ primaryKey.value.table = table.value.newName;
+ primaryKey.value.columnList = [];
+ const primaryKeyColumnNameList = (
+ originSchema?.primaryKeyList.find((pk) => pk.table === table.value.oldName)
+ ?.columnList || []
+ ).map((columnRef) => columnRef.value.oldName);
+ for (const column of table.value.columnList) {
+ if (primaryKeyColumnNameList.includes(column.oldName)) {
+ primaryKey.value.columnList.push(ref(column));
+ }
+ }
};
</script>
diff --git a/frontend/src/components/SchemaEditor/TabsContainer.vue b/frontend/src/components/SchemaEditor/TabsContainer.vue
index bc5733bd67..7d19f2146f 100644
--- a/frontend/src/components/SchemaEditor/TabsContainer.vue
+++ b/frontend/src/components/SchemaEditor/TabsContainer.vue
@@ -43,12 +43,12 @@
</template>
<script lang="ts" setup>
-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 { useSchemaEditorStore } from "@/store";
import { TabContext, SchemaEditorTabType } from "@/types";
+import { isTableChanged } from "./utils/table";
const editorStore = useSchemaEditorStore();
const tabsContainerRef = ref();
@@ -89,12 +89,7 @@ const getTabComputedClassList = (tab: TabContext) => {
return ["text-green-700"];
}
- const originTable = editorStore.getOriginTable(
- tab.databaseId,
- tab.schemaName,
- tab.tableName
- );
- if (!isEqual(originTable, table)) {
+ if (isTableChanged(tab.databaseId, tab.schemaName, tab.tableName)) {
return ["text-yellow-700"];
}
}
diff --git a/frontend/src/components/SchemaEditor/utils/table.ts b/frontend/src/components/SchemaEditor/utils/table.ts
new file mode 100644
index 0000000000..b847ed0ae5
--- /dev/null
+++ b/frontend/src/components/SchemaEditor/utils/table.ts
@@ -0,0 +1,30 @@
+import { useSchemaEditorStore } from "@/store";
+import { DatabaseId } from "@/types";
+import { isEqual } from "lodash-es";
+
+export const isTableChanged = (
+ databaseId: DatabaseId,
+ schemaName: string,
+ tableName: string
+): boolean => {
+ const editorStore = useSchemaEditorStore();
+ const originSchema = editorStore.getOriginSchema(databaseId, schemaName);
+ const schema = editorStore.getSchema(databaseId, schemaName);
+ const table = schema?.tableList.find((table) => table.newName === tableName);
+ const originTable = originSchema?.tableList.find(
+ (item) => item.oldName === table?.oldName
+ );
+ const originPrimaryKeyColumnList = originSchema?.primaryKeyList
+ .find((pk) => pk.table === tableName)
+ ?.columnList.map((columnRef) => columnRef.value)
+ .sort();
+ const primaryKeyColumnList = schema?.primaryKeyList
+ .find((pk) => pk.table === tableName)
+ ?.columnList.map((columnRef) => columnRef.value)
+ .sort();
+
+ return (
+ !isEqual(originTable, table) ||
+ !isEqual(originPrimaryKeyColumnList, primaryKeyColumnList)
+ );
+};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 0f613e0b24..93ce33604d 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1456,7 +1456,8 @@
"type": "Type",
"default": "Default",
"comment": "Comment",
- "not-null": "Not Null"
+ "not-null": "Not Null",
+ "primary": "Primary"
},
"nothing-changed": "Nothing changed",
"message": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index e291e106c2..76afd88114 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1457,7 +1457,8 @@
"type": "类型",
"default": "默认值",
"comment": "注释",
- "not-null": "不可为空"
+ "not-null": "不可为空",
+ "primary": "主键"
},
"nothing-changed": "无任何改动",
"message": {
diff --git a/frontend/src/store/modules/schemaEditor.ts b/frontend/src/store/modules/schemaEditor.ts
index 8498dd80de..14e30c6b41 100644
--- a/frontend/src/store/modules/schemaEditor.ts
+++ b/frontend/src/store/modules/schemaEditor.ts
@@ -181,6 +181,16 @@ export const useSchemaEditorStore = defineStore("SchemaEditor", {
return this.databaseSchemaById.get(databaseId)!.schemaList;
},
+ getSchema(databaseId: DatabaseId, schemaName: string) {
+ return this.databaseSchemaById
+ .get(databaseId)
+ ?.schemaList.find((schema) => schema.name === schemaName);
+ },
+ getOriginSchema(databaseId: DatabaseId, schemaName: string) {
+ return this.databaseSchemaById
+ .get(databaseId)
+ ?.originSchemaList.find((schema) => schema.name === schemaName);
+ },
getTable(databaseId: DatabaseId, schemaName: string, tableName: string) {
return this.databaseSchemaById
.get(databaseId)
diff --git a/frontend/src/types/schemaEditor/atomType.ts b/frontend/src/types/schemaEditor/atomType.ts
index 4e7bd919bb..86746f0999 100644
--- a/frontend/src/types/schemaEditor/atomType.ts
+++ b/frontend/src/types/schemaEditor/atomType.ts
@@ -1,3 +1,4 @@
+import { ref, Ref } from "vue";
import {
ColumnMetadata,
SchemaMetadata,
@@ -29,9 +30,9 @@ export interface Table {
}
export interface PrimaryKey {
- schema: string;
table: string;
- columnList: string[];
+ // column is a ref to Column.
+ columnList: Ref<Column>[];
}
export interface ForeignKey {
@@ -91,17 +92,27 @@ export const convertSchemaMetadataToSchema = (
const foreignKeyList: ForeignKey[] = [];
for (const tableMetadata of schemaMetadata.tables) {
- tableList.push(convertTableMetadataToTable(tableMetadata));
+ const table = convertTableMetadataToTable(tableMetadata);
+ tableList.push(table);
+ const primaryKey: PrimaryKey = {
+ table: tableMetadata.name,
+ columnList: [],
+ };
for (const indexMetadata of tableMetadata.indexes) {
if (indexMetadata.primary === true) {
- primaryKeyList.push({
- schema: schemaMetadata.name,
- table: tableMetadata.name,
- columnList: indexMetadata.expressions,
- });
+ for (const columnName of indexMetadata.expressions) {
+ const column = table.columnList.find(
+ (column) => column.oldName === columnName
+ );
+ if (column) {
+ primaryKey.columnList.push(ref(column));
+ }
+ }
+ break;
}
}
+ primaryKeyList.push(primaryKey);
for (const foreignKeyMetadata of tableMetadata.foreignKeys) {
foreignKeyList.push({
diff --git a/frontend/src/types/schemaEditor/index.ts b/frontend/src/types/schemaEditor/index.ts
index e94db8a2c5..dde7711633 100644
--- a/frontend/src/types/schemaEditor/index.ts
+++ b/frontend/src/types/schemaEditor/index.ts
@@ -60,6 +60,7 @@ export interface CreateTableContext {
comment: string;
addColumnList: AddColumnContext[];
+ primaryKeyList: string[];
}
export interface AlterTableContext {
@@ -68,6 +69,8 @@ export interface AlterTableContext {
addColumnList: AddColumnContext[];
changeColumnList: ChangeColumnContext[];
dropColumnList: DropColumnContext[];
+ dropPrimaryKey: boolean;
+ primaryKeyList?: string[];
}
export interface RenameTableContext {
diff --git a/frontend/src/utils/schemaEditor/diffTable.ts b/frontend/src/utils/schemaEditor/diffSchema.ts
similarity index 53%
rename from frontend/src/utils/schemaEditor/diffTable.ts
rename to frontend/src/utils/schemaEditor/diffSchema.ts
index c597770e1c..4572859f62 100644
--- a/frontend/src/utils/schemaEditor/diffTable.ts
+++ b/frontend/src/utils/schemaEditor/diffSchema.ts
@@ -1,45 +1,51 @@
-import { isEqual, isUndefined } from "lodash-es";
-import type {
+import {
AlterTableContext,
CreateTableContext,
DropTableContext,
RenameTableContext,
} from "@/types";
-import { Table } from "@/types/schemaEditor/atomType";
-import { transformTableToCreateTableContext } from "./transform";
+import { Schema } from "@/types/schemaEditor/atomType";
+import { isEqual } from "lodash-es";
import { diffColumnList } from "./diffColumn";
+import { transformTableToCreateTableContext } from "./transform";
-// diffTableList gets the difference between table object list.
-// Including createTableList, alterTableList and dropTableList.
-// * 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[]) => {
+export const diffSchema = (originSchema: Schema, schema: Schema) => {
const createTableContextList: CreateTableContext[] = [];
- const createdTableList = tableList.filter(
+ const createdTableList = schema.tableList.filter(
(table) => table.status === "created"
);
for (const table of createdTableList) {
const createTableContext = transformTableToCreateTableContext(table);
const diffColumnListResult = diffColumnList([], table.columnList);
createTableContext.addColumnList = diffColumnListResult.addColumnList;
+ createTableContext.primaryKeyList =
+ schema.primaryKeyList
+ .find((pk) => pk.table === createTableContext.name)
+ ?.columnList.map((columnRef) => columnRef.value.newName) ?? [];
createTableContextList.push(createTableContext);
}
const alterTableContextList: AlterTableContext[] = [];
const renameTableContextList: RenameTableContext[] = [];
- const changedTableList = tableList.filter(
+ const changedTableList = schema.tableList.filter(
(table) => table.status === "normal"
);
for (const table of changedTableList) {
- const originTable = originTableList.find(
+ const originTable = originSchema.tableList.find(
(originTable) => originTable.oldName === table.oldName
);
- if (isUndefined(originTable)) {
- continue;
- }
-
- if (!isEqual(originTable, table)) {
+ const originPrimaryKey = originSchema?.primaryKeyList
+ .find((pk) => pk.table === table.newName)
+ ?.columnList.map((columnRef) => columnRef.value)
+ .sort();
+ const primaryKey = schema?.primaryKeyList
+ .find((pk) => pk.table === table.newName)
+ ?.columnList.map((columnRef) => columnRef.value)
+ .sort();
+ if (
+ !isEqual(originTable, table) ||
+ !isEqual(originPrimaryKey, primaryKey)
+ ) {
if (table.newName !== table.oldName) {
renameTableContextList.push({
oldName: table.oldName,
@@ -48,24 +54,35 @@ export const diffTableList = (originTableList: Table[], tableList: Table[]) => {
}
const columnListDiffResult = diffColumnList(
- originTable.columnList,
+ originTable?.columnList ?? [],
table.columnList
);
if (
+ !isEqual(originPrimaryKey, primaryKey) ||
columnListDiffResult.addColumnList.length > 0 ||
columnListDiffResult.changeColumnList.length > 0 ||
columnListDiffResult.dropColumnList.length > 0
) {
- alterTableContextList.push({
- name: originTable.newName,
+ const alterTableContext: AlterTableContext = {
+ name: table.newName,
...columnListDiffResult,
- });
+ dropPrimaryKey: false,
+ };
+ if (!isEqual(originPrimaryKey, primaryKey)) {
+ if (originPrimaryKey?.length !== 0) {
+ alterTableContext.dropPrimaryKey = true;
+ }
+ alterTableContext.primaryKeyList = primaryKey?.map(
+ (column) => column.newName
+ );
+ }
+ alterTableContextList.push(alterTableContext);
}
}
}
const dropTableContextList: DropTableContext[] = [];
- const droppedTableList = tableList.filter(
+ const droppedTableList = schema.tableList.filter(
(table) => table.status === "dropped"
);
for (const table of droppedTableList) {
diff --git a/frontend/src/utils/schemaEditor/diffTable.test.ts b/frontend/src/utils/schemaEditor/diffTable.test.ts
deleted file mode 100644
index 809240cd17..0000000000
--- a/frontend/src/utils/schemaEditor/diffTable.test.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import { expect, it } from "vitest";
-import {
- DropTableContext,
- CreateTableContext,
- AlterTableContext,
- RenameTableContext,
-} from "@/types";
-import { Table } from "@/types/schemaEditor/atomType";
-import { UNKNOWN_ID } from "@/types/const";
-import { diffTableList } from "./diffTable";
-
-it("diff create table list", () => {
- const testList: {
- originTableList: Table[];
- targetTableList: Table[];
- wanted: {
- createTableList: CreateTableContext[];
- alterTableList: AlterTableContext[];
- renameTableList: RenameTableContext[];
- dropTableList: DropTableContext[];
- };
- }[] = [
- {
- originTableList: [],
- targetTableList: [
- {
- oldName: "user",
- newName: "user",
- engine: "InnoDB",
- collation: "",
- comment: "",
- originColumnList: [],
- columnList: [
- {
- id: UNKNOWN_ID,
- oldName: "id",
- newName: "id",
- type: "int",
- comment: "",
- nullable: false,
- status: "created",
- },
- ],
- status: "created",
- } as any as Table,
- ],
- wanted: {
- createTableList: [
- {
- name: "user",
- engine: "InnoDB",
- characterSet: "",
- collation: "",
- comment: "",
- addColumnList: [
- {
- name: "id",
- type: "int",
- characterSet: "",
- collation: "",
- comment: "",
- nullable: false,
- default: undefined,
- },
- ],
- },
- ],
- renameTableList: [],
- alterTableList: [],
- dropTableList: [],
- },
- },
- ];
-
- for (const test of testList) {
- const result = diffTableList(test.originTableList, test.targetTableList);
- expect(result).toStrictEqual(test.wanted);
- }
-});
-
-it("diff alter table list", () => {
- const testList: {
- originTableList: Table[];
- targetTableList: Table[];
- wanted: {
- createTableList: CreateTableContext[];
- alterTableList: AlterTableContext[];
- renameTableList: RenameTableContext[];
- dropTableList: DropTableContext[];
- };
- }[] = [
- {
- originTableList: [
- {
- oldName: "user",
- newName: "user",
- engine: "InnoDB",
- collation: "",
- comment: "",
- columnList: [
- {
- oldName: "id",
- newName: "id",
- type: "int",
- characterSet: "",
- collation: "",
- comment: "",
- nullable: false,
- status: "normal",
- },
- ],
- status: "normal",
- } as any as Table,
- ],
- targetTableList: [
- {
- oldName: "user",
- newName: "user",
- engine: "InnoDB",
- collation: "",
- comment: "",
- columnList: [
- {
- oldName: "id",
- newName: "id",
- type: "int",
- characterSet: "",
- collation: "",
- comment: "",
- nullable: false,
- status: "normal",
- },
- {
- oldName: "email",
- newName: "email",
- type: "varchar",
- characterSet: "",
- collation: "",
- comment: "",
- nullable: false,
- status: "created",
- },
- ],
- status: "normal",
- } as any as Table,
- ],
- wanted: {
- createTableList: [],
- alterTableList: [
- {
- name: "user",
- addColumnList: [
- {
- name: "email",
- type: "varchar",
- characterSet: "",
- collation: "",
- comment: "",
- default: undefined,
- nullable: false,
- },
- ],
- changeColumnList: [],
- dropColumnList: [],
- },
- ],
- renameTableList: [],
- dropTableList: [],
- },
- },
- ];
-
- for (const test of testList) {
- const result = diffTableList(test.originTableList, test.targetTableList);
- expect(result).toStrictEqual(test.wanted);
- }
-});
-
-it("diff drop table list", () => {
- const testList: {
- originTableList: Table[];
- targetTableList: Table[];
- wanted: {
- createTableList: CreateTableContext[];
- alterTableList: AlterTableContext[];
- renameTableList: RenameTableContext[];
- dropTableList: DropTableContext[];
- };
- }[] = [
- {
- originTableList: [
- {
- id: 1,
- oldName: "user",
- newName: "user",
- engine: "InnoDB",
- collation: "",
- comment: "",
- columnList: [
- {
- name: "id",
- type: "int",
- characterSet: "",
- collation: "",
- comment: "",
- nullable: false,
- },
- ],
- status: "normal",
- } as any as Table,
- ],
- targetTableList: [
- {
- id: 1,
- oldName: "user",
- newName: "user",
- engine: "InnoDB",
- collation: "",
- comment: "",
- columnList: [
- {
- name: "id",
- type: "int",
- characterSet: "",
- collation: "",
- comment: "",
- nullable: false,
- },
- ],
- status: "dropped",
- } as any as Table,
- ],
- wanted: {
- createTableList: [],
- alterTableList: [],
- renameTableList: [],
- dropTableList: [
- {
- name: "user",
- },
- ],
- },
- },
- ];
-
- for (const test of testList) {
- const result = diffTableList(test.originTableList, test.targetTableList);
- expect(result).toStrictEqual(test.wanted);
- }
-});
diff --git a/frontend/src/utils/schemaEditor/transform.ts b/frontend/src/utils/schemaEditor/transform.ts
index b97792c535..b840059ec3 100644
--- a/frontend/src/utils/schemaEditor/transform.ts
+++ b/frontend/src/utils/schemaEditor/transform.ts
@@ -45,6 +45,7 @@ export const transformTableToCreateTableContext = (
collation: defaultTo(table.collation, ""),
comment: defaultTo(table.comment, ""),
addColumnList: [],
+ primaryKeyList: [],
// As we don't have a CharacterSet field in table model,
// set it as an empty string for now.
characterSet: "",
diff --git a/plugin/parser/edit/mysql/deparse.go b/plugin/parser/edit/mysql/deparse.go
index 869dba883b..0aac4dd9b7 100644
--- a/plugin/parser/edit/mysql/deparse.go
+++ b/plugin/parser/edit/mysql/deparse.go
@@ -191,10 +191,12 @@ func transformAlterTableContext(alterTableContext *api.AlterTableContext) (*tidb
}
if alterTableContext.PrimaryKeyList != nil {
- dropPrimaryKeySpec := tidbast.AlterTableSpec{
- Tp: tidbast.AlterTableDropPrimaryKey,
+ if alterTableContext.DropPrimaryKey {
+ dropPrimaryKeySpec := tidbast.AlterTableSpec{
+ Tp: tidbast.AlterTableDropPrimaryKey,
+ }
+ alterTableStmt.Specs = append(alterTableStmt.Specs, &dropPrimaryKeySpec)
}
- alterTableStmt.Specs = append(alterTableStmt.Specs, &dropPrimaryKeySpec)
if len(*alterTableContext.PrimaryKeyList) != 0 {
alterTableSpec := tidbast.AlterTableSpec{
diff --git a/plugin/parser/edit/mysql/deparse_test.go b/plugin/parser/edit/mysql/deparse_test.go
index 35db6766ff..bc207d32f4 100644
--- a/plugin/parser/edit/mysql/deparse_test.go
+++ b/plugin/parser/edit/mysql/deparse_test.go
@@ -444,7 +444,7 @@ func TestDeparseAlterTableWithPrimaryKey(t *testing.T) {
},
},
},
- want: "ALTER TABLE `t1` ADD COLUMN (`id` INT NOT NULL), DROP PRIMARY KEY, ADD PRIMARY KEY (`id`);\n",
+ want: "ALTER TABLE `t1` ADD COLUMN (`id` INT NOT NULL), ADD PRIMARY KEY (`id`);\n",
},
{
name: "alter table t2",
@@ -460,6 +460,7 @@ func TestDeparseAlterTableWithPrimaryKey(t *testing.T) {
Nullable: false,
},
},
+ DropPrimaryKey: true,
PrimaryKeyList: &[]string{},
},
},
@@ -485,26 +486,6 @@ func TestDeparseAlterTableWithPrimaryKey(t *testing.T) {
},
want: "ALTER TABLE `t3` ADD COLUMN (`id` INT NOT NULL);\n",
},
- {
- name: "alter table t4",
- databaseEdit: &api.DatabaseEdit{
- DatabaseID: api.UnknownID,
- AlterTableList: []*api.AlterTableContext{
- {
- Name: "t4",
- AddColumnList: []*api.AddColumnContext{
- {
- Name: "id",
- Type: "int",
- Nullable: false,
- },
- },
- PrimaryKeyList: &[]string{"id"},
- },
- },
- },
- want: "ALTER TABLE `t4` ADD COLUMN (`id` INT NOT NULL), DROP PRIMARY KEY, ADD PRIMARY KEY (`id`);\n",
- },
}
mysqlEditor := &SchemaEditor{}