Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: support filter by table (#16635)
ecmadao80374bea62f3
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.goindex fa7d9a2512..2e937fc40b 100644--- a/backend/api/v1/database_service.go+++ b/backend/api/v1/database_service.go@@ -243,6 +243,16 @@ func getListDatabaseFilter(filter string) (*store.ListResourceFilter, error) {return fmt.Sprintf("db.project != $%d", len(positionalArgs)), nil}return "TRUE", nil+ case "table":+ positionalArgs = append(positionalArgs, value.(string))+ return fmt.Sprintf(`+ EXISTS (+ SELECT 1+ FROM json_array_elements(ds.metadata->'schemas') AS s,+ json_array_elements(s->'tables') AS t+ WHERE t->>'name' = $%d+ )+ `, len(positionalArgs)), nildefault:return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupport variable %q", variable))}@@ -267,14 +277,24 @@ func getListDatabaseFilter(filter string) (*store.ListResourceFilter, error) {return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`invalid args for %q`, variable))}value := args[0].AsLiteral().Value()- if variable != "name" {- return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`only "name" support %q operator, but found %q`, celoverloads.Matches, variable))- }strValue, ok := value.(string)if !ok {return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf("expect string, got %T, hint: filter literals should be string", value))}- return "LOWER(db.name) LIKE '%" + strings.ToLower(strValue) + "%'", nil+ strValue = strings.ToLower(strValue)++ switch variable {+ case "name":+ return "LOWER(db.name) LIKE '%" + strValue + "%'", nil+ case "table":+ return `EXISTS (+ SELECT 1+ FROM json_array_elements(ds.metadata->'schemas') AS s,+ json_array_elements(s->'tables') AS t+ WHERE t->>'name' LIKE '%` + strValue + `%')`, nil+ default:+ return "", connect.NewError(connect.CodeInvalidArgument, errors.Errorf(`only "name" or "table" support %q operator, but found %q`, celoverloads.Matches, variable))+ }case celoperators.In:return parseToEngineSQL(expr, "IN")case celoperators.LogicalNot:diff --git a/backend/store/database.go b/backend/store/database.goindex f2e4d39c65..bdb6196fd2 100644--- a/backend/store/database.go+++ b/backend/store/database.go@@ -347,9 +347,14 @@ func (s *Store) BatchUpdateDatabases(ctx context.Context, databases []*DatabaseMfunc (*Store) listDatabaseImplV2(ctx context.Context, txn *sql.Tx, find *FindDatabaseMessage) ([]*DatabaseMessage, error) {where, args := []string{"TRUE"}, []any{}+ joinQuery := ""if filter := find.Filter; filter != nil {where = append(where, filter.Where)args = append(args, filter.Args...)++ if strings.Contains(filter.Where, "ds.metadata->'schemas'") {+ joinQuery = "INNER JOIN db_schema ds ON db.instance = ds.instance AND db.name = ds.db_name"+ }}if v := find.ProjectID; v != nil {where, args = append(where, fmt.Sprintf("db.project = $%d", len(args)+1)), append(args, *v)@@ -393,9 +398,10 @@ func (*Store) listDatabaseImplV2(ctx context.Context, txn *sql.Tx, find *FindDatdb.deleted,db.metadataFROM db+ %sLEFT JOIN instance ON db.instance = instance.resource_idWHERE %s- ORDER BY db.project, db.instance, db.name`, strings.Join(where, " AND "))+ ORDER BY db.project, db.instance, db.name`, joinQuery, strings.Join(where, " AND "))if v := find.Limit; v != nil {query += fmt.Sprintf(" LIMIT %d", *v)}diff --git a/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts b/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.tsindex 4e28a6e976..636b4bddc9 100644--- a/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts+++ b/frontend/src/components/AdvancedSearch/useCommonSearchScopeOptions.ts@@ -159,6 +159,12 @@ export const useCommonSearchScopeOptions = (),allowMultiple: true,}),+ table: () => ({+ id: "table",+ title: t("issue.advanced-search.scope.table.title"),+ description: t("issue.advanced-search.scope.table.description"),+ allowMultiple: false,+ }),engine: () => ({id: "engine",title: t("issue.advanced-search.scope.engine.title"),diff --git a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vueindex c673637d2e..1258dd085e 100644--- a/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue+++ b/frontend/src/components/GrantRequestPanel/DatabaseResourceForm/DatabaseResourceSelector.vue@@ -5,6 +5,7 @@:autofocus="false":placeholder="$t('database.filter-database')":scope-options="scopeOptions"+ :override-route-query="false"/><NTransferid="database-resource-selector"@@ -44,7 +45,11 @@ import {instanceNamePrefix,environmentNamePrefix,} from "@/store/modules/v1/common";-import { DEBOUNCE_SEARCH_DELAY, type ComposedDatabase, type DatabaseResource } from "@/types";+import {+ DEBOUNCE_SEARCH_DELAY,+ type ComposedDatabase,+ type DatabaseResource,+} from "@/types";import { engineFromJSON } from "@/types/proto/v1/common";import {getDefaultPagination,@@ -84,6 +89,7 @@ const scopeOptions = useCommonSearchScopeOptions(["project","database-label","engine",+ "table",]);const parseResourceToKey = (resource: DatabaseResource): string => {@@ -172,6 +178,44 @@ const selectedEnvironment = computed(() => {return `${environmentNamePrefix}${environmentId}`;});+const selectedTable = computed(() => {+ return params.value.scopes.find((scope) => scope.id === "table")?.value;+});++const collectExpandedKeys = async ({+ database,+ table,+}: {+ database: string;+ table: string;+}) => {+ const databaseMetadata = await dbSchemaStore.getOrFetchDatabaseMetadata({+ database,+ });+ if (!databaseMetadata) {+ return;+ }+ expandedKeys.value.push(database);+ for (const schema of databaseMetadata.schemas) {+ expandedKeys.value.push(`${database}/schemas/${schema.name}`);+ for (const t of schema.tables) {+ if (t.name === table) {+ expandedKeys.value.push(+ `${database}/schemas/${schema.name}/tables/${t.name}`+ );+ }+ }+ }+};++const filterTableList = computed(() => {+ if (!selectedTable.value) {+ return undefined;+ }++ return expandedKeys.value;+});+const selectedLabels = computed(() => {return params.value.scopes.filter((scope) => scope.id === "database-label")@@ -191,6 +235,7 @@ const databaseFilter = computed(query: params.value.query,labels: selectedLabels.value,engines: selectedEngines.value,+ table: selectedTable.value,}));@@ -208,6 +253,7 @@ const fetchDatabaseList = useDebounceFn(async () => {if (pageToken) {databaseList.value.push(...databases);+ databaseList.value = uniqBy(databaseList.value, (db) => db.name);} else {databaseList.value = databases;}@@ -221,6 +267,7 @@ watch(() => databaseFilter.value,async () => {fetchDataState.value.nextPageToken = "";+ expandedKeys.value = [];await fetchDatabaseList();if (!params.value.query && params.value.scopes.length === 1) {databaseList.value = uniqBy(@@ -233,6 +280,16 @@ watch((db) => db.name);}++ if (databaseFilter.value.table) {+ // expand all+ for (const database of databaseList.value) {+ await collectExpandedKeys({+ database: database.name,+ table: databaseFilter.value.table,+ });+ }+ }},{deep: true,@@ -340,6 +397,7 @@ const sourceTreeOptions = computed(() => {return mapTreeOptions({databaseList: databaseList.value,includeCloumn: props.includeCloumn,+ filterValueList: filterTableList.value,});});diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 6d9d708644..2b192914b8 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -867,8 +867,12 @@"title": "Label","description": "Filter by issue label"},+ "table": {+ "title": "Table",+ "description": "Input the value then press Enter"+ },"database-label": {- "title": "Label",+ "title": "Database Label","description": "Input the \"key:value\" pair then press Enter"},"engine": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex f74568a1f2..f0a2ce02e1 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -867,8 +867,12 @@"title": "Etiqueta","description": "Filtrar por etiqueta de problema"},+ "table": {+ "title": "Mesa",+ "description": "Ingrese el valor y luego presione Enter"+ },"database-label": {- "title": "Etiqueta",+ "title": "Etiqueta de base de datos","description": "Ingrese la \"key:value\" y luego presione Enter"},"engine": {@@ -2787,4 +2791,4 @@"last-visit": "Última visita","changelog-for-version": "Registro de cambios para {version}"}-}+}\ No newline at end of filediff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex bab2654859..623b2fd73f 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -867,8 +867,12 @@"title": "ラベル","description": "イシュータグで絞り込む"},+ "table": {+ "title": "テーブル",+ "description": "値を入力してEnterを押します"+ },"database-label": {- "title": "ラベル",+ "title": "データベースラベル","description": "\"key:value\"を入力し、Enterを押します。"},"engine": {@@ -2787,4 +2791,4 @@"last-visit": "最終訪問","changelog-for-version": "{version} の変更履歴"}-}+}\ No newline at end of filediff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 972c74f8ee..b633e055c5 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -867,8 +867,12 @@"title": "Nhãn","description": "Lọc theo nhãn vấn đề"},+ "table": {+ "title": "bề mặt",+ "description": "Nhập giá trị sau đó nhấn Enter"+ },"database-label": {- "title": "Nhãn",+ "title": "Nhãn cơ sở dữ liệu","description": "Nhập \"key:value\" rồi nhấn Enter"},"engine": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 0e1f4f4ed9..abcc6ce984 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -867,8 +867,12 @@"title": "标签","description": "按工单标签过滤"},+ "table": {+ "title": "表",+ "description": "输入值然后按 Enter"+ },"database-label": {- "title": "标签",+ "title": "数据库标签","description": "输入 \"key:value\" 后按下回车"},"engine": {diff --git a/frontend/src/store/modules/v1/database.ts b/frontend/src/store/modules/v1/database.tsindex 40026453dd..d0a504e21f 100644--- a/frontend/src/store/modules/v1/database.ts+++ b/frontend/src/store/modules/v1/database.ts@@ -41,6 +41,7 @@ export interface DatabaseFilter {engines?: Engine[];excludeEngines?: Engine[];drifted?: boolean;+ table?: string;}const isValidParentName = (parent: string): boolean => {@@ -108,6 +109,9 @@ const getListDatabaseFilter = (filter: DatabaseFilter): string => {params.push(`label == "${labelKey}:${[...labelValues].join(",")}"`);}}+ if (filter.table) {+ params.push(`table.matches("${filter.table}")`);+ }return params.join(" && ");};diff --git a/frontend/src/types/proto-es/v1/database_service_pb.d.ts b/frontend/src/types/proto-es/v1/database_service_pb.d.tsindex 43cfed3c2c..fb5f6063ea 100644--- a/frontend/src/types/proto-es/v1/database_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/database_service_pb.d.ts@@ -125,6 +125,7 @@ export declare type ListDatabasesRequest = Message<"bytebase.v1.ListDatabasesReq* - label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.* - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.* - drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ * - table: filter by the database table, support "==" and ".matches()" operator.** For example:* environment == "environments/{environment resource id}"@@ -139,6 +140,9 @@ export declare type ListDatabasesRequest = Message<"bytebase.v1.ListDatabasesReq* label == "region:asia" && label == "tenant:bytebase"* exclude_unassigned == true* drifted == true+ * table == "sample"+ * table.matches("sam")+ ** You can combine filter conditions like:* environment == "environments/prod" && name.matches("employee")*diff --git a/frontend/src/types/proto/v1/database_service.ts b/frontend/src/types/proto/v1/database_service.tsindex 9b13efdb4f..d9e860de2f 100644--- a/frontend/src/types/proto/v1/database_service.ts+++ b/frontend/src/types/proto/v1/database_service.ts@@ -132,6 +132,7 @@ export interface ListDatabasesRequest {* - label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.* - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.* - drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ * - table: filter by the database table, support "==" and ".matches()" operator.** For example:* environment == "environments/{environment resource id}"@@ -146,6 +147,9 @@ export interface ListDatabasesRequest {* label == "region:asia" && label == "tenant:bytebase"* exclude_unassigned == true* drifted == true+ * table == "sample"+ * table.matches("sam")+ ** You can combine filter conditions like:* environment == "environments/prod" && name.matches("employee")*/diff --git a/frontend/src/utils/v1/advanced-search/common.ts b/frontend/src/utils/v1/advanced-search/common.tsindex 4ef2a2023e..cb33dc96a0 100644--- a/frontend/src/utils/v1/advanced-search/common.ts+++ b/frontend/src/utils/v1/advanced-search/common.ts@@ -28,6 +28,7 @@ export const AllSearchScopeIdList = ["engine","database-label","drifted",+ "table",// issue related search scopes."subscriber","issue-label",diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex c92c00f35c..4287a06e8e 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -1134,6 +1134,7 @@ paths:- label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.- drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ - table: filter by the database table, support "==" and ".matches()" operator.For example:environment == "environments/{environment resource id}"@@ -1148,6 +1149,9 @@ paths:label == "region:asia" && label == "tenant:bytebase"exclude_unassigned == truedrifted == true+ table == "sample"+ table.matches("sam")+You can combine filter conditions like:environment == "environments/prod" && name.matches("employee")schema:@@ -4062,6 +4066,7 @@ paths:- label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.- drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ - table: filter by the database table, support "==" and ".matches()" operator.For example:environment == "environments/{environment resource id}"@@ -4076,6 +4081,9 @@ paths:label == "region:asia" && label == "tenant:bytebase"exclude_unassigned == truedrifted == true+ table == "sample"+ table.matches("sam")+You can combine filter conditions like:environment == "environments/prod" && name.matches("employee")schema:@@ -7852,6 +7860,7 @@ paths:- label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.- drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ - table: filter by the database table, support "==" and ".matches()" operator.For example:environment == "environments/{environment resource id}"@@ -7866,6 +7875,9 @@ paths:label == "region:asia" && label == "tenant:bytebase"exclude_unassigned == truedrifted == true+ table == "sample"+ table.matches("sam")+You can combine filter conditions like:environment == "environments/prod" && name.matches("employee")schema:diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 9a3f46f61c..85b72ed5ab 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -2654,9 +2654,11 @@ Combine multiple functions with "&&" and "||", we MUST uWhen paginating, all other parameters provided to `ListDatabases` must match the call that provided the page token. || filter | [string](#string) | | Filter is used to filter databases returned in the list. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec-Supported filter: - environment: the environment full name in "environments/{id}" format, support "==" operator. - name: the database name, support ".matches()" operator. - project: the project full name in "projects/{id}" format, support "==" operator. - instance: the instance full name in "instances/{id}" format, support "==" operator. - engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator. - label: the database label in "{key}:{value1},{value2}" format. Support "==" operator. - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator. - drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+Supported filter: - environment: the environment full name in "environments/{id}" format, support "==" operator. - name: the database name, support ".matches()" operator. - project: the project full name in "projects/{id}" format, support "==" operator. - instance: the instance full name in "instances/{id}" format, support "==" operator. - engine: the database engine, check Engine enum for values. Support "==", "in [xx]", "!(in [xx])" operator. - label: the database label in "{key}:{value1},{value2}" format. Support "==" operator. - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator. - drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator. - table: filter by the database table, support "==" and ".matches()" operator.-For example: environment == "environments/{environment resource id}" project == "projects/{project resource id}" instance == "instances/{instance resource id}" name.matches("database name") engine == "MYSQL" engine in ["MYSQL", "POSTGRES"] !(engine in ["MYSQL", "POSTGRES"]) label == "region:asia" label == "tenant:asia,europe" label == "region:asia" && label == "tenant:bytebase" exclude_unassigned == true drifted == true You can combine filter conditions like: environment == "environments/prod" && name.matches("employee") |+For example: environment == "environments/{environment resource id}" project == "projects/{project resource id}" instance == "instances/{instance resource id}" name.matches("database name") engine == "MYSQL" engine in ["MYSQL", "POSTGRES"] !(engine in ["MYSQL", "POSTGRES"]) label == "region:asia" label == "tenant:asia,europe" label == "region:asia" && label == "tenant:bytebase" exclude_unassigned == true drifted == true table == "sample" table.matches("sam")++You can combine filter conditions like: environment == "environments/prod" && name.matches("employee") || show_deleted | [bool](#bool) | | Show deleted database if specified. |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 57850c480b..9ad1df7441 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -7986,6 +7986,7 @@ Supported filter:- label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.- exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.- drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+- table: filter by the database table, support "==" and ".matches()" operator.For example:environment == "environments/{environment resource id}"@@ -8000,6 +8001,9 @@ label == "tenant:asia,europe"label == "region:asia" && label == "tenant:bytebase"exclude_unassigned == truedrifted == true+table == "sample"+table.matches("sam")+You can combine filter conditions like:environment == "environments/prod" && name.matches("employee") </p></td></tr>diff --git a/proto/generated-go/v1/database_service.pb.go b/proto/generated-go/v1/database_service.pb.goindex 3da267b867..5a7c258649 100644--- a/proto/generated-go/v1/database_service.pb.go+++ b/proto/generated-go/v1/database_service.pb.go@@ -749,6 +749,7 @@ type ListDatabasesRequest struct {// - label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.// - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.// - drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ // - table: filter by the database table, support "==" and ".matches()" operator.//// For example:// environment == "environments/{environment resource id}"@@ -763,6 +764,9 @@ type ListDatabasesRequest struct {// label == "region:asia" && label == "tenant:bytebase"// exclude_unassigned == true// drifted == true+ // table == "sample"+ // table.matches("sam")+ //// You can combine filter conditions like:// environment == "environments/prod" && name.matches("employee")Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"`diff --git a/proto/v1/v1/database_service.proto b/proto/v1/v1/database_service.protoindex 91dd625927..3c15624218 100644--- a/proto/v1/v1/database_service.proto+++ b/proto/v1/v1/database_service.proto@@ -238,6 +238,7 @@ message ListDatabasesRequest {// - label: the database label in "{key}:{value1},{value2}" format. Support "==" operator.// - exclude_unassigned: should be "true" or "false", will not show unassigned databases if it's true, support "==" operator.// - drifted: should be "true" or "false", show drifted databases if it's true, support "==" operator.+ // - table: filter by the database table, support "==" and ".matches()" operator.//// For example:// environment == "environments/{environment resource id}"@@ -252,6 +253,9 @@ message ListDatabasesRequest {// label == "region:asia" && label == "tenant:bytebase"// exclude_unassigned == true// drifted == true+ // table == "sample"+ // table.matches("sam")+ //// You can combine filter conditions like:// environment == "environments/prod" && name.matches("employee")string filter = 4;