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(diff): support compare two indices (#2855)
h3n4lebc07dd370d1
diff --git a/plugin/parser/differ/mysql/differ.go b/plugin/parser/differ/mysql/differ.goindex 024f9cf94f..d5ef5dde32 100644--- a/plugin/parser/differ/mysql/differ.go+++ b/plugin/parser/differ/mysql/differ.go@@ -32,6 +32,9 @@ func init() {type SchemaDiffer struct {}+// constraintMap returns a map of constraint name to constraint.+type constraintMap map[string]*ast.Constraint+// SchemaDiff returns the schema diff.func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {oldNodes, _, err := parser.New().Parse(oldStmt, "", "")@@ -40,25 +43,30 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {}newNodes, _, err := parser.New().Parse(newStmt, "", "")if err != nil {- return "", errors.Wrapf(err, "failed to parse old statement %q", oldStmt)+ return "", errors.Wrapf(err, "failed to parse new statement %q", newStmt)}var diff []ast.Node+oldTableMap := buildTableMap(oldNodes)for _, node := range newNodes {switch newStmt := node.(type) {case *ast.CreateTableStmt:tableName := newStmt.Table.Name.O- if _, ok := oldTableMap[tableName]; !ok {+ oldStmt, ok := oldTableMap[tableName]+ if !ok {stmt := *newStmtstmt.IfNotExists = truediff = append(diff, &stmt)continue}-+ indexMap := buildIndexMap(oldStmt)var alterTableAddColumnSpecs []*ast.AlterTableSpecvar alterTableModifyColumnSpecs []*ast.AlterTableSpec+ var alterTableAddConstraintSpecs []*ast.AlterTableSpec+ var alterTableDropConstraintSpecs []*ast.AlterTableSpec+oldColumnMap := buildColumnMap(oldNodes, newStmt.Table.Name)for _, columnDef := range newStmt.Cols {newColumnName := columnDef.Name.Name.O@@ -79,7 +87,23 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {})}}-+ for _, constraint := range newStmt.Constraints {+ if constraint.Tp == ast.ConstraintIndex || constraint.Tp == ast.ConstraintKey ||+ constraint.Tp == ast.ConstraintUniq || constraint.Tp == ast.ConstraintUniqKey ||+ constraint.Tp == ast.ConstraintUniqIndex || constraint.Tp == ast.ConstraintFulltext {+ indexName := getIndexName(constraint)+ if oldConstraint, ok := indexMap[indexName]; ok {+ if isIndexEqual(constraint, oldConstraint) {+ delete(indexMap, indexName)+ continue+ }+ }+ alterTableAddConstraintSpecs = append(alterTableAddConstraintSpecs, &ast.AlterTableSpec{+ Tp: ast.AlterTableAddConstraint,+ Constraint: constraint,+ })+ }+ }if len(alterTableAddColumnSpecs) > 0 {diff = append(diff, &ast.AlterTableStmt{Table: &ast.TableName{@@ -96,6 +120,31 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {Specs: alterTableModifyColumnSpecs,})}+ // We should drop the remaining indices in the indexMap.+ for indexName := range indexMap {+ alterTableDropConstraintSpecs = append(alterTableDropConstraintSpecs, &ast.AlterTableSpec{+ Tp: ast.AlterTableDropIndex,+ Name: indexName,+ })+ }++ if len(alterTableAddConstraintSpecs) > 0 {+ diff = append(diff, &ast.AlterTableStmt{+ Table: &ast.TableName{+ Name: model.NewCIStr(tableName),+ },+ Specs: alterTableDropConstraintSpecs,+ })+ }++ if len(alterTableDropConstraintSpecs) > 0 {+ diff = append(diff, &ast.AlterTableStmt{+ Table: &ast.TableName{+ Name: model.NewCIStr(tableName),+ },+ Specs: alterTableAddConstraintSpecs,+ })+ }default:}}@@ -118,16 +167,16 @@ func (*SchemaDiffer) SchemaDiff(oldStmt, newStmt string) (string, error) {// buildTableMap returns a map of table name to create table statements.func buildTableMap(nodes []ast.StmtNode) map[string]*ast.CreateTableStmt {- oldTableMap := make(map[string]*ast.CreateTableStmt)+ tableMap := make(map[string]*ast.CreateTableStmt)for _, node := range nodes {switch stmt := node.(type) {case *ast.CreateTableStmt:tableName := stmt.Table.Name.String()- oldTableMap[tableName] = stmt+ tableMap[tableName] = stmtdefault:}}- return oldTableMap+ return tableMap}// buildColumnMap returns a map of column name to column definition on a given table.@@ -148,6 +197,20 @@ func buildColumnMap(nodes []ast.StmtNode, tableName model.CIStr) map[string]*astreturn oldColumnMap}+// buildIndexMap build a map of index name to constraint on given table name.+func buildIndexMap(stmt *ast.CreateTableStmt) constraintMap {+ indexMap := make(constraintMap)+ for _, constraint := range stmt.Constraints {+ if constraint.Tp == ast.ConstraintIndex || constraint.Tp == ast.ConstraintKey ||+ constraint.Tp == ast.ConstraintUniq || constraint.Tp == ast.ConstraintUniqKey ||+ constraint.Tp == ast.ConstraintUniqIndex || constraint.Tp == ast.ConstraintFulltext {+ indexName := getIndexName(constraint)+ indexMap[indexName] = constraint+ }+ }+ return indexMap+}+// isColumnEqual returns true if definitions of two columns with the same name are the same.func isColumnEqual(old, new *ast.ColumnDef) bool {if !isColumnTypesEqual(old, new) {@@ -205,3 +268,118 @@ func normalizeColumnOptions(options []*ast.ColumnOption) []*ast.ColumnOption {})return retOptions}++// isIndexEqual returns true if definitions of two indexes are the same.+func isIndexEqual(old, new *ast.Constraint) bool {+ // {INDEX | KEY} [index_name] [index_type] (key_part,...) [index_option] ...+ if old.Name != new.Name {+ return false+ }+ if (old.Option == nil) != (new.Option == nil) {+ return false+ }+ if old.Option != nil && new.Option != nil {+ if old.Option.Tp != new.Option.Tp {+ return false+ }+ }++ if !isKeyPartEqual(old.Keys, new.Keys) {+ return false+ }+ if !isIndexOptionEqual(old.Option, new.Option) {+ return false+ }+ return true+}++// isKeyPartEqual returns true if two key parts are the same.+func isKeyPartEqual(old, new []*ast.IndexPartSpecification) bool {+ if len(old) != len(new) {+ return false+ }+ // key_part: {col_name [(length)] | (expr)} [ASC | DESC]+ for idx, oldKeyPart := range old {+ newKeyPart := new[idx]+ if (oldKeyPart.Column == nil) != (newKeyPart.Column == nil) {+ return false+ }+ if oldKeyPart.Column != nil && newKeyPart.Column != nil {+ if oldKeyPart.Column.Name.String() != newKeyPart.Column.Name.String() {+ return false+ }+ if oldKeyPart.Length != newKeyPart.Length {+ return false+ }+ }+ if (oldKeyPart.Expr == nil) != (newKeyPart.Expr == nil) {+ // if the key part uses expression instead of column name, the expression node is nil.+ return false+ }+ if oldKeyPart.Expr != nil && newKeyPart.Expr != nil {+ var oldExpr bytes.Buffer+ var newExpr bytes.Buffer+ if err := oldKeyPart.Expr.Restore(format.NewRestoreCtx(format.DefaultRestoreFlags, &oldExpr)); err != nil {+ // Return error will cause the logic to be more complicated, so we just return false here.+ return false+ }+ if err := newKeyPart.Expr.Restore(format.NewRestoreCtx(format.DefaultRestoreFlags, &newExpr)); err != nil {+ return false+ }+ if oldExpr.String() != newExpr.String() {+ return false+ }+ }+ // TODO(zp): TiDB MySQL parser doesn't record the index order field in go struct, but it can parse correctly.+ // https://sourcegraph.com/github.com/pingcap/tidb/-/blob/parser/parser.y?L3688+ // We can support the index order until we implement the parser by ourself or https://github.com/pingcap/tidb/pull/38137 is merged.+ }+ return true+}++// isIndexOptionEqual returns true if two index options are the same.+func isIndexOptionEqual(old, new *ast.IndexOption) bool {+ // index_option: {+ // KEY_BLOCK_SIZE [=] value+ // | index_type+ // | WITH PARSER parser_name+ // | COMMENT 'string'+ // | {VISIBLE | INVISIBLE}+ // |ENGINE_ATTRIBUTE [=] 'string'+ // |SECONDARY_ENGINE_ATTRIBUTE [=] 'string'+ // }+ if (old == nil) != (new == nil) {+ return false+ }+ if old == nil && new == nil {+ return true+ }+ if old.KeyBlockSize != new.KeyBlockSize {+ return false+ }+ if old.Tp != new.Tp {+ return false+ }+ if old.ParserName.O != new.ParserName.O {+ return false+ }+ if old.Comment != new.Comment {+ return false+ }+ if old.Visibility != new.Visibility {+ return false+ }+ // TODO(zp): support ENGINE_ATTRIBUTE and SECONDARY_ENGINE_ATTRIBUTE.+ return true+}++// getIndexName returns the name of the index.+func getIndexName(index *ast.Constraint) string {+ if index.Name != "" {+ return index.Name+ }+ // If the index name is empty, it will be generated by MySQL.+ // https://dba.stackexchange.com/questions/160708/is-naming-an-index-required+ // TODO(zp): handle the duplicated index name.+ return index.Keys[0].Column.Name.O+}diff --git a/plugin/parser/differ/mysql/index_test.go b/plugin/parser/differ/mysql/index_test.gonew file mode 100644index 0000000000..30d18d82dd--- /dev/null+++ b/plugin/parser/differ/mysql/index_test.go@@ -0,0 +1,409 @@+package mysql++import (+ "testing"++ "github.com/pingcap/tidb/parser/ast"+ "github.com/pingcap/tidb/parser/model"+ "github.com/pingcap/tidb/parser/opcode"+ "github.com/pingcap/tidb/types"+ driver "github.com/pingcap/tidb/types/parser_driver"+ "github.com/stretchr/testify/require"+)++func TestIsKeyPartEqual(t *testing.T) {+ tests := []struct {+ old []*ast.IndexPartSpecification+ new []*ast.IndexPartSpecification+ eq bool+ }{+ {+ old: []*ast.IndexPartSpecification{+ // `id` + 1+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Plus,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(1),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ },+ new: []*ast.IndexPartSpecification{+ // `id` * 2+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Mul,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(2),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ },+ eq: false,+ },+ {+ old: []*ast.IndexPartSpecification{+ // `id` + 1+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Plus,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(1),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ },+ new: []*ast.IndexPartSpecification{+ // `id` + 1+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Plus,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(1),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ // `id` * 2+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Mul,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(2),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ },+ eq: false,+ },+ {+ old: []*ast.IndexPartSpecification{+ // `id` + 1+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Plus,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(1),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ },+ new: []*ast.IndexPartSpecification{+ // `id` + 1+ {+ Expr: &ast.BinaryOperationExpr{+ Op: opcode.Plus,+ L: &ast.ColumnNameExpr{+ Name: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ R: &driver.ValueExpr{+ Datum: types.NewDatum(1),+ },+ },+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ },+ eq: true,+ },+ }+ a := require.New(t)+ for _, test := range tests {+ got := isKeyPartEqual(test.old, test.new)+ a.Equalf(test.eq, got, "old: %v, new: %v", test.old, test.new)+ }+}+func TestIsIndexOptionEqual(t *testing.T) {+ tests := []struct {+ old *ast.IndexOption+ new *ast.IndexOption+ eq bool+ }{+ {+ old: nil,+ new: nil,+ eq: true,+ },+ {+ old: &ast.IndexOption{+ KeyBlockSize: 1024,+ },+ new: nil,+ eq: false,+ },+ {+ old: &ast.IndexOption{+ KeyBlockSize: 1024,+ },+ new: nil,+ eq: false,+ },+ {+ old: &ast.IndexOption{+ KeyBlockSize: 1024,+ Tp: model.IndexTypeBtree,+ ParserName: model.NewCIStr("parser"),+ Comment: "comment",+ Visibility: ast.IndexVisibilityVisible,+ },+ new: &ast.IndexOption{+ KeyBlockSize: 1024,+ Tp: model.IndexTypeHash,+ ParserName: model.NewCIStr("parser"),+ Comment: "commen_idx",+ Visibility: ast.IndexVisibilityInvisible,+ },+ eq: false,+ },+ {+ old: &ast.IndexOption{+ KeyBlockSize: 1024,+ Tp: model.IndexTypeBtree,+ ParserName: model.NewCIStr("parser"),+ Comment: "comment",+ Visibility: ast.IndexVisibilityVisible,+ },+ new: &ast.IndexOption{+ KeyBlockSize: 1024,+ Tp: model.IndexTypeBtree,+ ParserName: model.NewCIStr("parser"),+ Comment: "comment",+ Visibility: ast.IndexVisibilityVisible,+ },+ eq: true,+ },+ }++ a := require.New(t)+ for _, test := range tests {+ got := isIndexOptionEqual(test.old, test.new)+ a.Equalf(test.eq, got, "old: %v, new: %v", test.old, test.new)+ }+}++func TestGetIndexName(t *testing.T) {+ tests := []struct {+ constraint *ast.Constraint+ want string+ }{+ {+ constraint: &ast.Constraint{+ Name: "id_idx",+ Keys: []*ast.IndexPartSpecification{+ {+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ {+ Column: &ast.ColumnName{+ Name: model.NewCIStr("name"),+ },+ },+ },+ },+ want: "id_idx",+ },+ {+ constraint: &ast.Constraint{+ Keys: []*ast.IndexPartSpecification{+ {+ Column: &ast.ColumnName{+ Name: model.NewCIStr("id"),+ },+ },+ {+ Column: &ast.ColumnName{+ Name: model.NewCIStr("name"),+ },+ },+ },+ },+ want: "id",+ },+ }+ a := require.New(t)+ for _, test := range tests {+ got := getIndexName(test.constraint)+ a.Equalf(test.want, got, "constraint: %v", test.constraint)+ }+}++func TestIndexType(t *testing.T) {+ tests := []struct {+ old string+ new string+ want string+ }{+ {+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE(name));`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING HASH(name));`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`(`name`) USING HASH;\n",+ },+ {+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE(name));`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE(name));`,+ want: "",+ },+ {+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name));`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name));`,+ want: "",+ },+ }++ a := require.New(t)+ mysqlDiffer := &SchemaDiffer{}+ for _, test := range tests {+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)+ a.NoError(err)+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)+ }+}++func TestIndexOption(t *testing.T) {+ tests := []struct {+ old string+ new string+ want string+ }{+ {+ // KEY_BLOCK_SIZE not match.+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) KEY_BLOCK_SIZE=30);`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) KEY_BLOCK_SIZE=50);`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`(`name`) KEY_BLOCK_SIZE=50;\n",+ },+ {+ // WITH PARSER not match.+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) WITH PARSER parser_a);`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) WITH PARSER parser_b);`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD FULLTEXT `book_idx`(`name`) WITH PARSER `parser_b`;\n",+ },+ {+ // COMMENT not match.+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) COMMENT 'comment_a');`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) COMMENT 'comment_b');`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`(`name`) COMMENT 'comment_b';\n",+ },+ {+ // VISIBILITY not match.+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) VISIBLE);`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, INDEX book_idx(name) INVISIBLE);`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`(`name`) INVISIBLE;\n",+ },+ {+ old: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) KEY_BLOCK_SIZE=30 WITH PARSER parser_a COMMENT 'no difference!');`,+ new: `CREATE TABLE book(name VARCHAR(50) NOT NULL, FULLTEXT INDEX book_idx(name) KEY_BLOCK_SIZE=30 WITH PARSER parser_a COMMENT 'no difference!');`,+ want: "",+ },+ }++ a := require.New(t)+ mysqlDiffer := &SchemaDiffer{}+ for _, test := range tests {+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)+ a.NoError(err)+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)+ }+}++func TestKeyPart(t *testing.T) {+ tests := []struct {+ old string+ new string+ want string+ }{+ {+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id, name) COMMENT 'comment_a');`,+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id) COMMENT 'comment_a');`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`(`id`) USING BTREE COMMENT 'comment_a';\n",+ },+ {+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id, name) COMMENT 'comment_a');`,+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 1)) COMMENT 'comment_a');`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`((`id`+1)) USING BTREE COMMENT 'comment_a';\n",+ },+ {+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 1)) COMMENT 'comment_a');`,+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 2)) COMMENT 'comment_a');`,+ want: "ALTER TABLE `book` DROP INDEX `book_idx`;\n" ++ "ALTER TABLE `book` ADD INDEX `book_idx`((`id`+2)) USING BTREE COMMENT 'comment_a';\n",+ },+ {+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id, name) COMMENT 'comment_a');`,+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE (id, name) COMMENT 'comment_a');`,+ want: "",+ },+ {+ old: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 1)) COMMENT 'comment_a');`,+ new: `CREATE TABLE book(id INT, name VARCHAR(50) NOT NULL, INDEX book_idx USING BTREE ((id + 1)) COMMENT 'comment_a');`,+ want: "",+ },+ }++ a := require.New(t)+ mysqlDiffer := &SchemaDiffer{}+ for _, test := range tests {+ out, err := mysqlDiffer.SchemaDiff(test.old, test.new)+ a.NoError(err)+ a.Equalf(test.want, out, "old: %s\nnew: %s\n", test.old, test.new)+ }+}