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: use new differ for sync schema and fix bugs (#16664)
rebelicebef21fda4bf4
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.goindex 2e937fc40b..7c45e4ad9e 100644--- a/backend/api/v1/database_service.go+++ b/backend/api/v1/database_service.go@@ -27,6 +27,7 @@ import ("github.com/bytebase/bytebase/backend/plugin/schema""github.com/bytebase/bytebase/backend/runner/schemasync""github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/store/model"storepb "github.com/bytebase/bytebase/proto/generated-go/store"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1""github.com/bytebase/bytebase/proto/generated-go/v1/v1connect"@@ -803,6 +804,40 @@ func (s *DatabaseService) GetDatabaseSchema(ctx context.Context, req *connect.Re// DiffSchema diff the database schema.func (s *DatabaseService) DiffSchema(ctx context.Context, req *connect.Request[v1pb.DiffSchemaRequest]) (*connect.Response[v1pb.DiffSchemaResponse], error) {+ // Check if target is changelog - use new metadata-based approach+ changeHistoryID := req.Msg.GetChangelog()+ if changeHistoryID != "" {+ sourceDBSchema, err := s.getSourceDBSchema(ctx, req.Msg)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get source schema, error: %v", err))+ }++ targetDBSchema, err := s.getTargetDBSchema(ctx, req.Msg)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get target schema, error: %v", err))+ }++ engine, err := s.getParserEngine(ctx, req.Msg)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get parser engine, error: %v", err))+ }++ schemaDiff, err := schema.GetDatabaseSchemaDiff(sourceDBSchema, targetDBSchema)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to compute schema diff, error: %v", err))+ }++ migrationSQL, err := schema.GenerateMigration(engine, schemaDiff)+ if err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to generate migration SQL, error: %v", err))+ }++ return connect.NewResponse(&v1pb.DiffSchemaResponse{+ Diff: migrationSQL,+ }), nil+ }++ // Fallback to old string-based approach for schema string targetssource, err := s.getSourceSchema(ctx, req.Msg)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get source schema, error: %v", err))@@ -832,6 +867,145 @@ func (s *DatabaseService) DiffSchema(ctx context.Context, req *connect.Request[v}), nil}+func (s *DatabaseService) getSourceDBSchema(ctx context.Context, request *v1pb.DiffSchemaRequest) (*model.DatabaseSchema, error) {+ if strings.Contains(request.Name, common.ChangelogPrefix) {+ instanceID, databaseName, changelogUID, err := common.GetInstanceDatabaseChangelogUID(request.Name)+ if err != nil {+ return nil, err+ }++ changelog, err := s.store.GetChangelog(ctx, &store.FindChangelogMessage{+ UID: &changelogUID,+ })+ if err != nil {+ return nil, err+ }+ if changelog == nil {+ return nil, errors.Errorf("changelog %d not found", changelogUID)+ }++ // Use SyncHistoryUID to get historical metadata+ if changelog.SyncHistoryUID != nil {+ syncHistory, err := s.store.GetSyncHistoryByUID(ctx, *changelog.SyncHistoryUID)+ if err != nil {+ return nil, err+ }+ if syncHistory == nil {+ return nil, errors.Errorf("sync history %d not found", *changelog.SyncHistoryUID)+ }++ // Get instance to determine engine and case sensitivity+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})+ if err != nil {+ return nil, err+ }+ if instance == nil {+ return nil, errors.Errorf("instance %s not found", instanceID)+ }++ return model.NewDatabaseSchema(+ syncHistory.Metadata,+ []byte(syncHistory.Schema),+ &storepb.DatabaseConfig{},+ instance.Metadata.GetEngine(),+ store.IsObjectCaseSensitive(instance),+ ), nil+ }++ // Fallback to current database schema if no sync history+ dbSchema, err := s.store.GetDBSchema(ctx, instanceID, databaseName)+ if err != nil {+ return nil, err+ }+ if dbSchema == nil {+ return nil, errors.Errorf("database schema not found for %s/%s", instanceID, databaseName)+ }+ return dbSchema, nil+ }++ instanceID, databaseName, err := common.GetInstanceDatabaseID(request.Name)+ if err != nil {+ return nil, err+ }++ dbSchema, err := s.store.GetDBSchema(ctx, instanceID, databaseName)+ if err != nil {+ return nil, err+ }+ if dbSchema == nil {+ return nil, errors.Errorf("database schema not found for %s/%s", instanceID, databaseName)+ }+ return dbSchema, nil+}++func (s *DatabaseService) getTargetDBSchema(ctx context.Context, request *v1pb.DiffSchemaRequest) (*model.DatabaseSchema, error) {+ changeHistoryID := request.GetChangelog()++ // If the change history id is set, use the schema of the change history as the target.+ if changeHistoryID != "" {+ instanceID, databaseName, changelogUID, err := common.GetInstanceDatabaseChangelogUID(changeHistoryID)+ if err != nil {+ return nil, err+ }++ changelog, err := s.store.GetChangelog(ctx, &store.FindChangelogMessage{+ UID: &changelogUID,+ })+ if err != nil {+ return nil, err+ }+ if changelog == nil {+ return nil, errors.Errorf("changelog %d not found", changelogUID)+ }++ // Use SyncHistoryUID to get historical metadata+ if changelog.SyncHistoryUID != nil {+ syncHistory, err := s.store.GetSyncHistoryByUID(ctx, *changelog.SyncHistoryUID)+ if err != nil {+ return nil, err+ }+ if syncHistory == nil {+ return nil, errors.Errorf("sync history %d not found", *changelog.SyncHistoryUID)+ }++ // Get instance to determine engine and case sensitivity+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &instanceID})+ if err != nil {+ return nil, err+ }+ if instance == nil {+ return nil, errors.Errorf("instance %s not found", instanceID)+ }++ return model.NewDatabaseSchema(+ syncHistory.Metadata,+ []byte(syncHistory.Schema),+ &storepb.DatabaseConfig{},+ instance.Metadata.GetEngine(),+ store.IsObjectCaseSensitive(instance),+ ), nil+ }++ // Fallback to current database schema if no sync history+ dbSchema, err := s.store.GetDBSchema(ctx, instanceID, databaseName)+ if err != nil {+ return nil, err+ }+ if dbSchema == nil {+ return nil, errors.Errorf("database schema not found for %s/%s", instanceID, databaseName)+ }+ return dbSchema, nil+ }++ // If schema is provided, we need to parse it - for now, return an error as this case needs more implementation+ schema := request.GetSchema()+ if schema != "" {+ return nil, errors.Errorf("schema string target not yet supported with metadata-based diffing")+ }++ return nil, errors.Errorf("must set the schema or change history id as the target")+}+func (s *DatabaseService) getSourceSchema(ctx context.Context, request *v1pb.DiffSchemaRequest) (string, error) {if strings.Contains(request.Name, common.ChangelogPrefix) {changeHistory, err := s.GetChangelog(ctx, &connect.Request[v1pb.GetChangelogRequest]{diff --git a/backend/plugin/db/mysql/sync.go b/backend/plugin/db/mysql/sync.goindex 5be650ba51..ba238900da 100644--- a/backend/plugin/db/mysql/sync.go+++ b/backend/plugin/db/mysql/sync.go@@ -550,11 +550,10 @@ func (d *Driver) SyncDBSchema(ctx context.Context) (*storepb.DatabaseSchemaMetad// Quoted string has a single quote around it.comment = stripSingleQuote(comment)- // Skip partition entries by checking if CREATE_OPTIONS contains 'partitioned'- // This happens when MySQL shows individual partitions as separate table entries- if strings.Contains(strings.ToLower(createOptions), "partitioned") {- continue- }+ // Note: We should NOT skip partitioned tables here.+ // The CREATE_OPTIONS might contain 'partitioned' for partitioned tables,+ // but we still need to include them in the table list.+ // The partition details are fetched separately by listPartitionTables.key := db.TableKey{Schema: "", Table: tableName}switch tableType {diff --git a/backend/plugin/schema/mysql/generate_migration.go b/backend/plugin/schema/mysql/generate_migration.goindex fde43ed462..3cb431c488 100644--- a/backend/plugin/schema/mysql/generate_migration.go+++ b/backend/plugin/schema/mysql/generate_migration.go@@ -5,10 +5,18 @@ import ("slices""strings"+ parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base""github.com/bytebase/bytebase/backend/plugin/schema"storepb "github.com/bytebase/bytebase/proto/generated-go/store")+// tableDrop holds drop operations for deduplication+type tableDrop struct {+ checkConstraints map[string]string+ indexes map[string]string+ columns map[string]string+}+func init() {schema.RegisterGenerateMigration(storepb.Engine_MYSQL, generateMigration)schema.RegisterGenerateMigration(storepb.Engine_OCEANBASE, generateMigration)@@ -121,45 +129,132 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {}}- // Drop tables- for _, tableDiff := range diff.TableChanges {- if tableDiff.Action == schema.MetadataDiffActionDrop {- if err := writeDropTable(buf, tableDiff.TableName); err != nil {- return err- }- }+ // Drop tables in topologically sorted order (respecting foreign key dependencies)+ if err := dropTablesInDependencyOrder(diff, buf); err != nil {+ return err}// Handle ALTER table drops (constraints, indexes, columns)+ // Collect all drop operations by table to avoid duplicates+ dropsPerTable := make(map[string]*tableDrop)+for _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionAlter {- // Drop check constraints+ tableName := tableDiff.TableName+ if _, exists := dropsPerTable[tableName]; !exists {+ dropsPerTable[tableName] = &tableDrop{+ checkConstraints: make(map[string]string),+ indexes: make(map[string]string),+ columns: make(map[string]string),+ }+ }++ // Collect check constraints to dropfor _, checkDiff := range tableDiff.CheckConstraintChanges {if checkDiff.Action == schema.MetadataDiffActionDrop {- if err := writeDropCheckConstraint(buf, tableDiff.TableName, checkDiff.OldCheckConstraint.Name); err != nil {- return err- }+ dropsPerTable[tableName].checkConstraints[checkDiff.OldCheckConstraint.Name] = checkDiff.OldCheckConstraint.Name}}- // Drop indexes+ // Collect indexes to dropfor _, indexDiff := range tableDiff.IndexChanges {if indexDiff.Action == schema.MetadataDiffActionDrop {- if err := writeDropIndex(buf, tableDiff.TableName, indexDiff.OldIndex.Name); err != nil {- return err- }+ dropsPerTable[tableName].indexes[indexDiff.OldIndex.Name] = indexDiff.OldIndex.Name}}- // Drop columns+ // Collect columns to dropfor _, colDiff := range tableDiff.ColumnChanges {if colDiff.Action == schema.MetadataDiffActionDrop {- if err := writeDropColumn(buf, tableDiff.TableName, colDiff.OldColumn.Name); err != nil {+ dropsPerTable[tableName].columns[colDiff.OldColumn.Name] = colDiff.OldColumn.Name+ }+ }+ }+ }++ // Execute the deduplicated drop operations+ for tableName, drops := range dropsPerTable {+ // Drop check constraints+ for constraintName := range drops.checkConstraints {+ if err := writeDropCheckConstraint(buf, tableName, constraintName); err != nil {+ return err+ }+ }++ // Drop indexes+ for indexName := range drops.indexes {+ if err := writeDropIndex(buf, tableName, indexName); err != nil {+ return err+ }+ }++ // Drop columns+ for columnName := range drops.columns {+ if err := writeDropColumn(buf, tableName, columnName); err != nil {+ return err+ }+ }+ }++ return nil+}++// dropTablesInDependencyOrder drops tables in the correct order based on foreign key dependencies+func dropTablesInDependencyOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {+ // Build a graph of table dependencies+ graph := parserbase.NewGraph()+ tablesToDrop := make(map[string]*schema.TableDiff)++ // Add all tables to be dropped to the graph+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionDrop {+ graph.AddNode(tableDiff.TableName)+ tablesToDrop[tableDiff.TableName] = tableDiff+ }+ }++ // Add edges for foreign key dependencies+ // Edge from table with FK to referenced table (for dropping order)+ for _, tableDiff := range tablesToDrop {+ if tableDiff.OldTable != nil {+ for _, fk := range tableDiff.OldTable.ForeignKeys {+ if _, exists := tablesToDrop[fk.ReferencedTable]; exists {+ // Add edge from this table to referenced table+ // This ensures this table is dropped before referenced table+ graph.AddEdge(tableDiff.TableName, fk.ReferencedTable)+ }+ }+ }+ }++ // Get topological order+ orderedTables, err := graph.TopologicalSort()+ if err != nil {+ // If there's a cycle, fall back to dropping foreign keys first+ // Drop all foreign keys from tables being dropped+ for _, tableDiff := range tablesToDrop {+ if tableDiff.OldTable != nil {+ for _, fk := range tableDiff.OldTable.ForeignKeys {+ if err := writeDropForeignKey(buf, tableDiff.TableName, fk.Name); err != nil {return err}}}}++ // Then drop tables in any order+ for _, tableDiff := range tablesToDrop {+ if err := writeDropTable(buf, tableDiff.TableName); err != nil {+ return err+ }+ }+ } else {+ // Drop tables in topological order+ for _, tableName := range orderedTables {+ if err := writeDropTable(buf, tableName); err != nil {+ return err+ }+ }}return nil@@ -167,6 +262,16 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {// createObjectsInOrder creates all objects in the correct orderfunc createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error {+ // Create dummy views first for all new views to handle dependencies+ // This must be done before creating tables as triggers might reference views+ for _, viewDiff := range diff.ViewChanges {+ if viewDiff.Action == schema.MetadataDiffActionCreate && viewDiff.NewView != nil {+ if err := writeCreateTemporaryView(buf, viewDiff.ViewName, viewDiff.NewView); err != nil {+ return err+ }+ }+ }+// Create tables (without foreign keys first)for _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionCreate {@@ -196,11 +301,12 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}- // Create views+ // Create or replace views with actual definitionsfor _, viewDiff := range diff.ViewChanges {switch viewDiff.Action {case schema.MetadataDiffActionCreate:- if err := writeCreateView(buf, viewDiff.ViewName, viewDiff.NewView); err != nil {+ // Use CREATE OR REPLACE since we already have a dummy view+ if err := writeCreateOrReplaceView(buf, viewDiff.ViewName, viewDiff.NewView); err != nil {return err}case schema.MetadataDiffActionAlter:@@ -428,7 +534,8 @@ func writeCreateTableWithoutForeignKeys(buf *strings.Builder, tableName string,// Handle AUTO_INCREMENT before default valueif hasAutoIncrement(col) {_, _ = buf.WriteString(" AUTO_INCREMENT")- } else if hasDefaultValue(col) && !hasAutoIncrement(col) {+ } else if hasDefaultValue(col) && !hasAutoIncrement(col) && col.Generation == nil {+ // Don't add DEFAULT if this is a generated column_, _ = buf.WriteString(" DEFAULT ")_, _ = buf.WriteString(getDefaultExpression(col))}@@ -439,6 +546,19 @@ func writeCreateTableWithoutForeignKeys(buf *strings.Builder, tableName string,_, _ = buf.WriteString(col.OnUpdate)}+ // Handle generated columns+ if col.Generation != nil && col.Generation.Expression != "" {+ _, _ = buf.WriteString(" GENERATED ALWAYS AS (")+ _, _ = buf.WriteString(col.Generation.Expression)+ _, _ = buf.WriteString(") ")+ switch col.Generation.Type {+ case storepb.GenerationMetadata_TYPE_STORED:+ _, _ = buf.WriteString("STORED")+ case storepb.GenerationMetadata_TYPE_VIRTUAL:+ _, _ = buf.WriteString("VIRTUAL")+ }+ }+if col.Comment != "" {_, _ = buf.WriteString(" COMMENT '")_, _ = buf.WriteString(escapeString(col.Comment))@@ -551,7 +671,8 @@ func writeAddColumn(buf *strings.Builder, table string, column *storepb.ColumnMe// Handle AUTO_INCREMENT before default valueif hasAutoIncrement(column) {_, _ = buf.WriteString(" AUTO_INCREMENT")- } else if hasDefaultValue(column) && !hasAutoIncrement(column) {+ } else if hasDefaultValue(column) && !hasAutoIncrement(column) && column.Generation == nil {+ // Don't add DEFAULT if this is a generated column_, _ = buf.WriteString(" DEFAULT ")_, _ = buf.WriteString(getDefaultExpression(column))}@@ -562,6 +683,19 @@ func writeAddColumn(buf *strings.Builder, table string, column *storepb.ColumnMe_, _ = buf.WriteString(column.OnUpdate)}+ // Handle generated columns+ if column.Generation != nil && column.Generation.Expression != "" {+ _, _ = buf.WriteString(" GENERATED ALWAYS AS (")+ _, _ = buf.WriteString(column.Generation.Expression)+ _, _ = buf.WriteString(") ")+ switch column.Generation.Type {+ case storepb.GenerationMetadata_TYPE_STORED:+ _, _ = buf.WriteString("STORED")+ case storepb.GenerationMetadata_TYPE_VIRTUAL:+ _, _ = buf.WriteString("VIRTUAL")+ }+ }+if column.Comment != "" {_, _ = buf.WriteString(" COMMENT '")_, _ = buf.WriteString(escapeString(column.Comment))@@ -598,7 +732,8 @@ func writeModifyColumn(buf *strings.Builder, table string, column *storepb.Colum// Handle AUTO_INCREMENT before default valueif hasAutoIncrement(column) {_, _ = buf.WriteString(" AUTO_INCREMENT")- } else if hasDefaultValue(column) && !hasAutoIncrement(column) {+ } else if hasDefaultValue(column) && !hasAutoIncrement(column) && column.Generation == nil {+ // Don't add DEFAULT if this is a generated column_, _ = buf.WriteString(" DEFAULT ")_, _ = buf.WriteString(getDefaultExpression(column))}@@ -609,6 +744,19 @@ func writeModifyColumn(buf *strings.Builder, table string, column *storepb.Colum_, _ = buf.WriteString(column.OnUpdate)}+ // Handle generated columns+ if column.Generation != nil && column.Generation.Expression != "" {+ _, _ = buf.WriteString(" GENERATED ALWAYS AS (")+ _, _ = buf.WriteString(column.Generation.Expression)+ _, _ = buf.WriteString(") ")+ switch column.Generation.Type {+ case storepb.GenerationMetadata_TYPE_STORED:+ _, _ = buf.WriteString("STORED")+ case storepb.GenerationMetadata_TYPE_VIRTUAL:+ _, _ = buf.WriteString("VIRTUAL")+ }+ }+if column.Comment != "" {_, _ = buf.WriteString(" COMMENT '")_, _ = buf.WriteString(escapeString(column.Comment))@@ -638,12 +786,24 @@ func writeCreateIndex(buf *strings.Builder, table string, index *storepb.IndexMeif i > 0 {_, _ = buf.WriteString(", ")}- _, _ = buf.WriteString("`")- _, _ = buf.WriteString(expr)- _, _ = buf.WriteString("`")++ // Check if this is a functional expression or a column name+ // Functional expressions start with ( and end with )+ if strings.HasPrefix(expr, "(") && strings.HasSuffix(expr, ")") {+ // This is a functional expression, unescape quotes and write it as-is+ unescapedExpr := strings.ReplaceAll(expr, "\\'", "'")+ _, _ = buf.WriteString(unescapedExpr)+ } else {+ // This is a column name, wrap it in backticks+ _, _ = buf.WriteString("`")+ _, _ = buf.WriteString(expr)+ _, _ = buf.WriteString("`")+ }// Handle column length for text/blob columns- if i < len(index.KeyLength) && index.KeyLength[i] > 0 {+ // SPATIAL indexes do not support key lengths, and functional expressions don't use key lengths+ if i < len(index.KeyLength) && index.KeyLength[i] > 0 && strings.ToUpper(index.Type) != "SPATIAL" &&+ (!strings.HasPrefix(expr, "(") || !strings.HasSuffix(expr, ")")) {_, _ = fmt.Fprintf(buf, "(%d)", index.KeyLength[i])}}@@ -761,23 +921,6 @@ func writeAddForeignKey(buf *strings.Builder, table string, fk *storepb.ForeignKreturn nil}-func writeCreateView(buf *strings.Builder, viewName string, view *storepb.ViewMetadata) error {- _, _ = buf.WriteString("CREATE VIEW `")- _, _ = buf.WriteString(viewName)- _, _ = buf.WriteString("` AS ")- _, _ = buf.WriteString(view.Definition)-- if !strings.HasSuffix(strings.TrimSpace(view.Definition), ";") {- _, _ = buf.WriteString(";")- }- _, _ = buf.WriteString("\n")-- // Note: MySQL doesn't support adding comments directly to views via DDL- // View comments are stored in information_schema.VIEWS but cannot be set via CREATE VIEW- // The comment field is read-only- return nil-}-func writeCreateOrReplaceView(buf *strings.Builder, viewName string, view *storepb.ViewMetadata) error {_, _ = buf.WriteString("CREATE OR REPLACE VIEW `")_, _ = buf.WriteString(viewName)@@ -956,6 +1099,31 @@ func writeTemporaryViewForDrop(buf *strings.Builder, viewName string, view *storreturn nil}+func writeCreateTemporaryView(buf *strings.Builder, viewName string, view *storepb.ViewMetadata) error {+ // Create a temporary view with SELECT 1 AS column_name structure+ // to satisfy views that depend on this view before we create the real one+ _, _ = buf.WriteString("CREATE VIEW `")+ _, _ = buf.WriteString(viewName)+ _, _ = buf.WriteString("` AS SELECT")++ for i, column := range view.Columns {+ if i > 0 {+ _, _ = buf.WriteString(",")+ }+ _, _ = buf.WriteString(" 1 AS `")+ _, _ = buf.WriteString(column.Name)+ _, _ = buf.WriteString("`")+ }++ // If no columns, create a dummy view+ if len(view.Columns) == 0 {+ _, _ = buf.WriteString(" 1")+ }++ _, _ = buf.WriteString(";\n")+ return nil+}+func isNumeric(s string) bool {// Simple check for numeric values_, err := fmt.Sscanf(s, "%f", new(float64))diff --git a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.goindex a2d6f6e93c..201ecfcd75 100644--- a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go@@ -49,6 +49,57 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {migrationDDL stringdescription string}{+ {+ name: "drop_table_with_dependencies",+ initialSchema: ``,+ migrationDDL: `+--+-- Table structure for authors+--+CREATE TABLE authors (+ id int NOT NULL AUTO_INCREMENT,+ name varchar(100) NOT NULL,+ email varchar(100) DEFAULT NULL,+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;++--+-- Table structure for books+--+CREATE TABLE books (+ id int NOT NULL AUTO_INCREMENT,+ title varchar(200) NOT NULL,+ author_id int NOT NULL,+ isbn varchar(20) DEFAULT NULL,+ published_year int DEFAULT NULL,+ price decimal(8,2) DEFAULT NULL,+ PRIMARY KEY (id),+ KEY idx_author (author_id),+ KEY idx_year (published_year),+ UNIQUE KEY uk_isbn (isbn),+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors (id),+ CONSTRAINT chk_price_positive CHECK (price > 0),+ CONSTRAINT chk_year_valid CHECK ((published_year >= 1000) and (published_year <= 2100))+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;+++--+-- Table structure for products+--+CREATE TABLE products (+ id int NOT NULL AUTO_INCREMENT,+ name varchar(50) NOT NULL,+ price decimal(8,2) NOT NULL,+ description text DEFAULT NULL,+ category varchar(30) DEFAULT NULL,+ is_active tinyint(1) DEFAULT '1',+ PRIMARY KEY (id),+ KEY idx_category (category),+ KEY idx_price (price)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;+ `,+ },{name: "create_tables_with_fk",initialSchema: `@@ -972,6 +1023,564 @@ CREATE TABLE analytics (`,description: "Test comments with special characters, quotes, multiline text, and Unicode",},+ // Reverse test cases+ {+ name: "reverse_drop_table_with_dependencies",+ initialSchema: `+CREATE TABLE authors (+ id int NOT NULL AUTO_INCREMENT,+ name varchar(100) NOT NULL,+ email varchar(100) DEFAULT NULL,+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;++CREATE TABLE books (+ id int NOT NULL AUTO_INCREMENT,+ title varchar(200) NOT NULL,+ author_id int NOT NULL,+ isbn varchar(20) DEFAULT NULL,+ published_year int DEFAULT NULL,+ price decimal(8,2) DEFAULT NULL,+ PRIMARY KEY (id),+ KEY idx_author (author_id),+ KEY idx_year (published_year),+ UNIQUE KEY uk_isbn (isbn),+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors (id),+ CONSTRAINT chk_price_positive CHECK (price > 0),+ CONSTRAINT chk_year_valid CHECK ((published_year >= 1000) and (published_year <= 2100))+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;++CREATE TABLE products (+ id int NOT NULL AUTO_INCREMENT,+ name varchar(50) NOT NULL,+ price decimal(8,2) NOT NULL,+ description text DEFAULT NULL,+ category varchar(30) DEFAULT NULL,+ is_active tinyint(1) DEFAULT '1',+ PRIMARY KEY (id),+ KEY idx_category (category),+ KEY idx_price (price)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;+ `,+ migrationDDL: `+DROP TABLE books;+DROP TABLE authors;+DROP TABLE products;+ `,+ description: "Reverse: Drop tables with foreign key dependencies",+ },+ {+ name: "reverse_create_tables_with_fk",+ initialSchema: ``,+ migrationDDL: `+CREATE TABLE users (+ id INT NOT NULL AUTO_INCREMENT,+ username VARCHAR(50) NOT NULL,+ email VARCHAR(100) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email),+ INDEX idx_username (username)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;++CREATE TABLE posts (+ id INT NOT NULL AUTO_INCREMENT,+ user_id INT NOT NULL,+ title VARCHAR(200) NOT NULL,+ content TEXT,+ published_at DATETIME,+ PRIMARY KEY (id),+ INDEX idx_user_id (user_id),+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;+ `,+ description: "Reverse: Create tables with foreign key constraints",+ },+ {+ name: "reverse_basic_table_operations",+ initialSchema: `+CREATE TABLE users (+ id INT NOT NULL AUTO_INCREMENT,+ username VARCHAR(50) NOT NULL,+ email VARCHAR(100) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ is_active BOOLEAN DEFAULT true,+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email),+ INDEX idx_username (username),+ INDEX idx_email_active (email, is_active)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;++CREATE TABLE posts (+ id INT NOT NULL AUTO_INCREMENT,+ user_id INT NOT NULL,+ title VARCHAR(200) NOT NULL,+ content TEXT,+ published_at DATETIME,+ PRIMARY KEY (id),+ INDEX idx_user_id (user_id),+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,+ CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;++CREATE TABLE comments (+ id INT NOT NULL AUTO_INCREMENT,+ post_id INT NOT NULL,+ user_id INT NOT NULL,+ content TEXT NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (id),+ INDEX idx_post_user (post_id, user_id),+ CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;+ `,+ migrationDDL: `+-- Drop table+DROP TABLE comments;++-- Remove constraints+ALTER TABLE posts DROP CHECK chk_title_length;++-- Drop index+DROP INDEX idx_email_active ON users;++-- Drop column+ALTER TABLE users DROP COLUMN is_active;+ `,+ description: "Reverse: Basic table operations",+ },+ {+ name: "reverse_views_and_triggers",+ initialSchema: `+CREATE TABLE products (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ price DECIMAL(10, 2) NOT NULL,+ stock INT DEFAULT 0,+ PRIMARY KEY (id),+ INDEX idx_name (name)+) ENGINE=InnoDB;++CREATE TABLE orders (+ id INT NOT NULL AUTO_INCREMENT,+ product_id INT NOT NULL,+ quantity INT NOT NULL,+ total DECIMAL(10, 2),+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (id),+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)+) ENGINE=InnoDB;++CREATE VIEW product_inventory AS+SELECT+ p.id,+ p.name,+ p.price,+ p.stock,+ COALESCE(SUM(o.quantity), 0) AS total_ordered+FROM products p+LEFT JOIN orders o ON p.id = o.product_id+GROUP BY p.id, p.name, p.price, p.stock;++CREATE VIEW low_stock_products AS+SELECT * FROM products WHERE stock < 10;++CREATE TRIGGER update_order_total+BEFORE INSERT ON orders+FOR EACH ROW+BEGIN+ DECLARE product_price DECIMAL(10, 2);+ SELECT price INTO product_price FROM products WHERE id = NEW.product_id;+ SET NEW.total = NEW.quantity * product_price;+END;++CREATE PROCEDURE GetProductInventory(IN product_name VARCHAR(100))+BEGIN+ SELECT * FROM product_inventory+ WHERE name LIKE CONCAT('%', product_name, '%');+END;+ `,+ migrationDDL: `+-- Drop procedure+DROP PROCEDURE GetProductInventory;++-- Drop trigger+DROP TRIGGER update_order_total;++-- Drop views+DROP VIEW low_stock_products;+DROP VIEW product_inventory;+ `,+ description: "Reverse: Views and triggers",+ },+ {+ name: "reverse_stored_functions",+ initialSchema: `+CREATE TABLE sales (+ id INT NOT NULL AUTO_INCREMENT,+ product_id INT NOT NULL,+ quantity INT NOT NULL,+ unit_price DECIMAL(10, 2) NOT NULL,+ sale_date DATE NOT NULL,+ PRIMARY KEY (id),+ INDEX idx_product_date (product_id, sale_date)+) ENGINE=InnoDB;++CREATE TABLE sales_summary (+ id INT NOT NULL AUTO_INCREMENT,+ product_id INT NOT NULL,+ month_year VARCHAR(7) NOT NULL,+ total_sales DECIMAL(10, 2),+ tax_amount DECIMAL(10, 2),+ PRIMARY KEY (id),+ UNIQUE KEY uk_product_month (product_id, month_year)+) ENGINE=InnoDB;++CREATE FUNCTION CalculateTotalSales(p_product_id INT, p_start_date DATE, p_end_date DATE)+RETURNS DECIMAL(10, 2)+DETERMINISTIC+READS SQL DATA+BEGIN+ DECLARE total DECIMAL(10, 2);++ SELECT COALESCE(SUM(quantity * unit_price), 0) INTO total+ FROM sales+ WHERE product_id = p_product_id+ AND sale_date BETWEEN p_start_date AND p_end_date;++ RETURN total;+END;++CREATE FUNCTION GetTaxAmount(amount DECIMAL(10, 2), tax_rate DECIMAL(5, 2))+RETURNS DECIMAL(10, 2)+DETERMINISTIC+NO SQL+BEGIN+ RETURN amount * (tax_rate / 100);+END;+ `,+ migrationDDL: `+-- Drop functions+DROP FUNCTION CalculateTotalSales;+DROP FUNCTION GetTaxAmount;++-- Drop table+DROP TABLE sales_summary;+ `,+ description: "Reverse: Stored functions",+ },+ {+ name: "reverse_drop_indexes_and_constraints",+ initialSchema: `+CREATE TABLE products (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ category VARCHAR(50),+ price DECIMAL(10, 2),+ sku VARCHAR(50) NOT NULL,+ PRIMARY KEY (id)+) ENGINE=InnoDB;+ `,+ migrationDDL: `+-- Add indexes and constraints+CREATE INDEX idx_name ON products(name);+CREATE INDEX idx_category ON products(category);+CREATE INDEX idx_price ON products(price);+ALTER TABLE products ADD UNIQUE KEY uk_sku (sku);+ALTER TABLE products ADD CONSTRAINT chk_price_positive CHECK (price > 0);+ALTER TABLE products ADD CONSTRAINT chk_name_length CHECK (CHAR_LENGTH(name) >= 3);+ `,+ description: "Reverse: Add indexes and constraints",+ },+ {+ name: "reverse_alter_table_columns",+ initialSchema: `+CREATE TABLE products (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ price DECIMAL(10, 2) NOT NULL,+ description TEXT NOT NULL,+ category VARCHAR(50),+ is_active TINYINT(1) DEFAULT 1,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,+ stock_quantity INT DEFAULT 0,+ weight DECIMAL(5, 2),+ PRIMARY KEY (id),+ INDEX idx_category (category),+ INDEX idx_price (price),+ INDEX idx_created_at (created_at),+ UNIQUE INDEX uk_name_category (name, category),+ CONSTRAINT chk_price_positive CHECK (price > 0),+ CONSTRAINT chk_stock_non_negative CHECK (stock_quantity >= 0)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;+ `,+ migrationDDL: `+-- Drop constraints+ALTER TABLE products DROP CHECK chk_price_positive;+ALTER TABLE products DROP CHECK chk_stock_non_negative;++-- Drop indexes+DROP INDEX idx_created_at ON products;+DROP INDEX uk_name_category ON products;++-- Drop columns+ALTER TABLE products DROP COLUMN created_at;+ALTER TABLE products DROP COLUMN updated_at;+ALTER TABLE products DROP COLUMN stock_quantity;+ALTER TABLE products DROP COLUMN weight;++-- Modify columns+ALTER TABLE products MODIFY COLUMN name VARCHAR(50) NOT NULL;+ALTER TABLE products MODIFY COLUMN price DECIMAL(8, 2) NOT NULL;+ALTER TABLE products MODIFY COLUMN description TEXT;+ALTER TABLE products MODIFY COLUMN category VARCHAR(30);+ `,+ description: "Reverse: Alter table columns",+ },+ {+ name: "reverse_fulltext_and_spatial_indexes",+ initialSchema: `+CREATE TABLE articles (+ id INT NOT NULL AUTO_INCREMENT,+ title VARCHAR(200) NOT NULL,+ content TEXT NOT NULL,+ tags VARCHAR(500),+ PRIMARY KEY (id),+ FULLTEXT idx_fulltext_content (title, content),+ FULLTEXT idx_fulltext_tags (tags),+ INDEX idx_title_tags (title(50), tags(50))+) ENGINE=InnoDB;++CREATE TABLE locations (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ position POINT NOT NULL,+ PRIMARY KEY (id),+ SPATIAL INDEX idx_spatial_position (position)+) ENGINE=InnoDB;+ `,+ migrationDDL: `+-- Drop indexes+DROP INDEX idx_fulltext_content ON articles;+DROP INDEX idx_fulltext_tags ON articles;+DROP INDEX idx_title_tags ON articles;+DROP INDEX idx_spatial_position ON locations;+ `,+ description: "Reverse: Drop FULLTEXT and SPATIAL indexes",+ },+ {+ name: "reverse_generated_columns",+ initialSchema: `+CREATE TABLE products (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ price DECIMAL(10, 2) NOT NULL,+ tax_rate DECIMAL(5, 2) DEFAULT 8.0,+ price_with_tax DECIMAL(10, 2) AS (price * (1 + tax_rate / 100)) STORED,+ name_upper VARCHAR(100) AS (UPPER(name)) VIRTUAL,+ PRIMARY KEY (id),+ INDEX idx_price_with_tax (price_with_tax),+ INDEX idx_name_upper (name_upper)+) ENGINE=InnoDB;++CREATE TABLE order_summary (+ id INT NOT NULL AUTO_INCREMENT,+ product_id INT NOT NULL,+ quantity INT NOT NULL,+ unit_price DECIMAL(10, 2) NOT NULL,+ total_price DECIMAL(10, 2) AS (quantity * unit_price) STORED,+ order_date DATE NOT NULL,+ order_year INT AS (YEAR(order_date)) VIRTUAL,+ order_month INT AS (MONTH(order_date)) VIRTUAL,+ PRIMARY KEY (id),+ INDEX idx_year_month (order_year, order_month)+) ENGINE=InnoDB;+ `,+ migrationDDL: `+-- Drop table+DROP TABLE order_summary;++-- Drop indexes+DROP INDEX idx_price_with_tax ON products;+DROP INDEX idx_name_upper ON products;++-- Drop generated columns+ALTER TABLE products DROP COLUMN price_with_tax;+ALTER TABLE products DROP COLUMN name_upper;+ `,+ description: "Reverse: Drop generated columns",+ },+ {+ name: "reverse_json_columns_and_indexes",+ initialSchema: `+CREATE TABLE users (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ email VARCHAR(100) NOT NULL,+ preferences JSON,+ metadata JSON,+ PRIMARY KEY (id)+) ENGINE=InnoDB;++CREATE TABLE products (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ details JSON NOT NULL,+ tags JSON,+ brand VARCHAR(50) AS (details->>'$.brand') VIRTUAL,+ PRIMARY KEY (id),+ INDEX idx_product_brand ((CAST(details->>'$.brand' AS CHAR(50)))),+ INDEX idx_product_price ((CAST(details->>'$.price' AS DECIMAL(10,2)))),+ INDEX idx_brand (brand),+ CONSTRAINT chk_details_not_empty CHECK (JSON_TYPE(details) IS NOT NULL)+) ENGINE=InnoDB;+ `,+ migrationDDL: `+-- Drop table+DROP TABLE products;++-- Drop columns+ALTER TABLE users DROP COLUMN preferences;+ALTER TABLE users DROP COLUMN metadata;+ `,+ description: "Reverse: Drop JSON columns and indexes",+ },+ {+ name: "reverse_complex_triggers",+ initialSchema: `+CREATE TABLE inventory (+ id INT NOT NULL AUTO_INCREMENT,+ product_id INT NOT NULL,+ quantity INT NOT NULL DEFAULT 0,+ last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,+ PRIMARY KEY (id),+ UNIQUE KEY uk_product (product_id)+) ENGINE=InnoDB;++CREATE TABLE inventory_log (+ id INT NOT NULL AUTO_INCREMENT,+ product_id INT NOT NULL,+ old_quantity INT,+ new_quantity INT,+ change_type VARCHAR(20),+ changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (id)+) ENGINE=InnoDB;++CREATE TRIGGER trg_inventory_insert+AFTER INSERT ON inventory+FOR EACH ROW+BEGIN+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)+ VALUES (NEW.product_id, NULL, NEW.quantity, 'INSERT');+END;++CREATE TRIGGER trg_inventory_update+AFTER UPDATE ON inventory+FOR EACH ROW+BEGIN+ IF OLD.quantity != NEW.quantity THEN+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)+ VALUES (NEW.product_id, OLD.quantity, NEW.quantity, 'UPDATE');+ END IF;+END;++CREATE TRIGGER trg_inventory_delete+BEFORE DELETE ON inventory+FOR EACH ROW+BEGIN+ INSERT INTO inventory_log (product_id, old_quantity, new_quantity, change_type)+ VALUES (OLD.product_id, OLD.quantity, NULL, 'DELETE');+END;++CREATE VIEW inventory_changes AS+SELECT+ product_id,+ COUNT(*) AS change_count,+ MAX(changed_at) AS last_changed+FROM inventory_log+GROUP BY product_id;+ `,+ migrationDDL: `+-- Drop view+DROP VIEW inventory_changes;++-- Drop triggers+DROP TRIGGER trg_inventory_delete;+DROP TRIGGER trg_inventory_update;+DROP TRIGGER trg_inventory_insert;+ `,+ description: "Reverse: Drop triggers and views",+ },+ {+ name: "reverse_events_and_advanced_features",+ initialSchema: `+CREATE TABLE system_stats (+ id INT NOT NULL AUTO_INCREMENT,+ stat_name VARCHAR(100) NOT NULL,+ stat_value DECIMAL(10, 2),+ recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (id)+) ENGINE=InnoDB;++CREATE EVENT IF NOT EXISTS evt_cleanup_old_stats+ON SCHEDULE EVERY 1 DAY+STARTS CURRENT_TIMESTAMP+DO+BEGIN+ DELETE FROM system_stats+ WHERE recorded_at < DATE_SUB(NOW(), INTERVAL 30 DAY);+END;++CREATE PROCEDURE RecordSystemStat(+ IN p_stat_name VARCHAR(100),+ IN p_stat_value DECIMAL(10, 2)+)+BEGIN+ DECLARE EXIT HANDLER FOR SQLEXCEPTION+ BEGIN+ ROLLBACK;+ RESIGNAL;+ END;++ START TRANSACTION;++ INSERT INTO system_stats (stat_name, stat_value)+ VALUES (p_stat_name, p_stat_value);++ COMMIT;+END;++CREATE FUNCTION GetAverageStat(p_stat_name VARCHAR(100))+RETURNS DECIMAL(10, 2)+DETERMINISTIC+READS SQL DATA+BEGIN+ DECLARE avg_value DECIMAL(10, 2);++ SELECT AVG(stat_value) INTO avg_value+ FROM system_stats+ WHERE stat_name = p_stat_name+ AND recorded_at >= DATE_SUB(NOW(), INTERVAL 7 DAY);++ RETURN COALESCE(avg_value, 0);+END;+ `,+ migrationDDL: `+-- Drop event+DROP EVENT IF EXISTS evt_cleanup_old_stats;++-- Drop procedure+DROP PROCEDURE RecordSystemStat;++-- Drop function+DROP FUNCTION GetAverageStat;+ `,+ description: "Reverse: Drop events and advanced features",+ },}for _, tc := range testCases {diff --git a/backend/plugin/schema/mysql/get_database_definition.go b/backend/plugin/schema/mysql/get_database_definition.goindex ce06b4f06a..629c4f7381 100644--- a/backend/plugin/schema/mysql/get_database_definition.go+++ b/backend/plugin/schema/mysql/get_database_definition.go@@ -497,19 +497,8 @@ func writeView(out io.Writer, view *storepb.ViewMetadata) error {return err}- // Drop temporary view.- if _, err := io.WriteString(out, "DROP VIEW IF EXISTS `"); err != nil {- return err- }- if _, err := io.WriteString(out, view.Name); err != nil {- return err- }- if _, err := io.WriteString(out, "`;\n"); err != nil {- return err- }-// Definition.- if _, err := io.WriteString(out, "CREATE VIEW `"); err != nil {+ if _, err := io.WriteString(out, "CREATE OR REPLACE VIEW `"); err != nil {return err}if _, err := io.WriteString(out, view.Name); err != nil {diff --git a/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go b/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.goindex cea952d347..831605bbcd 100644--- a/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go+++ b/backend/plugin/schema/mysql/get_database_definition_testcontainer_test.go@@ -184,6 +184,7 @@ DELIMITER ;description: "Partitioned tables",databaseName: "test_partitions",originalDDL: `+-- RANGE partitionCREATE TABLE sales (id INT NOT NULL AUTO_INCREMENT,sale_date DATE NOT NULL,@@ -197,6 +198,55 @@ CREATE TABLE sales (PARTITION p2024 VALUES LESS THAN (2025),PARTITION p_future VALUES LESS THAN MAXVALUE);++-- HASH partition+CREATE TABLE employees (+ id INT NOT NULL,+ name VARCHAR(100) NOT NULL,+ department_id INT NOT NULL,+ hired_date DATE,+ PRIMARY KEY (id)+) PARTITION BY HASH(id) PARTITIONS 4;++-- LIST partition+CREATE TABLE customer_regions (+ id INT NOT NULL AUTO_INCREMENT,+ customer_name VARCHAR(100) NOT NULL,+ region VARCHAR(20) NOT NULL,+ sales_amount DECIMAL(10, 2),+ PRIMARY KEY (id, region)+) PARTITION BY LIST COLUMNS(region) (+ PARTITION p_north VALUES IN ('north', 'northeast', 'northwest'),+ PARTITION p_south VALUES IN ('south', 'southeast', 'southwest'),+ PARTITION p_east VALUES IN ('east'),+ PARTITION p_west VALUES IN ('west'),+ PARTITION p_central VALUES IN ('central')+);++-- KEY partition+CREATE TABLE user_sessions (+ session_id VARCHAR(64) NOT NULL,+ user_id INT NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,+ PRIMARY KEY (session_id)+) PARTITION BY KEY() PARTITIONS 8;++-- RANGE COLUMNS partition+CREATE TABLE order_archive (+ order_id INT NOT NULL,+ order_date DATE NOT NULL,+ customer_id INT NOT NULL,+ status VARCHAR(20) NOT NULL,+ total_amount DECIMAL(10, 2),+ PRIMARY KEY (order_id, order_date)+) PARTITION BY RANGE COLUMNS(order_date) (+ PARTITION p_2022_q1 VALUES LESS THAN ('2022-04-01'),+ PARTITION p_2022_q2 VALUES LESS THAN ('2022-07-01'),+ PARTITION p_2022_q3 VALUES LESS THAN ('2022-10-01'),+ PARTITION p_2022_q4 VALUES LESS THAN ('2023-01-01'),+ PARTITION p_2023_and_later VALUES LESS THAN (MAXVALUE)+);`,},{diff --git a/frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vue b/frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vueindex b5fc47be66..d7779a0085 100644--- a/frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vue+++ b/frontend/src/components/SyncDatabaseSchemaV1/SelectTargetDatabasesView.vue@@ -324,11 +324,20 @@ watch(if (schemaDiffCache.value[name]) {continue;} else {- const diffResp = await databaseStore.diffSchema({- name: db.name,- schema: props.sourceSchemaString,- sdlFormat: false,- });+ // Use changelog name if source is from changelog, otherwise use schema string+ const diffRequest = props.changelogSourceSchema?.changelogName+ ? {+ name: db.name,+ changelog: props.changelogSourceSchema.changelogName,+ sdlFormat: false,+ }+ : {+ name: db.name,+ schema: props.sourceSchemaString,+ sdlFormat: false,+ };++ const diffResp = await databaseStore.diffSchema(diffRequest);const schemaDiff = diffResp.diff ?? "";schemaDiffCache.value[name] = {raw: schemaDiff,