Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: implement schema designer (#7124)
boojackc951be9db805
diff --git a/backend/api/v1/schema_design_service.go b/backend/api/v1/schema_design_service.goindex 6964451510..b4119724dc 100644--- a/backend/api/v1/schema_design_service.go+++ b/backend/api/v1/schema_design_service.go@@ -147,26 +147,39 @@ func (s *SchemaDesignService) CreateSchemaDesign(ctx context.Context, request *vif database == nil {return nil, status.Errorf(codes.NotFound, "database %q not found", databaseName)}- schemaVersionUID, err := strconv.ParseInt(schemaDesign.SchemaVersion, 10, 64)- if err != nil || schemaVersionUID <= 0 {+ instanceID, _, changeHistoryIDStr, err := getInstanceDatabaseIDChangeHistory(schemaDesign.SchemaVersion)+ if err != nil {+ return nil, status.Errorf(codes.InvalidArgument, err.Error())+ }+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{+ ResourceID: &instanceID,+ })+ if err != nil {+ return nil, status.Errorf(codes.Internal, err.Error())+ }+ schemaVersionID, err := strconv.ParseInt(changeHistoryIDStr, 10, 64)+ if err != nil || schemaVersionID <= 0 {return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("invalid schema version %s, must be positive integer", schemaDesign.SchemaVersion))}changeHistory, err := s.store.GetInstanceChangeHistory(ctx, &store.FindInstanceChangeHistoryMessage{- ID: &schemaVersionUID,+ ID: &schemaVersionID,+ InstanceID: &instance.UID,})if err != nil {return nil, status.Errorf(codes.Internal, err.Error())}if changeHistory == nil {- return nil, status.Errorf(codes.NotFound, "schema version %d not found", schemaVersionUID)+ return nil, status.Errorf(codes.NotFound, "schema version %d not found", schemaVersionID)}schemaDesignSheetPayload := &storepb.SheetPayload{Type: storepb.SheetPayload_SCHEMA_DESIGN,SchemaDesign: &storepb.SheetPayload_SchemaDesign{- BaselineSheetId: int64(*changeHistory.SheetID),- Engine: storepb.Engine(schemaDesign.Engine),+ Engine: storepb.Engine(schemaDesign.Engine),},}+ if changeHistory.SheetID != nil {+ schemaDesignSheetPayload.SchemaDesign.BaselineSheetId = int64(*changeHistory.SheetID)+ }payloadBytes, err := protojson.Marshal(schemaDesignSheetPayload)if err != nil {return nil, status.Errorf(codes.Internal, fmt.Sprintf("failed to marshal schema design sheet payload: %v", err))@@ -201,6 +214,7 @@ func (s *SchemaDesignService) CreateSchemaDesign(ctx context.Context, request *v// UpdateSchemaDesign updates an existing schema design.func (s *SchemaDesignService) UpdateSchemaDesign(ctx context.Context, request *v1pb.UpdateSchemaDesignRequest) (*v1pb.SchemaDesign, error) {+ currentPrincipalID := ctx.Value(common.PrincipalIDContextKey).(int)_, sheetID, err := getProjectResourceIDAndSchemaDesignSheetID(request.SchemaDesign.Name)if err != nil {return nil, status.Errorf(codes.InvalidArgument, err.Error())@@ -212,18 +226,24 @@ func (s *SchemaDesignService) UpdateSchemaDesign(ctx context.Context, request *vif request.UpdateMask == nil {return nil, status.Errorf(codes.InvalidArgument, "update_mask is required")}- if !slices.Contains(request.UpdateMask.Paths, "schema") {- return nil, status.Errorf(codes.InvalidArgument, "schema is required")+ if len(request.UpdateMask.Paths) == 0 {+ return nil, status.Errorf(codes.InvalidArgument, "update_mask is required")}- schemaDesign := request.SchemaDesign- schema, err := getDesignSchema(schemaDesign.Engine, schemaDesign.BaselineSchema, schemaDesign.SchemaMetadata)- if err != nil {- return nil, err- }sheetUpdate := &store.PatchSheetMessage{UID: sheetUID,- Statement: &schema,+ UpdaterID: currentPrincipalID,+ }+ schemaDesign := request.SchemaDesign+ if slices.Contains(request.UpdateMask.Paths, "title") {+ sheetUpdate.Name = &schemaDesign.Title+ }+ if slices.Contains(request.UpdateMask.Paths, "schema") {+ schema, err := getDesignSchema(schemaDesign.Engine, schemaDesign.BaselineSchema, schemaDesign.SchemaMetadata)+ if err != nil {+ return nil, err+ }+ sheetUpdate.Statement = &schema}sheet, err := s.store.PatchSheet(ctx, sheetUpdate)if err != nil {diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vueindex 61dd93772c..92139fb1ce 100644--- a/frontend/src/components/QuickActionPanel.vue+++ b/frontend/src/components/QuickActionPanel.vue@@ -79,6 +79,22 @@{{ $t("database.change-data") }}</h3></div>++ <div+ v-if="+ isDev() && quickAction === 'quickaction.bb.database.schema.design'+ "+ class="flex flex-col items-center w-24"+ >+ <button class="btn-icon-primary p-3" @click.prevent="designSchema">+ <heroicons-outline:table-cells class="w-5 h-5" />+ </button>+ <h3+ class="flex-1 mt-1.5 text-center text-sm font-normal text-main tracking-tight"+ >+ {{ $t("schema-designer.quick-action") }}+ </h3>+ </div></template><div@@ -261,6 +277,11 @@:type="'bb.issue.database.data.update'"@dismiss="state.quickActionType = undefined"/>+ <DesignSchemaPrepForm+ v-if="state.quickActionType === 'quickaction.bb.database.schema.design'"+ :project-id="projectId"+ @dismiss="state.quickActionType = undefined"+ /><TransferDatabaseFormv-if="projectId &&@@ -327,6 +348,7 @@ import TransferDatabaseForm from "@/components/TransferDatabaseForm.vue";import TransferOutDatabaseForm from "@/components/TransferOutDatabaseForm";import RequestExportPanel from "@/components/Issue/panel/RequestExportPanel/index.vue";import RequestQueryPanel from "@/components/Issue/panel/RequestQueryPanel/index.vue";+import DesignSchemaPrepForm from "@/components/SchemaDesigner/PrepForm/index.vue";interface LocalState {feature?: string;@@ -409,6 +431,10 @@ const alterSchema = () => {state.quickActionType = "quickaction.bb.database.schema.update";};+const designSchema = () => {+ state.quickActionType = "quickaction.bb.database.schema.design";+};+const changeData = () => {state.quickActionType = "quickaction.bb.database.data.update";};diff --git a/frontend/src/components/SchemaDesigner/BaselineSchemaSelector.vue b/frontend/src/components/SchemaDesigner/BaselineSchemaSelector.vuenew file mode 100644index 0000000000..b1d4faf54e--- /dev/null+++ b/frontend/src/components/SchemaDesigner/BaselineSchemaSelector.vue@@ -0,0 +1,266 @@+<template>+ <div+ class="w-full mx-auto flex flex-col justify-start items-start space-y-3 mb-6"+ >+ <div class="w-full flex flex-row justify-start items-center">+ <span class="flex w-40 items-center shrink-0 text-sm">+ {{ $t("common.project") }}+ </span>+ <ProjectSelect+ class="!w-60 shrink-0"+ :selected-id="state.projectId"+ @select-project-id="handleProjectSelect"+ />+ </div>+ <div class="w-full flex flex-row justify-start items-center">+ <span class="flex w-40 items-center shrink-0 text-sm">+ {{ $t("common.database") }}+ </span>+ <EnvironmentSelect+ class="!w-60 mr-4 shrink-0"+ name="environment"+ :selected-id="state.environmentId"+ :select-default="false"+ @select-environment-id="handleEnvironmentSelect"+ />+ <DatabaseSelect+ class="!w-128"+ :selected-id="state.databaseId ?? String(UNKNOWN_ID)"+ :mode="'USER'"+ :environment-id="state.environmentId"+ :project-id="state.projectId"+ :engine-type-list="allowedEngineTypeList"+ :sync-status="'OK'"+ :customize-item="true"+ @select-database-id="handleDatabaseSelect"+ >+ <template #customizeItem="{ database: db }">+ <div class="flex items-center">+ <InstanceV1EngineIcon :instance="db.instanceEntity" />+ <span class="mx-2">{{ db.databaseName }}</span>+ <span class="text-gray-400">+ ({{ instanceV1Name(db.instanceEntity) }})+ </span>+ </div>+ </template>+ </DatabaseSelect>+ </div>+ <div class="w-full flex flex-row justify-start items-center">+ <span class="flex w-40 items-center shrink-0 text-sm">+ {{ $t("schema-designer.schema-version") }}+ </span>+ <div+ class="w-192 flex flex-row justify-start items-center relative"+ :class="isValidId(state.projectId) ? '' : 'opacity-50'"+ >+ <BBSelect+ class="w-full"+ :selected-item="state.changeHistory"+ :item-list="+ databaseChangeHistoryList(state.databaseId as string)+ "+ :placeholder="$t('change-history.select')"+ :show-prefix-item="databaseChangeHistoryList(state.databaseId as string).length > 0"+ @select-item="(changeHistory: ChangeHistory) => handleSchemaVersionSelect(changeHistory)"+ >+ <template+ #menuItem="{+ item: changeHistory,+ index,+ }: {+ item: ChangeHistory,+ index: number,+ }"+ >+ <div class="flex justify-between mr-2">+ <FeatureBadge+ v-if="index > 0"+ feature="bb.feature.sync-schema-all-versions"+ custom-class="mr-1"+ :instance="database?.instanceEntity"+ />+ <NEllipsis class="flex-1 pr-2" :tooltip="false">+ {{ changeHistory.version }} -+ {{ changeHistory.description }}+ </NEllipsis>+ <span class="text-control-light">+ {{ humanizeDate(changeHistory.updateTime) }}+ </span>+ </div>+ </template>+ </BBSelect>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import {+ useChangeHistoryStore,+ useDBSchemaV1Store,+ useDatabaseV1Store,+} from "@/store";+import { UNKNOWN_ID } from "@/types";+import { Engine } from "@/types/proto/v1/common";+import {+ ChangeHistory,+ ChangeHistoryView,+ ChangeHistory_Type,+} from "@/types/proto/v1/database_service";+import { isNull, isUndefined } from "lodash-es";+import { computed, onMounted, reactive, ref, watch } from "vue";+import { instanceV1Name } from "@/utils";++interface BaselineSchema {+ projectId?: string;+ databaseId?: string;+ changeHistory?: ChangeHistory;+}++const props = defineProps<{+ baselineSchema?: BaselineSchema;+}>();++const emit = defineEmits<{+ (event: "update", state: LocalState): void;+}>();++interface LocalState {+ projectId?: string;+ environmentId?: string;+ databaseId?: string;+ changeHistory?: ChangeHistory;+}++const state = reactive<LocalState>({});+const databaseStore = useDatabaseV1Store();+const dbSchemaStore = useDBSchemaV1Store();+const changeHistoryStore = useChangeHistoryStore();+const fullViewChangeHistoryCache = ref<Map<string, ChangeHistory>>(new Map());++const database = computed(() => {+ const databaseId = state.databaseId;+ if (!isValidId(databaseId)) {+ return;+ }+ return databaseStore.getDatabaseByUID(databaseId);+});++const prepareChangeHistoryList = async () => {+ if (!database.value) {+ return;+ }++ await changeHistoryStore.fetchChangeHistoryList({+ parent: database.value.name,+ });+};++onMounted(async () => {+ if (props.baselineSchema?.databaseId) {+ try {+ const database = await databaseStore.getOrFetchDatabaseByUID(+ props.baselineSchema.databaseId || ""+ );+ state.projectId = props.baselineSchema.projectId;+ state.databaseId = database.uid;+ state.environmentId = database.instanceEntity.environmentEntity.uid;+ state.changeHistory = props.baselineSchema.changeHistory;+ } catch (error) {+ // do nothing.+ }+ }+});++watch(() => state.databaseId, prepareChangeHistoryList);++const prepareFullViewChangeHistory = async () => {+ const changeHistory = state.changeHistory;+ if (!changeHistory || changeHistory.uid === String(UNKNOWN_ID)) {+ return;+ }++ const cache = fullViewChangeHistoryCache.value.get(changeHistory.name);+ if (!cache) {+ const fullViewChangeHistory = await changeHistoryStore.fetchChangeHistory({+ name: changeHistory.name,+ view: ChangeHistoryView.CHANGE_HISTORY_VIEW_FULL,+ });+ fullViewChangeHistoryCache.value.set(+ fullViewChangeHistory.name,+ fullViewChangeHistory+ );+ }+};++watch(() => state.changeHistory, prepareFullViewChangeHistory, {+ immediate: true,+ deep: true,+});++const allowedEngineTypeList: Engine[] = [Engine.MYSQL];+const allowedMigrationTypeList: ChangeHistory_Type[] = [+ ChangeHistory_Type.BASELINE,+ ChangeHistory_Type.MIGRATE,+ ChangeHistory_Type.BRANCH,+];++const isValidId = (id: any): id is string => {+ if (isNull(id) || isUndefined(id) || String(id) === String(UNKNOWN_ID)) {+ return false;+ }+ return true;+};++const handleProjectSelect = async (projectId: string) => {+ if (projectId !== state.projectId) {+ state.databaseId = String(UNKNOWN_ID);+ }+ state.projectId = projectId;+};++const handleEnvironmentSelect = async (environmentId: string) => {+ if (environmentId !== state.environmentId) {+ state.databaseId = String(UNKNOWN_ID);+ }+ state.environmentId = environmentId;+};++const handleDatabaseSelect = async (databaseId: string) => {+ if (isValidId(databaseId)) {+ const database = databaseStore.getDatabaseByUID(databaseId);+ if (!database) {+ return;+ }+ state.projectId = database.projectEntity.uid;+ state.environmentId = database.instanceEntity.environmentEntity.uid;+ state.databaseId = databaseId;+ dbSchemaStore.getOrFetchDatabaseMetadata(database.name);+ }+};++const databaseChangeHistoryList = (databaseId: string) => {+ const database = databaseStore.getDatabaseByUID(databaseId);+ const list = changeHistoryStore+ .changeHistoryListByDatabase(database.name)+ .filter((changeHistory) =>+ allowedMigrationTypeList.includes(changeHistory.type)+ );++ return list;+};++const handleSchemaVersionSelect = (changeHistory: ChangeHistory) => {+ state.changeHistory = changeHistory;+};++watch(+ () => state,+ () => {+ emit("update", {+ ...state,+ });+ },+ { deep: true }+);+</script>diff --git a/frontend/src/components/SchemaDesigner/DatabaseTree.vue b/frontend/src/components/SchemaDesigner/DatabaseTree.vueindex 26c6c4a70c..dc9fbc12ca 100644--- a/frontend/src/components/SchemaDesigner/DatabaseTree.vue+++ b/frontend/src/components/SchemaDesigner/DatabaseTree.vue@@ -1,6 +1,16 @@<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">+ <div class="w-full h-full px-2 relative overflow-y-hidden">+ <div class="w-full flex flex-col sticky top-0 pt-2 h-20 bg-white z-10">+ <p class="w-full flex flex-row justify-between items-center h-8 px-1">+ <span class="text-sm">{{ $t("schema-designer.tables") }}</span>+ <button+ class="text-gray-400 hover:text-gray-500"+ :disabled="readonly"+ @click="handleCreateTable"+ >+ <heroicons-outline:plus class="w-4 h-auto" />+ </button>+ </p><NInputv-model:value="searchPattern":placeholder="$t('schema-editor.search-database-and-table')"@@ -46,7 +56,7 @@<TableNameModalv-if="state.tableNameModalContext !== undefined"- :schema="state.tableNameModalContext.schema"+ :schema-id="state.tableNameModalContext.schemaId"@close="state.tableNameModalContext = undefined"/></template>@@ -54,19 +64,19 @@<script lang="ts" setup>import { escape, isUndefined } from "lodash-es";import { TreeOption, NEllipsis, NInput, NDropdown, NTree } from "naive-ui";-import { computed, onMounted, watch, ref, h, reactive, nextTick } from "vue";+import { computed, watch, ref, h, reactive, nextTick } from "vue";import { useI18n } from "vue-i18n";import scrollIntoView from "scroll-into-view-if-needed";import SchemaIcon from "~icons/heroicons-outline/view-columns";import TableIcon from "~icons/heroicons-outline/table-cells";import EllipsisIcon from "~icons/heroicons-solid/ellipsis-horizontal";+import { Engine } from "@/types/proto/v1/common";+import { useSchemaDesignerContext, SchemaDesignerTabType } from "./common";import { generateUniqueTabId } from "@/store";import { getHighlightHTMLByKeyWords, isDescendantOf } from "@/utils";import SchemaNameModal from "./Modals/SchemaNameModal.vue";import TableNameModal from "./Modals/TableNameModal.vue";-import { Engine } from "@/types/proto/v1/common";-import { useSchemaDesignerContext, SchemaDesignerTabType } from "./common";interface BaseTreeNode extends TreeOption {key: string;@@ -77,13 +87,13 @@ interface BaseTreeNode extends TreeOption {interface TreeNodeForSchema extends BaseTreeNode {type: "schema";- schema: string;+ schemaId: string;}interface TreeNodeForTable extends BaseTreeNode {type: "table";- schema: string;- table: string;+ schemaId: string;+ tableId: string;}type TreeNode = TreeNodeForSchema | TreeNodeForTable;@@ -101,18 +111,18 @@ interface LocalState {databaseId: string;};tableNameModalContext?: {- schema: string;+ schemaId: string;};}const { t } = useI18n();const {+ readonly,engine,- metadata,+ editableSchemas,tabState,addTab,getCurrentTab,- dropSchema,dropTable,} = useSchemaDesignerContext();const state = reactive<LocalState>({@@ -130,9 +140,9 @@ const expandedKeysRef = ref<string[]>([]);const selectedKeysRef = ref<string[]>([]);const treeDataRef = ref<TreeNode[]>([]);-const schemaList = computed(() => Array.from(metadata.value.schemas));+const schemaList = computed(() => editableSchemas.value);const tableList = computed(() =>- schemaList.value.map((schema) => schema.tables).flat()+ schemaList.value.map((schema) => schema.tableList).flat());const contextMenuOptions = computed(() => {const treeNode = contextMenu.treeNode;@@ -144,7 +154,7 @@ const contextMenuOptions = computed(() => {const options = [];if (engine === Engine.POSTGRES) {const schema = schemaList.value.find(- (schema) => schema.name === treeNode.schema+ (schema) => schema.id === treeNode.schemaId);if (!schema) {return [];@@ -153,22 +163,26 @@ const contextMenuOptions = computed(() => {options.push({key: "create-table",label: t("schema-editor.actions.create-table"),+ disabled: readonly,});options.push({key: "drop-schema",label: t("schema-editor.actions.drop-schema"),+ disabled: readonly,});}return options;} else if (treeNode.type === "table") {const schema = schemaList.value.find(- (schema) => schema.name === treeNode.schema+ (schema) => schema.id === treeNode.schemaId);if (!schema) {return [];}- const table = schema.tables.find((table) => table.name === treeNode.table);+ const table = schema.tableList.find(+ (table) => table.id === treeNode.tableId+ );if (!table) {return [];}@@ -177,6 +191,7 @@ const contextMenuOptions = computed(() => {options.push({key: "drop",label: t("schema-editor.actions.drop-table"),+ disabled: readonly,});return options;}@@ -184,46 +199,57 @@ const contextMenuOptions = computed(() => {return [];});-onMounted(async () => {- const treeNodeList: TreeNode[] = [];- if (engine === Engine.MYSQL) {- for (const table of tableList.value) {- const tableTreeNode: TreeNodeForTable = {- type: "table",- key: `t-${table.name}`,- label: table.name,- isLeaf: true,- schema: "",- table: table.name,- };- treeNodeList.push(tableTreeNode);- }- } else {- for (const schema of schemaList.value) {- const schemaTreeNode: TreeNodeForSchema = {- type: "schema",- key: `s-${schema.name}`,- label: schema.name,- isLeaf: false,- schema: schema.name,- };- treeNodeList.push(schemaTreeNode);- for (const table of schema.tables) {+watch(+ () => [schemaList.value, tableList.value],+ () => {+ const treeNodeList: TreeNode[] = [];+ if (engine === Engine.MYSQL) {+ const schema = schemaList.value[0];+ if (!schema) {+ return;+ }+ for (const table of tableList.value) {const tableTreeNode: TreeNodeForTable = {type: "table",- key: `t-${schema.name}-${table.name}`,+ key: `t-${table.id}`,label: table.name,isLeaf: true,- schema: schema.name,- table: table.name,+ schemaId: schema.id,+ tableId: table.id,};- schemaTreeNode.children?.push(tableTreeNode);+ treeNodeList.push(tableTreeNode);+ }+ } else {+ for (const schema of schemaList.value) {+ const schemaTreeNode: TreeNodeForSchema = {+ type: "schema",+ key: `s-${schema.id}`,+ label: schema.name,+ isLeaf: false,+ schemaId: schema.id,+ };+ treeNodeList.push(schemaTreeNode);+ for (const table of schema.tableList) {+ const tableTreeNode: TreeNodeForTable = {+ type: "table",+ key: `t-${schema.id}-${table.id}`,+ label: table.name,+ isLeaf: true,+ schemaId: schema.id,+ tableId: table.id,+ };+ schemaTreeNode.children?.push(tableTreeNode);+ }}}- }- treeDataRef.value = treeNodeList;-});+ treeDataRef.value = treeNodeList;+ },+ {+ immediate: true,+ deep: true,+ }+);watch(() => tabState.value.currentTabId,@@ -235,11 +261,11 @@ watch(}if (currentTab.type === SchemaDesignerTabType.TabForTable) {- const schemaTreeNodeKey = `s-${currentTab.schema}`;+ const schemaTreeNodeKey = `s-${currentTab.schemaId}`;if (!expandedKeysRef.value.includes(schemaTreeNodeKey)) {expandedKeysRef.value.push(schemaTreeNodeKey);}- const tableTreeNodeKey = `t-${currentTab.schema}-${currentTab.table}`;+ const tableTreeNodeKey = `t-${currentTab.schemaId}-${currentTab.tableId}`;selectedKeysRef.value = [tableTreeNodeKey];}@@ -274,6 +300,22 @@ const renderPrefix = ({ option: treeNode }: { option: TreeNode }) => {const renderLabel = ({ option: treeNode }: { option: TreeNode }) => {const additionalClassList: string[] = ["select-none"];+ if (treeNode.type === "schema") {+ // do nothing+ } else if (treeNode.type === "table") {+ const table = tableList.value.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");+ }+ }+ }+return h(NEllipsis,{@@ -318,6 +360,15 @@ const handleShowDropdown = (e: MouseEvent, treeNode: TreeNode) => {selectedKeysRef.value = [treeNode.key];};+const handleCreateTable = () => {+ if (engine === Engine.MYSQL) {+ const schema = editableSchemas.value[0];+ state.tableNameModalContext = {+ schemaId: schema.id,+ };+ }+};+// Set event handler to tree nodes.const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {return {@@ -331,8 +382,8 @@ const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {addTab({id: generateUniqueTabId(),type: SchemaDesignerTabType.TabForTable,- schema: treeNode.schema,- table: treeNode.table,+ schemaId: treeNode.schemaId,+ tableId: treeNode.tableId,});}@@ -358,17 +409,19 @@ const nodeProps = ({ option: treeNode }: { option: TreeNode }) => {const handleContextMenuDropdownSelect = async (key: string) => {const treeNode = contextMenu.treeNode;- if (treeNode?.type === "schema") {+ if (!treeNode) {+ return;+ }++ if (treeNode.type === "schema") {if (key === "create-table") {state.tableNameModalContext = {- schema: treeNode.schema,+ schemaId: treeNode.schemaId,};- } else if (key === "drop-schema") {- dropSchema(treeNode.schema);}- } else if (treeNode?.type === "table") {+ } else if (treeNode.type === "table") {if (key === "drop") {- dropTable(treeNode.schema, treeNode.table);+ dropTable(treeNode.schemaId, treeNode.tableId);}}contextMenu.showDropdown = false;diff --git a/frontend/src/components/SchemaDesigner/Designer.vue b/frontend/src/components/SchemaDesigner/Designer.vuenew file mode 100644index 0000000000..1028384cbf--- /dev/null+++ b/frontend/src/components/SchemaDesigner/Designer.vue@@ -0,0 +1,21 @@+<template>+ <main class="px-2 pt-2 w-full h-full flex flex-col overflow-y-auto">+ <template v-if="currentTab">+ <TabsContainer />+ <div :key="currentTab.id" class="w-full h-full relative overflow-y-auto">+ <TableEditor+ v-if="currentTab.type === SchemaDesignerTabType.TabForTable"+ />+ </div>+ </template>+ <EmptyTips v-else />+ </main>+</template>++<script lang="ts" setup>+import { computed } from "vue";+import { SchemaDesignerTabType, useSchemaDesignerContext } from "./common";++const { getCurrentTab } = useSchemaDesignerContext();+const currentTab = computed(() => getCurrentTab());+</script>diff --git a/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vue b/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vueindex 3ecada3722..bd6e442f53 100644--- a/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vue+++ b/frontend/src/components/SchemaDesigner/Modals/TableNameModal.vue@@ -32,6 +32,10 @@ import { useNotificationStore } from "@/store";import { ColumnMetadata, TableMetadata } from "@/types/proto/store/database";import { Engine } from "@/types/proto/v1/common";import { useSchemaDesignerContext } from "../common";+import {+ convertColumnMetadataToColumn,+ convertTableMetadataToTable,+} from "@/types";const tableNameFieldRegexp = /^\S+$/;@@ -40,10 +44,14 @@ interface LocalState {}const props = defineProps({- schema: {+ schemaId: {type: String,default: "",},+ tableId: {+ type: String,+ default: undefined,+ },});const emit = defineEmits<{@@ -51,7 +59,7 @@ const emit = defineEmits<{}>();const { t } = useI18n();-const { engine, metadata } = useSchemaDesignerContext();+const { engine, editableSchemas } = useSchemaDesignerContext();const notificationStore = useNotificationStore();const state = reactive<LocalState>({tableName: "",@@ -71,8 +79,8 @@ const handleConfirmButtonClick = async () => {return;}- const schema = metadata.value.schemas.find(- (schema) => schema.name === props.schema+ const schema = editableSchemas.value.find(+ (schema) => schema.id === props.schemaId);if (!schema) {notificationStore.pushNotification({@@ -93,8 +101,12 @@ const handleConfirmButtonClick = async () => {column.type = "INT";}column.comment = "ID";- table.columns.push(column);- schema.tables.push(table);+ const columnEdit = convertColumnMetadataToColumn(column);+ const tableEdit = convertTableMetadataToTable(table);+ tableEdit.status = "created";+ tableEdit.columnList.push(columnEdit);+ tableEdit.primaryKey.columnIdList.push(columnEdit.id);+ schema.tableList.push(tableEdit);dismissModal();};diff --git a/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue b/frontend/src/components/SchemaDesigner/Panels/TableEditor.vueindex 62b739f767..9ea79064e1 100644--- a/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue+++ b/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue@@ -8,6 +8,7 @@><buttonclass="flex flex-row justify-center items-center border px-3 py-1 leading-6 text-sm text-gray-700 rounded cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="disableChangeTable"@click="handleAddColumn"><heroicons-outline:plus class="w-4 h-auto mr-1 text-gray-400" />@@ -27,6 +28,7 @@</template></NInput><div+ v-if="false"class="flex flex-row justify-end items-center bg-gray-100 p-1 rounded"><button@@ -78,13 +80,17 @@<div class="w-full"><divv-for="(column, index) in shownColumnList"- :key="`${column.name}-${index}`"+ :key="`${index}-${column.id}`"class="grid grid-cols-[repeat(4,_minmax(0,_1fr))_repeat(2,_96px)_minmax(0,_1fr)_32px] gr text-sm even:bg-gray-50"- :class="[getColumnComputedClassList(column)]"+ :class="[+ `column-${column.id}`,+ getColumnItemComputedClassList(column),+ ]"><div class="table-body-item-container"><inputv-model="column.name"+ :disabled="disableAlterColumn(column)"placeholder="column name"class="column-field-input column-name-input"type="text"@@ -95,12 +101,14 @@><inputv-model="column.type"+ :disabled="disableAlterColumn(column)"placeholder="column type"class="column-field-input column-type-input !pr-8"type="text"/><NDropdowntrigger="click"+ :disabled="disableAlterColumn(column)":options="dataTypeOptions"@select="(dataType: string) => (column.type = dataType)">@@ -116,12 +124,14 @@><inputv-model="column.default"+ :disabled="disableAlterColumn(column)":placeholder="column.default === undefined ? 'NULL' : 'EMPTY'"class="column-field-input !pr-8"type="text"/><NDropdowntrigger="click"+ :disabled="disableAlterColumn(column)":options="dataDefaultOptions"@select="(defaultString:string)=>handleColumnDefaultFieldChange(column, defaultString)">@@ -135,6 +145,7 @@<div class="table-body-item-container"><inputv-model="column.comment"+ :disabled="disableAlterColumn(column)"placeholder="comment"class="column-field-input"type="text"@@ -146,7 +157,9 @@<BBCheckboxclass="ml-3":value="!column.nullable"- :disabled="isColumnPrimaryKey(column)"+ :disabled="+ disableAlterColumn(column) || isColumnPrimaryKey(column)+ "@toggle="(value) => (column.nullable = !value)"/></div>@@ -156,6 +169,7 @@<BBCheckboxclass="ml-3":value="isColumnPrimaryKey(column)"+ :disabled="disableAlterColumn(column)"@toggle="(value) => setColumnPrimaryKey(column, value)"/></div>@@ -165,6 +179,7 @@<spanv-if="checkColumnHasForeignKey(column)"class="column-field-text cursor-pointer !w-auto hover:opacity-80"+ @click="gotoForeignKeyReferencedTable(column)">{{ getReferencedForeignKeyName(column) }}</span>@@ -175,15 +190,17 @@><buttonclass="foreign-key-edit-button hidden cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="disableAlterColumn(column)"@click="handleEditColumnForeignKey(column)"><heroicons:pencil-square class="w-4 h-auto text-gray-400" /></button></div><div class="w-full flex justify-start items-center">- <n-tooltip trigger="hover">+ <n-tooltip v-if="!isDroppedColumn(column)" trigger="hover"><template #trigger><button+ :disabled="disableChangeTable"class="text-gray-500 cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"@click="handleDropColumn(column)">@@ -192,6 +209,18 @@</template><span>{{ $t("schema-editor.actions.drop-column") }}</span></n-tooltip>+ <n-tooltip v-else trigger="hover">+ <template #trigger>+ <button+ class="text-gray-500 cursor-pointer hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-60"+ :disabled="disableChangeTable"+ @click="handleRestoreColumn(column)"+ >+ <heroicons:arrow-uturn-left class="w-4 h-auto" />+ </button>+ </template>+ <span>{{ $t("schema-editor.actions.restore") }}</span>+ </n-tooltip></div></div></div>@@ -223,29 +252,38 @@<EditColumnForeignKeyModalv-if="state.showEditColumnForeignKeyModal && editForeignKeyColumn"- :schema="schema.name"- :table="table.name"- :column="editForeignKeyColumn.name"+ :schema-id="schema.id"+ :table-id="table.id"+ :column-id="editForeignKeyColumn.id"@close="state.showEditColumnForeignKeyModal = false"/></template><script lang="ts" setup>-import { isUndefined } from "lodash-es";+import { isUndefined, flatten } from "lodash-es";+import scrollIntoView from "scroll-into-view-if-needed";import { computed, nextTick, reactive, ref } from "vue";import { useI18n } from "vue-i18n";import { NDropdown } from "naive-ui";+import { generateUniqueTabId } from "@/store/modules";import { ColumnMetadata } from "@/types/proto/store/database";+import {+ Column,+ Table,+ Schema,+ convertColumnMetadataToColumn,+ ForeignKey,+} from "@/types/schemaEditor/atomType";import { getDataTypeSuggestionList } from "@/utils";import { BBCheckbox, BBSpin } from "@/bbkit";import HighlightCodeBlock from "@/components/HighlightCodeBlock";import EditColumnForeignKeyModal from "../Modals/EditColumnForeignKeyModal.vue";import { Engine } from "@/types/proto/v1/common";-import { TableTabContext, useSchemaDesignerContext } from "../common";import {- SchemaMetadata,- TableMetadata,-} from "@/types/proto/v1/database_service";+ SchemaDesignerTabType,+ TableTabContext,+ useSchemaDesignerContext,+} from "../common";type SubtabType = "column-list" | "raw-sql";@@ -257,7 +295,8 @@ interface LocalState {}const { t } = useI18n();-const { engine, metadata, getCurrentTab } = useSchemaDesignerContext();+const { readonly, engine, editableSchemas, getCurrentTab, addTab } =+ useSchemaDesignerContext();const currentTab = computed(() => getCurrentTab() as TableTabContext);const state = reactive<LocalState>({selectedSubtab:@@ -268,28 +307,38 @@ const state = reactive<LocalState>({});const schema = computed(() => {- return metadata.value.schemas.find(- (schema) => schema.name === currentTab.value.schema- ) as SchemaMetadata;-});-const table = computed(() => {- return schema.value.tables.find(- (table) => table.name === currentTab.value.table- ) as TableMetadata;+ return editableSchemas.value.find(+ (schema) => schema.id === currentTab.value.schemaId+ ) as Schema;});+const table = computed(+ () =>+ schema.value.tableList.find(+ (table) => table.id === currentTab.value.tableId+ ) as Table+);const foreignKeyList = computed(() => {- return table.value.foreignKeys;+ return schema.value.foreignKeyList.filter(+ (pk) => pk.tableId === currentTab.value.tableId+ ) as ForeignKey[];});const searchPattern = ref("");const tableEditorContainerRef = ref<HTMLDivElement>();-const editForeignKeyColumn = ref<ColumnMetadata>();+const editForeignKeyColumn = ref<Column>();const shownColumnList = computed(() => {- return table.value.columns.filter((column) =>+ return table.value.columnList.filter((column) =>column.name.includes(searchPattern.value.trim()));});+const isDroppedSchema = computed(() => {+ return schema.value.status === "dropped";+});++const isDroppedTable = computed(() => {+ return table.value.status === "dropped";+});const columnHeaderList = computed(() => {return [@@ -319,11 +368,29 @@ const columnHeaderList = computed(() => {},{key: "foreign_key",- label: "Foreign Key",+ label: t("schema-editor.column.foreign-key"),},];});+const dataTypeOptions = computed(() => {+ return getDataTypeSuggestionList(engine).map((dataType) => {+ return {+ label: dataType,+ key: dataType,+ };+ });+});++const getColumnItemComputedClassList = (column: Column) => {+ if (column.status === "dropped") {+ return ["text-red-700", "cursor-not-allowed", "!bg-red-50", "opacity-70"];+ } else if (column.status === "created") {+ return ["text-green-700", "!bg-green-50"];+ }+ return [];+};+const dataDefaultOptions = [{label: "NULL",@@ -335,66 +402,78 @@ const dataDefaultOptions = [},];-const dataTypeOptions = computed(() => {- return getDataTypeSuggestionList(engine).map((dataType) => {- return {- label: dataType,- key: dataType,- };- });-});--const getColumnComputedClassList = (column: ColumnMetadata) => {- return [`column-${column.name}`];+const isColumnPrimaryKey = (column: Column): boolean => {+ return table.value.primaryKey.columnIdList.includes(column.id);};-const isColumnPrimaryKey = (column: ColumnMetadata): boolean => {- return (- table.value.indexes.find(- (index) => index.primary && index.expressions.includes(column.name)- ) !== undefined+const checkColumnHasForeignKey = (column: Column): boolean => {+ const columnIdList = flatten(+ foreignKeyList.value.map((fk) => fk.columnIdList));+ return columnIdList.includes(column.id);};-const checkColumnHasForeignKey = (column: ColumnMetadata): boolean => {- return foreignKeyList.value- .map((fk) => fk.columns)- .flat()- .flat()- .includes(column.name);-};--const getReferencedForeignKeyName = (column: ColumnMetadata) => {+const getReferencedForeignKeyName = (column: Column) => {if (!checkColumnHasForeignKey(column)) {return;}const fk = foreignKeyList.value.find((fk) =>- fk.columns.find((columnName) => columnName === column.name) !== undefined+ fk.columnIdList.find((columnId) => columnId === column.id) !== undefined);- const index = fk?.columns.findIndex(- (columnName) => columnName === column.name+ const index = fk?.columnIdList.findIndex(+ (columnId) => columnId === column.id);+if (isUndefined(fk) || isUndefined(index) || index < 0) {return;}-- const referencedSchema = fk.referencedSchema[index];- const referencedTable = fk.referencedTable[index];- const referencedColumn = fk.referencedSchema[index];- if (!referencedTable || !referencedColumn) {+ const referencedSchema = editableSchemas.value.find(+ (schema) => schema.id === fk.referencedSchemaId+ );+ const referencedTable = referencedSchema?.tableList.find(+ (table) => table.id === fk.referencedTableId+ );+ if (!referencedTable) {return;}-+ const referColumn = referencedTable.columnList.find(+ (column) => column.id === fk.referencedColumnIdList[index]+ );if (engine === Engine.MYSQL) {- return `${referencedTable}(${referencedColumn})`;+ return `${referencedTable.name}(${referColumn?.name})`;} else {- return `${referencedSchema}.${referencedTable}(${referencedColumn})`;+ return `${referencedSchema?.name}.${referencedTable.name}(${referColumn?.name})`;}};-const setColumnPrimaryKey = (column: ColumnMetadata, isPrimaryKey: boolean) => {- // TODO+const isDroppedColumn = (column: Column): boolean => {+ return column.status === "dropped";+};++const disableChangeTable = computed(() => {+ return readonly || isDroppedSchema.value || isDroppedTable.value;+});++const disableAlterColumn = (column: Column): boolean => {+ return (+ readonly ||+ isDroppedSchema.value ||+ isDroppedTable.value ||+ isDroppedColumn(column)+ );+};++const setColumnPrimaryKey = (column: Column, isPrimaryKey: boolean) => {+ if (isPrimaryKey) {+ column.nullable = false;+ table.value.primaryKey.columnIdList.push(column.id);+ } else {+ table.value.primaryKey.columnIdList =+ table.value.primaryKey.columnIdList.filter(+ (columnId) => columnId !== column.id+ );+ }};const handleChangeTab = (tab: SubtabType) => {@@ -402,19 +481,20 @@ const handleChangeTab = (tab: SubtabType) => {};const handleAddColumn = () => {- const column = ColumnMetadata.fromPartial({});- table.value.columns.push(column);+ const column = convertColumnMetadataToColumn(ColumnMetadata.fromPartial({}));+ column.status = "created";+ table.value.columnList.push(column);nextTick(() => {(tableEditorContainerRef.value?.querySelector(- `.column-${column.name} .column-name-input`+ `.column-${column.id} .column-name-input`) as HTMLInputElement)?.focus();});};const handleColumnDefaultFieldChange = (- column: ColumnMetadata,+ column: Column,defaultString: string) => {if (defaultString === "NULL") {@@ -424,13 +504,94 @@ const handleColumnDefaultFieldChange = (}};-const handleEditColumnForeignKey = (column: ColumnMetadata) => {+const gotoForeignKeyReferencedTable = (column: Column) => {+ if (!checkColumnHasForeignKey(column)) {+ return;+ }+ const fk = foreignKeyList.value.find(+ (fk) =>+ fk.columnIdList.find((columnId) => columnId === column.id) !== undefined+ );+ const index = fk?.columnIdList.findIndex(+ (columnId) => columnId === column.id+ );+ if (isUndefined(fk) || isUndefined(index) || index < 0) {+ return;+ }++ const referencedSchema = editableSchemas.value.find(+ (schema) => schema.id === fk.referencedSchemaId+ );+ const referencedTable = referencedSchema?.tableList.find(+ (table) => table.id === fk.referencedTableId+ );+ if (!referencedTable) {+ return;+ }+ const referColumn = referencedTable?.columnList.find(+ (column) => column.id === fk.referencedColumnIdList[index]+ );+ if (!referencedSchema || !referencedTable || !referColumn) {+ return;+ }++ addTab({+ id: generateUniqueTabId(),+ type: SchemaDesignerTabType.TabForTable,+ schemaId: referencedSchema.id,+ tableId: referencedTable.id,+ });++ nextTick(() => {+ const container = document.querySelector("#table-editor-container");+ const input = container?.querySelector(+ `.column-${referColumn.id} .column-name-input`+ ) as HTMLInputElement | undefined;+ if (input) {+ input.focus();+ scrollIntoView(input);+ }+ });+};++const handleEditColumnForeignKey = (column: Column) => {editForeignKeyColumn.value = column;state.showEditColumnForeignKeyModal = true;};-const handleDropColumn = (column: ColumnMetadata) => {- table.value.columns = table.value.columns.filter((col) => col !== column);+const handleDropColumn = (column: Column) => {+ if (column.status === "created") {+ table.value.columnList = table.value.columnList.filter(+ (item) => item !== column+ );+ table.value.primaryKey.columnIdList =+ table.value.primaryKey.columnIdList.filter(+ (columnId) => columnId !== column.id+ );++ const foreignKeyList = schema.value.foreignKeyList.filter(+ (fk) => fk.tableId === currentTab.value.tableId+ );+ for (const foreignKey of foreignKeyList) {+ const columnRefIndex = foreignKey.columnIdList.findIndex(+ (columnId) => columnId === column.id+ );+ if (columnRefIndex > -1) {+ foreignKey.columnIdList.splice(columnRefIndex, 1);+ foreignKey.referencedColumnIdList.splice(columnRefIndex, 1);+ }+ }+ } else {+ column.status = "dropped";+ }+};++const handleRestoreColumn = (column: Column) => {+ if (column.status === "created") {+ return;+ }++ column.status = "normal";};</script>diff --git a/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vue b/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vueindex 1881259a11..bf2ad8d4cd 100644--- a/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vue+++ b/frontend/src/components/SchemaDesigner/PrepForm/SchemaDesignTable.vue@@ -1,6 +1,7 @@<template><div ref="wrapper" rule="database-table" v-bind="$attrs"><BBGrid+ class="border":column-list="COLUMN_LIST":data-source="schemaDesigns"@click-row="clickSchemaDesign"@@ -13,7 +14,7 @@{{ getFormatedValue(schemaDesign).project }}</div><div class="bb-grid-cell">- {{ getFormatedValue(schemaDesign).engine }}+ {{ engineNameV1(getFormatedValue(schemaDesign).engine) }}</div><div class="bb-grid-cell">{{ getFormatedValue(schemaDesign).creator }}@@ -25,7 +26,7 @@<HumanizeTs:ts="(schemaDesign.updateTime?.getTime() ?? 0) / 1000"class="ml-1"- />)+ /></div></template></BBGrid>@@ -40,7 +41,11 @@ import { BBGridColumn } from "@/bbkit";import { getProjectAndSchemaDesignSheetId } from "@/store/modules/v1/common";import { useProjectV1Store, useUserStore } from "@/store";import { SchemaDesign } from "@/types/proto/v1/schema_design_service";-import { projectV1Name } from "@/utils";+import { engineNameV1, projectV1Name } from "@/utils";++const emit = defineEmits<{+ (event: "click", schemaDesign: SchemaDesign): void;+}>();defineProps<{schemaDesigns: SchemaDesign[];@@ -57,7 +62,7 @@ const COLUMN_LIST = computed(() => {width: "1fr",},{- title: t("common.engine"),+ title: t("database.engine"),width: "1fr",},{ title: t("common.creator"), width: "minmax(auto, 10rem)" },@@ -89,6 +94,6 @@ const getFormatedValue = (schemaDesign: SchemaDesign) => {};const clickSchemaDesign = (schemaDesign: SchemaDesign) => {- // TODO+ emit("click", schemaDesign);};</script>diff --git a/frontend/src/components/SchemaDesigner/PrepForm/TargetDatabaseSelectPanel.vue b/frontend/src/components/SchemaDesigner/PrepForm/TargetDatabaseSelectPanel.vuenew file mode 100644index 0000000000..47560689a5--- /dev/null+++ b/frontend/src/components/SchemaDesigner/PrepForm/TargetDatabaseSelectPanel.vue@@ -0,0 +1,281 @@+<template>+ <NDrawer+ :show="true"+ width="auto"+ :auto-focus="false"+ @update:show="(show) => !show && $emit('close')"+ >+ <NDrawerContent+ :title="$t('database.sync-schema.target-databases')"+ :closable="true"+ class="w-[30rem] max-w-[100vw] relative"+ >+ <div class="flex items-center justify-end mx-2 mb-2">+ <BBTableSearch+ class="m-px"+ :placeholder="$t('database.search-database')"+ @change-text="(text: string) => (state.searchText = text)"+ />+ </div>+ <NCollapse+ class="overflow-y-auto"+ arrow-placement="left"+ :default-expanded-names="+ databaseListGroupByEnvironment.map((group) => group.environment.uid)+ "+ >+ <NCollapseItem+ v-for="{+ environment,+ databaseList: databaseListInEnvironment,+ } in databaseListGroupByEnvironment"+ :key="environment.uid"+ :name="environment.uid"+ >+ <template #header>+ <label class="flex items-center gap-x-2" @click.stop="">+ <EnvironmentV1Name :environment="environment" :link="false" />+ </label>+ </template>++ <template #header-extra>+ <div class="flex items-center text-xs text-gray-500 mr-2">+ {{+ $t(+ "database.n-selected-m-in-total",+ getSelectionStateSummaryForEnvironment(+ environment,+ databaseListInEnvironment+ )+ )+ }}+ </div>+ </template>++ <div class="relative bg-white rounded-md -space-y-px px-2">+ <template+ v-for="database in databaseListInEnvironment"+ :key="database.uid"+ >+ <label+ class="border-control-border relative border p-3 flex flex-col gap-y-2 md:flex-row md:pl-4 md:pr-6"+ :class="+ database.syncState === State.ACTIVE+ ? 'cursor-pointer'+ : 'cursor-not-allowed'+ "+ >+ <div class="radio text-sm flex justify-start md:flex-1">+ <input+ type="checkbox"+ class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"+ :checked="isDatabaseSelected(database.uid)"+ @input="(e: any) => toggleDatabaseSelected(database.uid, e.target.checked)"+ />+ <span+ class="font-medium ml-2 text-main"+ :class="database.syncState !== State.ACTIVE && 'opacity-40'"+ >{{ database.databaseName }}</span+ >+ </div>+ <div+ class="flex items-center gap-x-1 textinfolabel ml-6 pl-0 md:ml-0 md:pl-0 md:justify-end"+ >+ <InstanceV1Name+ :instance="database.instanceEntity"+ :link="false"+ />+ </div>+ </label>+ </template>+ </div>+ </NCollapseItem>+ </NCollapse>++ <template #footer>+ <div class="flex items-center justify-end gap-x-2">+ <NButton @click="$emit('close')">{{ $t("common.cancel") }}</NButton>+ <NButton+ type="primary"+ :loading="state.isLoading"+ @click="handleConfirm"+ >+ {{ $t("common.confirm") }}+ </NButton>+ </div>+ </template>+ </NDrawerContent>+ </NDrawer>+</template>++<script setup lang="ts">+import { head } from "lodash-es";+import { computed, reactive } from "vue";+import {+ NCollapse,+ NCollapseItem,+ NButton,+ NDrawer,+ NDrawerContent,+} from "naive-ui";+import {+ useDatabaseV1Store,+ useEnvironmentV1Store,+ useProjectV1Store,+} from "@/store";+import { ComposedDatabase } from "@/types";+import { Environment } from "@/types/proto/v1/environment_service";+import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";+import { Engine, State, engineToJSON } from "@/types/proto/v1/common";+import axios from "axios";+import dayjs from "dayjs";+import { useRouter } from "vue-router";++type LocalState = {+ searchText: string;+ isLoading: boolean;+ selectedDatabaseList: ComposedDatabase[];+};++const props = defineProps<{+ projectId: string;+ engine: Engine;+ schema: string;+}>();++defineEmits<{+ (event: "close"): void;+}>();++const router = useRouter();+const environmentV1Store = useEnvironmentV1Store();+const databaseStore = useDatabaseV1Store();+const state = reactive<LocalState>({+ searchText: "",+ isLoading: false,+ selectedDatabaseList: [],+});++const databaseListGroupByEnvironment = computed(() => {+ const project = useProjectV1Store().getProjectByUID(props.projectId);+ const databaseList =+ databaseStore+ .databaseListByProject(project.name)+ .filter((db) => db.databaseName.includes(state.searchText))+ .filter((db) => db.instanceEntity.engine === props.engine) || [];+ const listByEnv = environmentV1Store.environmentList.map((environment) => {+ const list = databaseList.filter(+ (db) => db.instanceEntity.environment === environment.name+ );+ return {+ environment,+ databaseList: list,+ };+ });++ return listByEnv.filter((group) => group.databaseList.length > 0);+});++const isDatabaseSelected = (databaseId: string) => {+ const idList = state.selectedDatabaseList.map((db) => db.uid);+ return idList.includes(databaseId);+};++const toggleDatabaseSelected = (databaseId: string, selected: boolean) => {+ const index = state.selectedDatabaseList.findIndex(+ (db) => db.uid === databaseId+ );+ if (selected) {+ if (index < 0) {+ // Now we only allow select one database.+ state.selectedDatabaseList = [databaseStore.getDatabaseByUID(databaseId)];+ }+ } else {+ if (index >= 0) {+ state.selectedDatabaseList.splice(index, 1);+ }+ }+};++const getSelectionStateSummaryForEnvironment = (+ environment: Environment,+ databaseList: ComposedDatabase[]+) => {+ const set = new Set(+ state.selectedDatabaseList+ .filter((db) => db.instanceEntity.environment === environment.name)+ .map((db) => db.uid)+ );+ const selected = databaseList.filter((db) => set.has(db.uid)).length;+ const total = databaseList.length;++ return { selected, total };+};++const handleConfirm = async () => {+ if (state.selectedDatabaseList.length === 0) {+ return;+ }+ if (state.isLoading) {+ return false;+ }+ state.isLoading = true;+ const database = head(state.selectedDatabaseList) as ComposedDatabase;+ const targetDatabaseSchema = await databaseStore.fetchDatabaseSchema(+ `${database.name}/schema`,+ true+ );++ const diff = await getSchemaDiff(+ props.engine,+ targetDatabaseSchema.schema,+ props.schema+ );++ const query: Record<string, any> = {+ template: "bb.issue.database.schema.update",+ project: props.projectId,+ mode: "normal",+ ghost: undefined,+ };+ query.databaseList = `${database.uid}`;+ query.sqlList = JSON.stringify([diff]);+ query.name = generateIssueName([database.databaseName]);++ const routeInfo = {+ name: "workspace.issue.detail",+ params: {+ issueSlug: "new",+ },+ query,+ };+ router.push(routeInfo);+};++const generateIssueName = (databaseNameList: string[]) => {+ const issueNameParts: string[] = [];+ if (databaseNameList.length === 1) {+ issueNameParts.push(`[${databaseNameList[0]}]`);+ } else {+ issueNameParts.push(`[${databaseNameList.length} databases]`);+ }+ issueNameParts.push(`Alter schema`);+ const datetime = dayjs().format("@MM-DD HH:mm");+ const tz = "UTC" + dayjs().format("ZZ");+ issueNameParts.push(`${datetime} ${tz}`);+ return issueNameParts.join(" ");+};++const getSchemaDiff = async (+ engine: Engine,+ sourceSchema: string,+ targetSchema: string+) => {+ const { data } = await axios.post("/v1/sql/schema/diff", {+ engineType: engineToJSON(engine),+ sourceSchema,+ targetSchema,+ });+ return data as string;+};+</script>diff --git a/frontend/src/components/SchemaDesigner/PrepForm/index.vue b/frontend/src/components/SchemaDesigner/PrepForm/index.vueindex 8f24d091f3..193bfcee09 100644--- a/frontend/src/components/SchemaDesigner/PrepForm/index.vue+++ b/frontend/src/components/SchemaDesigner/PrepForm/index.vue@@ -1,21 +1,467 @@<template>- <div>- <div class="w-full"></div>- <SchemaDesignTable :schema-designs="schemaDesignList" />- </div>+ <DrawerContent>+ <template #header>+ <div class="flex flex-col gap-y-1">+ <span>{{ $t("schema-designer.quick-action") }}</span>+ </div>+ </template>++ <div+ class="space-y-3 w-[calc(100vw-8rem)] sm:w-[64rem] max-w-[calc(100vw-8rem)] overflow-x-auto"+ >+ <div+ class="w-full border-b pb-2 mb-2 flex flex-row justify-between items-center"+ >+ <NRadioGroup v-model:value="state.tab" class="space-x-4">+ <NRadio+ :value="'LIST'"+ :label="$t('schema-designer.existing-schema-design')"+ />+ <NRadio+ :value="'CREATE'"+ :label="$t('schema-designer.new-schema-design')"+ />+ </NRadioGroup>+ </div>++ <template v-if="!isCreating && !isViewing && !isEditing">+ <SchemaDesignTable+ v-if="ready"+ :schema-designs="schemaDesignList"+ @click="handleSchemaDesignItemClick"+ />+ <div v-else class="w-full h-[20rem] flex items-center justify-center">+ <BBSpin />+ </div>+ </template>+ <template v-else>+ <div+ v-if="!isCreating"+ class="w-full flex flex-row justify-between items-center"+ >+ <div>+ <NButton+ v-if="isViewing"+ class="w-full flex flex-row justify-start items-center"+ @click="state.selectedSchemaDesign = undefined"+ >+ <heroicons-outline:chevron-left+ class="mr-1 w-4 h-auto text-gray-500 group-hover:text-gray-500 group-focus:text-gray-600"+ />+ {{ $t("common.back") }}+ </NButton>+ </div>+ <div class="flex flex-row justify-end items-center space-x-2">+ <template v-if="isViewing">+ <NButton @click="state.isEditing = true">{{+ $t("common.edit")+ }}</NButton>+ <NButton+ type="primary"+ @click="state.showSelectTargetDatabasePanel = true"+ >{{ $t("schema-designer.apply-to-database") }}</NButton+ >+ </template>+ <template v-else>+ <NButton @click="handleCancelEdit">{{+ $t("common.cancel")+ }}</NButton>+ <NButton type="primary" @click="handleUpdateSchemaDesign">{{+ $t("common.update")+ }}</NButton>+ </template>+ </div>+ </div>+ <div class="w-full flex flex-row justify-start items-center">+ <span class="flex w-40 items-center text-sm">{{+ $t("common.name")+ }}</span>+ <BBTextField+ class="w-60 !py-1.5"+ :disabled="isViewing"+ :value="state.schemaDesignName"+ @input="+ state.schemaDesignName = ($event.target as HTMLInputElement).value+ "+ />+ </div>+ <BaselineSchemaSelector+ v-if="isCreating"+ :baseline-schema="state.baselineSchema"+ @update="handleBaselineSchemaChange"+ />+ <div v-else class="w-full">+ <div class="flex flex-row justify-start items-center">+ <span class="text-sm w-40">{{+ $t("schema-designer.baseline-database")+ }}</span>+ <InstanceV1EngineIcon+ class="mr-1"+ :instance="+ databaseStore.getDatabaseByUID(+ state.baselineSchema.databaseId || ''+ ).instanceEntity+ "+ />+ <DatabaseV1Name+ :database="+ databaseStore.getDatabaseByUID(+ state.baselineSchema.databaseId || ''+ )+ "+ />+ </div>+ </div>+ <template v-if="state.selectedSchemaDesign">+ <SchemaDesigner+ ref="schemaDesignerRef"+ :key="schemaDesignId"+ :readonly="isViewing"+ :engine="state.selectedSchemaDesign.engine"+ :schema-design="state.selectedSchemaDesign"+ />+ </template>+ </template>+ </div>++ <template v-if="isCreating" #footer>+ <div class="flex-1 flex items-center justify-between">+ <div></div>++ <div class="flex items-center justify-end gap-x-3">+ <NButton @click.prevent="cancel">+ {{ cancelText }}+ </NButton>+ <NButton+ type="primary"+ :disabled="!allowConfirm"+ @click.prevent="handleConfirm"+ >+ {{ confirmText }}+ </NButton>+ </div>+ </div>+ </template>+ </DrawerContent>++ <TargetDatabaseSelectPanel+ v-if="state.selectedSchemaDesign && state.showSelectTargetDatabasePanel"+ :project-id="state.baselineSchema.projectId || ''"+ :engine="state.selectedSchemaDesign.engine"+ :schema="state.selectedSchemaDesign.schema"+ @close="state.showSelectTargetDatabasePanel = false"+ /></template><script lang="ts" setup>-import { reactive } from "vue";+import { isEqual, uniqueId } from "lodash-es";+import { NRadioGroup, NRadio, NButton } from "naive-ui";+import { computed, reactive, ref } from "vue";+import { useI18n } from "vue-i18n";+import {+ ChangeHistory,+ DatabaseMetadata,+} from "@/types/proto/v1/database_service";+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";+import {+ pushNotification,+ useChangeHistoryStore,+ useDatabaseV1Store,+ useProjectV1ByUID,+} from "@/store";+import {+ useSchemaDesignList,+ useSchemaDesignStore,+} from "@/store/modules/schemaDesign";import SchemaDesignTable from "./SchemaDesignTable.vue";-import { useSchemaDesignList } from "@/store/modules/schemaDesign";+import BaselineSchemaSelector from "../BaselineSchemaSelector.vue";+import SchemaDesigner from "../index.vue";+import { databaseNamePrefix } from "@/store/modules/v1/common";+import { watch } from "vue";+import { mergeSchemaEditToMetadata } from "../common/util";+import { DatabaseV1Name, InstanceV1EngineIcon } from "@/components/v2";+import TargetDatabaseSelectPanel from "./TargetDatabaseSelectPanel.vue";++interface BaselineSchema {+ // The uid of project.+ projectId?: string;+ // The uid of database.+ databaseId?: string;+ changeHistory?: ChangeHistory;+}interface LocalState {- tab: "TABLE" | "VIEW";+ tab: "LIST" | "CREATE";+ schemaDesignName: string;+ baselineSchema: BaselineSchema;+ isEditing: boolean;+ showSelectTargetDatabasePanel: boolean;+ selectedSchemaDesign?: SchemaDesign;}-const { schemaDesignList } = useSchemaDesignList();-const _ = reactive<LocalState>({- tab: "TABLE",+defineProps({+ projectId: {+ type: String,+ default: undefined,+ },+});+const emit = defineEmits(["dismiss"]);++const { t } = useI18n();+const schemaDesignerRef = ref<InstanceType<typeof SchemaDesigner>>();+const databaseStore = useDatabaseV1Store();+const schemaDesignStore = useSchemaDesignStore();+const { schemaDesignList, ready } = useSchemaDesignList();+const state = reactive<LocalState>({+ tab: "LIST",+ schemaDesignName: "",+ baselineSchema: {},+ isEditing: false,+ showSelectTargetDatabasePanel: false,+});+const isCreating = computed(() => state.tab === "CREATE");+const isViewing = computed(+ () => state.tab === "LIST" && !!state.selectedSchemaDesign && !state.isEditing+);+const isEditing = computed(+ () => state.tab === "LIST" && !!state.selectedSchemaDesign && state.isEditing+);++watch(+ () => state.tab,+ () => {+ if (state.tab === "CREATE") {+ state.schemaDesignName = "";+ state.baselineSchema = {};+ }+ state.selectedSchemaDesign = undefined;+ }+);++const prepareSchemaDesign = async () => {+ const changeHistory = state.baselineSchema.changeHistory;+ if (changeHistory && state.baselineSchema.databaseId) {+ const database = databaseStore.getDatabaseByUID(+ state.baselineSchema.databaseId+ );+ const baselineMetadata = await schemaDesignStore.parseSchemaString(+ changeHistory.schema,+ database.instanceEntity.engine+ );+ return SchemaDesign.fromPartial({+ engine: database.instanceEntity.engine,+ baselineSchema: changeHistory.schema,+ baselineSchemaMetadata: baselineMetadata,+ schema: changeHistory.schema,+ schemaMetadata: baselineMetadata,+ });+ }+ return undefined;+};++const schemaDesignId = computed(() => {+ if (!state.selectedSchemaDesign || !state.selectedSchemaDesign.name) {+ return uniqueId();+ } else {+ // Force remount component.+ return state.selectedSchemaDesign.name + isViewing.value;+ }+});++const allowConfirm = computed(() => {+ if (isCreating.value) {+ return (+ state.schemaDesignName &&+ state.baselineSchema.projectId &&+ state.baselineSchema.databaseId+ );+ } else if (isEditing.value) {+ return state.schemaDesignName;+ }+ return false;});++const cancelText = computed(() => {+ if (isCreating.value) {+ return t("common.cancel");+ } else if (isEditing.value) {+ return t("common.back");+ }+ return t("common.cancel");+});++const confirmText = computed(() => {+ if (isCreating.value) {+ return t("common.create");+ } else if (isEditing.value) {+ return t("common.update");+ }+ return t("common.next");+});++const handleSchemaDesignItemClick = async (schemaDesign: SchemaDesign) => {+ state.schemaDesignName = schemaDesign.title;+ state.selectedSchemaDesign = schemaDesign;+ const database = await databaseStore.getOrFetchDatabaseByName(+ schemaDesign.baselineDatabase+ );+ const baselineSchema: BaselineSchema = {+ projectId: database.projectEntity.uid,+ databaseId: database.uid,+ };+ if (schemaDesign.schemaVersion) {+ const changeHistory =+ await useChangeHistoryStore().getOrFetchChangeHistoryByName(+ schemaDesign.schemaVersion+ );+ baselineSchema.changeHistory = changeHistory;+ }+ state.baselineSchema = baselineSchema;+};++const handleBaselineSchemaChange = async (baselineSchema: BaselineSchema) => {+ state.baselineSchema = baselineSchema;++ if (isCreating.value) {+ state.selectedSchemaDesign = await prepareSchemaDesign();+ }+};++const handleCancelEdit = () => {+ state.isEditing = false;+ if (state.selectedSchemaDesign) {+ handleSchemaDesignItemClick(state.selectedSchemaDesign);+ }+};++const cancel = () => {+ if (isEditing.value) {+ state.tab = "LIST";+ state.selectedSchemaDesign = undefined;+ } else {+ emit("dismiss");+ }+};++const handleConfirm = async () => {+ if (!state.selectedSchemaDesign) {+ return;+ }++ const designerState = schemaDesignerRef.value;+ if (!designerState) {+ // Should not happen.+ throw new Error("schema designer is undefined");+ }+ if (state.schemaDesignName === "") {+ return;+ }++ const { project } = useProjectV1ByUID(state.baselineSchema.projectId || "");+ const database = useDatabaseV1Store().getDatabaseByUID(+ state.baselineSchema.databaseId || ""+ );++ if (isCreating.value) {+ const metadata = mergeSchemaEditToMetadata(+ designerState.editableSchemas,+ state.selectedSchemaDesign.baselineSchemaMetadata ||+ DatabaseMetadata.fromPartial({})+ );+ const baselineDatabase = `${database.instanceEntity.name}/${databaseNamePrefix}${state.baselineSchema.databaseId}`;+ await schemaDesignStore.createSchemaDesign(+ project.value.name,+ SchemaDesign.fromPartial({+ title: state.schemaDesignName,+ // Keep schema empty in frontend. Backend will generate the design schema.+ schema: "",+ schemaMetadata: metadata,+ baselineSchema: state.selectedSchemaDesign.baselineSchema,+ baselineSchemaMetadata:+ state.selectedSchemaDesign.baselineSchemaMetadata,+ engine: state.selectedSchemaDesign.engine,+ baselineDatabase: baselineDatabase,+ schemaVersion: state.baselineSchema.changeHistory?.name || "",+ })+ );+ state.tab = "LIST";+ state.selectedSchemaDesign = undefined;+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("schema-designer.message.created-succeed"),+ });+ } else {+ const updateMarks = [];+ if (state.selectedSchemaDesign.title !== state.schemaDesignName) {+ updateMarks.push("title");+ }+ const metadata = mergeSchemaEditToMetadata(+ designerState.editableSchemas,+ state.selectedSchemaDesign.schemaMetadata ||+ DatabaseMetadata.fromPartial({})+ );+ if (isEqual(metadata, state.selectedSchemaDesign.schemaMetadata)) {+ updateMarks.push("schema");+ }+ await schemaDesignStore.updateSchemaDesign(+ SchemaDesign.fromPartial({+ name: state.selectedSchemaDesign.name,+ title: state.schemaDesignName,+ engine: state.selectedSchemaDesign.engine,+ baselineSchema: state.selectedSchemaDesign.baselineSchema,+ schemaMetadata: metadata,+ }),+ updateMarks+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("schema-designer.message.updated-succeed"),+ });+ }+};++const handleUpdateSchemaDesign = async () => {+ if (!state.selectedSchemaDesign) {+ return;+ }++ const designerState = schemaDesignerRef.value;+ if (!designerState) {+ throw new Error("schema designer is undefined");+ }+ if (state.schemaDesignName === "") {+ return;+ }++ const updateMarks = [];+ if (state.selectedSchemaDesign.title !== state.schemaDesignName) {+ updateMarks.push("title");+ }+ const metadata = mergeSchemaEditToMetadata(+ designerState.editableSchemas,+ state.selectedSchemaDesign.schemaMetadata ||+ DatabaseMetadata.fromPartial({})+ );+ if (isEqual(metadata, state.selectedSchemaDesign.schemaMetadata)) {+ updateMarks.push("schema");+ }+ state.selectedSchemaDesign = await schemaDesignStore.updateSchemaDesign(+ SchemaDesign.fromPartial({+ name: state.selectedSchemaDesign.name,+ title: state.schemaDesignName,+ engine: state.selectedSchemaDesign.engine,+ baselineSchema: state.selectedSchemaDesign.baselineSchema,+ schemaMetadata: metadata,+ }),+ updateMarks+ );+ state.isEditing = false;+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("schema-designer.message.updated-succeed"),+ });+};</script>diff --git a/frontend/src/components/SchemaDesigner/TabsContainer.vue b/frontend/src/components/SchemaDesigner/TabsContainer.vueindex d728c9da0f..98fb61af81 100644--- a/frontend/src/components/SchemaDesigner/TabsContainer.vue+++ b/frontend/src/components/SchemaDesigner/TabsContainer.vue@@ -43,6 +43,7 @@</template><script lang="ts" setup>+import { head } from "lodash-es";import { NEllipsis } from "naive-ui";import { computed, nextTick, ref, watch } from "vue";import scrollIntoView from "scroll-into-view-if-needed";@@ -52,7 +53,7 @@ import {SchemaDesignerTabType,} from "./common";-const { tabState, getCurrentTab } = useSchemaDesignerContext();+const { tabState, getCurrentTab, getTable } = useSchemaDesignerContext();const tabsContainerRef = ref();const tabList = computed(() => {return Array.from(tabState.value.tabMap.values());@@ -83,7 +84,8 @@ const getTabComputedClassList = (tab: TabContext) => {const getTabName = (tab: TabContext) => {if (tab.type === SchemaDesignerTabType.TabForTable) {- return tab.table || "";+ const table = getTable(tab.schemaId, tab.tableId);+ return table.name || "Uknown tab";} else {// Should never reach here.return "unknown structure";@@ -95,6 +97,13 @@ const handleSelectTab = (tab: TabContext) => {};const handleCloseTab = (tab: TabContext) => {- tabState.value.currentTabId = undefined;+ tabState.value.tabMap.delete(tab.id);+ if (tab.id === currentTab.value?.id) {+ tabState.value.currentTabId = undefined;+ } else {+ tabState.value.currentTabId = head(+ Array.from(tabState.value.tabMap.values())+ )?.id;+ }};</script>diff --git a/frontend/src/components/SchemaDesigner/common/context.ts b/frontend/src/components/SchemaDesigner/common/context.tsindex 73a8059380..0f5a0d0b4f 100644--- a/frontend/src/components/SchemaDesigner/common/context.ts+++ b/frontend/src/components/SchemaDesigner/common/context.ts@@ -1,10 +1,10 @@+import { head, isUndefined } from "lodash-es";import { inject, InjectionKey, provide } from "vue";import {SchemaDesignerContext,SchemaDesignerTabType,TabContext,} from "./type";-import { isUndefined } from "lodash-es";export const KEY = Symbol("bb.schema-designer"@@ -17,13 +17,20 @@ export const useSchemaDesignerContext = () => {export const provideSchemaDesignerContext = (context: Pick<SchemaDesignerContext,- "engine" | "baselineMetadata" | "metadata" | "tabState"+ | "readonly"+ | "engine"+ | "baselineMetadata"+ | "metadata"+ | "tabState"+ | "originalSchemas"+ | "editableSchemas">) => {- const { metadata, tabState } = context;+ const { editableSchemas, tabState } = context;provide(KEY, {...context,+// Tab related functions.getCurrentTab: (): TabContext | undefined => {if (isUndefined(tabState.value.currentTabId)) {@@ -40,8 +47,8 @@ export const provideSchemaDesignerContext = (if (item.type === SchemaDesignerTabType.TabForTable &&- item.schema === tab.schema &&- item.table === tab.table+ item.schemaId === tab.schemaId &&+ item.tableId === tab.tableId) {return true;}@@ -62,49 +69,55 @@ export const provideSchemaDesignerContext = (tabState.value.currentTabId = tab.id;}},- // Schema related functions.- dropSchema: (schema: string) => {- const tabList = Array.from(tabState.value.tabMap.values());- for (const tab of tabList) {- if (tab.schema === schema) {- tabState.value.tabMap.delete(tab.id);- if (tabState.value.currentTabId === tab.id) {- tabState.value.currentTabId = undefined;- }- }++ // Table related functions.+ getTable: (schemaId: string, tableId: string) => {+ const schema = editableSchemas.value.find((item) => item.id === schemaId);+ if (schema === undefined) {+ throw new Error(`Schema ${schemaId} not found.`);}- metadata.value.schemas = metadata.value.schemas.filter(- (item) => item.name !== schema- );- },+ const tableItem = schema.tableList.find((item) => item.id === tableId);+ if (tableItem === undefined) {+ throw new Error(`Table ${tableId} not found.`);+ }- // Table related functions.- dropTable: (schema: string, table: string) => {+ return tableItem;+ },+ dropTable: (schemaId: string, tableId: string) => {const tabList = Array.from(tabState.value.tabMap.values());for (const tab of tabList) {if (tab.type === SchemaDesignerTabType.TabForTable &&- tab.schema === schema &&- tab.table === table+ tab.schemaId === schemaId &&+ tab.tableId === tableId) {tabState.value.tabMap.delete(tab.id);if (tabState.value.currentTabId === tab.id) {- tabState.value.currentTabId = undefined;+ tabState.value.currentTabId = head(+ Array.from(tabState.value.tabMap.values())+ )?.id;}}}- const schemaItem = metadata.value.schemas.find(- (item) => item.name === schema+ const schemaItem = editableSchemas.value.find(+ (item) => item.id === schemaId);if (schemaItem === undefined) {return;}-- schemaItem.tables = schemaItem.tables.filter(- (item) => item.name !== table- );+ const table = schemaItem.tableList.find((item) => item.id === tableId);+ if (table === undefined) {+ return;+ }+ if (table.status === "created") {+ schemaItem.tableList = schemaItem.tableList.filter(+ (item) => item.id !== tableId+ );+ } else {+ table.status = "dropped";+ }},});};diff --git a/frontend/src/components/SchemaDesigner/common/type.ts b/frontend/src/components/SchemaDesigner/common/type.tsindex 2ffeef86ed..04b96560f0 100644--- a/frontend/src/components/SchemaDesigner/common/type.ts+++ b/frontend/src/components/SchemaDesigner/common/type.ts@@ -1,3 +1,4 @@+import { Schema, Table } from "@/types";import { Engine } from "@/types/proto/v1/common";import { DatabaseMetadata } from "@/types/proto/v1/database_service";import { Ref } from "vue";@@ -10,8 +11,8 @@ export enum SchemaDesignerTabType {export interface TableTabContext {id: string;type: SchemaDesignerTabType.TabForTable;- schema: string;- table: string;+ schemaId: string;+ tableId: string;selectedSubtab?: string;}@@ -23,19 +24,21 @@ export interface SchemaDesignerTabState {}export interface SchemaDesignerContext {+ readonly: boolean;baselineMetadata: DatabaseMetadata;engine: Engine;metadata: Ref<DatabaseMetadata>;tabState: Ref<SchemaDesignerTabState>;+ originalSchemas: Schema[];+ editableSchemas: Ref<Schema[]>;+// Tab related functions.getCurrentTab: () => TabContext | undefined;addTab: (tab: TabContext, setAsCurrentTab?: boolean) => void;- // Schema related functions.- dropSchema: (schema: string) => void;-// Table related functions.- dropTable: (schema: string, table: string) => void;+ getTable: (schemaId: string, tableId: string) => Table;+ dropTable: (schemaId: string, tableId: string) => void;}diff --git a/frontend/src/components/SchemaDesigner/common/util.ts b/frontend/src/components/SchemaDesigner/common/util.tsnew file mode 100644index 0000000000..e41ffb9428--- /dev/null+++ b/frontend/src/components/SchemaDesigner/common/util.ts@@ -0,0 +1,242 @@+import { Column, Schema, Table } from "@/types";+import {+ ColumnMetadata,+ DatabaseMetadata,+ ForeignKeyMetadata,+ IndexMetadata,+ SchemaMetadata,+ TableMetadata,+} from "@/types/proto/v1/database_service";++export const mergeSchemaEditToMetadata = (+ schemaEdits: Schema[],+ metadata: DatabaseMetadata+): DatabaseMetadata => {+ for (const schemaEdit of schemaEdits) {+ if (schemaEdit.status === "created") {+ metadata.schemas.push(transformSchemaEditToMetadata(schemaEdit));+ continue;+ } else if (schemaEdit.status === "dropped") {+ metadata.schemas = metadata.schemas.filter(+ (item) => item.name !== schemaEdit.name+ );+ continue;+ } else {+ const schema = metadata.schemas.find(+ (item) => item.name === schemaEdit.name+ );+ if (!schema) {+ continue;+ }+ for (const tableEdit of schemaEdit.tableList) {+ if (tableEdit.status === "created") {+ schema.tables.push(transformTableEditToMetadata(tableEdit));+ continue;+ } else if (tableEdit.status === "dropped") {+ schema.tables = schema.tables.filter(+ (item) => item.name !== tableEdit.name+ );+ continue;+ } else {+ const table = schema.tables.find(+ (item) => item.name === tableEdit.name+ );+ if (!table) {+ continue;+ }+ for (const columnEdit of tableEdit.columnList) {+ if (columnEdit.status === "created") {+ table.columns.push(transformColumnEditToMetadata(columnEdit));+ continue;+ } else if (columnEdit.status === "dropped") {+ table.columns = table.columns.filter(+ (item) => item.name !== columnEdit.name+ );+ continue;+ } else {+ const column = table.columns.find(+ (item) => item.name === columnEdit.name+ );+ if (!column) {+ continue;+ }+ column.type = columnEdit.type;+ column.nullable = columnEdit.nullable;+ column.comment = columnEdit.comment;+ column.default = columnEdit.default;+ }+ }+ }+ }+ }++ for (const foreignKey of schemaEdit.foreignKeyList) {+ const schema = metadata.schemas.find(+ (schema) => schema.name === schemaEdit.name+ );+ if (!schema) {+ continue;+ }+ const tableEdit = schemaEdit.tableList.find(+ (table) => table.id === foreignKey.tableId+ );+ const table = schema.tables.find(+ (table) => table.name === tableEdit?.name+ );+ if (!tableEdit || !table) {+ continue;+ }+ const referencedSchema = metadata.schemas.find(+ (schema) =>+ schema.name ===+ schemaEdits.find(+ (schemaEdit) => schemaEdit.id === foreignKey.referencedSchemaId+ )?.name+ );+ if (!referencedSchema) {+ continue;+ }+ const referencedTableEdit = schemaEdits+ .find((schemaEdit) => schemaEdit.id === foreignKey.referencedSchemaId)+ ?.tableList.find((table) => table.id === foreignKey.referencedTableId);+ const referencedTable = referencedSchema.tables.find(+ (table) => table.name === referencedTableEdit?.name+ );+ if (!referencedTableEdit || !referencedTable) {+ continue;+ }++ const fk = ForeignKeyMetadata.fromPartial({+ name: foreignKey.name,+ referencedSchema: referencedSchema.name,+ referencedTable: referencedTable.name,+ });+ if (+ foreignKey.columnIdList.length !==+ foreignKey.referencedColumnIdList.length+ ) {+ continue;+ }+ for (const columnId of foreignKey.columnIdList) {+ const column = tableEdit.columnList.find(+ (column) => column.id === columnId+ );+ if (column) {+ fk.columns.push(column.name);+ }+ }+ for (const columnId of foreignKey.referencedColumnIdList) {+ const column = referencedTableEdit.columnList.find(+ (column) => column.id === columnId+ );+ if (column) {+ fk.referencedColumns.push(column.name);+ }+ }+ table.foreignKeys.push(fk);+ }+ }++ return metadata;+};++const transformSchemaEditToMetadata = (schemaEdit: Schema): SchemaMetadata => {+ const schemaMetadata = SchemaMetadata.fromPartial({+ name: schemaEdit.name,+ tables: [],+ });++ for (const table of schemaEdit.tableList) {+ const tableMetadata = TableMetadata.fromPartial({+ name: table.name,+ columns: [],+ indexes: [],+ foreignKeys: [],+ });++ for (const column of table.columnList) {+ tableMetadata.columns.push(+ ColumnMetadata.fromPartial({+ name: column.name,+ type: column.type,+ nullable: column.nullable,+ default: column.default,+ comment: column.comment,+ })+ );+ }++ if (table.primaryKey.columnIdList.length > 0) {+ const primaryIndex = IndexMetadata.fromPartial({+ primary: true,+ expressions: [],+ });+ for (const columnId of table.primaryKey.columnIdList) {+ const column = table.columnList.find(+ (column) => column.id === columnId+ );+ if (column) {+ primaryIndex.expressions.push(column.name);+ }+ }+ if (primaryIndex.expressions.length > 0) {+ tableMetadata.indexes.push(primaryIndex);+ }+ }++ schemaMetadata.tables.push(tableMetadata);+ }++ return schemaMetadata;+};++const transformTableEditToMetadata = (tableEdit: Table): TableMetadata => {+ const tableMetadata = TableMetadata.fromPartial({+ name: tableEdit.name,+ columns: [],+ indexes: [],+ foreignKeys: [],+ });++ for (const column of tableEdit.columnList) {+ tableMetadata.columns.push(+ ColumnMetadata.fromPartial({+ name: column.name,+ type: column.type,+ nullable: column.nullable,+ default: column.default,+ comment: column.comment,+ })+ );+ }++ if (tableEdit.primaryKey.columnIdList.length > 0) {+ const primaryIndex = IndexMetadata.fromPartial({+ primary: true,+ expressions: [],+ });+ for (const columnId of tableEdit.primaryKey.columnIdList) {+ const column = tableEdit.columnList.find(+ (column) => column.id === columnId+ );+ if (column) {+ primaryIndex.expressions.push(column.name);+ }+ }+ if (primaryIndex.expressions.length > 0) {+ tableMetadata.indexes.push(primaryIndex);+ }+ }++ return tableMetadata;+};++const transformColumnEditToMetadata = (columnEdit: Column): ColumnMetadata => {+ return ColumnMetadata.fromPartial({+ name: columnEdit.name,+ type: columnEdit.type,+ nullable: columnEdit.nullable,+ default: columnEdit.default,+ comment: columnEdit.comment,+ });+};diff --git a/frontend/src/components/SchemaDesigner/index.vue b/frontend/src/components/SchemaDesigner/index.vueindex e8ff687481..461fa00e47 100644--- a/frontend/src/components/SchemaDesigner/index.vue+++ b/frontend/src/components/SchemaDesigner/index.vue@@ -1,26 +1,13 @@<template>- <div v-if="!state.isLoading" class="w-full h-full">+ <div v-if="!state.isLoading" class="w-full h-[32rem] border rounded-lg"><Splitpanesclass="default-theme w-full h-full flex flex-row overflow-hidden">- <Pane size="20">+ <Pane size="25"><AsidePanel /></Pane>- <Pane min-size="60" size="80">- <main class="pl-2 pt-2 w-full h-full flex flex-col overflow-y-auto">- <template v-if="currentTab">- <TabsContainer />- <div- :key="currentTab.id"- class="w-full h-full relative overflow-y-auto"- >- <TableEditor- v-if="currentTab.type === SchemaDesignerTabType.TabForTable"- />- </div>- </template>- <EmptyTips v-else />- </main>+ <Pane min-size="60" size="75">+ <Designer /></Pane></Splitpanes></div>@@ -28,40 +15,33 @@<script lang="ts" setup>import { Splitpanes, Pane } from "splitpanes";-import { computed, onMounted, reactive, ref } from "vue";-import { useDBSchemaV1Store } from "@/store";-import AsidePanel from "./AsidePanel.vue";-import EmptyTips from "./EmptyTips.vue";-import TabsContainer from "./TabsContainer.vue";-import TableEditor from "./Panels/TableEditor.vue";-import {- provideSchemaDesignerContext,- useSchemaDesignerContext,-} from "./common";+import { onMounted, reactive, ref } from "vue";import { DatabaseMetadata } from "@/types/proto/v1/database_service";+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";import { Engine } from "@/types/proto/v1/common";-import { SchemaDesignerTabState, SchemaDesignerTabType } from "./common/type";+import { provideSchemaDesignerContext } from "./common";+import { SchemaDesignerTabState } from "./common/type";+import AsidePanel from "./AsidePanel.vue";+import Designer from "./Designer.vue";+import { Schema, convertSchemaMetadataList } from "@/types";+import { cloneDeep } from "lodash-es";interface LocalState {isLoading: boolean;}-const props = defineProps({- database: {- type: String,- required: true,- },-});+const props = defineProps<{+ readonly: boolean;+ engine: Engine;+ schemaDesign: SchemaDesign;+}>();+const state = reactive<LocalState>({isLoading: true,});-const { getCurrentTab } = useSchemaDesignerContext();-const dbSchemaStore = useDBSchemaV1Store();-const currentTab = computed(() => {- return getCurrentTab();-});const metadata = ref<DatabaseMetadata>(DatabaseMetadata.fromPartial({}));+const editableSchemas = ref<Schema[]>([]);const baselineMetadata = ref<DatabaseMetadata>(DatabaseMetadata.fromPartial({}));@@ -69,20 +49,31 @@ const tabState = ref<SchemaDesignerTabState>({tabMap: new Map(),});+onMounted(async () => {+ baselineMetadata.value =+ cloneDeep(props.schemaDesign?.baselineSchemaMetadata) ||+ DatabaseMetadata.fromPartial({});+ metadata.value =+ cloneDeep(props.schemaDesign?.schemaMetadata) ||+ DatabaseMetadata.fromPartial({});+ editableSchemas.value = convertSchemaMetadataList(metadata.value.schemas);+ state.isLoading = false;+});+provideSchemaDesignerContext({- metadata,+ readonly: props.readonly,baselineMetadata: baselineMetadata.value,- engine: Engine.MYSQL,+ engine: props.engine,+ metadata: metadata,tabState: tabState,+ originalSchemas: cloneDeep(editableSchemas.value),+ editableSchemas: editableSchemas,});-onMounted(async () => {- const databaseMetadata = await dbSchemaStore.getOrFetchDatabaseMetadata(- props.database- );- baselineMetadata.value = databaseMetadata;- metadata.value = databaseMetadata;- state.isLoading = false;+defineExpose({+ metadata,+ baselineMetadata,+ editableSchemas,});</script>diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vueindex 3d7dccf40e..748a989d28 100644--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue+++ b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue@@ -431,7 +431,7 @@ const columnHeaderList = computed(() => {},{key: "foreign_key",- label: "Foreign Key",+ label: t("schema-editor.column.foreign-key"),},];});diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 7d7ec97d76..f541a8c575 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -92,6 +92,7 @@"id": "ID","name": "Name","creator": "Creator",+ "updater": "Updater","version": "Version","issue": "Issue","issues": "Issues",@@ -1131,6 +1132,7 @@"alter-schema-in-vcs": "Alter Schema in VCS","change-data": "Change Data","change-data-in-vcs": "Change Data in VCS",+ "design-schema": "Design Schema","successfully-transferred-updateddatabase-name-to-project-updateddatabase-project-name": "Successfully transferred '{0}' to project '{1}'.","backup-name": "Backup name","create-backup": "Create backup",@@ -1841,7 +1843,8 @@"default": "Default","comment": "Comment","not-null": "Not Null",- "primary": "Primary"+ "primary": "Primary",+ "foreign-key": "Foreign Key"},"nothing-changed": "Nothing changed","message": {@@ -2682,5 +2685,19 @@},"export-center": {"self": "Export Center"+ },+ "schema-designer": {+ "self": "Schema Designer",+ "quick-action": "Design Schema",+ "existing-schema-design": "Existing Schema Design",+ "new-schema-design": "New Schema Design",+ "baseline-database": "Baseline database",+ "schema-version": "Schema version",+ "tables": "Tables",+ "apply-to-database": "Apply to database",+ "message": {+ "created-succeed": "Schema design created successfully",+ "updated-succeed": "Schema design updated successfully"+ }}}diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex b90e91d2da..60958f05a4 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1841,7 +1841,8 @@"default": "Valor predeterminado","comment": "Comentario","not-null": "No nulo",- "primary": "Primaria"+ "primary": "Primaria",+ "foreign-key": "Clave foránea"},"nothing-changed": "Nada ha cambiado","message": {@@ -2683,5 +2684,19 @@},"export-center": {"self": "centro de exportacion"+ },+ "schema-designer": {+ "self": "Diseñador de esquemas",+ "quick-action": "Diseñar esquema",+ "existing-schema-design": "Diseño de esquema existente",+ "new-schema-design": "Nuevo diseño de esquema",+ "baseline-database": "Base de datos de referencia",+ "schema-version": "Versión del esquema",+ "tables": "Tablas",+ "apply-to-database": "Aplicar a la base de datos",+ "message": {+ "created-succeed": "Diseño de esquema creado con éxito",+ "updated-succeed": "Diseño de esquema actualizado con éxito"+ }}}diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex da81ada14c..3ab15fca22 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1837,7 +1837,8 @@"default": "默认值","comment": "注释","not-null": "不可为空",- "primary": "主键"+ "primary": "主键",+ "foreign-key": "外键"},"nothing-changed": "无任何改动","message": {@@ -2675,5 +2676,19 @@},"export-center": {"self": "导出中心"+ },+ "schema-designer": {+ "self": "Schema 设计器",+ "quick-action": "设计 Schema",+ "existing-schema-design": "现有的 Schema 设计",+ "new-schema-design": "创建 Schema 设计",+ "baseline-database": "基准数据库",+ "schema-version": "Schema 版本",+ "tables": "表",+ "apply-to-database": "应用 Schema 设计",+ "message": {+ "created-succeed": "Schema 设计创建成功",+ "updated-succeed": "Schema 设计更新成功"+ }}}diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex be7e84a9c0..3464438d20 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -159,12 +159,14 @@ const routes: Array<RouteRecordRaw> = [quickActionListByRole: () => {const DBA_AND_OWNER_QUICK_ACTION_LIST: QuickActionType[] = ["quickaction.bb.database.schema.update",+ "quickaction.bb.database.schema.design","quickaction.bb.database.data.update","quickaction.bb.database.create","quickaction.bb.instance.create",];const DEVELOPER_QUICK_ACTION_LIST: QuickActionType[] = ["quickaction.bb.database.schema.update",+ "quickaction.bb.database.schema.design","quickaction.bb.database.data.update","quickaction.bb.database.create","quickaction.bb.issue.grant.request.querier",@@ -670,6 +672,7 @@ const routes: Array<RouteRecordRaw> = [if (project.state === State.ACTIVE) {const DBA_AND_OWNER_QUICK_ACTION_LIST: QuickActionType[] = ["quickaction.bb.database.schema.update",+ "quickaction.bb.database.schema.design","quickaction.bb.database.data.update","quickaction.bb.database.create","quickaction.bb.project.database.transfer",@@ -690,6 +693,7 @@ const routes: Array<RouteRecordRaw> = [// to be changed.DEVELOPER_QUICK_ACTION_LIST.push("quickaction.bb.database.schema.update",+ "quickaction.bb.database.schema.design","quickaction.bb.database.data.update","quickaction.bb.database.create");@@ -830,11 +834,13 @@ const routes: Array<RouteRecordRaw> = [quickActionListByRole: () => {const DBA_AND_OWNER_QUICK_ACTION_LIST: QuickActionType[] = ["quickaction.bb.database.schema.update",+ "quickaction.bb.database.schema.design","quickaction.bb.database.data.update","quickaction.bb.database.create",];const DEVELOPER_QUICK_ACTION_LIST: QuickActionType[] = ["quickaction.bb.database.schema.update",+ "quickaction.bb.database.schema.design","quickaction.bb.database.data.update","quickaction.bb.database.create","quickaction.bb.issue.grant.request.querier",diff --git a/frontend/src/store/modules/schemaDesign.ts b/frontend/src/store/modules/schemaDesign.tsindex 133c373d9c..9de0d0a016 100644--- a/frontend/src/store/modules/schemaDesign.ts+++ b/frontend/src/store/modules/schemaDesign.ts@@ -1,7 +1,9 @@-import { computed, reactive, ref, watch } from "vue";+import { computed, reactive, ref, watchEffect } from "vue";import { defineStore } from "pinia";import { schemaDesignServiceClient } from "@/grpcweb";import { SchemaDesign } from "@/types/proto/v1/schema_design_service";+import { Engine } from "@/types/proto/v1/common";+import { DatabaseMetadata } from "@/types/proto/v1/database_service";export const useSchemaDesignStore = defineStore("schema_design", () => {const schemaDesignMapByName = reactive(new Map<string, SchemaDesign>());@@ -15,7 +17,9 @@ export const useSchemaDesignStore = defineStore("schema_design", () => {// Actionsconst fetchSchemaDesignList = async () => {const { schemaDesigns } = await schemaDesignServiceClient.listSchemaDesigns(- {}+ {+ parent: "projects/-",+ });for (const schemaDesign of schemaDesigns) {schemaDesignMapByName.set(schemaDesign.name, schemaDesign);@@ -28,7 +32,7 @@ export const useSchemaDesignStore = defineStore("schema_design", () => {) => {const createdSchemaDesign =await schemaDesignServiceClient.createSchemaDesign({- parent: `projects/${projectResourceId}`,+ parent: projectResourceId,schemaDesign,});schemaDesignMapByName.set(createdSchemaDesign.name, createdSchemaDesign);@@ -70,6 +74,28 @@ export const useSchemaDesignStore = defineStore("schema_design", () => {return getSchemaDesignByName(name);};+ // Util functions+ const parseSchemaString = async (+ schema: string,+ engine: Engine+ ): Promise<DatabaseMetadata> => {+ try {+ const { schemaMetadata } =+ await schemaDesignServiceClient.parseSchemaString(+ {+ schemaString: schema,+ engine,+ },+ {+ silent: true,+ }+ );+ return schemaMetadata || DatabaseMetadata.fromPartial({});+ } catch (error) {+ return DatabaseMetadata.fromPartial({});+ }+ };+return {schemaDesignList,fetchSchemaDesignList,@@ -78,22 +104,21 @@ export const useSchemaDesignStore = defineStore("schema_design", () => {fetchSchemaDesignByName,getOrFetchSchemaDesignByName,getSchemaDesignByName,+ parseSchemaString,};});export const useSchemaDesignList = () => {const store = useSchemaDesignStore();const ready = ref(false);- watch(- [],- () => {- ready.value = false;- store.fetchSchemaDesignList().then(() => {- ready.value = true;- });- },- { immediate: true }- );++ watchEffect(() => {+ ready.value = false;+ store.fetchSchemaDesignList().then(() => {+ ready.value = true;+ });+ });+const schemaDesignList = computed(() => {return store.schemaDesignList;});diff --git a/frontend/src/store/modules/v1/changeHistory.ts b/frontend/src/store/modules/v1/changeHistory.tsindex 4654c20155..b864809500 100644--- a/frontend/src/store/modules/v1/changeHistory.ts+++ b/frontend/src/store/modules/v1/changeHistory.ts@@ -1,6 +1,5 @@import { defineStore } from "pinia";import { reactive } from "vue";-import { databaseServiceClient } from "@/grpcweb";import {ChangeHistory,@@ -49,6 +48,11 @@ export const useChangeHistoryStore = defineStore("changeHistory_v1", () => {await upsertChangeHistoryMap([changeHistory]);return changeHistory;};+ const getOrFetchChangeHistoryByName = async (name: string) => {+ const changeHistory = changeHistoryMapByName.get(name);+ if (changeHistory) return changeHistory;+ return await fetchChangeHistory({ name });+ };const getChangeHistoryByName = (name: string) => {return changeHistoryMapByName.get(name);};@@ -57,6 +61,7 @@ export const useChangeHistoryStore = defineStore("changeHistory_v1", () => {fetchChangeHistoryList,changeHistoryListByDatabase,fetchChangeHistory,+ getOrFetchChangeHistoryByName,getChangeHistoryByName,};});diff --git a/frontend/src/types/quickAction.ts b/frontend/src/types/quickAction.tsindex 65360de126..75c6241deb 100644--- a/frontend/src/types/quickAction.ts+++ b/frontend/src/types/quickAction.ts@@ -11,6 +11,8 @@ export type DatabaseQuickActionType =| "quickaction.bb.database.create" // Used by DBA and Owner| "quickaction.bb.database.request" // Used by Developer (not yet)| "quickaction.bb.database.schema.update"+ // Schema designer quick action. (Maybe will be removed after changelist is implemented)+ | "quickaction.bb.database.schema.design"| "quickaction.bb.database.data.update"| "quickaction.bb.database.troubleshoot";export type IssueQuickActionType =