Skip to content

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

feat: support cel in database resource selector (#18551)

ecmadao31e31ee4222f
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
index 57d6888561..6a061b0d48 100644
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
+++ b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
@@ -84,7 +84,7 @@
</div>
<ExprEditor
:expr="state.conditionExpr"
- :allow-admin="allowAdmin"
+ :readonly="!allowAdmin"
:factor-list="factorList"
:option-config-map="optionConfigMap"
@update="handleUpdate"
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts b/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
index 3ccf4466c1..5777a13b91 100644
--- a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
+++ b/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
@@ -140,6 +140,26 @@ export const getProjectIdOptions = (projects: Project[]) => {
});
};
+export const getDatabasFullNameOptions = (databases: ComposedDatabase[]) => {
+ return databases.map<SelectOption>((database) => {
+ return {
+ label: database.name,
+ value: database.name,
+ render: getRenderOptionFunc({
+ name: database.name,
+ title: () =>
+ h(RichDatabaseName, {
+ database,
+ showEngineIcon: true,
+ showInstance: true,
+ showProject: false,
+ showArrow: true,
+ }),
+ }),
+ };
+ });
+};
+
export const getDatabaseIdOptions = (databases: ComposedDatabase[]) => {
return databases.map<SelectOption>((database) => {
return {
diff --git a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
index 7a9c5e48ce..86599db3cc 100644
--- a/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
+++ b/frontend/src/components/DatabaseGroup/DatabaseGroupForm.vue
@@ -34,7 +34,7 @@
</p>
<ExprEditor
:expr="state.expr"
- :allow-admin="!readonly"
+ :readonly="readonly"
:factor-list="FactorList"
:option-config-map="getDatabaseGroupOptionConfigMap(project.name)"
/>
diff --git a/frontend/src/components/ExprEditor/Condition.vue b/frontend/src/components/ExprEditor/Condition.vue
index 7c1f11b22b..ecf52116ad 100644
--- a/frontend/src/components/ExprEditor/Condition.vue
+++ b/frontend/src/components/ExprEditor/Condition.vue
@@ -9,9 +9,9 @@
<ValueInput :expr="expr" />
<NButton
- v-if="allowAdmin"
size="small"
type="default"
+ :disabled="readonly"
:style="'shrink: 0;padding-left: 0;padding-right: 0;--n-width: 28px;--n-color: white;'"
@click="$emit('remove')"
>
@@ -37,7 +37,7 @@ const emit = defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
watch(
() => props.expr,
diff --git a/frontend/src/components/ExprEditor/ConditionGroup.vue b/frontend/src/components/ExprEditor/ConditionGroup.vue
index 7344490272..42f99661b1 100644
--- a/frontend/src/components/ExprEditor/ConditionGroup.vue
+++ b/frontend/src/components/ExprEditor/ConditionGroup.vue
@@ -25,12 +25,13 @@
</i18n-t>
</template>
</div>
- <div v-if="allowAdmin" class="flex items-center justify-end">
+ <div class="flex items-center justify-end">
<NButton
size="tiny"
quaternary
type="default"
:style="`shrink: 0; padding-left: 0; padding-right: 0; --n-width: 22px;`"
+ :disabled="readonly"
@click="emit('remove')"
>
<heroicons:trash class="w-3.5 h-3.5" />
@@ -50,10 +51,11 @@
<div class="w-14 shrink-0">
<div v-if="i === 0" class="pl-1.5 pt-1 text-control">Where</div>
<NSelect
- v-else-if="i === 1 && allowAdmin"
+ v-else-if="i === 1"
v-model:value="operator"
:options="OPERATORS"
:consistent-menu-width="false"
+ :disabled="readonly"
size="small"
@update:value="$emit('update')"
/>
@@ -84,14 +86,14 @@
</div>
</div>
- <div v-if="!root && allowAdmin" class="pl-1.5 pb-1">
- <NButton size="small" quaternary @click="addCondition">
+ <div v-if="!root" class="pl-1.5 pb-1">
+ <NButton size="small" quaternary :disabled="readonly" @click="addCondition">
<template #icon
><heroicons:plus class="w-4 h-4 text-gray-500"
/></template>
<span class="text-gray-500">{{ $t("cel.condition.add") }}</span>
</NButton>
- <NButton size="small" quaternary @click="addRawString">
+ <NButton size="small" quaternary :disabled="readonly" @click="addRawString">
<template #icon
><heroicons:plus class="w-4 h-4 text-gray-500"
/></template>
@@ -101,12 +103,12 @@
</NButton>
</div>
- <div v-if="root && allowAdmin" class="flex gap-x-1">
- <NButton size="small" quaternary @click="addCondition">
+ <div v-if="root" class="flex gap-x-1">
+ <NButton size="small" quaternary :disabled="readonly" @click="addCondition">
<template #icon><heroicons:plus class="w-4 h-4" /></template>
<span>{{ $t("cel.condition.add") }}</span>
</NButton>
- <NButton size="small" quaternary @click="addConditionGroup">
+ <NButton size="small" quaternary :disabled="readonly" @click="addConditionGroup">
<template #icon><heroicons:plus class="w-4 h-4" /></template>
<span>{{ $t("cel.condition.add-group") }}</span>
<NTooltip>
@@ -122,6 +124,7 @@
v-if="enableRawExpression"
size="small"
quaternary
+ :disabled="readonly"
@click="addRawString"
>
<template #icon><heroicons:plus class="w-4 h-4" /></template>
@@ -165,12 +168,8 @@ const emit = defineEmits<{
(event: "update"): void;
}>();
-const {
- allowAdmin,
- enableRawExpression,
- factorList,
- factorOperatorOverrideMap,
-} = useExprEditorContext();
+const { readonly, enableRawExpression, factorList, factorOperatorOverrideMap } =
+ useExprEditorContext();
const operator = computed({
get() {
diff --git a/frontend/src/components/ExprEditor/ExprEditor.vue b/frontend/src/components/ExprEditor/ExprEditor.vue
index 8492aa9ebd..b44e308976 100644
--- a/frontend/src/components/ExprEditor/ExprEditor.vue
+++ b/frontend/src/components/ExprEditor/ExprEditor.vue
@@ -13,14 +13,14 @@ import { type OptionConfig, provideExprEditorContext } from "./context";
const props = withDefaults(
defineProps<{
expr: ConditionGroupExpr;
- allowAdmin?: boolean;
+ readonly?: boolean;
enableRawExpression?: boolean;
factorList: Factor[];
optionConfigMap?: Map<Factor, OptionConfig>;
factorOperatorOverrideMap?: Map<Factor, Operator[]>;
}>(),
{
- allowAdmin: false,
+ readonly: false,
enableRawExpression: true,
factorOperatorOverrideMap: undefined,
optionConfigMap: () => new Map(),
@@ -32,7 +32,7 @@ defineEmits<{
}>();
provideExprEditorContext({
- allowAdmin: toRef(props, "allowAdmin"),
+ readonly: toRef(props, "readonly"),
enableRawExpression: toRef(props, "enableRawExpression"),
factorList: toRef(props, "factorList"),
optionConfigMap: toRef(props, "optionConfigMap"),
diff --git a/frontend/src/components/ExprEditor/RawString.vue b/frontend/src/components/ExprEditor/RawString.vue
index 9446b957ca..a7efce127f 100644
--- a/frontend/src/components/ExprEditor/RawString.vue
+++ b/frontend/src/components/ExprEditor/RawString.vue
@@ -11,10 +11,10 @@
/>
<NButton
- v-if="allowAdmin"
size="small"
type="default"
:style="'shrink: 0;padding-left: 0;padding-right: 0;--n-width: 28px;--n-color: white;'"
+ :disabled="readonly"
@click="$emit('remove')"
>
<heroicons:trash class="w-3.5 h-3.5" />
@@ -38,7 +38,7 @@ const emit = defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
watch(
() => props.expr,
diff --git a/frontend/src/components/ExprEditor/components/FactorSelect.vue b/frontend/src/components/ExprEditor/components/FactorSelect.vue
index e399a6c1d6..3be26137bc 100644
--- a/frontend/src/components/ExprEditor/components/FactorSelect.vue
+++ b/frontend/src/components/ExprEditor/components/FactorSelect.vue
@@ -3,7 +3,7 @@
v-model:value="factor"
:options="options"
:consistent-menu-width="false"
- :disabled="!allowAdmin"
+ :disabled="readonly"
size="small"
style="width: auto; min-width: 7rem; shrink: 0"
/>
@@ -21,7 +21,7 @@ const props = defineProps<{
expr: ConditionExpr;
}>();
-const { allowAdmin, factorList } = useExprEditorContext();
+const { readonly, factorList } = useExprEditorContext();
const factor = computed({
get() {
diff --git a/frontend/src/components/ExprEditor/components/MultiSelect.vue b/frontend/src/components/ExprEditor/components/MultiSelect.vue
index 2b108ad6f6..26c63e1f29 100644
--- a/frontend/src/components/ExprEditor/components/MultiSelect.vue
+++ b/frontend/src/components/ExprEditor/components/MultiSelect.vue
@@ -9,7 +9,7 @@
:consistent-menu-width="false"
:clear-filter-after-select="false"
:placeholder="$t('cel.condition.select-value')"
- :disabled="!allowAdmin"
+ :disabled="readonly"
max-tag-count="responsive"
size="small"
style="min-width: 12rem; width: auto; max-width: 20rem; overflow-x: hidden"
@@ -51,7 +51,7 @@ const emit = defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
const state = reactive<LocalState>({
loading: false,
rawOptionList: [],
diff --git a/frontend/src/components/ExprEditor/components/MultiStringInput.vue b/frontend/src/components/ExprEditor/components/MultiStringInput.vue
index 08655fd161..33425b50dc 100644
--- a/frontend/src/components/ExprEditor/components/MultiStringInput.vue
+++ b/frontend/src/components/ExprEditor/components/MultiStringInput.vue
@@ -8,7 +8,7 @@
:show="false"
:consistent-menu-width="false"
:placeholder="$t('cel.condition.input-value-press-enter')"
- :disabled="!allowAdmin"
+ :disabled="readonly"
max-tag-count="responsive"
size="small"
style="min-width: 16rem; width: auto; overflow-x: hidden"
@@ -30,7 +30,7 @@ const emit = defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
const onUpdate = (values: string[]) => {
emit(
diff --git a/frontend/src/components/ExprEditor/components/NumberInput.vue b/frontend/src/components/ExprEditor/components/NumberInput.vue
index 0b76fd4ddc..e0a0cd93e3 100644
--- a/frontend/src/components/ExprEditor/components/NumberInput.vue
+++ b/frontend/src/components/ExprEditor/components/NumberInput.vue
@@ -3,7 +3,7 @@
:value="value"
:show-button="false"
:placeholder="$t('cel.condition.input-value')"
- :disabled="!allowAdmin"
+ :disabled="readonly"
size="small"
style="width: auto; max-width: 5rem; overflow-x: hidden"
@update:value="$emit('update:value', $event ?? 0)"
@@ -23,5 +23,5 @@ defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
</script>
diff --git a/frontend/src/components/ExprEditor/components/OperatorSelect.vue b/frontend/src/components/ExprEditor/components/OperatorSelect.vue
index 27ed55b945..b97be726d6 100644
--- a/frontend/src/components/ExprEditor/components/OperatorSelect.vue
+++ b/frontend/src/components/ExprEditor/components/OperatorSelect.vue
@@ -4,7 +4,7 @@
v-model:value="operator"
:options="options"
:consistent-menu-width="false"
- :disabled="!allowAdmin"
+ :disabled="readonly"
size="small"
style="width: auto; max-width: 7rem; min-width: 2.5rem; shrink: 0"
/>
@@ -27,7 +27,7 @@ const props = defineProps<{
}>();
const context = useExprEditorContext();
-const { allowAdmin, factorOperatorOverrideMap } = context;
+const { readonly, factorOperatorOverrideMap } = context;
const operator = computed({
get() {
diff --git a/frontend/src/components/ExprEditor/components/SingleSelect.vue b/frontend/src/components/ExprEditor/components/SingleSelect.vue
index 6c05a40a7d..ce2f203e7c 100644
--- a/frontend/src/components/ExprEditor/components/SingleSelect.vue
+++ b/frontend/src/components/ExprEditor/components/SingleSelect.vue
@@ -7,7 +7,7 @@
:consistent-menu-width="false"
:filterable="true"
:placeholder="$t('cel.condition.select-value')"
- :disabled="!allowAdmin"
+ :disabled="readonly"
size="small"
style="min-width: 7rem; width: auto; overflow-x: hidden"
@search="handleSearch"
@@ -40,7 +40,7 @@ defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
const state = reactive<LocalState>({
loading: false,
rawOptionList: [],
diff --git a/frontend/src/components/ExprEditor/components/StringInput.vue b/frontend/src/components/ExprEditor/components/StringInput.vue
index 29b6b65020..35ad4ed8a2 100644
--- a/frontend/src/components/ExprEditor/components/StringInput.vue
+++ b/frontend/src/components/ExprEditor/components/StringInput.vue
@@ -2,7 +2,7 @@
<NInput
:value="value"
:placeholder="$t('cel.condition.input-value')"
- :disabled="!allowAdmin"
+ :disabled="readonly"
size="small"
style="min-width: 7rem; width: auto; overflow-x: hidden"
@update:value="$emit('update:value', $event)"
@@ -22,5 +22,5 @@ defineEmits<{
}>();
const context = useExprEditorContext();
-const { allowAdmin } = context;
+const { readonly } = context;
</script>
diff --git a/frontend/src/components/ExprEditor/context.ts b/frontend/src/components/ExprEditor/context.ts
index e7ff137006..ce7a5e0038 100644
--- a/frontend/src/components/ExprEditor/context.ts
+++ b/frontend/src/components/ExprEditor/context.ts
@@ -9,7 +9,7 @@ export type OptionConfig = {
};
export type ExprEditorContext = {
- allowAdmin: Ref<boolean>;
+ readonly: Ref<boolean>;
enableRawExpression: Ref<boolean>;
factorList: Ref<Factor[]>;
optionConfigMap: Ref<Map<Factor, OptionConfig>>;
diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
index c00bb105e0..0b797ba2fa 100644
--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
@@ -17,7 +17,7 @@
:render-target-list="renderTargetList"
/>
<div
- v-if="initializing"
+ v-if="initializeStatus !== 'DONE'"
class="z-1 absolute inset-0 bg-white bg-opacity-80 flex flex-row justify-center items-center"
>
<BBSpin size="large" />
@@ -30,7 +30,7 @@ import { useDebounceFn } from "@vueuse/core";
import { orderBy, uniqBy } from "lodash-es";
import type { TransferRenderSourceList, TreeOption } from "naive-ui";
import { NButton, NTransfer, NTree } from "naive-ui";
-import { computed, h, onMounted, ref, watch } from "vue";
+import { computed, h, onMounted, ref, watch, watchEffect } from "vue";
import { useI18n } from "vue-i18n";
import { BBSpin } from "@/bbkit";
import AdvancedSearch from "@/components/AdvancedSearch";
@@ -149,7 +149,7 @@ watch(
const selectedValueList = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);
const indeterminateKeys = ref<string[]>([]);
-const initializing = ref(true);
+const initializeStatus = ref<"PENDING" | "PROCESSING" | "DONE">("PENDING");
const databaseList = ref<ComposedDatabase[]>([]);
const fetchDataState = ref<{
nextPageToken?: string;
@@ -263,44 +263,99 @@ const fetchDatabaseList = useDebounceFn(async () => {
}
}, DEBOUNCE_SEARCH_DELAY);
+const refreshData = async () => {
+ fetchDataState.value.nextPageToken = "";
+ expandedKeys.value = [];
+ await fetchDatabaseList();
+
+ if (!params.value.query && params.value.scopes.length === 1) {
+ databaseList.value = uniqBy(
+ [
+ ...databaseList.value,
+ ...props.databaseResources.map((resource) =>
+ databaseStore.getDatabaseByName(resource.databaseFullName)
+ ),
+ ],
+ (db) => db.name
+ );
+ }
+
+ if (databaseFilter.value.table) {
+ // expand all
+ for (const database of databaseList.value) {
+ await collectExpandedKeys({
+ database: database.name,
+ table: databaseFilter.value.table,
+ });
+ }
+ }
+};
+
watch(
() => databaseFilter.value,
async () => {
- fetchDataState.value.nextPageToken = "";
- expandedKeys.value = [];
- await fetchDatabaseList();
- if (!params.value.query && params.value.scopes.length === 1) {
- databaseList.value = uniqBy(
- [
- ...databaseList.value,
- ...props.databaseResources.map((resource) =>
- databaseStore.getDatabaseByName(resource.databaseFullName)
- ),
- ],
- (db) => db.name
- );
- }
-
- if (databaseFilter.value.table) {
- // expand all
- for (const database of databaseList.value) {
- await collectExpandedKeys({
- database: database.name,
- table: databaseFilter.value.table,
- });
- }
- }
+ await refreshData();
},
- {
- deep: true,
- immediate: true,
- }
+ { deep: true }
);
onMounted(async () => {
await batchGetOrFetchDatabases(
props.databaseResources.map((resource) => resource.databaseFullName)
);
+ await refreshData();
+
+ if (databaseList.value.length === 0) {
+ initializeStatus.value = "DONE";
+ }
+});
+
+const parseKeyToPathes = (key: string): string[] => {
+ if (!key) {
+ return [];
+ }
+
+ const sections = key.split("/");
+ const nodePrefx = new Set(["schemas", "tables", "columns"]);
+ const resp: string[] = [];
+ const tmp: string[] = [];
+
+ for (const section of sections) {
+ if (nodePrefx.has(section)) {
+ resp.push(tmp.join("/"));
+ }
+ tmp.push(section);
+ }
+
+ if (tmp.length > 0) {
+ resp.push(tmp.join("/"));
+ }
+
+ return resp;
+};
+
+const sourceTreeOptions = computed(() => {
+ return mapTreeOptions({
+ databaseList: databaseList.value,
+ includeCloumn: props.includeCloumn,
+ filterValueList: filterTableList.value,
+ });
+});
+
+const sourceTransferOptions = computed((): DatabaseTreeOption[] => {
+ const options = flattenTreeOptions(sourceTreeOptions.value);
+ return options;
+});
+
+watchEffect(async () => {
+ if (initializeStatus.value !== "PENDING") {
+ return;
+ }
+ if (sourceTransferOptions.value.length === 0) {
+ return;
+ }
+
+ initializeStatus.value = "PROCESSING";
const selectedKeys: string[] = [];
const databaseNames = new Set<string>();
@@ -370,44 +425,7 @@ onMounted(async () => {
expandedKeys.value = [...newExpandedKeys];
indeterminateKeys.value = [...newIndeterminateKeys];
- initializing.value = false;
-});
-
-const parseKeyToPathes = (key: string): string[] => {
- if (!key) {
- return [];
- }
-
- const sections = key.split("/");
- const nodePrefx = new Set(["schemas", "tables", "columns"]);
- const resp: string[] = [];
- const tmp: string[] = [];
-
- for (const section of sections) {
- if (nodePrefx.has(section)) {
- resp.push(tmp.join("/"));
- }
- tmp.push(section);
- }
-
- if (tmp.length > 0) {
- resp.push(tmp.join("/"));
- }
-
- return resp;
-};
-
-const sourceTreeOptions = computed(() => {
- return mapTreeOptions({
- databaseList: databaseList.value,
- includeCloumn: props.includeCloumn,
- filterValueList: filterTableList.value,
- });
-});
-
-const sourceTransferOptions = computed((): DatabaseTreeOption[] => {
- const options = flattenTreeOptions(sourceTreeOptions.value);
- return options;
+ initializeStatus.value = "DONE";
});
const onTreeNodeLoad = async (node: TreeOption) => {
diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue
index 8ef5f71101..0084c4bd6d 100644
--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue
+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/index.vue
@@ -1,21 +1,27 @@
<template>
<div class="w-full mb-2">
<NRadioGroup
- v-if="allowSelectAll"
- v-model:value="state.allDatabases"
- :disabled="disabled"
+ :value="state.radioValue"
+ :disabled="disabled || state.loading"
class="w-full flex! flex-row justify-start items-center gap-4"
+ @update:value="onSelectUpdate"
>
<NTooltip trigger="hover">
<template #trigger>
<NRadio
- :value="true"
+ :value="'ALL'"
:label="$t('issue.grant-request.all-databases')"
/>
</template>
{{ $t("issue.grant-request.all-databases-tip") }}
</NTooltip>
- <NRadio class="leading-6!" :value="false" :disabled="!project">
+ <NRadio class="leading-6!" :value="'EXPRESSION'" :disabled="!project">
+ <div class="flex items-center gap-x-1">
+ <FeatureBadge :feature="requiredFeature" />
+ <span>{{ $t("issue.grant-request.use-cel") }}</span>
+ </div>
+ </NRadio>
+ <NRadio class="leading-6!" :value="'SELECT'" :disabled="!project">
<div class="flex items-center gap-x-1">
<FeatureBadge :feature="requiredFeature" />
<span>{{ $t("issue.grant-request.manually-select") }}</span>
@@ -24,17 +30,24 @@
</NRadioGroup>
</div>
<div
- v-if="!state.allDatabases"
+ v-if="state.radioValue === 'SELECT'"
class="w-full flex flex-row justify-start items-center"
>
<DatabaseResourceSelector
- v-if="project"
v-model:database-resources="state.databaseResources"
- :disabled="disabled"
+ :disabled="disabled || state.loading"
:project-name="project.name"
:include-cloumn="includeCloumn"
/>
</div>
+ <ExprEditor
+ v-if="state.radioValue === 'EXPRESSION'"
+ :expr="state.expr"
+ :readonly="disabled || state.loading"
+ :factor-list="factorList"
+ :option-config-map="factorOptionConfigMap"
+ :factor-operator-override-map="factorOperatorOverrideMap"
+ />
<FeatureModal
:open="state.showFeatureModal"
:feature="requiredFeature"
@@ -43,16 +56,46 @@
</template>
<script lang="ts" setup>
+import { cloneDeep, head } from "lodash-es";
import { NRadio, NRadioGroup, NTooltip } from "naive-ui";
-import { computed, onMounted, reactive, watch } from "vue";
+import { computed, reactive, watch } from "vue";
+import { getDatabasFullNameOptions } from "@/components/CustomApproval/Settings/components/common";
+import ExprEditor from "@/components/ExprEditor";
+import { type OptionConfig } from "@/components/ExprEditor/context";
import { FeatureBadge, FeatureModal } from "@/components/FeatureGuard";
-import { hasFeature, useProjectByName } from "@/store";
+import type { ConditionGroupExpr, Factor, Operator } from "@/plugins/cel";
+import {
+ buildCELExpr,
+ emptySimpleExpr,
+ resolveCELExpr,
+ validateSimpleExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+import { hasFeature, useDatabaseV1Store, useProjectByName } from "@/store";
import type { DatabaseResource } from "@/types";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import {
+ batchConvertCELStringToParsedExpr,
+ getDefaultPagination,
+} from "@/utils";
+import {
+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,
+ CEL_ATTRIBUTE_RESOURCE_DATABASE,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+} from "@/utils/cel-attributes";
+import {
+ convertFromExpr,
+ stringifyConditionExpression,
+} from "@/utils/issue/cel";
import DatabaseResourceSelector from "./DatabaseResourceSelector.vue";
+type RadioValue = "ALL" | "EXPRESSION" | "SELECT";
+
interface LocalState {
- allDatabases: boolean;
+ loading: boolean;
+ radioValue?: RadioValue;
+ expr: ConditionGroupExpr;
showFeatureModal: boolean;
databaseResources: DatabaseResource[];
}
@@ -63,55 +106,176 @@ const props = withDefaults(
projectName: string;
requiredFeature: PlanFeature;
includeCloumn: boolean;
- allowSelectAll?: boolean;
databaseResources?: DatabaseResource[];
}>(),
{
disabled: false,
- allowSelectAll: true,
databaseResources: undefined,
}
);
-const emit = defineEmits<{
- (
- event: "update:database-resources",
- databaseResources?: DatabaseResource[]
- ): void;
-}>();
-
const state = reactive<LocalState>({
- allDatabases:
- props.allowSelectAll && (props.databaseResources || []).length === 0,
+ loading: false,
showFeatureModal: false,
databaseResources: props.databaseResources || [],
+ expr: wrapAsGroup(emptySimpleExpr()),
});
+const convertToDatabaseResourceList = async (expr: ConditionGroupExpr) => {
+ try {
+ const parsedExpr = await buildCELExpr(expr);
+ if (!parsedExpr) {
+ return;
+ }
+ const conditionExpr = convertFromExpr(parsedExpr);
+ return conditionExpr.databaseResources;
+ } catch {
+ return;
+ }
+};
+
+const convertToConditionGroupExpr = async (
+ databaseResources: DatabaseResource[]
+) => {
+ if (databaseResources.length === 0) {
+ return wrapAsGroup(emptySimpleExpr());
+ }
+
+ try {
+ const expression = stringifyConditionExpression({
+ databaseResources,
+ });
+
+ const parsedExprs = await batchConvertCELStringToParsedExpr([expression]);
+ const celExpr = head(parsedExprs);
+ if (celExpr) {
+ return wrapAsGroup(resolveCELExpr(celExpr));
+ }
+ } catch {
+ return;
+ }
+};
+
+const onSelectUpdate = async (select: RadioValue) => {
+ if (!hasRequiredFeature.value && select !== "ALL") {
+ state.showFeatureModal = true;
+ return;
+ }
+
+ state.loading = true;
+ if (select === "EXPRESSION" && state.radioValue === "SELECT") {
+ // parse DatabaseResource[] to ConditionGroupExpr
+ const expr = await convertToConditionGroupExpr(state.databaseResources);
+ if (expr) {
+ state.expr = expr;
+ }
+ } else if (select === "SELECT" && state.radioValue === "EXPRESSION") {
+ // parse ConditionGroupExpr to DatabaseResource[]
+ const resources = await convertToDatabaseResourceList(state.expr);
+ if (resources) {
+ state.databaseResources = resources;
+ }
+ }
+ state.radioValue = select;
+ state.loading = false;
+};
+
+watch(
+ () => props.databaseResources,
+ async (databaseResources) => {
+ state.databaseResources = cloneDeep(databaseResources ?? []);
+ if (!databaseResources || databaseResources.length <= 0) {
+ state.radioValue = "ALL";
+ return;
+ }
+
+ state.loading = true;
+ const expr = await convertToConditionGroupExpr(databaseResources);
+ if (expr) {
+ state.expr = expr;
+ state.radioValue = "EXPRESSION";
+ } else {
+ // fallback
+ state.radioValue = "SELECT";
+ }
+ state.loading = false;
+ },
+ { immediate: true, deep: true }
+);
+
const { project } = useProjectByName(computed(() => props.projectName));
const hasRequiredFeature = computed(() => hasFeature(props.requiredFeature));
+const dbStore = useDatabaseV1Store();
-onMounted(() => {
- if (props.databaseResources && props.databaseResources.length > 0) {
- state.allDatabases = false;
+const factorList = computed((): Factor[] => {
+ const list: Factor[] = [
+ CEL_ATTRIBUTE_RESOURCE_DATABASE,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ ];
+ if (props.includeCloumn) {
+ list.push(CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME);
}
+ return list;
});
-watch(
- () => [state.allDatabases, state.databaseResources],
- () => {
- if (state.allDatabases) {
- emit("update:database-resources", undefined);
+const factorOperatorOverrideMap = new Map<Factor, Operator[]>([
+ [CEL_ATTRIBUTE_RESOURCE_DATABASE, ["_==_", "@in"]],
+ [CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME, ["_==_"]],
+ [CEL_ATTRIBUTE_RESOURCE_TABLE_NAME, ["_==_", "@in"]],
+ [CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME, ["_==_", "@in"]],
+]);
+
+const factorOptionConfigMap = computed((): Map<Factor, OptionConfig> => {
+ return factorList.value.reduce((map, factor) => {
+ if (factor !== CEL_ATTRIBUTE_RESOURCE_DATABASE) {
+ map.set(factor, {
+ remote: false,
+ options: [],
+ });
} else {
- if (!hasRequiredFeature.value) {
- state.showFeatureModal = true;
- state.allDatabases = true;
- return;
+ map.set(factor, {
+ remote: true,
+ options: [],
+ search: async (keyword: string) => {
+ return dbStore
+ .fetchDatabases({
+ pageSize: getDefaultPagination(),
+ parent: props.projectName,
+ filter: {
+ query: keyword,
+ },
+ })
+ .then((resp) => getDatabasFullNameOptions(resp.databases));
+ },
+ });
+ }
+ return map;
+ }, new Map<Factor, OptionConfig>());
+});
+
+defineExpose({
+ getDatabaseResources: async () => {
+ switch (state.radioValue) {
+ case "SELECT":
+ return state.databaseResources;
+ case "EXPRESSION": {
+ const resources = await convertToDatabaseResourceList(state.expr);
+ return resources;
}
- emit("update:database-resources", state.databaseResources);
+ default:
+ return undefined;
}
},
- {
- immediate: true,
- }
-);
+ isValid: computed(() => {
+ switch (state.radioValue) {
+ case "SELECT":
+ return state.databaseResources.length > 0;
+ case "EXPRESSION":
+ return validateSimpleExpr(state.expr);
+ default:
+ return true;
+ }
+ }),
+});
</script>
diff --git a/frontend/src/components/GrantRequestPanel/GrantRequestPanel.vue b/frontend/src/components/GrantRequestPanel/GrantRequestPanel.vue
index ca340ea696..35f66eda2c 100644
--- a/frontend/src/components/GrantRequestPanel/GrantRequestPanel.vue
+++ b/frontend/src/components/GrantRequestPanel/GrantRequestPanel.vue
@@ -15,7 +15,7 @@
ref="formRef"
class="w-full"
:project-name="projectName"
- :binding="state.binding"
+ :binding="binding"
:allow-remove="false"
:disable-member-change="true"
:require-reason="project.enforceIssueTitle"
@@ -47,7 +47,7 @@ import { DurationSchema } from "@bufbuild/protobuf/wkt";
import dayjs from "dayjs";
import { uniq } from "lodash-es";
import { NButton } from "naive-ui";
-import { computed, reactive, ref } from "vue";
+import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import AddProjectMemberForm from "@/components/ProjectMember/AddProjectMember/AddProjectMemberForm.vue";
@@ -57,7 +57,6 @@ import { PROJECT_V1_ROUTE_ISSUE_DETAIL_V1 } from "@/router/dashboard/projectV1";
import { useCurrentUserV1, useProjectV1Store } from "@/store";
import type { DatabaseResource } from "@/types";
import { getUserEmailInBinding } from "@/types";
-import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import { BindingSchema } from "@/types/proto-es/v1/iam_policy_pb";
import {
CreateIssueRequestSchema,
@@ -72,10 +71,6 @@ import {
generateIssueTitle,
} from "@/utils";
-interface LocalState {
- binding: Binding;
-}
-
const props = withDefaults(
defineProps<{
projectName: string;
@@ -101,12 +96,13 @@ const currentUser = useCurrentUserV1();
const projectStore = useProjectV1Store();
const router = useRouter();
-const state = reactive<LocalState>({
- binding: create(BindingSchema, {
+const binding = computed(() => {
+ return create(BindingSchema, {
role: props.role,
members: [getUserEmailInBinding(currentUser.value.email)],
- }),
+ });
});
+
const formRef = ref<InstanceType<typeof AddProjectMemberForm>>();
const project = computed(() =>
@@ -122,10 +118,15 @@ const doCreateIssue = async () => {
return;
}
+ const binding = await formRef.value?.getBinding();
+ if (!binding) {
+ return;
+ }
+
const grantRequest = create(GrantRequestSchema, {
- role: state.binding.role,
+ role: binding.role,
user: `users/${currentUser.value.email}`,
- condition: state.binding.condition,
+ condition: binding.condition,
expiration: formRef.value?.expirationTimestampInMS
? create(DurationSchema, {
seconds: BigInt(
@@ -135,21 +136,23 @@ const doCreateIssue = async () => {
: undefined,
});
+ const databaseResources = await formRef.value?.getDatabaseResources();
+
const newIssue = create(IssueSchema, {
title: project.value.enforceIssueTitle
? `[${t("issue.title.request-role")}] ${formRef.value?.reason}`
: generateIssueTitle(
"bb.issue.grant.request",
uniq(
- formRef.value?.databaseResources?.map(
+ databaseResources?.map(
(databaseResource) => databaseResource.databaseFullName
)
),
t("issue.title.request-specific-role", {
- role: displayRoleTitle(state.binding.role),
+ role: displayRoleTitle(binding.role),
})
),
- description: state.binding.condition?.description,
+ description: binding.condition?.description,
type: NewIssue_Type.GRANT_REQUEST,
grantRequest,
});
diff --git a/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMemberForm.vue b/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMemberForm.vue
index a23e1e8a19..6cdfdb19fd 100644
--- a/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMemberForm.vue
+++ b/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMemberForm.vue
@@ -53,7 +53,8 @@
<RequiredStar />
</div>
<QuerierDatabaseResourceForm
- v-model:database-resources="state.databaseResources"
+ ref="databaseResourceFormRef"
+ :database-resources="databaseResources"
:project-name="projectName"
:required-feature="PlanFeature.FEATURE_IAM"
:include-cloumn="false"
@@ -76,17 +77,16 @@
</template>
<script lang="ts" setup>
-/* eslint-disable vue/no-mutating-props */
-import { isUndefined } from "lodash-es";
+import { create } from "@bufbuild/protobuf";
import { NButton, NInput } from "naive-ui";
-import { computed, reactive, ref, watch } from "vue";
+import { computed, reactive, ref } from "vue";
import ExpirationSelector from "@/components/ExpirationSelector.vue";
import QuerierDatabaseResourceForm from "@/components/GrantRequestPanel/DatabaseResourceForm/index.vue";
import MembersBindingSelect from "@/components/Member/MembersBindingSelect.vue";
import RequiredStar from "@/components/RequiredStar.vue";
import { RoleSelect } from "@/components/v2/Select";
import { type DatabaseResource, PresetRoleType } from "@/types";
-import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
+import { type Binding, BindingSchema } from "@/types/proto-es/v1/iam_policy_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { checkRoleContainsAnyPermission } from "@/utils";
import { buildConditionExpr } from "@/utils/issue/cel";
@@ -118,8 +118,6 @@ interface LocalState {
role: string;
reason: string;
expirationTimestampInMS?: number;
- // Querier and exporter options.
- databaseResources?: DatabaseResource[];
databaseId?: string;
}
@@ -128,10 +126,6 @@ const getInitialState = (): LocalState => {
role: props.binding.role,
memberList: props.binding.members,
reason: "",
- databaseResources:
- props.databaseResources && props.databaseResources.length > 0
- ? props.databaseResources.map((r) => ({ ...r }))
- : undefined,
};
return defaultState;
@@ -139,42 +133,32 @@ const getInitialState = (): LocalState => {
const state = reactive<LocalState>(getInitialState());
const expirationSelectorRef = ref<InstanceType<typeof ExpirationSelector>>();
+const databaseResourceFormRef =
+ ref<InstanceType<typeof QuerierDatabaseResourceForm>>();
-watch(
- () => state.role,
- (newRole, oldRole) => {
- // Only reset databaseResources when role actually changes, not on initial mount
- if (oldRole !== undefined) {
- state.databaseResources =
- props.databaseResources && props.databaseResources.length > 0
- ? props.databaseResources.map((r) => ({ ...r }))
- : undefined;
- }
- }
-);
-
-watch(
- () => state,
- () => {
- props.binding.members = state.memberList;
- if (state.role) {
- props.binding.role = state.role;
- }
- props.binding.condition = buildConditionExpr({
+defineExpose({
+ reason: computed(() => state.reason),
+ getDatabaseResources: async () => {
+ const resources =
+ await databaseResourceFormRef.value?.getDatabaseResources();
+ return resources;
+ },
+ getBinding: async (): Promise<Binding> => {
+ const databaseResources =
+ await databaseResourceFormRef.value?.getDatabaseResources();
+ const condition = buildConditionExpr({
role: state.role,
description: state.reason,
expirationTimestampInMS: state.expirationTimestampInMS,
- databaseResources: state.databaseResources,
+ databaseResources,
});
- },
- {
- deep: true,
- }
-);
-defineExpose({
- reason: computed(() => state.reason),
- databaseResources: computed(() => state.databaseResources),
+ return create(BindingSchema, {
+ members: state.memberList,
+ role: state.role,
+ condition,
+ });
+ },
expirationTimestampInMS: computed(() => state.expirationTimestampInMS),
allowConfirm: computed(() => {
if (!state.role) {
@@ -186,11 +170,7 @@ defineExpose({
if (!expirationSelectorRef.value?.isValid) {
return false;
}
- // undefined databaseResources means all databases
- if (
- !isUndefined(state.databaseResources) &&
- state.databaseResources.length === 0
- ) {
+ if (!databaseResourceFormRef.value?.isValid) {
return false;
}
if (props.requireReason && !state.reason.trim()) {
diff --git a/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMembersPanel.vue b/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMembersPanel.vue
index 916d995b2b..efe0b66e37 100644
--- a/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMembersPanel.vue
+++ b/frontend/src/components/ProjectMember/AddProjectMember/AddProjectMembersPanel.vue
@@ -111,9 +111,10 @@ const handleRemove = (index: number) => {
state.bindings.splice(index, 1);
};
-const mergePolicyBinding = () => {
+const mergePolicyBinding = async () => {
const bindingMap = new Map<string, Binding>();
- for (const binding of state.bindings) {
+ for (const formRef of formRefs.value) {
+ const binding = await formRef.getBinding();
const key = getBindingIdentifier(binding);
if (!bindingMap.has(key)) {
bindingMap.set(key, binding);
@@ -151,7 +152,7 @@ const addMembers = async () => {
return;
}
- const policy = mergePolicyBinding();
+ const policy = await mergePolicyBinding();
await useProjectIamPolicyStore().updateProjectIamPolicy(
projectResourceName.value,
policy
diff --git a/frontend/src/components/ProjectMember/ProjectMemberRolePanel/EditProjectRolePanel.vue b/frontend/src/components/ProjectMember/ProjectMemberRolePanel/EditProjectRolePanel.vue
index 0ccfbef4ec..eabda921cf 100644
--- a/frontend/src/components/ProjectMember/ProjectMemberRolePanel/EditProjectRolePanel.vue
+++ b/frontend/src/components/ProjectMember/ProjectMemberRolePanel/EditProjectRolePanel.vue
@@ -34,7 +34,8 @@
<RequiredStar />
</div>
<QuerierDatabaseResourceForm
- v-model:database-resources="state.databaseResources"
+ ref="databaseResourceFormRef"
+ :database-resources="databaseResources"
:project-name="project.name"
:include-cloumn="false"
:required-feature="PlanFeature.FEATURE_IAM"
@@ -114,7 +115,7 @@ import {
useProjectIamPolicy,
useProjectIamPolicyStore,
} from "@/store";
-import { type DatabaseResource, PresetRoleType } from "@/types";
+import { PresetRoleType } from "@/types";
import { State } from "@/types/proto-es/v1/common_pb";
import type { Binding } from "@/types/proto-es/v1/iam_policy_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
@@ -136,8 +137,6 @@ interface LocalState {
title: string;
description: string;
expirationTimestamp?: number;
- // Querier and exporter options.
- databaseResources?: DatabaseResource[];
isLoading: boolean;
}
@@ -149,6 +148,8 @@ const state = reactive<LocalState>({
isLoading: true,
});
const expirationSelectorRef = ref<InstanceType<typeof ExpirationSelector>>();
+const databaseResourceFormRef =
+ ref<InstanceType<typeof QuerierDatabaseResourceForm>>();
const projectResourceName = computed(() => props.project.name);
const { policy: iamPolicy } = useProjectIamPolicy(projectResourceName);
@@ -171,25 +172,24 @@ const allowRemoveRole = () => {
return true;
};
-const bindingCondition = computed(() =>
- buildConditionExpr({
- title: state.title,
- role: props.binding.role,
- description: state.description,
- expirationTimestampInMS: state.expirationTimestamp,
- databaseResources: state.databaseResources,
- })
-);
-
const allowConfirm = computed(() => {
// only allow update current single user.
return (
props.binding.members.length === 1 &&
expirationSelectorRef.value?.isValid &&
- !isEqual(bindingCondition.value, props.binding.condition)
+ databaseResourceFormRef.value?.isValid
+ // TODO(ed): check if expression changed
);
});
+const databaseResources = computed(() => {
+ if (props.binding.parsedExpr) {
+ const conditionExpr = convertFromExpr(props.binding.parsedExpr);
+ return conditionExpr.databaseResources;
+ }
+ return undefined;
+});
+
onMounted(() => {
const binding = props.binding;
// Set the display title with the role name.
@@ -201,9 +201,6 @@ onMounted(() => {
if (conditionExpr.expiredTime) {
state.expirationTimestamp = new Date(conditionExpr.expiredTime).getTime();
}
- if (conditionExpr.databaseResources) {
- state.databaseResources = conditionExpr.databaseResources;
- }
}
state.isLoading = false;
@@ -226,7 +223,16 @@ const handleUpdateRole = async () => {
const newBinding = cloneDeep(props.binding);
newBinding.members = [member];
- newBinding.condition = bindingCondition.value;
+
+ const databaseResources =
+ await databaseResourceFormRef.value?.getDatabaseResources();
+ newBinding.condition = buildConditionExpr({
+ title: state.title,
+ role: props.binding.role,
+ description: state.description,
+ expirationTimestampInMS: state.expirationTimestamp,
+ databaseResources,
+ });
const policy = cloneDeep(iamPolicy.value);
const oldBindingIndex = policy.bindings.findIndex(
diff --git a/frontend/src/components/SensitiveData/GrantAccessForm.vue b/frontend/src/components/SensitiveData/GrantAccessForm.vue
index 8d4d0d0f96..638047f162 100644
--- a/frontend/src/components/SensitiveData/GrantAccessForm.vue
+++ b/frontend/src/components/SensitiveData/GrantAccessForm.vue
@@ -10,7 +10,8 @@
<RequiredStar />
</div>
<DatabaseResourceForm
- v-model:database-resources="state.databaseResources"
+ ref="databaseResourceFormRef"
+ :database-resources="databaseResources"
:project-name="projectName"
:required-feature="PlanFeature.FEATURE_DATA_MASKING"
:include-cloumn="true"
@@ -74,16 +75,14 @@
<script lang="tsx" setup>
import { create } from "@bufbuild/protobuf";
-import { isUndefined } from "lodash-es";
import { NButton, NDatePicker, NInput } from "naive-ui";
-import { computed, reactive } from "vue";
+import { computed, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import DatabaseResourceForm from "@/components/GrantRequestPanel/DatabaseResourceForm/index.vue";
import MembersBindingSelect from "@/components/Member/MembersBindingSelect.vue";
import RequiredStar from "@/components/RequiredStar.vue";
import FormLayout from "@/components/v2/Form/FormLayout.vue";
import { pushNotification, usePolicyV1Store } from "@/store";
-import type { DatabaseResource } from "@/types";
import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
import type {
MaskingExemptionPolicy_Exemption,
@@ -114,18 +113,20 @@ interface LocalState {
memberList: string[];
expirationTimestamp?: number;
processing: boolean;
- databaseResources?: DatabaseResource[];
description: string;
}
const state = reactive<LocalState>({
memberList: [],
processing: false,
- databaseResources: props.columnList.map(
- convertSensitiveColumnToDatabaseResource
- ),
description: "",
});
+const databaseResourceFormRef =
+ ref<InstanceType<typeof DatabaseResourceForm>>();
+
+const databaseResources = computed(() => {
+ return props.columnList.map(convertSensitiveColumnToDatabaseResource);
+});
const policyStore = usePolicyV1Store();
const { t } = useI18n();
@@ -133,7 +134,6 @@ const { t } = useI18n();
const resetState = () => {
state.expirationTimestamp = undefined;
state.memberList = [];
- state.databaseResources = undefined;
state.processing = false;
};
@@ -146,13 +146,7 @@ const submitDisabled = computed(() => {
if (state.memberList.length === 0) {
return true;
}
- if (
- !isUndefined(state.databaseResources) &&
- state.databaseResources?.length === 0
- ) {
- return true;
- }
- return false;
+ return !databaseResourceFormRef.value?.isValid;
});
const onSubmit = async () => {
@@ -189,7 +183,10 @@ const getPendingUpdatePolicy = async (
);
}
- const resourceExpressions = state.databaseResources?.map(
+ const databaseResources =
+ await databaseResourceFormRef.value?.getDatabaseResources();
+
+ const resourceExpressions = databaseResources?.map(
getExpressionsForDatabaseResource
) ?? [[""]];
for (const expressionList of resourceExpressions) {
diff --git a/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue b/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
index 3dc562c8e3..245779de7d 100644
--- a/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
+++ b/frontend/src/components/SensitiveData/components/MaskingRuleConfig.vue
@@ -23,7 +23,7 @@
</div>
<ExprEditor
:expr="state.expr"
- :allow-admin="!readonly"
+ :readonly="readonly"
:factor-list="factorList"
:option-config-map="optionConfigMap"
:factor-operator-override-map="factorOperatorOverrideMap"
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 82b259a651..06987ed8a1 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1081,6 +1081,7 @@
"all-databases": "All",
"all-databases-tip": "All current and future databases in this project.",
"manually-select": "Manually select",
+ "use-cel": "Use CEL Expression",
"custom-date": "Custom date",
"custom-date-placeholder": "Select expiration date and time"
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 6782283e81..5c41fedeac 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1081,6 +1081,7 @@
"all-databases": "todas las bases de datos",
"all-databases-tip": "Todas las bases de datos actuales y futuras de este proyecto.",
"manually-select": "selección manual",
+ "use-cel": "Usar expresión CEL",
"custom-date": "Fecha personalizada",
"custom-date-placeholder": "Seleccione la fecha y hora de vencimiento"
},
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 84b4f242b5..60800920d3 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1081,6 +1081,7 @@
"all-databases": "すべてのデータベース",
"all-databases-tip": "このプロジェクトに属する現在および将来のすべてのデータベース。",
"manually-select": "手動選択",
+ "use-cel": "CEL式を使用",
"custom-date": "カスタム日付",
"custom-date-placeholder": "有効期限と時刻を選択します"
},
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 29c3574ca6..a62baee801 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1081,6 +1081,7 @@
"all-databases": "Tất cả",
"all-databases-tip": "Tất cả cơ sở dữ liệu hiện tại và tương lai trong dự án này.",
"manually-select": "Chọn thủ công",
+ "use-cel": "Sử dụng biểu thức CEL",
"custom-date": "Ngày tùy chỉnh",
"custom-date-placeholder": "Chọn ngày và giờ hết hạn"
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 71387ee810..48160c44c5 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1081,6 +1081,7 @@
"all-databases": "所有数据库",
"all-databases-tip": "所有当前和未来属于这个项目的数据库。",
"manually-select": "手动选择",
+ "use-cel": "使用 CEL 表达式",
"custom-date": "自定义日期",
"custom-date-placeholder": "选择到期日期和时间"
},
diff --git a/frontend/src/utils/issue/cel.ts b/frontend/src/utils/issue/cel.ts
index b2a5921f98..52c1297e85 100644
--- a/frontend/src/utils/issue/cel.ts
+++ b/frontend/src/utils/issue/cel.ts
@@ -41,10 +41,18 @@ interface TableLevelCondition {
table: string[];
}
+interface ColumnLevelCondition {
+ database: string;
+ schema: string;
+ table: string;
+ column: string[];
+}
+
type DatabaseResourceCondition =
| DatabaseLevelCondition
| SchemaLevelCondition
- | TableLevelCondition;
+ | TableLevelCondition
+ | ColumnLevelCondition;
export interface ConditionExpression {
databaseResources?: DatabaseResource[];
@@ -145,26 +153,28 @@ export const stringifyDatabaseResources = (resources: DatabaseResource[]) => {
const conditionList: DatabaseResourceCondition[] = [];
for (const resource of resources) {
- if (resource.table === undefined && resource.schema === undefined) {
- // Database level
+ if (resource.columns !== undefined) {
conditionList.push({
- database: [resource.databaseFullName],
+ database: resource.databaseFullName,
+ schema: resource.schema ?? "",
+ table: resource.table ?? "",
+ column: [...resource.columns],
});
- } else if (resource.schema !== undefined && resource.table === undefined) {
- // Schema level
+ } else if (resource.table !== undefined) {
conditionList.push({
database: resource.databaseFullName,
- schema: [resource.schema],
+ schema: resource.schema ?? "",
+ table: [resource.table],
});
- } else if (resource.schema !== undefined && resource.table !== undefined) {
- // Table level
+ } else if (resource.schema !== undefined) {
conditionList.push({
database: resource.databaseFullName,
- schema: resource.schema,
- table: [resource.table],
+ schema: [resource.schema],
});
} else {
- throw new Error("Invalid database resource");
+ conditionList.push({
+ database: [resource.databaseFullName],
+ });
}
}
@@ -179,7 +189,7 @@ export const stringifyDatabaseResources = (resources: DatabaseResource[]) => {
typeof condition.database === "string" &&
Array.isArray((condition as SchemaLevelCondition).schema)
)
- ).filter((condition) => condition.schema.length > 0);
+ );
const tableLevelConditionList = mergeTableLevelConditions(
conditionList.filter(
(condition): condition is TableLevelCondition =>
@@ -187,17 +197,27 @@ export const stringifyDatabaseResources = (resources: DatabaseResource[]) => {
typeof (condition as TableLevelCondition).schema === "string" &&
Array.isArray((condition as TableLevelCondition).table)
)
- ).filter((condition) => condition.table.length > 0);
+ );
+ const columnLevelConditionList = mergeColumnLevelConditions(
+ conditionList.filter(
+ (condition): condition is ColumnLevelCondition =>
+ typeof condition.database === "string" &&
+ typeof (condition as ColumnLevelCondition).schema === "string" &&
+ typeof (condition as ColumnLevelCondition).table === "string" &&
+ Array.isArray((condition as ColumnLevelCondition).column)
+ )
+ );
const cel = convertToCELString([
...databaseLevelConditionList,
...schemaLevelConditionList,
...tableLevelConditionList,
+ ...columnLevelConditionList,
]);
return cel;
};
-const stringifyConditionExpression = ({
+export const stringifyConditionExpression = ({
expirationTimestampInMS,
databaseResources,
}: {
@@ -221,24 +241,77 @@ const convertToCELString = (
| DatabaseLevelCondition
| SchemaLevelCondition
| TableLevelCondition
+ | ColumnLevelCondition
)[]
): string => {
+ if (conditions.length === 0) {
+ return "";
+ }
+
+ const getArrayExpressionString = (resource: string, arr: string[]) => {
+ if (arr.length === 0) {
+ return "";
+ }
+ return `${resource} in ${JSON.stringify(arr)}`;
+ };
+
+ const getStringExpressionString = (resource: string, value: string) => {
+ if (!value) {
+ return "";
+ }
+ return `${resource} == "${value}"`;
+ };
+
function buildCondition(
condition:
| DatabaseLevelCondition
| SchemaLevelCondition
| TableLevelCondition
+ | ColumnLevelCondition
): string {
- if ("table" in condition) {
- return `${CEL_ATTRIBUTE_RESOURCE_DATABASE} == "${
- condition.database
- }" && ${CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME} == "${
- condition.schema
- }" && ${CEL_ATTRIBUTE_RESOURCE_TABLE_NAME} in ${JSON.stringify(condition.table)}`;
+ const databaseExpression = `${CEL_ATTRIBUTE_RESOURCE_DATABASE} == "${condition.database}"`;
+ if ("column" in condition) {
+ return [
+ databaseExpression,
+ getStringExpressionString(
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ condition.schema
+ ),
+ getStringExpressionString(
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+ condition.table
+ ),
+ getArrayExpressionString(
+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,
+ condition.column
+ ),
+ ]
+ .filter((str) => str)
+ .join(" && ");
+ } else if ("table" in condition) {
+ return [
+ databaseExpression,
+ getStringExpressionString(
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ condition.schema
+ ),
+ getArrayExpressionString(
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+ condition.table
+ ),
+ ]
+ .filter((str) => str)
+ .join(" && ");
} else if ("schema" in condition) {
- return `${CEL_ATTRIBUTE_RESOURCE_DATABASE} == "${
- condition.database
- }" && ${CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME} in ${JSON.stringify(condition.schema)}`;
+ return [
+ databaseExpression,
+ getArrayExpressionString(
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+ condition.schema
+ ),
+ ]
+ .filter((str) => str)
+ .join(" && ");
} else {
return `${CEL_ATTRIBUTE_RESOURCE_DATABASE} in ${JSON.stringify(condition.database)}`;
}
@@ -249,6 +322,7 @@ const convertToCELString = (
| DatabaseLevelCondition
| SchemaLevelCondition
| TableLevelCondition
+ | ColumnLevelCondition
)[]
): string {
if (conditions.length === 1) {
@@ -503,3 +577,35 @@ const mergeTableLevelConditions = (
return mergedConditions;
};
+
+const mergeColumnLevelConditions = (
+ conditions: ColumnLevelCondition[]
+): ColumnLevelCondition[] => {
+ const groupedConditions: Record<string, string[]> = {};
+
+ for (const condition of conditions) {
+ const { database, schema, table, column } = condition;
+ const key = `${database}:${schema}:${table}`;
+
+ if (groupedConditions[key]) {
+ groupedConditions[key] = [...groupedConditions[key], ...column];
+ } else {
+ groupedConditions[key] = [...column];
+ }
+ }
+
+ const mergedConditions: ColumnLevelCondition[] = [];
+
+ for (const key of Object.keys(groupedConditions)) {
+ const [database, schema, table] = key.split(":");
+ const condition: ColumnLevelCondition = {
+ database,
+ schema,
+ table,
+ column: groupedConditions[key],
+ };
+ mergedConditions.push(condition);
+ }
+
+ return mergedConditions;
+};