Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: implement expression comparison interface and clean up PostgreSQL codebase (#17276)
rebeliceb12e407c1c15
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex 356f175013..efdc3b90a8 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -5,7 +5,6 @@ import ("github.com/bytebase/bytebase/backend/common"storepb "github.com/bytebase/bytebase/backend/generated-go/store"- "github.com/bytebase/bytebase/backend/plugin/schema/pg/ast""github.com/bytebase/bytebase/backend/store/model")@@ -390,7 +389,7 @@ func compareSchemaObjects(engine storepb.Engine, diff *MetadataDiff, schemaName// Compare table detailsoldTable := oldSchema.GetTable(tableName)if oldTable != nil && !oldTable.GetProto().GetSkipDump() {- tableDiff := compareTableDetails(schemaName, tableName, oldTable, newTable)+ tableDiff := compareTableDetails(engine, schemaName, tableName, oldTable, newTable)if tableDiff != nil {diff.TableChanges = append(diff.TableChanges, tableDiff)}@@ -421,7 +420,7 @@ func compareSchemaObjects(engine storepb.Engine, diff *MetadataDiff, schemaName}// compareTableDetails compares the details of two tables.-func compareTableDetails(schemaName, tableName string, oldTable, newTable *model.TableMetadata) *TableDiff {+func compareTableDetails(engine storepb.Engine, schemaName, tableName string, oldTable, newTable *model.TableMetadata) *TableDiff {tableDiff := &TableDiff{Action: MetadataDiffActionAlter,SchemaName: schemaName,@@ -433,14 +432,14 @@ func compareTableDetails(schemaName, tableName string, oldTable, newTable *modelhasChanges := false// Compare columns- columnChanges := compareColumns(oldTable, newTable)+ columnChanges := compareColumns(engine, oldTable, newTable)if len(columnChanges) > 0 {tableDiff.ColumnChanges = columnChangeshasChanges = true}// Compare indexes- indexChanges := compareIndexes(oldTable, newTable)+ indexChanges := compareIndexes(engine, oldTable, newTable)if len(indexChanges) > 0 {tableDiff.IndexChanges = indexChangeshasChanges = true@@ -454,14 +453,14 @@ func compareTableDetails(schemaName, tableName string, oldTable, newTable *model}// Compare check constraints- checkChanges := compareCheckConstraints(oldTable.GetProto().CheckConstraints, newTable.GetProto().CheckConstraints)+ checkChanges := compareCheckConstraints(engine, oldTable.GetProto().CheckConstraints, newTable.GetProto().CheckConstraints)if len(checkChanges) > 0 {tableDiff.CheckConstraintChanges = checkChangeshasChanges = true}// Compare partitions- partitionChanges := comparePartitions(oldTable.GetProto().Partitions, newTable.GetProto().Partitions)+ partitionChanges := comparePartitions(engine, oldTable.GetProto().Partitions, newTable.GetProto().Partitions)if len(partitionChanges) > 0 {tableDiff.PartitionChanges = partitionChangeshasChanges = true@@ -487,7 +486,7 @@ func compareTableDetails(schemaName, tableName string, oldTable, newTable *model}// compareColumns compares columns between two tables.-func compareColumns(oldTable, newTable *model.TableMetadata) []*ColumnDiff {+func compareColumns(engine storepb.Engine, oldTable, newTable *model.TableMetadata) []*ColumnDiff {var changes []*ColumnDiffoldColumns := oldTable.GetColumns()@@ -511,7 +510,7 @@ func compareColumns(oldTable, newTable *model.TableMetadata) []*ColumnDiff {Action: MetadataDiffActionCreate,NewColumn: newCol,})- } else if !columnsEqual(oldCol, newCol) {+ } else if !columnsEqual(engine, oldCol, newCol) {changes = append(changes, &ColumnDiff{Action: MetadataDiffActionAlter,OldColumn: oldCol,@@ -524,7 +523,7 @@ func compareColumns(oldTable, newTable *model.TableMetadata) []*ColumnDiff {}// columnsEqual checks if two columns are equal.-func columnsEqual(col1, col2 *storepb.ColumnMetadata) bool {+func columnsEqual(engine storepb.Engine, col1, col2 *storepb.ColumnMetadata) bool {if col1.Type != col2.Type {return false}@@ -554,7 +553,7 @@ func columnsEqual(col1, col2 *storepb.ColumnMetadata) bool {return false}// Compare generated column metadata- if !generationMetadataEqual(col1.Generation, col2.Generation) {+ if !generationMetadataEqual(engine, col1.Generation, col2.Generation) {return false}// Compare identity column metadata@@ -588,18 +587,18 @@ func defaultValuesEqual(col1, col2 *storepb.ColumnMetadata) bool {}// generationMetadataEqual compares two generation metadata structs.-func generationMetadataEqual(gen1, gen2 *storepb.GenerationMetadata) bool {+func generationMetadataEqual(engine storepb.Engine, gen1, gen2 *storepb.GenerationMetadata) bool {if gen1 == nil && gen2 == nil {return true}if gen1 == nil || gen2 == nil {return false}- return gen1.Type == gen2.Type && ast.CompareExpressionsSemantically(gen1.Expression, gen2.Expression)+ return gen1.Type == gen2.Type && CompareExpressionsSemantically(engine, gen1.Expression, gen2.Expression)}// compareIndexes compares indexes between two tables.-func compareIndexes(oldTable, newTable *model.TableMetadata) []*IndexDiff {+func compareIndexes(engine storepb.Engine, oldTable, newTable *model.TableMetadata) []*IndexDiff {var changes []*IndexDiffoldIndexes := oldTable.ListIndexes()@@ -623,7 +622,7 @@ func compareIndexes(oldTable, newTable *model.TableMetadata) []*IndexDiff {Action: MetadataDiffActionCreate,NewIndex: newIdx.GetProto(),})- } else if !indexesEqual(oldIdx.GetProto(), newIdx.GetProto()) {+ } else if !indexesEqual(engine, oldIdx.GetProto(), newIdx.GetProto()) {// Drop the old index and recreate the new one instead of alteringchanges = append(changes, &IndexDiff{Action: MetadataDiffActionDrop,@@ -640,7 +639,7 @@ func compareIndexes(oldTable, newTable *model.TableMetadata) []*IndexDiff {}// indexesEqual checks if two indexes are equal.-func indexesEqual(idx1, idx2 *storepb.IndexMetadata) bool {+func indexesEqual(engine storepb.Engine, idx1, idx2 *storepb.IndexMetadata) bool {if idx1.Type != idx2.Type {return false}@@ -654,7 +653,7 @@ func indexesEqual(idx1, idx2 *storepb.IndexMetadata) bool {return false}for i, expr := range idx1.Expressions {- if !ast.CompareExpressionsSemantically(expr, idx2.Expressions[i]) {+ if !CompareExpressionsSemantically(engine, expr, idx2.Expressions[i]) {return false}}@@ -953,7 +952,7 @@ func foreignKeysEqual(fk1, fk2 *storepb.ForeignKeyMetadata) bool {}// compareCheckConstraints compares two lists of check constraints.-func compareCheckConstraints(oldChecks, newChecks []*storepb.CheckConstraintMetadata) []*CheckConstraintDiff {+func compareCheckConstraints(engine storepb.Engine, oldChecks, newChecks []*storepb.CheckConstraintMetadata) []*CheckConstraintDiff {var changes []*CheckConstraintDiffoldCheckMap := make(map[string]*storepb.CheckConstraintMetadata)@@ -984,7 +983,7 @@ func compareCheckConstraints(oldChecks, newChecks []*storepb.CheckConstraintMetaAction: MetadataDiffActionCreate,NewCheckConstraint: newCheck,})- } else if !checkConstraintsEqual(oldCheck, newCheck) {+ } else if !checkConstraintsEqual(engine, oldCheck, newCheck) {// Drop the old constraint and recreate the new one instead of alteringchanges = append(changes, &CheckConstraintDiff{Action: MetadataDiffActionDrop,@@ -1001,9 +1000,9 @@ func compareCheckConstraints(oldChecks, newChecks []*storepb.CheckConstraintMeta}// checkConstraintsEqual checks if two check constraints are equal.-func checkConstraintsEqual(check1, check2 *storepb.CheckConstraintMetadata) bool {+func checkConstraintsEqual(engine storepb.Engine, check1, check2 *storepb.CheckConstraintMetadata) bool {// First try semantic comparison- if ast.CompareExpressionsSemantically(check1.Expression, check2.Expression) {+ if CompareExpressionsSemantically(engine, check1.Expression, check2.Expression) {return true}@@ -1173,7 +1172,7 @@ func extractAnyValues(expr string) []string {}// comparePartitions compares two lists of partitions.-func comparePartitions(oldPartitions, newPartitions []*storepb.TablePartitionMetadata) []*PartitionDiff {+func comparePartitions(engine storepb.Engine, oldPartitions, newPartitions []*storepb.TablePartitionMetadata) []*PartitionDiff {var changes []*PartitionDiffoldPartMap := make(map[string]*storepb.TablePartitionMetadata)@@ -1204,7 +1203,7 @@ func comparePartitions(oldPartitions, newPartitions []*storepb.TablePartitionMetAction: MetadataDiffActionCreate,NewPartition: newPart,})- } else if !partitionsEqual(oldPart, newPart) {+ } else if !partitionsEqual(engine, oldPart, newPart) {// Drop the old partition and recreate the new one instead of alteringchanges = append(changes, &PartitionDiff{Action: MetadataDiffActionDrop,@@ -1273,18 +1272,53 @@ func triggersEqual(t1, t2 *storepb.TriggerMetadata) bool {if t1 == nil || t2 == nil {return t1 == t2}- return t1.Name == t2.Name &&++ basicEqual := t1.Name == t2.Name &&t1.Event == t2.Event &&- t1.Timing == t2.Timing &&- t1.Body == t2.Body+ t1.Timing == t2.Timing++ if !basicEqual {+ return false+ }++ // Direct comparison first+ if t1.Body == t2.Body {+ return true+ }++ // Normalize both bodies for comparison+ norm1 := normalizeTriggerBody(t1.Body)+ norm2 := normalizeTriggerBody(t2.Body)++ return norm1 == norm2+}++// normalizeTriggerBody normalizes trigger body for comparison+func normalizeTriggerBody(body string) string {+ if body == "" {+ return ""+ }++ // Aggressive normalization: remove ALL whitespace for comparison+ // This handles cases where ANTLR GetText() strips whitespace+ normalized := strings.ReplaceAll(body, " ", "")+ normalized = strings.ReplaceAll(normalized, "\r\n", "")+ normalized = strings.ReplaceAll(normalized, "\r", "")+ normalized = strings.ReplaceAll(normalized, "\n", "")+ normalized = strings.ReplaceAll(normalized, "\t", "")++ // Convert to uppercase for case-insensitive comparison+ normalized = strings.ToUpper(normalized)++ return normalized}// partitionsEqual checks if two partitions are equal.-func partitionsEqual(part1, part2 *storepb.TablePartitionMetadata) bool {+func partitionsEqual(engine storepb.Engine, part1, part2 *storepb.TablePartitionMetadata) bool {if part1.Type != part2.Type {return false}- if !ast.CompareExpressionsSemantically(part1.Expression, part2.Expression) {+ if !CompareExpressionsSemantically(engine, part1.Expression, part2.Expression) {return false}if part1.Value != part2.Value {@@ -1304,7 +1338,7 @@ func partitionsEqual(part1, part2 *storepb.TablePartitionMetadata) bool {}for _, sub2 := range part2.Subpartitions {sub1, exists := subPart1Map[sub2.Name]- if !exists || !partitionsEqual(sub1, sub2) {+ if !exists || !partitionsEqual(engine, sub1, sub2) {return false}}@@ -1528,7 +1562,7 @@ func compareFunctions(diff *MetadataDiff, schemaName string, oldSchema, newSchem// functionsEqual checks if two functions are equal.func functionsEqual(fn1, fn2 *storepb.FunctionMetadata) bool {if fn1.Definition != fn2.Definition {- // For PostgreSQL functions, try normalized comparison+ // Try normalized comparison for PostgreSQL functionsnorm1 := normalizePostgreSQLFunction(fn1.Definition)norm2 := normalizePostgreSQLFunction(fn2.Definition)if norm1 != norm2 {@@ -1585,7 +1619,7 @@ func compareProcedures(diff *MetadataDiff, schemaName string, oldSchema, newScheProcedureName: procName,NewProcedure: newProc.GetProto(),})- } else if !oldProc.GetProto().GetSkipDump() && oldProc.Definition != newProc.Definition {+ } else if !oldProc.GetProto().GetSkipDump() && !procedureDefinitionsEqual(oldProc.Definition, newProc.Definition, procName) {diff.ProcedureChanges = append(diff.ProcedureChanges, &ProcedureDiff{Action: MetadataDiffActionAlter,SchemaName: schemaName,@@ -1935,3 +1969,20 @@ func normalizePostgreSQLCheckConstraint(expression string) string {return strings.TrimSpace(expression)}++// procedureDefinitionsEqual compares procedure definitions with normalization+func procedureDefinitionsEqual(def1, def2, _ string) bool {+ if def1 == def2 {+ return true+ }++ // Try PostgreSQL normalization first+ norm1 := normalizePostgreSQLFunction(def1)+ norm2 := normalizePostgreSQLFunction(def2)+ if norm1 == norm2 {+ return true+ }++ // For other engines, fall back to simple comparison+ return false+}diff --git a/backend/plugin/schema/expression_comparer.go b/backend/plugin/schema/expression_comparer.gonew file mode 100644index 0000000000..abeb2a2a9e--- /dev/null+++ b/backend/plugin/schema/expression_comparer.go@@ -0,0 +1,43 @@+package schema++import (+ "strings"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ pgast "github.com/bytebase/bytebase/backend/plugin/schema/pg/ast"+)++// CompareExpressionsSemantically compares two expressions semantically based on the engine type.+func CompareExpressionsSemantically(engine storepb.Engine, expr1, expr2 string) bool {+ switch engine {+ case storepb.Engine_POSTGRES:+ return pgast.CompareExpressionsSemantically(expr1, expr2)+ default:+ // For unsupported engines, fall back to generic string-based comparison+ // This is safer than using engine-specific logic for unknown engines+ return compareExpressionsGeneric(expr1, expr2)+ }+}++// compareExpressionsGeneric provides a generic string-based comparison for unsupported engines+func compareExpressionsGeneric(expr1, expr2 string) bool {+ // Quick check for identical strings+ if expr1 == expr2 {+ return true+ }++ // Handle empty expressions+ if strings.TrimSpace(expr1) == "" && strings.TrimSpace(expr2) == "" {+ return true+ }+ if strings.TrimSpace(expr1) == "" || strings.TrimSpace(expr2) == "" {+ return false+ }++ // Normalize whitespace and compare+ norm1 := strings.Join(strings.Fields(expr1), " ")+ norm2 := strings.Join(strings.Fields(expr2), " ")++ // Case-insensitive comparison for SQL keywords+ return strings.EqualFold(norm1, norm2)+}diff --git a/backend/plugin/schema/pg/ast/expression_comparer.go b/backend/plugin/schema/pg/ast/expression_comparer.goindex 742419d44b..f349802529 100644--- a/backend/plugin/schema/pg/ast/expression_comparer.go+++ b/backend/plugin/schema/pg/ast/expression_comparer.go@@ -11,9 +11,6 @@ type ExpressionComparer interface {// CompareExpressions compares two expressions for semantic equivalenceCompareExpressions(expr1, expr2 string) (bool, error)- // NormalizeExpression normalizes expression to canonical form- NormalizeExpression(expr string) (string, error)-// ParseExpressionAST parses expression into ASTParseExpressionAST(expr string) (ExpressionAST, error)}@@ -220,21 +217,6 @@ func (c *PostgreSQLExpressionComparer) CompareExpressionListsUnordered(exprs1, ereturn true, nil}-// NormalizeExpressionList normalizes a list of expressions-func (c *PostgreSQLExpressionComparer) NormalizeExpressionList(exprs []string) ([]string, error) {- var normalized []string-- for _, expr := range exprs {- norm, err := c.NormalizeExpression(expr)- if err != nil {- return nil, err- }- normalized = append(normalized, norm)- }-- return normalized, nil-}-// ValidateExpression validates an expression for correctnessfunc (c *PostgreSQLExpressionComparer) ValidateExpression(expr string) error {if strings.TrimSpace(expr) == "" {@@ -421,16 +403,6 @@ func CompareExpressionsSemantically(expr1, expr2 string) bool {return result}-// NormalizeExpressionForComparison normalizes expression using default configuration-func NormalizeExpressionForComparison(expr string) string {- comparer := NewPostgreSQLExpressionComparer()- normalized, err := comparer.NormalizeExpression(expr)- if err != nil {- return expr // return original if normalization fails- }- return normalized-}-// CreatePostgreSQLExpressionComparer creates a PostgreSQL expression comparer with default settingsfunc CreatePostgreSQLExpressionComparer() ExpressionComparer {return NewPostgreSQLExpressionComparer()diff --git a/backend/plugin/schema/pg/ast/expression_comparer_production_test.go b/backend/plugin/schema/pg/ast/expression_comparer_production_test.goindex e7cea7d40b..cadf34c2a4 100644--- a/backend/plugin/schema/pg/ast/expression_comparer_production_test.go+++ b/backend/plugin/schema/pg/ast/expression_comparer_production_test.go@@ -709,16 +709,16 @@ func TestPostgreSQLExpressionComparer_BatchProcessing(t *testing.T) {"(price > 0)",}- normalized, err := comparer.NormalizeExpressionList(expressions)- require.NoError(t, err)- require.Len(t, normalized, len(expressions))+ // Each expression should parse consistently+ for _, expr := range expressions {+ ast, err := comparer.ParseExpressionAST(expr)+ require.NoError(t, err)+ require.NotNil(t, ast, "AST should not be nil: %s", expr)- // Each normalized expression should be consistent- for i, orig := range expressions {- renormalized, err := comparer.NormalizeExpression(normalized[i])+ // Test semantic comparison consistency+ equal, err := comparer.CompareExpressions(expr, expr)require.NoError(t, err)- require.Equal(t, normalized[i], renormalized,- "Normalized expression should be idempotent: %s", orig)+ require.True(t, equal, "Expression should be equal to itself: %s", expr)}})}@@ -820,10 +820,10 @@ func BenchmarkPostgreSQLExpressionComparer_ProductionScenarios(b *testing.B) {}})- b.Run(scenario.name+"_normalization", func(b *testing.B) {+ b.Run(scenario.name+"_parsing", func(b *testing.B) {b.ResetTimer()for i := 0; i < b.N; i++ {- _, _ = comparer.NormalizeExpression(scenario.expr1)+ _, _ = comparer.ParseExpressionAST(scenario.expr1)}})}diff --git a/backend/plugin/schema/pg/ast/expression_comparer_strict_test.go b/backend/plugin/schema/pg/ast/expression_comparer_strict_test.goindex 6c49402e5d..4749ef1455 100644--- a/backend/plugin/schema/pg/ast/expression_comparer_strict_test.go+++ b/backend/plugin/schema/pg/ast/expression_comparer_strict_test.go@@ -512,10 +512,10 @@ func TestPostgreSQLExpressionComparer_MemoryAndPerformance(t *testing.T) {require.NoError(t, err, "Should handle large expressions efficiently")require.True(t, result, "Large expressions should be comparable")- // Normalization should also work- normalized, err := comparer.NormalizeExpression(largeExpr)- require.NoError(t, err, "Should normalize large expressions efficiently")- require.NotEmpty(t, normalized, "Normalized expression should not be empty")+ // Parsing should also work+ ast, err := comparer.ParseExpressionAST(largeExpr)+ require.NoError(t, err, "Should parse large expressions efficiently")+ require.NotNil(t, ast, "Parsed AST should not be nil")})t.Run("performance_consistency", func(t *testing.T) {diff --git a/backend/plugin/schema/pg/ast/expression_comparer_test.go b/backend/plugin/schema/pg/ast/expression_comparer_test.goindex cb357a2c90..7e6060fca0 100644--- a/backend/plugin/schema/pg/ast/expression_comparer_test.go+++ b/backend/plugin/schema/pg/ast/expression_comparer_test.go@@ -207,91 +207,6 @@ func TestPostgreSQLExpressionComparer_CompareExpressions(t *testing.T) {}}-func TestPostgreSQLExpressionComparer_NormalizeExpression(t *testing.T) {- comparer := NewPostgreSQLExpressionComparer()-- tests := []struct {- name string- expr string- expected string- error bool- }{- {- name: "simple identifier",- expr: "column_name",- expected: "column_name",- },- {- name: "case normalization",- expr: "Column_Name",- expected: "column_name",- },- {- name: "remove public schema",- expr: "public.table.column",- expected: "table.column",- },- {- name: "preserve non-public schema",- expr: "myschema.table.column",- expected: "myschema.table.column",- },- {- name: "normalize operators",- expr: "a != b",- expected: "a <> b",- },- {- name: "remove irrelevant parentheses",- expr: "(column_name)",- expected: "column_name",- },- {- name: "function call normalization",- expr: "UPPER(Column)",- expected: "upper(column)",- },- {- name: "complex expression",- expr: "public.table.col1 = table2.col2 AND Status = 'ACTIVE'",- expected: "'ACTIVE' = status AND table.col1 = table2.col2", // commutative operators may be reordered- },- {- name: "empty expression",- expr: "",- expected: "",- },- {- name: "whitespace only",- expr: " ",- expected: "",- },- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- result, err := comparer.NormalizeExpression(test.expr)-- if test.error {- if err == nil {- t.Error("Expected error but got none")- }- return- }-- if err != nil {- t.Errorf("Unexpected error: %v", err)- return- }-- if result != test.expected {- t.Errorf("Expected '%s', got '%s' for normalizing '%s'",- test.expected, result, test.expr)- }- })- }-}-func TestPostgreSQLExpressionComparer_CompareExpressionLists(t *testing.T) {comparer := NewPostgreSQLExpressionComparer()@@ -573,41 +488,6 @@ func TestCompareExpressionsSemantically(t *testing.T) {}}-func TestNormalizeExpressionForComparison(t *testing.T) {- tests := []struct {- name string- expr string- expected string- }{- {- name: "simple identifier",- expr: "Column_Name",- expected: "column_name",- },- {- name: "remove public schema",- expr: "public.table.column",- expected: "table.column",- },- {- name: "normalize operators",- expr: "a != b",- expected: "a <> b",- },- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- result := NormalizeExpressionForComparison(test.expr)-- if result != test.expected {- t.Errorf("Expected '%s', got '%s' for normalizing '%s'",- test.expected, result, test.expr)- }- })- }-}-func TestPostgreSQLExpressionComparer_WithConfig(t *testing.T) {// Test case-sensitive configurationcomparer := NewPostgreSQLExpressionComparer().WithConfig(true, true, true, true)@@ -645,12 +525,3 @@ func BenchmarkCompareExpressionsSemantically(b *testing.B) {CompareExpressionsSemantically(expr1, expr2)}}--func BenchmarkNormalizeExpressionForComparison(b *testing.B) {- expr := "public.table1.column1 = table2.column2 AND Status = 'ACTIVE'"-- b.ResetTimer()- for i := 0; i < b.N; i++ {- NormalizeExpressionForComparison(expr)- }-}