Skip to content

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

feat: create/update database group(part1) (#6307)

boojack11605d2129e3
diff --git a/backend/api/v1/common.go b/backend/api/v1/common.go
index fd94800caa..e8ad2a5dec 100644
--- a/backend/api/v1/common.go
+++ b/backend/api/v1/common.go
@@ -86,7 +86,7 @@ func getProjectID(name string) (string, error) {
}
func getProjectIDDatabaseGroupID(name string) (string, string, error) {
- tokens, err := getNameParentTokens(name, databaseGroupNamePrefix)
+ tokens, err := getNameParentTokens(name, projectNamePrefix, databaseGroupNamePrefix)
if err != nil {
return "", "", err
}
@@ -94,7 +94,7 @@ func getProjectIDDatabaseGroupID(name string) (string, string, error) {
}
func getProjectIDDatabaseGroupIDSchemaGroupID(name string) (string, string, string, error) {
- tokens, err := getNameParentTokens(name, databaseGroupNamePrefix, schemaGroupNamePrefix)
+ tokens, err := getNameParentTokens(name, projectNamePrefix, databaseGroupNamePrefix, schemaGroupNamePrefix)
if err != nil {
return "", "", "", err
}
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.go
index c3c1902fd4..e4ebd4e58a 100644
--- a/backend/api/v1/project_service.go
+++ b/backend/api/v1/project_service.go
@@ -726,6 +726,7 @@ func (s *ProjectService) UpdateDatabaseGroup(ctx context.Context, request *v1pb.
if request.DatabaseGroup.DatabaseExpr == nil {
return nil, status.Errorf(codes.InvalidArgument, "database group expr is required")
}
+ updateDatabaseGroup.Expression = request.DatabaseGroup.DatabaseExpr
default:
return nil, status.Errorf(codes.InvalidArgument, "unsupported path: %q", path)
}
diff --git a/backend/store/database_group.go b/backend/store/database_group.go
index 7ede7fa62b..02f6f2f01d 100644
--- a/backend/store/database_group.go
+++ b/backend/store/database_group.go
@@ -125,10 +125,9 @@ func (*Store) listDatabaseGroupImpl(ctx context.Context, tx *Tx, find *FindDatab
resource_id,
placeholder,
expression
- FROM db_group %s ORDER BY id DESC;`, strings.Join(where, " AND "))
+ FROM db_group WHERE %s ORDER BY id DESC;`, strings.Join(where, " AND "))
var databaseGroups []*DatabaseGroupMessage
-
rows, err := tx.QueryContext(ctx, query, args...)
if err != nil {
return nil, errors.Wrapf(err, "failed to scan")
@@ -160,9 +159,7 @@ func (*Store) listDatabaseGroupImpl(ctx context.Context, tx *Tx, find *FindDatab
if err := rows.Err(); err != nil {
return nil, errors.Wrapf(err, "failed to scan")
}
- if err := tx.Commit(); err != nil {
- return nil, errors.Wrapf(err, "failed to commit transaction")
- }
+
return databaseGroups, nil
}
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
new file mode 100644
index 0000000000..4ca877b531
--- /dev/null
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
@@ -0,0 +1,164 @@
+<template>
+ <div class="w-full">
+ <div class="w-full grid grid-cols-3 gap-x-6 pb-6 mb-4 border-b">
+ <div>
+ <p class="text-lg mb-2">Name</p>
+ <input
+ v-model="state.databasePlaceholder"
+ required
+ type="text"
+ class="textfield w-full"
+ />
+ <ResourceIdField
+ ref="resourceIdField"
+ resource-type="database-group"
+ :readonly="!isCreating"
+ :value="state.resourceId"
+ :resource-title="state.databasePlaceholder"
+ :validate="validateResourceId"
+ />
+ </div>
+ <div>
+ <p class="text-lg mb-2">Environment</p>
+ <EnvironmentSelect
+ :selected-id="state.environmentId"
+ @select-environment-id="
+ (environmentId) => {
+ state.environmentId = environmentId;
+ }
+ "
+ />
+ </div>
+ <div>
+ <p class="text-lg mb-2">Project</p>
+ <input
+ required
+ type="text"
+ readonly
+ disabled
+ :value="project.title"
+ class="textfield w-full"
+ />
+ </div>
+ </div>
+ <div class="w-full grid grid-cols-5 gap-x-6">
+ <div class="col-span-3">
+ <p class="pl-1 text-lg mb-2">Condition</p>
+ <ExprEditor
+ :expr="state.expr"
+ :allow-admin="true"
+ :allow-high-level-factors="false"
+ />
+ </div>
+ <div class="col-span-2">
+ <p class="text-lg mb-2">Database</p>
+ <MatchedDatabaseView
+ :project="project"
+ :environment-id="state.environmentId || ''"
+ :expr="state.expr"
+ />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, onMounted, reactive, ref } from "vue";
+import { ConditionGroupExpr, resolveCELExpr, wrapAsGroup } from "@/plugins/cel";
+
+import { Expr as CELExpr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
+import ExprEditor from "./common/ExprEditor";
+import { ResourceType } from "./common/ExprEditor/context";
+import { DatabaseGroup } from "@/types/proto/v1/project_service";
+import { ComposedProject, ResourceId, ValidatedMessage } from "@/types";
+import EnvironmentSelect from "../EnvironmentSelect.vue";
+import MatchedDatabaseView from "./MatchedDatabaseView.vue";
+import { convertDatabaseGroupExprFromCEL } from "@/utils/databaseGroup/cel";
+import { useDBGroupStore, useEnvironmentV1Store } from "@/store";
+import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";
+import { useI18n } from "vue-i18n";
+import { getErrorCode } from "@/utils/grpcweb";
+import { Status } from "nice-grpc-web";
+
+const props = defineProps<{
+ project: ComposedProject;
+ databaseGroup?: DatabaseGroup;
+}>();
+
+type LocalState = {
+ resourceId: string;
+ databasePlaceholder: string;
+ environmentId?: string;
+ expr: ConditionGroupExpr;
+ resourceType: ResourceType;
+};
+
+const { t } = useI18n();
+const environmentStore = useEnvironmentV1Store();
+const dbGroupStore = useDBGroupStore();
+const state = reactive<LocalState>({
+ resourceId: "",
+ databasePlaceholder: props.databaseGroup?.databasePlaceholder ?? "",
+ expr: wrapAsGroup(resolveCELExpr(CELExpr.fromJSON({}))),
+ resourceType: "DATABASE_GROUP",
+});
+const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();
+
+const isCreating = computed(() => props.databaseGroup === undefined);
+
+onMounted(async () => {
+ const databaseGroup = props.databaseGroup;
+ if (!databaseGroup) {
+ return;
+ }
+
+ const convertResult = await convertDatabaseGroupExprFromCEL(
+ databaseGroup.databaseExpr?.expression ?? ""
+ );
+ const environment = environmentStore.getEnvironmentByName(
+ convertResult.environmentId
+ );
+ state.resourceId = databaseGroup.name.split("/").pop() || "";
+ state.databasePlaceholder = databaseGroup.databasePlaceholder;
+ state.environmentId = environment?.uid;
+ state.expr = convertResult.conditionGroupExpr;
+});
+
+const validateResourceId = async (
+ resourceId: ResourceId
+): Promise<ValidatedMessage[]> => {
+ if (!resourceId) {
+ return [];
+ }
+
+ try {
+ const dbGroup = await dbGroupStore.getOrFetchDBGroupById(
+ `${props.project.name}/databaseGroups/${resourceId}`
+ );
+ if (dbGroup) {
+ return [
+ {
+ type: "error",
+ message: t("resource-id.validation.duplicated", {
+ resource: t("resource.environment"),
+ }),
+ },
+ ];
+ }
+ } catch (error) {
+ if (getErrorCode(error) !== Status.NOT_FOUND) {
+ throw error;
+ }
+ }
+ return [];
+};
+
+defineExpose({
+ getFormState: () => {
+ return {
+ ...state,
+ resourceId: resourceIdField.value?.resourceId || "",
+ };
+ },
+});
+</script>
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
new file mode 100644
index 0000000000..5219d4fd7f
--- /dev/null
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupPanel.vue
@@ -0,0 +1,103 @@
+<template>
+ <NDrawer
+ :show="true"
+ width="auto"
+ :auto-focus="false"
+ @update:show="(show: boolean) => !show && $emit('close')"
+ >
+ <NDrawerContent
+ :title="title"
+ :closable="true"
+ class="w-[64rem] max-w-[100vw] relative"
+ >
+ <DatabaseGroupForm
+ ref="formRef"
+ :project="project"
+ :database-group="props.databaseGroup"
+ />
+ <template #footer>
+ <div class="flex items-center justify-end gap-x-2">
+ <NButton @click="$emit('close')">{{ $t("common.cancel") }}</NButton>
+ <NButton type="primary" @click="doConfirm">
+ {{ $t("common.confirm") }}
+ </NButton>
+ </div>
+ </template>
+ </NDrawerContent>
+ </NDrawer>
+</template>
+
+<script lang="ts" setup>
+import { NButton, NDrawer, NDrawerContent } from "naive-ui";
+import { computed, ref } from "vue";
+import { ComposedProject } from "@/types";
+import { DatabaseGroup } from "@/types/proto/v1/project_service";
+import DatabaseGroupForm from "./DatabaseGroupForm.vue";
+import { useDBGroupStore, useEnvironmentV1Store } from "@/store";
+import { stringifyDatabaseGroupExpr } from "@/utils/databaseGroup/cel";
+import { Expr } from "@/types/proto/google/type/expr";
+
+const props = defineProps<{
+ project: ComposedProject;
+ databaseGroup?: DatabaseGroup;
+}>();
+
+const emit = defineEmits<{
+ (event: "close"): void;
+}>();
+
+const environmentStore = useEnvironmentV1Store();
+const dbGroupStore = useDBGroupStore();
+const formRef = ref<InstanceType<typeof DatabaseGroupForm>>();
+
+const isCreating = computed(() => props.databaseGroup === undefined);
+
+const title = computed(() => {
+ return isCreating.value ? "Create database group" : "Edit database group";
+});
+
+const doConfirm = async () => {
+ const formState = formRef.value?.getFormState();
+ if (!formState) {
+ return;
+ }
+
+ if (isCreating.value) {
+ const environment = environmentStore.getEnvironmentByUID(
+ formState.environmentId || ""
+ );
+ const celString = stringifyDatabaseGroupExpr({
+ environmentId: environment.name,
+ conditionGroupExpr: formState.expr,
+ });
+ const resourceId = formState.resourceId;
+ await dbGroupStore.createDatabaseGroup(
+ props.project.name,
+ {
+ name: `${props.project.name}/databaseGroups/${resourceId}`,
+ databasePlaceholder: formState.databasePlaceholder,
+ databaseExpr: Expr.fromJSON({
+ expression: celString,
+ }),
+ },
+ resourceId
+ );
+ emit("close");
+ } else {
+ const environment = environmentStore.getEnvironmentByUID(
+ formState.environmentId || ""
+ );
+ const celString = stringifyDatabaseGroupExpr({
+ environmentId: environment.name,
+ conditionGroupExpr: formState.expr,
+ });
+ await dbGroupStore.updateDatabaseGroup({
+ ...props.databaseGroup!,
+ databasePlaceholder: formState.databasePlaceholder,
+ databaseExpr: Expr.fromJSON({
+ expression: celString,
+ }),
+ });
+ }
+};
+</script>
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupTable.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupTable.vue
new file mode 100644
index 0000000000..76d94c89c9
--- /dev/null
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupTable.vue
@@ -0,0 +1,90 @@
+<template>
+ <BBGrid
+ :column-list="COLUMN_LIST"
+ :data-source="formatedDatabaseGroupList"
+ :row-clickable="true"
+ row-key="name"
+ class="border"
+ >
+ <template #item="{ item }: { item: FormatedDatabaseGroup }">
+ <div class="bb-grid-cell">
+ {{ item.databasePlaceholder }}
+ </div>
+ <div class="bb-grid-cell">{{ item.environment }}</div>
+ <div class="bb-grid-cell gap-x-2">
+ <NButton size="small" @click="$emit('edit', item.databaseGroup)"
+ >Configure</NButton
+ >
+ </div>
+ </template>
+ </BBGrid>
+</template>
+
+<script lang="ts" setup>
+import { BBGridColumn } from "@/bbkit";
+import { useEnvironmentV1Store } from "@/store";
+import { DatabaseGroup } from "@/types/proto/v1/project_service";
+import { convertDatabaseGroupExprFromCEL } from "@/utils/databaseGroup/cel";
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+
+interface FormatedDatabaseGroup {
+ name: string;
+ databasePlaceholder: string;
+ environment: string;
+ databaseGroup: DatabaseGroup;
+}
+
+const props = defineProps<{
+ databaseGroupList: DatabaseGroup[];
+}>();
+
+defineEmits<{
+ (event: "edit", databaseGroup: DatabaseGroup): void;
+}>();
+
+const { t } = useI18n();
+const environmentStore = useEnvironmentV1Store();
+const formatedDatabaseGroupList = ref<FormatedDatabaseGroup[]>([]);
+
+const COLUMN_LIST = computed(() => {
+ const columns: BBGridColumn[] = [
+ { title: t("common.name"), width: "1fr" },
+ {
+ title: t("common.environment"),
+ width: "1fr",
+ },
+ {
+ title: "",
+ width: "10rem",
+ },
+ ];
+
+ return columns;
+});
+
+watch(
+ () => [props.databaseGroupList],
+ async () => {
+ const list: FormatedDatabaseGroup[] = [];
+ for (const databaseGroup of props.databaseGroupList) {
+ const convertResult = await convertDatabaseGroupExprFromCEL(
+ databaseGroup.databaseExpr?.expression ?? ""
+ );
+ const environment = environmentStore.getEnvironmentByName(
+ convertResult.environmentId
+ );
+ list.push({
+ name: databaseGroup.name,
+ databasePlaceholder: databaseGroup.databasePlaceholder,
+ environment: environment?.title || "",
+ databaseGroup,
+ });
+ }
+ formatedDatabaseGroupList.value = list;
+ },
+ {
+ immediate: true,
+ }
+);
+</script>
diff --git a/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue
new file mode 100644
index 0000000000..e7f674d334
--- /dev/null
+++ b/frontend/src/components/DatabaseGroup/MatchedDatabaseView.vue
@@ -0,0 +1,118 @@
+<template>
+ <div class="w-full border min-h-[20rem]">
+ <div
+ class="w-full flex flex-row justify-between items-center px-2 py-1 bg-gray-100 border-b"
+ >
+ <div>
+ <span>Matched database</span>
+ <span class="ml-1 text-gray-400"
+ >({{ matchedDatabaseList.length }})</span
+ >
+ </div>
+ <button
+ @click="state.showMatchedDatabaseList = !state.showMatchedDatabaseList"
+ >
+ <heroicons-outline:chevron-right
+ v-if="!state.showMatchedDatabaseList"
+ class="w-5 h-auto"
+ />
+ <heroicons-outline:chevron-down v-else class="w-5 h-auto" />
+ </button>
+ </div>
+ <div v-show="state.showMatchedDatabaseList" class="w-full">
+ <div
+ v-for="database in matchedDatabaseList"
+ :key="database.name"
+ class="w-full flex flex-row justify-between items-center px-2 py-1 gap-x-2"
+ >
+ <span>{{ database.databaseName }}</span>
+ <div class="flex flex-row justify-end items-center">
+ <InstanceV1EngineIcon :instance="database.instanceEntity" />
+ <span class="ml-1 text-sm text-gray-400">{{
+ database.instanceEntity.title
+ }}</span>
+ </div>
+ </div>
+ </div>
+ <div
+ class="w-full flex flex-row justify-between items-center px-2 py-1 bg-gray-100 border-b"
+ :class="[state.showMatchedDatabaseList && 'border-t']"
+ >
+ <div>
+ <span>Unmatched database</span>
+ <span class="ml-1 text-gray-400"
+ >({{ unmatchedDatabaseList.length }})</span
+ >
+ </div>
+ <button
+ @click="
+ state.showUnmatchedDatabaseList = !state.showUnmatchedDatabaseList
+ "
+ >
+ <heroicons-outline:chevron-right
+ v-if="!state.showUnmatchedDatabaseList"
+ class="w-5 h-auto"
+ />
+ <heroicons-outline:chevron-down v-else class="w-5 h-auto" />
+ </button>
+ </div>
+ <div v-show="state.showUnmatchedDatabaseList">
+ <div
+ v-for="database in matchedDatabaseList"
+ :key="database.name"
+ class="w-full flex flex-row justify-between items-center"
+ >
+ <span>{{ database.databaseName }}</span>
+ <div class="flex flex-row justify-end items-center">
+ <InstanceV1EngineIcon :instance="database.instanceEntity" />
+ <span class="ml-1 text-sm text-gray-400">{{
+ database.instanceEntity.title
+ }}</span>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref, watch, reactive } from "vue";
+import { ConditionGroupExpr } from "@/plugins/cel";
+import { useDatabaseV1Store } from "@/store";
+import { ComposedDatabase, ComposedProject } from "@/types";
+import { sortDatabaseV1List } from "@/utils";
+import { InstanceV1EngineIcon } from "../v2";
+
+interface LocalState {
+ showMatchedDatabaseList: boolean;
+ showUnmatchedDatabaseList: boolean;
+}
+
+const props = defineProps<{
+ project: ComposedProject;
+ environmentId: string;
+ expr: ConditionGroupExpr;
+}>();
+
+const state = reactive<LocalState>({
+ showMatchedDatabaseList: false,
+ showUnmatchedDatabaseList: false,
+});
+const matchedDatabaseList = ref<ComposedDatabase[]>([]);
+const unmatchedDatabaseList = ref<ComposedDatabase[]>([]);
+const databaseList = computed(() => {
+ const list = useDatabaseV1Store().databaseListByProject(props.project.name);
+ return sortDatabaseV1List(list);
+});
+
+watch(
+ () => [databaseList.value, props.expr],
+ async () => {
+ // TODO: fetch matched and unmatched database list with expr.
+ matchedDatabaseList.value = databaseList.value;
+ unmatchedDatabaseList.value = [];
+ },
+ {
+ immediate: true,
+ }
+);
+</script>
diff --git a/frontend/src/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue b/frontend/src/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue
new file mode 100644
index 0000000000..7f4c0939a3
--- /dev/null
+++ b/frontend/src/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue
@@ -0,0 +1,63 @@
+<template>
+ <div class="w-full">
+ <div class="w-full flex flex-row justify-between items-center">
+ <span>Database groups</span>
+ <div class="flex flex-row gap-x-2">
+ <NButton>New table group</NButton>
+ <NButton @click="state.showDatabaseGroupPanel = true"
+ >New database group</NButton
+ >
+ </div>
+ </div>
+ <div class="mt-4">
+ <DatabaseGroupTable
+ :database-group-list="databaseGroupList"
+ @edit="handleConfigureDatabaseGroup"
+ />
+ </div>
+ </div>
+
+ <DatabaseGroupPanel
+ v-if="state.showDatabaseGroupPanel"
+ :project="project"
+ :database-group="state.editingDatabaseGroup"
+ @close="state.showDatabaseGroupPanel = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { cloneDeep } from "lodash-es";
+import { computed, onMounted, reactive } from "vue";
+import { useDBGroupStore } from "@/store";
+import { ComposedProject } from "@/types";
+import DatabaseGroupTable from "./DatabaseGroupTable.vue";
+import DatabaseGroupPanel from "./DatabaseGroupPanel.vue";
+import { DatabaseGroup } from "@/types/proto/v1/project_service";
+
+interface LocalState {
+ showDatabaseGroupPanel: boolean;
+ editingDatabaseGroup?: DatabaseGroup;
+}
+
+const props = defineProps<{
+ project: ComposedProject;
+}>();
+
+const dbGroupStore = useDBGroupStore();
+const state = reactive<LocalState>({
+ showDatabaseGroupPanel: false,
+});
+
+const databaseGroupList = computed(() => {
+ return dbGroupStore.getDBGroupListByProjectName(props.project.name);
+});
+
+onMounted(async () => {
+ await dbGroupStore.getOrFetchDBGroupListByProjectName(props.project.name);
+});
+
+const handleConfigureDatabaseGroup = (databaseGroup: DatabaseGroup) => {
+ state.editingDatabaseGroup = cloneDeep(databaseGroup);
+ state.showDatabaseGroupPanel = true;
+};
+</script>
diff --git a/frontend/src/components/v2/Form/ResourceIdField.vue b/frontend/src/components/v2/Form/ResourceIdField.vue
index 637497b9fb..22f95f0a38 100644
--- a/frontend/src/components/v2/Form/ResourceIdField.vue
+++ b/frontend/src/components/v2/Form/ResourceIdField.vue
@@ -79,7 +79,13 @@ interface LocalState {
validatedMessages: ValidatedMessage[];
}
-type ResourceType = "environment" | "instance" | "project" | "idp" | "role";
+type ResourceType =
+ | "environment"
+ | "instance"
+ | "project"
+ | "idp"
+ | "role"
+ | "database-group";
const props = withDefaults(
defineProps<{
diff --git a/frontend/src/layouts/ProjectLayout.vue b/frontend/src/layouts/ProjectLayout.vue
index 0c5d4cf0b0..cddd840db1 100644
--- a/frontend/src/layouts/ProjectLayout.vue
+++ b/frontend/src/layouts/ProjectLayout.vue
@@ -48,6 +48,7 @@ import {
idFromSlug,
hasWorkspacePermissionV1,
hasPermissionInProjectV1,
+ isDev,
} from "../utils";
import ArchiveBanner from "../components/ArchiveBanner.vue";
import { BBTabFilterItem } from "../bbkit/types";
@@ -134,6 +135,11 @@ export default defineComponent({
{ name: t("common.overview"), hash: "overview" },
{ name: t("common.databases"), hash: "databases" },
+ // TODO(steven): remove this after we release the feature.
+ isDev() && isTenantProject.value
+ ? { name: "Database groups", hash: "database-groups" }
+ : null,
+
isTenantProject.value
? null // Hide "Change History" tab for tenant projects
: { name: t("common.change-history"), hash: "change-history" },
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 1c9813f5f5..a45b12f84c 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2182,7 +2182,8 @@
"instance": "Instance",
"project": "Project",
"idp": "Identity Provider",
- "role": "Role"
+ "role": "Role",
+ "database-group": "Database Group"
},
"resource-id": {
"self": "{resource} ID",
diff --git a/frontend/src/plugins/cel/logic/index.ts b/frontend/src/plugins/cel/logic/index.ts
index a80f116f9a..98d86784d5 100644
--- a/frontend/src/plugins/cel/logic/index.ts
+++ b/frontend/src/plugins/cel/logic/index.ts
@@ -1,3 +1,4 @@
export * from "./resolve";
export * from "./build";
export * from "./validate";
+export * from "./stringify";
diff --git a/frontend/src/plugins/cel/logic/resolve.ts b/frontend/src/plugins/cel/logic/resolve.ts
index 737d960444..1271570147 100644
--- a/frontend/src/plugins/cel/logic/resolve.ts
+++ b/frontend/src/plugins/cel/logic/resolve.ts
@@ -125,14 +125,11 @@ const resolveCompareExpr = (expr: CELExpr): CompareExpr => {
const resolveStringExpr = (expr: CELExpr): StringExpr => {
const operator = expr.callExpr!.function as StringOperator;
- const factor = expr.callExpr!.target!;
+ const factor = getFactorName(expr.callExpr!.target!);
const value = expr.callExpr!.args[0];
return {
operator,
- args: [
- factor.identExpr!.name as StringFactor,
- value.constExpr!.stringValue!,
- ],
+ args: [factor as StringFactor, value.constExpr!.stringValue!],
};
};
@@ -165,7 +162,7 @@ const resolveCollectionExpr = (expr: CELExpr): CollectionExpr => {
throw new Error(`cannot resolve expr ${JSON.stringify(expr)}`);
};
-const emptySimpleExpr = (): ConditionGroupExpr => {
+export const emptySimpleExpr = (): ConditionGroupExpr => {
return {
operator: LogicalOperatorList[0],
args: [],
diff --git a/frontend/src/plugins/cel/logic/stringify.ts b/frontend/src/plugins/cel/logic/stringify.ts
new file mode 100644
index 0000000000..1d9ef96b12
--- /dev/null
+++ b/frontend/src/plugins/cel/logic/stringify.ts
@@ -0,0 +1,122 @@
+import {
+ CollectionExpr,
+ CompareExpr,
+ ConditionExpr,
+ EqualityExpr,
+ LogicalExpr,
+ NumberFactor,
+ Operator,
+ SimpleExpr,
+ StringExpr,
+ StringFactor,
+ TimestampFactor,
+ isCollectionExpr,
+ isCompareExpr,
+ isConditionGroupExpr,
+ isEqualityExpr,
+} from "..";
+
+export function convertToCELString(expr: SimpleExpr): string {
+ if (isConditionGroupExpr(expr)) {
+ return convertLogicalExprToCELString(expr);
+ } else {
+ return convertConditionExprToCELString(expr);
+ }
+}
+
+function convertLogicalExprToCELString(expr: LogicalExpr): string {
+ const operator = convertOperatorToCELString(expr.operator);
+ const args = expr.args.map((arg) => convertToCELString(arg));
+ return `(${args.join(` ${operator} `)})`;
+}
+
+function convertConditionExprToCELString(expr: ConditionExpr): string {
+ if (isEqualityExpr(expr)) {
+ return convertEqualityExprToCELString(expr);
+ } else if (isCompareExpr(expr)) {
+ return convertCompareExprToCELString(expr);
+ } else if (isCollectionExpr(expr)) {
+ return convertCollectionExprToCELString(expr);
+ } else {
+ return convertStringExprToCELString(expr);
+ }
+}
+
+function convertEqualityExprToCELString(expr: EqualityExpr): string {
+ const operator = convertOperatorToCELString(expr.operator);
+ const factor = convertFactorToCELString(expr.args[0]);
+ const value = convertValueToCELString(expr.args[1]);
+ return `${factor} ${operator} ${value}`;
+}
+
+function convertCompareExprToCELString(expr: CompareExpr): string {
+ const operator = convertOperatorToCELString(expr.operator);
+ const factor = convertFactorToCELString(expr.args[0]);
+ const value = convertValueToCELString(expr.args[1]);
+ return `${factor} ${operator} ${value}`;
+}
+
+function convertCollectionExprToCELString(expr: CollectionExpr): string {
+ const operator = convertOperatorToCELString(expr.operator);
+ const factor = convertFactorToCELString(expr.args[0]);
+ const values = expr.args[1].map((value) => convertValueToCELString(value));
+ return `${factor} ${operator} [${values.join(", ")}]`;
+}
+
+function convertStringExprToCELString(expr: StringExpr): string {
+ const operator = convertOperatorToCELString(expr.operator);
+ const factor = convertFactorToCELString(expr.args[0]);
+ const value = convertValueToCELString(expr.args[1]);
+ return `${factor}.${operator}(${value})`;
+}
+
+function convertFactorToCELString(
+ factor: StringFactor | NumberFactor | TimestampFactor
+): string {
+ return String(factor);
+}
+
+function convertOperatorToCELString(operator: Operator): string {
+ switch (operator) {
+ case "_&&_":
+ return "&&";
+ case "_||_":
+ return "||";
+ case "_==_":
+ return "==";
+ case "_!=_":
+ return "!=";
+ case "_>_":
+ return ">";
+ case "_>=_":
+ return ">=";
+ case "_<_":
+ return "<";
+ case "_<=_":
+ return "<=";
+ case "@in":
+ return "in";
+ case "contains":
+ return "contains";
+ case "matches":
+ return "matches";
+ case "startsWith":
+ return "startsWith";
+ case "endsWith":
+ return "endsWith";
+ default:
+ throw new Error("Unsupported operator.");
+ }
+}
+
+function convertValueToCELString(value: string | number | Date): string {
+ if (typeof value === "string") {
+ return `"${value}"`;
+ } else if (typeof value === "number") {
+ return value.toString();
+ } else if (value instanceof Date) {
+ return `timestamp("${value.toISOString()}")`;
+ } else {
+ throw new Error("Unsupported value type.");
+ }
+}
diff --git a/frontend/src/plugins/cel/types/factor.ts b/frontend/src/plugins/cel/types/factor.ts
index 6827fe93cf..aa9d61df41 100644
--- a/frontend/src/plugins/cel/types/factor.ts
+++ b/frontend/src/plugins/cel/types/factor.ts
@@ -25,6 +25,7 @@ export const StringFactorList = [
"request.export_format",
// Database/table group related factors
+ "resource.environment_id", // using `environment.resource_id`
"resource.database_name",
"resource.table_name",
] as const;
diff --git a/frontend/src/store/modules/dbGroup.ts b/frontend/src/store/modules/dbGroup.ts
new file mode 100644
index 0000000000..590ed01183
--- /dev/null
+++ b/frontend/src/store/modules/dbGroup.ts
@@ -0,0 +1,96 @@
+import { projectServiceClient } from "@/grpcweb";
+import { DatabaseGroup } from "@/types/proto/v1/project_service";
+import { isEqual } from "lodash-es";
+import { defineStore } from "pinia";
+import { ref } from "vue";
+
+export const useDBGroupStore = defineStore("db-group", () => {
+ const dbGroupMapById = ref<Map<string, DatabaseGroup>>(new Map());
+ const cachedProjectNameSet = ref<Set<string>>(new Set());
+
+ const getOrFetchDBGroupById = async (dbGroupId: string) => {
+ const cached = dbGroupMapById.value.get(dbGroupId);
+ if (cached) return cached;
+
+ const databaseGroup = await projectServiceClient.getDatabaseGroup({
+ name: dbGroupId,
+ });
+ dbGroupMapById.value.set(dbGroupId, databaseGroup);
+ return databaseGroup;
+ };
+
+ const getOrFetchDBGroupListByProjectName = async (projectName: string) => {
+ const hasCache = cachedProjectNameSet.value.has(projectName);
+ if (hasCache) {
+ return Array.from(dbGroupMapById.value.values()).filter((dbGroup) =>
+ dbGroup.name.startsWith(projectName)
+ );
+ }
+
+ const { databaseGroups } = await projectServiceClient.listDatabaseGroups({
+ parent: projectName,
+ });
+ for (const dbGroup of databaseGroups) {
+ dbGroupMapById.value.set(dbGroup.name, dbGroup);
+ }
+ cachedProjectNameSet.value.add(projectName);
+ return databaseGroups;
+ };
+
+ const getDBGroupListByProjectName = (projectName: string) => {
+ return Array.from(dbGroupMapById.value.values()).filter((dbGroup) =>
+ dbGroup.name.startsWith(projectName)
+ );
+ };
+
+ const createDatabaseGroup = async (
+ projectName: string,
+ databaseGroup: DatabaseGroup,
+ databaseGroupId: string
+ ) => {
+ const createdDatabaseGroup = await projectServiceClient.createDatabaseGroup(
+ {
+ parent: projectName,
+ databaseGroup,
+ databaseGroupId,
+ }
+ );
+ dbGroupMapById.value.set(createdDatabaseGroup.name, createdDatabaseGroup);
+ return createdDatabaseGroup;
+ };
+
+ const updateDatabaseGroup = async (databaseGroup: DatabaseGroup) => {
+ const rawDatabaseGroup = dbGroupMapById.value.get(databaseGroup.name);
+ if (!rawDatabaseGroup) {
+ throw new Error("Database group not found");
+ }
+ const updateMask: string[] = [];
+ if (
+ !isEqual(
+ rawDatabaseGroup.databasePlaceholder,
+ databaseGroup.databasePlaceholder
+ )
+ ) {
+ updateMask.push("database_placeholder");
+ }
+ if (!isEqual(rawDatabaseGroup.databaseExpr, databaseGroup.databaseExpr)) {
+ updateMask.push("database_expr");
+ }
+ const updatedDatabaseGroup = await projectServiceClient.updateDatabaseGroup(
+ {
+ databaseGroup,
+ updateMask,
+ }
+ );
+ dbGroupMapById.value.set(updatedDatabaseGroup.name, updatedDatabaseGroup);
+ return updatedDatabaseGroup;
+ };
+
+ return {
+ getOrFetchDBGroupById,
+ getOrFetchDBGroupListByProjectName,
+ getDBGroupListByProjectName,
+ createDatabaseGroup,
+ updateDatabaseGroup,
+ };
+});
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index 10234b8201..fe8a0fb7fa 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -45,6 +45,7 @@ export * from "./workspaceApprovalSetting";
export * from "./review";
export * from "./slowQuery";
export * from "./role";
+export * from "./dbGroup";
export * from "./v1";
diff --git a/frontend/src/utils/databaseGroup/cel.ts b/frontend/src/utils/databaseGroup/cel.ts
new file mode 100644
index 0000000000..78c7dbbefa
--- /dev/null
+++ b/frontend/src/utils/databaseGroup/cel.ts
@@ -0,0 +1,70 @@
+import { celServiceClient } from "@/grpcweb";
+import {
+ ConditionGroupExpr,
+ SimpleExpr,
+ convertToCELString,
+ emptySimpleExpr,
+ isConditionGroupExpr,
+ resolveCELExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+
+interface DatabaseGroupExpr {
+ environmentId: string;
+ conditionGroupExpr: ConditionGroupExpr;
+}
+
+export const stringifyDatabaseGroupExpr = (
+ databaseGroupExpr: DatabaseGroupExpr
+): string => {
+ const { environmentId, conditionGroupExpr } = databaseGroupExpr;
+ return convertToCELString({
+ operator: "_&&_",
+ args: [
+ // Make the environment ID a condition first to avoid confusion when converting from CEL string.
+ {
+ operator: "_==_",
+ args: ["resource.environment_id", environmentId],
+ },
+ conditionGroupExpr,
+ ],
+ });
+};
+
+export const convertDatabaseGroupExprFromCEL = async (
+ cel: string
+): Promise<DatabaseGroupExpr> => {
+ const { expression: celExpr } = await celServiceClient.parse({
+ expression: cel,
+ });
+
+ if (!celExpr || !celExpr.expr) {
+ throw new Error("Invalid CEL expression");
+ }
+
+ const simpleExpr = resolveCELExpr(celExpr.expr);
+ const [environmentId, conditionGroupExpr] =
+ getEnvironmentIdAndConditionExpr(simpleExpr);
+ if (!environmentId) {
+ throw new Error("Invalid CEL expression");
+ }
+
+ return {
+ environmentId,
+ conditionGroupExpr,
+ };
+};
+
+const getEnvironmentIdAndConditionExpr = (
+ expr: SimpleExpr
+): [string, ConditionGroupExpr] => {
+ if (expr.operator !== "_&&_") {
+ throw ["", emptySimpleExpr()];
+ }
+
+ const [left, right] = expr.args;
+ return [
+ left.args[1] as string,
+ isConditionGroupExpr(right) ? right : wrapAsGroup(right),
+ ];
+};
diff --git a/frontend/src/views/ProjectDetail.vue b/frontend/src/views/ProjectDetail.vue
index 8ee18b9362..3024ecbbce 100644
--- a/frontend/src/views/ProjectDetail.vue
+++ b/frontend/src/views/ProjectDetail.vue
@@ -12,6 +12,9 @@
/>
<ProjectDatabasesPanel v-else :database-list="databaseV1List" />
</template>
+ <template v-if="isDev && hash === 'database-groups'">
+ <ProjectDatabaseGroupPanel :project="projectV1" />
+ </template>
<template v-if="hash === 'change-history'">
<ProjectMigrationHistoryPanel
id="change-history"
@@ -77,6 +80,7 @@ import {
useProjectV1Store,
} from "@/store";
import { TenantMode } from "@/types/proto/v1/project_service";
+import ProjectDatabaseGroupPanel from "@/components/DatabaseGroup/ProjectDatabaseGroupPanel.vue";
const props = defineProps({
projectWebhookSlug: {