Skip to content

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

chore: add labels to projects with simple CEL filtering (for now) (#17451)

Vincent Huangdef0526de4dc
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index cc5d44b01c..25a8cb7952 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -107,6 +107,12 @@ func getVariableAndValueFromExpr(expr celast.Expr) (string, any) {
switch arg.Kind() {
case celast.IdentKind:
variable = arg.AsIdent()
+ case celast.SelectKind:
+ // Handle member selection like "labels.environment"
+ sel := arg.AsSelect()
+ if sel.Operand().Kind() == celast.IdentKind {
+ variable = fmt.Sprintf("%s.%s", sel.Operand().AsIdent(), sel.FieldName())
+ }
case celast.LiteralKind:
value = arg.AsLiteral().Value()
case celast.ListKind:
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index 8d64b35937..b8c69c3998 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
+ "regexp"
"strconv"
"strings"
"time"
@@ -149,6 +150,22 @@ func getListProjectFilter(filter string) (*store.ListResourceFilter, error) {
positionalArgs = append(positionalArgs, v1pb.State(v1State) == v1pb.State_DELETED)
return fmt.Sprintf("project.deleted = $%d", len(positionalArgs)), nil
default:
+ // Check if it's a label filter (e.g., "labels.environment" == "production")
+ varStr, ok := variable.(string)
+ if !ok {
+ return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupport variable %q", variable))
+ }
+ if strings.HasPrefix(varStr, "labels.") {
+ labelKey := strings.TrimPrefix(varStr, "labels.")
+ labelValueStr, ok := value.(string)
+ if !ok {
+ return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf("label value must be a string, got %T", value))
+ }
+ // Use JSONB containment operator to check if the label exists with the specified value
+ // The setting column contains a proto message with a labels field
+ positionalArgs = append(positionalArgs, fmt.Sprintf(`{"%s":"%s"}`, labelKey, labelValueStr))
+ return fmt.Sprintf("project.setting->'labels' @> $%d::jsonb", len(positionalArgs)), nil
+ }
return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupport variable %q", variable))
}
}
@@ -278,6 +295,12 @@ func (s *ProjectService) CreateProject(ctx context.Context, req *connect.Request
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid project ID %v", req.Msg.ProjectId))
}
+ if req.Msg.Project != nil && req.Msg.Project.Labels != nil {
+ if err := validateProjectLabels(req.Msg.Project.Labels); err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ }
+
projectMessage := convertToProjectMessage(req.Msg.ProjectId, req.Msg.Project)
setting, err := s.store.GetDataClassificationSetting(ctx)
@@ -426,6 +449,13 @@ func (s *ProjectService) UpdateProject(ctx context.Context, req *connect.Request
projectSettings := project.Setting
projectSettings.ParallelTasksPerRollout = req.Msg.Project.ParallelTasksPerRollout
patch.Setting = projectSettings
+ case "labels":
+ if err := validateProjectLabels(req.Msg.Project.Labels); err != nil {
+ return nil, connect.NewError(connect.CodeInvalidArgument, err)
+ }
+ projectSettings := project.Setting
+ projectSettings.Labels = req.Msg.Project.Labels
+ patch.Setting = projectSettings
default:
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`unsupport update_mask "%s"`, path))
}
@@ -1446,6 +1476,7 @@ func convertToProject(projectMessage *store.ProjectMessage) *v1pb.Project {
ExecutionRetryPolicy: convertToV1ExecutionRetryPolicy(projectMessage.Setting.ExecutionRetryPolicy),
CiSamplingSize: projectMessage.Setting.CiSamplingSize,
ParallelTasksPerRollout: projectMessage.Setting.ParallelTasksPerRollout,
+ Labels: projectMessage.Setting.Labels,
}
}
@@ -1482,6 +1513,7 @@ func convertToProjectMessage(resourceID string, project *v1pb.Project) *store.Pr
AllowSelfApproval: project.AllowSelfApproval,
CiSamplingSize: project.CiSamplingSize,
ParallelTasksPerRollout: project.ParallelTasksPerRollout,
+ Labels: project.Labels,
}
return &store.ProjectMessage{
ResourceID: resourceID,
@@ -1701,3 +1733,28 @@ func validateMember(member string) error {
}
return errors.Errorf("invalid user %s", member)
}
+
+// validateProjectLabels validates the project labels according to the requirements.
+func validateProjectLabels(labels map[string]string) error {
+ if len(labels) > 64 {
+ return errors.Errorf("maximum 64 labels allowed, got %d", len(labels))
+ }
+
+ // Key pattern: must start with lowercase letter, then lowercase letters, numbers, underscores, dashes (max 63 chars)
+ keyPattern := `^[a-z][a-z0-9_-]{0,62}$`
+ // Value pattern: letters, numbers, underscores, dashes (max 63 chars, can be empty)
+ valuePattern := `^[a-zA-Z0-9_-]{0,63}$`
+
+ keyRegex := regexp.MustCompile(keyPattern)
+ valueRegex := regexp.MustCompile(valuePattern)
+
+ for key, value := range labels {
+ if !keyRegex.MatchString(key) {
+ return errors.Errorf("invalid label key %q: must start with lowercase letter and contain only lowercase letters, numbers, underscores, and dashes (max 63 chars)", key)
+ }
+ if !valueRegex.MatchString(value) {
+ return errors.Errorf("invalid label value %q for key %q: must contain only letters, numbers, underscores, and dashes (max 63 chars)", value, key)
+ }
+ }
+ return nil
+}
diff --git a/backend/api/v1/project_service_test.go b/backend/api/v1/project_service_test.go
index f8f743aacb..284453ef80 100644
--- a/backend/api/v1/project_service_test.go
+++ b/backend/api/v1/project_service_test.go
@@ -2,6 +2,7 @@ package v1
import (
"fmt"
+ "strings"
"testing"
"time"
@@ -9,6 +10,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/pkg/errors"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/genproto/googleapis/type/expr"
"google.golang.org/protobuf/types/known/durationpb"
@@ -437,3 +439,100 @@ func TestListProjectFilter(t *testing.T) {
}
}
}
+
+func TestValidateProjectLabels(t *testing.T) {
+ tests := []struct {
+ name string
+ labels map[string]string
+ wantErr bool
+ errMsg string
+ }{
+ {
+ name: "Valid labels",
+ labels: map[string]string{"environment": "production", "team": "backend"},
+ wantErr: false,
+ },
+ {
+ name: "Empty labels",
+ labels: map[string]string{},
+ wantErr: false,
+ },
+ {
+ name: "Valid key with empty value",
+ labels: map[string]string{"environment": ""},
+ wantErr: false,
+ },
+ {
+ name: "Key starting with number",
+ labels: map[string]string{"1environment": "production"},
+ wantErr: true,
+ errMsg: "invalid label key",
+ },
+ {
+ name: "Key with uppercase",
+ labels: map[string]string{"Environment": "production"},
+ wantErr: true,
+ errMsg: "invalid label key",
+ },
+ {
+ name: "Key with special characters",
+ labels: map[string]string{"env@prod": "production"},
+ wantErr: true,
+ errMsg: "invalid label key",
+ },
+ {
+ name: "Value with special characters",
+ labels: map[string]string{"environment": "prod@123"},
+ wantErr: true,
+ errMsg: "invalid label value",
+ },
+ {
+ name: "Key too long",
+ labels: map[string]string{strings.Repeat("a", 64): "value"},
+ wantErr: true,
+ errMsg: "invalid label key",
+ },
+ {
+ name: "Value too long",
+ labels: map[string]string{"key": strings.Repeat("a", 64)},
+ wantErr: true,
+ errMsg: "invalid label value",
+ },
+ {
+ name: "Too many labels",
+ labels: func() map[string]string {
+ labels := make(map[string]string)
+ for i := 0; i < 65; i++ {
+ labels[fmt.Sprintf("key%d", i)] = "value"
+ }
+ return labels
+ }(),
+ wantErr: true,
+ errMsg: "maximum 64 labels allowed",
+ },
+ {
+ name: "Valid underscore and dash",
+ labels: map[string]string{"env_name": "prod-01", "team-name": "backend_01"},
+ wantErr: false,
+ },
+ {
+ name: "Valid mixed case value",
+ labels: map[string]string{"environment": "Production", "region": "US-East-1"},
+ wantErr: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateProjectLabels(tt.labels)
+ if tt.wantErr {
+ assert.Error(t, err)
+ if tt.errMsg != "" {
+ assert.Contains(t, err.Error(), tt.errMsg)
+ }
+ } else {
+ assert.NoError(t, err)
+ }
+ })
+ }
+}
diff --git a/frontend/src/components/AdvancedSearch/index.ts b/frontend/src/components/AdvancedSearch/index.ts
index 04780dc6a4..dd74943a1e 100644
--- a/frontend/src/components/AdvancedSearch/index.ts
+++ b/frontend/src/components/AdvancedSearch/index.ts
@@ -1,6 +1,7 @@
import AdvancedSearch from "./AdvancedSearch.vue";
import TimeRange from "./TimeRange.vue";
+import { useCommonSearchScopeOptions } from "./useCommonSearchScopeOptions";
export default AdvancedSearch;
-export { TimeRange };
+export { TimeRange, useCommonSearchScopeOptions };
diff --git a/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts b/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts
index b62325fd92..f5d6b4dbf1 100644
--- a/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts
+++ b/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts
@@ -153,6 +153,12 @@ export const useCommonSearchScopeOptions = (
};
}),
}),
+ label: () => ({
+ id: "label",
+ title: t("common.labels"),
+ description: t("issue.advanced-search.scope.label.description"),
+ allowMultiple: true,
+ }),
"database-label": () => ({
id: "database-label",
title: t("issue.advanced-search.scope.database-label.title"),
@@ -160,6 +166,7 @@ export const useCommonSearchScopeOptions = (
"issue.advanced-search.scope.database-label.description"
),
allowMultiple: true,
+ deprecated: true, // Show deprecation notice
}),
table: () => ({
id: "table",
diff --git a/frontend/src/components/ColumnDataTable/LabelsCell.vue b/frontend/src/components/ColumnDataTable/LabelsCell.vue
index 7172f1db7b..788ea547d9 100644
--- a/frontend/src/components/ColumnDataTable/LabelsCell.vue
+++ b/frontend/src/components/ColumnDataTable/LabelsCell.vue
@@ -1,6 +1,6 @@
<template>
<div class="flex items-center space-x-1">
- <DatabaseLabelsCell :labels="labels" :show-count="2" />
+ <LabelsCell :labels="labels" :show-count="2" />
<button
v-if="!readonly"
class="w-5 h-5 p-0.5 hover:bg-gray-300 rounded cursor-pointer"
@@ -24,7 +24,7 @@
<script lang="ts" setup>
import { computed } from "vue";
import { reactive } from "vue";
-import { DatabaseLabelsCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { LabelsCell } from "@/components/v2/Model/cells";
import { useDatabaseCatalog, getColumnCatalog } from "@/store";
import LabelEditorDrawer from "../LabelEditorDrawer.vue";
import { updateColumnCatalog } from "./utils";
diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
index 4d37fa2ef4..72c67829a6 100644
--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
@@ -87,7 +87,8 @@ const { t } = useI18n();
const scopeOptions = useCommonSearchScopeOptions([
...CommonFilterScopeIdList,
"project",
- "database-label",
+ "label",
+ "database-label", // Keep for backward compatibility
"engine",
"table",
]);
@@ -226,7 +227,7 @@ const filterTableList = computed(() => {
const selectedLabels = computed(() => {
return params.value.scopes
- .filter((scope) => scope.id === "database-label")
+ .filter((scope) => scope.id === "label" || scope.id === "database-label")
.map((scope) => scope.value);
});
diff --git a/frontend/src/components/Project/ProjectSwitch/ProjectSwitchContent.vue b/frontend/src/components/Project/ProjectSwitch/ProjectSwitchContent.vue
index 644b9a5572..58a04e9e17 100644
--- a/frontend/src/components/Project/ProjectSwitch/ProjectSwitchContent.vue
+++ b/frontend/src/components/Project/ProjectSwitch/ProjectSwitchContent.vue
@@ -52,6 +52,7 @@
isValidProjectName(project.name) ? project : undefined
"
:keyword="state.searchText"
+ :show-labels="false"
@row-click="onProjectSelect"
/>
<PagedProjectTable
@@ -60,6 +61,7 @@
session-key="bb.project-table"
:filter="filter"
:loading="state.loading"
+ :show-labels="false"
@row-click="onProjectSelect"
/>
</NTabPane>
diff --git a/frontend/src/components/Project/ProjectSwitch/ProjectSwitchPopover.vue b/frontend/src/components/Project/ProjectSwitch/ProjectSwitchPopover.vue
index 96f3a469e7..2536cd731d 100644
--- a/frontend/src/components/Project/ProjectSwitch/ProjectSwitchPopover.vue
+++ b/frontend/src/components/Project/ProjectSwitch/ProjectSwitchPopover.vue
@@ -56,7 +56,7 @@ import { NButton, NPopover } from "naive-ui";
import { reactive, watch } from "vue";
import ProjectCreatePanel from "@/components/Project/ProjectCreatePanel.vue";
import { Drawer } from "@/components/v2";
-import { ProjectNameCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { ProjectNameCell } from "@/components/v2/Model/cells";
import { useCurrentProjectV1 } from "@/store";
import { isValidProjectName } from "@/types";
import ProjectSwitchContent from "./ProjectSwitchContent.vue";
diff --git a/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue b/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue
index 90449cfb15..eb31e3d1a0 100644
--- a/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue
+++ b/frontend/src/components/Project/Settings/ProjectGeneralSettingPanel.vue
@@ -20,19 +20,42 @@
/>
</div>
</div>
+
+ <!-- Project Labels Section -->
+ <div>
+ <div class="font-medium mb-2">
+ {{ $t("common.labels") }}
+ </div>
+ <div class="text-sm text-gray-500 mb-3">
+ {{ $t("project.settings.project-labels.description") }}
+ </div>
+
+ <LabelListEditor
+ ref="labelListEditorRef"
+ v-model:kv-list="labelKVList"
+ :readonly="!allowEdit"
+ :show-errors="true"
+ class="max-w-[30rem]"
+ />
+ </div>
</form>
</template>
<script lang="ts" setup>
-import { cloneDeep, isEmpty } from "lodash-es";
+import { cloneDeep, isEmpty, isEqual } from "lodash-es";
import { NInput } from "naive-ui";
-import { computed, reactive } from "vue";
+import { computed, reactive, ref, watch } from "vue";
+import { LabelListEditor } from "@/components/Label";
import RequiredStar from "@/components/RequiredStar.vue";
import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";
import { useProjectV1Store } from "@/store";
import { DEFAULT_PROJECT_NAME } from "@/types";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import { extractProjectResourceName } from "@/utils";
+import {
+ extractProjectResourceName,
+ convertLabelsToKVList,
+ convertKVListToLabels,
+} from "@/utils";
interface LocalState {
title: string;
@@ -44,24 +67,59 @@ const props = defineProps<{
}>();
const projectV1Store = useProjectV1Store();
+const labelListEditorRef = ref<InstanceType<typeof LabelListEditor>>();
const state = reactive<LocalState>({
title: props.project.title,
});
+// Convert labels to KVList format for LabelListEditor
+const labelKVList = ref(
+ convertLabelsToKVList(props.project.labels || {}, true /* sort */)
+);
+
+// Watch for external changes to project labels
+watch(
+ () => props.project.labels,
+ (newLabels) => {
+ labelKVList.value = convertLabelsToKVList(newLabels || {}, true /* sort */);
+ }
+);
+
const allowSave = computed((): boolean => {
- return (
+ const titleChanged =
props.project.name !== DEFAULT_PROJECT_NAME &&
!isEmpty(state.title) &&
- state.title !== props.project.title
+ state.title !== props.project.title;
+
+ const labelsChanged = !isEqual(
+ convertKVListToLabels(labelKVList.value, false),
+ props.project.labels
);
+
+ // Check if there are validation errors
+ const hasErrors = (labelListEditorRef.value?.flattenErrors ?? []).length > 0;
+
+ return (titleChanged || labelsChanged) && !hasErrors;
});
const onUpdate = async () => {
const projectPatch = cloneDeep(props.project);
+ const updateMask: string[] = [];
+
if (state.title !== props.project.title) {
projectPatch.title = state.title;
- await projectV1Store.updateProject(projectPatch, ["title"]);
+ updateMask.push("title");
+ }
+
+ const currentLabels = convertKVListToLabels(labelKVList.value, false);
+ if (!isEqual(currentLabels, props.project.labels)) {
+ projectPatch.labels = currentLabels;
+ updateMask.push("labels");
+ }
+
+ if (updateMask.length > 0) {
+ await projectV1Store.updateProject(projectPatch, updateMask);
}
};
@@ -70,6 +128,10 @@ defineExpose({
update: onUpdate,
revert: () => {
state.title = props.project.title;
+ labelKVList.value = convertLabelsToKVList(
+ props.project.labels || {},
+ true /* sort */
+ );
},
});
</script>
diff --git a/frontend/src/components/ProjectDatabasesPanel.vue b/frontend/src/components/ProjectDatabasesPanel.vue
index 961ba4c7f7..47b0357fd2 100644
--- a/frontend/src/components/ProjectDatabasesPanel.vue
+++ b/frontend/src/components/ProjectDatabasesPanel.vue
@@ -123,7 +123,8 @@ const allowToCreateDB = computed(() => {
const scopeOptions = useCommonSearchScopeOptions([
...CommonFilterScopeIdList,
- "database-label",
+ "label",
+ "database-label", // Keep for backward compatibility
"engine",
"drifted",
]);
@@ -150,7 +151,7 @@ const selectedEnvironment = computed(() => {
const selectedLabels = computed(() => {
return state.params.scopes
- .filter((scope) => scope.id === "database-label")
+ .filter((scope) => scope.id === "label" || scope.id === "database-label")
.map((scope) => scope.value);
});
diff --git a/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/components/LabelsCell.vue b/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/components/LabelsCell.vue
index 9b99d4ac74..cb414507e5 100644
--- a/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/components/LabelsCell.vue
+++ b/frontend/src/components/SchemaEditorLite/Panels/TableColumnEditor/components/LabelsCell.vue
@@ -1,6 +1,6 @@
<template>
<div class="flex justify-start items-center">
- <DatabaseLabelsCell :labels="columnCatalog?.labels ?? {}" :show-count="1" />
+ <LabelsCell :labels="columnCatalog?.labels ?? {}" :show-count="1" />
<MiniActionButton v-if="!readonly && !disabled" @click="$emit('edit')">
<PencilIcon class="w-3 h-3" />
</MiniActionButton>
@@ -12,7 +12,7 @@ import { PencilIcon } from "lucide-vue-next";
import { computed } from "vue";
import { useSchemaEditorContext } from "@/components/SchemaEditorLite/context";
import { MiniActionButton } from "@/components/v2";
-import { DatabaseLabelsCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { LabelsCell } from "@/components/v2/Model/cells";
const props = defineProps<{
database: string;
diff --git a/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue b/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue
index 9df4907e1f..2d8f23638f 100644
--- a/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue
+++ b/frontend/src/components/SchemaTemplate/FieldTemplateTable.vue
@@ -19,7 +19,7 @@ import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { getColumnDefaultValuePlaceholder } from "@/components/SchemaEditorLite";
import { MiniActionButton } from "@/components/v2";
-import { DatabaseLabelsCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { LabelsCell } from "@/components/v2/Model/cells";
import { useSettingV1Store } from "@/store";
import type { Engine } from "@/types/proto-es/v1/common_pb";
import type { SchemaTemplateSetting_FieldTemplate } from "@/types/proto-es/v1/setting_service_pb";
@@ -110,10 +110,7 @@ const columns = computed(
title: t("common.labels"),
key: "labels",
render: (item) => (
- <DatabaseLabelsCell
- labels={item.catalog?.labels ?? {}}
- showCount={2}
- />
+ <LabelsCell labels={item.catalog?.labels ?? {}} showCount={2} />
),
}
);
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue
index 8efa9f15e2..51a46b6547 100644
--- a/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue
+++ b/frontend/src/components/v2/Model/DatabaseV1Table/DatabaseV1Table.vue
@@ -22,9 +22,13 @@ import { NDataTable, type DataTableColumn } from "naive-ui";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";
+import {
+ DatabaseNameCell,
+ ProjectNameCell,
+ LabelsCell,
+} from "@/components/v2/Model/cells";
import type { ComposedDatabase } from "@/types";
import { hostPortOfInstanceV1 } from "@/utils";
-import { DatabaseNameCell, ProjectNameCell, DatabaseLabelsCell } from "./cells";
type DatabaseDataTableColumn = DataTableColumn<ComposedDatabase> & {
hide?: boolean;
@@ -153,7 +157,7 @@ const columnList = computed((): DatabaseDataTableColumn[] => {
title: t("common.labels"),
resizable: true,
render: (data) => (
- <DatabaseLabelsCell labels={data.labels} showCount={1} placeholder="-" />
+ <LabelsCell labels={data.labels} showCount={1} placeholder="-" />
),
};
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/cells/index.ts b/frontend/src/components/v2/Model/DatabaseV1Table/cells/index.ts
deleted file mode 100644
index a16be98eb0..0000000000
--- a/frontend/src/components/v2/Model/DatabaseV1Table/cells/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import DatabaseLabelsCell from "./DatabaseLabelsCell.vue";
-import DatabaseNameCell from "./DatabaseNameCell.vue";
-import ProjectNameCell from "./ProjectNameCell.vue";
-
-export { DatabaseNameCell, ProjectNameCell, DatabaseLabelsCell };
diff --git a/frontend/src/components/v2/Model/PagedProjectTable.vue b/frontend/src/components/v2/Model/PagedProjectTable.vue
index a65ea8b5d8..301960e745 100644
--- a/frontend/src/components/v2/Model/PagedProjectTable.vue
+++ b/frontend/src/components/v2/Model/PagedProjectTable.vue
@@ -11,6 +11,7 @@
:project-list="list"
:selected-project-names="selectedProjectNames"
:show-selection="showSelection"
+ :show-labels="showLabels"
:keyword="filter.query"
@update:selected-project-names="updateSelectedProjectNames"
/>
@@ -32,10 +33,12 @@ const props = withDefaults(
sessionKey: string;
selectedProjectNames?: string[];
showSelection?: boolean;
+ showLabels?: boolean;
}>(),
{
selectedProjectNames: () => [],
showSelection: false,
+ showLabels: true,
}
);
diff --git a/frontend/src/components/v2/Model/ProjectV1Table.vue b/frontend/src/components/v2/Model/ProjectV1Table.vue
index 0cb4d47853..575e2fb077 100644
--- a/frontend/src/components/v2/Model/ProjectV1Table.vue
+++ b/frontend/src/components/v2/Model/ProjectV1Table.vue
@@ -22,7 +22,7 @@ import { NDataTable, type DataTableColumn } from "naive-ui";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
-import { ProjectNameCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { ProjectNameCell, LabelsCell } from "@/components/v2/Model/cells";
import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";
import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import { getProjectName } from "@/store/modules/v1/common";
@@ -47,6 +47,8 @@ const props = withDefaults(
selectedProjectNames?: string[];
// Whether to show selection checkboxes
showSelection?: boolean;
+ // Whether to show labels column (hidden in dropdowns for cleaner UI)
+ showLabels?: boolean;
}>(),
{
bordered: true,
@@ -54,6 +56,7 @@ const props = withDefaults(
keyword: undefined,
selectedProjectNames: () => [],
showSelection: false,
+ showLabels: true,
}
);
@@ -136,6 +139,20 @@ const columnList = computed((): ProjectDataTableColumn[] => {
/>
),
},
+ {
+ key: "labels",
+ title: t("common.labels"),
+ width: 300,
+ ellipsis: true,
+ hide: !props.showLabels,
+ render: (project) => (
+ <LabelsCell
+ labels={project.labels || {}}
+ showCount={3}
+ placeholder=""
+ />
+ ),
+ },
] as ProjectDataTableColumn[]
).filter((column) => !column.hide);
});
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/cells/DatabaseNameCell.vue b/frontend/src/components/v2/Model/cells/DatabaseNameCell.vue
similarity index 100%
rename from frontend/src/components/v2/Model/DatabaseV1Table/cells/DatabaseNameCell.vue
rename to frontend/src/components/v2/Model/cells/DatabaseNameCell.vue
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/cells/DatabaseLabelsCell.vue b/frontend/src/components/v2/Model/cells/LabelsCell.vue
similarity index 100%
rename from frontend/src/components/v2/Model/DatabaseV1Table/cells/DatabaseLabelsCell.vue
rename to frontend/src/components/v2/Model/cells/LabelsCell.vue
diff --git a/frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue b/frontend/src/components/v2/Model/cells/ProjectNameCell.vue
similarity index 93%
rename from frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue
rename to frontend/src/components/v2/Model/cells/ProjectNameCell.vue
index ccfc43e4c2..b1f3e0ccf8 100644
--- a/frontend/src/components/v2/Model/DatabaseV1Table/cells/ProjectNameCell.vue
+++ b/frontend/src/components/v2/Model/cells/ProjectNameCell.vue
@@ -27,7 +27,7 @@ import { NTooltip } from "naive-ui";
import { ProjectV1Name } from "@/components/v2";
import { State } from "@/types/proto-es/v1/common_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import type { Mode } from "../DatabaseV1Table.vue";
+import type { Mode } from "../DatabaseV1Table/DatabaseV1Table.vue";
withDefaults(
defineProps<{
diff --git a/frontend/src/components/v2/Model/cells/index.ts b/frontend/src/components/v2/Model/cells/index.ts
new file mode 100644
index 0000000000..6696f6c72c
--- /dev/null
+++ b/frontend/src/components/v2/Model/cells/index.ts
@@ -0,0 +1,5 @@
+import DatabaseNameCell from "./DatabaseNameCell.vue";
+import LabelsCell from "./LabelsCell.vue";
+import ProjectNameCell from "./ProjectNameCell.vue";
+
+export { DatabaseNameCell, LabelsCell, ProjectNameCell };
diff --git a/frontend/src/components/v2/ResourceOccupiedModal/useResourceByName.ts b/frontend/src/components/v2/ResourceOccupiedModal/useResourceByName.ts
index 05105d527f..51fc384083 100644
--- a/frontend/src/components/v2/ResourceOccupiedModal/useResourceByName.ts
+++ b/frontend/src/components/v2/ResourceOccupiedModal/useResourceByName.ts
@@ -1,6 +1,6 @@
import { type Ref, watchEffect, computed, h } from "vue";
import { EnvironmentV1Name, RichDatabaseName } from "@/components/v2";
-import { ProjectNameCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { ProjectNameCell } from "@/components/v2/Model/cells";
import { t } from "@/plugins/i18n";
import {
useEnvironmentV1Store,
diff --git a/frontend/src/components/v2/Select/ProjectSelect.vue b/frontend/src/components/v2/Select/ProjectSelect.vue
index 51c76e9eef..bb4fd5aaba 100644
--- a/frontend/src/components/v2/Select/ProjectSelect.vue
+++ b/frontend/src/components/v2/Select/ProjectSelect.vue
@@ -26,7 +26,7 @@ import { useDebounceFn } from "@vueuse/core";
import { intersection } from "lodash-es";
import { computed, watchEffect, reactive, onMounted } from "vue";
import { useI18n } from "vue-i18n";
-import { ProjectNameCell } from "@/components/v2/Model/DatabaseV1Table/cells";
+import { ProjectNameCell } from "@/components/v2/Model/cells";
import { useProjectV1Store, usePermissionStore } from "@/store";
import {
unknownProject,
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 06d34bbabb..97d462a03a 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -204,6 +204,7 @@
"info": "Info",
"minutes": "Minutes",
"filter-by-name": "Filter by name",
+ "filter-by-name-or-label": "Filter by name or label (e.g., labels.environment == \"production\")",
"search-by-name": "Search by name",
"license": "License",
"view-details": "View details",
@@ -923,8 +924,12 @@
"title": "Table",
"description": "Input the value then press Enter"
},
+ "label": {
+ "title": "Label",
+ "description": "Input the \"key:value\" pair then press Enter"
+ },
"database-label": {
- "title": "Database Label",
+ "title": "Database Label (Deprecated - use Label)",
"description": "Input the \"key:value\" pair then press Enter"
},
"engine": {
@@ -1875,6 +1880,9 @@
"self": "Parallel tasks per rollout",
"description": "Control the number of parallel tasks per rollout. Setting this to zero disables any throttling."
}
+ },
+ "project-labels": {
+ "description": "Organize projects with key-value labels (max 64)"
}
},
"members": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 494e47be36..33f2f56c8e 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -204,6 +204,7 @@
"info": "Información",
"minutes": "Minutos",
"filter-by-name": "Filtrar por nombre",
+ "filter-by-name-or-label": "Filtrar por nombre o etiqueta (ej: labels.environment == \"production\")",
"search-by-name": "Buscar por nombre",
"license": "Licencia",
"view-details": "Ver detalles",
@@ -1875,6 +1876,9 @@
"self": "Tareas paralelas por despliegue",
"description": "Controle el número de tareas paralelas por despliegue. \nEstablecer esto en cero deshabilita cualquier estrangulamiento."
}
+ },
+ "project-labels": {
+ "description": "Organizar proyectos con etiquetas clave-valor (máximo 64)"
}
},
"members": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 7c02775cad..a270e8e7fc 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -204,6 +204,7 @@
"info": "情報",
"minutes": "分",
"filter-by-name": "名前でフィルタリングする",
+ "filter-by-name-or-label": "名前またはラベルでフィルタリング (例: labels.environment == \"production\")",
"search-by-name": "名前で検索",
"license": "ライセンス",
"view-details": "詳細を確認する",
@@ -1875,6 +1876,9 @@
"self": "ロールアウトごとの並列タスク",
"description": "ロールアウトあたりの並列タスクの数を制御します。\nこれをゼロに設定すると、スロットリングが無効になります。"
}
+ },
+ "project-labels": {
+ "description": "キーバリューラベルでプロジェクトを整理(最大64個)"
}
},
"members": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index badd240708..9f01b95069 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -204,6 +204,7 @@
"info": "Thông tin",
"minutes": "Phút",
"filter-by-name": "Lọc theo tên",
+ "filter-by-name-or-label": "Lọc theo tên hoặc nhãn (ví dụ: labels.environment == \"production\")",
"search-by-name": "Tìm kiếm theo tên",
"license": "Giấy phép",
"view-details": "Xem chi tiết",
@@ -1875,6 +1876,9 @@
"self": "Nhiệm vụ song song cho mỗi lần triển khai",
"description": "Kiểm soát số lượng các tác vụ song song cho mỗi lần triển khai. \nĐặt điều này thành 0 vô hiệu hóa bất kỳ điều chỉnh."
}
+ },
+ "project-labels": {
+ "description": "Tổ chức dự án với nhãn khóa-giá trị (tối đa 64)"
}
},
"members": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index ea2f7d7ae9..ae1c1173f1 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -204,6 +204,7 @@
"info": "信息",
"minutes": "分钟",
"filter-by-name": "按名称过滤",
+ "filter-by-name-or-label": "按名称或标签过滤 (例如: labels.environment == \"production\")",
"search-by-name": "按名称搜索",
"license": "证书",
"view-details": "查看详情",
@@ -1875,6 +1876,9 @@
"self": "每个发布的并行任务数",
"description": "控制每个发布的并行任务数量。\n将其设置为零,可以禁用任何节流。"
}
+ },
+ "project-labels": {
+ "description": "用键值标签组织项目(最多64个)"
}
},
"members": {
diff --git a/frontend/src/store/modules/v1/project.ts b/frontend/src/store/modules/v1/project.ts
index c6ce847bd0..a7010fa160 100644
--- a/frontend/src/store/modules/v1/project.ts
+++ b/frontend/src/store/modules/v1/project.ts
@@ -36,16 +36,35 @@ export interface ProjectFilter {
query?: string;
excludeDefault?: boolean;
state?: State;
+ // label should be "{label key}:{label value}" format
+ labels?: string[];
}
const getListProjectFilter = (params: ProjectFilter) => {
const list = [];
- const search = params.query?.trim().toLowerCase();
+ const search = params.query?.trim();
+
if (search) {
+ // It's a regular name/resource_id search
+ const searchLower = search.toLowerCase();
list.push(
- `(name.matches("${search}") || resource_id.matches("${search}"))`
+ `(name.matches("${searchLower}") || resource_id.matches("${searchLower}"))`
);
}
+
+ // Handle label filters from structured labels array
+ if (params.labels && params.labels.length > 0) {
+ // label filter like: labels.environment == "production" && labels.tier == "critical"
+ for (const label of params.labels) {
+ const sections = label.split(":");
+ if (sections.length !== 2) {
+ continue;
+ }
+ const [key, value] = sections;
+ list.push(`labels.${key} == "${value}"`);
+ }
+ }
+
if (params.excludeDefault) {
list.push("exclude_default == true");
}
diff --git a/frontend/src/utils/v1/advanced-search/common.ts b/frontend/src/utils/v1/advanced-search/common.ts
index 406826e5f6..804272d055 100644
--- a/frontend/src/utils/v1/advanced-search/common.ts
+++ b/frontend/src/utils/v1/advanced-search/common.ts
@@ -24,9 +24,11 @@ export const AllSearchScopeIdList = [
"updated",
"status",
"state",
+ // universal search scopes.
+ "label",
// database related search scopes.
"engine",
- "database-label",
+ "database-label", // Deprecated: use "label" instead
"drifted",
"table",
// issue related search scopes.
diff --git a/frontend/src/views/DatabaseDashboard.vue b/frontend/src/views/DatabaseDashboard.vue
index 4f9364c6d6..ce830962f4 100644
--- a/frontend/src/views/DatabaseDashboard.vue
+++ b/frontend/src/views/DatabaseDashboard.vue
@@ -122,13 +122,14 @@ const allowToCreateDB = computed(() => {
const scopeOptions = useCommonSearchScopeOptions([
...CommonFilterScopeIdList,
"project",
- "database-label",
+ "label",
+ "database-label", // Keep for backward compatibility
"engine",
]);
const selectedLabels = computed(() => {
return state.params.scopes
- .filter((scope) => scope.id === "database-label")
+ .filter((scope) => scope.id === "label" || scope.id === "database-label")
.map((scope) => scope.value);
});
diff --git a/frontend/src/views/InstanceDetail.vue b/frontend/src/views/InstanceDetail.vue
index 8f33b9293c..93a7ab8ba3 100644
--- a/frontend/src/views/InstanceDetail.vue
+++ b/frontend/src/views/InstanceDetail.vue
@@ -194,7 +194,8 @@ const route = useRoute();
const scopeOptions = useCommonSearchScopeOptions([
...CommonFilterScopeIdList,
"project",
- "database-label",
+ "label",
+ "database-label", // Keep for backward compatibility
]);
watch(
@@ -255,7 +256,7 @@ const selectedProject = computed(() => {
const selectedLabels = computed(() => {
return state.params.scopes
- .filter((scope) => scope.id === "database-label")
+ .filter((scope) => scope.id === "label" || scope.id === "database-label")
.map((scope) => scope.value);
});
diff --git a/frontend/src/views/ProjectDashboard.vue b/frontend/src/views/ProjectDashboard.vue
index 3005c47088..528a3e56d6 100644
--- a/frontend/src/views/ProjectDashboard.vue
+++ b/frontend/src/views/ProjectDashboard.vue
@@ -3,8 +3,9 @@
<div class="flex items-center justify-between px-4 space-x-2">
<AdvancedSearch
v-model:params="state.params"
+ :scope-options="scopeOptions"
:autofocus="false"
- :placeholder="$t('common.filter-by-name')"
+ :placeholder="$t('common.filter-by-name-or-label')"
/>
<NButton
v-if="hasWorkspacePermissionV2('bb.projects.create')"
@@ -57,6 +58,7 @@ import { computed, onMounted, reactive, ref } from "vue";
import type { ComponentExposed } from "vue-component-type-helpers";
import { useRouter } from "vue-router";
import AdvancedSearch from "@/components/AdvancedSearch";
+import { useCommonSearchScopeOptions } from "@/components/AdvancedSearch";
import ProjectCreatePanel from "@/components/Project/ProjectCreatePanel.vue";
import { PagedProjectTable } from "@/components/v2";
import { Drawer } from "@/components/v2";
@@ -89,9 +91,20 @@ const projectStore = useProjectV1Store();
const pagedProjectTableRef = ref<ComponentExposed<typeof PagedProjectTable>>();
+// Add label to the available scopes for filtering projects
+const scopeOptions = useCommonSearchScopeOptions(["label"]);
+
+// Extract labels from the search scopes
+const selectedLabels = computed(() => {
+ return state.params.scopes
+ .filter((scope) => scope.id === "label")
+ .map((scope) => scope.value);
+});
+
const filter = computed(() => ({
query: state.params.query,
excludeDefault: true,
+ labels: selectedLabels.value,
}));
const selectedProjectNames = computed(() => {
diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
index b453874268..5bcecbd1d0 100644
--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue
@@ -419,7 +419,8 @@ const handleUncheckDatabaseGroup = (databaseGroupName: string) => {
const scopeOptions = useCommonSearchScopeOptions([
...CommonFilterScopeIdList.filter((scope) => scope !== "environment"),
- "database-label",
+ "label",
+ "database-label", // Keep for backward compatibility
"engine",
]);
@@ -616,7 +617,7 @@ useEmitteryEventListener(editorEvents, "tree-ready", async () => {
const selectedLabels = computed(() => {
return state.params.scopes
- .filter((scope) => scope.id === "database-label")
+ .filter((scope) => scope.id === "label" || scope.id === "database-label")
.map((scope) => scope.value);
});
diff --git a/proto/v1/v1/project_service.proto b/proto/v1/v1/project_service.proto
index 9f9e6d1385..e16596a877 100644
--- a/proto/v1/v1/project_service.proto
+++ b/proto/v1/v1/project_service.proto
@@ -193,6 +193,7 @@ message ListProjectsRequest {
// Filter the project.
// Check filter for SearchProjectsRequest for details.
+ // Supports filtering by name, resource_id, state, and labels (e.g., labels.environment == "production").
string filter = 4;
}
@@ -217,6 +218,7 @@ message SearchProjectsRequest {
// - resource_id: the project id, support "==" and ".matches()" operator.
// - exclude_default: if not include the default project, should be "true" or "false", support "==" operator.
// - state: check the State enum for the values, support "==" operator.
+ // - labels.{key}: the project label, support "==" operator for exact match.
//
// For example:
// name = "project name"
@@ -225,9 +227,12 @@ message SearchProjectsRequest {
// resource_id.matches("project id")
// exclude_default == true
// state == "DELETED"
+ // labels.environment == "production"
+ // labels.tier == "critical"
// You can combine filter conditions like:
// name = "project name" && resource_id.matches("project id")
// name.matches("project name") || resource_id = "project id"
+ // labels.environment == "production" && labels.tier == "critical"
string filter = 2;
// The maximum number of projects to return. The service may return fewer than