Skip to content

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

feat: implement filter changed resources in ListChangeHistories (#7362)

rebelice73f0d36fdc85
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index acd0e6c6f3..682fce5faa 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -702,6 +702,9 @@ func (s *DatabaseService) ListChangeHistories(ctx context.Context, request *v1pb
if request.View == v1pb.ChangeHistoryView_CHANGE_HISTORY_VIEW_FULL {
find.ShowFull = true
}
+ if request.Filter != "" {
+ find.ResourcesFilter = &request.Filter
+ }
changeHistories, err := s.store.ListInstanceChangeHistory(ctx, find)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list change history, error: %v", err)
@@ -839,9 +842,45 @@ func convertToChangeHistory(h *store.InstanceChangeHistoryMessage) (*v1pb.Change
if h.IssueUID != nil {
v1pbHistory.Issue = fmt.Sprintf("%s%s/%s%d", common.ProjectNamePrefix, h.IssueProjectID, common.IssuePrefix, *h.IssueUID)
}
+ if h.Payload != nil && h.Payload.ChangedResources != nil {
+ v1pbHistory.ChangedResources = convertToChangedResources(h.Payload.ChangedResources)
+ }
return v1pbHistory, nil
}
+func convertToChangedResources(r *storepb.ChangedResources) *v1pb.ChangedResources {
+ result := &v1pb.ChangedResources{}
+ for _, database := range r.Databases {
+ v1Database := &v1pb.ChangedResourceDatabase{
+ Name: database.Name,
+ Schemas: []*v1pb.ChangedResourceSchema{},
+ }
+ for _, schema := range database.Schemas {
+ v1Schema := &v1pb.ChangedResourceSchema{
+ Name: schema.Name,
+ Tables: []*v1pb.ChangedResourceTable{},
+ }
+ for _, table := range schema.Tables {
+ v1Schema.Tables = append(v1Schema.Tables, &v1pb.ChangedResourceTable{
+ Name: table.Name,
+ })
+ }
+ sort.Slice(v1Schema.Tables, func(i, j int) bool {
+ return v1Schema.Tables[i].Name < v1Schema.Tables[j].Name
+ })
+ v1Database.Schemas = append(v1Database.Schemas, v1Schema)
+ }
+ sort.Slice(v1Database.Schemas, func(i, j int) bool {
+ return v1Database.Schemas[i].Name < v1Database.Schemas[j].Name
+ })
+ result.Databases = append(result.Databases, v1Database)
+ }
+ sort.Slice(result.Databases, func(i, j int) bool {
+ return result.Databases[i].Name < result.Databases[j].Name
+ })
+ return result
+}
+
func convertToPushEvent(e *storepb.PushEvent) *v1pb.PushEvent {
if e == nil {
return nil
diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.go
index 84d573bcfd..6ee88fd730 100644
--- a/backend/plugin/db/driver.go
+++ b/backend/plugin/db/driver.go
@@ -397,9 +397,10 @@ type MigrationHistory struct {
type MigrationHistoryFind struct {
ID *string
- Database *string
- Source *MigrationSource
- Version *string
+ Database *string
+ Source *MigrationSource
+ Version *string
+ ResourcesFilter *string
// If specified, then it will only fetch "Limit" most recent migration histories
Limit *int
Offset *int
diff --git a/backend/store/instance_change_history.go b/backend/store/instance_change_history.go
index 1273284ce7..ced6820a93 100644
--- a/backend/store/instance_change_history.go
+++ b/backend/store/instance_change_history.go
@@ -4,12 +4,17 @@ import (
"context"
"database/sql"
"fmt"
+ "sort"
"strconv"
"strings"
+ "github.com/google/cel-go/cel"
+ "github.com/google/cel-go/checker/decls"
"github.com/pkg/errors"
"google.golang.org/protobuf/encoding/protojson"
+ exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
+
"github.com/bytebase/bytebase/backend/plugin/db"
"github.com/bytebase/bytebase/backend/plugin/db/util"
storepb "github.com/bytebase/bytebase/proto/generated-go/store"
@@ -55,14 +60,15 @@ const instanceChangeHistoryTruncateLength = 1024 * 1024
// FindInstanceChangeHistoryMessage is for listing a list of instance change history.
type FindInstanceChangeHistoryMessage struct {
- ID *string
- InstanceID *int
- DatabaseID *int
- SheetID *int
- Source *db.MigrationSource
- Version *string
- Limit *int
- Offset *int
+ ID *string
+ InstanceID *int
+ DatabaseID *int
+ SheetID *int
+ Source *db.MigrationSource
+ Version *string
+ ResourcesFilter *string
+ Limit *int
+ Offset *int
// Truncate Statement, Schema, SchemaPrev unless ShowFull.
ShowFull bool
@@ -253,13 +259,14 @@ func convertInstanceChangeHistoryToMigrationHistory(change *InstanceChangeHistor
// FindInstanceChangeHistoryList finds a list of instance change history and returns as a list of migration history.
func (s *Store) FindInstanceChangeHistoryList(ctx context.Context, find *db.MigrationHistoryFind) ([]*db.MigrationHistory, error) {
findMessage := &FindInstanceChangeHistoryMessage{
- ID: find.ID,
- InstanceID: find.InstanceID,
- DatabaseID: find.DatabaseID,
- Source: find.Source,
- Version: find.Version,
- Limit: find.Limit,
- ShowFull: true,
+ ID: find.ID,
+ InstanceID: find.InstanceID,
+ DatabaseID: find.DatabaseID,
+ Source: find.Source,
+ Version: find.Version,
+ ResourcesFilter: find.ResourcesFilter,
+ Limit: find.Limit,
+ ShowFull: true,
}
list, err := s.ListInstanceChangeHistory(ctx, findMessage)
@@ -295,6 +302,218 @@ func (s *Store) FindInstanceChangeHistoryList(ctx context.Context, find *db.Migr
return migrationHistoryList, nil
}
+type resourceDatabase struct {
+ name string
+ schemas schemaMap
+}
+
+type databaseMap map[string]*resourceDatabase
+
+type resourceSchema struct {
+ name string
+ tables tableMap
+}
+
+type schemaMap map[string]*resourceSchema
+
+type resourceTable struct {
+ name string
+}
+
+type tableMap map[string]*resourceTable
+
+// The CEL filter MUST be a Disjunctive Normal Form (DNF) expression.
+// In other words, the CEL expression consists of several parts connected by OR operators.
+// For example, the following expression is valid:
+// (
+//
+// tableExists("db", "public", "table1") &&
+// tableExists("db", "public", "table2")
+//
+// ) || (
+//
+// tableExists("db", "public", "table3")
+//
+// )
+// .
+func generateResourceFilter(filter string) (string, error) {
+ env, err := cel.NewEnv(
+ cel.Declarations(
+ decls.NewFunction("tableExists", decls.NewOverload("tableExists_string", []*exprpb.Type{decls.String, decls.String, decls.String}, decls.Bool)),
+ ),
+ )
+ if err != nil {
+ return "", err
+ }
+
+ ast, iss := env.Compile(filter)
+ if iss != nil && iss.Err() != nil {
+ return "", iss.Err()
+ }
+
+ rewriter := &expressionRewriter{
+ metaMap: make(databaseMap),
+ }
+ if err := rewriter.rewriteExpression(ast.Expr()); err != nil {
+ return "", err
+ }
+
+ if len(rewriter.metaMap) != 0 {
+ if err := rewriter.appendDNFPart(); err != nil {
+ return "", err
+ }
+ }
+
+ if len(rewriter.dnfParts) == 0 {
+ return "", nil
+ }
+
+ var buf strings.Builder
+ if len(rewriter.dnfParts) > 1 {
+ if _, err := buf.WriteString("("); err != nil {
+ return "", err
+ }
+ }
+ for i, part := range rewriter.dnfParts {
+ if i > 0 {
+ if _, err := buf.WriteString(" OR "); err != nil {
+ return "", err
+ }
+ }
+ if _, err := buf.WriteString("(instance_change_history.payload @> '"); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString(part); err != nil {
+ return "", err
+ }
+ if _, err := buf.WriteString("'::jsonb)"); err != nil {
+ return "", err
+ }
+ }
+ if len(rewriter.dnfParts) > 1 {
+ if _, err := buf.WriteString(")"); err != nil {
+ return "", err
+ }
+ }
+ return buf.String(), nil
+}
+
+type expressionRewriter struct {
+ metaMap databaseMap
+ dnfParts []string
+}
+
+func (r *expressionRewriter) appendDNFPart() error {
+ if r.metaMap == nil {
+ return nil
+ }
+
+ defer func() {
+ r.metaMap = make(databaseMap)
+ }()
+
+ var meta storepb.ChangedResources
+ for _, dbMeta := range r.metaMap {
+ db := &storepb.ChangedResourceDatabase{
+ Name: dbMeta.name,
+ }
+ for _, schemaMeta := range dbMeta.schemas {
+ schema := &storepb.ChangedResourceSchema{
+ Name: schemaMeta.name,
+ }
+ for _, tableMeta := range schemaMeta.tables {
+ table := &storepb.ChangedResourceTable{
+ Name: tableMeta.name,
+ }
+ schema.Tables = append(schema.Tables, table)
+ }
+ sort.Slice(schema.Tables, func(i, j int) bool {
+ return schema.Tables[i].Name < schema.Tables[j].Name
+ })
+ db.Schemas = append(db.Schemas, schema)
+ }
+ sort.Slice(db.Schemas, func(i, j int) bool {
+ return db.Schemas[i].Name < db.Schemas[j].Name
+ })
+ meta.Databases = append(meta.Databases, db)
+ }
+ sort.Slice(meta.Databases, func(i, j int) bool {
+ return meta.Databases[i].Name < meta.Databases[j].Name
+ })
+
+ text, err := protojson.Marshal(&storepb.InstanceChangeHistoryPayload{
+ ChangedResources: &meta,
+ })
+ if err != nil {
+ return err
+ }
+ r.dnfParts = append(r.dnfParts, string(text))
+ return nil
+}
+
+func (r *expressionRewriter) rewriteExpression(expr *exprpb.Expr) error {
+ switch e := expr.ExprKind.(type) {
+ case *exprpb.Expr_CallExpr:
+ switch e.CallExpr.Function {
+ case "_||_":
+ for _, arg := range e.CallExpr.Args {
+ if err := r.rewriteExpression(arg); err != nil {
+ return err
+ }
+ if err := r.appendDNFPart(); err != nil {
+ return err
+ }
+ }
+ case "_&&_":
+ for _, arg := range e.CallExpr.Args {
+ if err := r.rewriteExpression(arg); err != nil {
+ return err
+ }
+ }
+ case "tableExists":
+ if len(e.CallExpr.Args) != 3 {
+ return errors.Errorf("invalid tableExists function call: %v, expected three arguments buf got %d", e.CallExpr, len(e.CallExpr.Args))
+ }
+ var args []string
+ for _, arg := range e.CallExpr.Args {
+ switch a := arg.ExprKind.(type) {
+ case *exprpb.Expr_ConstExpr:
+ switch a.ConstExpr.ConstantKind.(type) {
+ case *exprpb.Constant_StringValue:
+ args = append(args, a.ConstExpr.GetStringValue())
+ default:
+ return errors.Errorf("invalid tableExists function call: %v, expected string arguments buf got %v", e.CallExpr, arg)
+ }
+ default:
+ return errors.Errorf("invalid tableExists function call: %v, expected constant arguments buf got %v", e.CallExpr, arg)
+ }
+ }
+ database, ok := r.metaMap[args[0]]
+ if !ok {
+ database = &resourceDatabase{
+ name: args[0],
+ schemas: make(schemaMap),
+ }
+ r.metaMap[args[0]] = database
+ }
+ schema, ok := database.schemas[args[1]]
+ if !ok {
+ schema = &resourceSchema{
+ name: args[1],
+ tables: make(tableMap),
+ }
+ database.schemas[args[1]] = schema
+ }
+ schema.tables[args[2]] = &resourceTable{
+ name: args[2],
+ }
+ }
+ default:
+ return errors.Errorf("invalid expression: %v", expr)
+ }
+ return nil
+}
+
// ListInstanceChangeHistory finds the instance change history.
func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanceChangeHistoryMessage) ([]*InstanceChangeHistoryMessage, error) {
where, args := []string{"TRUE"}, []any{}
@@ -324,6 +543,15 @@ func (s *Store) ListInstanceChangeHistory(ctx context.Context, find *FindInstanc
if v := find.Version; v != nil {
where, args = append(where, fmt.Sprintf("instance_change_history.version = $%d", len(args)+1)), append(args, *v)
}
+ if v := find.ResourcesFilter; v != nil {
+ text, err := generateResourceFilter(*v)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to generate resource filter from %q", *v)
+ }
+ if text != "" {
+ where = append(where, text)
+ }
+ }
statementField := fmt.Sprintf("LEFT(instance_change_history.statement, %d)", instanceChangeHistoryTruncateLength)
if find.ShowFull {
diff --git a/backend/store/instance_change_history_test.go b/backend/store/instance_change_history_test.go
new file mode 100644
index 0000000000..2cd90f59ad
--- /dev/null
+++ b/backend/store/instance_change_history_test.go
@@ -0,0 +1,43 @@
+package store
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestGenerateResourceFilter(t *testing.T) {
+ tests := []struct {
+ filter string
+ expected string
+ }{
+ {
+ filter: `tableExists("db1", "schema1", "table1")`,
+ expected: `(instance_change_history.payload @> '{"changedResources":{"databases":[{"name":"db1", "schemas":[{"name":"schema1", "tables":[{"name":"table1"}]}]}]}}'::jsonb)`,
+ },
+ {
+ filter: `
+ tableExists("db1", "schema1", "table1") ||
+ tableExists("db1", "schema2", "table2")
+ `,
+ expected: `((instance_change_history.payload @> '{"changedResources":{"databases":[{"name":"db1", "schemas":[{"name":"schema1", "tables":[{"name":"table1"}]}]}]}}'::jsonb) OR (instance_change_history.payload @> '{"changedResources":{"databases":[{"name":"db1", "schemas":[{"name":"schema2", "tables":[{"name":"table2"}]}]}]}}'::jsonb))`,
+ },
+ {
+ filter: `
+ (
+ tableExists("db1", "schema1", "table1")
+ && tableExists("db1", "schema2", "table2")
+ ) || (
+ tableExists("db2", "schema1", "table1")
+ )
+ `,
+ expected: `((instance_change_history.payload @> '{"changedResources":{"databases":[{"name":"db1", "schemas":[{"name":"schema1", "tables":[{"name":"table1"}]}, {"name":"schema2", "tables":[{"name":"table2"}]}]}]}}'::jsonb) OR (instance_change_history.payload @> '{"changedResources":{"databases":[{"name":"db2", "schemas":[{"name":"schema1", "tables":[{"name":"table1"}]}]}]}}'::jsonb))`,
+ },
+ }
+
+ for _, test := range tests {
+ text, err := generateResourceFilter(test.filter)
+ require.NoError(t, err)
+ require.Equal(t, test.expected, text, test.filter)
+ }
+}
diff --git a/frontend/src/types/proto/v1/database_service.ts b/frontend/src/types/proto/v1/database_service.ts
index 65e871705f..b5c2c6e249 100644
--- a/frontend/src/types/proto/v1/database_service.ts
+++ b/frontend/src/types/proto/v1/database_service.ts
@@ -1238,17 +1238,24 @@ export interface ListChangeHistoriesRequest {
/**
* The filter of the change histories.
* Follow the CEL syntax.
- * currently, we have three attributes for CEL:
- * - resource.database
- * - resource.schema
- * - resource.table
+ * currently, we have one function for CEL:
+ * - tableExists(database, schema, table): return true if the table exists in changed resources.
+ *
* examples:
- * if you want to filter by databases, you should use:
- * resource.database in ["db1", "db2"]
- * even if you only want to filter by one database, you should use the array syntax.
- * if you want to filter by tables, you should use:
- * resource.database = "db1" && resource.schema = "" && resource.table in ["table1", "table2"]
- * Empty schema name is for no schema database engines, such as MySQL.
+ * Use
+ * tableExists("db", "public", "table1")
+ * to filter the change histories which have the table "table1" in the schema "public" of the database "db".
+ * For MySQL, the schema is always "", such as tableExists("db", "", "table1").
+ *
+ * Combine multiple functions with "&&" and "||", we MUST use the Disjunctive Normal Form(DNF).
+ * In other words, the CEL expression consists of several parts connected by OR operators.
+ * For example, the following expression is valid:
+ * (
+ * tableExists("db", "public", "table1") &&
+ * tableExists("db", "public", "table2")
+ * ) || (
+ * tableExists("db", "public", "table3")
+ * )
*/
filter: string;
}
diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.md
index 2f32d67447..fcf11f10de 100644
--- a/proto/gen/grpc-doc/v1/README.md
+++ b/proto/gen/grpc-doc/v1/README.md
@@ -2868,7 +2868,11 @@ When paginating, all other parameters provided to `ListBackup` must match the ca
When paginating, all other parameters provided to `ListChangeHistories` must match the call that provided the page token. |
| view | [ChangeHistoryView](#bytebase-v1-ChangeHistoryView) | | |
-| filter | [string](#string) | | The filter of the change histories. Follow the CEL syntax. currently, we have three attributes for CEL: - resource.database - resource.schema - resource.table examples: if you want to filter by databases, you should use: resource.database in [&#34;db1&#34;, &#34;db2&#34;] even if you only want to filter by one database, you should use the array syntax. if you want to filter by tables, you should use: resource.database = &#34;db1&#34; &amp;&amp; resource.schema = &#34;&#34; &amp;&amp; resource.table in [&#34;table1&#34;, &#34;table2&#34;] Empty schema name is for no schema database engines, such as MySQL. |
+| filter | [string](#string) | | The filter of the change histories. Follow the CEL syntax. currently, we have one function for CEL: - tableExists(database, schema, table): return true if the table exists in changed resources.
+
+examples: Use tableExists(&#34;db&#34;, &#34;public&#34;, &#34;table1&#34;) to filter the change histories which have the table &#34;table1&#34; in the schema &#34;public&#34; of the database &#34;db&#34;. For MySQL, the schema is always &#34;&#34;, such as tableExists(&#34;db&#34;, &#34;&#34;, &#34;table1&#34;).
+
+Combine multiple functions with &#34;&amp;&amp;&#34; and &#34;||&#34;, we MUST use the Disjunctive Normal Form(DNF). In other words, the CEL expression consists of several parts connected by OR operators. For example, the following expression is valid: ( tableExists(&#34;db&#34;, &#34;public&#34;, &#34;table1&#34;) &amp;&amp; tableExists(&#34;db&#34;, &#34;public&#34;, &#34;table2&#34;) ) || ( tableExists(&#34;db&#34;, &#34;public&#34;, &#34;table3&#34;) ) |
diff --git a/proto/generated-go/v1/database_service.pb.go b/proto/generated-go/v1/database_service.pb.go
index 81499d97ac..bb32b1c933 100644
--- a/proto/generated-go/v1/database_service.pb.go
+++ b/proto/generated-go/v1/database_service.pb.go
@@ -4389,18 +4389,30 @@ type ListChangeHistoriesRequest struct {
View ChangeHistoryView `protobuf:"varint,4,opt,name=view,proto3,enum=bytebase.v1.ChangeHistoryView" json:"view,omitempty"`
// The filter of the change histories.
// Follow the CEL syntax.
- // currently, we have three attributes for CEL:
- // - resource.database
- // - resource.schema
- // - resource.table
+ // currently, we have one function for CEL:
+ // - tableExists(database, schema, table): return true if the table exists in changed resources.
+ //
// examples:
+ // Use
+ //
+ // tableExists("db", "public", "table1")
+ //
+ // to filter the change histories which have the table "table1" in the schema "public" of the database "db".
+ // For MySQL, the schema is always "", such as tableExists("db", "", "table1").
+ //
+ // Combine multiple functions with "&&" and "||", we MUST use the Disjunctive Normal Form(DNF).
+ // In other words, the CEL expression consists of several parts connected by OR operators.
+ // For example, the following expression is valid:
+ // (
+ //
+ // tableExists("db", "public", "table1") &&
+ // tableExists("db", "public", "table2")
+ //
+ // ) || (
+ //
+ // tableExists("db", "public", "table3")
//
- // if you want to filter by databases, you should use:
- // resource.database in ["db1", "db2"]
- // even if you only want to filter by one database, you should use the array syntax.
- // if you want to filter by tables, you should use:
- // resource.database = "db1" && resource.schema = "" && resource.table in ["table1", "table2"]
- // Empty schema name is for no schema database engines, such as MySQL.
+ // )
Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"`
}
diff --git a/proto/v1/database_service.proto b/proto/v1/database_service.proto
index b79cd58e92..b8ff233d48 100644
--- a/proto/v1/database_service.proto
+++ b/proto/v1/database_service.proto
@@ -1009,17 +1009,24 @@ message ListChangeHistoriesRequest {
// The filter of the change histories.
// Follow the CEL syntax.
- // currently, we have three attributes for CEL:
- // - resource.database
- // - resource.schema
- // - resource.table
+ // currently, we have one function for CEL:
+ // - tableExists(database, schema, table): return true if the table exists in changed resources.
+ //
// examples:
- // if you want to filter by databases, you should use:
- // resource.database in ["db1", "db2"]
- // even if you only want to filter by one database, you should use the array syntax.
- // if you want to filter by tables, you should use:
- // resource.database = "db1" && resource.schema = "" && resource.table in ["table1", "table2"]
- // Empty schema name is for no schema database engines, such as MySQL.
+ // Use
+ // tableExists("db", "public", "table1")
+ // to filter the change histories which have the table "table1" in the schema "public" of the database "db".
+ // For MySQL, the schema is always "", such as tableExists("db", "", "table1").
+ //
+ // Combine multiple functions with "&&" and "||", we MUST use the Disjunctive Normal Form(DNF).
+ // In other words, the CEL expression consists of several parts connected by OR operators.
+ // For example, the following expression is valid:
+ // (
+ // tableExists("db", "public", "table1") &&
+ // tableExists("db", "public", "table2")
+ // ) || (
+ // tableExists("db", "public", "table3")
+ // )
string filter = 5;
}