Skip to content

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

feat: transfer db with labels (#825)

Liu Jid135fa3a98b5
diff --git a/frontend/src/components/TransferDatabaseForm.vue b/frontend/src/components/TransferDatabaseForm.vue
index e6af4a4abf..2559a22cef 100644
--- a/frontend/src/components/TransferDatabaseForm.vue
+++ b/frontend/src/components/TransferDatabaseForm.vue
@@ -1,85 +1,115 @@
<template>
- <div class="px-4 space-y-6 w-208">
- <div v-if="projectId != DEFAULT_PROJECT_ID" class="textlabel">
- <div v-if="state.transferSource == 'DEFAULT'" class="textinfolabel mb-2">
- {{ $t("quick-action.transfer-in-db-hint") }}
- </div>
- <div class="radio-set-row">
- <div class="flex flex-row">
+ <div
+ class="px-4 space-y-6"
+ :class="!state.selectedDatabase ? 'w-208' : 'w-112'"
+ >
+ <template v-if="!state.selectedDatabase">
+ <div v-if="projectId != DEFAULT_PROJECT_ID" class="textlabel">
+ <div
+ v-if="state.transferSource == 'DEFAULT'"
+ class="textinfolabel mb-2"
+ >
+ {{ $t("quick-action.transfer-in-db-hint") }}
+ </div>
+ <div class="radio-set-row">
+ <div class="flex flex-row">
+ <div class="radio">
+ <input
+ v-model="state.transferSource"
+ tabindex="-1"
+ type="radio"
+ class="btn"
+ value="DEFAULT"
+ />
+ <label class="label">
+ {{ $t("quick-action.from-default-project") }}
+ </label>
+ </div>
+ </div>
<div class="radio">
<input
v-model="state.transferSource"
tabindex="-1"
type="radio"
class="btn"
- value="DEFAULT"
+ value="OTHER"
/>
<label class="label">
- {{ $t("quick-action.from-default-project") }}
+ {{ $t("quick-action.from-other-projects") }}
</label>
</div>
</div>
- <div class="radio">
- <input
- v-model="state.transferSource"
- tabindex="-1"
- type="radio"
- class="btn"
- value="OTHER"
- />
- <label class="label">
- {{ $t("quick-action.from-other-projects") }}
- </label>
- </div>
</div>
- </div>
-
- <DatabaseTable
- :mode="'ALL_SHORT'"
- :bordered="true"
- :custom-click="true"
- :database-list="databaseList"
- @select-database="selectDatabase"
- />
-
- <!-- Update button group -->
- <div class="pt-4 border-t border-block-border flex justify-end">
- <button
- type="button"
- class="btn-normal py-2 px-4"
- @click.prevent="cancel"
+
+ <DatabaseTable
+ :mode="'ALL_SHORT'"
+ :bordered="true"
+ :custom-click="true"
+ :database-list="databaseList"
+ @select-database="selectDatabase"
+ />
+ <!-- Update button group -->
+ <div class="pt-4 border-t border-block-border flex justify-end">
+ <button
+ type="button"
+ class="btn-normal py-2 px-4"
+ @click.prevent="cancel"
+ >
+ {{ $t("common.cancel") }}
+ </button>
+ </div>
+ </template>
+
+ <template v-else>
+ <SelectDatabaseLabel
+ :database="state.selectedDatabase"
+ :target-project-id="projectId"
+ @next="transferDatabase"
>
- {{ $t("common.cancel") }}
- </button>
- </div>
-
- <BBAlert
- v-if="state.showModal"
- :style="'INFO'"
- :ok-text="$t('common.transfer')"
- :title="
- $t('quick-action.transfer-in-db-alert', {
- dbName: selectedDatabaseName,
- })
- "
- @ok="
- () => {
- state.showModal = false;
- transferDatabase();
- }
- "
- @cancel="state.showModal = false"
- >
- </BBAlert>
+ <template #buttons="{ next, valid }">
+ <div
+ class="w-full pt-4 mt-6 flex justify-end border-t border-block-border"
+ >
+ <button
+ type="button"
+ class="btn-normal py-2 px-4"
+ @click.prevent="state.selectedDatabase = undefined"
+ >
+ {{ $t("common.back") }}
+ </button>
+ <button
+ type="button"
+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"
+ :disabled="!valid"
+ @click.prevent="next"
+ >
+ {{ $t("common.transfer") }}
+ </button>
+ </div>
+ </template>
+ </SelectDatabaseLabel>
+ </template>
</div>
</template>
<script lang="ts">
-import { computed, PropType, reactive, watchEffect } from "vue";
+import {
+ computed,
+ defineComponent,
+ PropType,
+ reactive,
+ watchEffect,
+} from "vue";
import { useStore } from "vuex";
import { cloneDeep } from "lodash-es";
import DatabaseTable from "../components/DatabaseTable.vue";
-import { Database, ProjectId, DEFAULT_PROJECT_ID } from "../types";
+import { SelectDatabaseLabel } from "../components/TransferDatabaseForm";
+import {
+ Database,
+ ProjectId,
+ DEFAULT_PROJECT_ID,
+ DatabaseLabel,
+} from "../types";
import { sortDatabaseList } from "../utils";
type TransferSource = "DEFAULT" | "OTHER";
@@ -87,13 +117,13 @@ type TransferSource = "DEFAULT" | "OTHER";
interface LocalState {
selectedDatabase?: Database;
transferSource: TransferSource;
- showModal: boolean;
}
-export default {
+export default defineComponent({
name: "TransferDatabaseForm",
components: {
DatabaseTable,
+ SelectDatabaseLabel,
},
props: {
projectId: {
@@ -108,7 +138,6 @@ export default {
const state = reactive<LocalState>({
transferSource:
props.projectId == DEFAULT_PROJECT_ID ? "OTHER" : "DEFAULT",
- showModal: false,
});
const currentUser = computed(() => store.getters["auth/currentUser"]());
@@ -149,14 +178,14 @@ export default {
const selectDatabase = (database: Database) => {
state.selectedDatabase = database;
- state.showModal = true;
};
- const transferDatabase = () => {
+ const transferDatabase = (labels: DatabaseLabel[]) => {
store
.dispatch("database/transferProject", {
databaseId: state.selectedDatabase!.id,
projectId: props.projectId,
+ labels,
})
.then((updatedDatabase) => {
store.dispatch("notification/pushNotification", {
@@ -182,5 +211,5 @@ export default {
cancel,
};
},
-};
+});
</script>
diff --git a/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue b/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue
new file mode 100644
index 0000000000..451b361dd3
--- /dev/null
+++ b/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue
@@ -0,0 +1,249 @@
+<template>
+ <template v-if="!dbNameMatchesTemplate">
+ <div class="textinfolabel" v-bind="$attrs">
+ <i18n-t keypath="label.cannot-transfer-template-not-match">
+ <template #name>{{ database.name }}</template>
+ <template #template>
+ <code class="text-sm font-mono bg-control-bg">
+ {{ targetProject.dbNameTemplate }}
+ </code>
+ </template>
+ </i18n-t>
+ </div>
+ </template>
+ <template v-else>
+ <div
+ class="space-y-4 flex flex-col justify-center items-center"
+ v-bind="$attrs"
+ >
+ <div v-for="label in availableLabelList" :key="label.id" class="w-64">
+ <label class="textlabel capitalize">
+ {{ hidePrefix(label.key) }}
+ <span v-if="isRequiredLabel(label.key)" style="color: red">*</span>
+ </label>
+
+ <div class="flex flex-col space-y-1 w-64 mt-1">
+ <select
+ class="btn-select w-full disabled:cursor-not-allowed"
+ :value="getLabelValue(label.key)"
+ :disabled="isParsedLabel(label.key)"
+ @change="(e: any) => setLabelValue(label.key, e.target.value)"
+ >
+ <option disabled>{{ getLabelPlaceholder(label.key) }}</option>
+ <option
+ v-for="value in getLabelValueList(label)"
+ :key="value"
+ :value="value"
+ >
+ {{ value === "" ? $t("label.empty-label-value") : value }}
+ </option>
+ </select>
+ </div>
+
+ <div v-if="isParsedLabel(label.key)" class="mt-2 textinfolabel">
+ <i18n-t keypath="label.parsed-from-template">
+ <template #name>{{ database.name }}</template>
+ <template #template>
+ <code class="text-xs font-mono bg-control-bg">
+ {{ targetProject.dbNameTemplate }}
+ </code>
+ </template>
+ </i18n-t>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <slot name="buttons" :next="next" :valid="allowNext"></slot>
+</template>
+
+<script lang="ts">
+export default {
+ inheritAttrs: false,
+};
+</script>
+
+<script lang="ts" setup>
+import {
+ computed,
+ defineProps,
+ defineEmits,
+ reactive,
+ watchEffect,
+ watch,
+} from "vue";
+import { useStore } from "vuex";
+import { capitalize, cloneDeep } from "lodash-es";
+import {
+ Database,
+ DatabaseLabel,
+ Label,
+ LabelKeyType,
+ LabelValueType,
+ Project,
+ ProjectId,
+} from "../../types";
+import {
+ buildDatabaseNameRegExpByTemplate,
+ isReservedLabel,
+ parseLabelListInTemplate,
+ hidePrefix,
+} from "../../utils";
+import { useI18n } from "vue-i18n";
+
+const props = defineProps<{
+ database: Database;
+ targetProjectId: ProjectId;
+}>();
+
+const emit = defineEmits<{
+ (event: "next", labelList: DatabaseLabel[]): void;
+}>();
+
+const state = reactive({
+ databaseLabelList: cloneDeep(props.database.labels),
+});
+
+const store = useStore();
+
+const { t } = useI18n();
+
+const targetProject = computed(() => {
+ return store.getters["project/projectById"](props.targetProjectId) as Project;
+});
+
+const labelList = computed(() => {
+ return store.getters["label/labelList"]() as Label[];
+});
+
+const availableLabelList = computed(() => {
+ return labelList.value.filter((label) => !isReservedLabel(label));
+});
+
+const prepare = () => {
+ store.dispatch("project/fetchProjectById", props.targetProjectId);
+ store.dispatch("label/fetchLabelList");
+};
+
+watchEffect(prepare);
+
+const requiredLabelList = computed((): Label[] => {
+ const project = targetProject.value;
+ if (!project.dbNameTemplate) return [];
+
+ // for databases with dbNameTemplate, we need to parse required labels from its template
+ return parseLabelListInTemplate(
+ project.dbNameTemplate,
+ availableLabelList.value
+ );
+});
+
+const dbNameMatchesTemplate = computed((): boolean => {
+ const project = targetProject.value;
+ if (!project.dbNameTemplate) {
+ // no restrictions, because no template
+ return true;
+ }
+ const regex = buildDatabaseNameRegExpByTemplate(
+ project.dbNameTemplate,
+ availableLabelList.value
+ );
+ return regex.test(props.database.name);
+});
+
+const isRequiredLabel = (key: LabelKeyType): boolean => {
+ return requiredLabelList.value.some((label) => label.key === key);
+};
+
+const isParsedLabel = (key: LabelKeyType): boolean => {
+ return labelListParsedFromTemplate.value.some((label) => label.key === key);
+};
+
+const labelListParsedFromTemplate = computed((): DatabaseLabel[] => {
+ if (!dbNameMatchesTemplate.value) return [];
+
+ const regex = buildDatabaseNameRegExpByTemplate(
+ targetProject.value.dbNameTemplate,
+ availableLabelList.value
+ );
+ const match = props.database.name.match(regex);
+ if (!match) return [];
+
+ const parsedLabelList: DatabaseLabel[] = [];
+ availableLabelList.value.forEach((label) => {
+ const group = `label_${label.id}`;
+ if (match.groups?.[group]) {
+ const value = match.groups[group];
+ parsedLabelList.push({
+ key: label.key,
+ value,
+ });
+ }
+ });
+
+ return parsedLabelList;
+});
+
+watch(labelListParsedFromTemplate, (list) => {
+ list.forEach((label) => {
+ setLabelValue(label.key, label.value);
+ });
+});
+
+const allowNext = computed(() => {
+ if (!dbNameMatchesTemplate.value) return false;
+
+ // every required label must be filled
+ return requiredLabelList.value.every((label) => {
+ return !!getLabelValue(label.key);
+ });
+});
+
+const getLabelPlaceholder = (key: LabelKeyType): string => {
+ // provide "Select Tenant" if Tenant is optional
+ // provide "Select {{TENANT}}" if Tenant is required in the template
+ key = isRequiredLabel(key)
+ ? `{{${hidePrefix(key).toUpperCase()}}}`
+ : capitalize(hidePrefix(key));
+ return t("create-db.select-label-value", { key });
+};
+
+const getLabelValue = (key: LabelKeyType): LabelValueType | undefined => {
+ return (
+ state.databaseLabelList.find((label) => label.key === key)?.value || ""
+ );
+};
+
+const getLabelValueList = (label: Label): LabelValueType[] => {
+ const valueList = [...label.valueList];
+ if (!isRequiredLabel(label.key)) {
+ // for optional labels
+ // provide a "<empty value>" option ahead of other values
+ valueList.unshift("");
+ }
+ return valueList;
+};
+
+const setLabelValue = (key: LabelKeyType, value: LabelValueType) => {
+ const label = state.databaseLabelList.find((label) => label.key === key);
+ if (label) {
+ label.value = value;
+ } else {
+ state.databaseLabelList.push({ key, value });
+ }
+ state.databaseLabelList = state.databaseLabelList.filter(
+ (label) => !!label.value
+ );
+};
+
+watch(
+ () => props.database,
+ (db) => {
+ state.databaseLabelList = cloneDeep(db.labels);
+ }
+);
+
+const next = () => {
+ emit("next", cloneDeep(state.databaseLabelList));
+};
+</script>
diff --git a/frontend/src/components/TransferDatabaseForm/index.ts b/frontend/src/components/TransferDatabaseForm/index.ts
new file mode 100644
index 0000000000..4d90a475bb
--- /dev/null
+++ b/frontend/src/components/TransferDatabaseForm/index.ts
@@ -0,0 +1,3 @@
+import SelectDatabaseLabel from "./SelectDatabaseLabel.vue";
+
+export { SelectDatabaseLabel };
diff --git a/frontend/src/locales/en.yml b/frontend/src/locales/en.yml
index a8275a9137..81b526db38 100644
--- a/frontend/src/locales/en.yml
+++ b/frontend/src/locales/en.yml
@@ -1185,6 +1185,10 @@ label:
db-name-template-tips: >-
Allow you to group databases with the same {placeholder} from different
tenants. {link}.
+ parsed-from-template: Parsed from {name} by template {template}.
+ cannot-transfer-template-not-match: >-
+ Database '{name}' cannot be transferred to this project. Since its name
+ doesn't match the template {template}.
oauth:
unknown-event: Unexpeted event type, OAuth failed.
subscription:
diff --git a/frontend/src/locales/zh-CN.yml b/frontend/src/locales/zh-CN.yml
index 2caf827bdb..237558120b 100644
--- a/frontend/src/locales/zh-CN.yml
+++ b/frontend/src/locales/zh-CN.yml
@@ -1040,6 +1040,8 @@ label:
setting:
description: 标签是一组可用于标识数据库租户的键值对。{link}。
db-name-template-tips: 让您能够把属于不同租户但是有相同 {placeholder} 的数据库分成一组。{link}。
+ parsed-from-template: 从 {name} 中依据模板 {template} 解析得出
+ cannot-transfer-template-not-match: 数据库 '{name}' 无法转移到这个项目,因为它的名称不符合模板 {template}。
oauth:
unknown-event: 未知的事件类型,认证失败
subscription:
diff --git a/frontend/src/store/modules/database.ts b/frontend/src/store/modules/database.ts
index d352b1871f..8bbec9b6b2 100644
--- a/frontend/src/store/modules/database.ts
+++ b/frontend/src/store/modules/database.ts
@@ -380,18 +380,22 @@ const actions = {
{
databaseId,
projectId,
+ labels,
}: {
databaseId: DatabaseId;
projectId: ProjectId;
+ labels?: DatabaseLabel[];
}
) {
+ const attributes: any = { projectId };
+ if (labels) {
+ attributes.labels = JSON.stringify(labels);
+ }
const data = (
await axios.patch(`/api/database/${databaseId}`, {
data: {
type: "databasePatch",
- attributes: {
- projectId,
- },
+ attributes,
},
})
).data;
diff --git a/frontend/src/utils/deployment.ts b/frontend/src/utils/deployment.ts
index f69a7b48d3..bdf6d09d5f 100644
--- a/frontend/src/utils/deployment.ts
+++ b/frontend/src/utils/deployment.ts
@@ -83,6 +83,17 @@ export const parseDatabaseNameByTemplate = (
template: string,
labelList: Label[]
) => {
+ const regex = buildDatabaseNameRegExpByTemplate(template, labelList);
+ const match = name.match(regex);
+
+ // fallback to name it self when failed
+ return match?.groups?.name || name;
+};
+
+export const buildDatabaseNameRegExpByTemplate = (
+ template: string,
+ labelList: Label[]
+): RegExp => {
let regexpString = template.replace("{{DB_NAME}}", "(?<name>.+?)");
/*
Rewrite the placeholder-based template to a big RegExp
@@ -97,12 +108,11 @@ export const parseDatabaseNameByTemplate = (
const escapedValueList = valueList.map((value) =>
escapeStringRegexp(value)
);
- const regex = `(${escapedValueList.join("|")})`;
+ // the groups are named as "label_{id}"
+ // so the caller can get matched label values from the regex's match result
+ const regex = `(?<label_${label.id}>${escapedValueList.join("|")})`;
regexpString = regexpString.replace(placeholder, regex);
});
const regex = new RegExp(`^${regexpString}$`);
- const match = name.match(regex);
-
- // fallback to name it self when failed
- return match?.groups?.name || name;
+ return regex;
};
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index 3913ccb8ad..bac7ade419 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -197,43 +197,58 @@
:title="$t('database.transfer-project')"
@close="state.showTransferDatabaseModal = false"
>
- <div class="col-span-1 w-64">
- <label for="user" class="textlabel">{{ $t("common.project") }}</label>
- <!-- Only allow to transfer database to the project having OWNER role -->
- <!-- eslint-disable vue/attribute-hyphenation -->
- <ProjectSelect
- id="project"
- class="mt-1"
- name="project"
- :allowed-role-list="['OWNER']"
- :include-default-project="true"
- :selectedId="state.editingProjectId"
- @select-project-id="
- (projectId) => {
- state.editingProjectId = projectId;
- }
- "
- />
- </div>
- <div class="pt-6 flex justify-end">
- <button
- type="button"
- class="btn-normal py-2 px-4"
- @click.prevent="state.showTransferDatabaseModal = false"
- >
- {{ $t("common.cancel") }}
- </button>
- <button
- type="button"
- class="btn-primary ml-3 inline-flex justify-center py-2 px-4"
- :disabled="state.editingProjectId == database.project.id"
- @click.prevent="
- updateProject(state.editingProjectId);
- state.showTransferDatabaseModal = false;
- "
+ <div class="w-112 flex flex-col items-center">
+ <div class="col-span-1 w-64">
+ <label for="user" class="textlabel">{{ $t("common.project") }}</label>
+ <!-- Only allow to transfer database to the project having OWNER role -->
+ <ProjectSelect
+ id="project"
+ class="mt-1"
+ name="project"
+ :allowed-role-list="['OWNER']"
+ :include-default-project="true"
+ :selected-id="state.editingProjectId"
+ @select-project-id="
+ (projectId) => {
+ state.editingProjectId = projectId;
+ }
+ "
+ />
+ </div>
+ <SelectDatabaseLabel
+ :database="database"
+ :target-project-id="state.editingProjectId"
+ class="mt-4"
+ @next="doTransfer"
>
- {{ $t("common.transfer") }}
- </button>
+ <template #buttons="{ next, valid }">
+ <div
+ class="w-full pt-4 mt-6 flex justify-end border-t border-block-border"
+ >
+ <button
+ type="button"
+ class="btn-normal py-2 px-4"
+ @click.prevent="state.showTransferDatabaseModal = false"
+ >
+ {{ $t("common.cancel") }}
+ </button>
+ <!--
+ We are not allowed to transfer a db either its labels are not valid
+ or transferring into its project itself.
+ -->
+ <button
+ type="button"
+ class="btn-primary ml-3 inline-flex justify-center py-2 px-4"
+ :disabled="
+ !valid || state.editingProjectId == database.project.id
+ "
+ @click.prevent="next"
+ >
+ {{ $t("common.transfer") }}
+ </button>
+ </div>
+ </template>
+ </SelectDatabaseLabel>
</div>
</BBModal>
<BBModal
@@ -277,6 +292,7 @@ import DatabaseMigrationHistoryPanel from "../components/DatabaseMigrationHistor
import DatabaseOverviewPanel from "../components/DatabaseOverviewPanel.vue";
import InstanceEngineIcon from "../components/InstanceEngineIcon.vue";
import { DatabaseLabelProps } from "../components/DatabaseLabels";
+import { SelectDatabaseLabel } from "../components/TransferDatabaseForm";
import { idFromSlug, isDBAOrOwner, connectionSlug, hidePrefix } from "../utils";
import {
ProjectId,
@@ -315,6 +331,7 @@ export default defineComponent({
DatabaseBackupPanel,
InstanceEngineIcon,
DatabaseLabelProps,
+ SelectDatabaseLabel,
},
props: {
databaseSlug: {
@@ -513,11 +530,15 @@ export default defineComponent({
}
};
- const updateProject = (newProjectId: ProjectId) => {
+ const updateProject = (
+ newProjectId: ProjectId,
+ labels?: DatabaseLabel[]
+ ) => {
store
.dispatch("database/transferProject", {
databaseId: database.value.id,
projectId: newProjectId,
+ labels,
})
.then((updatedDatabase) => {
store.dispatch("notification/pushNotification", {
@@ -592,6 +613,11 @@ export default defineComponent({
}
);
+ const doTransfer = (labels: DatabaseLabel[]) => {
+ updateProject(state.editingProjectId, labels);
+ state.showTransferDatabaseModal = false;
+ };
+
return {
OVERVIEW_TAB,
MIGRATION_HISTORY_TAB,
@@ -614,6 +640,7 @@ export default defineComponent({
updateLabels,
selectTab,
gotoSqlEditor,
+ doTransfer,
hidePrefix,
};
},