Skip to content

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

chore: cascade select tree node in database resource selector (#14206)

ecmadao0da727e85cc6
diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
index ffe222d077..5812380454 100644
--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue
@@ -30,12 +30,16 @@ import {
useDBSchemaV1Store,
useProjectByName,
} from "@/store";
+import {
+ databaseNamePrefix,
+ instanceNamePrefix,
+} from "@/store/modules/v1/common";
import { useDatabaseV1List } from "@/store/modules/v1/databaseList";
import type { DatabaseResource } from "@/types";
import { DatabaseMetadataView } from "@/types/proto/v1/database_service";
import { wrapRefAsPromise } from "@/utils";
import Label from "./Label.vue";
-import type { DatabaseTreeOption } from "./common";
+import type { DatabaseTreeOption, DatabaseResourceType } from "./common";
import {
flattenTreeOptions,
getSchemaOrTableTreeOptions,
@@ -60,6 +64,47 @@ const databaseStore = useDatabaseV1Store();
const dbSchemaStore = useDBSchemaV1Store();
const { project } = useProjectByName(props.projectName);
+const parseKeyToResource = (key: string): DatabaseResource | undefined => {
+ const sections = key.split("/");
+ const resource: DatabaseResource = {
+ databaseName: "",
+ };
+
+ while (sections.length > 0) {
+ const keyword = sections.shift() as DatabaseResourceType | "instances";
+ const data = sections.shift() || "";
+
+ switch (keyword) {
+ case "instances":
+ resource.instanceResourceId = data;
+ break;
+ case "databases":
+ if (!resource.instanceResourceId) {
+ return;
+ }
+ resource.databaseName = `${instanceNamePrefix}${resource.instanceResourceId}/${databaseNamePrefix}${data}`;
+ break;
+ case "schemas":
+ resource.schema = data;
+ break;
+ case "tables":
+ resource.table = data;
+ break;
+ case "columns":
+ resource.column = data;
+ break;
+ default:
+ return;
+ }
+ }
+
+ if (!resource.databaseName) {
+ return;
+ }
+
+ return resource;
+};
+
const parseResourceToKey = (resource: DatabaseResource): string => {
const data = [
resource.databaseName,
@@ -84,20 +129,29 @@ const parseResourceToKey = (resource: DatabaseResource): string => {
return data.join("/");
};
-const selectedValueList = ref<string[]>(
- props.databaseResources.map((databaseResource) => {
- return parseResourceToKey(databaseResource);
- })
-);
-const defaultExpandedKeys = ref<string[]>([]);
+const selectedValueList = ref<string[]>([]);
+const expandedKeys = ref<string[]>([]);
const loading = ref(true);
+const cascadeLoopTreeNode = (
+ treeNode: DatabaseTreeOption,
+ callback: (node: DatabaseTreeOption) => void
+) => {
+ callback(treeNode);
+ for (const child of treeNode?.children ?? []) {
+ cascadeLoopTreeNode(child, callback);
+ }
+};
+
onMounted(async () => {
await wrapRefAsPromise(useDatabaseV1List(props.projectName).ready, true);
+ const selectedKeys = props.databaseResources.map(parseResourceToKey);
+ const databaseNames = new Set(
+ selectedKeys.map((key) => key.split("/schemas/")[0]).filter((key) => key)
+ );
await Promise.all(
- selectedValueList.value.map(async (key) => {
- const [databaseName] = key.split("/schemas/");
+ [...databaseNames].map(async (databaseName) => {
await dbSchemaStore.getOrFetchDatabaseMetadata({
database: databaseName,
view: DatabaseMetadataView.DATABASE_METADATA_VIEW_BASIC,
@@ -105,21 +159,44 @@ onMounted(async () => {
})
);
- defaultExpandedKeys.value = selectedValueList.value
- .map((key) => {
- const pathes = parseKeyToPathes(key);
- // key: {db}/schemas/{schema}
- // expaned: [{db}]
- //
- // key: {db}/schemas/{schema}/tables/{table}
- // expaned: [{db}, {db}/schemas/{schema}]
- //
- // key: {db}/schemas/{schema}/tables/{table}/columns/{column}
- // expaned: [{db}, {db}/schemas/{schema}, {db}/schemas/{schema}/tables/{table}]
- pathes.pop();
- return pathes;
- })
- .flat();
+ const newCheckedKeys = new Set(selectedKeys);
+ const newExpandedKeys = new Set(
+ // expand parents for selected keys
+ selectedKeys
+ .map((key) => {
+ const pathes = parseKeyToPathes(key);
+ // key: {db}/schemas/{schema}
+ // expaned: [{db}]
+ //
+ // key: {db}/schemas/{schema}/tables/{table}
+ // expaned: [{db}, {db}/schemas/{schema}]
+ //
+ // key: {db}/schemas/{schema}/tables/{table}/columns/{column}
+ // expaned: [{db}, {db}/schemas/{schema}, {db}/schemas/{schema}/tables/{table}]
+ pathes.pop();
+ return pathes;
+ })
+ .flat()
+ );
+
+ for (const selectedKey of selectedKeys) {
+ const checkedNode = sourceTransferOptions.value.find(
+ (option) => option.value === selectedKey
+ );
+ if (checkedNode) {
+ // check and expand all children
+ cascadeLoopTreeNode(checkedNode, (treeNode) => {
+ newCheckedKeys.add(treeNode.value);
+ if (treeNode.children) {
+ newExpandedKeys.add(treeNode.value);
+ }
+ });
+ }
+ }
+
+ selectedValueList.value = [...newCheckedKeys];
+ expandedKeys.value = [...newExpandedKeys];
+
loading.value = false;
});
@@ -168,14 +245,37 @@ const sourceTreeOptions = computed(() => {
});
});
-const sourceTransferOptions = computed(() => {
+const sourceTransferOptions = computed((): DatabaseTreeOption[] => {
const options = flattenTreeOptions(sourceTreeOptions.value);
return options;
});
+const onTreeNodeLoad = async (node: TreeOption) => {
+ const treeNode = node as DatabaseTreeOption;
+ if (treeNode.level === "databases") {
+ await dbSchemaStore.getOrFetchDatabaseMetadata({
+ database: treeNode.value,
+ view: DatabaseMetadataView.DATABASE_METADATA_VIEW_BASIC,
+ });
+ const database = databaseStore.getDatabaseByName(treeNode.value);
+ const children = getSchemaOrTableTreeOptions({
+ database,
+ includeCloumn: props.includeCloumn,
+ });
+ if (children && children.length > 0) {
+ treeNode.children = children;
+ treeNode.isLeaf = false;
+ } else {
+ treeNode.isLeaf = true;
+ }
+ }
+};
+
const renderSourceList: TransferRenderSourceList = ({ onCheck, pattern }) => {
return h(NTree, {
keyField: "value",
+ cascade: true,
+ allowCheckingNotLoaded: true,
checkable: true,
selectable: false,
checkOnClick: true,
@@ -192,30 +292,42 @@ const renderSourceList: TransferRenderSourceList = ({ onCheck, pattern }) => {
},
pattern,
showIrrelevantNodes: false,
- defaultExpandedKeys: defaultExpandedKeys.value,
+ expandedKeys: expandedKeys.value,
checkedKeys: selectedValueList.value,
- onLoad: async (node: TreeOption) => {
- const treeNode = node as DatabaseTreeOption;
- if (treeNode.level === "database") {
- await dbSchemaStore.getOrFetchDatabaseMetadata({
- database: treeNode.value,
- view: DatabaseMetadataView.DATABASE_METADATA_VIEW_BASIC,
- });
- const database = databaseStore.getDatabaseByName(treeNode.value);
- const children = getSchemaOrTableTreeOptions({
- database,
- includeCloumn: props.includeCloumn,
- });
- if (children && children.length > 0) {
- treeNode.children = children;
- treeNode.isLeaf = false;
- } else {
- treeNode.isLeaf = true;
+ onLoad: onTreeNodeLoad,
+ onUpdateExpandedKeys: (keys: string[]) => {
+ expandedKeys.value = keys;
+ },
+ onUpdateCheckedKeys: async (
+ checkedKeys: string[],
+ _: Array<TreeOption | null>,
+ meta: { node: TreeOption | null; action: "check" | "uncheck" }
+ ) => {
+ if (!meta.node) {
+ return;
+ }
+
+ const newCheckedKeys = new Set(checkedKeys);
+
+ const treeNode = meta.node as DatabaseTreeOption;
+ if (meta.action === "check") {
+ await onTreeNodeLoad(treeNode);
+ // refresh node in case the schema is updated
+ const checkedNode = sourceTransferOptions.value.find(
+ (option) => option.value === treeNode.value
+ );
+ if (checkedNode) {
+ // check and expand all children
+ cascadeLoopTreeNode(checkedNode, (treeNode) => {
+ newCheckedKeys.add(treeNode.value);
+ if (treeNode.children) {
+ expandedKeys.value.push(treeNode.value);
+ }
+ });
}
}
- },
- onUpdateCheckedKeys: (checkedKeys: string[]) => {
- onCheck(checkedKeys);
+
+ onCheck([...newCheckedKeys]);
},
});
};
@@ -267,6 +379,11 @@ watch(selectedValueList, (selectedValueList) => {
const parentExisted = filteredKeyList.some((parent) =>
key.startsWith(`${parent}/`)
);
+ // If the parent node is selected, means all children should be selected.
+ // So we can ignore the children.
+ // For example, select table "employee"."public"."employee" and all its fields "emp_no" & "name",
+ // we only need the "employee"."public"."employee" to build the database resource,
+ // and the expression only need table level too (ignore the column means column = "*")
if (!parentExisted) {
filteredKeyList.push(key);
}
@@ -274,24 +391,9 @@ watch(selectedValueList, (selectedValueList) => {
emit(
"update:databaseResources",
- filteredKeyList.map((key) => {
- const [databaseName, schemaAndTable] = key.split("/schemas/");
- const databaseResource: DatabaseResource = {
- databaseName,
- };
- if (schemaAndTable) {
- const [schema, tableAndColumn] = schemaAndTable.split("/tables/");
- databaseResource.schema = schema;
- if (tableAndColumn) {
- const [table, column] = tableAndColumn.split("/columns/");
- databaseResource.table = table;
- if (column) {
- databaseResource.column = column;
- }
- }
- }
- return databaseResource;
- })
+ filteredKeyList
+ .map(parseKeyToResource)
+ .filter((data) => data) as DatabaseResource[]
);
});
</script>
diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/Label.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/Label.vue
index fc50cefaec..f102d5348a 100644
--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/Label.vue
+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/Label.vue
@@ -36,26 +36,26 @@ const option = computed(() => props.option);
const database = computed(() => {
const { option } = props;
- if (option.level !== "database") return undefined;
+ if (option.level !== "databases") return undefined;
return useDatabaseV1Store().getDatabaseByName(option.value);
});
const environment = computed(() => {
const { option } = props;
- if (option.level !== "database") return undefined;
+ if (option.level !== "databases") return undefined;
return database.value?.effectiveEnvironmentEntity;
});
const Prefix = () => {
- if (option.value.level === "database") {
+ if (option.value.level === "databases") {
return h(DatabaseIcon, {
class: "w-4 h-auto text-gray-400 shrink-0",
});
- } else if (option.value.level === "schema") {
+ } else if (option.value.level === "schemas") {
return h(SchemaIcon, {
class: "w-4 h-auto text-gray-400 shrink-0",
});
- } else if (option.value.level === "table") {
+ } else if (option.value.level === "tables") {
return h(TableIcon, {
class: "w-4 h-auto text-gray-400 shrink-0",
});
diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/common.ts b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/common.ts
index e5f43b2b94..d06e309bf0 100644
--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/common.ts
+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/common.ts
@@ -5,9 +5,16 @@ import type { ComposedDatabase } from "@/types";
import type { TableMetadata } from "@/types/proto/v1/database_service";
import { hasSchemaProperty } from "@/utils";
-export interface DatabaseTreeOption<
- L = "database" | "schema" | "table" | "column",
-> extends TreeOption {
+export type DatabaseResourceType =
+ | "databases"
+ | "schemas"
+ | "tables"
+ | "columns";
+
+export interface DatabaseTreeOption<L = DatabaseResourceType>
+ extends TreeOption,
+ TransferOption {
+ label: string;
level: L;
value: string;
children?: DatabaseTreeOption[];
@@ -22,7 +29,7 @@ export const mapTreeOptions = ({
filterValueList?: string[];
includeCloumn: boolean;
}) => {
- const databaseNodes: DatabaseTreeOption<"database">[] = [];
+ const databaseNodes: DatabaseTreeOption<"databases">[] = [];
const filteredDatabaseList = filterValueList
? databaseList.filter((database) =>
filterValueList.some(
@@ -31,8 +38,8 @@ export const mapTreeOptions = ({
)
: databaseList;
for (const database of filteredDatabaseList) {
- const databaseNode: DatabaseTreeOption<"database"> = {
- level: "database",
+ const databaseNode: DatabaseTreeOption<"databases"> = {
+ level: "databases",
value: database.name,
label: database.databaseName,
isLeaf: false,
@@ -61,18 +68,18 @@ const getTableTreeOptions = ({
tableList: TableMetadata[];
filterValueList?: string[];
includeCloumn: boolean;
-}): DatabaseTreeOption<"table">[] => {
- const tableNodes = tableList.map((table): DatabaseTreeOption<"table"> => {
- const option: DatabaseTreeOption<"table"> = {
- level: "table",
+}): DatabaseTreeOption<"tables">[] => {
+ const tableNodes = tableList.map((table): DatabaseTreeOption<"tables"> => {
+ const option: DatabaseTreeOption<"tables"> = {
+ level: "tables",
value: `${prefix}/tables/${table.name}`,
label: table.name,
isLeaf: true,
};
if (includeCloumn) {
option.children = table.columns.map(
- (column): DatabaseTreeOption<"column"> => ({
- level: "column",
+ (column): DatabaseTreeOption<"columns"> => ({
+ level: "columns",
value: `${option.value}/columns/${column.name}`,
label: column.name,
isLeaf: true,
@@ -116,10 +123,10 @@ export const getSchemaOrTableTreeOptions = ({
}
if (hasSchemaProperty(database.instanceResource.engine)) {
const schemaNodes = databaseMetadata.schemas.map(
- (schema): DatabaseTreeOption<"schema"> => {
+ (schema): DatabaseTreeOption<"schemas"> => {
const value = `${database.name}/schemas/${schema.name}`;
- const schemaNode: DatabaseTreeOption<"schema"> = {
- level: "schema",
+ const schemaNode: DatabaseTreeOption<"schemas"> = {
+ level: "schemas",
value,
label: schema.name,
children: getTableTreeOptions({
@@ -157,10 +164,10 @@ export const getSchemaOrTableTreeOptions = ({
export const flattenTreeOptions = (
options: DatabaseTreeOption[]
-): TransferOption[] => {
+): DatabaseTreeOption[] => {
return options.flatMap((option) => {
return [
- option as TransferOption,
+ option,
...flattenTreeOptions(
(option.children as DatabaseTreeOption[] | undefined) ?? []
),