Skip to content

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

feat(frontend): table-level query data approval flow (#6235)

boojacka9abe955879b
diff --git a/frontend/src/components/Issue/form/DatabaseResourceView.vue b/frontend/src/components/Issue/form/DatabaseResourceView.vue
new file mode 100644
index 0000000000..c4d108931e
--- /dev/null
+++ b/frontend/src/components/Issue/form/DatabaseResourceView.vue
@@ -0,0 +1,50 @@
+<template>
+ <div
+ class="flex flex-row justify-start items-center flex-nowrap whitespace-nowrap"
+ >
+ <Prefix class="flex-shrink-0 mr-1" />
+ {{ database.name }}
+ <template v-if="props.databaseResource.schema">
+ /
+ {{ props.databaseResource.schema }}
+ </template>
+ <template v-if="props.databaseResource.table">
+ /
+ {{ props.databaseResource.table }}
+ </template>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, h } from "vue";
+import { DatabaseResource } from "./SelectDatabaseResourceForm/common";
+import { useDatabaseStore } from "@/store";
+import DatabaseIcon from "~icons/heroicons-outline/circle-stack";
+import SchemaIcon from "~icons/heroicons-outline/view-columns";
+import TableIcon from "~icons/heroicons-outline/table-cells";
+
+const props = defineProps<{
+ databaseResource: DatabaseResource;
+}>();
+
+const databaseStore = useDatabaseStore();
+
+const database = computed(() => {
+ return databaseStore.getDatabaseById(props.databaseResource.databaseId);
+});
+
+const Prefix = () => {
+ if (props.databaseResource.table !== undefined) {
+ return h(TableIcon, {
+ class: "w-4 h-auto text-gray-400",
+ });
+ } else if (props.databaseResource.schema !== undefined) {
+ return h(SchemaIcon, {
+ class: "w-4 h-auto text-gray-400",
+ });
+ }
+ return h(DatabaseIcon, {
+ class: "w-4 h-auto text-gray-400",
+ });
+};
+</script>
diff --git a/frontend/src/components/Issue/form/GrantRequestQuerierForm.vue b/frontend/src/components/Issue/form/GrantRequestQuerierForm.vue
index ccfa09b46c..b6503338c3 100644
--- a/frontend/src/components/Issue/form/GrantRequestQuerierForm.vue
+++ b/frontend/src/components/Issue/form/GrantRequestQuerierForm.vue
@@ -46,36 +46,34 @@
{{ $t("common.select") }}
</button>
<div
- v-if="selectedDatabaseList.length > 0"
+ v-if="state.selectedDatabaseResourceList.length > 0"
class="ml-6 flex flex-row justify-start items-start flex-wrap gap-2 gap-x-4"
>
<div
- v-for="database in selectedDatabaseList"
- :key="database.id"
+ v-for="databaseResource in state.selectedDatabaseResourceList"
+ :key="`${databaseResource.databaseId}`"
class="flex flex-row justify-start items-center"
>
- <InstanceEngineIcon
- class="mr-1"
- :instance="database.instance"
- />
- {{ database.name }}
+ <DatabaseResourceView :database-resource="databaseResource" />
</div>
</div>
</div>
</NRadioGroup>
</div>
- <div v-else class="flex flex-row justify-start items-start gap-4">
- <span v-if="state.selectedDatabaseIdList.length === 0">{{
+ <div
+ v-else
+ class="flex flex-row justify-start items-start flex-wrap gap-2 gap-x-4"
+ >
+ <span v-if="state.selectedDatabaseResourceList.length === 0">{{
$t("issue.grant-request.all-databases")
}}</span>
<div
- v-for="database in selectedDatabaseList"
+ v-for="databaseResource in state.selectedDatabaseResourceList"
v-else
- :key="database.id"
+ :key="`${databaseResource.databaseId}`"
class="flex flex-row justify-start items-center"
>
- <InstanceEngineIcon class="mr-1" :instance="database.instance" />
- {{ database.name }}
+ <DatabaseResourceView :database-resource="databaseResource" />
</div>
</div>
</div>
@@ -122,13 +120,19 @@
</div>
</div>
- <DatabasesSelectPanel
+ <BBModal
v-if="state.showSelectDatabasePanel && state.projectId"
- :project-id="state.projectId"
- :selected-database-id-list="state.selectedDatabaseIdList"
+ class="relative overflow-hidden"
+ :title="$t('issue.grant-request.manually-select')"
@close="state.showSelectDatabasePanel = false"
- @update="handleSelectedDatabaseIdListChanged"
- />
+ >
+ <SelectDatabaseResourceForm
+ :project-id="state.projectId"
+ :selected-database-resource-list="state.selectedDatabaseResourceList"
+ @close="state.showSelectDatabasePanel = false"
+ @update="handleSelectedDatabaseResourceChanged"
+ />
+ </BBModal>
</template>
<script lang="ts" setup>
@@ -146,18 +150,17 @@ import {
PresetRoleType,
UNKNOWN_ID,
} from "@/types";
-import {
- getDatabaseIdByName,
- memberListInProjectV1,
- parseConditionExpressionString,
-} from "@/utils";
+import { getDatabaseIdByName, memberListInProjectV1 } from "@/utils";
import {
convertUserToPrincipal,
useDatabaseStore,
useProjectV1Store,
} from "@/store";
+import { converFromCEL, stringifyDatabaseResources } from "@/utils/issue/cel";
+import { DatabaseResource } from "./SelectDatabaseResourceForm/common";
import RequiredStar from "@/components/RequiredStar.vue";
-import DatabasesSelectPanel from "../../DatabasesSelectPanel.vue";
+import SelectDatabaseResourceForm from "./SelectDatabaseResourceForm/index.vue";
+import DatabaseResourceView from "./DatabaseResourceView.vue";
interface LocalState {
showSelectDatabasePanel: boolean;
@@ -165,6 +168,7 @@ interface LocalState {
projectId?: string;
allDatabases: boolean;
selectedDatabaseIdList: DatabaseId[];
+ selectedDatabaseResourceList: DatabaseResource[];
expireDays: number;
customDays: number;
// For reviewing
@@ -179,6 +183,7 @@ const state = reactive<LocalState>({
projectId: undefined,
allDatabases: true,
selectedDatabaseIdList: [],
+ selectedDatabaseResourceList: [],
expireDays: 7,
customDays: 7,
expiredAt: "",
@@ -188,12 +193,6 @@ const projectId = computed(() => {
return create.value ? state.projectId : (issue.value as Issue).project.id;
});
-const selectedDatabaseList = computed(() => {
- return state.selectedDatabaseIdList.map((id) => {
- return databaseStore.getDatabaseById(id);
- });
-});
-
const expireDaysOptions = computed(() => [
{
value: 7,
@@ -261,14 +260,18 @@ const handleManuallySelectClick = () => {
}
};
-const handleSelectedDatabaseIdListChanged = (databaseIdList: DatabaseId[]) => {
- state.selectedDatabaseIdList = databaseIdList;
+const handleSelectedDatabaseResourceChanged = (
+ databaseResourceList: DatabaseResource[]
+) => {
+ state.selectedDatabaseResourceList = databaseResourceList;
state.showSelectDatabasePanel = false;
state.allDatabases = false;
+ stringifyDatabaseResources(databaseResourceList);
+
if (create.value) {
(
(issue.value as IssueCreate).createContext as GrantRequestContext
- ).databases = databaseIdList as string[];
+ ).databaseResources = databaseResourceList;
}
};
@@ -299,7 +302,7 @@ watch(
throw "Only support QUERIER role";
}
- const conditionExpression = parseConditionExpressionString(
+ const conditionExpression = await converFromCEL(
payload.condition.expression
);
if (conditionExpression.expiredTime !== undefined) {
@@ -320,6 +323,13 @@ watch(
}
state.selectedDatabaseIdList = uniq(databaseIdList);
}
+ if (
+ conditionExpression.databaseResources !== undefined &&
+ conditionExpression.databaseResources.length > 0
+ ) {
+ state.selectedDatabaseResourceList =
+ conditionExpression.databaseResources;
+ }
}
},
{
diff --git a/frontend/src/components/Issue/form/SelectDatabaseResourceForm/Label.vue b/frontend/src/components/Issue/form/SelectDatabaseResourceForm/Label.vue
new file mode 100644
index 0000000000..d18135bb60
--- /dev/null
+++ b/frontend/src/components/Issue/form/SelectDatabaseResourceForm/Label.vue
@@ -0,0 +1,79 @@
+<template>
+ <div class="flex items-center gap-x-1">
+ <span v-if="environment" class="text-gray-400">
+ (<EnvironmentV1Name :environment="environment" :link="false" />)
+ </span>
+ <Prefix />
+ <!-- eslint-disable-next-line vue/no-v-html -->
+ <span class="truncate" v-html="optionName" />
+ <span v-if="database" class="ml-1 text-gray-500 flex flex-row items-center">
+ (<InstanceName
+ :instance="database.instance"
+ :link="false"
+ class="whitespace-nowrap"
+ />)
+ </span>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { escape } from "lodash-es";
+import { computed, h } from "vue";
+import { DatabaseTreeOption } from "./common";
+import { useDatabaseStore, useEnvironmentV1Store } from "@/store";
+import { getHighlightHTMLByRegExp } from "@/utils";
+import { EnvironmentV1Name, InstanceName } from "@/components/v2";
+import DatabaseIcon from "~icons/heroicons-outline/circle-stack";
+import SchemaIcon from "~icons/heroicons-outline/view-columns";
+import TableIcon from "~icons/heroicons-outline/table-cells";
+
+const props = defineProps<{
+ option: DatabaseTreeOption;
+ keyword?: string;
+}>();
+
+const option = computed(() => props.option);
+
+const database = computed(() => {
+ const { option } = props;
+ if (option.level !== "database") return undefined;
+ const databaseId = option.value.replace("d-", "");
+ return useDatabaseStore().getDatabaseById(databaseId);
+});
+
+const environment = computed(() => {
+ const { option } = props;
+ if (option.level !== "database") return undefined;
+ return useEnvironmentV1Store().getEnvironmentByUID(
+ database.value?.instance.environment.id as string
+ );
+});
+
+const Prefix = () => {
+ if (option.value.level === "database") {
+ return h(DatabaseIcon, {
+ class: "w-4 h-auto text-gray-400",
+ });
+ } else if (option.value.level === "schema") {
+ return h(SchemaIcon, {
+ class: "w-4 h-auto text-gray-400",
+ });
+ } else if (option.value.level === "table") {
+ return h(TableIcon, {
+ class: "w-4 h-auto text-gray-400",
+ });
+ }
+ return null;
+};
+
+const optionName = computed(() => {
+ const name = option.value?.label ?? "";
+ const keyword = (props.keyword ?? "").trim();
+
+ return getHighlightHTMLByRegExp(
+ escape(name),
+ escape(keyword),
+ false /* !caseSensitive */
+ );
+});
+</script>
diff --git a/frontend/src/components/Issue/form/SelectDatabaseResourceForm/common.ts b/frontend/src/components/Issue/form/SelectDatabaseResourceForm/common.ts
new file mode 100644
index 0000000000..df810fcc52
--- /dev/null
+++ b/frontend/src/components/Issue/form/SelectDatabaseResourceForm/common.ts
@@ -0,0 +1,114 @@
+import { flatten } from "lodash-es";
+import { TransferOption, TreeOption } from "naive-ui";
+import { useDBSchemaStore } from "@/store";
+import { Database, DatabaseId } from "@/types";
+
+export interface DatabaseResource {
+ databaseId: DatabaseId;
+ schema?: string;
+ table?: string;
+}
+
+export interface DatabaseTreeOption<L = "database" | "schema" | "table">
+ extends TreeOption {
+ level: L;
+ value: string;
+}
+
+export const mapTreeOptions = (
+ databaseList: Database[],
+ filterValueList?: string[]
+) => {
+ const dbSchemaStore = useDBSchemaStore();
+ const databaseNodes: DatabaseTreeOption<"database">[] = [];
+ for (const database of databaseList) {
+ const databaseMetadata = dbSchemaStore.getDatabaseMetadataByDatabaseId(
+ database.id
+ );
+ const databaseNode: DatabaseTreeOption<"database"> = {
+ level: "database",
+ value: `d-${database.id}`,
+ label: database.name,
+ };
+
+ if (database.instance.engine === "POSTGRES") {
+ const schemaNodes = databaseMetadata.schemas.map(
+ (schema): DatabaseTreeOption<"schema"> => {
+ const schemaNode: DatabaseTreeOption<"schema"> = {
+ level: "schema",
+ value: `s-${database.id}-${schema.name}`,
+ label: schema.name,
+ };
+ const tableNodes = schema.tables.map(
+ (table): DatabaseTreeOption<"table"> => {
+ return {
+ level: "table",
+ value: `t-${database.id}-${schema.name}-${table.name}`,
+ label: table.name,
+ };
+ }
+ );
+ if (tableNodes.length > 0) {
+ schemaNode.children = filterValueList
+ ? tableNodes.filter(
+ (node) =>
+ (node.children && node.children?.length > 0) ||
+ filterValueList.includes(node.value)
+ )
+ : tableNodes;
+ }
+ return schemaNode;
+ }
+ );
+ if (schemaNodes.length > 0) {
+ databaseNode.children = filterValueList
+ ? schemaNodes.filter(
+ (node) =>
+ (node.children && node.children?.length > 0) ||
+ filterValueList.includes(node.value)
+ )
+ : schemaNodes;
+ }
+ } else {
+ const tableNodes = flatten(
+ databaseMetadata.schemas.map((schema) => schema.tables)
+ ).map((table): DatabaseTreeOption<"table"> => {
+ return {
+ level: "table",
+ value: `t-${database.id}--${table.name}`,
+ label: table.name,
+ };
+ });
+ if (tableNodes.length > 0) {
+ databaseNode.children = filterValueList
+ ? tableNodes.filter(
+ (node) =>
+ (node.children && node.children?.length > 0) ||
+ filterValueList.includes(node.value)
+ )
+ : tableNodes;
+ }
+ }
+ databaseNodes.push(databaseNode);
+ }
+ return filterValueList
+ ? databaseNodes.filter(
+ (node) =>
+ (node.children && node.children?.length > 0) ||
+ filterValueList.includes(node.value)
+ )
+ : databaseNodes;
+};
+
+export const flattenTreeOptions = (
+ options: DatabaseTreeOption[]
+): TransferOption[] => {
+ return options.flatMap((option) => {
+ return [
+ option as TransferOption,
+ ...flattenTreeOptions(
+ (option.children as DatabaseTreeOption[] | undefined) ?? []
+ ),
+ ];
+ });
+};
diff --git a/frontend/src/components/Issue/form/SelectDatabaseResourceForm/index.vue b/frontend/src/components/Issue/form/SelectDatabaseResourceForm/index.vue
new file mode 100644
index 0000000000..f80cfb87f7
--- /dev/null
+++ b/frontend/src/components/Issue/form/SelectDatabaseResourceForm/index.vue
@@ -0,0 +1,193 @@
+<template>
+ <div class="w-[60rem] space-y-2">
+ <NTransfer
+ v-if="!loading"
+ ref="transfer"
+ v-model:value="selectedValueList"
+ style="height: calc(100vh - 380px)"
+ :options="sourceTransferOptions"
+ :render-source-list="renderSourceList"
+ :render-target-list="renderTargetList"
+ :source-filterable="true"
+ :source-filter-placeholder="$t('database.search-database-name')"
+ />
+ <div class="flex items-center justify-end gap-x-2">
+ <NButton @click="$emit('close')">{{ $t("common.cancel") }}</NButton>
+ <NButton type="primary" :disabled="!allowConfirm" @click="doConfirm">
+ {{ $t("common.confirm") }}
+ </NButton>
+ </div>
+ <div
+ v-if="loading"
+ class="absolute inset-0 z-10 bg-white/70 flex items-center justify-center"
+ >
+ <BBSpin />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import {
+ NTransfer,
+ TransferRenderSourceList,
+ NButton,
+ NTree,
+ TreeOption,
+} from "naive-ui";
+import { computed, h, onMounted, ref } from "vue";
+import { useDatabaseStore, useDBSchemaStore } from "@/store";
+import {
+ flattenTreeOptions,
+ mapTreeOptions,
+ DatabaseTreeOption,
+ DatabaseResource,
+} from "./common";
+import Label from "./Label.vue";
+import { watch } from "vue";
+import { uniq } from "lodash-es";
+
+const props = defineProps<{
+ projectId: string;
+ selectedDatabaseResourceList: DatabaseResource[];
+}>();
+
+const emits = defineEmits<{
+ (e: "close"): void;
+ (e: "update", databaseResourceList: DatabaseResource[]): void;
+}>();
+
+const databaseStore = useDatabaseStore();
+const dbSchemaStore = useDBSchemaStore();
+const selectedValueList = ref<string[]>([]);
+const databaseResourceMap = ref<Map<string, DatabaseResource>>(new Map());
+const loading = ref(false);
+
+onMounted(async () => {
+ const databaseList = await databaseStore.fetchDatabaseListByProjectId(
+ props.projectId
+ );
+
+ for (const database of databaseList) {
+ const databaseMetadata = await dbSchemaStore.getOrFetchDatabaseMetadataById(
+ database.id
+ );
+ databaseResourceMap.value.set(`d-${database.id}`, {
+ databaseId: database.id,
+ });
+ for (const schema of databaseMetadata.schemas) {
+ databaseResourceMap.value.set(`s-${database.id}-${schema.name}`, {
+ databaseId: database.id,
+ schema: schema.name,
+ });
+ for (const table of schema.tables) {
+ databaseResourceMap.value.set(
+ `t-${database.id}-${schema.name}-${table.name}`,
+ {
+ databaseId: database.id,
+ schema: schema.name,
+ table: table.name,
+ }
+ );
+ }
+ }
+ }
+ loading.value = false;
+});
+
+const databaseList = computed(() => {
+ return databaseStore.getDatabaseListByProjectId(props.projectId);
+});
+
+const allowConfirm = computed(() => {
+ return selectedValueList.value.length > 0;
+});
+
+const sourceTreeOptions = computed(() => {
+ return mapTreeOptions(databaseList.value);
+});
+
+const sourceTransferOptions = computed(() => {
+ const options = flattenTreeOptions(sourceTreeOptions.value);
+ return options;
+});
+
+const renderSourceList: TransferRenderSourceList = ({ onCheck, pattern }) => {
+ return h(NTree, {
+ keyField: "value",
+ checkable: true,
+ selectable: false,
+ checkOnClick: true,
+ virtualScroll: true,
+ data: sourceTreeOptions.value,
+ renderLabel: ({ option }: { option: TreeOption }) => {
+ return h(Label, {
+ option: option as DatabaseTreeOption,
+ keyword: pattern,
+ });
+ },
+ pattern,
+ checkedKeys: selectedValueList.value,
+ showIrrelevantNodes: false,
+ onUpdateCheckedKeys: (checkedKeys: string[]) => {
+ onCheck(checkedKeys);
+ },
+ });
+};
+
+const targetTreeOptions = computed(() => {
+ return mapTreeOptions(databaseList.value, selectedValueList.value);
+});
+
+const renderTargetList: TransferRenderSourceList = ({ onCheck }) => {
+ return h(NTree, {
+ keyField: "value",
+ checkable: true,
+ selectable: false,
+ checkOnClick: true,
+ virtualScroll: true,
+ defaultExpandAll: true,
+ data: targetTreeOptions.value,
+ renderLabel: ({ option }: { option: TreeOption }) => {
+ return h(Label, {
+ option: option as DatabaseTreeOption,
+ });
+ },
+ checkedKeys: selectedValueList.value,
+ showIrrelevantNodes: false,
+ onUpdateCheckedKeys: (checkedKeys: string[]) => {
+ onCheck(checkedKeys);
+ },
+ });
+};
+
+const doConfirm = () => {
+ const list = selectedValueList.value
+ .map((key) => {
+ return databaseResourceMap.value.get(key);
+ })
+ .filter((item) => item !== undefined);
+ emits("update", list as DatabaseResource[]);
+};
+
+watch(
+ () => props.selectedDatabaseResourceList,
+ () => {
+ const selectedKeyList = [];
+ for (const databaseResource of props.selectedDatabaseResourceList) {
+ let key = "";
+ if (databaseResource.table !== undefined) {
+ key = `t-${databaseResource.databaseId}-${databaseResource.schema}-${databaseResource.table}`;
+ } else if (databaseResource.schema !== undefined) {
+ key = `s-${databaseResource.databaseId}-${databaseResource.schema}`;
+ } else {
+ key = `d-${databaseResource.databaseId}`;
+ }
+ selectedKeyList.push(key);
+ }
+ selectedValueList.value = uniq(selectedKeyList);
+ },
+ {
+ immediate: true,
+ }
+);
+</script>
diff --git a/frontend/src/components/Issue/logic/GrantRequestModeProvider.ts b/frontend/src/components/Issue/logic/GrantRequestModeProvider.ts
index f6459beb19..8b86fbdaee 100644
--- a/frontend/src/components/Issue/logic/GrantRequestModeProvider.ts
+++ b/frontend/src/components/Issue/logic/GrantRequestModeProvider.ts
@@ -3,6 +3,7 @@ import { defineComponent, onMounted } from "vue";
import { GrantRequestContext, IssueCreate } from "@/types";
import { useCurrentUserV1, useDatabaseStore, useProjectV1Store } from "@/store";
import { provideIssueLogic, useCommonLogic, useIssueLogic } from "./index";
+import { stringifyDatabaseResources } from "@/utils/issue/cel";
export default defineComponent({
name: "GrantRequestModeProvider",
@@ -21,6 +22,7 @@ export default defineComponent({
const context: GrantRequestContext = {
...{
databases: [],
+ databaseResources: [],
expireDays: 7,
maxRowCount: 1000,
statement: "",
@@ -30,19 +32,12 @@ export default defineComponent({
};
const expression: string[] = [];
if (context.role === "QUERIER") {
- if (Array.isArray(context.databases) && context.databases.length > 0) {
- const databaseNames = [];
- for (const databaseId of context.databases) {
- const database = await databaseStore.getOrFetchDatabaseById(
- databaseId
- );
- databaseNames.push(
- `instances/${database.instance.resourceId}/databases/${database.name}`
- );
- }
- expression.push(
- `resource.database in ${JSON.stringify(databaseNames)}`
- );
+ if (
+ Array.isArray(context.databaseResources) &&
+ context.databaseResources.length > 0
+ ) {
+ const cel = stringifyDatabaseResources(context.databaseResources);
+ expression.push(cel);
}
expression.push(
`request.time < timestamp("${new Date(
@@ -72,17 +67,17 @@ export default defineComponent({
throw "Invalid role";
}
+ const celExpressionString = expression.join(" && ");
issueCreate.payload = {
grantRequest: {
role: `roles/${context.role}`,
user: currentUser.value.name,
condition: {
- expression: expression.join(" && "),
+ expression: celExpressionString,
},
},
};
issueCreate.createContext = {};
-
createIssue(issueCreate);
};
diff --git a/frontend/src/types/issue.ts b/frontend/src/types/issue.ts
index 729520a696..b306d37e93 100644
--- a/frontend/src/types/issue.ts
+++ b/frontend/src/types/issue.ts
@@ -13,6 +13,7 @@ import { Principal } from "./principal";
import { Project } from "./project";
import { MigrationType } from "./instance";
import { Expr } from "./proto/google/type/expr";
+import { DatabaseResource } from "@/components/Issue/form/SelectDatabaseResourceForm/common";
type IssueTypeGeneral = "bb.issue.general";
@@ -92,6 +93,7 @@ export interface GrantRequestContext {
role: "EXPORTER" | "QUERIER";
// Conditions in CEL expression.
databases: string[];
+ databaseResources: DatabaseResource[];
expireDays: number;
maxRowCount: number;
statement: string;
diff --git a/frontend/src/utils/issue/cel.ts b/frontend/src/utils/issue/cel.ts
new file mode 100644
index 0000000000..e4a6a8a885
--- /dev/null
+++ b/frontend/src/utils/issue/cel.ts
@@ -0,0 +1,293 @@
+import { cloneDeep, last } from "lodash-es";
+import { getDatabaseIdByName, getDatabaseNameById } from "./expr";
+import { celServiceClient } from "@/grpcweb";
+import { SimpleExpr, resolveCELExpr } from "@/plugins/cel";
+import { useDatabaseStore } from "@/store";
+import { DatabaseResource } from "@/components/Issue/form/SelectDatabaseResourceForm/common";
+
+interface DatabaseLevelCondition {
+ database: string[];
+}
+
+interface SchemaLevelCondition {
+ database: string;
+ schema: string[];
+}
+
+interface TableLevelCondition {
+ database: string;
+ schema: string;
+ table: string[];
+}
+
+type DatabaseResourceCondition =
+ | DatabaseLevelCondition
+ | SchemaLevelCondition
+ | TableLevelCondition;
+
+export const stringifyDatabaseResources = (resources: DatabaseResource[]) => {
+ const conditionList: DatabaseResourceCondition[] = [];
+
+ for (const resource of resources) {
+ const database = useDatabaseStore().getDatabaseById(resource.databaseId);
+ const databaseName = getDatabaseNameById(database.id);
+ if (resource.table === undefined && resource.schema === undefined) {
+ // Database level
+ conditionList.push({
+ database: [databaseName],
+ });
+ } else if (resource.schema !== undefined && resource.table === undefined) {
+ // Schema level
+ conditionList.push({
+ database: databaseName,
+ schema: [resource.schema],
+ });
+ } else if (resource.schema !== undefined && resource.table !== undefined) {
+ // Table level
+ conditionList.push({
+ database: databaseName,
+ schema: resource.schema,
+ table: [resource.table],
+ });
+ } else {
+ throw new Error("Invalid database resource");
+ }
+ }
+
+ const databaseLevelConditionList = mergeDatabaseLevelConditions(
+ conditionList.filter((condition): condition is DatabaseLevelCondition =>
+ Array.isArray(condition.database)
+ )
+ ).filter((condition) => condition.database.length > 0);
+ const schemaLevelConditionList = mergeSchemaLevelConditions(
+ conditionList.filter(
+ (condition): condition is SchemaLevelCondition =>
+ 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 =>
+ typeof condition.database === "string" &&
+ typeof (condition as TableLevelCondition).schema === "string" &&
+ Array.isArray((condition as TableLevelCondition).table)
+ )
+ ).filter((condition) => condition.table.length > 0);
+
+ const cel = convertToCEL([
+ ...databaseLevelConditionList,
+ ...schemaLevelConditionList,
+ ...tableLevelConditionList,
+ ]);
+ return cel;
+};
+
+const convertToCEL = (
+ conditions: (
+ | DatabaseLevelCondition
+ | SchemaLevelCondition
+ | TableLevelCondition
+ )[]
+): string => {
+ function buildCondition(
+ condition:
+ | DatabaseLevelCondition
+ | SchemaLevelCondition
+ | TableLevelCondition
+ ): string {
+ if ("table" in condition) {
+ return `resource.database == "${
+ condition.database
+ }" && resource.schema == "${
+ condition.schema
+ }" && resource.table in ${JSON.stringify(condition.table)}`;
+ } else if ("schema" in condition) {
+ return `resource.database == "${
+ condition.database
+ }" && resource.schema in ${JSON.stringify(condition.schema)}`;
+ } else {
+ return `resource.database in ${JSON.stringify(condition.database)}`;
+ }
+ }
+
+ function buildGroup(
+ conditions: (
+ | DatabaseLevelCondition
+ | SchemaLevelCondition
+ | TableLevelCondition
+ )[]
+ ): string {
+ if (conditions.length === 1) {
+ return buildCondition(conditions[0]);
+ } else {
+ const conditionStrings = conditions.map(buildCondition);
+ return `${conditionStrings.map((s) => `(${s})`).join(" || ")}`;
+ }
+ }
+
+ const topLevelCondition = buildGroup(conditions);
+
+ return `(${topLevelCondition})`;
+};
+
+interface ConditionExpression {
+ databases?: string[];
+ databaseResources?: DatabaseResource[];
+ expiredTime?: string;
+ statement?: string;
+ rowLimit?: number;
+ exportFormat?: string;
+}
+
+export const converFromCEL = async (
+ cel: string
+): Promise<ConditionExpression> => {
+ const { expression: celExpr } = await celServiceClient.parse({
+ expression: cel,
+ });
+
+ if (!celExpr || !celExpr.expr) {
+ return {};
+ }
+
+ const simpleExpr = resolveCELExpr(celExpr.expr);
+ const conditionExpression: ConditionExpression = {
+ databaseResources: [],
+ };
+
+ async function processCondition(expr: SimpleExpr) {
+ if (expr.operator === "_&&_" || expr.operator === "_||_") {
+ for (const arg of expr.args) {
+ await processCondition(arg);
+ }
+ } else if (expr.operator === "@in") {
+ const [property, values] = expr.args;
+ if (typeof property === "string" && Array.isArray(values)) {
+ if (property === "resource.database") {
+ for (const value of values) {
+ const databaseId = await getDatabaseIdByName(value as string);
+ const databaseResource: DatabaseResource = {
+ databaseId: databaseId,
+ };
+ conditionExpression.databaseResources!.push(databaseResource);
+ }
+ } else if (property === "resource.schema") {
+ const databaseResource = conditionExpression.databaseResources?.pop();
+ if (databaseResource) {
+ for (const value of values) {
+ const temp: DatabaseResource = cloneDeep(
+ databaseResource
+ ) as DatabaseResource;
+ temp.schema = value as string;
+ conditionExpression.databaseResources!.push(temp);
+ }
+ }
+ } else if (property === "resource.table") {
+ const databaseResource = conditionExpression.databaseResources?.pop();
+ if (databaseResource) {
+ for (const value of values) {
+ const temp: DatabaseResource = cloneDeep(
+ databaseResource
+ ) as DatabaseResource;
+ temp.table = value as string;
+ conditionExpression.databaseResources!.push(temp);
+ }
+ }
+ }
+ }
+ } else if (expr.operator === "_==_") {
+ const [left, right] = expr.args;
+ if (typeof left === "string" && typeof right === "string") {
+ if (left === "resource.database") {
+ const databaseId = await getDatabaseIdByName(right);
+ const databaseResource: DatabaseResource = {
+ databaseId: databaseId,
+ };
+ conditionExpression.databaseResources!.push(databaseResource);
+ } else if (left === "resource.schema") {
+ const databaseResource = last(conditionExpression.databaseResources);
+ if (databaseResource) {
+ databaseResource.schema = right;
+ }
+ }
+ }
+ } else if (expr.operator === "_<_") {
+ const [left, right] = expr.args;
+ if (left === "request.time") {
+ conditionExpression.expiredTime = (right as Date).toISOString();
+ }
+ }
+ }
+ await processCondition(simpleExpr);
+ return conditionExpression;
+};
+
+const mergeDatabaseLevelConditions = (
+ conditions: DatabaseLevelCondition[]
+): DatabaseLevelCondition[] => {
+ return [
+ {
+ database: conditions.map((condition) => condition.database).flat(),
+ },
+ ];
+};
+
+const mergeSchemaLevelConditions = (
+ conditions: SchemaLevelCondition[]
+): SchemaLevelCondition[] => {
+ const groupedConditions: Record<string, string[]> = {};
+
+ for (const condition of conditions) {
+ const { database, schema } = condition;
+
+ if (groupedConditions[database]) {
+ groupedConditions[database] = [...groupedConditions[database], ...schema];
+ } else {
+ groupedConditions[database] = [...schema];
+ }
+ }
+
+ const mergedConditions: SchemaLevelCondition[] = [];
+
+ for (const database in groupedConditions) {
+ const condition: SchemaLevelCondition = {
+ database,
+ schema: groupedConditions[database],
+ };
+ mergedConditions.push(condition);
+ }
+
+ return mergedConditions;
+};
+
+const mergeTableLevelConditions = (
+ conditions: TableLevelCondition[]
+): TableLevelCondition[] => {
+ const groupedConditions: Record<string, string[]> = {};
+
+ for (const condition of conditions) {
+ const { database, schema, table } = condition;
+ const key = `${database}:${schema}`;
+
+ if (groupedConditions[key]) {
+ groupedConditions[key] = [...groupedConditions[key], ...table];
+ } else {
+ groupedConditions[key] = [...table];
+ }
+ }
+
+ const mergedConditions: TableLevelCondition[] = [];
+
+ for (const key in groupedConditions) {
+ const [database, schema] = key.split(":");
+ const condition: TableLevelCondition = {
+ database,
+ schema,
+ table: groupedConditions[key],
+ };
+ mergedConditions.push(condition);
+ }
+
+ return mergedConditions;
+};