Skip to content

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

feat(frontend): support arbitrary database label values (#3455)

Liu Jib653c7b7cc57
diff --git a/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue b/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue
index 658335fb85..778ec16df5 100644
--- a/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue
+++ b/frontend/src/components/AlterSchemaPrepForm/ProjectTenantView.vue
@@ -49,11 +49,7 @@
</template>
</label>
</div>
- <YAxisRadioGroup
- v-model:label="label"
- :label-list="labelList"
- class="text-sm"
- />
+ <YAxisRadioGroup v-model:label="label" class="text-sm" />
</div>
<template v-if="databaseListGroupByName.length === 1">
@@ -61,7 +57,6 @@
class="mt-4"
:database-list="databaseListGroupByName[0].list"
:label="label"
- :label-list="labelList"
:environment-list="environmentList"
:deployment="deployment!"
/>
@@ -101,7 +96,6 @@
<DeployDatabaseTable
:database-list="list"
:label="label"
- :label-list="labelList"
:environment-list="environmentList"
:deployment="deployment!"
/>
@@ -136,7 +130,7 @@ import {
getPipelineFromDeploymentSchedule,
projectSlug,
} from "@/utils";
-import { useDeploymentStore, useLabelList } from "@/store";
+import { useDeploymentStore } from "@/store";
import { useOverrideSubtitle } from "@/bbkit/BBModal.vue";
export type State = {
@@ -169,7 +163,6 @@ const fetchData = () => {
watchEffect(fetchData);
const label = ref<LabelKeyType>("bb.environment");
-const labelList = useLabelList();
const deployment = computed(() => {
if (props.project) {
@@ -186,14 +179,12 @@ const databaseListGroupByName = computed(
if (props.project.dbNameTemplate === "") {
return [{ name: "", list: props.databaseList }];
}
- if (props.project.dbNameTemplate && labelList.value.length === 0) return [];
const dict = groupBy(props.databaseList, (db) => {
if (props.project!.dbNameTemplate) {
return parseDatabaseNameByTemplate(
db.name,
- props.project!.dbNameTemplate,
- labelList.value
+ props.project!.dbNameTemplate
);
}
});
diff --git a/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue b/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue
index 76532cdfdf..2cbca8a8f1 100644
--- a/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue
+++ b/frontend/src/components/CreateDatabasePrepForm/DatabaseLabelForm.vue
@@ -1,26 +1,26 @@
<template>
<div
v-for="item in filteredFormItemList"
- :key="item.label.key"
+ :key="item.label"
class="w-full"
+ v-bind="$attrs"
>
<div class="flex flex-row items-center space-x-1">
<label for="instance" class="textlabel capitalize">
- {{ hidePrefix(item.label.key) }}
+ {{ hidePrefix(item.label) }}
<span v-if="item.required" class="text-red-600">*</span>
</label>
</div>
<div class="flex flex-col space-y-1">
- <BBSelect
- :selected-item="getLabelValue(item.label.key)"
- :item-list="getLabelValueList(item.label)"
- :placeholder="getLabelPlaceholder(item.label.key)"
- @select-item="(value: string) => setLabelValue(item.label.key, value)"
- >
- <template #menuItem="{ item: value }">
- {{ value === "" ? $t("label.empty-label-value") : value }}
- </template>
- </BBSelect>
+ <BBTextField
+ :required="item.required"
+ :value="getLabelValue(item.label)"
+ :placeholder="getLabelPlaceholder(item.label)"
+ class="textfield"
+ @input="
+ setLabelValue(item.label, ($event.target as HTMLInputElement).value)
+ "
+ />
</div>
</div>
</template>
@@ -33,18 +33,17 @@ import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type {
DatabaseLabel,
- Label,
LabelKeyType,
LabelValueType,
Project,
} from "@/types";
import {
- isReservedLabel,
- parseLabelListInTemplate,
hidePrefix,
validateLabelsWithTemplate,
+ parseLabelListInTemplate,
+ PRESET_LABEL_KEYS,
} from "@/utils";
-import { useLabelList } from "@/store";
+import { BBTextField } from "@/bbkit";
const props = defineProps<{
project: Project;
@@ -52,18 +51,12 @@ const props = defineProps<{
filter: "required" | "optional";
}>();
-const allLabelList = useLabelList();
const { t } = useI18n();
const isDbNameTemplateMode = computed((): boolean => {
return !!props.project.dbNameTemplate;
});
-const availableLabelList = computed(() => {
- // ignore reserved labels (e.g. bb.environment)
- return allLabelList.value.filter((label) => !isReservedLabel(label));
-});
-
const requiredLabelDict = computed((): Set<LabelKeyType> => {
if (!isDbNameTemplateMode.value) {
// all labels are optional if we have no template
@@ -71,26 +64,24 @@ const requiredLabelDict = computed((): Set<LabelKeyType> => {
}
// otherwise parse the placeholders from the template
- const labels = parseLabelListInTemplate(
- props.project.dbNameTemplate,
- availableLabelList.value
- );
- const keys = labels.map((label) => label.key);
+ const keys = parseLabelListInTemplate(props.project.dbNameTemplate);
return new Set(keys);
});
-const formItemList = computed((): { label: Label; required: boolean }[] => {
- return availableLabelList.value.map((label) => {
- const required = requiredLabelDict.value.has(label.key);
- return {
- label,
- required,
- };
- });
-});
+const formItemList = computed(
+ (): { label: LabelKeyType; required: boolean }[] => {
+ return PRESET_LABEL_KEYS.map((label) => {
+ const required = requiredLabelDict.value.has(label);
+ return {
+ label,
+ required,
+ };
+ });
+ }
+);
const filteredFormItemList = computed(
- (): { label: Label; required: boolean }[] => {
+ (): { label: LabelKeyType; required: boolean }[] => {
return formItemList.value.filter((item) =>
props.filter === "required" ? item.required : !item.required
);
@@ -98,28 +89,18 @@ const filteredFormItemList = computed(
);
const getLabelPlaceholder = (key: LabelKeyType): string => {
- // provide "Select Tenant" if Tenant is optional
- // provide "Select {{TENANT}}" if Tenant is required in the template
+ // provide "Input Tenant" if Tenant is optional
+ // provide "Input {{TENANT}}" if Tenant is required in the template
key = requiredLabelDict.value.has(key)
? `{{${hidePrefix(key).toUpperCase()}}}`
: capitalize(hidePrefix(key));
- return t("create-db.select-label-value", { key });
+ return t("create-db.input-label-value", { key });
};
const getLabelValue = (key: LabelKeyType): LabelValueType | undefined => {
return props.labelList.find((label) => label.key === key)?.value || "";
};
-const getLabelValueList = (label: Label): LabelValueType[] => {
- const valueList = [...label.valueList];
- if (!requiredLabelDict.value.has(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 = props.labelList.find((label) => label.key === key);
if (label) {
diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabel.vue b/frontend/src/components/DatabaseLabels/DatabaseLabel.vue
deleted file mode 100644
index 87297a4b66..0000000000
--- a/frontend/src/components/DatabaseLabels/DatabaseLabel.vue
+++ /dev/null
@@ -1,115 +0,0 @@
-<template>
- <!-- eslint-disable vue/no-mutating-props -->
- <div class="database-label" :class="{ editable }">
- <div class="select key">
- <span class="capitalize">{{ hidePrefix(label.key) }}</span>
- <span v-if="editable" class="dropdown-icon">
- <heroicons-solid:selector class="h-4 w-4 text-control-light" />
- </span>
- <select v-if="editable" v-model="label.key">
- <option v-for="(key, i) in keys" :key="i" :value="key">
- <!-- not available to use <span class="capitalize"> here -->
- {{ capitalize(hidePrefix(key)) }}
- </option>
- </select>
- </div>
- <div v-if="!editable" class="colon">:</div>
- <div class="select value">
- <span>{{ label.value }}</span>
- <span v-if="editable" class="dropdown-icon">
- <heroicons-solid:selector class="h-4 w-4 text-control-light" />
- </span>
- <select v-if="editable" v-model="label.value">
- <option v-for="(value, i) in values" :key="i" :value="value">
- {{ value }}
- </option>
- </select>
- </div>
- <div v-if="editable" class="remove" @click="$emit('remove')">
- <heroicons-solid:x class="w-3 h-3 text-control" />
- </div>
- </div>
-</template>
-
-<script lang="ts">
-/* eslint-disable vue/no-mutating-props */
-
-import { computed, defineComponent, PropType, watch } from "vue";
-import { DatabaseLabel, Label } from "../../types";
-import { hidePrefix } from "../../utils";
-import { capitalize } from "lodash-es";
-
-export default defineComponent({
- name: "DatabaseLabel",
- props: {
- // bound value will be mutated directly
- // this is an anti-pattern in vue
- // but we do it here to make this component simple and stupid
- label: {
- type: Object as PropType<DatabaseLabel>,
- required: true,
- },
- editable: {
- type: Boolean,
- default: false,
- },
- availableLabelList: {
- type: Array as PropType<Label[]>,
- default: () => [],
- },
- },
- emits: ["remove"],
- setup(props) {
- const keys = computed(() =>
- props.availableLabelList.map((label) => label.key)
- );
- const values = computed(() => {
- if (!props.label.key) return [];
- const labelDefinition = props.availableLabelList.find(
- (l) => l.key === props.label.key
- );
- if (!labelDefinition) return [];
- return labelDefinition.valueList;
- });
-
- watch(
- () => props.label.key,
- () => {
- if (!props.editable) return false; // if not editable, do nothing
-
- // otherwise when key changed, reset value selection
- props.label.value = values.value[0] || "";
- }
- );
-
- return {
- keys,
- values,
- hidePrefix,
- capitalize,
- };
- },
-});
-</script>
-
-<style scoped lang="postcss">
-.database-label {
- @apply h-6 relative z-0 flex items-center text-sm rounded overflow-hidden px-2 whitespace-nowrap
- bg-blue-100 border-blue-300 border select-none;
-}
-.select {
- @apply h-full relative flex items-center overflow-hidden;
-}
-.select .dropdown-icon {
- @apply ml-0 mr-1 flex items-center p-0 rounded-sm pointer-events-none; /* cursor-pointer hover:bg-gray-300;*/
-}
-.select select {
- @apply absolute w-full h-full inset-0 p-0 m-0 opacity-0 !important;
-}
-.colon {
- @apply ml-0.5 mr-2;
-}
-.remove {
- @apply ml-0 -mr-1 p-px cursor-pointer hover:bg-blue-300 rounded-sm;
-}
-</style>
diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabelPropItem.vue b/frontend/src/components/DatabaseLabels/DatabaseLabelPropItem.vue
index 825c141f0d..01e157caf1 100644
--- a/frontend/src/components/DatabaseLabels/DatabaseLabelPropItem.vue
+++ b/frontend/src/components/DatabaseLabels/DatabaseLabelPropItem.vue
@@ -1,43 +1,65 @@
<template>
- <span class="textlabel relative inline-flex items-center">
- <template v-if="!editable">
+ <span class="textlabel relative inline-flex items-center gap-x-1">
+ <template v-if="!state.editing">
{{ value || $t("label.empty-label-value") }}
+
+ <heroicons-outline:pencil
+ v-if="editable"
+ class="w-5 h-5 p-0.5 rounded cursor-pointer hover:bg-control-bg-hover"
+ @click="startEditing"
+ />
</template>
- <template v-else>
- <select
- class="absolute inset-0 opacity-0 m-0 p-0"
- :value="state.value"
- @change="onChange"
- >
- <option :value="''" :selected="!!state.value">
- {{ $t("label.empty-label-value") }}
- </option>
- <option
- v-for="(labelValue, i) in label.valueList"
- :key="i"
- :value="labelValue"
- >
- {{ labelValue }}
- </option>
- </select>
- {{ state.value || $t("label.empty-label-value") }}
- <heroicons-outline:chevron-down class="w-4 h-4 ml-0.5" />
+ <template v-else-if="state.editing">
+ <input
+ ref="input"
+ v-model="state.value"
+ type="text"
+ autocomplete="off"
+ class="textfield"
+ :class="{ error: !!state.error && state.changed }"
+ :placeholder="$t('setting.label.value-placeholder')"
+ @blur="cancel"
+ @keyup.esc="cancel"
+ @keyup.enter="save"
+ />
+ <div class="icon-btn cancel" @click="cancel">
+ <heroicons-solid:x class="w-4 h-4" />
+ </div>
+ <NPopover trigger="hover" :disabled="!state.error">
+ <template #trigger>
+ <div
+ class="icon-btn save"
+ :class="{ disabled: !!state.error }"
+ @mousedown.prevent.stop="save"
+ >
+ <heroicons-solid:check class="w-4 h-4" />
+ </div>
+ </template>
+
+ <div class="text-red-600 whitespace-nowrap">
+ {{ state.error }}
+ </div>
+ </NPopover>
</template>
</span>
</template>
<script lang="ts" setup>
-import { capitalize } from "lodash-es";
-import { useDialog } from "naive-ui";
-import { computed, reactive, watch } from "vue";
+import { computed, nextTick, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
-import { Database, Label, LabelValueType } from "../../types";
-import { hidePrefix } from "../../utils";
+import { Database, LabelKeyType, LabelValueType } from "../../types";
+import { LABEL_VALUE_EMPTY, MAX_LABEL_VALUE_LENGTH } from "../../utils";
+
+type LocalState = {
+ editing: boolean;
+ value: LabelValueType | undefined;
+ error: string | undefined;
+ changed: boolean;
+};
const props = defineProps<{
- label: Label;
- labelList: Label[];
- requiredLabelList: Label[];
+ labelKey: LabelKeyType;
+ required: boolean;
value: LabelValueType | undefined;
database: Database;
allowEdit: boolean;
@@ -49,11 +71,14 @@ const emit = defineEmits<{
const { t } = useI18n();
-const state = reactive({
+const state = reactive<LocalState>({
+ editing: false,
value: props.value,
+ error: undefined,
+ changed: false,
});
-const dialog = useDialog();
+const input = ref<HTMLInputElement>();
watch(
() => props.value,
@@ -63,33 +88,81 @@ watch(
const editable = computed((): boolean => {
if (!props.allowEdit) return false;
- // Not editable if this is a required label in `dbNameTemplate`
- // e.g. tenant in "{{DB_NAME}}_{{TENANT}}"
- const isRequired = !!props.requiredLabelList.find(
- (label) => label.key === props.label.key
- );
- return !isRequired;
+ return !props.required;
});
-const onChange = (e: Event) => {
- const select = e.target as HTMLSelectElement;
- dialog.create({
- positiveText: t("common.confirm"),
- negativeText: t("common.cancel"),
- title: t("label.confirm-change", {
- label: capitalize(hidePrefix(props.label.key)),
- }),
- closable: false,
- maskClosable: false,
- closeOnEsc: false,
- onNegativeClick: () => {
- state.value = props.value;
- select.value = state.value || "";
- },
- onPositiveClick: () => {
- const { value } = select;
- emit("update:value", value);
- },
+const startEditing = () => {
+ state.value = props.value;
+ state.error = undefined;
+ state.changed = false;
+ state.editing = true;
+
+ nextTick(() => {
+ input.value?.focus();
});
};
+const validate = (): boolean => {
+ const value = state.value?.trim();
+
+ if (!value) {
+ // Empty value is allowed
+ state.error = undefined;
+ return true;
+ }
+
+ if (value.length > MAX_LABEL_VALUE_LENGTH) {
+ // Max length exceeded
+ state.error = t("label.error.max-length-exceeded", {
+ len: MAX_LABEL_VALUE_LENGTH,
+ });
+ } else {
+ state.error = undefined;
+ }
+
+ return !state.error;
+};
+
+const cancel = () => {
+ state.editing = false;
+};
+
+const save = () => {
+ if (!validate()) return;
+
+ const value = state.value?.trim() ?? LABEL_VALUE_EMPTY;
+ emit("update:value", value);
+ cancel();
+};
+
+watch([() => state.editing, () => state.value], ([editing, value]) => {
+ if (!editing) return;
+ if (value !== props.value) {
+ state.changed = true;
+ validate();
+ }
+});
</script>
+
+<style scoped lang="postcss">
+.icon-btn {
+ @apply w-[20px] h-[20px] inline-flex items-center justify-center
+ rounded bg-white border border-control-border
+ hover:bg-control-bg-hover
+ cursor-pointer;
+}
+.icon-btn.disabled {
+ @apply cursor-not-allowed bg-control-bg;
+}
+.textfield {
+ @apply rounded px-0.5 py-0 text-sm w-32 h-[20px];
+}
+.textfield.error {
+ @apply border-error focus:ring-error focus:border-error;
+}
+.cancel {
+ @apply text-control;
+}
+.save {
+ @apply text-success;
+}
+</style>
diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabelProps.vue b/frontend/src/components/DatabaseLabels/DatabaseLabelProps.vue
index 84d218aeef..6f95ce8201 100644
--- a/frontend/src/components/DatabaseLabels/DatabaseLabelProps.vue
+++ b/frontend/src/components/DatabaseLabels/DatabaseLabelProps.vue
@@ -1,15 +1,14 @@
<template>
- <template v-for="label in availableLabelList" :key="label.key">
+ <template v-for="label in PRESET_LABEL_KEYS" :key="label.key">
<dd class="flex items-center text-sm md:mr-4">
<slot name="label" :label="label"></slot>
<DatabaseLabelPropItem
- :label="label"
- :value="getLabelValue(label.key)"
- :label-list="availableLabelList"
- :required-label-list="requiredLabelList"
+ :label-key="label"
+ :value="getLabelValue(label)"
+ :required="isRequired(label)"
:database="database"
:allow-edit="allowEdit"
- @update:value="(value) => onUpdateValue(label.key, value)"
+ @update:value="(value) => onUpdateValue(label, value)"
/>
</dd>
</template>
@@ -24,8 +23,7 @@ import type {
LabelKeyType,
LabelValueType,
} from "@/types";
-import { isReservedLabel, parseLabelListInTemplate } from "@/utils";
-import { useLabelList } from "@/store";
+import { parseLabelListInTemplate, PRESET_LABEL_KEYS } from "@/utils";
import DatabaseLabelPropItem from "./DatabaseLabelPropItem.vue";
const props = withDefaults(
@@ -47,28 +45,23 @@ const state = reactive({
labelList: cloneDeep(props.labelList),
});
-const allLabelList = useLabelList();
-
watch(
() => props.labelList,
(list) => (state.labelList = cloneDeep(list))
);
-const availableLabelList = computed(() => {
- return allLabelList.value.filter((label) => !isReservedLabel(label));
-});
-
-const requiredLabelList = computed(() => {
+const requiredLabelList = computed((): string[] => {
const { project } = props.database;
if (project.tenantMode !== "TENANT") return [];
if (!project.dbNameTemplate) return [];
- return parseLabelListInTemplate(
- project.dbNameTemplate,
- availableLabelList.value
- );
+ return parseLabelListInTemplate(project.dbNameTemplate);
});
+const isRequired = (key: LabelKeyType) => {
+ return requiredLabelList.value.includes(key);
+};
+
const getLabelValue = (key: LabelKeyType): LabelValueType | undefined => {
return state.labelList.find((label) => label.key === key)?.value || "";
};
diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabels.vue b/frontend/src/components/DatabaseLabels/DatabaseLabels.vue
deleted file mode 100644
index dafe63772e..0000000000
--- a/frontend/src/components/DatabaseLabels/DatabaseLabels.vue
+++ /dev/null
@@ -1,117 +0,0 @@
-<template>
- <div class="flex gap-2">
- <DatabaseLabel
- v-for="(label, i) in labelList"
- :key="i"
- :label="label"
- :editable="isEditableLabel(label)"
- :available-label-list="availableLabelList"
- @remove="removeLabel(i)"
- />
- <template v-if="editable">
- <NPopover trigger="hover" :disabled="allowAdd">
- <template #trigger>
- <button
- class="add-button"
- :class="{ disabled: !allowAdd }"
- @click="addLabel"
- >
- <heroicons-solid:plus class="w-4 h-4" />
- </button>
- </template>
-
- <div class="text-red-600 whitespace-nowrap">
- {{
- $t("label.error.max-label-count-exceeded", {
- count: MAX_DATABASE_LABEL_COUNT,
- })
- }}
- </div>
- </NPopover>
- </template>
- </div>
-</template>
-
-<script lang="ts">
-/* eslint-disable vue/no-mutating-props */
-
-import { computed, defineComponent, PropType } from "vue";
-import { NPopover } from "naive-ui";
-import type { DatabaseLabel } from "@/types";
-import { isReservedLabel, isReservedDatabaseLabel } from "@/utils";
-import { useLabelList } from "@/store";
-
-const MAX_DATABASE_LABEL_COUNT = 4;
-
-export default defineComponent({
- name: "DatabaseLabels",
- components: { NPopover },
- props: {
- labelList: {
- type: Array as PropType<DatabaseLabel[]>,
- default: () => [],
- },
- editable: {
- type: Boolean,
- default: false,
- },
- },
- setup(props) {
- const allowAdd = computed(
- () => props.labelList.length < MAX_DATABASE_LABEL_COUNT
- );
-
- const labelList = useLabelList();
-
- const availableLabelList = computed(() =>
- labelList.value.filter((label) => !isReservedLabel(label))
- );
-
- const addLabel = () => {
- if (!allowAdd.value) return;
-
- const key = labelList.value[0]?.key || "";
- const value = labelList.value[0]?.valueList[0] || "";
- props.labelList.push({
- key,
- value,
- });
- };
-
- const removeLabel = (index: number) => {
- props.labelList.splice(index, 1);
- };
-
- const isEditableLabel = (label: DatabaseLabel): boolean => {
- if (labelList.value.length === 0) {
- // not ready yet, disable editing temporarily
- // this also avoid some UI blinking
- return false;
- }
-
- return props.editable && !isReservedDatabaseLabel(label, labelList.value);
- };
-
- return {
- MAX_DATABASE_LABEL_COUNT,
- availableLabelList,
- isEditableLabel,
- allowAdd,
- addLabel,
- removeLabel,
- };
- },
-});
-</script>
-
-<style scoped lang="postcss">
-.add-button {
- @apply h-6 px-1 py-1 inline-flex items-center
- rounded bg-white border border-control-border
- hover:bg-control-bg-hover
- cursor-pointer;
-}
-.add-button.disabled {
- @apply cursor-not-allowed bg-control-bg;
-}
-</style>
diff --git a/frontend/src/components/DatabaseLabels/DatabaseLabelsEditor.vue b/frontend/src/components/DatabaseLabels/DatabaseLabelsEditor.vue
deleted file mode 100644
index b8d822b33f..0000000000
--- a/frontend/src/components/DatabaseLabels/DatabaseLabelsEditor.vue
+++ /dev/null
@@ -1,142 +0,0 @@
-<template>
- <div class="database-labels-editor flex items-center">
- <DatabaseLabels
- :label-list="state.labelList"
- :editable="allowEdit && state.mode === 'EDIT'"
- />
- <div
- v-if="state.mode === 'VIEW' && state.labelList.length === 0"
- class="text-sm text-control-placeholder"
- >
- {{ $t("label.no-label") }}
- </div>
- <div
- v-if="allowEdit"
- class="buttons flex items-center gap-1 ml-1 text-control"
- >
- <template v-if="state.mode === 'VIEW'">
- <button class="icon-btn lite" @click="state.mode = 'EDIT'">
- <heroicons-outline:pencil class="w-4 h-4" />
- </button>
- </template>
- <template v-else>
- <button class="icon-btn text-error" @click="cancel">
- <heroicons-solid:x class="w-4 h-4" />
- </button>
-
- <NPopover trigger="hover" :disabled="!state.error">
- <template #trigger>
- <button
- class="icon-btn text-success"
- :class="{ disabled: !!state.error }"
- @click="save"
- >
- <heroicons-solid:check class="w-4 h-4" />
- </button>
- </template>
-
- <div class="text-red-600 whitespace-nowrap">
- {{ state.error }}
- </div>
- </NPopover>
- </template>
- </div>
- </div>
-</template>
-
-<script lang="ts">
-import { cloneDeep } from "lodash-es";
-import { defineComponent, PropType, reactive, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { DatabaseLabel } from "../../types";
-import { validateLabels } from "../../utils";
-import { NPopover } from "naive-ui";
-
-type LocalState = {
- mode: "VIEW" | "EDIT";
- labelList: DatabaseLabel[];
- error: string | undefined;
-};
-
-export default defineComponent({
- name: "DatabaseLabelsEditor",
- components: { NPopover },
- props: {
- labelList: {
- type: Array as PropType<DatabaseLabel[]>,
- default: () => [],
- },
- allowEdit: {
- type: Boolean,
- default: true,
- },
- },
- emits: ["save"],
- setup(props, { emit }) {
- const { t } = useI18n();
-
- const state = reactive<LocalState>({
- mode: "VIEW",
- labelList: cloneDeep(props.labelList),
- error: undefined,
- });
-
- watch(
- () => props.labelList,
- (labelList) => {
- // state.labelList are a local deep-copy of props.labelList
- // <DatabaseLabels /> will mutate state.labelList directly
- // when save button clicked, we emit a event to notify the parent
- // component to dispatch a real save action
- state.labelList = cloneDeep(labelList);
- state.error = undefined;
- }
- );
-
- watch(
- () => state.labelList,
- (labels) => {
- const error = validateLabels(labels);
- if (error) {
- state.error = t(error);
- } else {
- state.error = undefined;
- }
- },
- { deep: true }
- );
-
- const cancel = () => {
- state.mode = "VIEW";
- state.labelList = cloneDeep(props.labelList);
- state.error = undefined;
- };
- const save = () => {
- if (state.error) return;
- emit("save", state.labelList);
- state.mode = "VIEW";
- };
-
- return {
- state,
- cancel,
- save,
- };
- },
-});
-</script>
-
-<style scoped lang="postcss">
-.icon-btn {
- @apply h-6 px-1 py-1 inline-flex items-center
- rounded bg-white border border-control-border
- hover:bg-control-bg-hover
- cursor-pointer;
-}
-.icon-btn.disabled {
- @apply cursor-not-allowed bg-control-bg;
-}
-.icon-btn.lite {
- @apply px-1 border-none hover:bg-control-bg-hover;
-}
-</style>
diff --git a/frontend/src/components/DatabaseLabels/index.ts b/frontend/src/components/DatabaseLabels/index.ts
index c98d0b56cf..5d749fc2e7 100644
--- a/frontend/src/components/DatabaseLabels/index.ts
+++ b/frontend/src/components/DatabaseLabels/index.ts
@@ -1,7 +1,3 @@
-import DatabaseLabels from "./DatabaseLabels.vue";
-import DatabaseLabelsEditor from "./DatabaseLabelsEditor.vue";
import DatabaseLabelProps from "./DatabaseLabelProps.vue";
-export default DatabaseLabels;
-
-export { DatabaseLabels, DatabaseLabelsEditor, DatabaseLabelProps };
+export { DatabaseLabelProps };
diff --git a/frontend/src/components/DatabaseListSidePanel.vue b/frontend/src/components/DatabaseListSidePanel.vue
index f680d3b741..7ec32ed1e2 100644
--- a/frontend/src/components/DatabaseListSidePanel.vue
+++ b/frontend/src/components/DatabaseListSidePanel.vue
@@ -21,12 +21,7 @@ import {
parseDatabaseNameByTemplate,
projectSlug,
} from "@/utils";
-import {
- useEnvironmentList,
- useCurrentUser,
- useDatabaseStore,
- useLabelList,
-} from "@/store";
+import { useEnvironmentList, useCurrentUser, useDatabaseStore } from "@/store";
export default defineComponent({
name: "DatabaseListSidePanel",
@@ -56,9 +51,6 @@ export default defineComponent({
return databaseStore.getDatabaseListByPrincipalId(currentUser.value.id);
});
- // Use this to parse database name from name template
- const labelList = useLabelList();
-
const databaseListByEnvironment = computed(() => {
const envToDbMap: Map<EnvironmentId, BBOutlineItem[]> = new Map();
for (const environment of environmentList.value) {
@@ -97,12 +89,6 @@ export default defineComponent({
});
const tenantDatabaseListByProject = computed((): BBOutlineItem[] => {
- if (labelList.value.length === 0) {
- // wait for the labelList to be loaded
- // to prevent UI jitter
- return [];
- }
-
const list = databaseList.value.filter(
(db) => db.project.tenantMode === "TENANT"
);
@@ -130,8 +116,7 @@ export default defineComponent({
// parse db name from template if possible
return parseDatabaseNameByTemplate(
db.name,
- project.dbNameTemplate,
- labelList.value
+ project.dbNameTemplate
);
} else {
// use raw db.name otherwise
diff --git a/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vue b/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vue
index d1b11ab7fb..2466069895 100644
--- a/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vue
+++ b/frontend/src/components/DeploymentConfigTool/DeploymentConfigTool.vue
@@ -9,7 +9,6 @@
:allow-edit="allowEdit"
:show-header="true"
:database-list="databaseList"
- :label-list="labelList"
@remove="removeStage(deployment)"
@prev="reorder(i, -1)"
@next="reorder(i, 1)"
@@ -22,12 +21,7 @@
/* eslint-disable vue/no-mutating-props */
import { defineComponent, PropType } from "vue";
-import {
- AvailableLabel,
- Database,
- Deployment,
- DeploymentSchedule,
-} from "../../types";
+import { Database, Deployment, DeploymentSchedule } from "../../types";
import DeploymentStage from "./DeploymentStage.vue";
export default defineComponent({
@@ -46,10 +40,6 @@ export default defineComponent({
type: Array as PropType<Database[]>,
default: () => [],
},
- labelList: {
- type: Array as PropType<AvailableLabel[]>,
- default: () => [],
- },
},
setup(props) {
const keyMap = new WeakMap<Deployment, number>();
diff --git a/frontend/src/components/DeploymentConfigTool/DeploymentMatrix.vue b/frontend/src/components/DeploymentConfigTool/DeploymentMatrix.vue
index 23ee00e19a..4a4b4ebed7 100644
--- a/frontend/src/components/DeploymentConfigTool/DeploymentMatrix.vue
+++ b/frontend/src/components/DeploymentConfigTool/DeploymentMatrix.vue
@@ -35,18 +35,13 @@
</select>
</div>
- <YAxisRadioGroup
- v-model:label="state.label"
- :label-list="labelList"
- class="text-sm"
- />
+ <YAxisRadioGroup v-model:label="state.label" class="text-sm" />
</div>
<div v-if="selectedDatabaseGroup">
<DeployDatabaseTable
:database-list="selectedDatabaseGroup.list"
:label="state.label"
- :label-list="labelList"
:environment-list="environmentList"
:deployment="deployment"
/>
@@ -62,7 +57,6 @@ import {
DeploymentConfig,
Environment,
Database,
- Label,
LabelKeyType,
} from "@/types";
import { groupBy } from "lodash-es";
@@ -79,7 +73,6 @@ const props = defineProps<{
deployment: DeploymentConfig;
environmentList: Environment[];
databaseList: Database[];
- labelList: Label[];
}>();
const state = reactive({
@@ -94,19 +87,9 @@ const databaseListGroupByName = computed((): DatabaseGroup[] => {
return [{ name: "", list: props.databaseList }];
}
- if (dbNameTemplate && props.labelList.length === 0) {
- // We can't calculate dbname correctly if labelList hasn't been fetched
- // So return empty array as a fallback
- return [];
- }
-
const dict = groupBy(props.databaseList, (db) => {
if (dbNameTemplate) {
- return parseDatabaseNameByTemplate(
- db.name,
- dbNameTemplate,
- props.labelList
- );
+ return parseDatabaseNameByTemplate(db.name, dbNameTemplate);
} else {
return db.name;
}
diff --git a/frontend/src/components/DeploymentConfigTool/DeploymentStage.vue b/frontend/src/components/DeploymentConfigTool/DeploymentStage.vue
index d0d7635867..790bae4aa8 100644
--- a/frontend/src/components/DeploymentConfigTool/DeploymentStage.vue
+++ b/frontend/src/components/DeploymentConfigTool/DeploymentStage.vue
@@ -46,7 +46,7 @@
<SelectorItem
:editable="allowEdit"
:selector="selector"
- :label-list="labelList"
+ :database-list="databaseList"
@remove="removeSelector(selector)"
/>
</div>
@@ -67,13 +67,9 @@
</template>
<script lang="ts">
-import { defineComponent, PropType } from "vue";
-import {
- AvailableLabel,
- Database,
- Deployment,
- LabelSelectorRequirement,
-} from "../../types";
+import { uniq } from "lodash-es";
+import { computed, defineComponent, PropType } from "vue";
+import { Database, Deployment, LabelSelectorRequirement } from "../../types";
import SelectorItem from "./SelectorItem.vue";
export default defineComponent({
@@ -100,10 +96,6 @@ export default defineComponent({
type: Array as PropType<Database[]>,
default: () => [],
},
- labelList: {
- type: Array as PropType<AvailableLabel[]>,
- default: () => [],
- },
showHeader: {
type: Boolean,
default: true,
@@ -115,6 +107,13 @@ export default defineComponent({
},
emits: ["remove", "prev", "next"],
setup(props) {
+ const keys = computed(() => {
+ const allKeys = props.databaseList.flatMap((db) =>
+ db.labels.map((label) => label.key)
+ );
+ return uniq(allKeys);
+ });
+
const removeSelector = (selector: LabelSelectorRequirement) => {
const array = props.deployment.spec.selector.matchExpressions;
const index = array.indexOf(selector);
@@ -125,15 +124,11 @@ export default defineComponent({
const addSelector = () => {
const array = props.deployment.spec.selector.matchExpressions;
- const label = props.labelList[0];
const rule: LabelSelectorRequirement = {
- key: label?.key || "",
+ key: keys.value[0] ?? "",
operator: "In",
values: [],
};
- if (label && label.valueList.length > 0) {
- rule.values.push(label.valueList[0]);
- }
array.push(rule);
};
diff --git a/frontend/src/components/DeploymentConfigTool/SelectorItem.vue b/frontend/src/components/DeploymentConfigTool/SelectorItem.vue
index b603265d4a..e95cba81a4 100644
--- a/frontend/src/components/DeploymentConfigTool/SelectorItem.vue
+++ b/frontend/src/components/DeploymentConfigTool/SelectorItem.vue
@@ -35,14 +35,10 @@
/* eslint-disable vue/no-mutating-props */
import { computed, defineComponent, PropType, watch } from "vue";
-import {
- AvailableLabel,
- LabelSelectorRequirement,
- OperatorType,
-} from "../../types";
-import { hidePrefix } from "../../utils";
+import { Database, LabelSelectorRequirement, OperatorType } from "../../types";
+import { getLabelValuesFromDatabaseList, hidePrefix } from "../../utils";
import LabelSelect from "./LabelSelect.vue";
-import { lowerCase } from "lodash-es";
+import { lowerCase, uniq } from "lodash-es";
const OPERATORS: OperatorType[] = ["In", "Exists"];
@@ -54,8 +50,8 @@ export default defineComponent({
type: Object as PropType<LabelSelectorRequirement>,
required: true,
},
- labelList: {
- type: Array as PropType<AvailableLabel[]>,
+ databaseList: {
+ type: Array as PropType<Database[]>,
default: () => [],
},
editable: {
@@ -65,14 +61,19 @@ export default defineComponent({
},
emits: ["remove"],
setup(props) {
- const keys = computed(() => props.labelList.map((label) => label.key));
+ const keys = computed(() => {
+ const allKeys = props.databaseList.flatMap((db) =>
+ db.labels.map((label) => label.key)
+ );
+ return uniq(allKeys);
+ });
const values = computed(() => {
if (!props.selector.key) return [];
- const labelDefinition = props.labelList.find(
- (l) => l.key === props.selector.key
+ return getLabelValuesFromDatabaseList(
+ props.selector.key,
+ props.databaseList,
+ false /* !withEmptyValue */
);
- if (!labelDefinition) return [];
- return labelDefinition.valueList;
});
const resetValues = () => {
diff --git a/frontend/src/components/Issue/IssueSidebar.vue b/frontend/src/components/Issue/IssueSidebar.vue
index 81d296c93e..8c4e10c71b 100644
--- a/frontend/src/components/Issue/IssueSidebar.vue
+++ b/frontend/src/components/Issue/IssueSidebar.vue
@@ -316,7 +316,6 @@ import {
useCurrentUser,
useDatabaseStore,
useEnvironmentStore,
- useLabelList,
useProjectStore,
} from "@/store";
import {
@@ -418,15 +417,12 @@ const project = computed((): Project => {
return (issue.value as Issue).project;
});
-const labelList = useLabelList();
-
const visibleLabelList = computed((): DatabaseLabel[] => {
// transform non-reserved labels to db properties
if (!props.database) return [];
- if (labelList.value.length === 0) return [];
return props.database.labels.filter(
- (label) => !isReservedDatabaseLabel(label, labelList.value)
+ (label) => !isReservedDatabaseLabel(label)
);
});
diff --git a/frontend/src/components/ProjectCreate.vue b/frontend/src/components/ProjectCreate.vue
index 6b7eb7ed18..a5b6480246 100644
--- a/frontend/src/components/ProjectCreate.vue
+++ b/frontend/src/components/ProjectCreate.vue
@@ -99,7 +99,7 @@
class="mt-2 w-full placeholder-gray-300"
:required="true"
:value="state.project.dbNameTemplate"
- placeholder="e.g. {{DB_NAME}}_{{TENANT}}"
+ :placeholder="`e.g. ${DEFAULT_DB_NAME_TEMPLATE}`"
@input="
state.project.dbNameTemplate = (
$event.target as HTMLInputElement
@@ -163,6 +163,8 @@ interface LocalState {
isCreating: boolean;
}
+const DEFAULT_DB_NAME_TEMPLATE = "{{DB_NAME}}__{{TENANT}}";
+
export default defineComponent({
name: "ProjectCreate",
emits: ["dismiss"],
@@ -206,7 +208,7 @@ export default defineComponent({
() => state.enableDbNameTemplate,
(on) => {
if (on) {
- state.project.dbNameTemplate = "{{DB_NAME}}_{{TENANT}}";
+ state.project.dbNameTemplate = DEFAULT_DB_NAME_TEMPLATE;
} else {
state.project.dbNameTemplate = "";
}
@@ -262,6 +264,7 @@ export default defineComponent({
};
return {
+ DEFAULT_DB_NAME_TEMPLATE,
state,
allowCreate,
cancel,
diff --git a/frontend/src/components/ProjectDeploymentConfigPanel.vue b/frontend/src/components/ProjectDeploymentConfigPanel.vue
index 84ce703dff..01b77b4248 100644
--- a/frontend/src/components/ProjectDeploymentConfigPanel.vue
+++ b/frontend/src/components/ProjectDeploymentConfigPanel.vue
@@ -46,7 +46,6 @@
<DeploymentConfigTool
:schedule="state.deployment.schedule"
:allow-edit="allowEdit"
- :label-list="availableLabelList"
:database-list="databaseList"
/>
<div class="pt-4 border-t flex justify-between items-center">
@@ -94,7 +93,6 @@
:deployment="state.deployment"
:database-list="databaseList"
:environment-list="environmentList"
- :label-list="labelList"
/>
</div>
</div>
@@ -120,7 +118,6 @@ import { useI18n } from "vue-i18n";
import { NPopover, useDialog } from "naive-ui";
import {
Project,
- AvailableLabel,
DeploymentConfig,
EMPTY_ID,
DeploymentConfigPatch,
@@ -134,7 +131,6 @@ import {
useDeploymentStore,
useEnvironmentList,
useEnvironmentStore,
- useLabelList,
} from "@/store";
type LocalState = {
@@ -185,20 +181,12 @@ export default defineComponent({
const environmentList = useEnvironmentList();
- const labelList = useLabelList();
-
const databaseList = computed(() =>
databaseStore.getDatabaseListByProjectId(props.project.id)
);
watchEffect(prepareList);
- const availableLabelList = computed((): AvailableLabel[] => {
- return labelList.value.map((label) => {
- return { key: label.key, valueList: [...label.valueList] };
- });
- });
-
const resetStates = async () => {
await nextTick(); // Waiting for all watchers done
state.error = undefined;
@@ -305,9 +293,7 @@ export default defineComponent({
dirty,
allowUpdate,
environmentList,
- labelList,
databaseList,
- availableLabelList,
addStage,
revert,
update,
diff --git a/frontend/src/components/ProjectOverviewPanel.vue b/frontend/src/components/ProjectOverviewPanel.vue
index f36d392e31..e8dc3656e6 100644
--- a/frontend/src/components/ProjectOverviewPanel.vue
+++ b/frontend/src/components/ProjectOverviewPanel.vue
@@ -53,7 +53,7 @@
<YAxisRadioGroup
v-if="isTenantProject && state.yAxisLabel"
v-model:label="state.yAxisLabel"
- :label-list="selectableLabelList"
+ :excluded-key-list="excludedKeyList"
class="text-sm font-normal py-1"
/>
@@ -65,7 +65,6 @@
:project="project"
:x-axis-label="state.xAxisLabel"
:y-axis-label="state.yAxisLabel"
- :label-list="labelList"
/>
<div v-else class="w-full h-40 flex justify-center items-center">
<NSpin />
@@ -167,7 +166,6 @@ import { Activity, Database, Issue, Project, LabelKeyType } from "../types";
import { findDefaultGroupByLabel } from "../utils";
import {
useActivityStore,
- useLabelList,
usePolicyListByResourceTypeAndPolicyType,
} from "@/store";
import PagedIssueTable from "@/components/Issue/PagedIssueTable.vue";
@@ -255,8 +253,6 @@ export default defineComponent({
watch(() => props.project.id, prepare, { immediate: true });
- const labelList = useLabelList();
-
const filteredDatabaseList = computed(() => {
const filter = state.databaseNameFilter.toLocaleLowerCase();
if (!filter) return props.databaseList;
@@ -266,16 +262,12 @@ export default defineComponent({
);
});
- // make "bb.environment" non-selectable because it was already specified to the x-axis
- const selectableLabelList = computed(() => {
- const excludes = new Set([state.xAxisLabel]);
- return labelList.value.filter((label) => !excludes.has(label.key));
- });
+ const excludedKeyList = computed(() => [state.xAxisLabel]);
watchEffect(() => {
state.yAxisLabel = findDefaultGroupByLabel(
- selectableLabelList.value,
- filteredDatabaseList.value
+ filteredDatabaseList.value,
+ excludedKeyList.value
);
});
@@ -283,8 +275,7 @@ export default defineComponent({
state,
isTenantProject,
filteredDatabaseList,
- labelList,
- selectableLabelList,
+ excludedKeyList,
accessControlPolicyList,
};
},
diff --git a/frontend/src/components/ProvideDashboardContext.vue b/frontend/src/components/ProvideDashboardContext.vue
index e546c33bf0..2b34ba6757 100644
--- a/frontend/src/components/ProvideDashboardContext.vue
+++ b/frontend/src/components/ProvideDashboardContext.vue
@@ -10,7 +10,6 @@ import {
useSettingStore,
useUIStateStore,
useProjectStore,
- useLabelStore,
useDebugStore,
} from "@/store";
import { defineComponent } from "vue";
@@ -31,7 +30,6 @@ export default defineComponent({
useEnvironmentStore().fetchEnvironmentList(),
// The default project hosts databases not explicitly assigned to other users project.
useProjectStore().fetchProjectById(DEFAULT_PROJECT_ID),
- useLabelStore().fetchLabelList(),
useUIStateStore().restoreState(),
useDebugStore().fetchDebug(),
]);
diff --git a/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vue b/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vue
index f18281abc3..a740a3a363 100644
--- a/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vue
+++ b/frontend/src/components/TenantDatabaseTable/DatabaseMatrix.vue
@@ -50,7 +50,6 @@
v-for="db in dbList"
:key="db.id"
:database="db"
- :label-list="labelList"
/>
<span v-if="dbList.length === 0">-</span>
</div>
@@ -64,13 +63,17 @@ import { computed, defineComponent, PropType, ref, watchEffect } from "vue";
import {
Database,
Environment,
- Label,
LabelKeyType,
LabelValueType,
} from "../../types";
import DatabaseMatrixItem from "./DatabaseMatrixItem.vue";
-import { groupBy } from "lodash-es";
-import { hidePrefix, getLabelValue } from "../../utils";
+import { groupBy, last } from "lodash-es";
+import {
+ hidePrefix,
+ getLabelValue,
+ getLabelValuesFromDatabaseList,
+ LABEL_VALUE_EMPTY,
+} from "../../utils";
type DatabaseMatrix = {
labelValue: LabelValueType;
@@ -101,10 +104,6 @@ export default defineComponent({
type: Array as PropType<Environment[]>,
required: true,
},
- labelList: {
- type: Array as PropType<Label[]>,
- required: true,
- },
xAxisLabel: {
type: String as PropType<LabelKeyType>,
required: true,
@@ -129,21 +128,23 @@ export default defineComponent({
return [];
}
- // order based on label.valueList
- // plus one more "<empty value>"
- const label = props.labelList.find((label) => label.key === key);
- if (!label) return [];
- return [...label.valueList, ""];
+ return getLabelValuesFromDatabaseList(
+ key,
+ props.databaseList,
+ true /* withEmptyValue */
+ );
});
// pre-filtered x-axis values
const xAxisValueList = computed(() => {
- // order based on label.valueList
- // plus one more "<empty value>"
+ // Select all distinct database label values of {{key}}
const key = props.xAxisLabel;
- const label = props.labelList.find((label) => label.key === key);
- if (!label) return [];
- return [...label.valueList, ""];
+
+ return getLabelValuesFromDatabaseList(
+ key,
+ props.databaseList,
+ true /* withEmptyValue */
+ );
});
// first, group databases by `yAxisLabel` into some rows
@@ -192,14 +193,12 @@ export default defineComponent({
// no such an environment named "Prod" or "Prod" has no databases.
watchEffect(() => {
filteredXAxisValueList.value = [...xAxisValueList.value];
- // if every row's "<empty value>" has no databases
- // we should hide the "<empty value>" col
- const shouldClipLastCol = matrixList.value.every(
- (row) =>
- row.databaseMatrix.length > 0 &&
- row.databaseMatrix[row.databaseMatrix.length - 1].length === 0
+
+ // Hide the "<empty value>" COL if every row of this col has no databases.
+ const hideLastCol = shouldHideEmptyValueCol(
+ filteredXAxisValueList.value,
+ matrixList.value
);
- if (shouldClipLastCol) filteredXAxisValueList.value.pop();
filteredMatrixList.value = [];
for (let i = 0; i < matrixList.value.length; i++) {
@@ -207,19 +206,14 @@ export default defineComponent({
labelValue: matrixList.value[i].labelValue,
databaseMatrix: [...matrixList.value[i].databaseMatrix],
};
- if (shouldClipLastCol) {
+ if (hideLastCol) {
row.databaseMatrix.pop();
}
filteredMatrixList.value.push(row);
}
- // if every col of "<empty value>" row is empty
- // we should hide the "<empty value>" row
- if (
- filteredMatrixList.value.length > 0 &&
- filteredMatrixList.value[
- filteredMatrixList.value.length - 1
- ].databaseMatrix.every((item) => item.length === 0)
- ) {
+
+ // Hide the "<empty value>" ROW if every col of this row has no databases.
+ if (shouldHideEmptyValueRow(filteredMatrixList.value)) {
filteredMatrixList.value.pop();
}
});
@@ -233,4 +227,35 @@ export default defineComponent({
};
},
});
+
+const shouldHideEmptyValueCol = (
+ valueList: string[],
+ matrixList: DatabaseMatrix[]
+): boolean => {
+ const lastValue = valueList[valueList.length - 1];
+ if (lastValue === LABEL_VALUE_EMPTY) {
+ // if every row's "<empty value>" has no databases
+ // we should hide the "<empty value>" col
+ if (
+ matrixList.every((row) => {
+ const lastCol = last(row.databaseMatrix) ?? [];
+ return lastCol.length === 0;
+ })
+ ) {
+ return true;
+ }
+ }
+ return false;
+};
+
+const shouldHideEmptyValueRow = (matrixList: DatabaseMatrix[]) => {
+ const lastRow = last(matrixList);
+ if (
+ lastRow?.labelValue === LABEL_VALUE_EMPTY &&
+ lastRow?.databaseMatrix.every((databases) => databases.length === 0)
+ ) {
+ return true;
+ }
+ return false;
+};
</script>
diff --git a/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vue b/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vue
index f625c9fa44..bac529c837 100644
--- a/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vue
+++ b/frontend/src/components/TenantDatabaseTable/DatabaseMatrixItem.vue
@@ -81,7 +81,7 @@
<script lang="ts">
import { computed, defineComponent, PropType } from "vue";
-import { Database, Label } from "../../types";
+import { Database } from "../../types";
import { databaseSlug, isReservedDatabaseLabel, hidePrefix } from "../../utils";
import InstanceEngineIcon from "../InstanceEngineIcon.vue";
import { NPopover } from "naive-ui";
@@ -97,16 +97,12 @@ export default defineComponent({
type: Object as PropType<Database>,
required: true,
},
- labelList: {
- type: Array as PropType<Label[]>,
- default: () => [],
- },
},
setup(props) {
const displayLabelList = computed(() => {
- return props.database.labels.filter((dbLabel) => {
- if (!dbLabel.value) return false;
- if (isReservedDatabaseLabel(dbLabel, props.labelList)) return false;
+ return props.database.labels.filter((label) => {
+ if (!label.value) return false;
+ if (isReservedDatabaseLabel(label)) return false;
return true;
});
});
diff --git a/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vue b/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vue
index 7c2e885532..f130c8b87e 100644
--- a/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vue
+++ b/frontend/src/components/TenantDatabaseTable/DeployDatabaseTable.vue
@@ -75,7 +75,6 @@
v-for="db in dbList"
:key="db.id"
:database="db"
- :label-list="labelList"
/>
<span v-if="dbList.length === 0">-</span>
</div>
@@ -87,7 +86,6 @@
v-for="db in matrix.rest"
:key="db.id"
:database="db"
- :label-list="labelList"
/>
<span v-if="matrix.rest.length === 0">-</span>
</div>
@@ -104,13 +102,13 @@ import type {
Database,
DeploymentConfig,
Environment,
- Label,
LabelKeyType,
} from "../../types";
import {
hidePrefix,
getLabelValue,
getPipelineFromDeploymentSchedule,
+ getLabelValuesFromDatabaseList,
} from "../../utils";
import { NPopover } from "naive-ui";
import { DeploymentStage } from "../DeploymentConfigTool";
@@ -119,7 +117,6 @@ const props = withDefaults(
defineProps<{
databaseList: Database[];
label: LabelKeyType;
- labelList: Label[];
environmentList: Environment[];
deployment: DeploymentConfig;
bordered?: boolean;
@@ -132,12 +129,11 @@ const props = withDefaults(
);
const yAxisValueList = computed(() => {
- // order based on label.valueList
- // plus one more "<empty value>"
- const key = props.label;
- const label = props.labelList.find((label) => label.key === key);
- if (!label) return [];
- return [...label.valueList, ""];
+ return getLabelValuesFromDatabaseList(
+ props.label,
+ props.databaseList,
+ true /* withEmptyValue */
+ );
});
const xAxisValueList = computed(() => {
diff --git a/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vue b/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vue
index e42d63c75f..dcf6e2c198 100644
--- a/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vue
+++ b/frontend/src/components/TenantDatabaseTable/TenantDatabaseTable.vue
@@ -6,7 +6,6 @@
:name="dbGroup.name"
:database-list="dbGroup.databaseList"
:environment-list="environmentList"
- :label-list="labelList"
:x-axis-label="xAxisLabel"
:y-axis-label="yAxisLabel"
/>
@@ -15,7 +14,7 @@
<script lang="ts">
import { computed, defineComponent, PropType, watchEffect } from "vue";
-import { Database, Label, Project, LabelKeyType } from "../../types";
+import { Database, Project, LabelKeyType } from "../../types";
import { groupBy } from "lodash-es";
import DatabaseMatrix from "./DatabaseMatrix.vue";
import { parseDatabaseNameByTemplate } from "../../utils";
@@ -40,10 +39,6 @@ export default defineComponent({
default: "ALL",
type: String as PropType<Mode>,
},
- labelList: {
- type: Array as PropType<Label[]>,
- required: true,
- },
databaseList: {
type: Object as PropType<Database[]>,
required: true,
@@ -73,16 +68,12 @@ export default defineComponent({
if (props.project.dbNameTemplate === "") {
return [{ name: "", databaseList: props.databaseList }];
}
- if (props.project.dbNameTemplate) {
- if (props.labelList.length === 0) return [];
- }
const dict = groupBy(props.databaseList, (db) => {
if (props.project.dbNameTemplate) {
return parseDatabaseNameByTemplate(
db.name,
- props.project.dbNameTemplate,
- props.labelList
+ props.project.dbNameTemplate
);
} else {
return db.name;
diff --git a/frontend/src/components/TenantDatabaseTable/YAxisRadioGroup.vue b/frontend/src/components/TenantDatabaseTable/YAxisRadioGroup.vue
index 39f749af7e..f8f09a5464 100644
--- a/frontend/src/components/TenantDatabaseTable/YAxisRadioGroup.vue
+++ b/frontend/src/components/TenantDatabaseTable/YAxisRadioGroup.vue
@@ -1,36 +1,57 @@
<template>
- <div v-if="label" class="flex items-center space-x-2">
+ <div v-if="visible" class="flex items-center space-x-2">
<slot name="title">
<span class="textlabel mr-1">Group by</span>
</slot>
<select class="btn-select py-[0.3rem]" :value="label" @change="onChange">
<option
- v-for="lbl in labelList"
- :key="lbl.key"
- :value="lbl.key"
+ v-for="key in labelKeyList"
+ :key="key"
+ :value="key"
class="capitalize"
>
- {{ capitalize(hidePrefix(lbl.key)) }}
+ {{ capitalize(hidePrefix(key)) }}
</option>
</select>
</div>
</template>
<script lang="ts" setup>
+import { computed, withDefaults } from "vue";
import { capitalize } from "lodash-es";
-import { Label, LabelKeyType } from "../../types";
-import { hidePrefix } from "../../utils";
+import { LabelKeyType } from "../../types";
+import {
+ hidePrefix,
+ PRESET_LABEL_KEYS,
+ RESERVED_LABEL_KEYS,
+} from "../../utils";
-defineProps<{
- label: LabelKeyType;
- labelList: Label[];
-}>();
+const props = withDefaults(
+ defineProps<{
+ label: LabelKeyType;
+ excludedKeyList?: LabelKeyType[];
+ }>(),
+ {
+ excludedKeyList: () => [],
+ }
+);
+
+const LABEL_KEY_LIST = [...RESERVED_LABEL_KEYS, ...PRESET_LABEL_KEYS];
const emit = defineEmits<{
(event: "update:label", label: LabelKeyType): void;
}>();
+const labelKeyList = computed(() => {
+ return LABEL_KEY_LIST.filter((key) => !props.excludedKeyList.includes(key));
+});
+
+const visible = computed(() => {
+ if (!props.label) return false;
+ return labelKeyList.value.includes(props.label);
+});
+
const onChange = (e: Event) => {
const target = e.target as HTMLSelectElement;
emit("update:label", target.value);
diff --git a/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue b/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue
index 96af45f65b..efed7e63b6 100644
--- a/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue
+++ b/frontend/src/components/TransferDatabaseForm/SelectDatabaseLabel.vue
@@ -16,31 +16,25 @@
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">
+ <div v-for="label in PRESET_LABEL_KEYS" :key="label" class="w-64">
<label class="textlabel capitalize">
- {{ hidePrefix(label.key) }}
- <span v-if="isRequiredLabel(label.key)" style="color: red">*</span>
+ {{ hidePrefix(label) }}
+ <span v-if="isRequiredLabel(label)" 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>
+ <BBTextField
+ :disabled="isParsedLabel(label)"
+ :value="getLabelValue(label)"
+ :placeholder="getLabelPlaceholder(label)"
+ class="textfield"
+ @input="
+ setLabelValue(label, ($event.target as HTMLInputElement).value)
+ "
+ />
</div>
- <div v-if="isParsedLabel(label.key)" class="mt-2 textinfolabel">
+ <div v-if="isParsedLabel(label)" class="mt-2 textinfolabel">
<i18n-t keypath="label.parsed-from-template">
<template #name>{{ database.name }}</template>
<template #template>
@@ -70,7 +64,6 @@ import { useI18n } from "vue-i18n";
import type {
Database,
DatabaseLabel,
- Label,
LabelKeyType,
LabelValueType,
Project,
@@ -78,11 +71,12 @@ import type {
} from "@/types";
import {
buildDatabaseNameRegExpByTemplate,
- isReservedLabel,
- parseLabelListInTemplate,
hidePrefix,
+ parseLabelListInTemplate,
+ PRESET_LABEL_KEYS,
+ PRESET_LABEL_KEY_PLACEHOLDERS,
} from "@/utils";
-import { useLabelList, useProjectStore } from "@/store";
+import { useProjectStore } from "@/store";
const props = defineProps<{
database: Database;
@@ -105,27 +99,18 @@ const targetProject = computed(() => {
return projectStore.getProjectById(props.targetProjectId) as Project;
});
-const labelList = useLabelList();
-
-const availableLabelList = computed(() => {
- return labelList.value.filter((label) => !isReservedLabel(label));
-});
-
const prepare = () => {
projectStore.fetchProjectById(props.targetProjectId);
};
watchEffect(prepare);
-const requiredLabelList = computed((): Label[] => {
+const requiredLabelList = computed((): string[] => {
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
- );
+ return parseLabelListInTemplate(project.dbNameTemplate);
});
const dbNameMatchesTemplate = computed((): boolean => {
@@ -134,15 +119,12 @@ const dbNameMatchesTemplate = computed((): boolean => {
// no restrictions, because no template
return true;
}
- const regex = buildDatabaseNameRegExpByTemplate(
- project.dbNameTemplate,
- availableLabelList.value
- );
+ const regex = buildDatabaseNameRegExpByTemplate(project.dbNameTemplate);
return regex.test(props.database.name);
});
const isRequiredLabel = (key: LabelKeyType): boolean => {
- return requiredLabelList.value.some((label) => label.key === key);
+ return requiredLabelList.value.includes(key);
};
const isParsedLabel = (key: LabelKeyType): boolean => {
@@ -153,21 +135,16 @@ const labelListParsedFromTemplate = computed((): DatabaseLabel[] => {
if (!dbNameMatchesTemplate.value) return [];
const regex = buildDatabaseNameRegExpByTemplate(
- targetProject.value.dbNameTemplate,
- availableLabelList.value
+ targetProject.value.dbNameTemplate
);
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,
- });
+ PRESET_LABEL_KEY_PLACEHOLDERS.forEach(([placeholder, key]) => {
+ const value = match.groups?.[placeholder];
+ if (value) {
+ parsedLabelList.push({ key, value });
}
});
@@ -184,18 +161,18 @@ const allowNext = computed(() => {
if (!dbNameMatchesTemplate.value) return false;
// every required label must be filled
- return requiredLabelList.value.every((label) => {
- return !!getLabelValue(label.key);
+ return requiredLabelList.value.every((key) => {
+ return !!getLabelValue(key);
});
});
const getLabelPlaceholder = (key: LabelKeyType): string => {
- // provide "Select Tenant" if Tenant is optional
- // provide "Select {{TENANT}}" if Tenant is required in the template
+ // provide "Input Tenant" if Tenant is optional
+ // provide "Input {{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 });
+ return t("create-db.input-label-value", { key });
};
const getLabelValue = (key: LabelKeyType): LabelValueType | undefined => {
@@ -204,16 +181,6 @@ const getLabelValue = (key: LabelKeyType): LabelValueType | undefined => {
);
};
-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) {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 12b3168ecb..dae97b9bbe 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -609,7 +609,7 @@
"reserved-db-error": "{databaseName} is a reserved name",
"generated-database-name": "Generated database name",
"db-name-generated-by-template": "Generated by template \"{template}\"",
- "select-label-value": "Select {key}"
+ "input-label-value": "Input {key}"
},
"db": {
"encoding": "Encoding",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index b446808705..f02591fdc0 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -609,7 +609,7 @@
"reserved-db-error": "{databaseName} 是一个预留名称",
"generated-database-name": "生成的数据库名称",
"db-name-generated-by-template": "依据模板 \"{template}\" 生成",
- "select-label-value": "选择 {key}"
+ "input-label-value": "输入 {key}"
},
"db": {
"encoding": "字符编码",
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 5e1eb15dfc..655c770e35 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -307,13 +307,6 @@ const routes: Array<RouteRecordRaw> = [
component: () => import("../views/SettingWorkspaceGeneral.vue"),
props: true,
},
- {
- path: "label",
- name: "setting.workspace.label",
- meta: { title: () => t("settings.sidebar.labels") },
- component: () => import("../views/SettingWorkspaceLabel.vue"),
- props: true,
- },
{
path: "agent",
name: "setting.workspace.agent",
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index 07daec84a3..a3ce7d1a4f 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -16,7 +16,6 @@ export * from "./issue";
export * from "./issueSubscriber";
export * from "./inbox";
export * from "./instance";
-export * from "./label";
export * from "./member";
export * from "./notification";
export * from "./oauth";
diff --git a/frontend/src/store/modules/label.ts b/frontend/src/store/modules/label.ts
deleted file mode 100644
index b83c4bd243..0000000000
--- a/frontend/src/store/modules/label.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { defineStore, storeToRefs } from "pinia";
-import axios from "axios";
-import {
- Label,
- ResourceObject,
- LabelState,
- LabelId,
- LabelPatch,
- LabelValueType,
-} from "@/types";
-
-function convert(label: ResourceObject): Label {
- const valueList = (label.attributes.valueList || []) as LabelValueType[];
- return {
- ...(label.attributes as Omit<
- Label,
- "valueList" | "id" | "creator" | "updater"
- >),
- valueList,
- id: parseInt(label.id, 10),
- };
-}
-
-export const useLabelStore = defineStore("label", {
- state: (): LabelState => ({
- labelList: [],
- }),
- actions: {
- setLabelList(labelList: Label[]) {
- this.labelList = labelList;
- },
-
- replaceLabelInList(updatedLabel: Label) {
- const i = this.labelList.findIndex(
- (item: Label) => item.id == updatedLabel.id
- );
- if (i != -1) {
- this.labelList[i] = updatedLabel;
- }
- },
-
- async fetchLabelList() {
- const data = (await axios.get(`/api/label`)).data;
-
- const labelList: Label[] = data.data.map((label: ResourceObject) => {
- return convert(label);
- });
-
- this.setLabelList(labelList);
- return labelList;
- },
-
- async patchLabel({
- id,
- labelPatch,
- }: {
- id: LabelId;
- labelPatch: LabelPatch;
- }) {
- const data = (
- await axios.patch(`/api/label/${id}`, {
- data: {
- type: "labelPatch",
- attributes: labelPatch,
- },
- })
- ).data;
- const updatedLabel = convert(data.data);
-
- this.replaceLabelInList(updatedLabel);
-
- return updatedLabel;
- },
- },
-});
-
-export const useLabelList = () => {
- const store = useLabelStore();
- return storeToRefs(store).labelList;
-};
diff --git a/frontend/src/utils/deployment.ts b/frontend/src/utils/deployment.ts
index 35f9a66641..3df7ecd00d 100644
--- a/frontend/src/utils/deployment.ts
+++ b/frontend/src/utils/deployment.ts
@@ -1,6 +1,5 @@
-import { DeploymentConfig, DeploymentSpec, Label } from "../types";
-import escapeStringRegexp from "escape-string-regexp";
-import { hidePrefix } from "./label";
+import type { DeploymentConfig, DeploymentSpec } from "@/types";
+import { PRESET_DB_NAME_TEMPLATE_PLACEHOLDERS } from "./label";
export const validateDeploymentConfig = (
config: DeploymentConfig
@@ -49,46 +48,28 @@ export const validateDeploymentSpec = (
return undefined;
};
-export const parseDatabaseNameByTemplate = (
- name: string,
- template: string,
- labelList: Label[]
-) => {
- const regex = buildDatabaseNameRegExpByTemplate(template, labelList);
+export const parseDatabaseNameByTemplate = (name: string, template: string) => {
+ const regex = buildDatabaseNameRegExpByTemplate(template);
const match = name.match(regex);
// fallback to name it self when failed
- return match?.groups?.name || name;
+ return match?.groups?.DB_NAME || name;
};
-export const buildDatabaseNameRegExpByTemplate = (
- template: string,
- labelList: Label[]
-): RegExp => {
- let regexpString = template.replace("{{DB_NAME}}", "(?<name>.+?)");
+export const buildDatabaseNameRegExpByTemplate = (template: string): RegExp => {
+ let regexpString = template;
- const fixed = template.split(/{{[^{}]+}}/).filter((template) => template);
- for (const s of fixed) {
- regexpString = regexpString.replace(s, s.replace(/\W/g, "\\$&"));
- }
/*
Rewrite the placeholder-based template to a big RegExp
- e.g. template = "{{DB_NAME}}_{{TENANT}}"
- bb.tenant has values (bytebase, tenant1, tenant2)
- here regex will be /^(?<name>.+?)_(bytebase|tenant1|tenant2)$/
+ e.g. template = "{{DB_NAME}}__{{TENANT}}"
+ here regex will be /^(?<DB_NAME>.+?)__(?<TENANT>.+?)$/
*/
- labelList.forEach((label) => {
- const { key, valueList } = label;
- const placeholder = `{{${hidePrefix(key).toUpperCase()}}}`;
- // replace special chars in values
- const escapedValueList = valueList.map((value) =>
- escapeStringRegexp(value)
- );
- // 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);
+ PRESET_DB_NAME_TEMPLATE_PLACEHOLDERS.forEach((placeholder) => {
+ const pattern = `{{${placeholder}}}`;
+ const groupRegExp = `(?<${placeholder}>.+?)`;
+ regexpString = regexpString.replace(pattern, groupRegExp);
});
- const regex = new RegExp(`^${regexpString}$`);
- return regex;
+
+ const regexp = new RegExp(`^${regexpString}$`);
+ return regexp;
};
diff --git a/frontend/src/utils/label.ts b/frontend/src/utils/label.ts
index 640e6e9210..b0ad8b677b 100644
--- a/frontend/src/utils/label.ts
+++ b/frontend/src/utils/label.ts
@@ -1,4 +1,5 @@
-import { countBy, groupBy, uniqBy } from "lodash-es";
+import { useEnvironmentStore } from "@/store";
+import { countBy, groupBy, uniq, uniqBy } from "lodash-es";
import {
Database,
DatabaseLabel,
@@ -10,21 +11,31 @@ import {
LabelValueType,
} from "../types";
-// reserved labels (e.g. bb.environment) have zero ID and their values are immutable.
-// see api/label.go for more details
-export const RESERVED_LABEL_ID = 0;
+export const MAX_LABEL_VALUE_LENGTH = 63;
+
+export const RESERVED_LABEL_KEYS = ["bb.environment"];
+
+export const PRESET_LABEL_KEYS = ["bb.location", "bb.tenant"];
+
+export const PRESET_DB_NAME_TEMPLATE_PLACEHOLDERS = [
+ "DB_NAME",
+ "LOCATION",
+ "TENANT",
+];
+
+export const PRESET_LABEL_KEY_PLACEHOLDERS = [
+ ["LOCATION", "bb.location"],
+ ["TENANT", "bb.tenant"],
+];
+
+export const LABEL_VALUE_EMPTY = "";
export const isReservedLabel = (label: Label): boolean => {
- return label.id === RESERVED_LABEL_ID;
+ return RESERVED_LABEL_KEYS.includes(label.key);
};
-export const isReservedDatabaseLabel = (
- dbLabel: DatabaseLabel,
- labelList: Label[]
-): boolean => {
- const label = labelList.find((label) => label.key === dbLabel.key);
- if (!label) return false;
- return label.id === RESERVED_LABEL_ID;
+export const isReservedDatabaseLabel = (label: DatabaseLabel): boolean => {
+ return RESERVED_LABEL_KEYS.includes(label.key);
};
export const hidePrefix = (key: LabelKeyType): LabelKeyType => {
@@ -36,14 +47,14 @@ export const getLabelValue = (
key: LabelKeyType
): LabelValueType => {
const label = db.labels.find((target) => target.key === key);
- if (!label) return "";
+ if (!label) return LABEL_VALUE_EMPTY;
return label.value;
};
export const groupingDatabaseListByLabelKey = (
databaseList: Database[],
key: LabelKeyType,
- emptyValue: LabelValueType = ""
+ emptyValue: LabelValueType = LABEL_VALUE_EMPTY
): Array<{ labelValue: LabelValueType; databaseList: Database[] }> => {
const dict = groupBy(databaseList, (db) => {
const label = db.labels.find((target) => target.key === key);
@@ -80,16 +91,14 @@ export const validateLabelsWithTemplate = (
};
export const findDefaultGroupByLabel = (
- labelList: Label[],
- databaseList: Database[]
-): string | undefined => {
- const availableKeys = labelList.map((label) => label.key);
-
+ databaseList: Database[],
+ excludedKeyList: LabelKeyType[] = []
+): string => {
// concat all databases' keys into one array
const databaseLabelKeys = databaseList.flatMap((db) =>
db.labels
.map((label) => label.key)
- .filter((key) => availableKeys.includes(key))
+ .filter((key) => !excludedKeyList.includes(key))
);
if (databaseLabelKeys.length > 0) {
// counting up the keys' frequency
@@ -101,10 +110,9 @@ export const findDefaultGroupByLabel = (
// return the most frequent used key
countsList.sort((a, b) => b.count - a.count);
return countsList[0].key;
- } else {
- // just use the first label key
- return availableKeys[0];
}
+ // Fallback to bb.environment if all databases have no labels and values.
+ return "bb.environment";
};
export const filterDatabaseListByLabelSelector = (
@@ -174,16 +182,13 @@ const checkLabelExists = (
return db.labels.some((label) => label.key === rule.key);
};
-export const parseLabelListInTemplate = (
- template: string,
- availableLabelList: Label[]
-): Label[] => {
- const labelList: Label[] = [];
-
- availableLabelList.forEach((label) => {
- const placeholder = `{{${hidePrefix(label.key).toUpperCase()}}}`;
- if (template.includes(placeholder)) {
- labelList.push(label);
+export const parseLabelListInTemplate = (template: string): string[] => {
+ const labelList: string[] = [];
+
+ PRESET_LABEL_KEY_PLACEHOLDERS.forEach(([placeholder, labelKey]) => {
+ const pattern = `{{${placeholder}}}`;
+ if (template.includes(pattern)) {
+ labelList.push(labelKey);
}
});
@@ -212,3 +217,27 @@ export const buildDatabaseNameByTemplateAndLabelList = (
return databaseName;
};
+
+export const getLabelValuesFromDatabaseList = (
+ key: string,
+ databaseList: Database[],
+ withEmptyValue = false
+): string[] => {
+ if (key === "bb.environment") {
+ const environmentList = useEnvironmentStore().getEnvironmentList();
+ return environmentList.map((env) => env.name);
+ }
+
+ const labelList = databaseList.flatMap((db) =>
+ db.labels.filter((label) => label.key === key)
+ );
+ // Select all distinct database label values of {{key}}
+ const distinctValueList = uniq(labelList.map((label) => label.value));
+
+ if (withEmptyValue) {
+ // plus one more "<empty value>" if needed
+ distinctValueList.push(LABEL_VALUE_EMPTY);
+ }
+
+ return distinctValueList;
+};
diff --git a/frontend/src/views/DatabaseDetail.vue b/frontend/src/views/DatabaseDetail.vue
index 819e921a84..cbe24dce55 100644
--- a/frontend/src/views/DatabaseDetail.vue
+++ b/frontend/src/views/DatabaseDetail.vue
@@ -115,7 +115,7 @@
>
<template #label="{ label }">
<span class="textlabel capitalize">
- {{ hidePrefix(label.key) }}&nbsp;-&nbsp;
+ {{ hidePrefix(label) }}&nbsp;-&nbsp;
</span>
</template>
</DatabaseLabelProps>
diff --git a/frontend/src/views/SettingSidebar.vue b/frontend/src/views/SettingSidebar.vue
index 447f72f6f7..905f64e6ed 100644
--- a/frontend/src/views/SettingSidebar.vue
+++ b/frontend/src/views/SettingSidebar.vue
@@ -58,15 +58,6 @@
class="outline-item group w-full flex items-center pl-11 pr-2 py-2"
>{{ $t("settings.sidebar.members") }}</router-link
>
- <!--
- Label Management is visible to all
- but only editable to Owners and DBAs
- -->
- <router-link
- to="/setting/label"
- class="outline-item group w-full flex items-center pl-11 pr-2 py-2"
- >{{ $t("settings.sidebar.labels") }}</router-link
- >
<router-link
v-if="showSensitiveDataItem"
to="/setting/sensitive-data"
diff --git a/frontend/src/views/SettingWorkspaceLabel.vue b/frontend/src/views/SettingWorkspaceLabel.vue
deleted file mode 100644
index b638290d34..0000000000
--- a/frontend/src/views/SettingWorkspaceLabel.vue
+++ /dev/null
@@ -1,161 +0,0 @@
-<template>
- <div class="space-y-4">
- <div class="textinfolabel mt-2">
- <i18n-t keypath="label.setting.description">
- <template #link>
- <a
- class="normal-link inline-flex items-center"
- href="https://bytebase.com/docs/tenant-database-management#labels?source=console"
- target="__BLANK"
- >
- {{ $t("common.learn-more") }}
- <heroicons-outline:external-link class="w-4 h-4 ml-1" />
- </a>
- </template>
- </i18n-t>
- </div>
- <div>
- <BBTable
- class="mt-2"
- :column-list="columnList"
- :data-source="labelList"
- :show-header="true"
- :row-clickable="false"
- >
- <template #body="{ rowData: label }">
- <BBTableCell :left-padding="4" class="w-36 table-cell capitalize">
- <!-- will not capitalize label.key here due to it may be editable in the future -->
- <!-- capitalizing editable things may be confusing -->
- <!-- capitalizing only bb.prefixed things makes it inconsistent with others -->
- <!-- so just capitalize none of them -->
- {{ hidePrefix(label.key) }}
- </BBTableCell>
- <BBTableCell class="whitespace-nowrap">
- <div class="tags">
- <div v-for="(value, j) in label.valueList" :key="j" class="tag">
- <span>{{ value }}</span>
- <span
- v-if="allowRemove"
- class="remove"
- @click="removeValue(label, value)"
- >
- <heroicons-solid:x class="w-3 h-3" />
- </span>
- </div>
- <template v-if="allowEdit">
- <router-link
- v-if="label.key === 'bb.environment'"
- :to="{ name: 'workspace.environment' }"
- class="h-6 px-1 py-1 inline-flex items-center rounded bg-white border border-control-border hover:bg-control-bg-hover cursor-pointer"
- >
- {{ $t("common.manage") }}
- </router-link>
- <AddLabelValue
- v-else
- :label="label"
- @add="(v) => addValue(label, v)"
- />
- </template>
- </div>
- </BBTableCell>
- </template>
- </BBTable>
- </div>
- </div>
-</template>
-
-<script lang="ts">
-import { computed, defineComponent } from "vue";
-import { useI18n } from "vue-i18n";
-import { storeToRefs } from "pinia";
-import { hasWorkspacePermission, hidePrefix } from "@/utils";
-import type { Label, LabelPatch } from "@/types";
-import type { BBTableColumn } from "@/bbkit/types";
-import { BBTable, BBTableCell } from "@/bbkit";
-import AddLabelValue from "@/components/AddLabelValue.vue";
-import { useCurrentUser, useLabelStore } from "@/store";
-
-export default defineComponent({
- name: "SettingWorkspaceLabels",
- components: {
- BBTable,
- BBTableCell,
- AddLabelValue,
- },
- setup() {
- const { t } = useI18n();
- const labelStore = useLabelStore();
- const currentUser = useCurrentUser();
-
- const { labelList } = storeToRefs(labelStore);
-
- const allowEdit = computed(() => {
- return hasWorkspacePermission(
- "bb.permission.workspace.manage-label",
- currentUser.value.role
- );
- });
-
- const allowRemove = computed(() => {
- // no, we don't allow to remove values now
- return false;
- // return allowEdit.value;
- });
-
- const addValue = (label: Label, value: string) => {
- const labelPatch: LabelPatch = {
- valueList: [...label.valueList, value],
- };
- labelStore.patchLabel({
- id: label.id,
- labelPatch,
- });
- };
-
- const removeValue = (label: Label, value: string) => {
- const valueList = [...label.valueList];
- const index = valueList.indexOf(value);
- if (index < 0) return;
- valueList.splice(index, 1);
- const labelPatch: LabelPatch = {
- valueList,
- };
- labelStore.patchLabel({
- id: label.id,
- labelPatch,
- });
- };
-
- const columnList = computed((): BBTableColumn[] => [
- {
- title: t("setting.label.key"),
- },
- {
- title: t("setting.label.values"),
- },
- ]);
-
- return {
- columnList,
- labelList,
- hidePrefix,
- allowEdit,
- allowRemove,
- addValue,
- removeValue,
- };
- },
-});
-</script>
-
-<style scoped lang="postcss">
-.tags {
- @apply flex flex-wrap gap-2;
-}
-.tag {
- @apply h-6 bg-blue-100 border-blue-300 border px-2 rounded whitespace-nowrap inline-flex items-center;
-}
-.tag > .remove {
- @apply ml-1 -mr-1 p-px cursor-pointer hover:bg-blue-300 rounded-sm;
-}
-</style>