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(differ): non-strict mode for plsql (#10496)
rebelice28e550bc71d6
diff --git a/backend/plugin/parser/plsql/differ.go b/backend/plugin/parser/plsql/differ.goindex 5113beab8a..590469596b 100644--- a/backend/plugin/parser/plsql/differ.go+++ b/backend/plugin/parser/plsql/differ.go@@ -21,6 +21,11 @@ func init() {}type diffNode struct {+ // The different between the strict mode and non-strict mode is that the non-strict mode:+ // 1. does not compare the index or constraint name, use the definition instead.+ // 2. does not compare the storage option.+ strictMode bool+schemaName stringdropConstraint []stringdropIndex []string@@ -111,17 +116,18 @@ func (diff *diffNode) String() (string, error) {}// SchemaDiff implements the differ.SchemaDiffer interface.-func SchemaDiff(_ base.DiffContext, oldStmt, newStmt string) (string, error) {- oldSchemaInfo, err := buildSchemaInfo(oldStmt)+func SchemaDiff(ctx base.DiffContext, oldStmt, newStmt string) (string, error) {+ oldSchemaInfo, err := buildSchemaInfo(oldStmt, ctx.StrictMode)if err != nil {return "", errors.Wrapf(err, "failed to build schema info for old statement")}- newSchemaInfo, err := buildSchemaInfo(newStmt)+ newSchemaInfo, err := buildSchemaInfo(newStmt, ctx.StrictMode)if err != nil {return "", errors.Wrapf(err, "failed to build schema info for new statement")}diff := &diffNode{+ strictMode: ctx.StrictMode,schemaName: oldSchemaInfo.name,}var newTables []*tableInfo@@ -160,19 +166,21 @@ func SchemaDiff(_ base.DiffContext, oldStmt, newStmt string) (string, error) {newIndexes = append(newIndexes, index)}sort.Slice(newIndexes, func(i, j int) bool {- return newIndexes[i].id < newIndexes[j].id+ return newIndexes[i].pos < newIndexes[j].pos})for _, newIndex := range newIndexes {- indexName := newIndex.name- oldIndex, exists := oldSchemaInfo.indexMap[indexName]+ id := newIndex.id+ oldIndex, exists := oldSchemaInfo.indexMap[id]if !exists {diff.addIndex = append(diff.addIndex, newIndex.createIndex.GetParser().GetTokenStream().GetTextFromRuleContext(newIndex.createIndex))continue}- if err := diff.diffIndex(oldIndex, newIndex); err != nil {- return "", err+ if ctx.StrictMode {+ if err := diff.diffIndex(oldIndex, newIndex); err != nil {+ return "", err+ }}- delete(oldSchemaInfo.indexMap, indexName)+ delete(oldSchemaInfo.indexMap, id)}var remainingIndexes []*indexInfo@@ -180,7 +188,7 @@ func SchemaDiff(_ base.DiffContext, oldStmt, newStmt string) (string, error) {remainingIndexes = append(remainingIndexes, index)}sort.Slice(remainingIndexes, func(i, j int) bool {- return remainingIndexes[i].id < remainingIndexes[j].id+ return remainingIndexes[i].pos < remainingIndexes[j].pos})for _, index := range remainingIndexes {diff.dropIndex = append(diff.dropIndex, fmt.Sprintf(`DROP INDEX "%s"."%s";`, oldSchemaInfo.name, index.name))@@ -207,36 +215,46 @@ func (diff *diffNode) diffTable(oldTable, newTable *tableInfo) error {return diff.diffConstraint(oldTable, newTable)}-func buildConstraintMap(table *tableInfo) map[string]plsql.IRelational_propertyContext {+func (diff *diffNode) buildConstraintMap(table *tableInfo) map[string]plsql.IRelational_propertyContext {constraintMap := make(map[string]plsql.IRelational_propertyContext)if table.createTable.Relational_table() == nil {return constraintMap}for _, item := range table.createTable.Relational_table().AllRelational_property() {+ id := diff.getConstraintID(item)+ if id != "" {+ constraintMap[id] = item+ }+ }+ return constraintMap+}++func (diff *diffNode) getConstraintID(ctx plsql.IRelational_propertyContext) string {+ if diff.strictMode {switch {- case item.Out_of_line_constraint() != nil:- constraint := item.Out_of_line_constraint()+ case ctx.Out_of_line_constraint() != nil:+ constraint := ctx.Out_of_line_constraint()if constraint.Constraint_name() == nil {- continue+ return ""}_, constraintName := NormalizeConstraintName(constraint.Constraint_name())- if constraintName == "" {- continue- }- constraintMap[constraintName] = item- case item.Out_of_line_ref_constraint() != nil:- constraint := item.Out_of_line_ref_constraint()+ return constraintName+ case ctx.Out_of_line_ref_constraint() != nil:+ constraint := ctx.Out_of_line_ref_constraint()if constraint.Constraint_name() == nil {- continue+ return ""}_, constraintName := NormalizeConstraintName(constraint.Constraint_name())- if constraintName == "" {- continue- }- constraintMap[constraintName] = item+ return constraintName}+ } else if ctx.Out_of_line_constraint() != nil || ctx.Out_of_line_ref_constraint() != nil {+ return EraseString(EraseContext{+ eraseConstraintName: true,+ eraseSchemaName: true,+ eraseIndexName: true,+ }, ctx, ctx.GetParser().GetTokenStream())}- return constraintMap+ return ""}func (diff *diffNode) diffConstraint(oldTable, newTable *tableInfo) error {@@ -247,52 +265,45 @@ func (diff *diffNode) diffConstraint(oldTable, newTable *tableInfo) error {var addConstraints []plsql.IRelational_propertyContextvar dropConstraints []string- oldConstraintMap := buildConstraintMap(oldTable)+ oldConstraintMap := diff.buildConstraintMap(oldTable)for _, item := range newTable.createTable.Relational_table().AllRelational_property() {switch {case item.Out_of_line_constraint() != nil:- constraint := item.Out_of_line_constraint()- if constraint.Constraint_name() == nil {- continue- }- _, constraintName := NormalizeConstraintName(constraint.Constraint_name())- if constraintName == "" {+ id := diff.getConstraintID(item)+ if id == "" {continue}- oldConstraint, ok := oldConstraintMap[constraintName]+ oldConstraint, ok := oldConstraintMap[id]if !ok {addConstraints = append(addConstraints, item)continue}// Compare the constraint definition.- if !isConstraintEqual(oldConstraint, item) {+ if diff.strictMode && !isConstraintEqual(oldConstraint, item) {addConstraints = append(addConstraints, item)- dropConstraints = append(dropConstraints, constraintName)+ dropConstraints = append(dropConstraints, id)}- delete(oldConstraintMap, constraintName)+ delete(oldConstraintMap, id)case item.Out_of_line_ref_constraint() != nil:- constraint := item.Out_of_line_ref_constraint()- if constraint.Constraint_name() == nil {- continue- }- _, constraintName := NormalizeConstraintName(constraint.Constraint_name())- if constraintName == "" {- continue- }- oldConstraint, ok := oldConstraintMap[constraintName]+ id := diff.getConstraintID(item)+ oldConstraint, ok := oldConstraintMap[id]if !ok {addConstraints = append(addConstraints, item)continue}// Compare the constraint definition.- if !isConstraintEqual(oldConstraint, item) {+ if diff.strictMode && !isConstraintEqual(oldConstraint, item) {addConstraints = append(addConstraints, item)- dropConstraints = append(dropConstraints, constraintName)+ dropConstraints = append(dropConstraints, id)}- delete(oldConstraintMap, constraintName)+ delete(oldConstraintMap, id)}}- for constraintName := range oldConstraintMap {+ for _, item := range oldConstraintMap {+ constraintName := getConstraintName(item)+ if constraintName == "" {+ continue+ }dropConstraints = append(dropConstraints, constraintName)}@@ -303,6 +314,26 @@ func (diff *diffNode) diffConstraint(oldTable, newTable *tableInfo) error {return diff.appendConstraintDiff(newTable.name, addConstraints, dropConstraints)}+func getConstraintName(ctx plsql.IRelational_propertyContext) string {+ switch {+ case ctx.Out_of_line_constraint() != nil:+ constraint := ctx.Out_of_line_constraint()+ if constraint.Constraint_name() == nil {+ return ""+ }+ _, constraintName := NormalizeConstraintName(constraint.Constraint_name())+ return constraintName+ case ctx.Out_of_line_ref_constraint() != nil:+ constraint := ctx.Out_of_line_ref_constraint()+ if constraint.Constraint_name() == nil {+ return ""+ }+ _, constraintName := NormalizeConstraintName(constraint.Constraint_name())+ return constraintName+ }+ return ""+}+func (diff *diffNode) appendConstraintDiff(tableName string, addConstraints []plsql.IRelational_propertyContext, dropConstraints []string) error {for _, constraint := range addConstraints {if err := diff.appendAddConstraint(tableName, constraint); err != nil {@@ -580,13 +611,14 @@ func isColumnEqual(oldColumn, newColumn plsql.IColumn_definitionContext) bool {return oldString == newString}-func buildSchemaInfo(statement string) (*schemaInfo, error) {+func buildSchemaInfo(statement string, strictMode bool) (*schemaInfo, error) {node, _, err := ParsePLSQL(statement)if err != nil {return nil, err}listener := &buildSchemaInfoListener{+ strictMode: strictMode,schemaInfo: &schemaInfo{name: "",tableMap: make(tableMap),@@ -606,6 +638,7 @@ func buildSchemaInfo(statement string) (*schemaInfo, error) {type buildSchemaInfoListener struct {*plsql.BasePlSqlParserListener+ strictMode boolschemaInfo *schemaInfoerr error}@@ -646,6 +679,7 @@ func (l *buildSchemaInfoListener) EnterCreate_index(ctx *plsql.Create_indexContereturn}+ id := getIndexID(ctx, l.strictMode)schema, index := NormalizeIndexName(ctx.Index_name())if schema != "" && l.schemaInfo.name == "" {l.schemaInfo.name = schema@@ -654,14 +688,27 @@ func (l *buildSchemaInfoListener) EnterCreate_index(ctx *plsql.Create_indexContel.err = errors.Errorf("schema name mismatch: %s != %s", schema, l.schemaInfo.name)return}- l.schemaInfo.indexMap[index] = &indexInfo{- id: len(l.schemaInfo.indexMap),+ l.schemaInfo.indexMap[id] = &indexInfo{+ pos: len(l.schemaInfo.indexMap),+ id: id,name: index,existsInNew: false,createIndex: ctx,}}+func getIndexID(ctx plsql.ICreate_indexContext, strictMode bool) string {+ if strictMode {+ _, indexName := NormalizeIndexName(ctx.Index_name())+ return indexName+ }+ return EraseString(EraseContext{+ eraseIndexName: true,+ eraseSchemaName: true,+ eraseConstraintName: true,+ }, ctx, ctx.GetParser().GetTokenStream())+}+type tableMap map[string]*tableInfotype indexMap map[string]*indexInfo@@ -679,7 +726,8 @@ type tableInfo struct {}type indexInfo struct {- id int+ pos int+ id stringname stringexistsInNew boolcreateIndex plsql.ICreate_indexContextdiff --git a/backend/plugin/parser/plsql/differ_test.go b/backend/plugin/parser/plsql/differ_test.goindex de5c0f1343..2a222ffad4 100644--- a/backend/plugin/parser/plsql/differ_test.go+++ b/backend/plugin/parser/plsql/differ_test.go@@ -19,7 +19,7 @@ type DifferTestData struct {Diff string `yaml:"diff"`}-func runDifferTest(t *testing.T, file string, record bool) {+func runDifferTest(t *testing.T, file string, record bool, strict bool) {var tests []DifferTestDatafilepath := filepath.Join("test-data", file)yamlFile, err := os.Open(filepath)@@ -34,7 +34,7 @@ func runDifferTest(t *testing.T, file string, record bool) {for i, test := range tests {diff, err := SchemaDiff(base.DiffContext{IgnoreCaseSensitive: false,- StrictMode: true,+ StrictMode: strict,}, test.OldSchema, test.NewSchema)require.NoError(t, err)if record {@@ -59,6 +59,15 @@ func TestPLSQLDiffer(t *testing.T) {"test_differ_data.yaml",}for _, file := range testFileList {- runDifferTest(t, file, false /* record */)+ runDifferTest(t, file, false /* record */, true /* strict */)+ }+}++func TestPlSQLDifferNonStrict(t *testing.T) {+ testFileList := []string{+ "test_differ_non_strict.yaml",+ }+ for _, file := range testFileList {+ runDifferTest(t, file, false /* record */, false /* strict */)}}diff --git a/backend/plugin/parser/plsql/replace.go b/backend/plugin/parser/plsql/replace.gonew file mode 100644index 0000000000..564a525bf3--- /dev/null+++ b/backend/plugin/parser/plsql/replace.go@@ -0,0 +1,67 @@+package plsql++import (+ "github.com/antlr4-go/antlr/v4"+ parser "github.com/bytebase/plsql-parser"+)++type EraseContext struct {+ eraseSchemaName bool+ eraseIndexName bool+ eraseConstraintName bool+}++func EraseString(ctx EraseContext, rule antlr.ParserRuleContext, tokens antlr.TokenStream) string {+ listener := &eraseListener{+ ctx: ctx,+ rewriter: *antlr.NewTokenStreamRewriter(tokens),+ }+ antlr.ParseTreeWalkerDefault.Walk(listener, rule)+ return listener.rewriter.GetText(antlr.DefaultProgramName, antlr.Interval{+ Start: rule.GetStart().GetTokenIndex(),+ Stop: rule.GetStop().GetTokenIndex(),+ })+}++type eraseListener struct {+ *parser.BasePlSqlParserListener++ ctx EraseContext+ rewriter antlr.TokenStreamRewriter+}++func (l *eraseListener) EnterTableview_name(ctx *parser.Tableview_nameContext) {+ if l.ctx.eraseSchemaName && ctx.Id_expression() != nil {+ l.rewriter.DeleteDefault(+ ctx.Identifier().GetStart().GetTokenIndex(),+ ctx.Id_expression().GetStart().GetTokenIndex()-1,+ )+ }+}++func (l *eraseListener) EnterSchema_name(ctx *parser.Schema_nameContext) {+ if l.ctx.eraseSchemaName {+ l.rewriter.DeleteDefault(+ ctx.Identifier().GetStart().GetTokenIndex(),+ ctx.Identifier().GetStop().GetTokenIndex(),+ )+ }+}++func (l *eraseListener) EnterCreate_index(ctx *parser.Create_indexContext) {+ if l.ctx.eraseIndexName && ctx.Index_name() != nil {+ l.rewriter.DeleteDefault(+ ctx.Index_name().GetStart().GetTokenIndex(),+ ctx.Index_name().GetStop().GetTokenIndex(),+ )+ }+}++func (l *eraseListener) EnterConstraint_name(ctx *parser.Constraint_nameContext) {+ if l.ctx.eraseConstraintName {+ l.rewriter.DeleteDefault(+ ctx.Identifier().GetStart().GetTokenIndex(),+ ctx.Identifier().GetStop().GetTokenIndex(),+ )+ }+}diff --git a/backend/plugin/parser/plsql/test-data/test_differ_non_strict.yaml b/backend/plugin/parser/plsql/test-data/test_differ_non_strict.yamlnew file mode 100644index 0000000000..d125d417bc--- /dev/null+++ b/backend/plugin/parser/plsql/test-data/test_differ_non_strict.yaml@@ -0,0 +1,29 @@+- oldSchema: |-+ CREATE TABLE "TEST"."TEST_TABLE" (+ "ID" NUMBER(10,0) NOT NULL ENABLE,+ "NAME" VARCHAR2(100 BYTE) NOT NULL ENABLE,+ "DESCRIPTION" VARCHAR2(200 BYTE),+ "CREATED" DATE DEFAULT SYSDATE NOT NULL ENABLE,+ "DELETED" DATE,+ CONSTRAINT "TEST_TABLE_UK2xxx" UNIQUE ("NAME") ENABLE,+ CONSTRAINT "TEST_TABLE_PKxxx" PRIMARY KEY ("ID") ENABLE,+ CONSTRAINT "TEST_TABLE_FKxxx" FOREIGN KEY ("ID") REFERENCES "TEST"."TEST_TABLE_C" ("ID") ENABLE+ );+ CREATE INDEX "TEST"."TEST_TABLE_ID" ON "TEST"."TEST_TABLE" ("ID", "NAME");+ CREATE INDEX "TEST"."TEST_TABLE_IDX2" ON "TEST"."TEST_TABLE" ("ID", "NAME");+ CREATE INDEX "TEST"."TEST_TABLE_B_ID" ON "TEST"."TEST_TABLE_B" ("NAME");+ newSchema: |-+ CREATE TABLE "AAAA"."TEST_TABLE" (+ "ID" NUMBER(10,0) NOT NULL ENABLE,+ "NAME" VARCHAR2(100 BYTE) NOT NULL ENABLE,+ "DESCRIPTION" VARCHAR2(200 BYTE),+ "CREATED" DATE DEFAULT SYSDATE NOT NULL ENABLE,+ "DELETED" DATE,+ CONSTRAINT "TEST_TABLE_UK2" UNIQUE ("NAME") ENABLE,+ CONSTRAINT "TEST_TABLE_PK" PRIMARY KEY ("ID") ENABLE,+ CONSTRAINT "TEST_TABLE_FK" FOREIGN KEY ("ID") REFERENCES "AAAA"."TEST_TABLE_C" ("ID") ENABLE+ );+ CREATE INDEX "AAAA"."TEST_TABLE_IDXxxx" ON "AAAA"."TEST_TABLE" ("ID", "NAME");+ CREATE INDEX "AAAA"."TEST_TABLE_IDX2xxx" ON "AAAA"."TEST_TABLE" ("ID", "NAME");+ CREATE INDEX "AAAA"."TEST_TABLE_B_IDXxxx" ON "AAAA"."TEST_TABLE_B" ("NAME");+ diff: ""