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 test cases and bug fix for pg (#16666)
rebelice5a7494e15522
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.goindex 8293c7a60a..c6f600a687 100644--- a/backend/plugin/schema/pg/generate_migration.go+++ b/backend/plugin/schema/pg/generate_migration.go@@ -597,6 +597,18 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) errorif createTableSQL != "" {_, _ = buf.WriteString("\n")}++ // Add table and column comments for newly created tables+ if tableDiff.NewTable != nil && tableDiff.NewTable.Comment != "" {+ writeCommentOnTable(buf, tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable.Comment)+ }+ if tableDiff.NewTable != nil {+ for _, col := range tableDiff.NewTable.Columns {+ if col.Comment != "" {+ writeCommentOnColumn(buf, tableDiff.SchemaName, tableDiff.TableName, col.Name, col.Comment)+ }+ }+ }}// Create views@@ -604,6 +616,10 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) errorif err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {return err}+ // Add view comment for newly created views+ if viewDiff.NewView != nil && viewDiff.NewView.Comment != "" {+ writeCommentOnView(buf, viewDiff.SchemaName, viewDiff.ViewName, viewDiff.NewView.Comment)+ }}// Create materialized views@@ -611,6 +627,10 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) errorif err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {return err}+ // Add materialized view comment for newly created materialized views+ if mvDiff.NewMaterializedView != nil && mvDiff.NewMaterializedView.Comment != "" {+ writeCommentOnMaterializedView(buf, mvDiff.SchemaName, mvDiff.MaterializedViewName, mvDiff.NewMaterializedView.Comment)+ }}// Create functions@@ -618,6 +638,10 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) errorif err := writeFunctionDiff(buf, funcDiff); err != nil {return err}+ // Add function comment for newly created functions+ if funcDiff.Action == schema.MetadataDiffActionCreate && funcDiff.NewFunction != nil && funcDiff.NewFunction.Comment != "" {+ writeCommentOnFunction(buf, funcDiff.SchemaName, funcDiff.NewFunction.Signature, funcDiff.NewFunction.Comment)+ }}// Set sequence ownership after all tables are created@@ -640,7 +664,7 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}} else {- // Create in topological order (dependencies first)+ // First pass: Create tables and functions onlyfor _, objID := range orderedList {if tableDiff, ok := tableMap[objID]; ok {// Create table without foreign keys@@ -652,17 +676,58 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) errorif createTableSQL != "" {_, _ = buf.WriteString("\n")}- } else if viewDiff, ok := viewMap[objID]; ok {++ // Add table and column comments for newly created tables+ if tableDiff.NewTable != nil && tableDiff.NewTable.Comment != "" {+ writeCommentOnTable(buf, tableDiff.SchemaName, tableDiff.TableName, tableDiff.NewTable.Comment)+ }+ if tableDiff.NewTable != nil {+ for _, col := range tableDiff.NewTable.Columns {+ if col.Comment != "" {+ writeCommentOnColumn(buf, tableDiff.SchemaName, tableDiff.TableName, col.Name, col.Comment)+ }+ }+ }+ } else if funcDiff, ok := functionMap[objID]; ok {+ if err := writeFunctionDiff(buf, funcDiff); err != nil {+ return err+ }+ // Add function comment for newly created functions+ if funcDiff.Action == schema.MetadataDiffActionCreate && funcDiff.NewFunction != nil && funcDiff.NewFunction.Comment != "" {+ writeCommentOnFunction(buf, funcDiff.SchemaName, funcDiff.NewFunction.Signature, funcDiff.NewFunction.Comment)+ }+ }+ }++ // Handle ALTER table operations that add columns (views might depend on these)+ for _, tableDiff := range diff.TableChanges {+ if tableDiff.Action == schema.MetadataDiffActionAlter {+ // Only process column additions here+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionCreate {+ writeAddColumn(buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ }+ }+ }+ }++ // Second pass: Create views and materialized views (after columns are added)+ for _, objID := range orderedList {+ if viewDiff, ok := viewMap[objID]; ok {if err := writeMigrationView(buf, viewDiff.SchemaName, viewDiff.NewView); err != nil {return err}+ // Add view comment for newly created views+ if viewDiff.NewView != nil && viewDiff.NewView.Comment != "" {+ writeCommentOnView(buf, viewDiff.SchemaName, viewDiff.ViewName, viewDiff.NewView.Comment)+ }} else if mvDiff, ok := materializedViewMap[objID]; ok {if err := writeMigrationMaterializedView(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView); err != nil {return err}- } else if funcDiff, ok := functionMap[objID]; ok {- if err := writeFunctionDiff(buf, funcDiff); err != nil {- return err+ // Add materialized view comment for newly created materialized views+ if mvDiff.NewMaterializedView != nil && mvDiff.NewMaterializedView.Comment != "" {+ writeCommentOnMaterializedView(buf, mvDiff.SchemaName, mvDiff.MaterializedViewName, mvDiff.NewMaterializedView.Comment)}}}@@ -686,12 +751,31 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error}}}++ // Create triggers after foreign keys+ for _, tableDiff := range tableMap {+ if tableDiff.NewTable != nil {+ for _, trigger := range tableDiff.NewTable.Triggers {+ writeMigrationTrigger(buf, trigger)+ }+ }+ }++ // Create indexes for materialized views after they are created+ for _, mvDiff := range diff.MaterializedViewChanges {+ if mvDiff.Action == schema.MetadataDiffActionCreate && mvDiff.NewMaterializedView != nil {+ for _, index := range mvDiff.NewMaterializedView.Indexes {+ writeMigrationMaterializedViewIndex(buf, mvDiff.SchemaName, mvDiff.NewMaterializedView.Name, index)+ }+ }+ }}// Handle ALTER table operationsfor _, tableDiff := range diff.TableChanges {if tableDiff.Action == schema.MetadataDiffActionAlter {- alterTableSQL, err := generateAlterTable(tableDiff)+ // Skip column additions as they were handled earlier+ alterTableSQL, err := generateAlterTableWithOptions(tableDiff, false)if err != nil {return err}@@ -788,13 +872,15 @@ func generateCreateTable(schemaName, tableName string, table *storepb.TableMetadreturn buf.String(), nil}-func generateAlterTable(tableDiff *schema.TableDiff) (string, error) {+func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdditions bool) (string, error) {var buf strings.Builder// Add columns first (other operations might depend on them)- for _, colDiff := range tableDiff.ColumnChanges {- if colDiff.Action == schema.MetadataDiffActionCreate {- writeAddColumn(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ if includeColumnAdditions {+ for _, colDiff := range tableDiff.ColumnChanges {+ if colDiff.Action == schema.MetadataDiffActionCreate {+ writeAddColumn(&buf, tableDiff.SchemaName, tableDiff.TableName, colDiff.NewColumn)+ }}}@@ -838,6 +924,13 @@ func generateAlterTable(tableDiff *schema.TableDiff) (string, error) {}}+ // Add triggers after foreign keys+ for _, triggerDiff := range tableDiff.TriggerChanges {+ if triggerDiff.Action == schema.MetadataDiffActionCreate {+ writeMigrationTrigger(&buf, triggerDiff.NewTrigger)+ }+ }+return buf.String(), nil}@@ -1395,6 +1488,30 @@ func writeMigrationForeignKey(out *strings.Builder, schema, table string, fk *streturn nil}+// writeMigrationTrigger writes a trigger creation statement+func writeMigrationTrigger(out *strings.Builder, trigger *storepb.TriggerMetadata) {+ if trigger == nil || trigger.Body == "" {+ return+ }+ _, _ = out.WriteString(trigger.Body)+ if !strings.HasSuffix(strings.TrimSpace(trigger.Body), ";") {+ _, _ = out.WriteString(";")+ }+ _, _ = out.WriteString("\n")+}++// writeMigrationMaterializedViewIndex writes an index creation statement for a materialized view+func writeMigrationMaterializedViewIndex(out *strings.Builder, _ string, _ string, index *storepb.IndexMetadata) {+ if index == nil || index.Definition == "" {+ return+ }+ _, _ = out.WriteString(index.Definition)+ if !strings.HasSuffix(strings.TrimSpace(index.Definition), ";") {+ _, _ = out.WriteString(";")+ }+ _, _ = out.WriteString("\n")+}+// writeCreateTable writes a CREATE TABLE statementfunc writeMigrationCreateTable(out *strings.Builder, schema, table string, columns []*storepb.ColumnMetadata, checks []*storepb.CheckConstraintMetadata) {_, _ = out.WriteString(`CREATE TABLE "`)@@ -1488,6 +1605,17 @@ func writeMigrationUniqueKey(out *strings.Builder, schema, table string, index *// writeIndex writes a CREATE INDEX statementfunc writeMigrationIndex(out *strings.Builder, schema, table string, index *storepb.IndexMetadata) {+ // If index has a full definition, use it directly+ if index.Definition != "" {+ _, _ = out.WriteString(index.Definition)+ if !strings.HasSuffix(strings.TrimSpace(index.Definition), ";") {+ _, _ = out.WriteString(";")+ }+ _, _ = out.WriteString("\n")+ return+ }++ // Otherwise, construct the CREATE INDEX statement_, _ = out.WriteString(`CREATE `)if index.Unique {_, _ = out.WriteString(`UNIQUE `)@@ -1520,9 +1648,6 @@ func writeMigrationIndex(out *strings.Builder, schema, table string, index *stor}_, _ = out.WriteString(`)`)- // Note: IndexMetadata doesn't have a Where field in the current protobuf definition- // This would need to be added if partial indexes need to be supported-_, _ = out.WriteString(`;`)_, _ = out.WriteString("\n")}diff --git a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go b/backend/plugin/schema/pg/generate_migration_testcontainer_test.goindex 11cc921fad..f7cb0008e5 100644--- a/backend/plugin/schema/pg/generate_migration_testcontainer_test.go+++ b/backend/plugin/schema/pg/generate_migration_testcontainer_test.go@@ -879,6 +879,924 @@ $$ LANGUAGE plpgsql;COMMENT ON FUNCTION get_active_records() IS 'Returns all active records from test_table';`,description: "Comments with special characters, quotes, and multiline text",},+ // Reverse test cases+ {+ name: "reverse_basic_table_operations",+ initialSchema: `+CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL,+ email VARCHAR(100) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ is_active BOOLEAN DEFAULT true+);++CREATE TABLE posts (+ id SERIAL PRIMARY KEY,+ user_id INTEGER NOT NULL,+ title VARCHAR(200) NOT NULL,+ content TEXT,+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id),+ CONSTRAINT check_title_length CHECK (length(title) > 0)+);++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_post FOREIGN KEY (post_id) REFERENCES posts(id),+ CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES users(id)+);++CREATE INDEX idx_posts_user_id ON posts(user_id);+CREATE INDEX idx_users_email ON users(email);+`,+ migrationDDL: `+-- Drop index+DROP INDEX idx_users_email;++-- Drop check constraint+ALTER TABLE posts DROP CONSTRAINT check_title_length;++-- Drop table+DROP TABLE comments;++-- Drop column+ALTER TABLE users DROP COLUMN is_active;+`,+ description: "Reverse of basic_table_operations: DROP column, table, index, constraint",+ },+ {+ name: "reverse_views_and_functions",+ initialSchema: `+CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ price DECIMAL(10, 2) NOT NULL,+ stock INTEGER DEFAULT 0+);++CREATE TABLE orders (+ id SERIAL PRIMARY KEY,+ product_id INTEGER NOT NULL,+ quantity INTEGER NOT NULL,+ total DECIMAL(10, 2),+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id)+);++CREATE VIEW product_inventory AS+SELECT+ p.id,+ p.name,+ p.price,+ p.stock,+ COALESCE(SUM(o.quantity), 0) as total_ordered+FROM products p+LEFT JOIN orders o ON p.id = o.product_id+GROUP BY p.id, p.name, p.price, p.stock;++CREATE OR REPLACE FUNCTION calculate_order_total()+RETURNS TRIGGER AS $$+BEGIN+ NEW.total := NEW.quantity * (SELECT price FROM products WHERE id = NEW.product_id);+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER update_order_total+BEFORE INSERT OR UPDATE ON orders+FOR EACH ROW+EXECUTE FUNCTION calculate_order_total();++CREATE MATERIALIZED VIEW product_stats AS+SELECT+ product_id,+ COUNT(*) as order_count,+ SUM(quantity) as total_quantity,+ SUM(total) as total_revenue+FROM orders+GROUP BY product_id;++CREATE INDEX idx_product_stats_revenue ON product_stats(total_revenue DESC);+`,+ migrationDDL: `+-- Drop index on materialized view+DROP INDEX idx_product_stats_revenue;++-- Drop materialized view+DROP MATERIALIZED VIEW product_stats;++-- Drop trigger+DROP TRIGGER update_order_total ON orders;++-- Drop function+DROP FUNCTION calculate_order_total();++-- Drop view+DROP VIEW product_inventory;+`,+ description: "Reverse of views_and_functions: DROP view, function, trigger, materialized view",+ },+ {+ name: "reverse_schema_and_sequences",+ initialSchema: `+CREATE SCHEMA inventory;+CREATE SCHEMA sales;++CREATE SEQUENCE sales.order_seq START WITH 1000 INCREMENT BY 10;++CREATE TYPE inventory.item_status AS ENUM ('available', 'out_of_stock', 'discontinued');++CREATE TABLE inventory.items (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ status inventory.item_status DEFAULT 'available'+);++CREATE TABLE sales.orders (+ id INTEGER DEFAULT nextval('sales.order_seq') PRIMARY KEY,+ item_id INTEGER NOT NULL,+ quantity INTEGER NOT NULL,+ CONSTRAINT fk_item FOREIGN KEY (item_id) REFERENCES inventory.items(id)+);+`,+ migrationDDL: `+-- Drop table in sales schema+DROP TABLE sales.orders;++-- Drop sequence+DROP SEQUENCE sales.order_seq;++-- Drop schema+DROP SCHEMA sales;++-- Drop column that uses enum+ALTER TABLE inventory.items DROP COLUMN status;++-- Drop enum type+DROP TYPE inventory.item_status;+`,+ description: "Reverse of schema_and_sequences: DROP schema, sequence, table, type",+ },+ {+ name: "reverse_complex_dependencies",+ initialSchema: `+CREATE TABLE departments (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL+);++CREATE TABLE employees (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ department_id INTEGER,+ CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(id)+);++CREATE TABLE projects (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ department_id INTEGER NOT NULL,+ lead_employee_id INTEGER,+ CONSTRAINT fk_project_dept FOREIGN KEY (department_id) REFERENCES departments(id),+ CONSTRAINT fk_project_lead FOREIGN KEY (lead_employee_id) REFERENCES employees(id)+);++CREATE VIEW department_employees AS+SELECT d.id as dept_id, d.name as dept_name, e.id as emp_id, e.name as emp_name+FROM departments d+LEFT JOIN employees e ON d.id = e.department_id;++CREATE VIEW department_summary AS+SELECT dept_id, dept_name, COUNT(emp_id) as employee_count+FROM department_employees+GROUP BY dept_id, dept_name;++CREATE OR REPLACE FUNCTION get_department_employees(dept_id INTEGER)+RETURNS TABLE(employee_id INTEGER, employee_name VARCHAR) AS $$+BEGIN+ RETURN QUERY+ SELECT id, name+ FROM employees+ WHERE department_id = dept_id;+END;+$$ LANGUAGE plpgsql;+`,+ migrationDDL: `+-- Drop table with foreign keys+DROP TABLE projects;++-- Drop function+DROP FUNCTION get_department_employees(INTEGER);++-- Drop dependent view first+DROP VIEW department_summary;++-- Drop base view+DROP VIEW department_employees;+`,+ description: "Reverse of complex_dependencies: DROP views, functions, tables with dependencies",+ },+ {+ name: "reverse_drop_indexes_and_constraints",+ initialSchema: `+CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ category VARCHAR(50),+ price DECIMAL(10, 2),+ supplier_id INTEGER+);+`,+ migrationDDL: `+-- Create indexes and constraints+CREATE INDEX idx_products_category ON products(category);+CREATE INDEX idx_products_price ON products(price);+CREATE UNIQUE INDEX idx_products_name ON products(name);++ALTER TABLE products ADD CONSTRAINT check_price_positive CHECK (price > 0);+ALTER TABLE products ADD CONSTRAINT check_name_length CHECK (length(name) >= 3);+`,+ description: "Reverse of drop_indexes_and_constraints: CREATE indexes and constraints",+ },+ {+ name: "reverse_drop_views_and_functions",+ initialSchema: `+CREATE TABLE sales (+ id SERIAL PRIMARY KEY,+ product_name VARCHAR(100) NOT NULL,+ sale_amount DECIMAL(10, 2) NOT NULL,+ sale_date DATE NOT NULL+);+`,+ migrationDDL: `+-- Create views and functions+CREATE VIEW monthly_sales AS+SELECT+ EXTRACT(YEAR FROM sale_date) as year,+ EXTRACT(MONTH FROM sale_date) as month,+ SUM(sale_amount) as total_sales+FROM sales+GROUP BY EXTRACT(YEAR FROM sale_date), EXTRACT(MONTH FROM sale_date);++CREATE MATERIALIZED VIEW top_products AS+SELECT+ product_name,+ COUNT(*) as sale_count,+ SUM(sale_amount) as total_revenue+FROM sales+GROUP BY product_name+ORDER BY total_revenue DESC;++CREATE OR REPLACE FUNCTION get_monthly_total(year_param INTEGER, month_param INTEGER)+RETURNS DECIMAL AS $$+BEGIN+ RETURN (+ SELECT COALESCE(SUM(sale_amount), 0)+ FROM sales+ WHERE EXTRACT(YEAR FROM sale_date) = year_param+ AND EXTRACT(MONTH FROM sale_date) = month_param+ );+END;+$$ LANGUAGE plpgsql;++CREATE OR REPLACE FUNCTION calculate_discount(amount DECIMAL)+RETURNS DECIMAL AS $$+BEGIN+ RETURN amount * 0.1;+END;+$$ LANGUAGE plpgsql;+`,+ description: "Reverse of drop_views_and_functions: CREATE views and functions",+ },+ {+ name: "reverse_alter_table_columns",+ initialSchema: `+CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ price DECIMAL(10, 2) NOT NULL,+ description TEXT NOT NULL,+ category VARCHAR(30),+ is_active BOOLEAN DEFAULT true,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ stock_quantity INTEGER DEFAULT 0,+ weight DECIMAL(5, 2),+ CONSTRAINT check_price_positive CHECK (price > 0),+ CONSTRAINT check_stock_non_negative CHECK (stock_quantity >= 0)+);++CREATE INDEX idx_products_category ON products(category);+CREATE INDEX idx_products_price ON products(price);+CREATE INDEX idx_products_created_at ON products(created_at);+CREATE UNIQUE INDEX idx_products_name_category ON products(name, category);+`,+ migrationDDL: `+-- Drop indexes+DROP INDEX idx_products_created_at;+DROP INDEX idx_products_name_category;++-- Drop constraints+ALTER TABLE products DROP CONSTRAINT check_stock_non_negative;+ALTER TABLE products DROP CONSTRAINT check_price_positive;++-- Revert column changes+ALTER TABLE products ALTER COLUMN category SET NOT NULL;+ALTER TABLE products ALTER COLUMN description DROP NOT NULL;+ALTER TABLE products ALTER COLUMN price TYPE DECIMAL(8, 2);+ALTER TABLE products ALTER COLUMN name TYPE VARCHAR(50);++-- Drop columns+ALTER TABLE products+ DROP COLUMN weight,+ DROP COLUMN stock_quantity,+ DROP COLUMN created_at;+`,+ description: "Reverse of alter_table_columns: DROP columns, constraints, indexes",+ },+ {+ name: "reverse_drop_and_recreate_constraints",+ initialSchema: `+CREATE TABLE authors (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ email VARCHAR(100) UNIQUE+);++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_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE,+ CONSTRAINT check_year_extended CHECK (published_year >= 1000 AND published_year <= 2030),+ CONSTRAINT check_title_length CHECK (length(title) >= 3)+);++CREATE INDEX idx_books_author ON books(author_id);+CREATE INDEX idx_books_year ON books(published_year);+CREATE INDEX idx_books_isbn ON books(isbn);+`,+ migrationDDL: `+-- Drop new constraints+ALTER TABLE books DROP CONSTRAINT check_title_length;++-- Drop index and recreate unique constraint+DROP INDEX idx_books_isbn;+ALTER TABLE books ADD CONSTRAINT books_isbn_key UNIQUE (isbn);++-- Drop and recreate check constraints with original definitions+ALTER TABLE books DROP CONSTRAINT check_year_extended;+ALTER TABLE books ADD CONSTRAINT check_year_valid CHECK (published_year >= 1000 AND published_year <= 2100);++-- Drop and recreate foreign key with original options+ALTER TABLE books DROP CONSTRAINT fk_author_new;+ALTER TABLE books ADD CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id);++-- Add back original constraint+ALTER TABLE books ADD CONSTRAINT check_price_positive CHECK (price > 0);+`,+ description: "Reverse of drop_and_recreate_constraints: Reverse the constraint changes",+ },+ {+ name: "reverse_drop_sequence_and_type",+ initialSchema: ``,+ migrationDDL: `+-- Create schema and objects+CREATE SCHEMA accounting;++CREATE TYPE accounting.transaction_status AS ENUM ('pending', 'completed', 'cancelled');++CREATE SEQUENCE accounting.transaction_seq START 1000;++CREATE TABLE accounting.simple_log (+ message TEXT NOT NULL,+ status accounting.transaction_status DEFAULT 'pending'+);+`,+ description: "Reverse of drop_sequence_and_type: CREATE schema, sequence, type, table",+ },+ {+ name: "reverse_mixed_operations_complex",+ initialSchema: `+CREATE TABLE suppliers (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ contact_email VARCHAR(100),+ CONSTRAINT check_email_format CHECK (contact_email LIKE '%@%')+);++CREATE TABLE categories (+ id SERIAL PRIMARY KEY,+ name VARCHAR(50) NOT NULL UNIQUE,+ description TEXT+);++CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ supplier_id INTEGER,+ price DECIMAL(10, 2),+ category_id INTEGER,+ CONSTRAINT fk_supplier_cascade FOREIGN KEY (supplier_id) REFERENCES suppliers(id) ON DELETE SET NULL,+ CONSTRAINT fk_category FOREIGN KEY (category_id) REFERENCES categories(id),+ CONSTRAINT check_price_range CHECK (price >= 0 AND price <= 10000)+);++CREATE INDEX idx_products_category ON products(category_id);+CREATE INDEX idx_products_price_range ON products(price) WHERE price > 100;++CREATE VIEW product_summary AS+SELECT+ p.id,+ p.name as product_name,+ s.name as supplier_name,+ c.name as category_name,+ p.price+FROM products p+LEFT JOIN suppliers s ON p.supplier_id = s.id+LEFT JOIN categories c ON p.category_id = c.id;++CREATE OR REPLACE FUNCTION get_expensive_products(threshold DECIMAL DEFAULT 100)+RETURNS TABLE(product_name VARCHAR, supplier_name VARCHAR, price DECIMAL) AS $$+BEGIN+ RETURN QUERY+ SELECT p.name, s.name, p.price+ FROM products p+ JOIN suppliers s ON p.supplier_id = s.id+ WHERE p.price > threshold+ ORDER BY p.price DESC;+END;+$$ LANGUAGE plpgsql;+`,+ migrationDDL: `+-- Drop function+DROP FUNCTION get_expensive_products(DECIMAL);++-- Drop indexes+DROP INDEX idx_products_price_range;+DROP INDEX idx_products_category;++-- Drop constraints+ALTER TABLE suppliers DROP CONSTRAINT check_email_format;+ALTER TABLE products DROP CONSTRAINT check_price_range;++-- Drop and recreate foreign key with original action+ALTER TABLE products DROP CONSTRAINT fk_supplier_cascade;+ALTER TABLE products ADD CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES suppliers(id);++-- Drop view+DROP VIEW product_summary;++-- Drop foreign key to categories+ALTER TABLE products DROP CONSTRAINT fk_category;++-- Drop column+ALTER TABLE products DROP COLUMN category_id;++-- Drop table+DROP TABLE categories;+`,+ description: "Reverse of mixed_operations_complex: Reverse all mixed operations",+ },+ {+ name: "reverse_create_tables_with_fk",+ initialSchema: ``,+ migrationDDL: `+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);+`,+ description: "Reverse of create_tables_with_fk: CREATE tables with foreign keys",+ },+ {+ name: "reverse_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,+ is_active BOOLEAN DEFAULT true+);++CREATE UNIQUE INDEX uk_email ON users(email);+CREATE INDEX idx_username ON users(username);+CREATE INDEX idx_email_active ON users(email, is_active);++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,+ CONSTRAINT chk_title_length CHECK (LENGTH(title) > 0)+);++CREATE INDEX idx_user_id ON posts(user_id);++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);+`,+ migrationDDL: `+-- Drop check constraint+ALTER TABLE posts DROP CONSTRAINT chk_title_length;++-- Drop index+DROP INDEX idx_email_active;++-- Drop table with multiple foreign keys+DROP TABLE comments;++-- Drop column+ALTER TABLE users DROP COLUMN is_active;+`,+ description: "Reverse of multiple_foreign_keys: DROP column, table, indexes, constraints",+ },+ {+ name: "reverse_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_new FOREIGN KEY (author_id) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT chk_year_extended CHECK (published_year >= 1000 AND published_year <= 2030),+ CONSTRAINT chk_price_positive CHECK (price > 0),+ CONSTRAINT chk_title_length CHECK (LENGTH(title) >= 3)+);++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 new constraints+ALTER TABLE books DROP CONSTRAINT chk_title_length;++-- Drop and modify check constraints+ALTER TABLE books DROP CONSTRAINT chk_year_extended;+ALTER TABLE books ADD CONSTRAINT chk_year_valid CHECK (published_year >= 1000 AND published_year <= 2100);++-- Drop and recreate foreign key with different options+ALTER TABLE books DROP CONSTRAINT fk_author_new;+ALTER TABLE books ADD CONSTRAINT fk_author FOREIGN KEY (author_id) REFERENCES authors(id);+`,+ description: "Reverse of drop_and_recreate_fk_constraints: Reverse FK constraint changes",+ },+ {+ name: "reverse_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);++ALTER TABLE departments ADD CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employees(id);++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 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 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 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;+`,+ migrationDDL: `+-- Drop function using views+DROP FUNCTION get_department_report(VARCHAR);++-- Drop highly dependent view+DROP VIEW dept_manager_summary;++-- Drop dependent view+DROP VIEW dept_summary;++-- Drop base view+DROP VIEW dept_employee_count;+`,+ description: "Reverse of self_referencing_foreign_keys: DROP views and functions with dependencies",+ },+ {+ name: "reverse_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),+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE+);++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);++ALTER TABLE customers ADD CONSTRAINT fk_preferred_order FOREIGN KEY (preferred_order_id) REFERENCES orders(id) ON DELETE SET NULL;++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();+`,+ migrationDDL: `+-- Drop trigger+DROP TRIGGER trg_update_order_total ON order_items;++-- Drop function+DROP FUNCTION update_order_total();++-- Drop index+DROP INDEX idx_order;++-- Drop table+DROP TABLE order_items;++-- Drop circular foreign key constraints+ALTER TABLE customers DROP CONSTRAINT fk_preferred_order;+ALTER TABLE orders DROP CONSTRAINT fk_customer;+`,+ description: "Reverse of circular_foreign_key_dependencies: DROP circular FK dependencies",+ },+ {+ name: "reverse_table_and_column_comments",+ initialSchema: `+CREATE TABLE products (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ price DECIMAL(10, 2) NOT NULL,+ category VARCHAR(50),+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++CREATE TABLE customers (+ id SERIAL PRIMARY KEY,+ first_name VARCHAR(50) NOT NULL,+ last_name VARCHAR(50) NOT NULL,+ email VARCHAR(100) UNIQUE,+ phone VARCHAR(20)+);++CREATE TABLE orders (+ id SERIAL PRIMARY KEY,+ customer_id INTEGER NOT NULL,+ product_id INTEGER NOT NULL,+ quantity INTEGER DEFAULT 1,+ order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT fk_order_customer FOREIGN KEY (customer_id) REFERENCES customers(id),+ CONSTRAINT fk_order_product FOREIGN KEY (product_id) REFERENCES products(id)+);++COMMENT ON TABLE products IS 'Product catalog with pricing information';+COMMENT ON TABLE customers IS 'Customer master data';+COMMENT ON TABLE orders IS 'Customer purchase orders';++COMMENT ON COLUMN products.id IS 'Unique product identifier';+COMMENT ON COLUMN products.name IS 'Product display name';+COMMENT ON COLUMN products.price IS 'Product price in USD';+COMMENT ON COLUMN products.category IS 'Product category classification';+COMMENT ON COLUMN products.created_at IS 'Record creation timestamp';++COMMENT ON COLUMN customers.id IS 'Unique customer identifier';+COMMENT ON COLUMN customers.first_name IS 'Customer first name';+COMMENT ON COLUMN customers.last_name IS 'Customer last name';+COMMENT ON COLUMN customers.email IS 'Customer email address';+COMMENT ON COLUMN customers.phone IS 'Customer contact phone number';++COMMENT ON COLUMN orders.id IS 'Unique order identifier';+COMMENT ON COLUMN orders.customer_id IS 'Reference to customer who placed the order';+COMMENT ON COLUMN orders.product_id IS 'Reference to ordered product';+COMMENT ON COLUMN orders.quantity IS 'Number of items ordered';+COMMENT ON COLUMN orders.order_date IS 'Date and time when order was placed';+`,+ migrationDDL: `+-- Drop all column comments+COMMENT ON COLUMN orders.order_date IS NULL;+COMMENT ON COLUMN orders.quantity IS NULL;+COMMENT ON COLUMN orders.product_id IS NULL;+COMMENT ON COLUMN orders.customer_id IS NULL;+COMMENT ON COLUMN orders.id IS NULL;++COMMENT ON COLUMN customers.phone IS NULL;+COMMENT ON COLUMN customers.email IS NULL;+COMMENT ON COLUMN customers.last_name IS NULL;+COMMENT ON COLUMN customers.first_name IS NULL;+COMMENT ON COLUMN customers.id IS NULL;++COMMENT ON COLUMN products.created_at IS NULL;+COMMENT ON COLUMN products.category IS NULL;+COMMENT ON COLUMN products.price IS NULL;+COMMENT ON COLUMN products.name IS NULL;+COMMENT ON COLUMN products.id IS NULL;++-- Drop table comments+COMMENT ON TABLE orders IS NULL;+COMMENT ON TABLE customers IS NULL;+COMMENT ON TABLE products IS NULL;++-- Drop orders table with foreign keys+DROP TABLE orders;+`,+ description: "Reverse of table_and_column_comments: DROP comments",+ },+ {+ name: "reverse_modify_and_drop_comments",+ initialSchema: `+CREATE TABLE inventory (+ id SERIAL PRIMARY KEY,+ product_code VARCHAR(20) NOT NULL UNIQUE,+ stock_level INTEGER DEFAULT 0,+ warehouse_location VARCHAR(100),+ last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ reorder_point INTEGER DEFAULT 10+);++CREATE VIEW low_stock_items AS+SELECT product_code, stock_level, reorder_point+FROM inventory+WHERE stock_level <= reorder_point;++COMMENT ON TABLE inventory IS 'Comprehensive inventory management system';+COMMENT ON COLUMN inventory.id IS 'Primary key for inventory records';+COMMENT ON COLUMN inventory.product_code IS 'SKU - Stock Keeping Unit identifier';+COMMENT ON COLUMN inventory.stock_level IS 'Available quantity for sale';+COMMENT ON COLUMN inventory.reorder_point IS 'Minimum stock level before reordering';+COMMENT ON VIEW low_stock_items IS 'Products that need to be restocked';+`,+ migrationDDL: `+-- Drop view comment+COMMENT ON VIEW low_stock_items IS NULL;++-- Drop view+DROP VIEW low_stock_items;++-- Drop column with comment+ALTER TABLE inventory DROP COLUMN reorder_point;++-- Add back removed comments+COMMENT ON COLUMN inventory.warehouse_location IS 'Physical location in warehouse';+COMMENT ON COLUMN inventory.last_updated IS 'Last modification timestamp';++-- Modify existing comments back to original+COMMENT ON COLUMN inventory.stock_level IS 'Current stock quantity';+COMMENT ON COLUMN inventory.product_code IS 'Unique product identifier code';+COMMENT ON TABLE inventory IS 'Initial inventory tracking table';+`,+ description: "Reverse of modify_and_drop_comments: Reverse comment changes",+ },+ {+ name: "reverse_comments_with_special_characters",+ initialSchema: `+CREATE TABLE test_table (+ id SERIAL PRIMARY KEY,+ data VARCHAR(255),+ status VARCHAR(20) DEFAULT 'active'+);++CREATE OR REPLACE FUNCTION get_active_records()+RETURNS TABLE(id INTEGER, data VARCHAR) AS $$+BEGIN+ RETURN QUERY+ SELECT t.id, t.data+ FROM test_table t+ WHERE t.status = 'active';+END;+$$ LANGUAGE plpgsql;++COMMENT ON TABLE test_table IS 'Test table with "quotes" and ''apostrophes'' and $special$ characters';+COMMENT ON COLUMN test_table.id IS 'ID with symbols: @#$%^&*()_+-={}|[]\\:";''<>?,./';+COMMENT ON COLUMN test_table.data IS 'Data field containing+multiline+text with various symbols: ñáéíóú àèìòù äëïöü';+COMMENT ON COLUMN test_table.status IS 'Status: active/inactive (default: active)';+COMMENT ON FUNCTION get_active_records() IS 'Returns all active records from test_table';+`,+ migrationDDL: `+-- Drop function comment+COMMENT ON FUNCTION get_active_records() IS NULL;++-- Drop function+DROP FUNCTION get_active_records();++-- Drop column comments+COMMENT ON COLUMN test_table.status IS NULL;+COMMENT ON COLUMN test_table.data IS NULL;+COMMENT ON COLUMN test_table.id IS NULL;++-- Drop table comment+COMMENT ON TABLE test_table IS NULL;+`,+ description: "Reverse of comments_with_special_characters: DROP comments with special chars",+ },}for _, tc := range testCases {@@ -1036,6 +1954,11 @@ func normalizeMetadataForComparison(metadata *storepb.DatabaseSchemaMetadata) {table.IndexSize = 0table.RowCount = 0+ // Clear column positions as they can change when columns are added/dropped+ for _, column := range table.Columns {+ column.Position = 0+ }+// Sort columns by name for consistent comparisonsortColumnsByName(table.Columns)