Skip to content

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

feat: apply schema design in sync schema (#7160)

boojack69e1c9a1d455
diff --git a/backend/api/v1/schema_design_service.go b/backend/api/v1/schema_design_service.go
index 749df34b72..a0a1d89a8b 100644
--- a/backend/api/v1/schema_design_service.go
+++ b/backend/api/v1/schema_design_service.go
@@ -185,6 +185,10 @@ func (s *SchemaDesignService) CreateSchemaDesign(ctx context.Context, request *v
if err != nil {
return nil, err
}
+ // Try to transform the schema string to database metadata to make sure it's valid.
+ if _, err := transformSchemaStringToDatabaseMetadata(schemaDesign.Engine, schema); err != nil {
+ return nil, status.Errorf(codes.Internal, fmt.Sprintf("failed to transform schema string to database metadata: %v", err))
+ }
sheetCreate := &store.SheetMessage{
Name: schemaDesign.Title,
@@ -240,6 +244,10 @@ func (s *SchemaDesignService) UpdateSchemaDesign(ctx context.Context, request *v
if err != nil {
return nil, err
}
+ // Try to transform the schema string to database metadata to make sure it's valid.
+ if _, err := transformSchemaStringToDatabaseMetadata(schemaDesign.Engine, schema); err != nil {
+ return nil, status.Errorf(codes.Internal, fmt.Sprintf("failed to transform schema string to database metadata: %v", err))
+ }
sheetUpdate.Statement = &schema
}
sheet, err := s.store.PatchSheet(ctx, sheetUpdate)
diff --git a/frontend/src/bbkit/BBStepTab.vue b/frontend/src/bbkit/BBStepTab.vue
index 8192315d0e..ba9b30b0d2 100644
--- a/frontend/src/bbkit/BBStepTab.vue
+++ b/frontend/src/bbkit/BBStepTab.vue
@@ -168,4 +168,8 @@ const finish = () => {
const cancel = () => {
emit("cancel");
};
+
+defineExpose({
+ changeStep,
+});
</script>
diff --git a/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue b/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue
index d4092487ef..0656a1ff88 100644
--- a/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue
+++ b/frontend/src/components/SchemaDesigner/CreateSchemaDesignPanel.vue
@@ -100,7 +100,10 @@ defineProps({
default: undefined,
},
});
-const emit = defineEmits(["dismiss"]);
+const emit = defineEmits<{
+ (event: "dismiss"): void;
+ (event: "created", schemaDesign: SchemaDesign): void;
+}>();
const { t } = useI18n();
const schemaDesignerRef = ref<InstanceType<typeof SchemaDesigner>>();
@@ -201,7 +204,7 @@ const handleConfirm = async () => {
DatabaseMetadata.fromPartial({})
);
const baselineDatabase = `${database.instanceEntity.name}/${databaseNamePrefix}${state.baselineSchema.databaseId}`;
- await schemaDesignStore.createSchemaDesign(
+ const createdSchemaDesign = await schemaDesignStore.createSchemaDesign(
project.value.name,
SchemaDesign.fromPartial({
title: state.schemaDesignName,
@@ -220,5 +223,6 @@ const handleConfirm = async () => {
style: "SUCCESS",
title: t("schema-designer.message.created-succeed"),
});
+ emit("created", createdSchemaDesign);
};
</script>
diff --git a/frontend/src/components/SchemaDesigner/DatabaseTree.vue b/frontend/src/components/SchemaDesigner/DatabaseTree.vue
index dc9fbc12ca..e62f1deabe 100644
--- a/frontend/src/components/SchemaDesigner/DatabaseTree.vue
+++ b/frontend/src/components/SchemaDesigner/DatabaseTree.vue
@@ -13,7 +13,7 @@
</p>
<NInput
v-model:value="searchPattern"
- :placeholder="$t('schema-editor.search-database-and-table')"
+ :placeholder="$t('schema-designer.search-tables')"
>
<template #prefix>
<heroicons-outline:search class="w-4 h-auto text-gray-300" />
diff --git a/frontend/src/components/SchemaDesigner/EmptyTips.vue b/frontend/src/components/SchemaDesigner/EmptyTips.vue
index b74e12488c..f4b03d6613 100644
--- a/frontend/src/components/SchemaDesigner/EmptyTips.vue
+++ b/frontend/src/components/SchemaDesigner/EmptyTips.vue
@@ -3,6 +3,6 @@
class="w-full h-full flex flex-row justify-center items-center text-gray-600 font-medium"
>
<heroicons-solid:pencil-square class="w-4 h-auto mr-2" />
- {{ $t("schema-editor.use-tips") }}
+ {{ $t("schema-designer.use-tips") }}
</div>
</template>
diff --git a/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue b/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue
index 9ea79064e1..30b6400bbd 100644
--- a/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue
+++ b/frontend/src/components/SchemaDesigner/Panels/TableEditor.vue
@@ -125,7 +125,7 @@
<input
v-model="column.default"
:disabled="disableAlterColumn(column)"
- :placeholder="column.default === undefined ? 'NULL' : 'EMPTY'"
+ :placeholder="column.default === undefined ? 'EMPTY' : 'NULL'"
class="column-field-input !pr-8"
type="text"
/>
@@ -498,9 +498,9 @@ const handleColumnDefaultFieldChange = (
defaultString: string
) => {
if (defaultString === "NULL") {
- column.default = undefined;
+ column.default = "NULL";
} else if (defaultString === "EMPTY") {
- column.default = "";
+ column.default = undefined;
}
};
diff --git a/frontend/src/components/SchemaDesigner/PrepForm/TargetDatabaseSelectPanel.vue b/frontend/src/components/SchemaDesigner/PrepForm/TargetDatabaseSelectPanel.vue
deleted file mode 100644
index 47560689a5..0000000000
--- a/frontend/src/components/SchemaDesigner/PrepForm/TargetDatabaseSelectPanel.vue
+++ /dev/null
@@ -1,281 +0,0 @@
-<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.vue
index 13c8fe0d68..6300ff78b0 100644
--- a/frontend/src/components/SchemaDesigner/PrepForm/index.vue
+++ b/frontend/src/components/SchemaDesigner/PrepForm/index.vue
@@ -45,11 +45,9 @@
<NButton @click="state.isEditing = true">{{
$t("common.edit")
}}</NButton>
- <NButton
- type="primary"
- @click="state.showSelectTargetDatabasePanel = true"
- >{{ $t("schema-designer.apply-to-database") }}</NButton
- >
+ <NButton type="primary" @click="handleApplySchemaDesignClick">{{
+ $t("schema-designer.apply-to-database")
+ }}</NButton>
</template>
<template v-else>
<NButton @click="handleCancelEdit">{{
@@ -110,17 +108,15 @@
</div>
</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"
- />
-
<CreateSchemaDesignPanel
v-if="state.showCreatePanel"
@dismiss="state.showCreatePanel = false"
+ @created="
+ (schemaDesign) => {
+ state.showCreatePanel = false;
+ handleSchemaDesignItemClick(schemaDesign);
+ }
+ "
/>
</template>
@@ -147,8 +143,8 @@ import SchemaDesignTable from "./SchemaDesignTable.vue";
import SchemaDesigner from "../index.vue";
import { mergeSchemaEditToMetadata } from "../common/util";
import { DatabaseV1Name, InstanceV1EngineIcon } from "@/components/v2";
-import TargetDatabaseSelectPanel from "./TargetDatabaseSelectPanel.vue";
import CreateSchemaDesignPanel from "../CreateSchemaDesignPanel.vue";
+import { useRouter } from "vue-router";
interface BaselineSchema {
// The uid of project.
@@ -162,7 +158,6 @@ interface LocalState {
schemaDesignName: string;
baselineSchema: BaselineSchema;
isEditing: boolean;
- showSelectTargetDatabasePanel: boolean;
selectedSchemaDesign?: SchemaDesign;
showCreatePanel: boolean;
}
@@ -176,6 +171,7 @@ defineProps({
defineEmits(["dismiss"]);
const { t } = useI18n();
+const router = useRouter();
const schemaDesignerRef = ref<InstanceType<typeof SchemaDesigner>>();
const databaseStore = useDatabaseV1Store();
const schemaDesignStore = useSchemaDesignStore();
@@ -184,7 +180,6 @@ const state = reactive<LocalState>({
schemaDesignName: "",
baselineSchema: {},
isEditing: false,
- showSelectTargetDatabasePanel: false,
showCreatePanel: false,
});
const isViewing = computed(
@@ -272,4 +267,13 @@ const handleUpdateSchemaDesign = async () => {
title: t("schema-designer.message.updated-succeed"),
});
};
+
+const handleApplySchemaDesignClick = () => {
+ router.push({
+ name: "workspace.sync-schema",
+ query: {
+ schemaDesignName: state.selectedSchemaDesign?.name,
+ },
+ });
+};
</script>
diff --git a/frontend/src/components/SchemaDesigner/common/util.ts b/frontend/src/components/SchemaDesigner/common/util.ts
index e41ffb9428..948b96842d 100644
--- a/frontend/src/components/SchemaDesigner/common/util.ts
+++ b/frontend/src/components/SchemaDesigner/common/util.ts
@@ -7,6 +7,7 @@ import {
SchemaMetadata,
TableMetadata,
} from "@/types/proto/v1/database_service";
+import { randomString } from "@/utils";
export const mergeSchemaEditToMetadata = (
schemaEdits: Schema[],
@@ -106,11 +107,17 @@ export const mergeSchemaEditToMetadata = (
continue;
}
+ const foreignKeyName = foreignKey.name
+ ? foreignKey.name
+ : `${table.name}-fk-${randomString(4).toLowerCase()}`;
const fk = ForeignKeyMetadata.fromPartial({
- name: foreignKey.name,
+ name: foreignKeyName,
referencedSchema: referencedSchema.name,
referencedTable: referencedTable.name,
});
+ if (table.foreignKeys.find((fk) => fk.name === foreignKeyName)) {
+ continue;
+ }
if (
foreignKey.columnIdList.length !==
foreignKey.referencedColumnIdList.length
diff --git a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
index 748a989d28..30fed1557e 100644
--- a/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
+++ b/frontend/src/components/SchemaEditor/Panels/TableEditor.vue
@@ -144,7 +144,7 @@
<input
v-model="column.default"
:disabled="disableAlterColumn(column)"
- :placeholder="column.default === undefined ? 'NULL' : 'EMPTY'"
+ :placeholder="column.default === undefined ? 'EMPTY' : 'NULL'"
class="column-field-input !pr-8"
type="text"
/>
@@ -654,9 +654,9 @@ const handleColumnDefaultFieldChange = (
defaultString: string
) => {
if (defaultString === "NULL") {
- column.default = undefined;
+ column.default = "NULL";
} else if (defaultString === "EMPTY") {
- column.default = "";
+ column.default = undefined;
}
};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 02460c8319..02161f9922 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2689,11 +2689,14 @@
"schema-designer": {
"self": "Schema Designer",
"quick-action": "Design Schema",
+ "schema-design": "Schema Design",
"schema-design-list": "Schema Design List",
"new-schema-design": "New Schema Design",
"baseline-database": "Baseline database",
"schema-version": "Schema version",
"tables": "Tables",
+ "search-tables": "Search tables",
+ "use-tips": "Click a table to start.",
"apply-to-database": "Apply to database",
"message": {
"created-succeed": "Schema design created successfully",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index a09517213d..e99f274425 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2688,12 +2688,15 @@
"schema-designer": {
"self": "Diseñador de esquemas",
"quick-action": "Diseñar esquema",
+ "schema-design": "Esquema diseñar",
"schema-design-list": "Lista de 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",
+ "search-tables": "Buscar tablas",
+ "use-tips": "Selecciona las tablas a diseñar",
"apply-to-database": "Aplicar a la base de datos",
"message": {
"created-succeed": "Diseño de esquema creado con éxito",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 119ddcdf13..5dac25079a 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2680,11 +2680,14 @@
"schema-designer": {
"self": "Schema 设计器",
"quick-action": "设计 Schema",
+ "schema-design": "Schema 设计",
"schema-design-list": "Schema 设计列表",
"new-schema-design": "创建 Schema 设计",
"baseline-database": "基准数据库",
"schema-version": "Schema 版本",
"tables": "表",
+ "search-tables": "搜索表",
+ "use-tips": "选择需要设计的表",
"apply-to-database": "应用 Schema 设计",
"message": {
"created-succeed": "Schema 设计创建成功",
diff --git a/frontend/src/store/modules/schemaDesign.ts b/frontend/src/store/modules/schemaDesign.ts
index 9de0d0a016..5ba1ec6815 100644
--- a/frontend/src/store/modules/schemaDesign.ts
+++ b/frontend/src/store/modules/schemaDesign.ts
@@ -36,7 +36,7 @@ export const useSchemaDesignStore = defineStore("schema_design", () => {
schemaDesign,
});
schemaDesignMapByName.set(createdSchemaDesign.name, createdSchemaDesign);
- return schemaDesignMapByName;
+ return createdSchemaDesign;
};
const updateSchemaDesign = async (
schemaDesign: SchemaDesign,
diff --git a/frontend/src/types/schemaEditor/atomType.ts b/frontend/src/types/schemaEditor/atomType.ts
index 0c2f8ade42..496194ef00 100644
--- a/frontend/src/types/schemaEditor/atomType.ts
+++ b/frontend/src/types/schemaEditor/atomType.ts
@@ -1,10 +1,10 @@
import { isGhostTable } from "@/utils";
import { v1 as uuidv1 } from "uuid";
import {
- ColumnMetadata,
SchemaMetadata,
TableMetadata,
-} from "../proto/store/database";
+ ColumnMetadata,
+} from "../proto/v1/database_service";
type AtomResourceStatus = "normal" | "created" | "dropped";
diff --git a/frontend/src/utils/table.ts b/frontend/src/utils/table.ts
index 036feeb44f..8514693088 100644
--- a/frontend/src/utils/table.ts
+++ b/frontend/src/utils/table.ts
@@ -1,4 +1,4 @@
-import { TableMetadata } from "@/types/proto/store/database";
+import { TableMetadata } from "@/types/proto/v1/database_service";
export function isGhostTable(table: TableMetadata): boolean {
const { name } = table;
diff --git a/frontend/src/views/SyncDatabaseSchema/DatabaseSchemaSelector.vue b/frontend/src/views/SyncDatabaseSchema/DatabaseSchemaSelector.vue
new file mode 100644
index 0000000000..510f2fd826
--- /dev/null
+++ b/frontend/src/views/SyncDatabaseSchema/DatabaseSchemaSelector.vue
@@ -0,0 +1,341 @@
+<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">
+ {{ $t("database.sync-schema.schema-version.self") }}
+ </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>
+ <template v-if="shouldShowMoreVersionButton" #suffixItem>
+ <div
+ class="w-full flex flex-row justify-start items-center pl-3 leading-8 text-accent cursor-pointer hover:opacity-80"
+ @click.prevent.capture="() => (state.showFeatureModal = true)"
+ >
+ <heroicons-solid:sparkles class="w-4 h-auto mr-1" />
+ {{ $t("database.sync-schema.more-version") }}
+ </div>
+ </template>
+ </BBSelect>
+ </div>
+ </div>
+ </div>
+
+ <FeatureModal
+ feature="bb.feature.sync-schema-all-versions"
+ :open="state.showFeatureModal"
+ :instance="database?.instanceEntity"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import {
+ useChangeHistoryStore,
+ useDBSchemaV1Store,
+ useDatabaseV1Store,
+ useSubscriptionV1Store,
+} 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 { head, isNull, isUndefined } from "lodash-es";
+import { computed, onMounted, reactive, ref, watch } from "vue";
+import { instanceV1Name } from "@/utils";
+import { ChangeHistorySourceSchema } from "./types";
+
+const props = defineProps<{
+ selectState?: ChangeHistorySourceSchema;
+}>();
+
+const emit = defineEmits<{
+ (event: "update", state: LocalState): void;
+}>();
+
+interface LocalState {
+ showFeatureModal: boolean;
+ projectId?: string;
+ environmentId?: string;
+ databaseId?: string;
+ changeHistory?: ChangeHistory;
+}
+
+const state = reactive<LocalState>({
+ showFeatureModal: false,
+});
+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 hasSyncSchemaFeature = computed(() => {
+ return useSubscriptionV1Store().hasInstanceFeature(
+ "bb.feature.sync-schema-all-versions",
+ database.value?.instanceEntity
+ );
+});
+
+const shouldShowMoreVersionButton = computed(() => {
+ return (
+ hasSyncSchemaFeature.value &&
+ databaseChangeHistoryList(state.databaseId as string).length > 0
+ );
+});
+
+const prepareChangeHistoryList = async () => {
+ if (!database.value) {
+ return;
+ }
+
+ await changeHistoryStore.fetchChangeHistoryList({
+ parent: database.value.name,
+ });
+};
+
+onMounted(async () => {
+ if (props.selectState?.databaseId) {
+ try {
+ const database = await databaseStore.getOrFetchDatabaseByUID(
+ props.selectState.databaseId || ""
+ );
+ state.projectId = props.selectState.projectId;
+ state.databaseId = database.uid;
+ state.environmentId = database.instanceEntity.environmentEntity.uid;
+ state.changeHistory = props.selectState.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, Engine.POSTGRES];
+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.databaseId],
+ async () => {
+ const databaseId = state.databaseId;
+ if (!isValidId(databaseId)) {
+ state.changeHistory = undefined;
+ return;
+ }
+
+ const database = databaseStore.getDatabaseByUID(databaseId);
+ if (database) {
+ const changeHistoryList = (
+ await changeHistoryStore.fetchChangeHistoryList({
+ parent: database.name,
+ })
+ ).filter((changeHistory) =>
+ allowedMigrationTypeList.includes(changeHistory.type)
+ );
+
+ if (changeHistoryList.length > 0) {
+ // Default select the first migration history.
+ state.changeHistory = head(changeHistoryList);
+ } else {
+ // If database has no migration history, we will use its latest schema.
+ const schema = await databaseStore.fetchDatabaseSchema(
+ `${database.name}/schema`
+ );
+ state.changeHistory = {
+ name: `${database.name}/changeHistories/${UNKNOWN_ID}`,
+ uid: String(UNKNOWN_ID),
+ updateTime: new Date(),
+ schema: schema.schema,
+ version: "Latest version",
+ description: "the latest schema of database",
+ } as ChangeHistory;
+ }
+ } else {
+ state.changeHistory = undefined;
+ }
+ }
+);
+
+watch(
+ () => [state, fullViewChangeHistoryCache.value],
+ () => {
+ const fullViewChangeHistory = fullViewChangeHistoryCache.value.get(
+ state.changeHistory?.name || ""
+ );
+ emit("update", {
+ ...state,
+ changeHistory: fullViewChangeHistory || state.changeHistory,
+ });
+ },
+ { deep: true }
+);
+</script>
diff --git a/frontend/src/views/SyncDatabaseSchema/DiffViewPanel.vue b/frontend/src/views/SyncDatabaseSchema/DiffViewPanel.vue
index 1cace35447..cd131a51f3 100644
--- a/frontend/src/views/SyncDatabaseSchema/DiffViewPanel.vue
+++ b/frontend/src/views/SyncDatabaseSchema/DiffViewPanel.vue
@@ -66,16 +66,17 @@
</template>
<script lang="ts" setup>
-import { computed, ref } from "vue";
+import { ref } from "vue";
import { CodeDiff } from "v-code-diff";
import { NTabs, NTab } from "naive-ui";
import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";
-import { ComposedDatabase, dialectOfEngineV1 } from "@/types";
+import { dialectOfEngineV1 } from "@/types";
+import { Engine } from "@/types/proto/v1/common";
-const props = defineProps<{
+defineProps<{
statement: string;
- sourceDatabase: ComposedDatabase;
+ engine: Engine;
targetDatabaseSchema: string;
sourceDatabaseSchema: string;
shouldShowDiff: boolean;
@@ -90,10 +91,6 @@ const $emit = defineEmits<{
const tab = ref<"diff" | "ddl">("diff");
const editorRef = ref<InstanceType<typeof MonacoEditor>>();
-const engine = computed(() => {
- return props.sourceDatabase.instanceEntity.engine;
-});
-
const updateEditorHeight = () => {
const contentHeight =
editorRef.value?.editorInstance?.getContentHeight() as number;
diff --git a/frontend/src/views/SyncDatabaseSchema/SchemaDesignSelector.vue b/frontend/src/views/SyncDatabaseSchema/SchemaDesignSelector.vue
new file mode 100644
index 0000000000..ed3dd7018b
--- /dev/null
+++ b/frontend/src/views/SyncDatabaseSchema/SchemaDesignSelector.vue
@@ -0,0 +1,141 @@
+<template>
+ <div class="w-full" v-bind="$attrs">
+ <div
+ class="w-full mb-4 flex flex-row justify-between items-center space-x-2"
+ >
+ <span>
+ {{ $t("schema-designer.schema-design-list") }}
+ </span>
+ <div>
+ <NButton type="primary" @click="state.showCreatePanel = true">{{
+ $t("common.create")
+ }}</NButton>
+ </div>
+ </div>
+ <BBGrid
+ class="border"
+ :column-list="COLUMN_LIST"
+ :data-source="schemaDesignList"
+ @click-row="clickSchemaDesign"
+ >
+ <template #item="{ item: schemaDesign }: { item: SchemaDesign }">
+ <div class="bb-grid-cell">
+ <NRadio :checked="schemaDesign.name === selectedSchemaDesign?.name" />
+ </div>
+ <div class="bb-grid-cell">
+ {{ schemaDesign.title }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).project }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ engineNameV1(getFormatedValue(schemaDesign).engine) }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).creator }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ getFormatedValue(schemaDesign).updater }}
+ </div>
+ <div class="bb-grid-cell">
+ <HumanizeTs
+ :ts="(schemaDesign.updateTime?.getTime() ?? 0) / 1000"
+ class="ml-1"
+ />
+ </div>
+ </template>
+ </BBGrid>
+ </div>
+
+ <CreateSchemaDesignPanel
+ v-if="state.showCreatePanel"
+ @dismiss="state.showCreatePanel = false"
+ @created="
+ (schemaDesign) => {
+ state.showCreatePanel = false;
+ clickSchemaDesign(schemaDesign);
+ }
+ "
+ />
+</template>
+
+<script lang="ts" setup>
+import dayjs from "dayjs";
+import { computed, ref, reactive } from "vue";
+import { useI18n } from "vue-i18n";
+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 { engineNameV1, projectV1Name } from "@/utils";
+import { useSchemaDesignList } from "@/store/modules/schemaDesign";
+import { NRadio } from "naive-ui";
+import CreateSchemaDesignPanel from "@/components/SchemaDesigner/CreateSchemaDesignPanel.vue";
+
+interface LocalState {
+ showCreatePanel: boolean;
+}
+
+const emit = defineEmits<{
+ (event: "select", schemaDesign: SchemaDesign): void;
+}>();
+
+const props = defineProps<{
+ selectedSchemaDesign?: SchemaDesign;
+}>();
+
+const { t } = useI18n();
+const projectV1Store = useProjectV1Store();
+const { schemaDesignList } = useSchemaDesignList();
+const state = reactive<LocalState>({
+ showCreatePanel: false,
+});
+const selectedSchemaDesign = ref<SchemaDesign | undefined>(
+ props.selectedSchemaDesign
+);
+
+const COLUMN_LIST = computed(() => {
+ const columns: BBGridColumn[] = [
+ { title: "", width: "3rem" },
+ { title: t("common.name"), width: "1fr" },
+ {
+ title: t("common.project"),
+ width: "1fr",
+ },
+ {
+ title: t("database.engine"),
+ width: "1fr",
+ },
+ { title: t("common.creator"), width: "minmax(auto, 10rem)" },
+ { title: t("common.updater"), width: "minmax(auto, 10rem)" },
+ { title: t("common.updated-at"), width: "minmax(auto, 10rem)" },
+ ];
+
+ return columns;
+});
+
+const getFormatedValue = (schemaDesign: SchemaDesign) => {
+ const [projectName] = getProjectAndSchemaDesignSheetId(schemaDesign.name);
+ const project = projectV1Store.getProjectByName(`projects/${projectName}`);
+
+ return {
+ name: schemaDesign.title,
+ project: projectV1Name(project),
+ engine: schemaDesign.engine,
+ creator:
+ useUserStore().getUserByIdentifier(schemaDesign.creator)?.title ??
+ schemaDesign.creator,
+ updater:
+ useUserStore().getUserByIdentifier(schemaDesign.updater)?.title ??
+ schemaDesign.updater,
+ updated: dayjs
+ .duration((schemaDesign.updateTime ?? new Date()).getTime() - Date.now())
+ .humanize(true),
+ };
+};
+
+const clickSchemaDesign = (schemaDesign: SchemaDesign) => {
+ selectedSchemaDesign.value = schemaDesign;
+ emit("select", schemaDesign);
+};
+</script>
diff --git a/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue b/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue
index 190d961b21..7e4deea226 100644
--- a/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue
+++ b/frontend/src/views/SyncDatabaseSchema/SelectTargetDatabasesView.vue
@@ -4,42 +4,66 @@
>
<div class="w-full flex flex-row gap-8">
<span>{{ $t("database.sync-schema.source-schema") }}</span>
- <div class="space-y-2">
- <div>
- <span>{{ $t("common.project") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="`/project/${projectV1Slug(project)}`"
- >{{ project.title }}</a
- >
- </div>
- <div>
- <span>{{ $t("common.environment") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="`/environment#${environment.uid}`"
- >{{ environment.title }}</a
- >
+ <template
+ v-if="sourceSchemaType === 'DATABASE_SCHEMA' && databaseSourceSchema"
+ >
+ <div class="space-y-2">
+ <div>
+ <span>{{ $t("common.project") }} - </span>
+ <a
+ class="normal-link inline-flex items-center"
+ :href="`/project/${projectV1Slug(project)}`"
+ >{{ project.title }}</a
+ >
+ </div>
+ <div>
+ <span>{{ $t("common.environment") }} - </span>
+ <a
+ class="normal-link inline-flex items-center"
+ :href="`/environment#${getDatabaseSourceSchemaEnvironment()!.uid}`"
+ >{{ getDatabaseSourceSchemaEnvironment()!.title }}</a
+ >
+ </div>
</div>
- </div>
- <div class="space-y-2">
- <div>
- <span>{{ $t("common.database") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="`/db/${databaseV1Slug(sourceDatabase)}`"
- >{{ sourceDatabase.databaseName }}</a
+ <div class="space-y-2">
+ <div>
+ <span>{{ $t("common.database") }} - </span>
+ <a
+ class="normal-link inline-flex items-center"
+ :href="`/db/${databaseV1Slug(getSourceDatabase()!)}`"
+ >{{ getSourceDatabase()!.databaseName }}</a
+ >
+ </div>
+ <div
+ v-if="databaseSourceSchema.changeHistory.uid !== String(UNKNOWN_ID)"
>
+ <span>{{ $t("database.sync-schema.schema-version.self") }} - </span>
+ <a
+ class="normal-link inline-flex items-center"
+ :href="changeHistoryLink(databaseSourceSchema.changeHistory)"
+ >{{ databaseSourceSchema.changeHistory.version }}</a
+ >
+ </div>
</div>
- <div v-if="sourceSchema.changeHistory.uid !== String(UNKNOWN_ID)">
- <span>{{ $t("database.sync-schema.schema-version.self") }} - </span>
- <a
- class="normal-link inline-flex items-center"
- :href="changeHistoryLink(sourceSchema.changeHistory)"
- >{{ sourceSchema.changeHistory.version }}</a
- >
+ </template>
+ <template v-else>
+ <div class="space-y-2">
+ <div>
+ <span>{{ $t("common.project") }} - </span>
+ <a
+ class="normal-link inline-flex items-center"
+ :href="`/project/${projectV1Slug(project)}`"
+ >{{ project.title }}</a
+ >
+ </div>
+ <div>
+ <span>{{ $t("schema-designer.schema-design") }} - </span>
+ <span>
+ {{ schemaDesign?.title || "Unknown" }}
+ </span>
+ </div>
</div>
- </div>
+ </template>
</div>
<div
@@ -152,7 +176,7 @@
? databaseDiffCache[state.selectedDatabaseId].edited
: ''
"
- :source-database="sourceDatabase"
+ :engine="engine"
:target-database-schema="targetDatabaseSchema"
:source-database-schema="sourceDatabaseSchema"
:should-show-diff="shouldShowDiff"
@@ -182,8 +206,7 @@
<TargetDatabasesSelectPanel
v-if="state.showSelectDatabasePanel"
:project-id="projectId"
- :environment-id="sourceSchema.environmentId"
- :database-id="sourceSchema.databaseId"
+ :engine="engine"
:selected-database-id-list="state.selectedDatabaseIdList"
@close="state.showSelectDatabasePanel = false"
@update="handleSelectedDatabaseIdListChanged"
@@ -195,15 +218,7 @@ import { toClipboard } from "@soerenmartius/vue3-clipboard";
import axios from "axios";
import { head } from "lodash-es";
import { NEllipsis } from "naive-ui";
-import {
- PropType,
- computed,
- onMounted,
- reactive,
- ref,
- toRef,
- watch,
-} from "vue";
+import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import {
pushNotification,
@@ -218,8 +233,10 @@ import DiffViewPanel from "./DiffViewPanel.vue";
import { Engine, engineToJSON } from "@/types/proto/v1/common";
import { InstanceV1EngineIcon } from "@/components/v2";
import { ChangeHistory } from "@/types/proto/v1/database_service";
+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";
+import { SourceSchemaType } from "./types";
-interface SourceSchema {
+interface DatabaseSourceSchema {
environmentId: string;
databaseId: string;
changeHistory: ChangeHistory;
@@ -233,16 +250,12 @@ interface LocalState {
showSelectDatabasePanel: boolean;
}
-const props = defineProps({
- projectId: {
- type: String,
- required: true,
- },
- sourceSchema: {
- type: Object as PropType<SourceSchema>,
- required: true,
- },
-});
+const props = defineProps<{
+ projectId: string;
+ sourceSchemaType: SourceSchemaType;
+ databaseSourceSchema?: DatabaseSourceSchema;
+ schemaDesign?: SchemaDesign;
+}>();
const { t } = useI18n();
const environmentV1Store = useEnvironmentV1Store();
@@ -266,17 +279,22 @@ const databaseDiffCache = reactive<
>
>({});
-const { project } = useProjectV1ByUID(toRef(props, "projectId"));
-const environment = computed(() => {
- return environmentV1Store.getEnvironmentByUID(
- props.sourceSchema.environmentId
- );
-});
-const sourceDatabase = computed(() => {
- return databaseStore.getDatabaseByUID(props.sourceSchema.databaseId);
-});
+const { project } = useProjectV1ByUID(props.projectId);
const sourceDatabaseSchema = computed(() => {
- return props.sourceSchema.changeHistory.schema || "";
+ if (props.sourceSchemaType === "DATABASE_SCHEMA") {
+ return props.databaseSourceSchema?.changeHistory.schema || "";
+ } else {
+ return props.schemaDesign?.schema || "";
+ }
+});
+const engine = computed(() => {
+ if (props.sourceSchemaType === "DATABASE_SCHEMA") {
+ return databaseStore.getDatabaseByUID(
+ props.databaseSourceSchema!.databaseId
+ ).instanceEntity.engine;
+ } else {
+ return props.schemaDesign!.engine;
+ }
});
const targetDatabaseList = computed(() => {
return state.selectedDatabaseIdList.map((id) => {
@@ -336,6 +354,22 @@ onMounted(() => {
state.isLoading = false;
});
+const getSourceDatabase = () => {
+ if (!props.databaseSourceSchema) {
+ return;
+ }
+ return databaseStore.getDatabaseByUID(props.databaseSourceSchema.databaseId);
+};
+
+const getDatabaseSourceSchemaEnvironment = () => {
+ if (!props.databaseSourceSchema) {
+ return;
+ }
+ return environmentV1Store.getEnvironmentByUID(
+ props.databaseSourceSchema.environmentId
+ );
+};
+
const handleSelectedDatabaseIdListChanged = (databaseIdList: string[]) => {
state.selectedDatabaseIdList = databaseIdList;
state.showSelectDatabasePanel = false;
@@ -397,7 +431,7 @@ watch(
continue;
} else {
const schemaDiff = await getSchemaDiff(
- sourceDatabase.value.instanceEntity.engine,
+ engine.value,
/* the current schema of the database to be updated */
schema.schema,
/* the schema to be updated to */
diff --git a/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue b/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue
index bcecfa1c2d..34da56ea35 100644
--- a/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue
+++ b/frontend/src/views/SyncDatabaseSchema/TargetDatabasesSelectPanel.vue
@@ -123,7 +123,7 @@
</template>
<script setup lang="ts">
-import { computed, reactive, PropType } from "vue";
+import { computed, reactive } from "vue";
import {
NCollapse,
NCollapseItem,
@@ -139,31 +139,18 @@ import {
import { ComposedDatabase } from "@/types";
import { Environment } from "@/types/proto/v1/environment_service";
import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";
-import { State } from "@/types/proto/v1/common";
+import { Engine, State } from "@/types/proto/v1/common";
type LocalState = {
searchText: string;
selectedDatabaseList: ComposedDatabase[];
};
-const props = defineProps({
- projectId: {
- type: String,
- required: true,
- },
- environmentId: {
- type: String,
- required: true,
- },
- databaseId: {
- type: String as PropType<string>,
- required: true,
- },
- selectedDatabaseIdList: {
- type: Array as PropType<string[]>,
- required: true,
- },
-});
+const props = defineProps<{
+ projectId: string;
+ engine: Engine;
+ selectedDatabaseIdList: string[];
+}>();
const emit = defineEmits<{
(event: "close"): void;
@@ -179,21 +166,13 @@ const state = reactive<LocalState>({
}),
});
-const sourceDatabase = computed(() => {
- return databaseStore.getDatabaseByUID(props.databaseId);
-});
-
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 ===
- sourceDatabase.value.instanceEntity.engine
- ) || [];
+ .filter((db) => db.instanceEntity.engine === props.engine) || [];
const listByEnv = environmentV1Store.environmentList.map((environment) => {
const list = databaseList.filter(
(db) => db.instanceEntity.environment === environment.name
diff --git a/frontend/src/views/SyncDatabaseSchema/index.vue b/frontend/src/views/SyncDatabaseSchema/index.vue
index e7edfcc61a..c8ab4cdba4 100644
--- a/frontend/src/views/SyncDatabaseSchema/index.vue
+++ b/frontend/src/views/SyncDatabaseSchema/index.vue
@@ -7,232 +7,116 @@
/>
</p>
<BBStepTab
+ ref="bbStepTabRef"
class="p-4 flex-1 overflow-hidden flex flex-col"
:step-item-list="stepTabList"
:show-cancel="false"
:allow-next="allowNext"
:finish-title="$t('database.sync-schema.preview-issue')"
- :current-step="state.currentStep"
pane-class="flex-1 overflow-y-auto"
@cancel="cancelSetup"
@try-change-step="tryChangeStep"
@try-finish="tryFinishSetup"
>
<template #0>
- <div
- class="w-full mx-auto flex flex-col justify-start items-start space-y-4 my-8"
- >
- <div class="w-full flex flex-row justify-start items-center">
- <span class="flex w-40 items-center">
- {{ $t("database.sync-schema.select-project") }}
- </span>
- <ProjectSelect
- class="!w-60 shrink-0"
- :selected-id="state.projectId"
- @select-project-id="handleSourceProjectSelect"
- />
- </div>
- <div class="w-full flex flex-row justify-start items-center">
- <span class="flex w-40 items-center shrink-0">
- {{ $t("database.sync-schema.source-database") }}
- </span>
- <EnvironmentSelect
- class="!w-60 mr-4 shrink-0"
- name="environment"
- :selected-id="state.sourceSchema.environmentId"
- :select-default="false"
- @select-environment-id="handleSourceEnvironmentSelect"
- />
- <DatabaseSelect
- class="!w-128"
- :selected-id="state.sourceSchema.databaseId ?? String(UNKNOWN_ID)"
- :mode="'USER'"
- :environment-id="state.sourceSchema.environmentId"
- :project-id="state.projectId"
- :engine-type-list="allowedEngineTypeList"
- :sync-status="'OK'"
- :customize-item="true"
- @select-database-id="handleSourceDatabaseSelect"
- >
- <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">
- {{ $t("database.sync-schema.schema-version.self") }}
- </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.sourceSchema.changeHistory"
- :item-list="
- databaseChangeHistoryList(state.sourceSchema.databaseId as string)
- "
- :placeholder="$t('change-history.select')"
- :show-prefix-item="databaseChangeHistoryList(state.sourceSchema.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>
- <template v-if="shouldShowMoreVersionButton" #suffixItem>
- <div
- class="w-full flex flex-row justify-start items-center pl-3 leading-8 text-accent cursor-pointer hover:opacity-80"
- @click.prevent.capture="
- () => (state.showFeatureModal = true)
- "
- >
- <heroicons-solid:sparkles class="w-4 h-auto mr-1" />
- {{ $t("database.sync-schema.more-version") }}
- </div>
- </template>
- </BBSelect>
- </div>
- </div>
+ <div class="mb-4">
+ <NRadioGroup v-model:value="state.sourceSchemaType" class="space-x-4">
+ <NRadio :value="'DATABASE_SCHEMA'" :label="'Database Schema'" />
+ <NRadio :value="'SCHEMA_DESIGN'" :label="'Schema Design'" />
+ </NRadioGroup>
</div>
+ <DatabaseSchemaSelector
+ v-if="state.sourceSchemaType === 'DATABASE_SCHEMA'"
+ :select-state="changeHistorySourceSchemaState"
+ @update="handleChangeHistorySchameVersionChanges"
+ />
+ <SchemaDesignSelector
+ v-if="state.sourceSchemaType === 'SCHEMA_DESIGN'"
+ :selected-schema-design="schemaDesignState.selectedSchemaDesign"
+ @select="
+ (schemaDesign) =>
+ (schemaDesignState.selectedSchemaDesign = schemaDesign)
+ "
+ />
</template>
<template #1>
<SelectTargetDatabasesView
ref="targetDatabaseViewRef"
- :project-id="state.projectId!"
- :source-schema="fullViewSourceSchema as any"
+ :project-id="projectId!"
+ :source-schema-type="state.sourceSchemaType"
+ :database-source-schema="(changeHistorySourceSchemaState as any)"
+ :schema-design="schemaDesignState.selectedSchemaDesign"
/>
</template>
</BBStepTab>
</div>
-
- <FeatureModal
- feature="bb.feature.sync-schema-all-versions"
- :open="state.showFeatureModal"
- :instance="database?.instanceEntity"
- @cancel="state.showFeatureModal = false"
- />
</template>
<script lang="ts" setup>
import dayjs from "dayjs";
-import { head, isNull, isUndefined } from "lodash-es";
-import { NEllipsis, useDialog } from "naive-ui";
-import { computed, reactive, ref, watch } from "vue";
+import { isNull, isUndefined } from "lodash-es";
+import { NRadioGroup, NRadio, useDialog } from "naive-ui";
+import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-import {
- useChangeHistoryStore,
- useDatabaseV1Store,
- useProjectV1Store,
- useSubscriptionV1Store,
-} from "@/store";
+import { useProjectV1Store } from "@/store";
import { UNKNOWN_ID } from "@/types";
-import DatabaseSelect from "@/components/DatabaseSelect.vue";
import SelectTargetDatabasesView from "./SelectTargetDatabasesView.vue";
-import { Engine } from "@/types/proto/v1/common";
-import { InstanceV1EngineIcon } from "@/components/v2";
-import { instanceV1Name } from "@/utils";
-import {
- ChangeHistory,
- ChangeHistoryView,
- ChangeHistory_Type,
-} from "@/types/proto/v1/database_service";
-
-const SELECT_SOURCE_DATABASE = 0;
+import { ChangeHistorySourceSchema, SourceSchemaType } from "./types";
+import DatabaseSchemaSelector from "./DatabaseSchemaSelector.vue";
+import SchemaDesignSelector from "./SchemaDesignSelector.vue";
+import { SchemaDesign } from "@/types/proto/v1/schema_design_service";
+import { getProjectAndSchemaDesignSheetId } from "@/store/modules/v1/common";
+import { useSchemaDesignStore } from "@/store/modules/schemaDesign";
+import { BBStepTab } from "@/bbkit";
+
+const SELECT_SOURCE_SCHEMA = 0;
const SELECT_TARGET_DATABASE_LIST = 1;
-type Step = typeof SELECT_SOURCE_DATABASE | typeof SELECT_TARGET_DATABASE_LIST;
-
-interface SourceSchema {
- environmentId?: string;
- databaseId?: string;
- changeHistory?: ChangeHistory;
-}
+type Step = typeof SELECT_SOURCE_SCHEMA | typeof SELECT_TARGET_DATABASE_LIST;
interface LocalState {
+ sourceSchemaType: SourceSchemaType;
currentStep: Step;
- projectId?: string;
- sourceSchema: SourceSchema;
- showFeatureModal: boolean;
}
-const allowedEngineTypeList: Engine[] = [Engine.MYSQL, Engine.POSTGRES];
-const allowedMigrationTypeList: ChangeHistory_Type[] = [
- ChangeHistory_Type.BASELINE,
- ChangeHistory_Type.MIGRATE,
- ChangeHistory_Type.BRANCH,
-];
-
const { t } = useI18n();
const router = useRouter();
const dialog = useDialog();
+const bbStepTabRef = ref<InstanceType<typeof BBStepTab>>();
const projectStore = useProjectV1Store();
-const databaseStore = useDatabaseV1Store();
-const changeHistoryStore = useChangeHistoryStore();
-const subscriptionV1Store = useSubscriptionV1Store();
-const fullViewChangeHistoryCache = ref<Map<string, ChangeHistory>>(new Map());
+const schemaDesignStore = useSchemaDesignStore();
const targetDatabaseViewRef =
ref<InstanceType<typeof SelectTargetDatabasesView>>();
const state = reactive<LocalState>({
- currentStep: SELECT_SOURCE_DATABASE,
- sourceSchema: {},
- showFeatureModal: false,
+ sourceSchemaType: "DATABASE_SCHEMA",
+ currentStep: SELECT_SOURCE_SCHEMA,
});
-
-const prepareFullViewChangeHistory = async () => {
- const changeHistory = state.sourceSchema.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
+const changeHistorySourceSchemaState = reactive<ChangeHistorySourceSchema>({});
+const schemaDesignState = reactive<{
+ selectedSchemaDesign?: SchemaDesign;
+}>({});
+const projectId = computed(() => {
+ if (state.sourceSchemaType === "DATABASE_SCHEMA") {
+ return changeHistorySourceSchemaState.projectId;
+ } else {
+ if (!schemaDesignState.selectedSchemaDesign) {
+ return undefined;
+ }
+ const [projectName] = getProjectAndSchemaDesignSheetId(
+ schemaDesignState.selectedSchemaDesign.name
);
+ const project = projectStore.getProjectByName(`projects/${projectName}`);
+ return project.uid;
}
-};
-
-watch(() => state.sourceSchema.changeHistory, prepareFullViewChangeHistory, {
- immediate: true,
- deep: true,
});
+const handleChangeHistorySchameVersionChanges = (
+ schemaVersion: ChangeHistorySourceSchema
+) => {
+ Object.assign(changeHistorySourceSchemaState, schemaVersion);
+};
+
const isValidId = (id: any): id is string => {
if (isNull(id) || isUndefined(id) || String(id) === String(UNKNOWN_ID)) {
return false;
@@ -240,29 +124,6 @@ const isValidId = (id: any): id is string => {
return true;
};
-const database = computed(() => {
- const databaseId = state.sourceSchema.databaseId;
- if (!isValidId(databaseId)) {
- return;
- }
- return databaseStore.getDatabaseByUID(databaseId);
-});
-
-const hasSyncSchemaFeature = computed(() => {
- return subscriptionV1Store.hasInstanceFeature(
- "bb.feature.sync-schema-all-versions",
- database.value?.instanceEntity
- );
-});
-
-const shouldShowMoreVersionButton = computed(() => {
- return (
- hasSyncSchemaFeature.value &&
- databaseChangeHistoryList(state.sourceSchema.databaseId as string).length >
- 0
- );
-});
-
const stepTabList = computed(() => {
return [
{ title: t("database.sync-schema.select-source-schema") },
@@ -270,23 +131,17 @@ const stepTabList = computed(() => {
];
});
-const fullViewSourceSchema = computed(() => {
- const fullViewChangeHistory = fullViewChangeHistoryCache.value.get(
- state.sourceSchema.changeHistory?.name || ""
- );
- return {
- ...state.sourceSchema,
- changeHistory: fullViewChangeHistory || state.sourceSchema.changeHistory,
- };
-});
-
const allowNext = computed(() => {
- if (state.currentStep === SELECT_SOURCE_DATABASE) {
- return (
- isValidId(state.sourceSchema.environmentId) &&
- isValidId(state.sourceSchema.databaseId) &&
- !isUndefined(state.sourceSchema.changeHistory)
- );
+ if (state.currentStep === SELECT_SOURCE_SCHEMA) {
+ if (state.sourceSchemaType === "DATABASE_SCHEMA") {
+ return (
+ isValidId(changeHistorySourceSchemaState.environmentId) &&
+ isValidId(changeHistorySourceSchemaState.databaseId) &&
+ !isUndefined(changeHistorySourceSchemaState.changeHistory)
+ );
+ } else {
+ return !isUndefined(schemaDesignState.selectedSchemaDesign);
+ }
} else {
if (!targetDatabaseViewRef.value) {
return false;
@@ -305,56 +160,24 @@ const allowNext = computed(() => {
}
});
-const databaseChangeHistoryList = (databaseId: string) => {
- const database = databaseStore.getDatabaseByUID(databaseId);
- const list = changeHistoryStore
- .changeHistoryListByDatabase(database.name)
- .filter((changeHistory) =>
- allowedMigrationTypeList.includes(changeHistory.type)
- );
-
- return list;
-};
-
-const handleSourceProjectSelect = async (projectId: string) => {
- if (projectId !== state.projectId) {
- state.sourceSchema.databaseId = String(UNKNOWN_ID);
- }
- state.projectId = projectId;
-};
-
-const handleSourceEnvironmentSelect = async (environmentId: string) => {
- if (environmentId !== state.sourceSchema.environmentId) {
- state.sourceSchema.databaseId = String(UNKNOWN_ID);
- }
- state.sourceSchema.environmentId = environmentId;
-};
-
-const handleSourceDatabaseSelect = async (databaseId: string) => {
- if (isValidId(databaseId)) {
- const database = databaseStore.getDatabaseByUID(databaseId);
- if (!database) {
- return;
+onMounted(async () => {
+ const schemaDesignName = router.currentRoute.value.query
+ .schemaDesignName as string;
+ if (schemaDesignName) {
+ try {
+ const schemaDesign = await schemaDesignStore.getOrFetchSchemaDesignByName(
+ schemaDesignName
+ );
+ if (schemaDesign) {
+ state.sourceSchemaType = "SCHEMA_DESIGN";
+ schemaDesignState.selectedSchemaDesign = schemaDesign;
+ bbStepTabRef.value?.changeStep(SELECT_TARGET_DATABASE_LIST);
+ }
+ } catch (error) {
+ // do nothing
}
- state.projectId = database.projectEntity.uid;
- state.sourceSchema.environmentId =
- database.instanceEntity.environmentEntity.uid;
- state.sourceSchema.databaseId = databaseId;
- }
-};
-
-const handleSchemaVersionSelect = (changeHistory: ChangeHistory) => {
- const list = databaseChangeHistoryList(
- state.sourceSchema.databaseId as string
- );
- const index = list.findIndex((data) => data.uid === changeHistory.uid);
- if (index > 0 && !hasSyncSchemaFeature.value) {
- state.showFeatureModal = true;
- state.sourceSchema.changeHistory = head(list);
- return;
}
- state.sourceSchema.changeHistory = changeHistory;
-};
+});
const tryChangeStep = async (
oldStep: number,
@@ -405,8 +228,7 @@ const tryFinishSetup = async () => {
.filter((item) => item.diff !== "");
const databaseIdList = targetDatabaseDiffList.map((item) => item.id);
const statementList = targetDatabaseDiffList.map((item) => item.diff);
-
- const project = await projectStore.getOrFetchProjectByUID(state.projectId!);
+ const project = await projectStore.getOrFetchProjectByUID(projectId.value!);
const query: Record<string, any> = {
template: "bb.issue.database.schema.update",
@@ -449,46 +271,4 @@ const cancelSetup = () => {
name: "workspace.home",
});
};
-
-watch(
- () => [state.sourceSchema.databaseId],
- async () => {
- const databaseId = state.sourceSchema.databaseId;
- if (!isValidId(databaseId)) {
- state.sourceSchema.changeHistory = undefined;
- return;
- }
-
- const database = databaseStore.getDatabaseByUID(databaseId);
- if (database) {
- const changeHistoryList = (
- await changeHistoryStore.fetchChangeHistoryList({
- parent: database.name,
- })
- ).filter((changeHistory) =>
- allowedMigrationTypeList.includes(changeHistory.type)
- );
-
- if (changeHistoryList.length > 0) {
- // Default select the first migration history.
- state.sourceSchema.changeHistory = head(changeHistoryList);
- } else {
- // If database has no migration history, we will use its latest schema.
- const schema = await databaseStore.fetchDatabaseSchema(
- `${database.name}/schema`
- );
- state.sourceSchema.changeHistory = {
- name: `${database.name}/changeHistories/${UNKNOWN_ID}`,
- uid: String(UNKNOWN_ID),
- updateTime: new Date(),
- schema: schema.schema,
- version: "Latest version",
- description: "the latest schema of database",
- } as ChangeHistory;
- }
- } else {
- state.sourceSchema.changeHistory = undefined;
- }
- }
-);
</script>
diff --git a/frontend/src/views/SyncDatabaseSchema/types.ts b/frontend/src/views/SyncDatabaseSchema/types.ts
new file mode 100644
index 0000000000..dee9af49db
--- /dev/null
+++ b/frontend/src/views/SyncDatabaseSchema/types.ts
@@ -0,0 +1,10 @@
+import { ChangeHistory } from "@/types/proto/v1/database_service";
+
+export type SourceSchemaType = "DATABASE_SCHEMA" | "SCHEMA_DESIGN";
+
+export interface ChangeHistorySourceSchema {
+ projectId?: string;
+ environmentId?: string;
+ databaseId?: string;
+ changeHistory?: ChangeHistory;
+}