Skip to content

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

chore: batch edit database labels (#8657)

ecmadaof87d817463da
diff --git a/frontend/src/components/ColumnTable.vue b/frontend/src/components/ColumnTable.vue
index 7f546eb50b..bf253b799a 100644
--- a/frontend/src/components/ColumnTable.vue
+++ b/frontend/src/components/ColumnTable.vue
@@ -156,9 +156,10 @@
v-if="state.activeColumn"
:show="state.showLabelsDrawer"
:readonly="!hasEditLabelsPermission"
- :database="database"
- :column="state.activeColumn.name"
- :labels="getColumnConfig(state.activeColumn.name).labels"
+ :title="
+ $t('db.labels-for-resource', { resource: `'${state.activeColumn.name}'` })
+ "
+ :labels="[getColumnConfig(state.activeColumn.name).labels]"
@dismiss="state.showLabelsDrawer = false"
@apply="onLabelsApply($event)"
/>
@@ -312,13 +313,13 @@ const getColumnSemanticType = (columnName: string) => {
);
};
-const onLabelsApply = async (labels: { [key: string]: string }) => {
+const onLabelsApply = async (labelsList: { [key: string]: string }[]) => {
const column = state.activeColumn;
if (!column) {
return;
}
try {
- await updateColumnConfig(column.name, { labels });
+ await updateColumnConfig(column.name, { labels: labelsList[0] });
} finally {
state.showLabelsDrawer = false;
}
diff --git a/frontend/src/components/Label/LabelEditorRow.vue b/frontend/src/components/Label/LabelEditorRow.vue
index ccc4cbf57f..8b3a42f2b0 100644
--- a/frontend/src/components/Label/LabelEditorRow.vue
+++ b/frontend/src/components/Label/LabelEditorRow.vue
@@ -1,7 +1,7 @@
<template>
- <div class="contents text-sm">
+ <div class="contents text-sm space-x-2">
<div class="flex flex-col">
- <span class="text-xs font-medium"> Key {{ index + 1 }} </span>
+ <span class="text-xs font-medium mb-1"> Key {{ index + 1 }} </span>
<span v-if="readonly" class="leading-[34px]">
{{ kv.key }}
</span>
@@ -14,34 +14,36 @@
/>
</div>
<div class="flex flex-col">
- <span class="text-xs font-medium"> Value {{ index + 1 }} </span>
- <span v-if="readonly" class="leading-[34px]">
- <template v-if="kv.value">{{ kv.value }}</template>
- <span v-else class="text-control-placeholder">
- {{ $t("label.empty-label-value") }}
+ <span class="text-xs font-medium mb-1"> Value {{ index + 1 }} </span>
+ <div class="flex items-center space-x-2">
+ <span v-if="readonly" class="leading-[34px]">
+ <template v-if="kv.value">{{ kv.value }}</template>
+ <span v-else class="text-control-placeholder">
+ {{ $t("label.empty-label-value") }}
+ </span>
</span>
- </span>
- <NInput
- v-else
- :value="kv.value"
- :placeholder="$t('setting.label.value-placeholder')"
- :status="errors.value.length > 0 ? 'error' : undefined"
- @update:value="$emit('update-value', $event)"
- />
- </div>
- <div class="flex flex-row self-stretch items-center pt-4">
- <NButton
- quaternary
- size="small"
- style="--n-padding: 0 6px"
- :class="[readonly ? 'invisible' : 'visible']"
- @click="$emit('remove')"
- >
- <template #icon>
- <heroicons:trash />
- </template>
- </NButton>
+ <NInput
+ v-else
+ :value="kv.value"
+ :placeholder="$t('setting.label.value-placeholder')"
+ :status="errors.value.length > 0 ? 'error' : undefined"
+ @update:value="$emit('update-value', $event)"
+ />
+ <NButton
+ quaternary
+ size="small"
+ style="--n-padding: 0 6px"
+ :class="['ml-1', readonly ? 'invisible' : 'visible']"
+ @click="$emit('remove')"
+ >
+ <template #icon>
+ <heroicons:trash />
+ </template>
+ </NButton>
+ </div>
+ <div v-if="kv.message" class="textinfolabel">{{ kv.message }}</div>
</div>
+ <div />
</div>
<div v-if="combinedErrors.length > 0" class="text-xs text-error col-span-3">
<ErrorList :errors="combinedErrors" bullets="always" />
@@ -52,9 +54,10 @@
import { NButton, NInput } from "naive-ui";
import { computed } from "vue";
import ErrorList from "../misc/ErrorList.vue";
+import { Label } from "./types";
const props = defineProps<{
- kv: { key: string; value: string };
+ kv: Label;
index: number;
readonly: boolean;
errors: {
diff --git a/frontend/src/components/Label/LabelListEditor.vue b/frontend/src/components/Label/LabelListEditor.vue
index afada4005a..51732e16e0 100644
--- a/frontend/src/components/Label/LabelListEditor.vue
+++ b/frontend/src/components/Label/LabelListEditor.vue
@@ -35,17 +35,16 @@ import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { MAX_LABEL_VALUE_LENGTH, isVirtualLabelKey } from "@/utils";
import LabelEditorRow from "./LabelEditorRow.vue";
-
-export type KV = { key: string; value: string };
+import { Label } from "./types";
const props = defineProps<{
- kvList: KV[];
+ kvList: Label[];
readonly: boolean;
showErrors: boolean;
}>();
const emit = defineEmits<{
- (event: "update:kvList", kvList: KV[]): void;
+ (event: "update:kvList", kvList: Label[]): void;
}>();
const { t } = useI18n();
@@ -72,7 +71,9 @@ const errorList = computed(() => {
}
}
if (!value) {
- errors.value.push(t("label.error.value-necessary"));
+ if (!kv.allowEmpty) {
+ errors.value.push(t("label.error.value-necessary"));
+ }
} else if (value.length > MAX_LABEL_VALUE_LENGTH) {
errors.value.push(
t("label.error.max-value-length-exceeded", {
diff --git a/frontend/src/components/Label/types.ts b/frontend/src/components/Label/types.ts
new file mode 100644
index 0000000000..9b9e0e185d
--- /dev/null
+++ b/frontend/src/components/Label/types.ts
@@ -0,0 +1,6 @@
+export type Label = {
+ key: string;
+ value: string;
+ message?: string;
+ allowEmpty?: boolean;
+};
diff --git a/frontend/src/components/LabelEditorDrawer.vue b/frontend/src/components/LabelEditorDrawer.vue
index aa165f09fb..2cd894e3e2 100644
--- a/frontend/src/components/LabelEditorDrawer.vue
+++ b/frontend/src/components/LabelEditorDrawer.vue
@@ -1,12 +1,16 @@
<template>
<Drawer :show="show" @close="$emit('dismiss')">
- <DrawerContent :title="$t('db.labels-for-resource', { resource: column })">
+ <DrawerContent :title="title">
+ <BBAttention
+ class="mb-5"
+ :style="'WARN'"
+ :title="$t('database.mixed-label-values-warning')"
+ />
<LabelListEditor
ref="labelListEditorRef"
v-model:kv-list="state.kvList"
:readonly="readonly"
:show-errors="dirty"
- class="max-w-[30rem]"
/>
<template #footer>
<div class="w-full flex justify-between items-center">
@@ -18,7 +22,7 @@
v-if="!readonly"
:disabled="!allowSave"
type="primary"
- @click="$emit('apply', convertKVListToLabels(state.kvList))"
+ @click="$emit('apply', convertKVListToLabelsList())"
>
{{ $t("common.save") }}
</NButton>
@@ -30,21 +34,21 @@
</template>
<script lang="ts" setup>
-import { isEqual } from "lodash-es";
+import { isEqual, cloneDeep } from "lodash-es";
import { computed, reactive, watch, ref } from "vue";
-import LabelListEditor from "@/components/Label/LabelListEditor.vue";
+import { useI18n } from "vue-i18n";
+import { LabelListEditor } from "@/components/Label";
+import { Label } from "@/components/Label/types";
import { Drawer, DrawerContent } from "@/components/v2";
-import { type ComposedDatabase } from "@/types";
-import { convertKVListToLabels, convertLabelsToKVList } from "@/utils";
+import { convertKVListToLabels } from "@/utils";
const props = defineProps<{
show: boolean;
readonly: boolean;
- database: ComposedDatabase;
- column: string;
+ title: string;
labels: {
[key: string]: string;
- };
+ }[];
}>();
defineEmits<{
(event: "dismiss"): void;
@@ -52,25 +56,91 @@ defineEmits<{
event: "apply",
labels: {
[key: string]: string;
- }
+ }[]
): void;
}>();
type LocalState = {
- kvList: { key: string; value: string }[];
+ kvList: Label[];
};
+const { t } = useI18n();
const state = reactive<LocalState>({
kvList: [],
});
const labelListEditorRef = ref<InstanceType<typeof LabelListEditor>>();
-const convert = () => {
- return convertLabelsToKVList(props.labels, true /* sort */);
+const convertKVListToLabelsList = () => {
+ return props.labels.map((oldLabel) => {
+ const labels = convertKVListToLabels(state.kvList);
+ for (const label of state.kvList) {
+ if (!label.value) {
+ if (oldLabel[label.key]) {
+ labels[label.key] = oldLabel[label.key];
+ }
+ }
+ }
+ return labels;
+ });
+};
+
+const convertLabelsToKVList = () => {
+ interface TmpLabel {
+ [key: string]: {
+ value: string;
+ message?: string;
+ allowEmpty?: boolean;
+ };
+ }
+
+ let tmp: TmpLabel = {};
+ if (props.labels.length > 0) {
+ tmp = Object.entries(props.labels[0]).reduce((resp, [key, value]) => {
+ resp[key] = {
+ value,
+ };
+ return resp;
+ }, {} as TmpLabel);
+ }
+ for (let i = 1; i < props.labels.length; i++) {
+ const label = cloneDeep(props.labels[i]);
+ for (const key of Object.keys(tmp)) {
+ if (!label[key] || label[key] !== tmp[key].value) {
+ tmp[key] = {
+ message: t("database.mixed-values-for-label"),
+ value: "",
+ allowEmpty: true,
+ };
+ }
+ delete label[key];
+ }
+ for (const [key, value] of Object.entries(label)) {
+ if (!tmp[key]) {
+ tmp[key] = {
+ value,
+ };
+ } else if (tmp[key].value !== value) {
+ tmp[key] = {
+ message: t("database.mixed-values-for-label"),
+ value: "",
+ allowEmpty: true,
+ };
+ }
+ }
+ }
+
+ const list: Label[] = Object.entries(tmp).map(([key, obj]) => ({
+ key,
+ value: obj.value,
+ message: obj.message,
+ allowEmpty: obj.allowEmpty,
+ }));
+
+ return list;
};
const dirty = computed(() => {
- const original = convert();
+ const original = convertLabelsToKVList();
const local = state.kvList;
return !isEqual(original, local);
});
@@ -84,7 +154,7 @@ const allowSave = computed(() => {
watch(
() => props.labels,
() => {
- state.kvList = convert();
+ state.kvList = convertLabelsToKVList();
},
{
immediate: true,
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue
index b9f7518f3e..8acd88b154 100644
--- a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue
+++ b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseOperations.vue
@@ -59,6 +59,19 @@
@dismiss="state.showTransferOutDatabaseForm = false"
/>
</Drawer>
+
+ <LabelEditorDrawer
+ :show="state.showLabelEditorDrawer"
+ :readonly="false"
+ :title="
+ $t('db.labels-for-resource', {
+ resource: $t('database.n-databases', { n: databases.length }),
+ })
+ "
+ :labels="databases.map((db) => db.labels)"
+ @dismiss="state.showLabelEditorDrawer = false"
+ @apply="onLabelsApply($event)"
+ />
</template>
<script lang="ts" setup>
@@ -69,6 +82,7 @@ import PencilIcon from "~icons/heroicons-outline/pencil";
import PencilAltIcon from "~icons/heroicons-outline/pencil-alt";
import RefreshIcon from "~icons/heroicons-outline/refresh";
import SwitchHorizontalIcon from "~icons/heroicons-outline/switch-horizontal";
+import TagIcon from "~icons/heroicons-outline/tag";
import { Drawer } from "@/components/v2";
import {
useCurrentUserV1,
@@ -80,6 +94,7 @@ import {
pushNotification,
} from "@/store";
import { ComposedDatabase, DEFAULT_PROJECT_V1_NAME } from "@/types";
+import { Database } from "@/types/proto/v1/database_service";
import {
hasWorkspacePermissionV1,
hasPermissionInProjectV1,
@@ -101,6 +116,7 @@ interface LocalState {
loading: boolean;
showSchemaEditorModal: boolean;
showTransferOutDatabaseForm: boolean;
+ showLabelEditorDrawer: boolean;
}
const props = defineProps<{
@@ -115,6 +131,7 @@ const state = reactive<LocalState>({
loading: false,
showSchemaEditorModal: false,
showTransferOutDatabaseForm: false,
+ showLabelEditorDrawer: false,
});
const schemaEditorContext = ref<{
databaseIdList: string[];
@@ -196,6 +213,23 @@ const allowTransferProject = computed(() => {
);
});
+const allowEditLabels = computed(() => {
+ return props.databases.every((db) => {
+ const project = db.projectEntity;
+ return (
+ hasWorkspacePermissionV1(
+ "bb.permission.workspace.manage-label",
+ currentUserV1.value.userRole
+ ) ||
+ hasPermissionInProjectV1(
+ project.iamPolicy,
+ currentUserV1.value,
+ "bb.permission.project.manage-general"
+ )
+ );
+ });
+});
+
const selectedDatabaseUidList = computed(() => {
return props.databases.map((db) => db.uid);
});
@@ -309,6 +343,42 @@ const actions = computed((): DatabaseAction[] => {
});
}
}
+ if (allowEditLabels.value) {
+ resp.push({
+ icon: h(TagIcon),
+ text: t("database.edit-labels"),
+ disabled: false,
+ click: () => (state.showLabelEditorDrawer = true),
+ });
+ }
return resp;
});
+
+const onLabelsApply = async (labelsList: { [key: string]: string }[]) => {
+ if (labelsList.length !== props.databases.length) {
+ // This should never happen.
+ return;
+ }
+
+ await Promise.all(
+ props.databases.map(async (database, i) => {
+ const label = labelsList[i];
+ const patch: Database = {
+ ...Database.fromPartial(database),
+ labels: label,
+ };
+ await useDatabaseV1Store().updateDatabase({
+ database: patch,
+ updateMask: ["labels"],
+ });
+ })
+ );
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ state.showLabelEditorDrawer = false;
+};
</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 81265d43f6..cb7d749613 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1046,7 +1046,7 @@
"streams": "Streams",
"tasks": "Tasks",
"parent": "Parent",
- "labels-for-resource": "Labels for \"{resource}\"",
+ "labels-for-resource": "Labels for {resource}",
"last-successful-sync": "Last successful sync",
"sync-status": "Sync status",
"failed-to-sync-schema-for-database-database-value-name": "Failed to sync schema for database '{0}'.",
@@ -1328,6 +1328,9 @@
"transfer-project": "Transfer Project",
"edit-schema": "Edit Schema",
"edit-schema-in-vcs": "Edit Schema in VCS",
+ "edit-labels": "Edit Labels",
+ "mixed-values-for-label": "This selected label have mixed values",
+ "mixed-label-values-warning": "Some of the selected resources have mixed values for the same key",
"change-data": "Change Data",
"change-data-in-vcs": "Change Data in VCS",
"branch": "Branch",
@@ -1435,6 +1438,7 @@
"unassigned-databases": "Unassigned databases",
"restore-database": "Restore database",
"selected-n-databases": "{n} database selected | {n} databases selected",
+ "n-databases": "{n} database | {n} databases",
"select-databases-from-same-project": "Please select databases from the same project",
"sync-schema": {
"title": "Sync Schema",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 11795ccf08..add928fc98 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1045,7 +1045,7 @@
"streams": "Streams",
"tasks": "Tareas",
"parent": "Padre",
- "labels-for-resource": "Etiquetas para \"{resource}\"",
+ "labels-for-resource": "Etiquetas para {resource}",
"last-successful-sync": "Última sincronización exitosa",
"sync-status": "Estado de sincronización",
"failed-to-sync-schema-for-database-database-value-name": "Error al sincronizar el esquema para la base de datos '{0}'.",
@@ -1327,6 +1327,9 @@
"transfer-project": "Transferir proyecto",
"edit-schema": "Modificar esquema",
"edit-schema-in-vcs": "Modificar esquema en VCS",
+ "edit-labels": "Editar etiquetas",
+ "mixed-values-for-label": "Esta etiqueta seleccionada tiene valores mixtos.",
+ "mixed-label-values-warning": "Algunos de los recursos seleccionados tienen valores mixtos para la misma clave",
"change-data": "Cambiar datos",
"change-data-in-vcs": "Cambiar datos en VCS",
"branch": "Rama",
@@ -1434,6 +1437,7 @@
"unassigned-databases": "Bases de datos no asignadas",
"restore-database": "Restaurar base de datos",
"selected-n-databases": "{n} base de datos seleccionada | {n} bases de datos seleccionadas",
+ "n-databases": "{n} base de datos | {n} bases de datos",
"select-databases-from-same-project": "Por favor seleccione bases de datos del mismo proyecto",
"sync-schema": {
"title": "Sincronizar esquema",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 5884da639a..ea1ddc177f 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1043,7 +1043,7 @@
"streams": "Streams",
"tasks": "任务",
"parent": "母",
- "labels-for-resource": "\"{resource}\"的标签",
+ "labels-for-resource": "{resource}的标签",
"last-successful-sync": "上次成功同步于",
"sync-status": "同步状态",
"failed-to-sync-schema-for-database-database-value-name": "为数据库'{0}'同步 schema 失败。",
@@ -1324,6 +1324,9 @@
"transfer-project": "转移项目",
"edit-schema": "变更 Schema",
"edit-schema-in-vcs": "变更 Schema (VCS)",
+ "edit-labels": "编辑标签",
+ "mixed-values-for-label": "该标签拥有不同的值",
+ "mixed-label-values-warning": "某些标签拥有不同的值,编辑标签将会批量应用",
"change-data": "变更数据",
"change-data-in-vcs": "变更数据 (VCS)",
"branch": "分支",
@@ -1432,6 +1435,7 @@
"unassigned-databases": "未分配的数据库",
"restore-database": "恢复数据库",
"selected-n-databases": "已选择 {n} 个数据库",
+ "n-databases": "{n} 个数据库",
"select-databases-from-same-project": "请选择同一个项目下的数据库",
"sync-schema": {
"title": "库表同步",