Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(frontend): improve UX for creating database with tenant database name template (#4701)
Liu Ji6c38c3c8210b
diff --git a/frontend/src/bbkit/BBTextField.vue b/frontend/src/bbkit/BBTextField.vueindex 3d51cdca90..569aadb4ab 100644--- a/frontend/src/bbkit/BBTextField.vue+++ b/frontend/src/bbkit/BBTextField.vue@@ -34,6 +34,7 @@ interface LocalState {const props = withDefaults(defineProps<{required?: boolean;+ forceRequired?: boolean;value?: string;placeholder?: string;disabled?: boolean;@@ -43,6 +44,7 @@ const props = withDefaults(}>(),{required: false,+ forceRequired: true,value: "",placeholder: "",disabled: false,@@ -76,6 +78,11 @@ watch(() => props.value,(cur) => {state.text = cur;+ if (props.required && isEmpty(state.text.trim())) {+ state.hasError = true;+ } else {+ state.hasError = false;+ }});@@ -87,8 +94,8 @@ const onBlur = () => {if (props.required && isEmpty(state.text.trim())) {state.hasError = true;nextTick(() => {- state.text = state.originalText;- if (inputField.value) {+ if (props.forceRequired && inputField.value) {+ state.text = state.originalText;// Since we set focus in the nextTick, inputField might already disappear due to outside state change.inputField.value.focus();nextTick(() => {diff --git a/frontend/src/components/CreateDatabasePrepForm.vue b/frontend/src/components/CreateDatabasePrepForm.vueindex d93679adf3..6ff134e4d2 100644--- a/frontend/src/components/CreateDatabasePrepForm.vue+++ b/frontend/src/components/CreateDatabasePrepForm.vue@@ -16,35 +16,6 @@/></div>- <!-- Providing a preview of generated database name in template mode -->- <div v-if="isDbNameTemplateMode" class="w-full">- <label for="name" class="textlabel">- {{ $t("create-db.generated-database-name") }}- <NTooltip trigger="hover" placement="top">- <template #trigger>- <heroicons-outline:question-mark-circle- class="w-4 h-4 inline-block"- />- </template>- <div class="whitespace-nowrap">- {{- $t("create-db.db-name-generated-by-template", {- template: project.dbNameTemplate,- })- }}- </div>- </NTooltip>- </label>- <input- id="name"- disabled- name="name"- type="text"- class="textfield mt-1 w-full"- :value="generatedDatabaseName"- />- </div>-<div class="w-full"><label for="name" class="textlabel">{{ $t("create-db.new-database-name") }}@@ -65,6 +36,12 @@</template></i18n-t></span>+ <DatabaseNameTemplateTips+ v-if="isDbNameTemplateMode"+ :project="project"+ :name="state.databaseName"+ :label-list="state.labelList"+ /></div><div v-if="selectedInstance.engine == 'MONGODB'" class="w-full">@@ -261,11 +238,15 @@ import {watchEffect,defineComponent,ref,+ toRef,} from "vue";import { useRouter } from "vue-router";import { isEmpty } from "lodash-es";-import { NTooltip } from "naive-ui";-import { DatabaseLabelForm } from "./CreateDatabasePrepForm/";+import {+ DatabaseLabelForm,+ DatabaseNameTemplateTips,+ useDBNameTemplateInputState,+} from "./CreateDatabasePrepForm/";import InstanceSelect from "../components/InstanceSelect.vue";import EnvironmentSelect from "../components/EnvironmentSelect.vue";import ProjectSelect from "../components/ProjectSelect.vue";@@ -290,11 +271,7 @@ import {InstanceUserId,PITRContext,} from "../types";-import {- buildDatabaseNameByTemplateAndLabelList,- hasWorkspacePermission,- issueSlug,-} from "../utils";+import { hasWorkspacePermission, issueSlug } from "../utils";import { useEventListener } from "@vueuse/core";import {hasFeature,@@ -324,13 +301,13 @@ interface LocalState {export default defineComponent({name: "CreateDatabasePrepForm",components: {- NTooltip,InstanceSelect,EnvironmentSelect,ProjectSelect,MemberSelect,InstanceEngineIcon,DatabaseLabelForm,+ DatabaseNameTemplateTips,},props: {projectId: {@@ -423,20 +400,6 @@ export default defineComponent({return !!project.value.dbNameTemplate;});- const generatedDatabaseName = computed((): string => {- if (!isDbNameTemplateMode.value) {- // don't modify anything if we are not in template mode- return state.databaseName;- }-- return buildDatabaseNameByTemplateAndLabelList(- project.value.dbNameTemplate,- state.databaseName,- state.labelList,- true // keepEmpty: true to keep non-selected values as original placeholders- );- });-const allowCreate = computed(() => {// If we are not in template mode, none of labels are required// So we just treat this case as 'yes, valid'@@ -504,6 +467,11 @@ export default defineComponent({return state.instanceUserId !== undefined;});+ useDBNameTemplateInputState(project, {+ databaseName: toRef(state, "databaseName"),+ labels: toRef(state, "labelList"),+ });+const selectProject = (projectId: ProjectId) => {state.projectId = projectId;};@@ -535,9 +503,7 @@ export default defineComponent({let newIssue: IssueCreate;- const databaseName = isDbNameTemplateMode.value- ? generatedDatabaseName.value- : state.databaseName;+ const databaseName = state.databaseName;const tableName = state.tableName;const instanceId = state.instanceId as InstanceId;let owner = "";@@ -647,7 +613,6 @@ export default defineComponent({project,isTenantProject,isDbNameTemplateMode,- generatedDatabaseName,labelForm,allowCreate,allowEditProject,diff --git a/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue b/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vueindex 2cbca8a8f1..92bf4224ce 100644--- a/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue+++ b/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue@@ -14,9 +14,10 @@<div class="flex flex-col space-y-1"><BBTextField:required="item.required"+ :force-required="false":value="getLabelValue(item.label)":placeholder="getLabelPlaceholder(item.label)"- class="textfield"+ class="text-sm"@input="setLabelValue(item.label, ($event.target as HTMLInputElement).value)"@@ -29,8 +30,7 @@/* eslint-disable vue/no-mutating-props */import { capitalize } from "lodash-es";-import { computed } from "vue";-import { useI18n } from "vue-i18n";+import { computed, defineComponent } from "vue";import type {DatabaseLabel,LabelKeyType,@@ -51,8 +51,6 @@ const props = defineProps<{filter: "required" | "optional";}>();-const { t } = useI18n();-const isDbNameTemplateMode = computed((): boolean => {return !!props.project.dbNameTemplate;});@@ -94,7 +92,7 @@ const getLabelPlaceholder = (key: LabelKeyType): string => {key = requiredLabelDict.value.has(key)? `{{${hidePrefix(key).toUpperCase()}}}`: capitalize(hidePrefix(key));- return t("create-db.input-label-value", { key });+ return key;};const getLabelValue = (key: LabelKeyType): LabelValueType | undefined => {@@ -117,3 +115,9 @@ defineExpose({},});</script>++<script lang="ts">+export default defineComponent({+ inheritAttrs: false,+});+</script>diff --git a/frontend/src/components/CreateDatabasePrepForm/DatabaseNameTemplateTips.vue b/frontend/src/components/CreateDatabasePrepForm/DatabaseNameTemplateTips.vuenew file mode 100644index 0000000000..acdc0ae615--- /dev/null+++ b/frontend/src/components/CreateDatabasePrepForm/DatabaseNameTemplateTips.vue@@ -0,0 +1,59 @@+<template>+ <div+ v-if="mode !== 'none'"+ class="space-y-1 mt-2 text-xs"+ :class="[+ mode === 'template-mismatch' && 'text-warning',+ mode === 'value-mismatch' && 'text-warning',+ ]"+ >+ <template v-if="mode === 'normal'">+ <p>{{ $t("database.should-follow-database-name-template") }}</p>+ <p>+ <code>{{ project.dbNameTemplate }}</code>+ </p>+ </template>+ <template v-if="mode === 'template-mismatch'">+ <p>{{ $t("database.doesnt-match-database-name-template") }}</p>+ <p>+ <code>{{ project.dbNameTemplate }}</code>+ </p>+ </template>+ <template v-else-if="mode === 'value-mismatch'">+ <p>{{ $t("database.doesnt-match-tenant-value") }}</p>+ </template>+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue";++import type { DatabaseLabel, Project } from "@/types";+import {+ buildDatabaseNameRegExpByTemplate,+ getLabelValueFromLabelList,+} from "@/utils";++type ViewMode = "none" | "normal" | "template-mismatch" | "value-mismatch";++const props = defineProps<{+ name: string;+ project: Project;+ labelList: DatabaseLabel[];+}>();++const mode = computed((): ViewMode => {+ const { project, name, labelList } = props;+ if (!project.dbNameTemplate) return "none";+ if (!name) return "normal";+ const regex = buildDatabaseNameRegExpByTemplate(project.dbNameTemplate);+ const matches = name.match(regex);+ if (!matches) return "template-mismatch";+ const parsedTenant = matches.groups?.["TENANT"];+ const tenant = getLabelValueFromLabelList(labelList, "bb.tenant");+ if (parsedTenant && parsedTenant !== tenant) {+ return "value-mismatch";+ }+ return "none";+});+</script>diff --git a/frontend/src/components/CreateDatabasePrepForm/index.ts b/frontend/src/components/CreateDatabasePrepForm/index.tsindex 991d8328dc..d1bbc703d1 100644--- a/frontend/src/components/CreateDatabasePrepForm/index.ts+++ b/frontend/src/components/CreateDatabasePrepForm/index.ts@@ -1,3 +1,5 @@import DatabaseLabelForm from "./DatabaseLabelForm.vue";+import DatabaseNameTemplateTips from "./DatabaseNameTemplateTips.vue";-export { DatabaseLabelForm };+export { DatabaseLabelForm, DatabaseNameTemplateTips };+export * from "./logic";diff --git a/frontend/src/components/CreateDatabasePrepForm/logic.ts b/frontend/src/components/CreateDatabasePrepForm/logic.tsnew file mode 100644index 0000000000..009990d0dc--- /dev/null+++ b/frontend/src/components/CreateDatabasePrepForm/logic.ts@@ -0,0 +1,46 @@+import { computed, Ref, unref, watch } from "vue";+import { DatabaseLabel, MaybeRef, Project } from "@/types";+import {+ getLabelValueFromLabelList,+ parseDatabaseLabelValueByTemplate,+ setLabelValue,+} from "@/utils";+export const useDBNameTemplateInputState = (+ project: MaybeRef<Project>,+ values: {+ databaseName: Ref<string>;+ labels: Ref<DatabaseLabel[]>;+ }+) => {+ const TENANT_LABEL_KEY = "bb.tenant";+ const TENANT_LABEL_REGEXP_GROUP_NAME = "TENANT";++ const tenantValue = computed(() => {+ return getLabelValueFromLabelList(unref(values.labels), TENANT_LABEL_KEY);+ });++ const parsedTenantValue = computed(() => {+ return parseDatabaseLabelValueByTemplate(+ unref(project).dbNameTemplate,+ values.databaseName.value,+ TENANT_LABEL_REGEXP_GROUP_NAME+ );+ });++ watch(+ parsedTenantValue,+ (newValue, oldValue) => {+ const proj = unref(project);+ if (proj.tenantMode !== "TENANT") return;+ if (!proj.dbNameTemplate) return;++ const tenant = tenantValue.value;+ if (tenant && tenant !== oldValue) {+ // Tenant value has been changed by user manually, don't touch it.+ return;+ }+ setLabelValue(values.labels.value, TENANT_LABEL_KEY, newValue);+ },+ { immediate: true }+ );+};diff --git a/frontend/src/components/DatabaseDetail/CreatePITRDatabaseForm.vue b/frontend/src/components/DatabaseDetail/CreatePITRDatabaseForm.vueindex 8e3f71089d..e9367c180d 100644--- a/frontend/src/components/DatabaseDetail/CreatePITRDatabaseForm.vue+++ b/frontend/src/components/DatabaseDetail/CreatePITRDatabaseForm.vue@@ -9,40 +9,11 @@:disabled="true":include-default-project="true":selected-id="state.context.projectId"- @select-project-id="(id) => (state.context.projectId = id)"+ @select-project-id="(id: number) => (state.context.projectId = id)"/></div>- <!-- Providing a preview of generated database name in template mode -->- <div v-if="isDbNameTemplateMode" class="space-y-2">- <label class="textlabel w-full flex items-center gap-1">- {{ $t("create-db.generated-database-name") }}- <NTooltip trigger="hover" placement="top">- <template #trigger>- <heroicons-outline:question-mark-circle- class="w-4 h-4 inline-block"- />- </template>- <div class="whitespace-nowrap">- {{- $t("create-db.db-name-generated-by-template", {- template: project.dbNameTemplate,- })- }}- </div>- </NTooltip>- </label>- <input- id="name"- disabled- name="name"- type="text"- class="textfield mt-1 w-full"- :value="generatedDatabaseName"- />- </div>-- <div class="col-span-2 col-start-2 w-64">+ <div class="col-span-2 col-start-2"><label for="name" class="textlabel">{{ $t("create-db.new-database-name") }}<span class="text-red-600">*</span>@@ -62,6 +33,12 @@</template></i18n-t></span>+ <DatabaseNameTemplateTips+ v-if="isDbNameTemplateMode"+ :project="project"+ :name="state.context.databaseName"+ :label-list="state.context.labelList"+ /></div><!-- Providing more dropdowns for required labels as if they are normal required props of DB -->@@ -82,7 +59,7 @@class="mt-1":selected-id="state.context.environmentId":disabled="true"- @select-environment-id="(id) => (state.context.environmentId = id)"+ @select-environment-id="(id: number) => (state.context.environmentId = id)"/></div>@@ -101,7 +78,7 @@:selected-id="state.context.instanceId":environment-id="state.context.environmentId":filter="instanceFilter"- @select-instance-id="(id) => (state.context.instanceId = id)"+ @select-instance-id="(id: number) => (state.context.instanceId = id)"/></div>@@ -131,7 +108,7 @@/></div>- <div class="col-span-2 col-start-2 w-64">+ <div class="col-span-2 col-start-2"><label for="collation" class="textlabel">{{ $t("db.collation") }}</label>@@ -149,7 +126,15 @@</template><script lang="ts" setup>-import { computed, onBeforeMount, PropType, reactive, ref, watch } from "vue";+import {+ computed,+ onBeforeMount,+ PropType,+ reactive,+ ref,+ toRef,+ watch,+} from "vue";import { cloneDeep, isEmpty } from "lodash-es";import {Database,@@ -159,9 +144,12 @@ import {defaultCollation,} from "@/types";import { CreatePITRDatabaseContext } from "./utils";-import { DatabaseLabelForm } from "@/components/CreateDatabasePrepForm";+import {+ DatabaseLabelForm,+ DatabaseNameTemplateTips,+ useDBNameTemplateInputState,+} from "@/components/CreateDatabasePrepForm";import { useInstanceStore, useProjectStore, useDBSchemaStore } from "@/store";-import { buildDatabaseNameByTemplateAndLabelList } from "@/utils";import { isPITRAvailableOnInstance } from "@/plugins/pitr";interface LocalState {@@ -240,20 +228,6 @@ const isDbNameTemplateMode = computed((): boolean => {return !!project.value.dbNameTemplate;});-const generatedDatabaseName = computed((): string => {- if (!isDbNameTemplateMode.value) {- // don't modify anything if we are not in template mode- return state.context.databaseName;- }-- return buildDatabaseNameByTemplateAndLabelList(- project.value.dbNameTemplate,- state.context.databaseName,- state.context.labelList,- true // keepEmpty: true to keep non-selected values as original placeholders- );-});-const selectedInstance = computed((): Instance => {return instanceStore.getInstanceById(state.context.instanceId);});@@ -262,6 +236,11 @@ const instanceFilter = (instance: Instance): boolean => {return isPITRAvailableOnInstance(instance);};+useDBNameTemplateInputState(project, {+ databaseName: toRef(state.context, "databaseName"),+ labels: toRef(state.context, "labelList"),+});+// Sync values from props when changes.watch([() => props.database, () => props.context], () => {state.context = extractLocalContextFromProps();diff --git a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vueindex faee301a23..3bb8432b9a 100644--- a/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue+++ b/frontend/src/components/DatabaseDetail/PITRRestoreButton.vue@@ -70,7 +70,7 @@</template><template v-else>- <div class="w-[16.5rem] space-y-4">+ <div class="w-72 space-y-4"><div class="space-y-2"><label class="textlabel w-full flex items-baseline"><span>{{ $t("database.pitr.point-in-time") }}</span>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 4216569a72..506da15854 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1079,7 +1079,10 @@"select": "Select schema"},"show-missing-databases": "Show missing databases",- "n-selected-m-in-total": "({selected} selected, {total} in total)"+ "n-selected-m-in-total": "({selected} selected, {total} in total)",+ "doesnt-match-database-name-template": "Doesn't match tenant database name template",+ "doesnt-match-tenant-value": "Doesn't match label value",+ "should-follow-database-name-template": "Should follow tenant database name template"},"repository": {"branch-observe-file-change": "The branch where Bytebase observes the file change.",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex aead1accff..793bef2f6e 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1077,7 +1077,10 @@"select": "选择 schema"},"show-missing-databases": "显示未找到的数据库",- "n-selected-m-in-total": "(已选择 {selected},共计 {total})"+ "n-selected-m-in-total": "(已选择 {selected},共计 {total})",+ "doesnt-match-database-name-template": "不符合租户数据库名称模板",+ "doesnt-match-tenant-value": "与租户标签值不匹配",+ "should-follow-database-name-template": "需要遵循租户数据库名称模板"},"repository": {"branch-observe-file-change": "Bytebase 跟踪文件变更的分支。",diff --git a/frontend/src/utils/deployment.ts b/frontend/src/utils/deployment.tsindex b1ebe84472..358c51ce61 100644--- a/frontend/src/utils/deployment.ts+++ b/frontend/src/utils/deployment.ts@@ -53,7 +53,7 @@ export const buildDatabaseNameRegExpByTemplate = (template: string): RegExp => {/*Rewrite the placeholder-based template to a big RegExp- e.g. template = "{{DB_NAME}}_{{TENANT}}"+ e.g. template = "{{DB_NAME}}__{{TENANT}}"here regex will be /^(?<DB_NAME>.+?)__(?<TENANT>.+?)$/*/PRESET_DB_NAME_TEMPLATE_PLACEHOLDERS.forEach((placeholder) => {@@ -65,3 +65,19 @@ export const buildDatabaseNameRegExpByTemplate = (template: string): RegExp => {const regexp = new RegExp(`^${regexpString}$`);return regexp;};++export const parseDatabaseLabelValueByTemplate = (+ template: string,+ name: string,+ group: "DB_NAME" | "TENANT"+) => {+ if (!template) return "";++ const regex = buildDatabaseNameRegExpByTemplate(template);+ const matches = name.match(regex);+ if (!matches) return "";++ const value = matches.groups?.[group];+ if (!value) return "";+ return value;+};diff --git a/frontend/src/utils/label.ts b/frontend/src/utils/label.tsindex 831ad89b67..89b9b0de92 100644--- a/frontend/src/utils/label.ts+++ b/frontend/src/utils/label.ts@@ -35,15 +35,44 @@ export const hidePrefix = (key: LabelKeyType): LabelKeyType => {return key.replace(/^bb\./, "");};-export const getLabelValue = (- db: Database,+export const getLabelValueFromLabelList = (+ labels: DatabaseLabel[],key: LabelKeyType): LabelValueType => {- const label = db.labels.find((target) => target.key === key);+ const label = labels.find((target) => target.key === key);if (!label) return LABEL_VALUE_EMPTY;return label.value;};+export const getLabelValue = (+ db: Database,+ key: LabelKeyType+): LabelValueType => {+ return getLabelValueFromLabelList(db.labels, key);+};++export const setLabelValue = (+ labels: DatabaseLabel[],+ key: LabelKeyType,+ value: LabelValueType+) => {+ const index = labels.findIndex((label) => label.key === key);++ if (index < 0) {+ if (value) {+ // push new value+ labels.push({ key, value });+ }+ } else {+ if (value) {+ labels[index].value = value;+ } else {+ // remove empty value from the list+ labels.splice(index, 1);+ }+ }+};+export const groupingDatabaseListByLabelKey = (databaseList: Database[],key: LabelKeyType,