Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: more cases for mssql (#16669)
rebelicea0a88f884876
diff --git a/backend/plugin/schema/mssql/generate_migration.go b/backend/plugin/schema/mssql/generate_migration.goindex 4281e0e485..61b1abf3a6 100644--- a/backend/plugin/schema/mssql/generate_migration.go+++ b/backend/plugin/schema/mssql/generate_migration.go@@ -678,35 +678,45 @@ func generateAlterTable(tableDiff *schema.TableDiff) string {func generateColumnDefinition(column *storepb.ColumnMetadata) string {var buf strings.Builder-_, _ = buf.WriteString("[")_, _ = buf.WriteString(column.Name)_, _ = 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(")")- }+ // Check if this is a computed column by examining the type field+ isComputedColumn := strings.Contains(column.Type, " AS (") || strings.HasPrefix(column.Type, "AS (")- // Add nullability- if column.Nullable {- _, _ = buf.WriteString(" NULL")+ if isComputedColumn {+ // For computed columns, just use the type as-is (it contains the AS expression)+ _, _ = buf.WriteString(column.Type)+ // Note: Computed columns don't have explicit nullability, IDENTITY, or defaults+ // unless they are PERSISTED, which would be included in the type definition} else {- _, _ = buf.WriteString(" NOT NULL")- }+ // Regular column: add type, identity, nullability, and default+ _, _ = buf.WriteString(column.Type)- // Add default value if present- if column.GetDefaultExpression() != "" {- _, _ = buf.WriteString(" DEFAULT ")- _, _ = buf.WriteString(column.GetDefaultExpression())- } else if column.GetDefault() != "" {- _, _ = buf.WriteString(" DEFAULT ")- _, _ = buf.WriteString(column.GetDefault())- }+ // Add IDENTITY if applicable+ if column.IsIdentity {+ _, _ = buf.WriteString(" IDENTITY(")+ _, _ = buf.WriteString(fmt.Sprintf("%d,%d", column.IdentitySeed, column.IdentityIncrement))+ _, _ = buf.WriteString(")")+ }+ // Add nullability+ if column.Nullable {+ _, _ = buf.WriteString(" NULL")+ } else {+ _, _ = buf.WriteString(" NOT NULL")+ }++ // Add default value if present+ if column.GetDefaultExpression() != "" {+ _, _ = buf.WriteString(" DEFAULT ")+ _, _ = buf.WriteString(column.GetDefaultExpression())+ } else if column.GetDefault() != "" {+ _, _ = buf.WriteString(" DEFAULT ")+ _, _ = buf.WriteString(column.GetDefault())+ }+ }return buf.String()}diff --git a/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go b/backend/plugin/schema/mssql/generate_migration_testcontainer_test.goindex 5bb10f9c13..27b56fb3c9 100644--- a/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/mssql/generate_migration_testcontainer_test.go@@ -272,9 +272,9 @@ CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);--- Add filtered index+-- Add filtered index (using deterministic date)CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name])-WHERE [timestamp] >= DATEADD(DAY, -30, GETDATE());+WHERE [timestamp] >= '2023-01-01';-- Add computed column firstALTER TABLE [perf].[events] ADD [event_month] AS DATEPART(MONTH, [timestamp]);@@ -458,44 +458,6 @@ CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_wit`,description: "Computed columns with indexes",},- {- name: "temporal_tables",- initialSchema: `-CREATE SCHEMA [tracking];-GO--CREATE TABLE [tracking].[products] (- [id] INT IDENTITY(1,1) PRIMARY KEY,- [name] NVARCHAR(100) NOT NULL,- [price] DECIMAL(10,2) NOT NULL,- [last_modified] DATETIME2-);-`,- migrationDDL: `--- Add columns and period definition in single statement-ALTER TABLE [tracking].[products] ADD- [valid_from] DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,- [valid_to] DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,- PERIOD FOR SYSTEM_TIME ([valid_from], [valid_to]);---- Create history table-CREATE TABLE [tracking].[products_history] (- [id] INT NOT NULL,- [name] NVARCHAR(100) NOT NULL,- [price] DECIMAL(10,2) NOT NULL,- [last_modified] DATETIME2,- [valid_from] DATETIME2 NOT NULL,- [valid_to] DATETIME2 NOT NULL-);---- Create clustered index on history table-CREATE CLUSTERED INDEX [idx_products_history_period] ON [tracking].[products_history] ([valid_to], [valid_from]);---- Enable system versioning-ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [tracking].[products_history]));-`,- description: "Temporal tables with system versioning",- },{name: "create_tables_with_fk",initialSchema: `@@ -1102,172 +1064,1186 @@ ALTER TABLE [edge].[test_defaults] ADD [json_config] NVARCHAR(MAX) DEFAULT N'{"e`,description: "Edge cases for default constraints including special characters, unicode, extreme values",},- }-- for _, testCase := range testCases {- t.Run(testCase.name, func(t *testing.T) {- // Step 1: Execute 5-step workflow- portInt, err := strconv.Atoi(port.Port())- require.NoError(t, err)- err = executeFiveStepWorkflow(ctx, host, portInt, testCase.initialSchema, testCase.migrationDDL)- require.NoError(t, err, "Failed 5-step workflow for test case: %s", testCase.description)- })- }-}+ {+ name: "reverse_basic_table_operations",+ initialSchema: `+CREATE SCHEMA [app];+GO-// executeFiveStepWorkflow implements the 5-step workflow:-// 1. Initialize database schema, get schema result A via syncDBSchema-// 2. Apply migration DDL, get schema result B via syncDBSchema-// 3. Generate rollback DDL via generate_migration-// 4. Execute rollback DDL, get schema result C via syncDBSchema-// 5. Compare schema results A and C to verify they are identical-func executeFiveStepWorkflow(ctx context.Context, host string, port int, initialSchema, migrationDDL string) error {- // Create driver instance- driverInstance := &mssqldb.Driver{}+CREATE TABLE [app].[users] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [username] NVARCHAR(50) NOT NULL,+ [email] NVARCHAR(100) NOT NULL,+ [created_at] DATETIME2,+ [status] NVARCHAR(20),+ CONSTRAINT [uk_users_email] UNIQUE ([email]),+ CONSTRAINT [ck_users_status] CHECK ([status] IN ('active', 'inactive', 'suspended'))+);- // Create connection config- config := db.ConnectionConfig{- DataSource: &storepb.DataSource{- Type: storepb.DataSourceType_ADMIN,- Username: "sa",- Host: host,- Port: strconv.Itoa(port),- Database: "master",- },- Password: "Test123!",- ConnectionContext: db.ConnectionContext{- DatabaseName: "master",- },- }+CREATE INDEX [idx_users_username] ON [app].[users] ([username]);- // Open connection- driver, err := driverInstance.Open(ctx, storepb.Engine_MSSQL, config)- if err != nil {- return errors.Wrap(err, "failed to connect to MSSQL")- }- defer driver.Close(ctx)+CREATE TABLE [app].[posts] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [user_id] INT NOT NULL,+ [title] NVARCHAR(200) NOT NULL,+ [content] NTEXT,+ [published_at] DATETIME2,+ CONSTRAINT [fk_posts_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]) ON DELETE CASCADE+);- // Create test database with unique name- testDB := fmt.Sprintf("test_db_%d_%d", time.Now().Unix(), time.Now().UnixNano()%1000000)- if _, err := driver.Execute(ctx, fmt.Sprintf("CREATE DATABASE [%s]", testDB), db.ExecuteOptions{CreateDatabase: true}); err != nil {- return errors.Wrap(err, "failed to create test database")- }- defer func() {- // Clean up test database - reconnect to master first- driver.Close(ctx)- config.DataSource.Database = "master"- config.ConnectionContext.DatabaseName = "master"- cleanupDriver, err := driverInstance.Open(ctx, storepb.Engine_MSSQL, config)- if err == nil {- // Set the database to single user mode to close any open connections- _, _ = cleanupDriver.Execute(ctx, fmt.Sprintf("ALTER DATABASE [%s] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", testDB), db.ExecuteOptions{CreateDatabase: true})- // Drop the database using CreateDatabase option to avoid transaction issues- if _, err := cleanupDriver.Execute(ctx, fmt.Sprintf("DROP DATABASE [%s]", testDB), db.ExecuteOptions{CreateDatabase: true}); err != nil {- // Log but don't fail if cleanup fails- fmt.Printf("Warning: failed to clean up test database %s: %v\n", testDB, err)- }- cleanupDriver.Close(ctx)- }- }()+CREATE INDEX [idx_posts_user_id] ON [app].[posts] ([user_id]);- // Reconnect to test database- driver.Close(ctx)- config.DataSource.Database = testDB- config.ConnectionContext.DatabaseName = testDB- driver, err = driverInstance.Open(ctx, storepb.Engine_MSSQL, config)- if err != nil {- return errors.Wrap(err, "failed to reconnect to test database")- }- defer driver.Close(ctx)+CREATE TABLE [app].[comments] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [post_id] INT NOT NULL,+ [user_id] INT NOT NULL,+ [content] NTEXT NOT NULL,+ [created_at] DATETIME2,+ CONSTRAINT [fk_comments_post] FOREIGN KEY ([post_id]) REFERENCES [app].[posts]([id]) ON DELETE CASCADE,+ CONSTRAINT [fk_comments_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id])+);- // Step 1: Initialize database schema and get schema result A- if err := executeSQL(ctx, driver, initialSchema); err != nil {- return errors.Wrap(err, "failed to execute initial schema")- }+CREATE INDEX [idx_comments_post_id] ON [app].[comments] ([post_id]);+`,+ migrationDDL: `+-- Drop index+DROP INDEX [idx_comments_post_id] ON [app].[comments];- mssqlDriver, ok := driver.(*mssqldb.Driver)- if !ok {- return errors.New("failed to cast to mssqldb.Driver")- }+-- Drop check constraint+ALTER TABLE [app].[users] DROP CONSTRAINT [ck_users_status];- schemaA, err := mssqlDriver.SyncDBSchema(ctx)- if err != nil {- return errors.Wrap(err, "failed to sync schema A")- }+-- Drop table (must drop in correct order due to foreign keys)+DROP TABLE [app].[comments];- // Step 2: Apply migration DDL and get schema result B- if err := executeSQL(ctx, driver, migrationDDL); err != nil {- return errors.Wrap(err, "failed to execute migration DDL")- }+-- Drop column+ALTER TABLE [app].[users] DROP COLUMN [status];+`,+ description: "Reverse of basic table operations - dropping column, table, index, and constraint",+ },+ {+ name: "reverse_schema_operations",+ initialSchema: `+CREATE SCHEMA [sales];+GO- schemaB, err := mssqlDriver.SyncDBSchema(ctx)- if err != nil {- return errors.Wrap(err, "failed to sync schema B")- }+CREATE SCHEMA [inventory];+GO- // Debug: Print what tables are in each schema- fmt.Printf("Schema A contents:\n")- for _, s := range schemaA.Schemas {- fmt.Printf(" Schema [%s]: %d tables\n", s.Name, len(s.Tables))- for _, t := range s.Tables {- fmt.Printf(" - [%s].[%s]\n", s.Name, t.Name)- }- }- fmt.Printf("Schema B contents:\n")- for _, s := range schemaB.Schemas {- fmt.Printf(" Schema [%s]: %d tables\n", s.Name, len(s.Tables))- for _, t := range s.Tables {- fmt.Printf(" - [%s].[%s]\n", s.Name, t.Name)- }- }+CREATE TABLE [sales].[customers] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [email] NVARCHAR(100)+);- // Step 3: Generate rollback DDL using generate_migration- // Convert to model schemas for diff- dbSchemaA := model.NewDatabaseSchema(schemaA, nil, nil, storepb.Engine_MSSQL, false)- dbSchemaB := model.NewDatabaseSchema(schemaB, nil, nil, storepb.Engine_MSSQL, false)+CREATE TABLE [sales].[orders] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [customer_id] INT NOT NULL,+ [order_date] DATE,+ [total] DECIMAL(10,2),+ [product_id] INT,+ CONSTRAINT [fk_orders_customer] FOREIGN KEY ([customer_id]) REFERENCES [sales].[customers]([id])+);- // Get diff from B to A (to generate rollback)- diff, err := schema.GetDatabaseSchemaDiff(dbSchemaB, dbSchemaA)- if err != nil {- return errors.Wrap(err, "failed to generate diff")- }+CREATE TABLE [inventory].[products] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [price] DECIMAL(10,2) NOT NULL,+ [category_id] INT,+ CONSTRAINT [ck_products_price] CHECK ([price] > 0)+);- // Debug: Print what changes are detected- fmt.Printf("Schema changes detected:\n")- fmt.Printf("- Table changes: %d\n", len(diff.TableChanges))- for i, tc := range diff.TableChanges {- fmt.Printf(" %d. %s [%s].[%s]\n", i+1, tc.Action, tc.SchemaName, tc.TableName)- }- fmt.Printf("- Schema changes: %d\n", len(diff.SchemaChanges))- for i, sc := range diff.SchemaChanges {- fmt.Printf(" %d. %s [%s]\n", i+1, sc.Action, sc.SchemaName)- }+ALTER TABLE [sales].[orders] ADD CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [inventory].[products]([id]);+`,+ migrationDDL: `+-- Drop foreign key referencing table in different schema+ALTER TABLE [sales].[orders] DROP CONSTRAINT [fk_orders_product];- rollbackDDL, err := schema.GenerateMigration(storepb.Engine_MSSQL, diff)- if err != nil {- return errors.Wrap(err, "failed to generate rollback migration")- }+-- Drop column referencing another schema+ALTER TABLE [sales].[orders] DROP COLUMN [product_id];- // Debug: Print the generated rollback DDL- fmt.Printf("Generated rollback DDL:\n%s\n", rollbackDDL)+-- Drop table in inventory schema+DROP TABLE [inventory].[products];- // Only proceed if there's actual rollback DDL to execute- if strings.TrimSpace(rollbackDDL) == "" {- // No rollback needed, schemas should already be identical- return nil- }+-- Drop the inventory schema+DROP SCHEMA [inventory];+`,+ description: "Reverse of schema operations - dropping cross-schema foreign key, table, and schema",+ },+ {+ name: "reverse_view_operations",+ initialSchema: `+CREATE SCHEMA [reporting];+GO- // Step 4: Execute rollback DDL and get schema result C- if err := executeSQL(ctx, driver, rollbackDDL); err != nil {- return errors.Wrapf(err, "failed to execute rollback DDL: %s", rollbackDDL)- }+CREATE TABLE [reporting].[sales_data] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [product_name] NVARCHAR(100) NOT NULL,+ [quantity] INT NOT NULL,+ [price] DECIMAL(10,2) NOT NULL,+ [sale_date] DATE+);- schemaC, err := mssqlDriver.SyncDBSchema(ctx)- if err != nil {- return errors.Wrap(err, "failed to sync schema C")- }+CREATE TABLE [reporting].[customers] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [region] NVARCHAR(50)+);+GO- // Step 5: Compare schema results A and C+CREATE VIEW [reporting].[product_summary] AS+SELECT+ [product_name],+ COUNT(*) as [sale_count],+ SUM([quantity]) as [total_quantity],+ AVG([price]) as [avg_price]+FROM [reporting].[sales_data]+GROUP BY [product_name];+GO++CREATE VIEW [reporting].[top_products] AS+SELECT TOP 10+ [product_name],+ [total_quantity]+FROM [reporting].[product_summary]+WHERE [total_quantity] > 100+ORDER BY [total_quantity] DESC;+GO+`,+ migrationDDL: `+-- Drop dependent view first+DROP VIEW [reporting].[top_products];+GO++-- Drop base view+DROP VIEW [reporting].[product_summary];+GO+`,+ description: "Reverse of view operations - dropping views in correct dependency order",+ },+ {+ name: "reverse_function_and_procedure_operations",+ initialSchema: `+CREATE SCHEMA [calc];+GO++CREATE TABLE [calc].[numbers] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [value] INT NOT NULL,+ [category] NVARCHAR(20)+);+GO++CREATE FUNCTION [calc].[square](@input INT)+RETURNS INT+AS+BEGIN+ RETURN @input * @input;+END;+GO++CREATE FUNCTION [calc].[get_numbers_by_category](@category NVARCHAR(20))+RETURNS TABLE+AS+RETURN (+ SELECT [id], [value], [category]+ FROM [calc].[numbers]+ WHERE [category] = @category+);+GO++CREATE PROCEDURE [calc].[add_number]+ @value INT,+ @category NVARCHAR(20)+AS+BEGIN+ INSERT INTO [calc].[numbers] ([value], [category])+ VALUES (@value, @category);+END;+GO+`,+ migrationDDL: `+-- Drop stored procedure+DROP PROCEDURE [calc].[add_number];+GO++-- Drop table-valued function+DROP FUNCTION [calc].[get_numbers_by_category];+GO++-- Drop scalar function+DROP FUNCTION [calc].[square];+GO+`,+ description: "Reverse of function and procedure operations - dropping procedures and functions",+ },+ {+ name: "reverse_index_operations",+ initialSchema: `+CREATE SCHEMA [perf];+GO++CREATE TABLE [perf].[events] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [event_name] NVARCHAR(100) NOT NULL,+ [event_data] NVARCHAR(MAX),+ [timestamp] DATETIME2,+ [user_id] INT,+ [category] NVARCHAR(50),+ [event_month] AS DATEPART(MONTH, [timestamp])+);++CREATE INDEX [idx_events_timestamp] ON [perf].[events] ([timestamp]);+CREATE INDEX [idx_events_user_category] ON [perf].[events] ([user_id], [category]);+CREATE UNIQUE INDEX [idx_events_name_timestamp] ON [perf].[events] ([event_name], [timestamp]);++CREATE INDEX [idx_events_recent] ON [perf].[events] ([event_name])+WHERE [timestamp] >= '2023-01-01';++CREATE INDEX [idx_events_month] ON [perf].[events] ([event_month]);+`,+ migrationDDL: `+-- Drop index on computed column+DROP INDEX [idx_events_month] ON [perf].[events];++-- Drop computed column+ALTER TABLE [perf].[events] DROP COLUMN [event_month];++-- Drop filtered index+DROP INDEX [idx_events_recent] ON [perf].[events];++-- Drop unique index+DROP INDEX [idx_events_name_timestamp] ON [perf].[events];++-- Drop composite index+DROP INDEX [idx_events_user_category] ON [perf].[events];++-- Drop simple index+DROP INDEX [idx_events_timestamp] ON [perf].[events];+`,+ description: "Reverse of index operations - dropping various index types including filtered and computed column indexes",+ },+ {+ name: "reverse_complex_constraints",+ initialSchema: `+CREATE SCHEMA [finance];+GO++CREATE TABLE [finance].[accounts] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [account_number] NVARCHAR(20) NOT NULL,+ [balance] DECIMAL(15,2),+ [account_type] NVARCHAR(20) NOT NULL,+ [created_at] DATETIME2 DEFAULT GETDATE(),+ CONSTRAINT [ck_accounts_balance] CHECK ([balance] >= 0),+ CONSTRAINT [ck_accounts_type] CHECK ([account_type] IN ('CHECKING', 'SAVINGS', 'CREDIT')),+ CONSTRAINT [uk_accounts_number] UNIQUE ([account_number])+);++CREATE TABLE [finance].[transactions] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [account_id] INT NOT NULL,+ [amount] DECIMAL(15,2) NOT NULL,+ [transaction_type] NVARCHAR(20) NOT NULL,+ [transaction_date] DATETIME2,+ CONSTRAINT [fk_transactions_account] FOREIGN KEY ([account_id]) REFERENCES [finance].[accounts]([id]),+ CONSTRAINT [ck_transactions_amount] CHECK ([amount] != 0),+ CONSTRAINT [ck_transactions_type] CHECK ([transaction_type] IN ('DEBIT', 'CREDIT'))+);+`,+ migrationDDL: `+-- Drop table with foreign key and check constraints+DROP TABLE [finance].[transactions];++-- Drop unique constraint+ALTER TABLE [finance].[accounts] DROP CONSTRAINT [uk_accounts_number];++-- Drop check constraints+ALTER TABLE [finance].[accounts] DROP CONSTRAINT [ck_accounts_type];+ALTER TABLE [finance].[accounts] DROP CONSTRAINT [ck_accounts_balance];+`,+ description: "Reverse of complex constraints - dropping tables with foreign keys and removing constraints",+ },+ {+ name: "reverse_column_modifications",+ initialSchema: `+CREATE SCHEMA [hr];+GO++CREATE TABLE [hr].[departments] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [budget] DECIMAL(15,2)+);++CREATE TABLE [hr].[employees] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [first_name] NVARCHAR(50),+ [last_name] NVARCHAR(50),+ [email] NVARCHAR(100),+ [phone] VARCHAR(20),+ [hire_date] DATE,+ [salary] DECIMAL(10,2),+ [department_id] INT,+ [manager_id] INT,+ [status] NVARCHAR(20),+ CONSTRAINT [fk_employees_department] FOREIGN KEY ([department_id]) REFERENCES [hr].[departments]([id]),+ CONSTRAINT [fk_employees_manager] FOREIGN KEY ([manager_id]) REFERENCES [hr].[employees]([id]),+ CONSTRAINT [ck_employees_salary] CHECK ([salary] > 0),+ CONSTRAINT [ck_employees_status] CHECK ([status] IN ('ACTIVE', 'INACTIVE', 'TERMINATED'))+);+`,+ migrationDDL: `+-- Drop check constraints first+ALTER TABLE [hr].[employees] DROP CONSTRAINT [ck_employees_status];+ALTER TABLE [hr].[employees] DROP CONSTRAINT [ck_employees_salary];++-- Drop foreign key constraints before dropping columns+ALTER TABLE [hr].[employees] DROP CONSTRAINT [fk_employees_manager];+ALTER TABLE [hr].[employees] DROP CONSTRAINT [fk_employees_department];++-- Now safe to drop columns+ALTER TABLE [hr].[employees] DROP COLUMN [status];+ALTER TABLE [hr].[employees] DROP COLUMN [manager_id];+ALTER TABLE [hr].[employees] DROP COLUMN [department_id];++-- Finally drop department table+DROP TABLE [hr].[departments];+`,+ description: "Reverse of column modifications - dropping columns, constraints, and related tables",+ },+ {+ name: "reverse_multiple_schema_dependencies",+ initialSchema: `+CREATE SCHEMA [core];+GO+CREATE SCHEMA [app];+GO++CREATE TABLE [core].[users] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [username] NVARCHAR(50) NOT NULL,+ [email] NVARCHAR(100) NOT NULL+);++CREATE TABLE [core].[roles] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(50) NOT NULL+);++CREATE TABLE [core].[user_roles] (+ [user_id] INT NOT NULL,+ [role_id] INT NOT NULL,+ [assigned_at] DATETIME2,+ CONSTRAINT [pk_user_roles] PRIMARY KEY ([user_id], [role_id]),+ CONSTRAINT [fk_user_roles_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE,+ CONSTRAINT [fk_user_roles_role] FOREIGN KEY ([role_id]) REFERENCES [core].[roles]([id]) ON DELETE CASCADE+);++CREATE TABLE [app].[sessions] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [user_id] INT NOT NULL,+ [token] NVARCHAR(255) NOT NULL,+ [expires_at] DATETIME2 NOT NULL,+ CONSTRAINT [fk_sessions_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id]) ON DELETE CASCADE+);++CREATE TABLE [app].[audit_log] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [user_id] INT,+ [action] NVARCHAR(100) NOT NULL,+ [timestamp] DATETIME2,+ [details] NVARCHAR(MAX),+ CONSTRAINT [fk_audit_user] FOREIGN KEY ([user_id]) REFERENCES [core].[users]([id])+);+`,+ migrationDDL: `+-- Drop tables that reference core schema+DROP TABLE [app].[audit_log];+DROP TABLE [app].[sessions];++-- Drop junction table+DROP TABLE [core].[user_roles];+`,+ description: "Reverse of multiple schema dependencies - dropping cross-schema references",+ },+ {+ name: "reverse_computed_columns_and_triggers",+ initialSchema: `+CREATE SCHEMA [ecommerce];+GO++CREATE TABLE [ecommerce].[products] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [price] DECIMAL(10,2) NOT NULL,+ [tax_rate] DECIMAL(5,4),+ [price_with_tax] AS ([price] * (1 + [tax_rate])),+ [price_category] AS (+ CASE+ WHEN [price] < 10 THEN 'Budget'+ WHEN [price] < 100 THEN 'Standard'+ ELSE 'Premium'+ END+ )+);+GO++CREATE INDEX [idx_products_price_category] ON [ecommerce].[products] ([price_category]);+CREATE INDEX [idx_products_price_with_tax] ON [ecommerce].[products] ([price_with_tax]);++CREATE TABLE [ecommerce].[orders] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [product_id] INT NOT NULL,+ [quantity] INT NOT NULL,+ [unit_price] DECIMAL(10,2) NOT NULL,+ [total] DECIMAL(15,2),+ [order_date] DATETIME2,+ [computed_total] AS ([quantity] * [unit_price]),+ CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [ecommerce].[products]([id])+);+GO+`,+ migrationDDL: `+-- Drop table with computed column+DROP TABLE [ecommerce].[orders];+GO++-- Drop indexes on computed columns+DROP INDEX [idx_products_price_with_tax] ON [ecommerce].[products];+DROP INDEX [idx_products_price_category] ON [ecommerce].[products];++-- Drop computed columns+ALTER TABLE [ecommerce].[products] DROP COLUMN [price_category];+GO++ALTER TABLE [ecommerce].[products] DROP COLUMN [price_with_tax];+GO+`,+ description: "Reverse of computed columns - dropping indexes and computed columns",+ },+ {+ name: "reverse_temporal_tables",+ initialSchema: `+CREATE SCHEMA [tracking];+GO++CREATE TABLE [tracking].[products] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [price] DECIMAL(10,2) NOT NULL,+ [last_modified] DATETIME2,+ [valid_from] DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,+ [valid_to] DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,+ PERIOD FOR SYSTEM_TIME ([valid_from], [valid_to])+);++CREATE TABLE [tracking].[products_history] (+ [id] INT NOT NULL,+ [name] NVARCHAR(100) NOT NULL,+ [price] DECIMAL(10,2) NOT NULL,+ [last_modified] DATETIME2,+ [valid_from] DATETIME2 NOT NULL,+ [valid_to] DATETIME2 NOT NULL+);++CREATE CLUSTERED INDEX [idx_products_history_period] ON [tracking].[products_history] ([valid_to], [valid_from]);++ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [tracking].[products_history]));+`,+ migrationDDL: `+-- Disable system versioning first+ALTER TABLE [tracking].[products] SET (SYSTEM_VERSIONING = OFF);++-- Drop history table (and its index will be dropped automatically)+DROP TABLE [tracking].[products_history];++-- Drop period definition and system time columns+ALTER TABLE [tracking].[products] DROP PERIOD FOR SYSTEM_TIME;+ALTER TABLE [tracking].[products] DROP COLUMN [valid_to];+ALTER TABLE [tracking].[products] DROP COLUMN [valid_from];+`,+ description: "Reverse of temporal tables - disabling system versioning and dropping history",+ },+ {+ name: "reverse_table_and_column_comments",+ initialSchema: `+CREATE SCHEMA [app];+GO++CREATE TABLE [app].[users] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [username] NVARCHAR(50) NOT NULL,+ [email] NVARCHAR(100) NOT NULL,+ [created_at] DATETIME2,+ [status] NVARCHAR(20)+);++CREATE TABLE [app].[products] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [price] DECIMAL(10,2) NOT NULL,+ [category] NVARCHAR(50)+);++CREATE INDEX [idx_users_email] ON [app].[users] ([email]);+CREATE INDEX [idx_products_category] ON [app].[products] ([category]);++CREATE TABLE [app].[orders] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [user_id] INT NOT NULL,+ [product_id] INT NOT NULL,+ [quantity] INT NOT NULL,+ [order_date] DATETIME2,+ CONSTRAINT [fk_orders_user] FOREIGN KEY ([user_id]) REFERENCES [app].[users]([id]),+ CONSTRAINT [fk_orders_product] FOREIGN KEY ([product_id]) REFERENCES [app].[products]([id])+);+GO++-- Add table comments using extended properties+EXEC sp_addextendedproperty 'MS_Description', 'User accounts and profile information', 'SCHEMA', 'app', 'TABLE', 'users';+EXEC sp_addextendedproperty 'MS_Description', 'Product catalog with pricing information', 'SCHEMA', 'app', 'TABLE', 'products';+EXEC sp_addextendedproperty 'MS_Description', 'Customer orders tracking system', 'SCHEMA', 'app', 'TABLE', 'orders';+GO++-- Add column comments for users table+EXEC sp_addextendedproperty 'MS_Description', 'Unique identifier for each user', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';+EXEC sp_addextendedproperty 'MS_Description', 'Unique username for login authentication', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';+EXEC sp_addextendedproperty 'MS_Description', 'User email address for notifications', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';+EXEC sp_addextendedproperty 'MS_Description', 'Timestamp when the user account was created', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';+EXEC sp_addextendedproperty 'MS_Description', 'Current status: active, inactive, or suspended', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';+GO++-- Add column comments for products table+EXEC sp_addextendedproperty 'MS_Description', 'Unique product identifier', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';+EXEC sp_addextendedproperty 'MS_Description', 'Product display name', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';+EXEC sp_addextendedproperty 'MS_Description', 'Product price in USD', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';+EXEC sp_addextendedproperty 'MS_Description', 'Product category classification', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';+GO++-- Add comments to orders table+EXEC sp_addextendedproperty 'MS_Description', 'Unique order identifier', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';+EXEC sp_addextendedproperty 'MS_Description', 'Reference to the user who placed the order', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';+EXEC sp_addextendedproperty 'MS_Description', 'Reference to the ordered product', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';+EXEC sp_addextendedproperty 'MS_Description', 'Number of items ordered', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';+EXEC sp_addextendedproperty 'MS_Description', 'When the order was placed', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';+`,+ migrationDDL: `+-- Drop column comments from orders table+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'order_date';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'quantity';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'product_id';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'user_id';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders', 'COLUMN', 'id';+GO++-- Drop table comment from orders+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'orders';+GO++-- Drop the orders table+DROP TABLE [app].[orders];+GO++-- Drop column comments from products table+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'category';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'price';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'name';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products', 'COLUMN', 'id';+GO++-- Drop column comments from users table+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'status';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'created_at';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'email';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'username';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users', 'COLUMN', 'id';+GO++-- Drop table comments+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'products';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'app', 'TABLE', 'users';+`,+ description: "Reverse of table and column comments - dropping extended properties",+ },+ {+ name: "reverse_default_constraint_operations",+ initialSchema: `+CREATE SCHEMA [defaults];+GO++CREATE TABLE [defaults].[employees] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [email] NVARCHAR(100) NOT NULL,+ [hire_date] DATE NOT NULL DEFAULT GETDATE(),+ [status] NVARCHAR(20) NOT NULL CONSTRAINT [DF_employees_status_new] DEFAULT 'pending',+ [is_active] BIT NOT NULL DEFAULT 1,+ [salary] DECIMAL(10,2) DEFAULT 50000.00,+ [department_id] INT DEFAULT 1,+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),+ [updated_at] DATETIME2,+ [vacation_days] INT NOT NULL DEFAULT 15,+ [bonus_percentage] DECIMAL(5,2) DEFAULT (CASE WHEN MONTH(GETDATE()) = 12 THEN 10.0 ELSE 5.0 END)+);++CREATE TABLE [defaults].[products] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [name] NVARCHAR(100) NOT NULL,+ [price] DECIMAL(10,2) NOT NULL DEFAULT 0.00,+ [stock] INT NOT NULL DEFAULT 0,+ [is_available] BIT DEFAULT 1,+ [cost] DECIMAL(10,2) NOT NULL+);++CREATE TABLE [defaults].[orders] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [order_number] NVARCHAR(50) NOT NULL DEFAULT CONCAT('ORD-', YEAR(GETDATE()), '-', FORMAT(GETDATE(), 'MMdd')),+ [order_date] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),+ [status] NVARCHAR(20) NOT NULL DEFAULT 'pending',+ [total] DECIMAL(10,2) NOT NULL DEFAULT 0,+ [discount] DECIMAL(5,2) DEFAULT NULL,+ [is_paid] BIT NOT NULL DEFAULT 0,+ [notes] NVARCHAR(MAX) DEFAULT 'No notes'+);+`,+ migrationDDL: `+-- Drop orders table with all its defaults+DROP TABLE [defaults].[orders];+GO++-- Drop default constraint for bonus_percentage column+DECLARE @constraint_name NVARCHAR(128);+SELECT @constraint_name = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'defaults' AND t.name = 'employees' AND c.name = 'bonus_percentage';+IF @constraint_name IS NOT NULL+ EXEC('ALTER TABLE [defaults].[employees] DROP CONSTRAINT [' + @constraint_name + ']');+GO++-- Drop default constraint for vacation_days column+DECLARE @constraint_name2 NVARCHAR(128);+SELECT @constraint_name2 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'defaults' AND t.name = 'employees' AND c.name = 'vacation_days';+IF @constraint_name2 IS NOT NULL+ EXEC('ALTER TABLE [defaults].[employees] DROP CONSTRAINT [' + @constraint_name2 + ']');+GO++-- Now safe to drop columns+ALTER TABLE [defaults].[employees] DROP COLUMN [bonus_percentage];+ALTER TABLE [defaults].[employees] DROP COLUMN [vacation_days];++-- Remove default from status column (named constraint)+ALTER TABLE [defaults].[employees] DROP CONSTRAINT [DF_employees_status_new];++-- Drop cost column (which has no default)+ALTER TABLE [defaults].[products] DROP COLUMN [cost];+`,+ description: "Reverse of default constraint operations - dropping tables, columns with defaults, and default constraints",+ },+ {+ name: "reverse_complex_default_expressions",+ initialSchema: `+CREATE SCHEMA [complex];+GO++CREATE TABLE [complex].[audit_log] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [event_type] NVARCHAR(50) NOT NULL,+ [user_name] NVARCHAR(100) NOT NULL DEFAULT SYSTEM_USER,+ [event_time] DATETIME2 NOT NULL DEFAULT SYSDATETIME(),+ [ip_address] NVARCHAR(45),+ [session_id] UNIQUEIDENTIFIER DEFAULT NEWID(),+ [server_name] NVARCHAR(100) DEFAULT @@SERVERNAME,+ [database_name] NVARCHAR(100) DEFAULT DB_NAME(),+ [schema_name] NVARCHAR(100) DEFAULT SCHEMA_NAME()+);++CREATE TABLE [complex].[documents] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [title] NVARCHAR(200) NOT NULL,+ [content] NVARCHAR(MAX),+ [version] INT NOT NULL DEFAULT 1,+ [created_date] DATE DEFAULT CAST(GETDATE() AS DATE),+ [expiry_date] DATE DEFAULT DATEADD(YEAR, 1, CAST(GETDATE() AS DATE)),+ [document_code] NVARCHAR(50) DEFAULT CONCAT('DOC-', FORMAT(GETDATE(), 'yyyyMMdd'), '-', NEWID()),+ [priority] INT DEFAULT+ CASE+ WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 1+ WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 2+ ELSE 3+ END+);++CREATE TABLE [complex].[calculations] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [value1] DECIMAL(10,2) NOT NULL,+ [value2] DECIMAL(10,2) NOT NULL,+ [pi_value] DECIMAL(10,8) DEFAULT PI(),+ [random_value] FLOAT DEFAULT RAND(),+ [checksum_value] INT DEFAULT CHECKSUM(NEWID()),+ [created_at] DATETIME2 DEFAULT SYSDATETIME(),+ [created_offset] DATETIMEOFFSET DEFAULT SYSDATETIMEOFFSET()+);+`,+ migrationDDL: `+-- Drop table with function-based defaults+DROP TABLE [complex].[calculations];+GO++-- Drop default constraint for priority column+DECLARE @constraint_name NVARCHAR(128);+SELECT @constraint_name = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'complex' AND t.name = 'documents' AND c.name = 'priority';+IF @constraint_name IS NOT NULL+ EXEC('ALTER TABLE [complex].[documents] DROP CONSTRAINT [' + @constraint_name + ']');+GO++-- Drop default constraint for document_code column+DECLARE @constraint_name2 NVARCHAR(128);+SELECT @constraint_name2 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'complex' AND t.name = 'documents' AND c.name = 'document_code';+IF @constraint_name2 IS NOT NULL+ EXEC('ALTER TABLE [complex].[documents] DROP CONSTRAINT [' + @constraint_name2 + ']');+GO++-- Drop default constraint for schema_name column+DECLARE @constraint_name3 NVARCHAR(128);+SELECT @constraint_name3 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'complex' AND t.name = 'audit_log' AND c.name = 'schema_name';+IF @constraint_name3 IS NOT NULL+ EXEC('ALTER TABLE [complex].[audit_log] DROP CONSTRAINT [' + @constraint_name3 + ']');+GO++-- Drop default constraint for database_name column+DECLARE @constraint_name4 NVARCHAR(128);+SELECT @constraint_name4 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'complex' AND t.name = 'audit_log' AND c.name = 'database_name';+IF @constraint_name4 IS NOT NULL+ EXEC('ALTER TABLE [complex].[audit_log] DROP CONSTRAINT [' + @constraint_name4 + ']');+GO++-- Drop default constraint for server_name column+DECLARE @constraint_name5 NVARCHAR(128);+SELECT @constraint_name5 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'complex' AND t.name = 'audit_log' AND c.name = 'server_name';+IF @constraint_name5 IS NOT NULL+ EXEC('ALTER TABLE [complex].[audit_log] DROP CONSTRAINT [' + @constraint_name5 + ']');+GO++-- Now safe to drop columns+ALTER TABLE [complex].[documents] DROP COLUMN [priority];+ALTER TABLE [complex].[documents] DROP COLUMN [document_code];+ALTER TABLE [complex].[audit_log] DROP COLUMN [schema_name];+ALTER TABLE [complex].[audit_log] DROP COLUMN [database_name];+ALTER TABLE [complex].[audit_log] DROP COLUMN [server_name];+`,+ description: "Reverse of complex default expressions - dropping columns with system functions and conditional defaults",+ },+ {+ name: "reverse_comments_with_special_characters",+ initialSchema: `+CREATE SCHEMA [special];+GO++CREATE TABLE [special].[documents] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [title] NVARCHAR(200) NOT NULL,+ [content] NVARCHAR(MAX),+ [author] NVARCHAR(100),+ [created_date] DATETIME2,+ [metadata] NVARCHAR(500)+);++CREATE TABLE [special].[translations] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [document_id] INT NOT NULL,+ [lang_code] NVARCHAR(10) NOT NULL,+ [translated_title] NVARCHAR(200),+ [translated_content] NVARCHAR(MAX),+ CONSTRAINT [fk_translations_doc] FOREIGN KEY ([document_id]) REFERENCES [special].[documents]([id])+);++CREATE TABLE [special].[test_extreme] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [data] NVARCHAR(MAX)+);+GO++-- Add table comments with special characters and quotes+EXEC sp_addextendedproperty 'MS_Description', 'Document storage system - handles files, "metadata", & special chars: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'documents';+GO++-- Add multiline comment with special formatting+EXEC sp_addextendedproperty 'MS_Description',+'Translation table for international support:+- Supports Unicode characters: αβγδε, 中文, العربية, русский+- Handles quotes: "double quotes" and ''single quotes''+- Special symbols: @#$%^&*()_+-={}[]|\:";''<>?,./', 'SCHEMA', 'special', 'TABLE', 'translations';+GO++-- Column comments with various special cases+EXEC sp_addextendedproperty 'MS_Description', 'Primary key (auto-increment) - unique ID for each document', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';+EXEC sp_addextendedproperty 'MS_Description', 'Document title - may contain "quotes", ''apostrophes'', and symbols: @#$%', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';+GO++-- Multiline comment with technical details+EXEC sp_addextendedproperty 'MS_Description',+'Document content field:+ • Supports rich text formatting+ • HTML tags like <p>, <div>, <span>+ • Special characters: © ® ™ § ¶ † ‡ • ‰ ′ ″+ • Mathematical: ± × ÷ ≠ ≤ ≥ ∞ ∑ ∏ ∫+ • Currency: $ € £ ¥ ₹ ₽+ • Arrows: ← → ↑ ↓ ↔ ⇐ ⇒ ⇔', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';+GO++-- Comment with SQL injection attempt (should be safely handled)+EXEC sp_addextendedproperty 'MS_Description', 'Author name field - prevents SQL injection like ''; DROP TABLE users; --', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';+GO++-- Comment with JSON-like structure+EXEC sp_addextendedproperty 'MS_Description', 'Metadata JSON: {"version": "1.0", "tags": ["important", "draft"], "settings": {"public": false}}', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';+GO++-- Unicode characters in comments+EXEC sp_addextendedproperty 'MS_Description', 'Language code: en-US, fr-FR, de-DE, ja-JP, zh-CN, ar-SA, ru-RU, hi-IN, 한국어, ไทย', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';+GO++-- Comment with URLs and file paths+EXEC sp_addextendedproperty 'MS_Description', 'Translated content - may reference URLs like https://example.com/path?param=value&other=123 or file paths C:\Users\Name\Documents\file.txt', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';+GO++-- Extremely long comment to test limits+EXEC sp_addextendedproperty 'MS_Description',+'This is an extremely long comment designed to test the limits of extended property storage in SQL Server. It contains multiple lines of text with various formatting, special characters, and technical information. The purpose is to verify that the migration system can properly handle, store, and retrieve complex comment data without truncation or corruption. This comment includes: numbers (123456789), symbols (!@#$%^&*()_+-={}[]|\:";''<>?,./ ), Unicode characters (αβγδε中文العربيةрусский한국어), and structured data like JSON {"key": "value", "array": [1, 2, 3], "nested": {"deep": true}}. Additionally, it tests SQL-like syntax: SELECT * FROM table WHERE column = ''value'' AND other_column IN (1, 2, 3); as well as HTML markup: <html><body><p class="test">Content</p></body></html> and XML: <?xml version="1.0"?><root><item id="1">Test</item></root>. The comment system should preserve all these characters and structures exactly as written, demonstrating robust handling of complex metadata in database schema documentation.', 'SCHEMA', 'special', 'TABLE', 'test_extreme';+`,+ migrationDDL: `+-- Drop extremely long comment+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'test_extreme';+GO++-- Drop table with extreme comment+DROP TABLE [special].[test_extreme];+GO++-- Drop column comments with special characters+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'translated_content';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations', 'COLUMN', 'lang_code';+GO++-- Drop column comments from documents+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'metadata';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'author';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'content';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'title';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents', 'COLUMN', 'id';+GO++-- Drop table comments with special characters+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'translations';+EXEC sp_dropextendedproperty 'MS_Description', 'SCHEMA', 'special', 'TABLE', 'documents';+`,+ description: "Reverse of comments with special characters - dropping comments with quotes, unicode, and special formatting",+ },+ {+ name: "reverse_default_constraint_edge_cases",+ initialSchema: `+CREATE SCHEMA [edge];+GO++CREATE TABLE [edge].[test_defaults] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [nullable_with_default] INT CONSTRAINT [DF_test_defaults_nullable_new] DEFAULT 84,+ [string_default] NVARCHAR(50) DEFAULT N'Default''s value',+ [empty_string] NVARCHAR(50) DEFAULT '',+ [zero_default] INT DEFAULT 0,+ [negative_default] INT DEFAULT -1,+ [decimal_precision] DECIMAL(18,6) DEFAULT 123.456789,+ [special_chars] NVARCHAR(100) DEFAULT N'Line1' + CHAR(13) + CHAR(10) + N'Line2',+ [unicode_default] NVARCHAR(100) DEFAULT N'你好世界 🌍',+ [max_int] BIGINT DEFAULT 9223372036854775807,+ [min_int] BIGINT DEFAULT -9223372036854775808,+ [json_config] NVARCHAR(MAX) DEFAULT N'{"enabled": true, "count": 0}'+);++CREATE TABLE [edge].[flags] (+ [id] INT IDENTITY(1,1) PRIMARY KEY,+ [is_enabled] BIT NOT NULL DEFAULT 1,+ [is_deleted] BIT NOT NULL DEFAULT 0,+ [is_visible] BIT DEFAULT 1,+ [is_archived] BIT DEFAULT 0+);+`,+ migrationDDL: `+-- Drop table with bit field defaults+DROP TABLE [edge].[flags];++-- Drop default constraints before dropping columns+-- Drop default constraint for json_config column+DECLARE @constraint_name NVARCHAR(128);+SELECT @constraint_name = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'json_config';+IF @constraint_name IS NOT NULL+ EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name + ']');+GO++-- Drop default constraint for min_int column+DECLARE @constraint_name2 NVARCHAR(128);+SELECT @constraint_name2 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'min_int';+IF @constraint_name2 IS NOT NULL+ EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name2 + ']');+GO++-- Drop default constraint for max_int column+DECLARE @constraint_name3 NVARCHAR(128);+SELECT @constraint_name3 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'max_int';+IF @constraint_name3 IS NOT NULL+ EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name3 + ']');+GO++-- Drop default constraint for unicode_default column+DECLARE @constraint_name4 NVARCHAR(128);+SELECT @constraint_name4 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'unicode_default';+IF @constraint_name4 IS NOT NULL+ EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name4 + ']');+GO++-- Drop default constraint for special_chars column+DECLARE @constraint_name5 NVARCHAR(128);+SELECT @constraint_name5 = dc.name+FROM sys.default_constraints dc+INNER JOIN sys.columns c ON dc.parent_column_id = c.column_id AND dc.parent_object_id = c.object_id+INNER JOIN sys.tables t ON c.object_id = t.object_id+INNER JOIN sys.schemas s ON t.schema_id = s.schema_id+WHERE s.name = 'edge' AND t.name = 'test_defaults' AND c.name = 'special_chars';+IF @constraint_name5 IS NOT NULL+ EXEC('ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [' + @constraint_name5 + ']');+GO++-- Now safe to drop columns+ALTER TABLE [edge].[test_defaults] DROP COLUMN [json_config];+ALTER TABLE [edge].[test_defaults] DROP COLUMN [min_int];+ALTER TABLE [edge].[test_defaults] DROP COLUMN [max_int];+ALTER TABLE [edge].[test_defaults] DROP COLUMN [unicode_default];+ALTER TABLE [edge].[test_defaults] DROP COLUMN [special_chars];++-- Remove named default constraint+ALTER TABLE [edge].[test_defaults] DROP CONSTRAINT [DF_test_defaults_nullable_new];+`,+ description: "Reverse of edge case defaults - dropping special default constraints and columns",+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ // Step 1: Execute 5-step workflow+ portInt, err := strconv.Atoi(port.Port())+ require.NoError(t, err)+ err = executeFiveStepWorkflow(ctx, host, portInt, testCase.initialSchema, testCase.migrationDDL)+ require.NoError(t, err, "Failed 5-step workflow for test case: %s", testCase.description)+ })+ }+}++// executeFiveStepWorkflow implements the 5-step workflow:+// 1. Initialize database schema, get schema result A via syncDBSchema+// 2. Apply migration DDL, get schema result B via syncDBSchema+// 3. Generate rollback DDL via generate_migration+// 4. Execute rollback DDL, get schema result C via syncDBSchema+// 5. Compare schema results A and C to verify they are identical+func executeFiveStepWorkflow(ctx context.Context, host string, port int, initialSchema, migrationDDL string) error {+ // Create driver instance+ driverInstance := &mssqldb.Driver{}++ // Create connection config+ config := db.ConnectionConfig{+ DataSource: &storepb.DataSource{+ Type: storepb.DataSourceType_ADMIN,+ Username: "sa",+ Host: host,+ Port: strconv.Itoa(port),+ Database: "master",+ },+ Password: "Test123!",+ ConnectionContext: db.ConnectionContext{+ DatabaseName: "master",+ },+ }++ // Open connection+ driver, err := driverInstance.Open(ctx, storepb.Engine_MSSQL, config)+ if err != nil {+ return errors.Wrap(err, "failed to connect to MSSQL")+ }+ defer driver.Close(ctx)++ // Create test database with unique name+ testDB := fmt.Sprintf("test_db_%d_%d", time.Now().Unix(), time.Now().UnixNano()%1000000)+ if _, err := driver.Execute(ctx, fmt.Sprintf("CREATE DATABASE [%s]", testDB), db.ExecuteOptions{CreateDatabase: true}); err != nil {+ return errors.Wrap(err, "failed to create test database")+ }+ defer func() {+ // Clean up test database - reconnect to master first+ driver.Close(ctx)+ config.DataSource.Database = "master"+ config.ConnectionContext.DatabaseName = "master"+ cleanupDriver, err := driverInstance.Open(ctx, storepb.Engine_MSSQL, config)+ if err == nil {+ // Set the database to single user mode to close any open connections+ _, _ = cleanupDriver.Execute(ctx, fmt.Sprintf("ALTER DATABASE [%s] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", testDB), db.ExecuteOptions{CreateDatabase: true})+ // Drop the database using CreateDatabase option to avoid transaction issues+ if _, err := cleanupDriver.Execute(ctx, fmt.Sprintf("DROP DATABASE [%s]", testDB), db.ExecuteOptions{CreateDatabase: true}); err != nil {+ // Log but don't fail if cleanup fails+ fmt.Printf("Warning: failed to clean up test database %s: %v\n", testDB, err)+ }+ cleanupDriver.Close(ctx)+ }+ }()++ // Reconnect to test database+ driver.Close(ctx)+ config.DataSource.Database = testDB+ config.ConnectionContext.DatabaseName = testDB+ driver, err = driverInstance.Open(ctx, storepb.Engine_MSSQL, config)+ if err != nil {+ return errors.Wrap(err, "failed to reconnect to test database")+ }+ defer driver.Close(ctx)++ // Step 1: Initialize database schema and get schema result A+ if err := executeSQL(ctx, driver, initialSchema); err != nil {+ return errors.Wrap(err, "failed to execute initial schema")+ }++ mssqlDriver, ok := driver.(*mssqldb.Driver)+ if !ok {+ return errors.New("failed to cast to mssqldb.Driver")+ }++ schemaA, err := mssqlDriver.SyncDBSchema(ctx)+ if err != nil {+ return errors.Wrap(err, "failed to sync schema A")+ }++ // Step 2: Apply migration DDL and get schema result B+ if err := executeSQL(ctx, driver, migrationDDL); err != nil {+ return errors.Wrap(err, "failed to execute migration DDL")+ }++ schemaB, err := mssqlDriver.SyncDBSchema(ctx)+ if err != nil {+ return errors.Wrap(err, "failed to sync schema B")+ }++ // Debug: Print what tables are in each schema+ fmt.Printf("Schema A contents:\n")+ for _, s := range schemaA.Schemas {+ fmt.Printf(" Schema [%s]: %d tables\n", s.Name, len(s.Tables))+ for _, t := range s.Tables {+ fmt.Printf(" - [%s].[%s]\n", s.Name, t.Name)+ }+ }+ fmt.Printf("Schema B contents:\n")+ for _, s := range schemaB.Schemas {+ fmt.Printf(" Schema [%s]: %d tables\n", s.Name, len(s.Tables))+ for _, t := range s.Tables {+ fmt.Printf(" - [%s].[%s]\n", s.Name, t.Name)+ }+ }++ // Step 3: Generate rollback DDL using generate_migration+ // Convert to model schemas for diff+ dbSchemaA := model.NewDatabaseSchema(schemaA, nil, nil, storepb.Engine_MSSQL, false)+ dbSchemaB := model.NewDatabaseSchema(schemaB, nil, nil, storepb.Engine_MSSQL, false)++ // Get diff from B to A (to generate rollback)+ diff, err := schema.GetDatabaseSchemaDiff(dbSchemaB, dbSchemaA)+ if err != nil {+ return errors.Wrap(err, "failed to generate diff")+ }++ // Debug: Print what changes are detected+ fmt.Printf("Schema changes detected:\n")+ fmt.Printf("- Table changes: %d\n", len(diff.TableChanges))+ for i, tc := range diff.TableChanges {+ fmt.Printf(" %d. %s [%s].[%s]\n", i+1, tc.Action, tc.SchemaName, tc.TableName)+ }+ fmt.Printf("- Schema changes: %d\n", len(diff.SchemaChanges))+ for i, sc := range diff.SchemaChanges {+ fmt.Printf(" %d. %s [%s]\n", i+1, sc.Action, sc.SchemaName)+ }++ rollbackDDL, err := schema.GenerateMigration(storepb.Engine_MSSQL, diff)+ if err != nil {+ return errors.Wrap(err, "failed to generate rollback migration")+ }++ // Debug: Print the generated rollback DDL+ fmt.Printf("Generated rollback DDL:\n%s\n", rollbackDDL)++ // Only proceed if there's actual rollback DDL to execute+ if strings.TrimSpace(rollbackDDL) == "" {+ // No rollback needed, schemas should already be identical+ return nil+ }++ // Step 4: Execute rollback DDL and get schema result C+ if err := executeSQL(ctx, driver, rollbackDDL); err != nil {+ return errors.Wrapf(err, "failed to execute rollback DDL: %s", rollbackDDL)+ }++ schemaC, err := mssqlDriver.SyncDBSchema(ctx)+ if err != nil {+ return errors.Wrap(err, "failed to sync schema C")+ }++ // Step 5: Compare schema results A and Cif err := compareSchemas(schemaA, schemaC); err != nil {return errors.Wrap(err, "schema comparison failed")}@@ -1347,8 +2323,22 @@ func splitByGO(sql string) []string {var result []stringfor _, stmt := range statements {stmt = strings.TrimSpace(stmt)- if stmt != "" && !strings.HasPrefix(stmt, "--") {- result = append(result, stmt)+ if stmt != "" {+ // Check if this statement contains any non-comment SQL+ lines := strings.Split(stmt, "\n")+ hasSQL := false+ var sqlLines []string+ for _, line := range lines {+ line = strings.TrimSpace(line)+ if line != "" && !strings.HasPrefix(line, "--") {+ hasSQL = true+ sqlLines = append(sqlLines, line)+ }+ }+ // Only include if there's actual SQL (not just comments)+ if hasSQL {+ result = append(result, strings.Join(sqlLines, " "))+ }}}return result