Skip to content

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

feat: batch transfer out databases from project (#5953)

Liu Ji6ebb433146f5
diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vue
index 460959eace..b398b01a59 100644
--- a/frontend/src/components/QuickActionPanel.vue
+++ b/frontend/src/components/QuickActionPanel.vue
@@ -166,6 +166,23 @@
{{ $t("quick-action.transfer-in-db") }}
</h3>
</div>
+
+ <div
+ v-if="quickAction === 'quickaction.bb.project.database.transfer'"
+ class="flex flex-col items-center w-24"
+ >
+ <button
+ class="btn-icon-primary p-3"
+ @click.prevent="transferOutDatabase"
+ >
+ <heroicons-outline:chevron-double-up class="w-5 h-5" />
+ </button>
+ <h3
+ class="flex-1 mt-1.5 text-center text-sm font-normal text-main tracking-tight"
+ >
+ {{ $t("quick-action.transfer-out-db") }}
+ </h3>
+ </div>
</template>
</div>
<BBModal
@@ -228,6 +245,17 @@
@dismiss="state.showModal = false"
/>
</template>
+ <template
+ v-else-if="
+ state.quickActionType == 'quickaction.bb.project.database.transfer-out'
+ "
+ >
+ <TransferOutDatabaseForm
+ v-if="projectId"
+ :project-id="projectId"
+ @dismiss="state.showModal = false"
+ />
+ </template>
</BBModal>
<FeatureModal
v-if="state.showFeatureModal && state.featureName !== ''"
@@ -255,6 +283,7 @@ import AlterSchemaPrepForm from "./AlterSchemaPrepForm/";
import CreateDatabasePrepForm from "../components/CreateDatabasePrepForm.vue";
import RequestDatabasePrepForm from "../components/RequestDatabasePrepForm.vue";
import TransferDatabaseForm from "../components/TransferDatabaseForm.vue";
+import TransferOutDatabaseForm from "../components/TransferOutDatabaseForm";
interface LocalState {
showModal: boolean;
@@ -313,6 +342,13 @@ const transferDatabase = () => {
state.showModal = true;
};
+const transferOutDatabase = () => {
+ state.modalTitle = t("quick-action.transfer-out-db-title");
+ state.modalSubtitle = "";
+ state.quickActionType = "quickaction.bb.project.database.transfer-out";
+ state.showModal = true;
+};
+
const createInstance = () => {
const instanceList = useInstanceStore().getInstanceList();
if (subscriptionStore.instanceCount <= instanceList.length) {
diff --git a/frontend/src/components/TransferOutDatabaseForm/Label.vue b/frontend/src/components/TransferOutDatabaseForm/Label.vue
new file mode 100644
index 0000000000..0072c75de0
--- /dev/null
+++ b/frontend/src/components/TransferOutDatabaseForm/Label.vue
@@ -0,0 +1,61 @@
+<template>
+ <EnvironmentName
+ v-if="environment"
+ :environment="environment"
+ :link="false"
+ />
+ <template v-if="database">
+ <div class="flex items-center gap-x-1">
+ <InstanceName
+ :instance="database.instance"
+ :link="false"
+ class="whitespace-nowrap"
+ />
+ <heroicons:chevron-right class="shrink-0 h-3 w-3 opacity-70" />
+ <!-- eslint-disable-next-line vue/no-v-html -->
+ <span class="truncate" v-html="databaseName" />
+ </div>
+ </template>
+</template>
+
+<script setup lang="ts">
+import { computed } from "vue";
+import { escape } from "lodash-es";
+
+import { DatabaseTreeOption } from "./common";
+import { useDatabaseStore, useEnvironmentStore } from "@/store";
+import { EnvironmentName, InstanceName } from "@/components/v2";
+import { getHighlightHTMLByRegExp } from "@/utils";
+
+const props = defineProps<{
+ option: DatabaseTreeOption;
+ keyword?: string;
+}>();
+
+const id = computed(() => {
+ return parseInt(props.option.value.split("-").pop()!, 10);
+});
+
+const environment = computed(() => {
+ const { option } = props;
+ if (option.level === "database") return undefined;
+ return useEnvironmentStore().getEnvironmentById(id.value);
+});
+
+const database = computed(() => {
+ const { option } = props;
+ if (option.level === "environment") return undefined;
+ return useDatabaseStore().getDatabaseById(id.value);
+});
+
+const databaseName = computed(() => {
+ const name = database.value?.name ?? "";
+ const keyword = (props.keyword ?? "").trim();
+
+ return getHighlightHTMLByRegExp(
+ escape(name),
+ escape(keyword),
+ false /* !caseSensitive */
+ );
+});
+</script>
diff --git a/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vue b/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vue
new file mode 100644
index 0000000000..d2eb16a349
--- /dev/null
+++ b/frontend/src/components/TransferOutDatabaseForm/TransferOutDatabaseForm.vue
@@ -0,0 +1,216 @@
+<template>
+ <div class="w-[60rem] space-y-2">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-x-2">
+ <label class="textlabel">
+ {{ $t("database.transfer.source-project") }}
+ </label>
+ <ProjectName :project="sourceProject" :link="false" />
+ </div>
+ <div class="flex items-center gap-x-2">
+ <label class="textlabel">
+ {{ $t("database.transfer.target-project") }}
+ </label>
+ <ProjectSelect
+ v-model:project="targetProjectId"
+ :allowed-project-role-list="['OWNER']"
+ :include-default-project="true"
+ :filter="filterTargetProject"
+ />
+ </div>
+ </div>
+ <NTransfer
+ ref="transfer"
+ v-model:value="selectedValueList"
+ style="height: calc(100vh - 380px)"
+ :options="sourceTransferOptions"
+ :render-source-list="renderSourceList"
+ :render-target-list="renderTargetList"
+ :source-filterable="true"
+ :source-filter-placeholder="$t('database.search-database-name')"
+ />
+ <div class="flex items-center justify-end gap-x-2">
+ <NButton @click="$emit('dismiss')">{{ $t("common.cancel") }}</NButton>
+ <NButton type="primary" :disabled="!allowTransfer" @click="doTransfer">
+ {{ $t("common.transfer") }}
+ </NButton>
+ </div>
+ <div
+ v-if="loading"
+ class="absolute inset-0 z-10 bg-white/70 flex items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, h, ref } from "vue";
+import {
+ NTransfer,
+ NTree,
+ TreeOption,
+ TransferRenderSourceList,
+ NButton,
+} from "naive-ui";
+
+import { Database, IdType, Project, ProjectId, UNKNOWN_ID } from "@/types";
+import { pushNotification, useDatabaseStore, useProjectStore } from "@/store";
+import { ProjectName, ProjectSelect } from "../v2";
+import Label from "./Label.vue";
+import {
+ DatabaseTreeOption,
+ flattenTreeOptions,
+ mapTreeOptions,
+} from "./common";
+
+const props = defineProps<{
+ projectId: ProjectId;
+}>();
+
+const emit = defineEmits<{
+ (e: "dismiss"): void;
+}>();
+
+const projectStore = useProjectStore();
+const databaseStore = useDatabaseStore();
+const loading = ref(false);
+const transfer = ref<InstanceType<typeof NTransfer>>();
+
+const databaseList = computed(() => {
+ return databaseStore.getDatabaseListByProjectId(props.projectId);
+});
+
+const selectedValueList = ref<string[]>([]);
+const selectedDatabaseList = computed(() => {
+ return selectedValueList.value
+ .filter((value) => value.startsWith("database-"))
+ .map((value) => {
+ const id = parseInt(value.split("-").pop()!, 10);
+ return databaseStore.getDatabaseById(id);
+ });
+});
+const targetProjectId = ref<IdType>();
+const targetProject = computed(() => {
+ const id = targetProjectId.value;
+ if (!id || id === UNKNOWN_ID) return undefined;
+ return projectStore.getProjectById(id);
+});
+
+const sourceProject = computed(() => {
+ return useProjectStore().getProjectById(props.projectId);
+});
+
+const allowTransfer = computed(() => {
+ if (!targetProject.value) return false;
+ return selectedDatabaseList.value.length > 0;
+});
+
+const sourceTreeOptions = computed(() => {
+ return mapTreeOptions(databaseList.value);
+});
+const sourceTransferOptions = computed(() => {
+ return flattenTreeOptions(sourceTreeOptions.value);
+});
+
+const renderSourceList: TransferRenderSourceList = ({ onCheck, pattern }) => {
+ return h(NTree, {
+ style: "margin: 0 4px;",
+ keyField: "value",
+ defaultExpandAll: true,
+ checkable: true,
+ selectable: false,
+ blockLine: true,
+ checkOnClick: true,
+ cascade: true,
+ virtualScroll: true,
+ data: sourceTreeOptions.value,
+ renderLabel: ({ option }: { option: TreeOption }) => {
+ return h(Label, {
+ option: option as DatabaseTreeOption,
+ keyword: pattern,
+ });
+ },
+ pattern,
+ checkedKeys: selectedValueList.value,
+ showIrrelevantNodes: false,
+ onUpdateCheckedKeys: (checkedKeys: string[]) => {
+ onCheck(checkedKeys.filter((value) => value.startsWith("database-")));
+ },
+ });
+};
+
+const targetTreeOptions = computed(() => {
+ return mapTreeOptions(selectedDatabaseList.value);
+});
+const targetCheckedKeys = computed(() => {
+ return flattenTreeOptions(targetTreeOptions.value).map(
+ (option) => option.value
+ );
+});
+
+const renderTargetList: TransferRenderSourceList = ({ onCheck }) => {
+ return h(NTree, {
+ key: targetCheckedKeys.value.join(","),
+ style: "margin: 0 4px;",
+ keyField: "value",
+ defaultExpandAll: true,
+ selectable: false,
+ blockLine: true,
+ checkable: true,
+ checkOnClick: true,
+ cascade: true,
+ virtualScroll: true,
+ data: targetTreeOptions.value,
+ renderLabel: ({ option }: { option: TreeOption }) => {
+ return h(Label, {
+ option: option as DatabaseTreeOption,
+ });
+ },
+ checkedKeys: targetCheckedKeys.value,
+ onUpdateCheckedKeys: (checkedKeys: string[]) => {
+ onCheck(checkedKeys.filter((value) => value.startsWith("database-")));
+ },
+ });
+};
+
+const filterTargetProject = (project: Project) => {
+ return project.id !== props.projectId;
+};
+
+const doTransfer = async () => {
+ const target = targetProject.value!;
+ if (!target) if (!targetProject.value) return;
+
+ const transferOneDatabase = (database: Database) => {
+ return databaseStore.transferProject({
+ databaseId: database.id,
+ projectId: target.id,
+ });
+ };
+
+ const databaseList = selectedDatabaseList.value;
+
+ try {
+ loading.value = true;
+ const requests = databaseList.map((db) => {
+ transferOneDatabase(db);
+ });
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ await Promise.all(requests);
+ const displayDatabaseName =
+ databaseList.length > 1
+ ? `${databaseList.length} databases`
+ : `'${databaseList[0].name}'`;
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: `Successfully transferred ${displayDatabaseName} to project '${target.name}'.`,
+ });
+ emit("dismiss");
+ } finally {
+ loading.value = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/TransferOutDatabaseForm/common.ts b/frontend/src/components/TransferOutDatabaseForm/common.ts
new file mode 100644
index 0000000000..14be9e5f7c
--- /dev/null
+++ b/frontend/src/components/TransferOutDatabaseForm/common.ts
@@ -0,0 +1,45 @@
+import { groupBy } from "lodash-es";
+import { TransferOption, TreeOption } from "naive-ui";
+import { useEnvironmentStore } from "@/store";
+import { Database } from "@/types";
+
+export interface DatabaseTreeOption<L = "environment" | "database">
+ extends TreeOption {
+ level: L;
+ value: string;
+}
+
+export const mapTreeOptions = (databaseList: Database[]) => {
+ const environmentStore = useEnvironmentStore();
+ const databaseListGroupByEnvironment = groupBy(
+ databaseList,
+ (db) => db.instance.environment.id
+ );
+ return Object.keys(databaseListGroupByEnvironment).map<
+ DatabaseTreeOption<"environment">
+ >((environmentId) => {
+ const environment = environmentStore.getEnvironmentById(environmentId);
+ const group = databaseListGroupByEnvironment[environmentId];
+ const children = group.map<DatabaseTreeOption<"database">>((db) => ({
+ level: "database",
+ value: `database-${db.id}`,
+ label: db.name,
+ isLeaf: true,
+ }));
+ return {
+ level: "environment",
+ value: `environment-${environmentId}`,
+ label: environment.name,
+ children,
+ };
+ });
+};
+
+export const flattenTreeOptions = (options: DatabaseTreeOption[]) => {
+ return options.flatMap((option) => {
+ return [
+ option as TransferOption,
+ ...((option.children as TransferOption[] | undefined) ?? []),
+ ];
+ });
+};
diff --git a/frontend/src/components/TransferOutDatabaseForm/index.ts b/frontend/src/components/TransferOutDatabaseForm/index.ts
new file mode 100644
index 0000000000..29b114a308
--- /dev/null
+++ b/frontend/src/components/TransferOutDatabaseForm/index.ts
@@ -0,0 +1,3 @@
+import TransferOutDatabaseForm from "./TransferOutDatabaseForm.vue";
+
+export default TransferOutDatabaseForm;
diff --git a/frontend/src/components/v2/Model/InstanceName.vue b/frontend/src/components/v2/Model/InstanceName.vue
index 6c0ef57097..f2a14b66fb 100644
--- a/frontend/src/components/v2/Model/InstanceName.vue
+++ b/frontend/src/components/v2/Model/InstanceName.vue
@@ -5,7 +5,6 @@
:to="link && `/instance/${instance.id}`"
class="inline-flex items-center gap-x-1"
:class="link && 'normal-link'"
- @click.stop=""
>
<InstanceEngineIcon
v-if="icon && iconPosition === 'prefix'"
diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vue
index 7a35da242b..1684ef3ecd 100644
--- a/frontend/src/components/v2/Select/ProjectSelect.vue
+++ b/frontend/src/components/v2/Select/ProjectSelect.vue
@@ -42,6 +42,7 @@ const props = withDefaults(
includeAll?: boolean;
includeDefaultProject?: boolean;
includeArchived?: boolean;
+ filter?: (project: Project, index: number) => boolean;
}>(),
{
allowedProjectRoleList: () => ["OWNER", "DEVELOPER"],
@@ -50,6 +51,7 @@ const props = withDefaults(
includeAll: false,
includeDefaultProject: false,
includeArchived: false,
+ filter: () => true,
}
);
@@ -101,7 +103,7 @@ const isOrphanValue = computed(() => {
});
const combinedProjectList = computed(() => {
- const list = rawProjectList.value.filter((project) => {
+ let list = rawProjectList.value.filter((project) => {
if (props.includeArchived) return true;
if (project.rowStatus === "NORMAL") return true;
// ARCHIVED
@@ -112,6 +114,11 @@ const combinedProjectList = computed(() => {
if (props.includeDefaultProject) {
list.unshift(projectStore.getProjectById(DEFAULT_PROJECT_ID));
}
+
+ if (props.filter) {
+ list = list.filter(props.filter);
+ }
+
if (
props.project &&
props.project !== DEFAULT_PROJECT_ID &&
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 81265852bc..0451e0b954 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -780,7 +780,9 @@
"transfer-in-db-title": "Transfer in database",
"default-db-hint": "Bytebase periodically syncs the instance schema. Newly synced databases are first placed in the default project.",
"transfer-in-db-alert": "Are you sure to transfer \"{ dbName }\" into our project?",
- "unassigned-db-hint": "Bytebase periodically syncs the instance schema. Newly synced databases are first placed in unassigned databases."
+ "unassigned-db-hint": "Bytebase periodically syncs the instance schema. Newly synced databases are first placed in unassigned databases.",
+ "transfer-out-db": "Transfer out DB",
+ "transfer-out-db-title": "Transfer out database"
},
"create-db": {
"new-database-name": "New database name",
@@ -1221,6 +1223,10 @@
"value-placeholder": "Input value (write only)",
"delete-tips": "Delete secret",
"description": "You can use secret in the change script to hide sensitive information, please refer to {guide}"
+ },
+ "transfer": {
+ "source-project": "Source project",
+ "target-project": "Target project"
}
},
"repository": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 83ce3547b1..3ef241fae7 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -778,7 +778,9 @@
"transfer-in-db-title": "Transferir base de datos",
"default-db-hint": "Bytebase sincroniza periódicamente el esquema de la instancia. Las bases de datos recién sincronizadas se colocan primero en el proyecto predeterminado.",
"transfer-in-db-alert": "¿Estás seguro de transferir \"{dbName}\" a nuestro proyecto?",
- "unassigned-db-hint": "Bytebase sincroniza periódicamente el esquema de la instancia. Las bases de datos recién sincronizadas se colocan primero en bases de datos no asignadas."
+ "unassigned-db-hint": "Bytebase sincroniza periódicamente el esquema de la instancia. Las bases de datos recién sincronizadas se colocan primero en bases de datos no asignadas.",
+ "transfer-out-db": "Transferir base de datos",
+ "transfer-out-db-title": "Transferir la base de datos"
},
"create-db": {
"new-database-name": "Nuevo nombre de la base de datos",
@@ -1219,6 +1221,10 @@
"value-placeholder": "Valor de entrada (solo escritura)",
"delete-tips": "Eliminar secreto",
"description": "Puede usar secreto en su secuencia de comandos de cambio para ocultar información confidencial, consulte nuestra {guide}"
+ },
+ "transfer": {
+ "source-project": "Proyecto fuente",
+ "target-project": "proyecto de destino"
}
},
"repository": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 47076cb400..2049fc97cc 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -778,7 +778,9 @@
"transfer-in-db-title": "转移数据库",
"default-db-hint": "Bytebase 会定期同步实例的 Schema。新同步的数据库会放在默认项目中。",
"transfer-in-db-alert": "您确定要转移 \"{ dbName }\" 到我们的项目中吗?",
- "unassigned-db-hint": "Bytebase 会定期同步实例的 Schema。新同步的数据库会放在未分配数据库中。"
+ "unassigned-db-hint": "Bytebase 会定期同步实例的 Schema。新同步的数据库会放在未分配数据库中。",
+ "transfer-out-db": "转出数据库",
+ "transfer-out-db-title": "转出数据库"
},
"create-db": {
"new-database-name": "新数据库名称",
@@ -1217,6 +1219,10 @@
"self": "保密变量",
"delete-tips": "删除保密变量",
"description": "您可以在变更脚本中使用保密变量,来隐藏敏感信息, 请参考{guide}"
+ },
+ "transfer": {
+ "source-project": "源项目",
+ "target-project": "目标项目"
}
},
"repository": {
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 7671a64528..ee52672746 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -690,6 +690,7 @@ const routes: Array<RouteRecordRaw> = [
let allowAlterSchemaOrChangeData = false;
let allowCreateDB = false;
let allowTransferDB = false;
+ let allowTransferOutDB = false;
if (
hasWorkspacePermission(
"bb.permission.workspace.manage-instance",
@@ -699,6 +700,7 @@ const routes: Array<RouteRecordRaw> = [
allowAlterSchemaOrChangeData = true;
allowCreateDB = true;
allowTransferDB = true;
+ allowTransferOutDB = true;
} else {
const memberList = memberListInProject(
project,
@@ -715,6 +717,11 @@ const routes: Array<RouteRecordRaw> = [
currentUser.value,
"bb.permission.project.transfer-database"
);
+ allowTransferOutDB = hasPermissionInProject(
+ project,
+ currentUser.value,
+ "bb.permission.project.transfer-database"
+ );
if (
useSubscriptionStore().currentPlan ===
@@ -752,6 +759,11 @@ const routes: Array<RouteRecordRaw> = [
if (allowTransferDB) {
actionList.push("quickaction.bb.project.database.transfer");
}
+ if (allowTransferOutDB) {
+ actionList.push(
+ "quickaction.bb.project.database.transfer-out"
+ );
+ }
return new Map([
["OWNER", actionList],
diff --git a/frontend/src/types/common.ts b/frontend/src/types/common.ts
index 0ddb9b4d70..271f52081e 100644
--- a/frontend/src/types/common.ts
+++ b/frontend/src/types/common.ts
@@ -83,7 +83,8 @@ export type EnvironmentQuickActionType =
| "quickaction.bb.environment.reorder";
export type ProjectQuickActionType =
| "quickaction.bb.project.create"
- | "quickaction.bb.project.database.transfer";
+ | "quickaction.bb.project.database.transfer"
+ | "quickaction.bb.project.database.transfer-out";
export type InstanceQuickActionType = "quickaction.bb.instance.create";
export type UserQuickActionType = "quickaction.bb.user.manage";
export type DatabaseQuickActionType =