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: use schema editor v1 in edit schema (#8200)
boojacke2b893090a4f
diff --git a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vueindex 7c37c8e2a2..ce9d5f9f2a 100644--- a/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue+++ b/frontend/src/components/AlterSchemaPrepForm/SchemaEditorModal.vue@@ -33,9 +33,12 @@</button></div><div class="w-full h-full max-h-full overflow-auto border-b mb-4">- <SchemaEditor+ <SchemaEditorV1v-show="state.selectedTab === 'schema-editor'"- :database-id-list="props.databaseIdList"+ :engine="databaseEngine"+ :project="project"+ :resource-type="'database'"+ :databases="databaseList"/><divv-show="state.selectedTab === 'raw-sql'"@@ -123,6 +126,7 @@</template><script lang="ts" setup>+import axios from "axios";import dayjs from "dayjs";import { head, uniq } from "lodash-es";import { computed, onMounted, PropType, reactive, ref, watch } from "vue";@@ -130,15 +134,16 @@ import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import BBBetaBadge from "@/bbkit/BBBetaBadge.vue";import ActionConfirmModal from "@/components/SchemaEditor/Modals/ActionConfirmModal.vue";-import SchemaEditor from "@/components/SchemaEditor/SchemaEditor.vue";+import SchemaEditorV1 from "@/components/SchemaEditorV1/index.vue";import {useDatabaseV1Store,useNotificationStore,- useSchemaEditorStore,+ useSchemaEditorV1Store,} from "@/store";import {ComposedDatabase,DatabaseEdit,+ DatabaseEditResult,dialectOfEngineV1,UNKNOWN_PROJECT_NAME,unknownProject,@@ -191,7 +196,7 @@ const state = reactive<LocalState>({editStatement: "",showActionConfirmModal: false,});-const editorStore = useSchemaEditorStore();+const schemaEditorV1Store = useSchemaEditorV1Store();const databaseV1Store = useDatabaseV1Store();const notificationStore = useNotificationStore();const statementFromSchemaEditor = ref<string>();@@ -299,17 +304,19 @@ const handleSyncSQLFromSchemaEditor = async () => {const getDatabaseEditListWithSchemaEditor = () => {const databaseEditList: DatabaseEdit[] = [];- for (const database of editorStore.databaseList) {- const databaseSchema = editorStore.databaseSchemaById.get(database.uid);- if (!databaseSchema) {- continue;- }-+ for (const databaseSchema of Array.from(+ schemaEditorV1Store.resourceMap["database"].values()+ )) {+ const database = databaseSchema.database;for (const schema of databaseSchema.schemaList) {const originSchema = databaseSchema.originSchemaList.find((originSchema) => originSchema.id === schema.id);- const diffSchemaResult = diffSchema(database.uid, originSchema, schema);+ if (!originSchema) {+ continue;+ }++ const diffSchemaResult = diffSchema(database.name, originSchema, schema);if (checkHasSchemaChanges(diffSchemaResult)) {const index = databaseEditList.findIndex((edit) => String(edit.databaseId) === database.uid@@ -336,9 +343,7 @@ const fetchDatabaseEditStatementMapWithSchemaEditor = async () => {const databaseEditMap: Map<string, string> = new Map();if (databaseEditList.length > 0) {for (const databaseEdit of databaseEditList) {- const databaseEditResult = await editorStore.postDatabaseEdit(- databaseEdit- );+ const databaseEditResult = await postDatabaseEdit(databaseEdit);if (databaseEditResult.validateResultList.length > 0) {notificationStore.pushNotification({module: "bytebase",@@ -538,6 +543,17 @@ const generateIssueName = (return issueNameParts.join(" ");};+const postDatabaseEdit = async (databaseEdit: DatabaseEdit) => {+ const resData = (+ await axios.post(+ `/api/database/${databaseEdit.databaseId}/edit`,+ databaseEdit+ )+ ).data;+ const databaseEditResult = resData.data.attributes as DatabaseEditResult;+ return databaseEditResult;+};+watch(() => getDatabaseEditListWithSchemaEditor(),() => {diff --git a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue b/frontend/src/components/SchemaDiagram/SchemaDiagram.vueindex 4d2e3093b8..e618e2d734 100644--- a/frontend/src/components/SchemaDiagram/SchemaDiagram.vue+++ b/frontend/src/components/SchemaDiagram/SchemaDiagram.vue@@ -39,7 +39,7 @@ import {DatabaseMetadata,SchemaMetadata,TableMetadata,-} from "@/types/proto/store/database";+} from "@/types/proto/v1/database_service";import Canvas from "./Canvas";import { TableNode, autoLayout, GraphNodeItem, GraphEdgeItem } from "./ER";import Navigator from "./Navigator";diff --git a/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue b/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vuenew file mode 100644index 0000000000..3e5772afce--- /dev/null+++ b/frontend/src/components/SchemaEditorV1/Aside/DatabaseTree.vue@@ -0,0 +1,866 @@+<template>+ <div class="w-full h-full pl-1 pr-2 relative overflow-y-hidden">+ <div class="w-full sticky top-0 pt-2 h-12 bg-white z-10">+ <NInput+ v-model:value="searchPattern"+ :placeholder="$t('schema-editor.search-database-and-table')"+ >+ <template #prefix>+ <heroicons-outline:search class="w-4 h-auto text-gray-300" />+ </template>+ </NInput>+ </div>+ <div+ class="schema-editor-database-tree pb-2 overflow-y-auto h-full text-sm"+ >+ <NTree+ ref="treeRef"+ block-line+ virtual-scroll+ style="height: 100%"+ :data="treeDataRef"+ :pattern="searchPattern"+ :render-prefix="renderPrefix"+ :render-label="renderLabel"+ :render-suffix="renderSuffix"+ :node-props="nodeProps"+ :on-load="loadSubTree"+ :expanded-keys="expandedKeysRef"+ :selected-keys="selectedKeysRef"+ :on-update:expanded-keys="handleExpandedKeysChange"+ />+ <NDropdown+ trigger="manual"+ placement="bottom-start"+ :show="contextMenu.showDropdown"+ :options="contextMenuOptions"+ :x="contextMenu.clientX"+ :y="contextMenu.clientY"+ to="body"+ @select="handleContextMenuDropdownSelect"+ @clickoutside="handleDropdownClickoutside"+ />+ </div>+ </div>++ <SchemaNameModal+ v-if="state.schemaNameModalContext !== undefined"+ :parent-name="state.schemaNameModalContext.parentName"+ :schema-id="state.schemaNameModalContext.schemaId"+ @close="state.schemaNameModalContext = undefined"+ />++ <TableNameModal+ v-if="state.tableNameModalContext !== undefined"+ :parent-name="state.tableNameModalContext.parentName"+ :schema-id="state.tableNameModalContext.schemaId"+ :table-id="state.tableNameModalContext.tableId"+ @close="state.tableNameModalContext = undefined"+ />+</template>++<script lang="ts" setup>+import { cloneDeep, escape, head, isUndefined } from "lodash-es";+import { TreeOption, NEllipsis, NInput, NDropdown, NTree } from "naive-ui";+import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";+import { useI18n } from "vue-i18n";+import DatabaseIcon from "~icons/heroicons-outline/circle-stack";+import TableIcon from "~icons/heroicons-outline/table-cells";+import SchemaIcon from "~icons/heroicons-outline/view-columns";+import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";+import { InstanceV1EngineIcon } from "@/components/v2";+import {+ generateUniqueTabId,+ useDBSchemaV1Store,+ useDatabaseV1Store,+ useInstanceV1Store,+ useNotificationStore,+ useSchemaEditorV1Store,+} from "@/store";+import { SchemaEditorTabType } from "@/types";+import { Engine } from "@/types/proto/v1/common";+import { SchemaMetadata } from "@/types/proto/v1/database_service";+import {+ Schema,+ Table,+ convertSchemaMetadataList,+ convertSchemaMetadataToSchema,+} from "@/types/v1/schemaEditor";+import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";+import SchemaNameModal from "../Modals/SchemaNameModal.vue";+import TableNameModal from "../Modals/TableNameModal.vue";+import { isSchemaChanged } from "../utils/schema";+import { isTableChanged } from "../utils/table";++interface BaseTreeNode extends TreeOption {+ key: string;+ label: string;+ isLeaf: boolean;+ children?: TreeNode[];+}++interface TreeNodeForInstance extends BaseTreeNode {+ type: "instance";+ // Resoure name format.+ instance: string;+}++interface TreeNodeForDatabase extends BaseTreeNode {+ type: "database";+ instance: string;+ // Resoure name format.+ database: string;+}++interface TreeNodeForSchema extends BaseTreeNode {+ type: "schema";+ instance: string;+ database: string;+ schemaId: string;+}++interface TreeNodeForTable extends BaseTreeNode {+ type: "table";+ instance: string;+ database: string;+ schemaId: string;+ tableId: string;+}++type TreeNode =+ | TreeNodeForInstance+ | TreeNodeForDatabase+ | TreeNodeForSchema+ | TreeNodeForTable;++interface TreeContextMenu {+ showDropdown: boolean;+ clientX: number;+ clientY: number;+ treeNode?: TreeNode;+}++interface LocalState {+ shouldRelocateTreeNode: boolean;+ schemaNameModalContext?: {+ parentName: string;+ schemaId: string | undefined;+ };+ tableNameModalContext?: {+ parentName: string;+ schemaId: string;+ tableId: string | undefined;+ };+}++const { t } = useI18n();+const schemaEditorV1Store = useSchemaEditorV1Store();+const instanceStore = useInstanceV1Store();+const state = reactive<LocalState>({+ shouldRelocateTreeNode: false,+});+const currentTab = computed(() => schemaEditorV1Store.currentTab);++const contextMenu = reactive<TreeContextMenu>({+ showDropdown: false,+ clientX: 0,+ clientY: 0,+ treeNode: undefined,+});+const treeRef = ref<InstanceType<typeof NTree>>();+const searchPattern = ref("");+const expandedKeysRef = ref<string[]>([]);+const selectedKeysRef = ref<string[]>([]);+const treeDataRef = ref<TreeNode[]>([]);+const databaseDataLoadedSet = ref<Set<string>>(new Set());++const databaseList = computed(() => schemaEditorV1Store.databaseList);+const schemaList = computed(() =>+ Array.from(schemaEditorV1Store.resourceMap["database"].values())+ .map((item) => item.schemaList)+ .flat()+);+const tableList = computed(() =>+ schemaList.value.map((schema) => schema.tableList).flat()+);+const contextMenuOptions = computed(() => {+ const treeNode = contextMenu.treeNode;+ if (isUndefined(treeNode)) {+ return [];+ }+ const instanceEngine = instanceStore.getInstanceByName(+ treeNode.instance+ ).engine;++ if (treeNode.type === "database") {+ const options = [];+ if (instanceEngine === Engine.MYSQL) {+ options.push({+ key: "create-table",+ label: t("schema-editor.actions.create-table"),+ });+ } else if (instanceEngine === Engine.POSTGRES) {+ options.push({+ key: "create-schema",+ label: t("schema-editor.actions.create-schema"),+ });+ }+ return options;+ } else if (treeNode.type === "schema") {+ const options = [];+ if (instanceEngine === Engine.POSTGRES) {+ const schema = schemaEditorV1Store.getSchema(+ treeNode.database,+ treeNode.schemaId+ );+ if (!schema) {+ return [];+ }++ const isDropped = schema.status === "dropped";+ if (isDropped) {+ options.push({+ key: "restore",+ label: t("schema-editor.actions.restore"),+ });+ } else {+ options.push({+ key: "create-table",+ label: t("schema-editor.actions.create-table"),+ });+ options.push({+ key: "rename",+ label: t("schema-editor.actions.rename"),+ });+ options.push({+ key: "drop-schema",+ label: t("schema-editor.actions.drop-schema"),+ });+ }+ }+ return options;+ } else if (treeNode.type === "table") {+ const table = schemaEditorV1Store.getTable(+ treeNode.database,+ treeNode.schemaId,+ treeNode.tableId+ );+ if (!table) {+ return [];+ }++ const isDropped = table.status === "dropped";+ const options = [];+ if (isDropped) {+ options.push({+ key: "restore",+ label: t("schema-editor.actions.restore"),+ });+ } else {+ options.push({+ key: "rename",+ label: t("schema-editor.actions.rename"),+ });+ options.push({+ key: "drop",+ label: t("schema-editor.actions.drop-table"),+ });+ }+ return options;+ }++ return [];+});++onMounted(async () => {+ const treeNodeList: TreeNode[] = [];+ const instanceTreeNodeMap: Map<string, TreeNodeForInstance> = new Map();+ const databaseTreeNodeList: TreeNodeForDatabase[] = [];+ for (const database of databaseList.value) {+ const instance = database.instanceEntity;+ let instanceTreeNode: TreeNodeForInstance;+ if (instanceTreeNodeMap.has(instance.name)) {+ instanceTreeNode = instanceTreeNodeMap.get(+ instance.name+ ) as TreeNodeForInstance;+ } else {+ instanceTreeNode = {+ type: "instance",+ key: `i-${instance.name}`,+ label: instance.title,+ isLeaf: false,+ instance: instance.name,+ children: [],+ };+ instanceTreeNodeMap.set(instance.name, instanceTreeNode);+ treeNodeList.push(instanceTreeNode);+ // Make the instance tree node expanded as default.+ expandedKeysRef.value.push(instanceTreeNode.key);+ }++ const databaseTreeNode: TreeNodeForDatabase = {+ type: "database",+ key: `d-${database.name}`,+ label: database.databaseName,+ isLeaf: false,+ instance: instance.name,+ database: database.name,+ };+ instanceTreeNode.children?.push(databaseTreeNode);+ databaseTreeNodeList.push(databaseTreeNode);+ }+ treeDataRef.value = treeNodeList;+});++watch(+ [+ () => schemaList.value,+ () => tableList.value,+ () => databaseDataLoadedSet.value,+ ],+ () => {+ const databaseTreeNodeList: TreeNodeForDatabase[] = [];+ for (const treeNode of treeDataRef.value) {+ if (treeNode.type === "instance") {+ databaseTreeNodeList.push(+ ...(treeNode.children as TreeNodeForDatabase[])+ );+ }+ }++ for (const database of databaseList.value) {+ if (!databaseDataLoadedSet.value.has(database.name)) {+ continue;+ }+ const databaseTreeNode = databaseTreeNodeList.find(+ (treeNode) =>+ treeNode.database === database.name &&+ databaseDataLoadedSet.value.has(treeNode.database)+ );+ if (isUndefined(databaseTreeNode)) {+ continue;+ }+ const instance = database.instanceEntity;+ const instanceEngine = instance.engine;+ if (instanceEngine === Engine.MYSQL) {+ const schemaList: Schema[] =+ schemaEditorV1Store.resourceMap["database"].get(database.name)+ ?.schemaList || [];+ const schema = head(schemaList);+ if (!schema) {+ return;+ }+ const tableList: Table[] = schema.tableList;+ if (tableList.length === 0) {+ databaseTreeNode.isLeaf = true;+ databaseTreeNode.children = [];+ } else {+ databaseTreeNode.isLeaf = false;+ databaseTreeNode.children = tableList.map((table) => {+ return {+ type: "table",+ key: `t-${database.name}-${table.id}`,+ label: table.name,+ children: [],+ isLeaf: true,+ instance: instance.name,+ database: database.name,+ schemaId: schema.id,+ tableId: table.id,+ };+ });+ }+ } else if (instanceEngine === Engine.POSTGRES) {+ const schemaList: Schema[] =+ schemaEditorV1Store.resourceMap["database"].get(database.name)+ ?.schemaList || [];+ const schemaTreeNodeList: TreeNodeForSchema[] = [];+ for (const schema of schemaList) {+ const schemaTreeNode: TreeNodeForSchema = {+ type: "schema",+ key: `s-${database.name}-${schema.id}`,+ label: schema.name,+ instance: instance.name,+ database: database.name,+ schemaId: schema.id,+ isLeaf: true,+ };++ if (schema.tableList.length === 0) {+ schemaTreeNode.isLeaf = true;+ schemaTreeNode.children = [];+ } else {+ schemaTreeNode.isLeaf = false;+ schemaTreeNode.children = schema.tableList.map((table) => {+ return {+ type: "table",+ key: `t-${database.name}-${table.id}`,+ label: table.name,+ children: [],+ isLeaf: true,+ instance: instance.name,+ database: database.name,+ schemaId: schema.id,+ tableId: table.id,+ };+ });+ }+ schemaTreeNodeList.push(schemaTreeNode);+ }++ if (schemaTreeNodeList.length === 0) {+ databaseTreeNode.isLeaf = true;+ databaseTreeNode.children = [];+ } else {+ databaseTreeNode.isLeaf = false;+ databaseTreeNode.children = schemaTreeNodeList;+ }+ }+ }+ },+ {+ deep: true,+ }+);++watch(+ () => currentTab.value,+ () => {+ if (!currentTab.value) {+ selectedKeysRef.value = [];+ return;+ }++ if (currentTab.value.type === SchemaEditorTabType.TabForDatabase) {+ if (currentTab.value.selectedSchemaId) {+ const key = `s-${currentTab.value.parentName}-${currentTab.value.selectedSchemaId}`;+ selectedKeysRef.value = [key];+ } else {+ const key = `d-${currentTab.value.parentName}`;+ selectedKeysRef.value = [key];+ }+ } else if (currentTab.value.type === SchemaEditorTabType.TabForTable) {+ const databaseTreeNodeKey = `d-${currentTab.value.parentName}`;+ if (!expandedKeysRef.value.includes(databaseTreeNodeKey)) {+ expandedKeysRef.value.push(databaseTreeNodeKey);+ }+ const schemaTreeNodeKey = `s-${currentTab.value.parentName}-${currentTab.value.schemaId}`;+ if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {+ expandedKeysRef.value.push(schemaTreeNodeKey);+ }+ const tableTreeNodeKey = `t-${currentTab.value.parentName}-${currentTab.value.tableId}`;+ selectedKeysRef.value = [tableTreeNodeKey];+ }++ if (state.shouldRelocateTreeNode) {+ nextTick(() => {+ treeRef.value?.scrollTo({+ key: selectedKeysRef.value[0],+ });+ });+ }+ }+);++watch(searchPattern, () => {+ for (const treeNode of treeDataRef.value) {+ if (treeNode.type === "instance" && treeNode.children) {+ for (const databaseTreeNode of treeNode.children) {+ if (databaseTreeNode.children === undefined) {+ loadSubTree(databaseTreeNode);+ }+ }+ }+ }+});++// Render prefix icons before label text.+const renderPrefix = ({ option }: { option: TreeOption }) => {+ const treeNode = option as TreeNode;++ if (treeNode.type === "instance") {+ const instance = instanceStore.getInstanceByName(treeNode.instance);+ const children = [+ h(InstanceV1EngineIcon, {+ instance,+ }),+ h(+ "span",+ {+ class: "text-gray-500 text-sm",+ },+ `(${instance.environmentEntity.title})`+ ),+ ];++ return h("span", { class: "flex items-center gap-x-1" }, children);+ } else if (treeNode.type === "database") {+ return h(DatabaseIcon, {+ class: "w-4 h-auto text-gray-400",+ });+ } else if (treeNode.type === "schema") {+ return h(SchemaIcon, {+ class: "w-4 h-auto text-gray-400",+ });+ } else if (treeNode.type === "table") {+ return h(TableIcon, {+ class: "w-4 h-auto text-gray-400",+ });+ }+ return null;+};++// Render label text.+const renderLabel = ({ option }: { option: TreeOption }) => {+ const treeNode = option as TreeNode;+ const additionalClassList: string[] = ["select-none"];++ if (treeNode.type === "schema") {+ const schema = schemaEditorV1Store.resourceMap["database"]+ .get(treeNode.database)+ ?.schemaList.find((schema) => schema.id === treeNode.schemaId);++ if (schema) {+ if (schema.status === "created") {+ additionalClassList.push("text-green-700");+ } else if (schema.status === "dropped") {+ additionalClassList.push("text-red-700 line-through");+ } else {+ if (isSchemaChanged(treeNode.database, treeNode.schemaId)) {+ additionalClassList.push("text-yellow-700");+ }+ }+ }+ } else if (treeNode.type === "table") {+ const table = schemaEditorV1Store.resourceMap["database"]+ .get(treeNode.database)+ ?.schemaList.find((schema) => schema.id === treeNode.schemaId)+ ?.tableList.find((table) => table.id === treeNode.tableId);++ if (table) {+ if (table.status === "created") {+ additionalClassList.push("text-green-700");+ } else if (table.status === "dropped") {+ additionalClassList.push("text-red-700 line-through");+ } else {+ if (+ isTableChanged(treeNode.database, treeNode.schemaId, treeNode.tableId)+ ) {+ additionalClassList.push("text-yellow-700");+ }+ }+ }+ }++ return h(+ NEllipsis,+ {+ class: additionalClassList.join(" "),+ },+ () => [+ h("span", {+ innerHTML: getHighlightHTMLByKeyWords(+ escape(treeNode.label),+ escape(searchPattern.value)+ ),+ }),+ ]+ );+};++// Render a 'menu' icon in the right of the node+const renderSuffix = ({ option }: { option: TreeOption }) => {+ const treeNode = option as TreeNode;+ const icon = h(EllipsisIcon, {+ class: "w-4 h-auto text-gray-600",+ onClick: (e) => {+ handleShowDropdown(e, treeNode);+ },+ });+ const instanceEngine = instanceStore.getInstanceByName(+ treeNode.instance+ ).engine;+ if (treeNode.type === "database") {+ return icon;+ } else if (treeNode.type === "schema") {+ if (instanceEngine === Engine.POSTGRES) {+ return icon;+ }+ } else if (treeNode.type === "table") {+ return icon;+ }+ return null;+};++const handleShowDropdown = (e: MouseEvent, treeNode: TreeNode) => {+ e.preventDefault();+ e.stopPropagation();+ contextMenu.treeNode = treeNode;+ contextMenu.showDropdown = true;+ contextMenu.clientX = e.clientX;+ contextMenu.clientY = e.clientY;+ selectedKeysRef.value = [treeNode.key];+};++const fetchSchemaListByDatabaseId = async (+ databaseName: string,+ skipCache = false+) => {+ const database = useDatabaseV1Store().getDatabaseByName(databaseName);+ const schemaMetadataList = await useDBSchemaV1Store().getOrFetchSchemaList(+ database.name,+ skipCache+ );+ const schemaList = convertSchemaMetadataList(schemaMetadataList);+ if (+ schemaList.length === 0 &&+ database.instanceEntity.engine === Engine.MYSQL+ ) {+ schemaList.push(+ convertSchemaMetadataToSchema(SchemaMetadata.fromPartial({}))+ );+ }++ schemaEditorV1Store.resourceMap["database"].set(database.name, {+ database,+ schemaList: schemaList,+ originSchemaList: cloneDeep(schemaList),+ });++ return schemaList;+};++// Dynamic fetching table list when database tree node clicking.+const loadSubTree = async (option: TreeOption) => {+ const treeNode = option as TreeNode;+ if (treeNode.type === "database") {+ const databaseName = treeNode.database;+ if (databaseDataLoadedSet.value.has(databaseName)) {+ return;+ }++ databaseDataLoadedSet.value.add(databaseName);+ try {+ const schemaList = await fetchSchemaListByDatabaseId(databaseName, true);+ if (schemaList.length === 0) {+ treeNode.children = [];+ treeNode.isLeaf = true;+ }+ } catch (error) {+ useNotificationStore().pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("schema-editor.message.failed-to-fetch-database-schema"),+ });+ }+ }+};++// Set event handler to tree nodes.+const nodeProps = ({ option }: { option: TreeOption }) => {+ const treeNode = option as TreeNode;+ return {+ async onclick(e: MouseEvent) {+ // Check if clicked on the content part.+ // And ignore the fold/unfold arrow.+ if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {+ state.shouldRelocateTreeNode = false;++ if (treeNode.type === "instance") {+ // Toggle instance tree node expanded status.+ const index = expandedKeysRef.value.findIndex(+ (key) => key === treeNode.key+ );+ if (index >= 0) {+ expandedKeysRef.value.splice(index, 1);+ } else {+ expandedKeysRef.value.push(treeNode.key);+ }+ } else if (treeNode.type === "database") {+ await loadSubTree(treeNode);+ const index = expandedKeysRef.value.findIndex(+ (key) => key === treeNode.key+ );+ if (index < 0) {+ expandedKeysRef.value.push(treeNode.key);+ }+ schemaEditorV1Store.addTab({+ id: generateUniqueTabId(),+ type: SchemaEditorTabType.TabForDatabase,+ parentName: treeNode.database,+ });+ } else if (treeNode.type === "schema") {+ const index = expandedKeysRef.value.findIndex(+ (key) => key === treeNode.key+ );+ if (index < 0) {+ expandedKeysRef.value.push(treeNode.key);+ }+ } else if (treeNode.type === "table") {+ schemaEditorV1Store.addTab({+ id: generateUniqueTabId(),+ type: SchemaEditorTabType.TabForTable,+ parentName: treeNode.database,+ schemaId: treeNode.schemaId,+ tableId: treeNode.tableId,+ });+ }++ nextTick(() => {+ if (treeNode.type === "database") {+ selectedKeysRef.value = [`d-${treeNode.database}`];+ } else if (treeNode.type === "schema") {+ selectedKeysRef.value = [+ `s-${treeNode.database}-${treeNode.schemaId}`,+ ];+ } else if (treeNode.type === "table") {+ selectedKeysRef.value = [+ `t-${treeNode.database}-${treeNode.tableId}`,+ ];+ }+ state.shouldRelocateTreeNode = true;+ });+ } else {+ nextTick(() => {+ selectedKeysRef.value = [];+ });+ }+ },+ async ondblclick() {+ await loadSubTree(treeNode);+ nextTick(() => {+ const index = expandedKeysRef.value.findIndex(+ (key) => key === treeNode.key+ );+ if (index >= 0) {+ expandedKeysRef.value.splice(index, 1);+ } else {+ expandedKeysRef.value.push(treeNode.key);+ }+ });+ },+ oncontextmenu(e: MouseEvent) {+ handleShowDropdown(e, treeNode);+ },+ };+};++const handleContextMenuDropdownSelect = async (key: string) => {+ const treeNode = contextMenu.treeNode;+ if (treeNode?.type === "database") {+ if (key === "create-table") {+ await loadSubTree(treeNode);+ const instanceEngine = instanceStore.getInstanceByName(+ treeNode.instance+ ).engine;+ if (instanceEngine === Engine.MYSQL) {+ const schemaList: Schema[] =+ schemaEditorV1Store.resourceMap["database"].get(treeNode.database)+ ?.schemaList || [];+ const schema = head(schemaList);+ if (!schema) {+ return;+ }+ state.tableNameModalContext = {+ parentName: treeNode.database,+ schemaId: schema.id,+ tableId: undefined,+ };+ }+ } else if (key === "create-schema") {+ state.schemaNameModalContext = {+ parentName: treeNode.database,+ schemaId: undefined,+ };+ }+ } else if (treeNode?.type === "schema") {+ if (key === "create-table") {+ await loadSubTree(treeNode);+ state.tableNameModalContext = {+ parentName: treeNode.database,+ schemaId: treeNode.schemaId,+ tableId: undefined,+ };+ } else if (key === "rename") {+ state.schemaNameModalContext = {+ parentName: treeNode.database,+ schemaId: treeNode.schemaId,+ };+ } else if (key === "drop-schema") {+ schemaEditorV1Store.dropSchema(treeNode.database, treeNode.schemaId);+ } else if (key === "restore") {+ schemaEditorV1Store.restoreSchema(treeNode.database, treeNode.schemaId);+ }+ } else if (treeNode?.type === "table") {+ if (key === "rename") {+ state.tableNameModalContext = {+ parentName: treeNode.database,+ schemaId: treeNode.schemaId,+ tableId: treeNode.tableId,+ };+ } else if (key === "drop") {+ schemaEditorV1Store.dropTable(+ treeNode.database,+ treeNode.schemaId,+ treeNode.tableId+ );+ } else if (key === "restore") {+ schemaEditorV1Store.restoreTable(+ treeNode.database,+ treeNode.schemaId,+ treeNode.tableId+ );+ }+ }+ contextMenu.showDropdown = false;+};++const handleDropdownClickoutside = (e: MouseEvent) => {+ if (+ !isDescendantOf(e.target as Element, ".n-tree-node-wrapper") ||+ e.button !== 2+ ) {+ selectedKeysRef.value = [];+ contextMenu.showDropdown = false;+ }+};++const handleExpandedKeysChange = (expandedKeys: string[]) => {+ expandedKeysRef.value = expandedKeys;+};+</script>++<style>+.schema-editor-database-tree .n-tree-node-wrapper {+ @apply !py-px;+}+.schema-editor-database-tree .n-tree-node-content__prefix {+ @apply shrink-0 !mr-1;+}+.schema-editor-database-tree .n-tree-node-content__text {+ @apply truncate mr-1;+}+.schema-editor-database-tree .n-tree-node-content__suffix {+ @apply rounded-sm !hidden hover:opacity-80;+}+.schema-editor-database-tree+ .n-tree-node-wrapper:hover+ .n-tree-node-content__suffix {+ @apply !flex;+}+.schema-editor-database-tree+ .n-tree-node-wrapper+ .n-tree-node--selected+ .n-tree-node-content__suffix {+ @apply !flex;+}+.schema-editor-database-tree .n-tree-node-switcher {+ @apply px-0 !w-4 !h-7;+}+</style>++<style scoped>+.schema-editor-database-tree {+ max-height: calc(100% - 48px);+}+</style>diff --git a/frontend/src/components/SchemaEditorV1/Aside/index.vue b/frontend/src/components/SchemaEditorV1/Aside/index.vueindex 09f7fcf4fe..e5ff8f2d9a 100644--- a/frontend/src/components/SchemaEditorV1/Aside/index.vue+++ b/frontend/src/components/SchemaEditorV1/Aside/index.vue@@ -1,10 +1,12 @@<template><BranchTree v-if="schemaEditorV1Store.resourceType === 'branch'" />+ <DatabaseTree v-else-if="schemaEditorV1Store.resourceType === 'database'" /></template><script lang="ts" setup>import { useSchemaEditorV1Store } from "@/store";import BranchTree from "./BranchTree.vue";+import DatabaseTree from "./DatabaseTree.vue";const schemaEditorV1Store = useSchemaEditorV1Store();</script>diff --git a/frontend/src/components/SchemaEditorV1/Editor.vue b/frontend/src/components/SchemaEditorV1/Editor.vueindex 4d7859973f..06dba0cda6 100644--- a/frontend/src/components/SchemaEditorV1/Editor.vue+++ b/frontend/src/components/SchemaEditorV1/Editor.vue@@ -3,8 +3,11 @@<template v-if="currentTab"><TabsContainer /><div :key="currentTab.id" class="w-full h-full relative overflow-y-auto">+ <DatabaseEditor+ v-if="currentTab.type === SchemaEditorTabType.TabForDatabase"+ /><TableEditor- v-if="currentTab.type === SchemaEditorTabType.TabForTable"+ v-else-if="currentTab.type === SchemaEditorTabType.TabForTable"/></div></template>@@ -16,6 +19,7 @@import { computed } from "vue";import { useSchemaEditorV1Store } from "@/store/modules/v1/schemaEditor";import { SchemaEditorTabType } from "@/types/v1/schemaEditor";+import DatabaseEditor from "./Panels/DatabaseEditor.vue";import TableEditor from "./Panels/TableEditor.vue";import TabsContainer from "./TabsContainer.vue";diff --git a/frontend/src/components/SchemaEditorV1/Panels/DatabaseEditor.vue b/frontend/src/components/SchemaEditorV1/Panels/DatabaseEditor.vuenew file mode 100644index 0000000000..626caff553--- /dev/null+++ b/frontend/src/components/SchemaEditorV1/Panels/DatabaseEditor.vue@@ -0,0 +1,423 @@+<template>+ <div class="flex flex-col w-full h-full overflow-y-auto">+ <div class="py-2 w-full flex flex-row justify-between items-center">+ <div>+ <div+ v-if="state.selectedSubtab === 'table-list'"+ class="w-full flex justify-between items-center space-x-2"+ >+ <div class="flex flex-row justify-start items-center">+ <div+ v-if="shouldShowSchemaSelector"+ class="ml-2 flex flex-row justify-start items-center mr-3 text-sm"+ >+ <span class="mr-1">Schema:</span>+ <n-select+ v-model:value="state.selectedSchemaId"+ class="min-w-[8rem]"+ :options="schemaSelectorOptionList"+ />+ </div>+ <button+ class="flex flex-row justify-center items-center border px-3 py-1 leading-6 rounded text-sm hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="!allowCreateTable"+ @click="handleCreateNewTable"+ >+ <heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />+ {{ $t("schema-editor.actions.create-table") }}+ </button>+ </div>+ </div>+ </div>+ <div class="flex justify-end items-center">+ <NInput+ v-if="state.selectedSubtab === 'table-list'"+ v-model:value="searchPattern"+ class="!w-48 mr-3"+ :placeholder="$t('schema-editor.search-table')"+ >+ <template #prefix>+ <heroicons-outline:search class="w-4 h-auto text-gray-300" />+ </template>+ </NInput>+ <div+ class="flex flex-row justify-end items-center bg-gray-100 p-1 rounded"+ >+ <button+ class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"+ :class="+ state.selectedSubtab === 'table-list' &&+ 'bg-gray-200 text-gray-800'+ "+ @click="handleChangeTab('table-list')"+ >+ <heroicons-outline:queue-list class="inline w-4 h-auto mr-1" />+ {{ $t("schema-editor.tables") }}+ </button>+ <button+ class="px-2 leading-7 text-sm text-gray-500 cursor-pointer select-none rounded flex justify-center items-center"+ :class="+ state.selectedSubtab === 'schema-diagram' &&+ 'bg-gray-200 text-gray-800'+ "+ @click="handleChangeTab('schema-diagram')"+ >+ <SchemaDiagramIcon class="mr-1" />+ {{ $t("schema-diagram.self") }}+ </button>+ </div>+ </div>+ </div>++ <!-- List view -->+ <template v-if="state.selectedSubtab === 'table-list'">+ <!-- table list -->+ <div+ class="w-full h-auto grid auto-rows-auto border-y relative overflow-y-auto"+ >+ <!-- table header -->+ <div+ class="sticky top-0 z-10 grid grid-cols-[repeat(6,_minmax(0,_1fr))_32px] w-full border-b text-sm leading-6 select-none bg-gray-50 text-gray-400"+ >+ <span+ v-for="header in tableHeaderList"+ :key="header.key"+ class="table-header-item-container"+ >{{ header.label }}</span+ >+ <span></span>+ </div>+ <!-- table body -->+ <div class="w-full">+ <div+ v-for="(table, index) in shownTableList"+ :key="`${index}-${table.name}`"+ 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 leading-6 my-2 hover:text-accent"+ >+ <span @click="handleTableItemClick(table)">+ {{ table.name }}+ </span>+ </NEllipsis>+ </div>+ <div class="table-body-item-container">+ {{ table.rowCount }}+ </div>+ <div class="table-body-item-container">+ {{ bytesToString(table.dataSize) }}+ </div>+ <div class="table-body-item-container">+ {{ table.engine }}+ </div>+ <div class="table-body-item-container">+ {{ table.collation }}+ </div>+ <div class="table-body-item-container">+ {{ table.comment }}+ </div>+ <div class="w-full flex justify-start items-center">+ <NTooltip v-if="!isDroppedTable(table)" trigger="hover" to="body">+ <template #trigger>+ <heroicons:trash+ class="w-[14px] h-auto text-gray-500 cursor-pointer hover:opacity-80"+ @click="handleDropTable(table)"+ />+ </template>+ <span>{{ $t("schema-editor.actions.drop-table") }}</span>+ </NTooltip>+ <NTooltip v-else trigger="hover" to="body">+ <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("schema-editor.actions.restore") }}</span>+ </NTooltip>+ </div>+ </div>+ </div>+ </div>+ </template>+ <template v-else-if="state.selectedSubtab === 'schema-diagram'">+ <SchemaDiagram+ :key="currentTab.parentName"+ :database="databaseV1"+ :database-metadata="databaseMetadata"+ :schema-status="schemaStatus"+ :table-status="tableStatus"+ :column-status="columnStatus"+ :editable="true"+ @edit-table="tryEditTable"+ @edit-column="tryEditColumn"+ />+ </template>+ </div>++ <TableNameModal+ v-if="state.tableNameModalContext !== undefined"+ :parent-name="state.tableNameModalContext.parentName"+ :schema-id="state.tableNameModalContext.schemaId"+ :table-name="state.tableNameModalContext.tableName"+ @close="state.tableNameModalContext = undefined"+ />+</template>++<script lang="ts" setup>+import { head } from "lodash-es";+import { NEllipsis, NTooltip } from "naive-ui";+import scrollIntoView from "scroll-into-view-if-needed";+import { computed, nextTick, reactive, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { SchemaDiagram, SchemaDiagramIcon } from "@/components/SchemaDiagram";+import {+ generateUniqueTabId,+ useDatabaseV1Store,+ useSchemaEditorV1Store,+} from "@/store";+import { Engine } from "@/types/proto/v1/common";+import {+ ColumnMetadata,+ SchemaMetadata,+ TableMetadata,+} from "@/types/proto/v1/database_service";+import { Table } from "@/types/schemaEditor/atomType";+import {+ DatabaseTabContext,+ DatabaseSchema,+ SchemaEditorTabType,+} from "@/types/v1/schemaEditor";+import { bytesToString } from "@/utils";+import TableNameModal from "../Modals/TableNameModal.vue";+import { useMetadataForDiagram } from "../utils/useMetadataForDiagram";++type SubtabType = "table-list" | "schema-diagram";++interface LocalState {+ selectedSubtab: SubtabType;+ selectedSchemaId: string;+ isFetchingDDL: boolean;+ statement: string;+ tableNameModalContext?: {+ parentName: string;+ schemaId: string;+ tableName: string | undefined;+ };+}++const { t } = useI18n();+const editorStore = useSchemaEditorV1Store();+const searchPattern = ref("");+const currentTab = computed(() => editorStore.currentTab as DatabaseTabContext);+const state = reactive<LocalState>({+ selectedSubtab: "table-list",+ selectedSchemaId: "",+ isFetchingDDL: false,+ statement: "",+});+const databaseSchema = computed(() => {+ return editorStore.resourceMap["database"].get(+ currentTab.value.parentName+ ) as DatabaseSchema;+});+const database = computed(() => databaseSchema.value.database);+const databaseV1 = computed(() => {+ return useDatabaseV1Store().getDatabaseByUID(database.value.uid);+});+const databaseEngine = computed(() => database.value.instanceEntity.engine);+const schemaList = computed(() => {+ return databaseSchema.value.schemaList;+});+const selectedSchema = computed(() => {+ return schemaList.value.find(+ (schema) => schema.id === state.selectedSchemaId+ );+});+const tableList = computed(() => {+ return selectedSchema.value?.tableList ?? [];+});+const shownTableList = computed(() => {+ return tableList.value.filter((table) =>+ table.name.includes(searchPattern.value.trim())+ );+});++const shouldShowSchemaSelector = computed(() => {+ return databaseEngine.value === Engine.POSTGRES;+});++const allowCreateTable = computed(() => {+ if (databaseEngine.value === Engine.POSTGRES) {+ return (+ schemaList.value.length > 0 &&+ selectedSchema.value &&+ selectedSchema.value.status !== "dropped"+ );+ }+ return true;+});++const schemaSelectorOptionList = computed(() => {+ const optionList = [];+ for (const schema of schemaList.value) {+ optionList.push({+ label: schema.name,+ value: schema.id,+ });+ }+ return optionList;+});++const tableHeaderList = computed(() => {+ return [+ {+ key: "name",+ label: t("schema-editor.database.name"),+ },+ {+ key: "raw-count",+ label: t("schema-editor.database.row-count"),+ },+ {+ key: "data-size",+ label: t("schema-editor.database.data-size"),+ },+ {+ key: "engine",+ label: t("schema-editor.database.engine"),+ },+ {+ key: "collation",+ label: t("schema-editor.database.collation"),+ },+ {+ key: "comment",+ label: t("schema-editor.database.comment"),+ },+ ];+});++watch(+ [() => currentTab.value, () => schemaList],+ () => {+ const schemaIdList = schemaList.value.map((schema) => schema.id);+ if (+ currentTab.value &&+ currentTab.value.selectedSchemaId &&+ schemaIdList.includes(currentTab.value.selectedSchemaId)+ ) {+ state.selectedSchemaId = currentTab.value.selectedSchemaId;+ } else {+ state.selectedSchemaId = head(schemaIdList) || "";+ }+ },+ {+ immediate: true,+ deep: true,+ }+);++const isDroppedTable = (table: Table) => {+ return table.status === "dropped";+};++const handleChangeTab = (tab: SubtabType) => {+ state.selectedSubtab = tab;+};++const handleCreateNewTable = () => {+ const selectedSchema = schemaList.value.find(+ (schema) => schema.id === state.selectedSchemaId+ );+ if (selectedSchema) {+ state.tableNameModalContext = {+ parentName: database.value.name,+ schemaId: selectedSchema.id,+ tableName: undefined,+ };+ }+};++const handleTableItemClick = (table: Table) => {+ editorStore.addTab({+ id: generateUniqueTabId(),+ type: SchemaEditorTabType.TabForTable,+ parentName: database.value.name,+ schemaId: state.selectedSchemaId,+ tableId: table.id,+ });+};++const handleDropTable = (table: Table) => {+ editorStore.dropTable(database.value.uid, state.selectedSchemaId, table.id);+};++const handleRestoreTable = (table: Table) => {+ editorStore.restoreTable(+ database.value.uid,+ state.selectedSchemaId,+ table.id+ );+};++const {+ databaseMetadata,+ schemaStatus,+ tableStatus,+ columnStatus,+ editableSchema,+ editableTable,+ editableColumn,+} = useMetadataForDiagram(databaseSchema);++const tryEditTable = async (+ schemaMeta: SchemaMetadata,+ tableMeta: TableMetadata+) => {+ const schema = editableSchema(schemaMeta);+ const table = editableTable(tableMeta);+ if (schema && table) {+ state.selectedSchemaId = schema.id;+ await nextTick();+ handleTableItemClick(table);+ }+};++const tryEditColumn = async (+ schemaMeta: SchemaMetadata,+ tableMeta: TableMetadata,+ columnMeta: ColumnMetadata,+ target: "name" | "type"+) => {+ const schema = editableSchema(schemaMeta);+ const table = editableTable(tableMeta);+ const column = editableColumn(columnMeta);+ if (schema && table && column) {+ await tryEditTable(schemaMeta, tableMeta);+ await nextTick();+ const container = document.querySelector("#table-editor-container");+ const input = container?.querySelector(+ `.column-${column.id} .column-${target}-input`+ ) as HTMLInputElement | undefined;+ if (input) {+ input.focus();+ scrollIntoView(input);+ }+ }+};+</script>++<style scoped>+.table-header-item-container {+ @apply py-2 px-3;+}+.table-body-item-container {+ @apply w-full h-10 box-border p-px pl-3 pr-4 relative truncate leading-10;+}+</style>diff --git a/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vue b/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vueindex c3926d248a..01ad321437 100644--- a/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vue+++ b/frontend/src/components/SchemaEditorV1/Panels/TableEditor.vue@@ -292,10 +292,8 @@ import {useSettingV1Store,useSchemaEditorV1Store,} from "@/store/modules";-import { ComposedDatabase } from "@/types";import { Engine } from "@/types/proto/v1/common";import { ColumnMetadata } from "@/types/proto/v1/database_service";-import { SchemaDesign } from "@/types/proto/v1/schema_design_service";import { SchemaTemplateSetting_FieldTemplate } from "@/types/proto/v1/setting_service";import {Column,@@ -324,6 +322,7 @@ const settingStore = useSettingV1Store();const currentTab = computed(() => schemaEditorV1Store.currentTab as TableTabContext);+const parentResouce = computed(() => {return schemaEditorV1Store.resourceMap[schemaEditorV1Store.resourceType].get(currentTab.value.parentName@@ -331,10 +330,9 @@ const parentResouce = computed(() => {});const engine = computed(() => {if (schemaEditorV1Store.resourceType === "branch") {- return (parentResouce.value as any as SchemaDesign).engine;+ return (parentResouce.value as any).branch.engine;} else if (schemaEditorV1Store.resourceType === "database") {- return (parentResouce.value as any as ComposedDatabase).instanceEntity- .engine;+ return (parentResouce.value as any).database.instanceEntity.engine;} else {return Engine.MYSQL;}diff --git a/frontend/src/components/SchemaEditorV1/TabsContainer.vue b/frontend/src/components/SchemaEditorV1/TabsContainer.vueindex 074fecf1fa..eca64cb84c 100644--- a/frontend/src/components/SchemaEditorV1/TabsContainer.vue+++ b/frontend/src/components/SchemaEditorV1/TabsContainer.vue@@ -96,12 +96,17 @@ const getTabComputedClassList = (tab: TabContext) => {};const getTabName = (tab: TabContext) => {- if (tab.type === SchemaEditorTabType.TabForTable) {+ if (tab.type === SchemaEditorTabType.TabForDatabase) {+ const database = schemaEditorV1Store.databaseList.find(+ (database) => database.name === tab.parentName+ );+ return database?.databaseName || "Uknown database";+ } else if (tab.type === SchemaEditorTabType.TabForTable) {const table = schemaEditorV1Store.getTableWithTableTab(tab);- return table?.name || "Uknown tab";+ return table?.name || "Uknown table";} else {// Should never reach here.- return "unknown structure";+ return "unknown tab";}};diff --git a/frontend/src/components/SchemaEditorV1/utils/useMetadataForDiagram.ts b/frontend/src/components/SchemaEditorV1/utils/useMetadataForDiagram.tsnew file mode 100644index 0000000000..8b08edbdf0--- /dev/null+++ b/frontend/src/components/SchemaEditorV1/utils/useMetadataForDiagram.ts@@ -0,0 +1,221 @@+import { computed, unref } from "vue";+import { EditStatus } from "@/components/SchemaDiagram";+import { ComposedDatabase, MaybeRef } from "@/types";+import {+ ColumnMetadata,+ DatabaseMetadata,+ ForeignKeyMetadata,+ IndexMetadata,+ SchemaMetadata,+ TableMetadata,+} from "@/types/proto/v1/database_service";+import { DatabaseSchema, Column, Schema, Table } from "@/types/v1/schemaEditor";+import { isColumnChanged } from "./column";+import { isSchemaChanged } from "./schema";+import { isTableChanged } from "./table";++type MetadataWithEditStatus<T, E> = T & {+ $$status?: EditStatus;+ $$edit?: E;+};++const statusOfSchema = (database: ComposedDatabase, schema: Schema) => {+ const { status } = schema;+ if (status === "created" || status === "dropped") {+ return status;+ }+ if (isSchemaChanged(database.name, schema.id)) {+ return "changed";+ }+ return "normal";+};++const statusOfTable = (+ database: ComposedDatabase,+ schema: Schema,+ table: Table+): EditStatus => {+ const { status } = table;+ if (status === "created" || status === "dropped") {+ return status;+ }+ if (isTableChanged(database.name, schema.id, table.id)) {+ return "changed";+ }++ return "normal";+};++const statusOfColumn = (+ database: ComposedDatabase,+ schema: Schema,+ table: Table,+ column: Column+): EditStatus => {+ const { status } = column;+ if (status === "created" || status === "dropped") {+ return status;+ }+ if (isColumnChanged(database.name, schema.id, table.id, column.id)) {+ return "changed";+ }++ return "normal";+};++export const useMetadataForDiagram = (+ databaseSchema: MaybeRef<DatabaseSchema>+) => {+ const databaseMetadata = computed(() => {+ const { database, schemaList } = unref(databaseSchema);+ const databaseMeta = DatabaseMetadata.fromPartial({});+ databaseMeta.name = database.name;+ databaseMeta.schemas = schemaList.map((schema) => {+ const schemaMeta = SchemaMetadata.fromPartial({});+ Object.defineProperty(schemaMeta, "$$status", {+ enumerable: false,+ value: statusOfSchema(database, schema),+ });+ Object.defineProperty(schemaMeta, "$$edit", {+ enumerable: false,+ value: schema,+ });++ schemaMeta.name = schema.name;+ schemaMeta.tables = schema.tableList.map((table) => {+ const tableMeta = TableMetadata.fromPartial({});+ Object.defineProperty(tableMeta, "$$status", {+ enumerable: false,+ value: statusOfTable(database, schema, table),+ });+ Object.defineProperty(tableMeta, "$$edit", {+ enumerable: false,+ value: table,+ });++ tableMeta.name = table.name;+ tableMeta.engine = table.engine;+ tableMeta.collation = table.collation;+ tableMeta.rowCount = table.rowCount;+ tableMeta.dataSize = table.dataSize;+ tableMeta.comment = table.comment;++ tableMeta.columns = table.columnList.map((column) => {+ const columnMeta = ColumnMetadata.fromPartial({});+ Object.defineProperty(columnMeta, "$$status", {+ enumerable: false,+ value: statusOfColumn(database, schema, table, column),+ });+ Object.defineProperty(columnMeta, "$$edit", {+ enumerable: false,+ value: column,+ });++ columnMeta.name = column.name;+ columnMeta.type = column.type;+ columnMeta.nullable = column.nullable;+ columnMeta.comment = column.comment;+ columnMeta.default = column.default;++ return columnMeta;+ });++ // We don't have indexes other than primary key in Schema Editor,+ // so something will lost here when converting Table back to+ // TableMetadata.+ // But they will be back soon when editing indexes is supported in+ // Schema Editor.+ const pk = IndexMetadata.fromPartial({});+ Object.assign(pk, {+ primary: true,+ name: table.primaryKey.name,+ expressions: table.primaryKey.columnIdList.map(+ (id) => table.columnList.find((col) => col.id === id)!.name+ ),+ });+ tableMeta.indexes = [pk];++ tableMeta.foreignKeys = table.foreignKeyList.map((fk) => {+ // In PostgreSQL, foreign keys can cross different schemas.+ // So we need to search the schemaList here.+ const refSchema = schemaList.find(+ (schema) => schema.id === fk.referencedSchemaId+ )!;+ const refTable = refSchema.tableList.find(+ (table) => table.id === fk.referencedTableId+ )!;+ const fkMeta = ForeignKeyMetadata.fromPartial({});+ Object.assign(fkMeta, {+ columns: fk.columnIdList.map(+ (id) => table.columnList.find((col) => col.id === id)!.name+ ),+ name: fk.name,+ referencedSchema: refSchema.name,+ referencedTable: refTable.name,+ referencedColumns: fk.referencedColumnIdList.map(+ (id) => refTable.columnList.find((col) => col.id === id)!.name+ ),+ });+ return fkMeta;+ });+ return tableMeta;+ });+ return schemaMeta;+ });++ return databaseMeta;+ });++ const schemaStatus = (schemaMeta: SchemaMetadata): EditStatus => {+ const status = (schemaMeta as MetadataWithEditStatus<SchemaMetadata, Table>)+ .$$status;+ if (typeof status !== "undefined") {+ return status;+ }+ return "normal";+ };+ const tableStatus = (tableMeta: TableMetadata): EditStatus => {+ const status = (tableMeta as MetadataWithEditStatus<TableMetadata, Table>)+ .$$status;+ if (typeof status !== "undefined") {+ return status;+ }+ return "normal";+ };+ const columnStatus = (columnMeta: ColumnMetadata): EditStatus => {+ const status = (+ columnMeta as MetadataWithEditStatus<ColumnMetadata, Column>+ ).$$status;+ if (typeof status !== "undefined") {+ return status;+ }+ return "normal";+ };+ const editableSchema = (schemaMeta: SchemaMetadata) => {+ const schema = (+ schemaMeta as MetadataWithEditStatus<SchemaMetadata, Schema>+ ).$$edit;+ return schema;+ };+ const editableTable = (tableMeta: TableMetadata) => {+ const table = (tableMeta as MetadataWithEditStatus<TableMetadata, Table>)+ .$$edit;+ return table;+ };+ const editableColumn = (columnMeta: ColumnMetadata) => {+ const column = (+ columnMeta as MetadataWithEditStatus<ColumnMetadata, Column>+ ).$$edit;+ return column;+ };++ return {+ databaseMetadata,+ schemaStatus,+ tableStatus,+ columnStatus,+ editableSchema,+ editableTable,+ editableColumn,+ };+};diff --git a/frontend/src/utils/schemaEditor/diffSchema.ts b/frontend/src/utils/schemaEditor/diffSchema.tsindex ef1047f490..9b51308528 100644--- a/frontend/src/utils/schemaEditor/diffSchema.ts+++ b/frontend/src/utils/schemaEditor/diffSchema.ts@@ -1,5 +1,5 @@import { isEqual, isUndefined } from "lodash-es";-import { useSchemaEditorStore } from "@/store";+import { useSchemaEditorV1Store } from "@/store";import {AlterTableContext,CreateSchemaContext,@@ -9,7 +9,7 @@ import {RenameSchemaContext,RenameTableContext,} from "@/types";-import { Schema } from "@/types/schemaEditor/atomType";+import { Schema } from "@/types/v1/schemaEditor";import { diffColumnList } from "./diffColumn";import { transformTableToCreateTableContext } from "./transform";@@ -24,11 +24,11 @@ interface DiffResult {}export const diffSchema = (- databaseId: string,+ database: string,originSchema: Schema | undefined,schema: Schema): DiffResult => {- const editorStore = useSchemaEditorStore();+ const schemaEditorV1Store = useSchemaEditorV1Store();const createSchemaContextList: CreateSchemaContext[] = [];const renameSchemaContextList: RenameSchemaContext[] = [];const dropSchemaContextList: DropSchemaContext[] = [];@@ -65,16 +65,16 @@ export const diffSchema = (createTableContext.primaryKeyList.push(column.name);}}- const foreignKeyList = schema.foreignKeyList.filter(+ const foreignKeyList = table.foreignKeyList.filter((fk) => fk.tableId === table.id);for (const foreignKey of foreignKeyList) {- const referencedSchema = editorStore.getSchema(- databaseId,+ const referencedSchema = schemaEditorV1Store.getSchema(+ database,foreignKey.referencedSchemaId);- const referencedTable = editorStore.getTable(- databaseId,+ const referencedTable = schemaEditorV1Store.getTable(+ database,foreignKey.referencedSchemaId,foreignKey.referencedTableId);@@ -124,10 +124,10 @@ export const diffSchema = (const originPrimaryKey = originTable.primaryKey;const primaryKey = table.primaryKey;- const originForeignKeyList = originSchema?.foreignKeyList.filter(+ const originForeignKeyList = originTable.foreignKeyList.filter((fk) => fk.tableId === table.id);- const foreignKeyList = schema.foreignKeyList.filter(+ const foreignKeyList = table.foreignKeyList.filter((fk) => fk.tableId === table.id);@@ -221,8 +221,8 @@ export const diffSchema = (foreignKey.columnIdList.length ===foreignKey.referencedColumnIdList.length) {- const referencedSchema = editorStore.getSchema(- databaseId,+ const referencedSchema = schemaEditorV1Store.getSchema(+ database,foreignKey.referencedSchemaId);const referencedTable = referencedSchema?.tableList.find(