Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix: mysql schema model bugs (#16758)
rebelice5b126868db98
diff --git a/backend/plugin/schema/mysql/generate_migration.go b/backend/plugin/schema/mysql/generate_migration.goindex 8927cae53e..ae993e327b 100644--- a/backend/plugin/schema/mysql/generate_migration.go+++ b/backend/plugin/schema/mysql/generate_migration.go@@ -12,7 +12,7 @@ import (// tableDrop holds drop operations for deduplicationtype tableDrop struct {checkConstraints map[string]string- indexes map[string]string+ indexes map[string]*storepb.IndexMetadatacolumns map[string]string}@@ -143,7 +143,7 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {if _, exists := dropsPerTable[tableName]; !exists {dropsPerTable[tableName] = &tableDrop{checkConstraints: make(map[string]string),- indexes: make(map[string]string),+ indexes: make(map[string]*storepb.IndexMetadata),columns: make(map[string]string),}}@@ -158,7 +158,7 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {// Collect indexes to dropfor _, indexDiff := range tableDiff.IndexChanges {if indexDiff.Action == schema.MetadataDiffActionDrop {- dropsPerTable[tableName].indexes[indexDiff.OldIndex.Name] = indexDiff.OldIndex.Name+ dropsPerTable[tableName].indexes[indexDiff.OldIndex.Name] = indexDiff.OldIndex}}@@ -180,10 +180,16 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {}}- // Drop indexes- for indexName := range drops.indexes {- if err := writeDropIndex(buf, tableName, indexName); err != nil {- return err+ // Drop indexes (handle primary key specially)+ for _, index := range drops.indexes {+ if index.Primary {+ if err := writeDropPrimaryKey(buf, tableName); err != nil {+ return err+ }+ } else {+ if err := writeDropIndex(buf, tableName, index.Name); err != nil {+ return err+ }}}@@ -478,7 +484,7 @@ func writeDropTable(buf *strings.Builder, table string) error {func writeDropCheckConstraint(buf *strings.Builder, table, constraint string) error {_, _ = buf.WriteString("ALTER TABLE `")_, _ = buf.WriteString(table)- _, _ = buf.WriteString("` DROP CHECK `")+ _, _ = buf.WriteString("` DROP CONSTRAINT `")_, _ = buf.WriteString(constraint)_, _ = buf.WriteString("`;\n\n")return nil@@ -493,6 +499,13 @@ func writeDropIndex(buf *strings.Builder, table, index string) error {return nil}+func writeDropPrimaryKey(buf *strings.Builder, table string) error {+ _, _ = buf.WriteString("ALTER TABLE `")+ _, _ = buf.WriteString(table)+ _, _ = buf.WriteString("` DROP PRIMARY KEY;\n\n")+ return nil+}+func writeDropColumn(buf *strings.Builder, table, column string) error {_, _ = buf.WriteString("ALTER TABLE `")_, _ = buf.WriteString(table)@@ -872,9 +885,10 @@ func writeAddCheckConstraint(buf *strings.Builder, table string, check *storepb._, _ = buf.WriteString(table)_, _ = buf.WriteString("` ADD CONSTRAINT `")_, _ = buf.WriteString(check.Name)- _, _ = buf.WriteString("` CHECK (")+ _, _ = buf.WriteString("` CHECK ")+ // The expression already includes parentheses from the parser_, _ = buf.WriteString(check.Expression)- _, _ = buf.WriteString(");\n")+ _, _ = buf.WriteString(";\n")return nil}diff --git a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.goindex d1d2e7c599..e6de0cbf2b 100644--- a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go@@ -1581,6 +1581,57 @@ DROP FUNCTION GetAverageStat;`,description: "Reverse: Drop events and advanced features",},+ {+ name: "no_diff_identical_schemas",+ initialSchema: `+-- Test that identical schemas don't generate unnecessary migrations+-- This tests the fixes for primary key, index type, check constraints, and DEFAULT NULL++CREATE TABLE test_table (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) DEFAULT NULL,+ email VARCHAR(100),+ status VARCHAR(20) DEFAULT 'active',+ age INT DEFAULT NULL,+ score DECIMAL(5,2),+ PRIMARY KEY (id),+ INDEX idx_name (name),+ INDEX idx_status_hash (status) USING HASH,+ UNIQUE KEY uk_email (email),+ CONSTRAINT chk_age CHECK (age >= 18),+ CONSTRAINT chk_status CHECK (status IN ('active', 'inactive', 'pending'))+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;++-- Table with various column types and defaults+CREATE TABLE t (+ id INT NOT NULL AUTO_INCREMENT,+ name CHAR(255) DEFAULT NULL,+ PRIMARY KEY (id)+) ENGINE=InnoDB;++CREATE TABLE t1 (+ id INT NOT NULL,+ a INT NOT NULL,+ b INT DEFAULT NULL,+ c INT,+ PRIMARY KEY (id),+ INDEX b (b) USING HASH+) ENGINE=InnoDB;++-- Table with check constraint that has spaces+CREATE TABLE some_table (+ id INT PRIMARY KEY,+ a INT NOT NULL,+ CONSTRAINT some_table_chk_1 CHECK (a IN (1, 2, 3))+) ENGINE=InnoDB;+ `,+ migrationDDL: `+-- No changes - schemas should be identical+-- This simulates running the exact same CREATE statements again+-- The test verifies that no migration DDL is generated+ `,+ description: "Verify no migration generated for identical schemas (tests primary key, index, check constraints, DEFAULT NULL fixes)",+ },}for _, tc := range testCases {@@ -1654,6 +1705,15 @@ DROP FUNCTION GetAverageStat;t.Logf("Rollback DDL:\n%s", rollbackDDL)+ // Special handling for the no-diff test case+ if tc.name == "no_diff_identical_schemas" {+ // For identical schemas, we expect no migration DDL to be generated+ if strings.TrimSpace(rollbackDDL) != "" {+ t.Errorf("Expected no migration DDL for identical schemas, but got:\n%s", rollbackDDL)+ }+ return+ }+// Step 4: Run rollback DDL and get schema result Cif err := executeStatements(db, rollbackDDL); err != nil {t.Fatalf("Failed to execute rollback DDL: %v", err)diff --git a/backend/plugin/schema/mysql/get_database_metadata.go b/backend/plugin/schema/mysql/get_database_metadata.goindex 827ff6a6fa..e5552e026e 100644--- a/backend/plugin/schema/mysql/get_database_metadata.go+++ b/backend/plugin/schema/mysql/get_database_metadata.go@@ -370,7 +370,7 @@ func (*metadataExtractor) extractFieldAttributes(ctx mysql.IFieldDefinitionConte}} else if attr.ExprWithParentheses() != nil {// Expression - wrap in parentheses like sync logic does for DEFAULT_GENERATED- column.Default = fmt.Sprintf("(%s)", attr.ExprWithParentheses().GetText())+ column.Default = fmt.Sprintf("(%s)", attr.GetParser().GetTokenStream().GetTextFromRuleContext(attr.ExprWithParentheses()))} else {// Check for special keywords like CURRENT_TIMESTAMP// Parse the entire attribute text to find DEFAULT keyword and what follows@@ -499,7 +499,7 @@ func (*metadataExtractor) extractPrimaryKey(ctx mysql.ITableConstraintDefContextindex := &storepb.IndexMetadata{Name: "PRIMARY",- Type: "PRIMARY",+ Type: "BTREE",Expressions: keyColumns,Primary: true,Unique: true,@@ -595,7 +595,7 @@ func (*metadataExtractor) extractForeignKey(ctx mysql.ITableConstraintDefContext}// extractIndex extracts regular index-func (*metadataExtractor) extractIndex(ctx mysql.ITableConstraintDefContext, table *storepb.TableMetadata) {+func (e *metadataExtractor) extractIndex(ctx mysql.ITableConstraintDefContext, table *storepb.TableMetadata) {if ctx.KeyList() == nil {return}@@ -622,7 +622,7 @@ func (*metadataExtractor) extractIndex(ctx mysql.ITableConstraintDefContext, tab}if len(expressions) > 0 {- indexType := "BTREE"+ indexType := e.getIndexType(ctx)index := &storepb.IndexMetadata{Name: indexName,@@ -680,8 +680,8 @@ func (*metadataExtractor) extractCheckConstraint(ctx mysql.ICheckConstraintContereturn}- // Extract expression- expression := ctx.ExprWithParentheses().GetText()+ // Extract expression with proper spacing+ expression := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx.ExprWithParentheses())// If no constraint name provided, generate one like MySQL doesif constraintName == "" {@@ -1053,6 +1053,19 @@ func (e *metadataExtractor) EnterCreateIndex(ctx *mysql.CreateIndexContext) {}}+// getIndexType extracts the index type from the table constraint definition+func (*metadataExtractor) getIndexType(_ mysql.ITableConstraintDefContext) string {+ // Default to BTREE if no type specified+ indexType := "BTREE"++ // Try to extract index type from various possible locations in the parse tree+ // This depends on the specific MySQL parser implementation+ // For now, we'll return the default BTREE+ // TODO: Implement proper index type extraction when parser methods are available++ return indexType+}+// normalizeDefaultValue normalizes default values to match MySQL's internal representationfunc normalizeDefaultValue(defaultValue string) string {if defaultValue == "" {