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 schema editor and fix bugs (#16636)
rebelice4a095a2b7186
diff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex a9d1f8a4b3..3ede70716a 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -1747,7 +1747,7 @@ func convertAdviceStatus(status storepb.Advice_Status) v1pb.Advice_Status {func (*SQLService) DiffMetadata(_ context.Context, req *connect.Request[v1pb.DiffMetadataRequest]) (*connect.Response[v1pb.DiffMetadataResponse], error) {request := req.Msgswitch request.Engine {- case v1pb.Engine_MYSQL, v1pb.Engine_POSTGRES, v1pb.Engine_TIDB, v1pb.Engine_ORACLE:+ case v1pb.Engine_MYSQL, v1pb.Engine_POSTGRES, v1pb.Engine_TIDB, v1pb.Engine_ORACLE, v1pb.Engine_MSSQL:default:return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupported engine: %v", request.Engine))}@@ -1771,27 +1771,21 @@ func (*SQLService) DiffMetadata(_ context.Context, req *connect.Request[v1pb.Difreturn nil, connect.NewError(connect.CodeInvalidArgument, errors.Wrap(err, "invalid target metadata"))}- sourceSchema, err := schema.GetDatabaseDefinition(storepb.Engine(request.Engine), schema.GetDefinitionContext{- SkipBackupSchema: false,- PrintHeader: true,- }, storeSourceMetadata)- if err != nil {- return nil, err- }- targetSchema, err := schema.GetDatabaseDefinition(storepb.Engine(request.Engine), schema.GetDefinitionContext{- SkipBackupSchema: false,- PrintHeader: true,- }, storeTargetMetadata)+ // Convert metadata to model.DatabaseSchema for diffing+ isObjectCaseSensitive := true+ sourceDBSchema := model.NewDatabaseSchema(storeSourceMetadata, nil, nil, storepb.Engine(request.Engine), isObjectCaseSensitive)+ targetDBSchema := model.NewDatabaseSchema(storeTargetMetadata, nil, nil, storepb.Engine(request.Engine), isObjectCaseSensitive)++ // Get the metadata diff between source and target+ metadataDiff, err := schema.GetDatabaseSchemaDiff(sourceDBSchema, targetDBSchema)if err != nil {- return nil, err+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to compute diff between source and target schemas, error: %v", err))}- diff, err := parserbase.SchemaDiff(convertEngine(request.Engine), parserbase.DiffContext{- IgnoreCaseSensitive: false,- StrictMode: true,- }, sourceSchema, targetSchema)+ // Generate migration SQL from the diff+ diff, err := schema.GenerateMigration(storepb.Engine(request.Engine), metadataDiff)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to compute diff between source and target schemas, error: %v", err))+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to generate migration SQL, error: %v", err))}return connect.NewResponse(&v1pb.DiffMetadataResponse{diff --git a/backend/plugin/db/mssql/sync.go b/backend/plugin/db/mssql/sync.goindex 60352e3a94..133f2e9004 100644--- a/backend/plugin/db/mssql/sync.go+++ b/backend/plugin/db/mssql/sync.go@@ -536,7 +536,13 @@ func getColumnType(definition, typeName sql.NullString, isComputed, isPersistedreturn "", err}} else {- if _, err := fmt.Fprintf(&buf, "(%d)", maxLength.Int64); err != nil {+ // For Unicode types (nchar, nvarchar), SQL Server stores byte count in max_length+ // Each Unicode character takes 2 bytes, so we need to divide by 2+ length := maxLength.Int64+ if typeName.String == "nchar" || typeName.String == "nvarchar" {+ length /= 2+ }+ if _, err := fmt.Fprintf(&buf, "(%d)", length); err != nil {return "", err}}diff --git a/backend/plugin/schema/mssql/generate_migration.go b/backend/plugin/schema/mssql/generate_migration.goindex 77650c5126..4a23b2500b 100644--- a/backend/plugin/schema/mssql/generate_migration.go+++ b/backend/plugin/schema/mssql/generate_migration.go@@ -147,8 +147,20 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {}// Drop columns- for _, colDiff := range tableDiff.ColumnChanges {+ hasDroppedIndex := false+ for _, indexDiff := range tableDiff.IndexChanges {+ if indexDiff.Action == schema.MetadataDiffActionDrop {+ hasDroppedIndex = true+ break+ }+ }++ for i, colDiff := range tableDiff.ColumnChanges {if colDiff.Action == schema.MetadataDiffActionDrop {+ // Add GO before first column drop if we dropped indexes+ if i == 0 && hasDroppedIndex {+ _, _ = buf.WriteString("GO\n")+ }_, _ = buf.WriteString("ALTER TABLE [")_, _ = buf.WriteString(tableDiff.SchemaName)_, _ = buf.WriteString("].[")@@ -161,9 +173,27 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {}}+ // Add GO after table alterations if we had any and we're about to drop tables+ hasTableAlterations := false+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionAlter {+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionDrop {+ hasTableAlterations = true+ break+ }+ }+ }+ }+// 1.6 Drop tables+ hasTableDrops := falsefor _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionDrop {+ if !hasTableDrops && hasTableAlterations {+ _, _ = buf.WriteString("GO\n")+ }+ hasTableDrops = true_, _ = buf.WriteString("DROP TABLE [")_, _ = buf.WriteString(tableDiff.SchemaName)_, _ = buf.WriteString("].[")@@ -237,30 +267,8 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {_, _ = buf.WriteString("\n")}- // 2.2 Create new tables WITHOUT foreign keys (sorted for consistent output)- var tablesToCreate []*schema.TableDiff- for _, tableDiff := range diff.TableChanges {- if tableDiff.Action == schema.MetadataDiffActionCreate {- tablesToCreate = append(tablesToCreate, tableDiff)- }- }- // Sort by schema.table name for consistent output- slices.SortFunc(tablesToCreate, func(i, j *schema.TableDiff) int {- iFullName := getObjectID(i.SchemaName, i.TableName)- jFullName := getObjectID(j.SchemaName, j.TableName)- if iFullName < jFullName {- return -1- }- if iFullName > jFullName {- return 1- }- return 0- })- for _, tableDiff := range tablesToCreate {- createTableSQL := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable)- _, _ = buf.WriteString(createTableSQL)- _, _ = buf.WriteString("\n")- }+ // 2.2 Create new tables WITHOUT foreign keys (in topological order based on FK dependencies)+ createTablesInOrder(diff, &buf)// 2.3 Alter existing tables (add columns, alter columns)for _, tableDiff := range diff.TableChanges {@@ -274,11 +282,13 @@ func generateMigration(diff *schema.MetadataDiff) (string, error) {}// 2.4 Add foreign keys for newly created tables (after all tables exist)- for _, tableDiff := range tablesToCreate {- for _, fk := range tableDiff.NewTable.ForeignKeys {- fkSQL := generateAddForeignKey(tableDiff.SchemaName, tableDiff.TableName, fk)- _, _ = buf.WriteString(fkSQL)- _, _ = buf.WriteString(";\n")+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {+ for _, fk := range tableDiff.NewTable.ForeignKeys {+ fkSQL := generateAddForeignKey(tableDiff.SchemaName, tableDiff.TableName, fk)+ _, _ = buf.WriteString(fkSQL)+ _, _ = buf.WriteString(";\n")+ }}}@@ -525,6 +535,13 @@ func generateColumnDefinition(column *storepb.ColumnMetadata) string {_, _ = buf.WriteString("] ")_, _ = buf.WriteString(column.Type)+ // Add IDENTITY if applicable+ if column.IsIdentity {+ _, _ = buf.WriteString(" IDENTITY(")+ _, _ = buf.WriteString(fmt.Sprintf("%d,%d", column.IdentitySeed, column.IdentityIncrement))+ _, _ = buf.WriteString(")")+ }+// Add nullabilityif column.Nullable {_, _ = buf.WriteString(" NULL")@@ -532,11 +549,13 @@ func generateColumnDefinition(column *storepb.ColumnMetadata) string {_, _ = buf.WriteString(" NOT NULL")}- // Add default value- defaultExpr := getDefaultExpression(column)- if defaultExpr != "" {- _, _ = buf.WriteString(" DEFAULT ")- _, _ = buf.WriteString(defaultExpr)+ // Add default value (but not for IDENTITY columns)+ if !column.IsIdentity {+ defaultExpr := getDefaultExpression(column)+ if defaultExpr != "" {+ _, _ = buf.WriteString(" DEFAULT ")+ _, _ = buf.WriteString(defaultExpr)+ }}return buf.String()@@ -1019,6 +1038,79 @@ func dropViewsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {}}+// createTablesInOrder creates tables in topological order (dependencies first based on foreign keys)+func createTablesInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {+ // Build dependency graph for tables being created+ graph := base.NewGraph()+ tableMap := make(map[string]*schema.TableDiff)++ // First pass: Add all tables to be created to the graph and tableMap+ // Sort for deterministic processing order+ var tablesToCreate []*schema.TableDiff+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionCreate {+ tablesToCreate = append(tablesToCreate, tableDiff)+ }+ }+ slices.SortFunc(tablesToCreate, func(i, j *schema.TableDiff) int {+ iFullName := getObjectID(i.SchemaName, i.TableName)+ jFullName := getObjectID(j.SchemaName, j.TableName)+ if iFullName < jFullName {+ return -1+ }+ if iFullName > jFullName {+ return 1+ }+ return 0+ })++ for _, tableDiff := range tablesToCreate {+ tableID := getObjectID(tableDiff.SchemaName, tableDiff.TableName)+ graph.AddNode(tableID)+ tableMap[tableID] = tableDiff+ }++ // Second pass: Add dependency edges based on foreign keys+ for _, tableDiff := range tablesToCreate {+ tableID := getObjectID(tableDiff.SchemaName, tableDiff.TableName)++ // Add edges based on foreign key dependencies+ if tableDiff.NewTable != nil {+ for _, fk := range tableDiff.NewTable.ForeignKeys {+ // Create dependency ID for the referenced table+ refTableID := getObjectID(fk.ReferencedSchema, fk.ReferencedTable)++ // Only add edge if the referenced table is also being created+ if _, exists := tableMap[refTableID]; exists {+ // Edge from referenced table to this table (referenced must be created first)+ graph.AddEdge(refTableID, tableID)+ }+ }+ }+ }++ // Get topological order+ orderedList, err := graph.TopologicalSort()+ if err != nil {+ // If there's a cycle or error, fall back to alphabetical order+ for _, tableDiff := range tablesToCreate {+ createTableSQL := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable)+ _, _ = buf.WriteString(createTableSQL)+ _, _ = buf.WriteString("\n")+ }+ return+ }++ // Create tables in order+ for _, tableID := range orderedList {+ if tableDiff, ok := tableMap[tableID]; ok {+ createTableSQL := generateCreateTable(tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable)+ _, _ = buf.WriteString(createTableSQL)+ _, _ = buf.WriteString("\n")+ }+ }+}+// createViewsInOrder creates views in topological order (dependencies first)func createViewsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {// Build dependency graph for views being created or altereddiff --git a/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mssql/generate_migration_testcontainer_test.goindex b9b9c8b624..3f39876558 100644--- a/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go@@ -499,6 +499,211 @@ ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [`,description: "Temporal tables with system versioning",},+ {+ name: "create_tables_with_fk",+ initialSchema: `+CREATE SCHEMA [test];+GO++CREATE TABLE [test].[users] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [username] NVARCHAR(50) NOT NULL,+ [email] NVARCHAR(100) NOT NULL,+ [created_at] DATETIME2 DEFAULT GETDATE(),+ CONSTRAINT [uk_email] UNIQUE ([email])+);++CREATE INDEX [idx_username] ON [test].[users] ([username]);++CREATE TABLE [test].[posts] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [user_id] INT NOT NULL,+ [title] NVARCHAR(200) NOT NULL,+ [content] NVARCHAR(MAX),+ [published_at] DATETIME2,+ CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE+);++CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);+`,+ migrationDDL: `+DROP TABLE [test].[posts];+DROP TABLE [test].[users];+DROP SCHEMA [test];`,+ description: "Create tables with foreign key constraints",+ },+ {+ name: "multiple_foreign_keys",+ initialSchema: `+CREATE SCHEMA [test];+GO++CREATE TABLE [test].[users] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [username] NVARCHAR(50) NOT NULL,+ [email] NVARCHAR(100) NOT NULL,+ [created_at] DATETIME2 DEFAULT GETDATE(),+ CONSTRAINT [uk_email] UNIQUE ([email])+);+GO++CREATE INDEX [idx_username] ON [test].[users] ([username]);+GO++CREATE TABLE [test].[posts] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [user_id] INT NOT NULL,+ [title] NVARCHAR(200) NOT NULL,+ [content] NVARCHAR(MAX),+ [published_at] DATETIME2,+ CONSTRAINT [fk_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE CASCADE+);+GO++CREATE INDEX [idx_user_id] ON [test].[posts] ([user_id]);+GO+`,+ migrationDDL: `+-- Add new column+ALTER TABLE [test].[users] ADD [is_active] BIT;+GO++-- Create new table with multiple foreign keys+CREATE TABLE [test].[comments] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [post_id] INT NOT NULL,+ [user_id] INT NOT NULL,+ [content] NVARCHAR(MAX) NOT NULL,+ [created_at] DATETIME2 DEFAULT GETDATE(),+ CONSTRAINT [fk_comment_post] FOREIGN KEY ([post_id]) REFERENCES [test].[posts]([id]) ON DELETE CASCADE,+ CONSTRAINT [fk_comment_user] FOREIGN KEY ([user_id]) REFERENCES [test].[users]([id]) ON DELETE NO ACTION+);+GO++CREATE INDEX [idx_post_user] ON [test].[comments] ([post_id], [user_id]);++-- Add new index+CREATE INDEX [idx_email_active] ON [test].[users] ([email], [is_active]);++-- Add check constraint+ALTER TABLE [test].[posts] ADD CONSTRAINT [chk_title_length] CHECK (LEN([title]) > 0);+`,+ description: "Tables with multiple foreign key constraints",+ },+ {+ name: "drop_and_recreate_fk_constraints",+ initialSchema: `+CREATE SCHEMA [library];+GO++CREATE TABLE [library].[authors] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [email] NVARCHAR(100),+ CONSTRAINT [uk_email] UNIQUE ([email])+);++CREATE TABLE [library].[books] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [title] NVARCHAR(200) NOT NULL,+ [author_id] INT NOT NULL,+ [isbn] NVARCHAR(20),+ [published_year] INT,+ [price] DECIMAL(8, 2),+ CONSTRAINT [fk_author] FOREIGN KEY ([author_id]) REFERENCES [library].[authors]([id]),+ CONSTRAINT [chk_year_valid] CHECK ([published_year] >= 1000 AND [published_year] <= 2100),+ CONSTRAINT [chk_price_positive] CHECK ([price] > 0),+ CONSTRAINT [uk_isbn] UNIQUE ([isbn])+);++CREATE INDEX [idx_author] ON [library].[books] ([author_id]);+CREATE INDEX [idx_year] ON [library].[books] ([published_year]);+`,+ migrationDDL: `+-- Drop and recreate foreign key with different options+ALTER TABLE [library].[books] DROP CONSTRAINT [fk_author];+ALTER TABLE [library].[books] ADD CONSTRAINT [fk_author_new] FOREIGN KEY ([author_id]) REFERENCES [library].[authors]([id]) ON DELETE CASCADE ON UPDATE CASCADE;++-- Drop and modify check constraints+ALTER TABLE [library].[books] DROP CONSTRAINT [chk_year_valid];+ALTER TABLE [library].[books] ADD CONSTRAINT [chk_year_extended] CHECK ([published_year] >= 1000 AND [published_year] <= 2030);++-- Add new constraints+ALTER TABLE [library].[books] ADD CONSTRAINT [chk_title_length] CHECK (LEN([title]) >= 3);+`,+ description: "Drop and recreate foreign key constraints with different options",+ },+ {+ name: "self_referencing_foreign_keys",+ initialSchema: `+CREATE SCHEMA [company];+GO++CREATE TABLE [company].[departments] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [manager_id] INT+);++CREATE TABLE [company].[employees] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [department_id] INT,+ [salary] DECIMAL(10, 2),+ [hire_date] DATE,+ CONSTRAINT [fk_dept] FOREIGN KEY ([department_id]) REFERENCES [company].[departments]([id])+);++CREATE INDEX [idx_dept] ON [company].[employees] ([department_id]);++-- Add self-referencing foreign key+ALTER TABLE [company].[departments] ADD CONSTRAINT [fk_manager] FOREIGN KEY ([manager_id]) REFERENCES [company].[employees]([id]);+`,+ migrationDDL: `+-- Create base view+CREATE VIEW [company].[dept_employee_count] AS+SELECT d.[id] AS dept_id, d.[name] AS dept_name, COUNT(e.[id]) AS emp_count+FROM [company].[departments] d+LEFT JOIN [company].[employees] e ON d.[id] = e.[department_id]+GROUP BY d.[id], d.[name];+GO++-- Create dependent view+CREATE VIEW [company].[dept_summary] AS+SELECT+ dept_id,+ dept_name,+ emp_count,+ 0 AS avg_salary,+ 0 AS max_salary,+ 0 AS min_salary+FROM [company].[dept_employee_count];+GO++-- Create highly dependent view+CREATE VIEW [company].[dept_manager_summary] AS+SELECT+ ds.dept_id,+ ds.dept_name,+ ds.emp_count,+ ds.avg_salary,+ m.[name] AS manager_name+FROM [company].[dept_summary] ds+JOIN [company].[departments] d ON ds.dept_id = d.[id]+LEFT JOIN [company].[employees] m ON d.[manager_id] = m.[id];+GO++-- Create stored procedure using views+CREATE PROCEDURE [company].[GetDepartmentReport]+ @dept_name_pattern NVARCHAR(100)+AS+BEGIN+ SELECT * FROM [company].[dept_manager_summary]+ WHERE dept_name LIKE '%' + @dept_name_pattern + '%';+END;+`,+ description: "Self-referencing foreign keys and complex view dependencies",+ },}for _, testCase := range testCases {diff --git a/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml b/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yamlindex 231c2d0ba8..b30cfc827e 100644--- a/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml+++ b/backend/plugin/schema/mssql/test-data/test_migration_safe_order.yaml@@ -65,17 +65,17 @@END;GOexpected: |+ CREATE TABLE [dbo].[users] (+ [id] int NOT NULL,+ [name] nvarchar(100) NULL,+ CONSTRAINT [PK_users_1] PRIMARY KEY ([id])+ );CREATE TABLE [dbo].[orders] ([id] int NOT NULL,[user_id] int NOT NULL,CONSTRAINT [PK_orders_2] PRIMARY KEY ([id]));CREATE INDEX [IX_orders_user_id] ON [dbo].[orders] ([user_id]);- CREATE TABLE [dbo].[users] (- [id] int NOT NULL,- [name] nvarchar(100) NULL,- CONSTRAINT [PK_users_1] PRIMARY KEY ([id])- );ALTER TABLE [dbo].[orders] ADD CONSTRAINT [FK_orders_users] FOREIGN KEY ([user_id]) REFERENCES [dbo].[users] ([id]) ON DELETE NO ACTION ON UPDATE NO ACTION;GOdiff --git a/backend/plugin/schema/mysql/generate_migration.go b/backend/plugin/schema/mysql/generate_migration.goindex 481797ae7b..4e41d29186 100644--- a/backend/plugin/schema/mysql/generate_migration.go+++ b/backend/plugin/schema/mysql/generate_migration.go@@ -167,15 +167,26 @@ 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 tables+ // Create tables (without foreign keys first)for _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionCreate {- if err := writeCreateTable(buf, tableDiff.TableName, tableDiff.NewTable); err != nil {+ if err := writeCreateTableWithoutForeignKeys(buf, tableDiff.TableName, tableDiff.NewTable); err != nil {return err}}}+ // Add foreign keys after all tables are created+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {+ for _, fk := range tableDiff.NewTable.ForeignKeys {+ if err := writeAddForeignKey(buf, tableDiff.TableName, fk); err != nil {+ return err+ }+ }+ }+ }+// Handle ALTER table operationsfor _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionAlter {@@ -378,7 +389,7 @@ func writeDropColumn(buf *strings.Builder, table, column string) error {return nil}-func writeCreateTable(buf *strings.Builder, tableName string, table *storepb.TableMetadata) error {+func writeCreateTableWithoutForeignKeys(buf *strings.Builder, tableName string, table *storepb.TableMetadata) error {_, _ = buf.WriteString("CREATE TABLE IF NOT EXISTS `")_, _ = buf.WriteString(tableName)_, _ = buf.WriteString("` (\n")@@ -503,12 +514,7 @@ func writeCreateTable(buf *strings.Builder, tableName string, table *storepb.Tab}}- // Create foreign keys separately- for _, fk := range table.ForeignKeys {- if err := writeAddForeignKey(buf, tableName, fk); err != nil {- return err- }- }+ // Note: Foreign keys are NOT created here - they will be added separatelyreturn nil}diff --git a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.goindex d99ba01fbf..bc4e65f9db 100644--- a/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mysql/generate_migration_testcontainer_test.go@@ -72,6 +72,35 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {migrationDDL stringdescription string}{+ {+ name: "create_tables_with_fk",+ 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,+ 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;+`,+ migrationDDL: `+DROP TABLE IF EXISTS posts;+DROP TABLE IF EXISTS users;`,+ description: "Create tables with foreign key constraints",+ },{name: "basic_table_operations",initialSchema: `@@ -820,8 +849,10 @@ END;cleanupDatabase(t, testDB)// Execute initial schema- if err := executeStatements(testDB, tc.initialSchema); err != nil {- t.Fatalf("Failed to execute initial schema: %v", err)+ if strings.TrimSpace(tc.initialSchema) != "" {+ if err := executeStatements(testDB, tc.initialSchema); err != nil {+ t.Fatalf("Failed to execute initial schema: %v", err)+ }}schemaA, err := getSyncMetadataForGenerateMigration(ctx, host, portInt, "root", "test123", "testdb")diff --git a/backend/plugin/schema/oracle/generate_migration_testcontainer_test.go b/backend/plugin/schema/oracle/generate_migration_testcontainer_test.goindex 5b40f65039..103aa38bd5 100644--- a/backend/plugin/schema/oracle/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/oracle/generate_migration_testcontainer_test.go@@ -89,6 +89,35 @@ func TestGenerateMigrationWithTestcontainer(t *testing.T) {migrationDDL stringdescription string}{+ {+ name: "create_tables_with_fk",+ initialSchema: `+CREATE TABLE USERS (+ ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,+ USERNAME VARCHAR2(50) NOT NULL,+ EMAIL VARCHAR2(100) NOT NULL,+ CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++CREATE UNIQUE INDEX UK_EMAIL ON USERS(EMAIL);+CREATE INDEX IDX_USERNAME ON USERS(USERNAME);++CREATE TABLE POSTS (+ ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,+ USER_ID NUMBER NOT NULL,+ TITLE VARCHAR2(200) NOT NULL,+ CONTENT CLOB,+ PUBLISHED_AT TIMESTAMP,+ CONSTRAINT FK_USER FOREIGN KEY (USER_ID) REFERENCES USERS(ID) ON DELETE CASCADE+);++CREATE INDEX IDX_USER_ID ON POSTS(USER_ID);+`,+ migrationDDL: `+DROP TABLE POSTS CASCADE CONSTRAINTS;+DROP TABLE USERS CASCADE CONSTRAINTS;`,+ description: "Create tables with foreign key constraints",+ },{name: "basic_table_operations",initialSchema: `diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.goindex e66220fa38..ab3a2939df 100644--- a/backend/plugin/schema/pg/generate_migration.go+++ b/backend/plugin/schema/pg/generate_migration.go@@ -620,6 +620,15 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}+ // Set sequence ownership after all tables are created+ for _, seqDiff := range diff.SequenceChanges {+ if seqDiff.Action == schema.MetadataDiffActionCreate && seqDiff.NewSequence.OwnerTable != "" && seqDiff.NewSequence.OwnerColumn != "" {+ if err := writeMigrationSequenceOwnership(buf, seqDiff.SchemaName, seqDiff.NewSequence); err != nil {+ return err+ }+ }+ }+// Add foreign keysfor _, tableDiff := range tableMap {if tableDiff.NewTable != nil {@@ -658,6 +667,15 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}+ // Set sequence ownership after all tables are created+ for _, seqDiff := range diff.SequenceChanges {+ if seqDiff.Action == schema.MetadataDiffActionCreate && seqDiff.NewSequence.OwnerTable != "" && seqDiff.NewSequence.OwnerColumn != "" {+ if err := writeMigrationSequenceOwnership(buf, seqDiff.SchemaName, seqDiff.NewSequence); err != nil {+ return err+ }+ }+ }+// Add foreign keys after all tables are createdfor _, tableDiff := range tableMap {if tableDiff.NewTable != nil {@@ -1239,6 +1257,23 @@ func writeMigrationCreateSequence(out *strings.Builder, schema string, seq *storreturn nil}+// writeMigrationSequenceOwnership writes an ALTER SEQUENCE OWNED BY statement+func writeMigrationSequenceOwnership(out *strings.Builder, schema string, seq *storepb.SequenceMetadata) error {+ _, _ = out.WriteString(`ALTER SEQUENCE "`)+ _, _ = out.WriteString(schema)+ _, _ = out.WriteString(`"."`)+ _, _ = out.WriteString(seq.Name)+ _, _ = out.WriteString(`" OWNED BY "`)+ _, _ = out.WriteString(schema)+ _, _ = out.WriteString(`"."`)+ _, _ = out.WriteString(seq.OwnerTable)+ _, _ = out.WriteString(`"."`)+ _, _ = out.WriteString(seq.OwnerColumn)+ _, _ = out.WriteString(`";`)+ _, _ = out.WriteString("\n")+ return nil+}+// writeView writes a CREATE VIEW statementfunc writeMigrationView(out *strings.Builder, schema string, view *storepb.ViewMetadata) error {_, _ = out.WriteString(`CREATE VIEW "`)diff --git a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go b/backend/plugin/schema/pg/generate_migration_testcontainer_test.goindex 48ff79349b..90cbad17fc 100644--- a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go@@ -512,6 +512,246 @@ $$ LANGUAGE plpgsql;`,description: "Mixed operations: CREATE, ALTER, DROP with complex dependencies",},+ {+ name: "create_tables_with_fk",+ initialSchema: `+CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL,+ email VARCHAR(100) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++CREATE UNIQUE INDEX uk_email ON users(email);+CREATE INDEX idx_username ON users(username);++CREATE TABLE posts (+ id SERIAL PRIMARY KEY,+ user_id INTEGER NOT NULL,+ title VARCHAR(200) NOT NULL,+ content TEXT,+ published_at TIMESTAMP,+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+);++CREATE INDEX idx_user_id ON posts(user_id);+`,+ migrationDDL: `+DROP TABLE IF EXISTS posts;+DROP TABLE IF EXISTS users;`,+ description: "Create tables with foreign key constraints",+ },+ {+ name: "multiple_foreign_keys",+ initialSchema: `+CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL,+ email VARCHAR(100) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++CREATE UNIQUE INDEX uk_email ON users(email);+CREATE INDEX idx_username ON users(username);++CREATE TABLE posts (+ id SERIAL PRIMARY KEY,+ user_id INTEGER NOT NULL,+ title VARCHAR(200) NOT NULL,+ content TEXT,+ published_at TIMESTAMP,+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+);++CREATE INDEX idx_user_id ON posts(user_id);+`,+ migrationDDL: `+-- Add new column+ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;++-- Create new table with multiple foreign keys+CREATE TABLE comments (+ id SERIAL PRIMARY KEY,+ post_id INTEGER NOT NULL,+ user_id INTEGER NOT NULL,+ content TEXT NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ 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+);++CREATE INDEX idx_post_user ON comments(post_id, user_id);++-- Add new index+CREATE INDEX idx_email_active ON users(email, is_active);++-- Add check constraint+ALTER TABLE posts ADD CONSTRAINT chk_title_length CHECK (LENGTH(title) > 0);+`,+ description: "Tables with multiple foreign key constraints",+ },+ {+ name: "drop_and_recreate_fk_constraints",+ initialSchema: `+CREATE TABLE authors (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ email VARCHAR(100)+);++CREATE UNIQUE INDEX uk_email ON authors(email);++CREATE TABLE books (+ id SERIAL PRIMARY KEY,+ title VARCHAR(200) NOT NULL,+ author_id INTEGER NOT NULL,+ isbn VARCHAR(20),+ published_year INTEGER,+ price DECIMAL(8, 2),+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),+ CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),+ CONSTRAINT chk_price_positive CHECK (price > 0)+);++CREATE UNIQUE INDEX uk_isbn ON books(isbn);+CREATE INDEX idx_author ON books(author_id);+CREATE INDEX idx_year ON books(published_year);+`,+ migrationDDL: `+-- Drop and recreate foreign key with different options+ALTER TABLE books DROP CONSTRAINT fk_author;+ALTER TABLE books ADD CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE;++-- Drop and modify check constraints+ALTER TABLE books DROP CONSTRAINT chk_year_valid;+ALTER TABLE books ADD CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030);++-- Add new constraints+ALTER TABLE books ADD CONSTRAINT chk_title_length CHECK (LENGTH(title) >= 3);+`,+ description: "Drop and recreate foreign key constraints with different options",+ },+ {+ name: "self_referencing_foreign_keys",+ initialSchema: `+CREATE TABLE departments (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ manager_id INTEGER+);++CREATE TABLE employees (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ department_id INTEGER,+ salary DECIMAL(10, 2),+ hire_date DATE,+ CONSTRAINT fk_dept FOREIGN KEY (department_id) REFERENCES departments(id)+);++CREATE INDEX idx_dept ON employees(department_id);++-- Add self-referencing foreign key+ALTER TABLE departments ADD CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id);+`,+ migrationDDL: `+-- Create base view+CREATE VIEW dept_employee_count AS+SELECT d.id AS dept_id, d.name AS dept_name, COUNT(e.id) AS emp_count+FROM departments d+LEFT JOIN employees e ON d.id = e.department_id+GROUP BY d.id, d.name;++-- Create dependent view+CREATE VIEW dept_summary AS+SELECT+ dept_id,+ dept_name,+ emp_count,+ 0 AS avg_salary,+ 0 AS max_salary,+ 0 AS min_salary+FROM dept_employee_count;++-- Create highly dependent view+CREATE VIEW dept_manager_summary AS+SELECT+ ds.dept_id,+ ds.dept_name,+ ds.emp_count,+ ds.avg_salary,+ m.name AS manager_name+FROM dept_summary ds+JOIN departments d ON ds.dept_id = d.id+LEFT JOIN employees m ON d.manager_id = m.id;++-- Create function using views+CREATE OR REPLACE FUNCTION get_department_report(dept_name_pattern VARCHAR)+RETURNS TABLE(dept_id INTEGER, dept_name VARCHAR, emp_count BIGINT, avg_salary INTEGER, manager_name VARCHAR) AS $$+BEGIN+ RETURN QUERY+ SELECT * FROM dept_manager_summary+ WHERE dept_name LIKE '%' || dept_name_pattern || '%';+END;+$$ LANGUAGE plpgsql;+`,+ description: "Self-referencing foreign keys and complex view dependencies",+ },+ {+ name: "circular_foreign_key_dependencies",+ initialSchema: `+CREATE TABLE customers (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ preferred_order_id INTEGER+);++CREATE TABLE orders (+ id SERIAL PRIMARY KEY,+ customer_id INTEGER NOT NULL,+ order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ total_amount DECIMAL(10, 2)+);+`,+ migrationDDL: `+-- Create circular foreign key dependencies+ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;+ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;++-- Add more tables with complex relationships+CREATE TABLE order_items (+ id SERIAL PRIMARY KEY,+ order_id INTEGER NOT NULL,+ product_name VARCHAR(100) NOT NULL,+ quantity INTEGER NOT NULL,+ unit_price DECIMAL(10, 2) NOT NULL,+ CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE+);++CREATE INDEX idx_order ON order_items(order_id);++-- Create trigger to update order total+CREATE OR REPLACE FUNCTION update_order_total()+RETURNS TRIGGER AS $$+BEGIN+ UPDATE orders+ SET total_amount = (+ SELECT SUM(quantity * unit_price)+ FROM order_items+ WHERE order_id = NEW.order_id+ )+ WHERE id = NEW.order_id;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER trg_update_order_total+AFTER INSERT OR UPDATE ON order_items+FOR EACH ROW+EXECUTE FUNCTION update_order_total();+`,+ description: "Circular foreign key dependencies and triggers",+ },}for _, tc := range testCases {diff --git a/backend/plugin/schema/tidb/generate_migration.go b/backend/plugin/schema/tidb/generate_migration.goindex 754687f285..e401dc55b2 100644--- a/backend/plugin/schema/tidb/generate_migration.go+++ b/backend/plugin/schema/tidb/generate_migration.go@@ -166,15 +166,26 @@ 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 tables+ // Create tables (without foreign keys first)for _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionCreate {- if err := writeCreateTable(buf, tableDiff.TableName, tableDiff.NewTable); err != nil {+ if err := writeCreateTableWithoutForeignKeys(buf, tableDiff.TableName, tableDiff.NewTable); err != nil {return err}}}+ // Add foreign keys after all tables are created+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionCreate && tableDiff.NewTable != nil {+ for _, fk := range tableDiff.NewTable.ForeignKeys {+ if err := writeAddForeignKey(buf, tableDiff.TableName, fk); err != nil {+ return err+ }+ }+ }+ }+// Handle ALTER table operationsfor _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionAlter {@@ -377,7 +388,7 @@ func writeDropColumn(buf *strings.Builder, table, column string) error {return nil}-func writeCreateTable(buf *strings.Builder, tableName string, table *storepb.TableMetadata) error {+func writeCreateTableWithoutForeignKeys(buf *strings.Builder, tableName string, table *storepb.TableMetadata) error {_, _ = buf.WriteString("CREATE TABLE IF NOT EXISTS `")_, _ = buf.WriteString(tableName)_, _ = buf.WriteString("` (\n")@@ -527,12 +538,7 @@ func writeCreateTable(buf *strings.Builder, tableName string, table *storepb.Tab}}- // Create foreign keys separately- for _, fk := range table.ForeignKeys {- if err := writeAddForeignKey(buf, tableName, fk); err != nil {- return err- }- }+ // Note: Foreign keys are NOT created here - they will be added separatelyreturn nil}diff --git a/backend/plugin/schema/tidb/generate_migration_testcontainer_test.go b/backend/plugin/schema/tidb/generate_migration_testcontainer_test.goindex ae66d66a87..6cf926ab0b 100644--- a/backend/plugin/schema/tidb/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/tidb/generate_migration_testcontainer_test.go@@ -351,6 +351,165 @@ ALTER TABLE sales_data ADD CONSTRAINT chk_amount_positive CHECK (amount > 0);`,description: "Operations on partitioned tables",},+ // Note: TiDB added foreign key support in v6.6.0 (experimental) and v7.5.0 (GA)+ // These tests verify that our migration generation handles foreign keys correctly+ {+ name: "create_tables_with_fk",+ 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,+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email),+ INDEX idx_username (username)+);++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+);+`,+ migrationDDL: `+DROP TABLE IF EXISTS posts;+DROP TABLE IF EXISTS users;`,+ description: "Create tables with foreign key constraints",+ },+ {+ name: "multiple_foreign_keys",+ 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,+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email),+ INDEX idx_username (username)+);++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+);+`,+ migrationDDL: `+-- Add new column+ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;++-- Create new table with multiple foreign keys+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+);++-- Add new index+CREATE INDEX idx_email_active ON users(email, is_active);++-- Add check constraint (TiDB supports check constraints)+ALTER TABLE posts ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) > 0);+`,+ description: "Tables with multiple foreign key constraints",+ },+ {+ name: "drop_and_recreate_fk_constraints",+ initialSchema: `+CREATE TABLE authors (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ email VARCHAR(100),+ PRIMARY KEY (id),+ UNIQUE KEY uk_email (email)+);++CREATE TABLE books (+ id INT NOT NULL AUTO_INCREMENT,+ title VARCHAR(200) NOT NULL,+ author_id INT NOT NULL,+ isbn VARCHAR(20),+ published_year INT,+ price DECIMAL(8, 2),+ PRIMARY KEY (id),+ UNIQUE KEY uk_isbn (isbn),+ INDEX idx_author (author_id),+ INDEX idx_year (published_year),+ CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id),+ CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100),+ CONSTRAINT chk_price_positive CHECK (price > 0)+);+`,+ migrationDDL: `+-- Drop and recreate foreign key with different options+ALTER TABLE books DROP FOREIGN KEY fk_author;+ALTER TABLE books ADD CONSTRAINT fk_author_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE;++-- Drop and modify check constraints+ALTER TABLE books DROP CHECK chk_year_valid;+ALTER TABLE books ADD CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030);++-- Add new constraints+ALTER TABLE books ADD CONSTRAINT chk_title_length CHECK (CHAR_LENGTH(title) >= 3);+`,+ description: "Drop and recreate foreign key constraints with different options",+ },+ {+ name: "circular_foreign_key_dependencies",+ initialSchema: `+CREATE TABLE customers (+ id INT NOT NULL AUTO_INCREMENT,+ name VARCHAR(100) NOT NULL,+ preferred_order_id INT,+ PRIMARY KEY (id)+);++CREATE TABLE orders (+ id INT NOT NULL AUTO_INCREMENT,+ customer_id INT NOT NULL,+ order_date DATETIME DEFAULT CURRENT_TIMESTAMP,+ total_amount DECIMAL(10, 2),+ PRIMARY KEY (id)+);+`,+ migrationDDL: `+-- Create circular foreign key dependencies+-- Note: Circular FKs might have limitations in TiDB+ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;+ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE;++-- Add more tables with complex relationships+CREATE TABLE order_items (+ id INT NOT NULL AUTO_INCREMENT,+ order_id INT NOT NULL,+ product_name VARCHAR(100) NOT NULL,+ quantity INT NOT NULL,+ unit_price DECIMAL(10, 2) NOT NULL,+ PRIMARY KEY (id),+ INDEX idx_order (order_id),+ CONSTRAINT fk_order_item FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE+);+`,+ description: "Circular foreign key dependencies",+ },}for _, tc := range testCases {