Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test: add sdl test framework and type test cases (#17321)
rebelice1f66e829431b
diff --git a/backend/plugin/db/pg/sync.go b/backend/plugin/db/pg/sync.goindex 9b903583c2..ae4eeedd44 100644--- a/backend/plugin/db/pg/sync.go+++ b/backend/plugin/db/pg/sync.go@@ -712,6 +712,9 @@ SELECTcols.column_name,cols.data_type,cols.character_maximum_length,+ cols.numeric_precision,+ cols.numeric_scale,+ cols.datetime_precision,cols.ordinal_position,cols.column_default,cols.is_nullable,@@ -735,8 +738,8 @@ func getTableColumns(txn *sql.Tx) (map[db.TableKey][]*storepb.ColumnMetadata, erfor rows.Next() {column := &storepb.ColumnMetadata{}var schemaName, tableName, nullable string- var characterMaxLength, defaultStr, collation, udtSchema, udtName, identityGeneration, comment sql.NullString- if err := rows.Scan(&schemaName, &tableName, &column.Name, &column.Type, &characterMaxLength, &column.Position, &defaultStr, &nullable, &collation, &udtSchema, &udtName, &identityGeneration, &comment); err != nil {+ var characterMaxLength, numericPrecision, numericScale, datetimePrecision, defaultStr, collation, udtSchema, udtName, identityGeneration, comment sql.NullString+ if err := rows.Scan(&schemaName, &tableName, &column.Name, &column.Type, &characterMaxLength, &numericPrecision, &numericScale, &datetimePrecision, &column.Position, &defaultStr, &nullable, &collation, &udtSchema, &udtName, &identityGeneration, &comment); err != nil {return nil, err}// Store schema-qualified default in the Default field for Step 4 of column default migration@@ -763,6 +766,34 @@ func getTableColumns(txn *sql.Tx) (map[db.TableKey][]*storepb.ColumnMetadata, er// https://www.postgresql.org/docs/current/infoschema-columns.html.column.Type = fmt.Sprintf("%s(%s)", column.Type, characterMaxLength.String)}+ case "numeric", "decimal":+ // Handle numeric/decimal precision and scale+ if numericPrecision.Valid && numericScale.Valid {+ // If scale is 0, only show precision (NUMERIC(8) not NUMERIC(8,0))+ if numericScale.String == "0" {+ column.Type = fmt.Sprintf("%s(%s)", column.Type, numericPrecision.String)+ } else {+ column.Type = fmt.Sprintf("%s(%s,%s)", column.Type, numericPrecision.String, numericScale.String)+ }+ } else if numericPrecision.Valid {+ column.Type = fmt.Sprintf("%s(%s)", column.Type, numericPrecision.String)+ }+ case "time", "time without time zone", "time with time zone",+ "timestamp", "timestamp without time zone", "timestamp with time zone":+ // Handle time/timestamp precision+ if datetimePrecision.Valid {+ // For time types, add precision before "without time zone" part+ if strings.Contains(column.Type, "without time zone") {+ baseType := strings.Replace(column.Type, " without time zone", "", 1)+ column.Type = fmt.Sprintf("%s(%s) without time zone", baseType, datetimePrecision.String)+ } else if strings.Contains(column.Type, "with time zone") {+ baseType := strings.Replace(column.Type, " with time zone", "", 1)+ column.Type = fmt.Sprintf("%s(%s) with time zone", baseType, datetimePrecision.String)+ } else {+ // For plain "time" or "timestamp"+ column.Type = fmt.Sprintf("%s(%s)", column.Type, datetimePrecision.String)+ }+ }default:// Keep the type as is}diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex b540319d3c..cc5025610b 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -586,15 +586,50 @@ func columnsEqual(engine storepb.Engine, col1, col2 *storepb.ColumnMetadata) boo// defaultValuesEqual compares default values.func defaultValuesEqual(col1, col2 *storepb.ColumnMetadata) bool {- // Now we only need to compare the consolidated default field+ // Quick check for identical stringsif col1.Default == col2.Default {return true}- // For PostgreSQL, try normalized comparison to handle schema prefix differences- norm1 := normalizePostgreSQLDefaultValue(col1.Default)- norm2 := normalizePostgreSQLDefaultValue(col2.Default)- return norm1 == norm2+ // Handle PostgreSQL type cast normalization for common cases before expression comparison+ // This is needed because the expression comparer may not parse complex type casts correctly+ normalized1 := normalizePostgreSQLTypecastInDefault(col1.Default)+ normalized2 := normalizePostgreSQLTypecastInDefault(col2.Default)++ if normalized1 == normalized2 {+ return true+ }++ // Use semantic expression comparison for PostgreSQL default values+ // This handles schema prefixes and other semantic equivalences+ return CompareExpressionsSemantically(storepb.Engine_POSTGRES, col1.Default, col2.Default)+}++// normalizePostgreSQLTypecastInDefault normalizes PostgreSQL type casts in default values+func normalizePostgreSQLTypecastInDefault(defaultValue string) string {+ if defaultValue == "" {+ return ""+ }++ normalized := strings.TrimSpace(defaultValue)++ // Remove PostgreSQL type casts from default values+ // Handle patterns like '1 day'::interval -> '1 day'+ normalized = strings.ReplaceAll(normalized, "'::interval", "'")+ normalized = strings.ReplaceAll(normalized, "'::timestamp", "'")+ normalized = strings.ReplaceAll(normalized, "'::date", "'")+ normalized = strings.ReplaceAll(normalized, "'::time", "'")+ normalized = strings.ReplaceAll(normalized, "'::numeric", "'")++ // Handle string type casts+ // Handle character varying first (longest match first to avoid partial replacement)+ normalized = strings.ReplaceAll(normalized, "'::character varying", "'") // CHARACTER VARYING type (full form of VARCHAR)+ normalized = strings.ReplaceAll(normalized, "'::bpchar", "'") // CHAR type+ normalized = strings.ReplaceAll(normalized, "'::text", "'") // TEXT type+ normalized = strings.ReplaceAll(normalized, "'::varchar", "'") // VARCHAR type+ normalized = strings.ReplaceAll(normalized, "'::character", "'") // CHARACTER type++ return normalized}// generationMetadataEqual compares two generation metadata structs.@@ -695,7 +730,9 @@ func indexesEqual(engine storepb.Engine, idx1, idx2 *storepb.IndexMetadata) boolreturn false}- return true+ // Compare WHERE conditions for partial indexes using engine-specific comparer+ comparer := GetIndexComparer(engine)+ return comparer.CompareIndexWhereConditions(idx1.Definition, idx2.Definition)}// descendingArraysEqual compares two descending arrays, considering empty arrays@@ -1934,34 +1971,6 @@ func normalizePostgreSQLFunction(definition string) string {return strings.TrimSpace(normalized)}-// normalizePostgreSQLDefaultValue normalizes PostgreSQL default values for comparison-func normalizePostgreSQLDefaultValue(defaultValue string) string {- if defaultValue == "" {- return ""- }-- normalized := strings.ToLower(defaultValue)-- // Remove quotes around the entire default value if present- if len(normalized) >= 2 && normalized[0] == '\'' && normalized[len(normalized)-1] == '\'' {- normalized = normalized[1 : len(normalized)-1]- }-- // Normalize whitespace- normalized = strings.ReplaceAll(normalized, "\n", " ")- normalized = strings.ReplaceAll(normalized, "\t", " ")-- // Remove extra spaces- for strings.Contains(normalized, " ") {- normalized = strings.ReplaceAll(normalized, " ", " ")- }-- // Remove public schema prefix from function calls- normalized = strings.ReplaceAll(normalized, "public.", "")-- return strings.TrimSpace(normalized)-}-// normalizePostgreSQLCheckConstraint normalizes PostgreSQL check constraint expressions for comparisonfunc normalizePostgreSQLCheckConstraint(expression string) string {// Based on the test output, we need to normalize:@@ -2015,6 +2024,14 @@ func normalizePostgreSQLCheckConstraint(expression string) string {expression = strings.ReplaceAll(expression, "year')", "year'")}+ // Step 6: Normalize timestamp literals and type casts+ // '2020-01-01 00:00:00'::timestamp without time zone -> '2020-01-01'::timestamp+ expression = strings.ReplaceAll(expression, " 00:00:00'::timestamp without time zone", "'::timestamp")++ // Step 7: Normalize numeric type casts+ // >= 0::numeric -> >= 0+ expression = strings.ReplaceAll(expression, "::numeric", "")+return strings.TrimSpace(expression)}diff --git a/backend/plugin/schema/index_comparer.go b/backend/plugin/schema/index_comparer.gonew file mode 100644index 0000000000..fee6b3355d--- /dev/null+++ b/backend/plugin/schema/index_comparer.go@@ -0,0 +1,91 @@+package schema++import (+ "strings"+ "sync"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+)++// IndexComparer provides database-specific index comparison logic.+type IndexComparer interface {+ // CompareIndexWhereConditions compares WHERE conditions from two index definitions+ CompareIndexWhereConditions(def1, def2 string) bool++ // ExtractWhereClauseFromIndexDef extracts the WHERE clause from an index definition+ ExtractWhereClauseFromIndexDef(definition string) string+}++// DefaultIndexComparer provides default index comparison logic using simple string matching.+type DefaultIndexComparer struct{}++// CompareIndexWhereConditions provides a default implementation using simple string extraction.+func (c *DefaultIndexComparer) CompareIndexWhereConditions(def1, def2 string) bool {+ whereClause1 := c.ExtractWhereClauseFromIndexDef(def1)+ whereClause2 := c.ExtractWhereClauseFromIndexDef(def2)++ // Simple string comparison - not ideal but works for basic cases+ return whereClause1 == whereClause2+}++// ExtractWhereClauseFromIndexDef provides a default implementation using simple string matching.+func (*DefaultIndexComparer) ExtractWhereClauseFromIndexDef(definition string) string {+ // This is the original hack method - kept for compatibility+ if definition == "" {+ return ""+ }++ // Find WHERE keyword (case insensitive)+ defUpper := strings.ToUpper(definition)+ whereIdx := strings.Index(defUpper, " WHERE ")++ if whereIdx == -1 {+ return ""+ }++ // Extract everything after WHERE, removing trailing semicolon if present+ whereClause := strings.TrimSpace(definition[whereIdx+7:]) // 7 = len(" WHERE ")+ whereClause = strings.TrimSuffix(whereClause, ";")+ return strings.TrimSpace(whereClause)+}++// Global registry for index comparers+var (+ indexComparers = make(map[storepb.Engine]IndexComparer)+ indexComparerMutex sync.RWMutex+)++// RegisterIndexComparer registers an index comparer for a specific engine.+func RegisterIndexComparer(engine storepb.Engine, comparer IndexComparer) {+ indexComparerMutex.Lock()+ defer indexComparerMutex.Unlock()+ indexComparers[engine] = comparer+}++// GetIndexComparer returns the registered index comparer for the given engine.+func GetIndexComparer(engine storepb.Engine) IndexComparer {+ indexComparerMutex.RLock()+ defer indexComparerMutex.RUnlock()++ if comparer, exists := indexComparers[engine]; exists {+ return comparer+ }++ // Return default comparer if no specific comparer is registered+ return &DefaultIndexComparer{}+}++func init() {+ // Register default comparers for engines that don't have specific implementations+ defaultComparer := &DefaultIndexComparer{}++ RegisterIndexComparer(storepb.Engine_MYSQL, defaultComparer)+ RegisterIndexComparer(storepb.Engine_TIDB, defaultComparer)+ RegisterIndexComparer(storepb.Engine_ORACLE, defaultComparer)+ RegisterIndexComparer(storepb.Engine_MSSQL, defaultComparer)+ RegisterIndexComparer(storepb.Engine_SQLITE, defaultComparer)+ RegisterIndexComparer(storepb.Engine_MONGODB, defaultComparer)+ RegisterIndexComparer(storepb.Engine_REDIS, defaultComparer)+ RegisterIndexComparer(storepb.Engine_SNOWFLAKE, defaultComparer)+ RegisterIndexComparer(storepb.Engine_CLICKHOUSE, defaultComparer)+}diff --git a/backend/plugin/schema/pg/ast/expression_comparer.go b/backend/plugin/schema/pg/ast/expression_comparer.goindex f349802529..eb316c8ef9 100644--- a/backend/plugin/schema/pg/ast/expression_comparer.go+++ b/backend/plugin/schema/pg/ast/expression_comparer.go@@ -104,7 +104,15 @@ func (c *PostgreSQLExpressionComparer) CompareExpressions(expr1, expr2 string) (normalized2 := c.normalizer.NormalizeExpression(ast2)// Compare normalized ASTs- return normalized1.Equals(normalized2), nil+ result := normalized1.Equals(normalized2)++ // If AST comparison fails, try fallback string comparison for special cases+ if !result {+ fallbackResult := c.compareExpressionsAsStrings(expr1, expr2)+ return fallbackResult, nil+ }++ return result, nil}// NormalizeExpression normalizes expression to canonical form@@ -141,7 +149,12 @@ func (c *PostgreSQLExpressionComparer) compareExpressionsAsStrings(expr1, expr2norm1 := c.normalizeStringExpression(expr1)norm2 := c.normalizeStringExpression(expr2)- return norm1 == norm2+ if norm1 == norm2 {+ return true+ }++ // Handle PostgreSQL implicit type casts+ return c.handleImplicitTypeCasts(norm1, norm2)}// normalizeStringExpression applies basic string normalization@@ -154,14 +167,159 @@ func (c *PostgreSQLExpressionComparer) normalizeStringExpression(expr string) stexpr = strings.ReplaceAll(expr, "public.", "")}- // Apply case normalization+ // Always normalize built-in types regardless of IgnoreSchemaPrefix setting+ // This is necessary because built-in types should never be schema-qualified+ expr = c.normalizeBuiltinTypes(expr)++ // Apply case normalization - but preserve string literal caseif !c.CaseSensitive {- expr = strings.ToLower(expr)+ expr = c.normalizeCasePreservingStringLiterals(expr)}return strings.TrimSpace(expr)}+// handleImplicitTypeCasts handles PostgreSQL implicit type casting scenarios+func (c *PostgreSQLExpressionComparer) handleImplicitTypeCasts(expr1, expr2 string) bool {+ // Handle JSONB implicit casts+ // '{}' should be equivalent to '{}'::jsonb+ if c.isJSONBImplicitCast(expr1, expr2) {+ return true+ }++ // Handle BIT literal format differences+ // B'1010' should be equivalent to '1010'::"bit"+ if c.isBitLiteralEquivalent(expr1, expr2) {+ return true+ }++ // Handle array type implicit casts (already covered by AST comparison)+ // 'ARRAY[]::TEXT[]' vs 'ARRAY[]::text[]'+ if c.isArrayTypeImplicitCast(expr1, expr2) {+ return true+ }++ return false+}++// isJSONBImplicitCast checks if two expressions represent the same JSONB value with/without explicit cast+func (*PostgreSQLExpressionComparer) isJSONBImplicitCast(expr1, expr2 string) bool {+ // Check if one has ::jsonb suffix and the other doesn't, but otherwise identical+ if strings.HasSuffix(expr1, "::jsonb") && !strings.HasSuffix(expr2, "::jsonb") {+ baseExpr1 := strings.TrimSuffix(expr1, "::jsonb")+ baseExpr1 = strings.TrimSpace(baseExpr1)+ return baseExpr1 == expr2+ }+ if strings.HasSuffix(expr2, "::jsonb") && !strings.HasSuffix(expr1, "::jsonb") {+ baseExpr2 := strings.TrimSuffix(expr2, "::jsonb")+ baseExpr2 = strings.TrimSpace(baseExpr2)+ return baseExpr2 == expr1+ }++ // Also handle JSON type casts (json vs jsonb)+ if strings.HasSuffix(expr1, "::json") && !strings.HasSuffix(expr2, "::json") && !strings.HasSuffix(expr2, "::jsonb") {+ baseExpr1 := strings.TrimSuffix(expr1, "::json")+ baseExpr1 = strings.TrimSpace(baseExpr1)+ return baseExpr1 == expr2+ }+ if strings.HasSuffix(expr2, "::json") && !strings.HasSuffix(expr1, "::json") && !strings.HasSuffix(expr1, "::jsonb") {+ baseExpr2 := strings.TrimSuffix(expr2, "::json")+ baseExpr2 = strings.TrimSpace(baseExpr2)+ return baseExpr2 == expr1+ }++ return false+}++// isBitLiteralEquivalent checks if two expressions represent the same BIT value in different formats+func (*PostgreSQLExpressionComparer) isBitLiteralEquivalent(expr1, expr2 string) bool {+ // Check for b'...' vs '...'::"bit" patterns (lowercase b due to AST normalization)+ if strings.HasPrefix(expr1, "b'") && strings.HasSuffix(expr1, "'") &&+ strings.Contains(expr2, ":") && strings.Contains(expr2, "bit") {+ // Extract bit value from b'...' format+ bitValue1 := expr1[2 : len(expr1)-1] // Remove b'...'++ // Extract bit value from '...'::"bit" format+ var bitValue2 string+ if strings.HasPrefix(expr2, "'") && strings.Contains(expr2, "':") {+ // Find the closing quote before the type cast+ endQuotePos := strings.Index(expr2[1:], "'")+ if endQuotePos > 0 {+ bitValue2 = expr2[1 : endQuotePos+1] // Extract between first ' and second '+ }+ }++ return bitValue1 == bitValue2 && bitValue2 != ""+ }++ // Check the reverse case: '...'::"bit" vs b'...'+ if strings.HasPrefix(expr2, "b'") && strings.HasSuffix(expr2, "'") &&+ strings.Contains(expr1, ":") && strings.Contains(expr1, "bit") {+ // Extract bit value from b'...' format+ bitValue2 := expr2[2 : len(expr2)-1] // Remove b'...'++ // Extract bit value from '...'::"bit" format+ var bitValue1 string+ if strings.HasPrefix(expr1, "'") && strings.Contains(expr1, "':") {+ // Find the closing quote before the type cast+ endQuotePos := strings.Index(expr1[1:], "'")+ if endQuotePos > 0 {+ bitValue1 = expr1[1 : endQuotePos+1] // Extract between first ' and second '+ }+ }++ return bitValue1 == bitValue2 && bitValue1 != ""+ }++ return false+}++// isArrayTypeImplicitCast checks if two expressions represent array types with different case+func (c *PostgreSQLExpressionComparer) isArrayTypeImplicitCast(expr1, expr2 string) bool {+ // This is primarily handled by the AST parser, but we can add string-level fallback+ if c.CaseSensitive {+ return false+ }++ // Check for array type patterns like ARRAY[]::TYPE[] vs ARRAY[]::type[]+ if strings.Contains(expr1, "ARRAY[]::") && strings.Contains(expr2, "ARRAY[]::") {+ return strings.EqualFold(expr1, expr2)+ }++ return false+}++// normalizeBuiltinTypes removes public schema qualification from built-in PostgreSQL types+func (*PostgreSQLExpressionComparer) normalizeBuiltinTypes(expr string) string {+ // List of PostgreSQL built-in types that should not be schema-qualified+ builtinTypes := []string{+ "varbit", "bit", "bit varying",+ "varchar", "character varying", "char", "character",+ "text", "numeric", "decimal", "int", "integer", "bigint", "smallint",+ "float", "real", "double precision", "boolean", "bool",+ "date", "time", "timestamp", "timestamptz", "interval",+ "uuid", "json", "jsonb", "bytea", "inet", "cidr",+ "point", "line", "lseg", "box", "path", "polygon", "circle",+ "int4range", "int8range", "numrange", "tsrange", "tstzrange", "daterange",+ }++ for _, builtinType := range builtinTypes {+ // Replace public.typename with typename+ publicQualified := "public." + builtinType+ if strings.Contains(expr, publicQualified) {+ expr = strings.ReplaceAll(expr, publicQualified, builtinType)+ }++ // Also handle quoted versions+ quotedPublicQualified := "\"public\"." + builtinType+ if strings.Contains(expr, quotedPublicQualified) {+ expr = strings.ReplaceAll(expr, quotedPublicQualified, builtinType)+ }+ }++ return expr+}+// CompareExpressionLists compares two lists of expressionsfunc (c *PostgreSQLExpressionComparer) CompareExpressionLists(exprs1, exprs2 []string) (bool, error) {if len(exprs1) != len(exprs2) {@@ -403,6 +561,100 @@ func CompareExpressionsSemantically(expr1, expr2 string) bool {return result}+// normalizeCasePreservingStringLiterals normalizes case while preserving string literal content+func (*PostgreSQLExpressionComparer) normalizeCasePreservingStringLiterals(expr string) string {+ // This is a production-grade implementation that preserves:+ // 1. Single-quoted string literal case ('...')+ // 2. Double-quoted identifier case ("...")+ // while normalizing unquoted identifiers, keywords, and function names++ result := make([]rune, 0, len(expr))+ runes := []rune(expr)+ i := 0++ for i < len(runes) {+ char := runes[i]++ // Handle single-quoted string literals+ if char == '\'' {+ // Preserve the entire string literal including quotes+ result = append(result, char) // opening quote+ i++++ // Copy content until closing quote, handling escaped quotes+ for i < len(runes) {+ char = runes[i]+ result = append(result, char)++ if char == '\'' {+ // Check if this is an escaped quote ''+ if i+1 < len(runes) && runes[i+1] == '\'' {+ // Escaped quote, copy both quotes+ i+++ result = append(result, runes[i])+ } else {+ // End of string literal+ break+ }+ }+ i+++ }+ } else if char == '"' {+ // Handle double-quoted identifiers (case-sensitive)+ // Preserve the entire quoted identifier including quotes+ result = append(result, char) // opening quote+ i++++ // Copy content until closing quote, handling escaped quotes+ for i < len(runes) {+ char = runes[i]+ result = append(result, char)++ if char == '"' {+ // Check if this is an escaped quote ""+ if i+1 < len(runes) && runes[i+1] == '"' {+ // Escaped quote, copy both quotes+ i+++ result = append(result, runes[i])+ } else {+ // End of quoted identifier+ break+ }+ }+ i+++ }+ } else {+ // For non-quoted parts, apply case normalization+ result = append(result, char)+ }+ i+++ }++ // Apply case normalization to the parts outside quoted literals/identifiers+ finalResult := string(result)++ // Process both single and double quotes to preserve their content+ // First handle single quotes (string literals)+ singleQuoteParts := strings.Split(finalResult, "'")+ for i := 0; i < len(singleQuoteParts); i++ {+ if i%2 == 0 {+ // Outside single quotes - now check for double quotes+ doubleQuoteParts := strings.Split(singleQuoteParts[i], `"`)+ for j := 0; j < len(doubleQuoteParts); j++ {+ if j%2 == 0 {+ // Outside both single and double quotes - apply case normalization+ doubleQuoteParts[j] = strings.ToLower(doubleQuoteParts[j])+ }+ // Inside double quotes - preserve case+ }+ singleQuoteParts[i] = strings.Join(doubleQuoteParts, `"`)+ }+ // Inside single quotes - preserve case+ }++ return strings.Join(singleQuoteParts, "'")+}+// CreatePostgreSQLExpressionComparer creates a PostgreSQL expression comparer with default settingsfunc CreatePostgreSQLExpressionComparer() ExpressionComparer {return NewPostgreSQLExpressionComparer()diff --git a/backend/plugin/schema/pg/ast/expression_comparer_test.go b/backend/plugin/schema/pg/ast/expression_comparer_test.goindex 7e6060fca0..1727670b9f 100644--- a/backend/plugin/schema/pg/ast/expression_comparer_test.go+++ b/backend/plugin/schema/pg/ast/expression_comparer_test.go@@ -101,10 +101,22 @@ func TestPostgreSQLExpressionComparer_CompareExpressions(t *testing.T) {expr2: "column_name",expected: true,},+ {+ name: "where condition with parentheses",+ expr1: "text_col IS NOT NULL",+ expr2: "(text_col IS NOT NULL)",+ expected: true,+ },+ {+ name: "complex where condition with parentheses",+ expr1: "column > 0 AND status = 'active'",+ expr2: "(column > 0 AND status = 'active')",+ expected: true,+ },- // Function call tests+ // Function call tests - basic cases{- name: "function calls",+ name: "function calls case insensitive",expr1: "UPPER(column)",expr2: "upper(column)",expected: true,@@ -122,6 +134,58 @@ func TestPostgreSQLExpressionComparer_CompareExpressions(t *testing.T) {expected: false,},+ // Quoted vs unquoted function names - PostgreSQL identifier normalization+ {+ name: "unquoted LEFT vs quoted lowercase left - EQUAL",+ expr1: "LEFT(text_col, 50)",+ expr2: "\"left\"(text_col, 50)",+ expected: true,+ },+ {+ name: "unquoted left vs quoted lowercase left - EQUAL",+ expr1: "left(text_col, 50)",+ expr2: "\"left\"(text_col, 50)",+ expected: true,+ },+ {+ name: "unquoted LEFT vs quoted uppercase LEFT - NOT EQUAL",+ expr1: "LEFT(text_col, 50)",+ expr2: "\"LEFT\"(text_col, 50)",+ expected: false,+ },+ {+ name: "unquoted left vs quoted uppercase LEFT - NOT EQUAL",+ expr1: "left(text_col, 50)",+ expr2: "\"LEFT\"(text_col, 50)",+ expected: false,+ },+ {+ name: "unquoted LEFT vs quoted mixed case Left - NOT EQUAL",+ expr1: "LEFT(text_col, 50)",+ expr2: "\"Left\"(text_col, 50)",+ expected: false,+ },+ {+ name: "quoted function with complex expression",+ expr1: "SUBSTRING(column FROM 1 FOR 10)",+ expr2: "\"substring\"(column FROM 1 FOR 10)",+ expected: true,+ },++ // Additional identifier normalization tests+ {+ name: "unquoted Column_Name vs quoted lowercase column_name - EQUAL",+ expr1: "Column_Name",+ expr2: "\"column_name\"",+ expected: true,+ },+ {+ name: "unquoted Column_Name vs quoted original Column_Name - NOT EQUAL",+ expr1: "Column_Name",+ expr2: "\"Column_Name\"",+ expected: false,+ },+// Complex expression tests{name: "complex equality expression",@@ -136,6 +200,50 @@ func TestPostgreSQLExpressionComparer_CompareExpressions(t *testing.T) {expected: true,},+ // PostgreSQL type cast tests+ {+ name: "JSONB implicit cast",+ expr1: "'{}'",+ expr2: "'{}'::jsonb",+ expected: true,+ },+ {+ name: "JSONB explicit cast both ways",+ expr1: "'{\"key\": \"value\"}'::jsonb",+ expr2: "'{\"key\": \"value\"}'::jsonb",+ expected: true,+ },+ {+ name: "Array type cast case insensitive",+ expr1: "ARRAY[]::TEXT[]",+ expr2: "ARRAY[]::text[]",+ expected: true,+ },+ {+ name: "BIT literal formats",+ expr1: "B'1010'",+ expr2: "'1010'::\"bit\"",+ expected: true,+ },+ {+ name: "BIT literal formats reverse",+ expr1: "'0000'::\"bit\"",+ expr2: "B'0000'",+ expected: true,+ },+ {+ name: "VARBIT schema qualification",+ expr1: "varbit(16)",+ expr2: "public.varbit(16)",+ expected: true,+ },+ {+ name: "BIT schema qualification",+ expr1: "bit(32)",+ expr2: "public.bit(32)",+ expected: true,+ },+// Literal tests{name: "string literals",diff --git a/backend/plugin/schema/pg/ast/expression_normalizer.go b/backend/plugin/schema/pg/ast/expression_normalizer.goindex 13c7f85365..18c7d562a4 100644--- a/backend/plugin/schema/pg/ast/expression_normalizer.go+++ b/backend/plugin/schema/pg/ast/expression_normalizer.go@@ -91,9 +91,22 @@ func (v *normalizationVisitor) VisitLiteral(expr *LiteralExpr) any {// VisitBinaryOp normalizes binary operation expressionsfunc (v *normalizationVisitor) VisitBinaryOp(expr *BinaryOpExpr) any {left := v.normalizeChild(expr.Left)- right := v.normalizeChild(expr.Right)operator := v.normalizeOperator(expr.Operator)+ // Special handling for type cast operator+ var right ExpressionAST+ if operator == "::" {+ // For type cast, the right operand should be normalized as a type name+ right = v.normalizeChildAsType(expr.Right)++ // Check if this is a redundant type cast that can be removed+ if v.isRedundantTypeCast(left, right) {+ return left // Return the left operand without the cast+ }+ } else {+ right = v.normalizeChild(expr.Right)+ }+// For commutative operators, ensure consistent orderingif isCommutativeOperator(operator) && v.shouldSwapOperands(left, right) {left, right = right, left@@ -167,6 +180,25 @@ func (v *normalizationVisitor) normalizeChild(expr ExpressionAST) ExpressionASTreturn expr}+// normalizeChildAsType normalizes a child expression as a type name+func (v *normalizationVisitor) normalizeChildAsType(expr ExpressionAST) ExpressionAST {+ if expr == nil {+ return nil+ }++ // If it's a literal, treat it as a type name+ if literal, ok := expr.(*LiteralExpr); ok {+ normalizedValue := v.normalizeTypeName(literal.Value)+ return &LiteralExpr{+ Value: normalizedValue,+ ValueType: literal.ValueType,+ }+ }++ // Otherwise, normalize normally+ return v.normalizeChild(expr)+}+// normalizeSchema normalizes schema namesfunc (v *normalizationVisitor) normalizeSchema(schema string) string {if schema == "" {@@ -181,7 +213,9 @@ func (v *normalizationVisitor) normalizeSchema(schema string) string {return v.normalizeIdentifier(schema)}-// normalizeIdentifier normalizes identifier names+// normalizeIdentifier normalizes identifier names according to PostgreSQL rules:+// - Unquoted identifiers are case-insensitive and folded to lowercase+// - Quoted identifiers preserve their original case but without quotes in the IRfunc (v *normalizationVisitor) normalizeIdentifier(identifier string) string {if identifier == "" {return ""@@ -189,20 +223,14 @@ func (v *normalizationVisitor) normalizeIdentifier(identifier string) string {// Handle quoted identifiersif v.isQuotedIdentifier(identifier) {- // Remove quotes and get the actual identifier+ // Remove quotes and preserve the original case contentunquoted := identifier[1 : len(identifier)-1]-- // In PostgreSQL, if a quoted identifier is all lowercase,- // it's equivalent to the unquoted version- if strings.ToLower(unquoted) == unquoted {- // If quoted identifier is all lowercase, normalize as unquoted- return v.normalizeUnquotedIdentifier(unquoted)- }-- // Otherwise, preserve the quoted form for case-sensitive comparison- return identifier+ // Handle escaped quotes within the identifier+ unquoted = strings.ReplaceAll(unquoted, `""`, `"`)+ return unquoted}+ // For unquoted identifiers, apply PostgreSQL case folding (to lowercase)return v.normalizeUnquotedIdentifier(identifier)}@@ -216,19 +244,15 @@ func (v *normalizationVisitor) normalizeUnquotedIdentifier(identifier string) streturn strings.ToLower(identifier)}-// normalizeFunctionName normalizes function names+// normalizeFunctionName normalizes function names using PostgreSQL standard rules+// Same logic as normalizeIdentifier - function names are identifiersfunc (v *normalizationVisitor) normalizeFunctionName(name string) string {- // Handle quoted function names - preserve exact case- if v.isQuotedIdentifier(name) {- return name- }-- // Function names are case-insensitive in PostgreSQL for unquoted names- return strings.ToLower(name)+ // Function names follow the same identifier normalization rules+ return v.normalizeIdentifier(name)}// normalizeLiteral normalizes literal values-func (*normalizationVisitor) normalizeLiteral(value, valueType string) string {+func (v *normalizationVisitor) normalizeLiteral(value, valueType string) string {switch strings.ToLower(valueType) {case "boolean":return strings.ToUpper(value) // TRUE/FALSE@@ -240,11 +264,22 @@ func (*normalizationVisitor) normalizeLiteral(value, valueType string) string {case "number":// Normalize numeric literals - could handle leading zeros, etc.return value+ case "type":+ // Type names in cast expressions should be case-insensitive+ return v.normalizeTypeName(value)default:return value}}+// normalizeTypeName normalizes type names for case-insensitive comparison+func (v *normalizationVisitor) normalizeTypeName(typeName string) string {+ if v.normalizer.CaseSensitive {+ return typeName+ }+ return strings.ToLower(typeName)+}+// normalizeOperator normalizes operatorsfunc (*normalizationVisitor) normalizeOperator(operator string) string {return normalizeOperator(operator) // Use the helper from expression_ast.go@@ -372,3 +407,43 @@ func SortStringList(strs []string) []string {return sorted}++// isRedundantTypeCast checks if a type cast can be safely removed+// This handles cases where PostgreSQL implicit casting makes explicit casts unnecessary+func (v *normalizationVisitor) isRedundantTypeCast(leftExpr, typeExpr ExpressionAST) bool {+ // Check if left is a string literal and right is a JSON/JSONB type+ if literalExpr, ok := leftExpr.(*LiteralExpr); ok {+ if typeIdent, ok := typeExpr.(*IdentifierExpr); ok {+ typeName := strings.ToLower(typeIdent.Name)++ // For JSON-like literals cast to jsonb/json, the cast is redundant+ // because PostgreSQL will implicitly cast string literals to JSON types+ if (typeName == "jsonb" || typeName == "json") &&+ literalExpr.ValueType == "string" &&+ v.isJSONLiteral(literalExpr.Value) {+ return true+ }+ }+ }++ return false+}++// isJSONLiteral checks if a string value looks like JSON+func (*normalizationVisitor) isJSONLiteral(value string) bool {+ // Remove quotes if present+ if len(value) >= 2 && value[0] == '\'' && value[len(value)-1] == '\'' {+ value = value[1 : len(value)-1]+ }++ // Check for simple JSON patterns+ trimmed := strings.TrimSpace(value)+ return (strings.HasPrefix(trimmed, "{") && strings.HasSuffix(trimmed, "}")) ||+ (strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]")) ||+ trimmed == "null" ||+ trimmed == "true" ||+ trimmed == "false" ||+ (len(trimmed) > 0 && (trimmed[0] == '"' ||+ (trimmed[0] >= '0' && trimmed[0] <= '9') ||+ trimmed[0] == '-'))+}diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.goindex a58b743902..ad9c661d42 100644--- a/backend/plugin/schema/pg/generate_migration.go+++ b/backend/plugin/schema/pg/generate_migration.go@@ -3,6 +3,7 @@ package pgimport ("fmt""slices"+ "strconv""strings""github.com/antlr4-go/antlr/v4"@@ -11,6 +12,7 @@ import (storepb "github.com/bytebase/bytebase/backend/generated-go/store"parserbase "github.com/bytebase/bytebase/backend/plugin/parser/base""github.com/bytebase/bytebase/backend/plugin/schema"+ "github.com/bytebase/bytebase/backend/plugin/schema/pg/ast")func init() {@@ -980,7 +982,7 @@ func generateAlterColumn(schemaName, tableName string, colDiff *schema.ColumnDif// If type changed, alter the column typeif colDiff.OldColumn.Type != colDiff.NewColumn.Type {- writeAlterColumnType(&buf, schemaName, tableName, colDiff.NewColumn.Name, colDiff.NewColumn.Type)+ writeAlterColumnType(&buf, schemaName, tableName, colDiff.NewColumn.Name, colDiff.OldColumn.Type, colDiff.NewColumn.Type)}// If nullability changed@@ -1030,6 +1032,25 @@ func defaultValuesEqual(col1, col2 *storepb.ColumnMetadata) bool {// Check default valuedef1 := col1.GetDefault()def2 := col2.GetDefault()++ // Use semantic comparison for default values+ // This handles cases like 'ARRAY[]::TEXT[]' vs 'ARRAY[]::text[]'+ if def1 == def2 {+ return true+ }++ // If they're not identical strings, try semantic comparison+ if def1 != "" || def2 != "" {+ // Use the expression comparer from the ast package+ comparer := ast.NewPostgreSQLExpressionComparer()+ equal, err := comparer.CompareExpressions(def1, def2)+ if err != nil {+ // If comparison fails, fall back to string comparison+ return def1 == def2+ }+ return equal+ }+return def1 == def2}@@ -1227,7 +1248,92 @@ func writeAddColumn(out *strings.Builder, schema, table string, column *storepb._, _ = out.WriteString("\n")}-func writeAlterColumnType(out *strings.Builder, schema, table, column, newType string) {+// requiresExplicitCasting determines if a PostgreSQL type conversion requires a USING clause+func requiresExplicitCasting(oldType, newType string) bool {+ // Types are already normalized by get_database_metadata.go, no need to normalize again++ // Extract base types without parameters+ oldBaseType := extractBaseType(oldType)+ newBaseType := extractBaseType(newType)++ // If same base type, usually no USING clause needed (except for precision reductions)+ if oldBaseType == newBaseType {+ return requiresUsingForSameType(oldType, newType)+ }++ // Define incompatible type conversions that require USING clause+ incompatibleConversions := map[string][]string{+ "text": {"integer", "numeric", "real", "double precision", "smallint", "bigint", "boolean"},+ "character varying": {"integer", "numeric", "real", "double precision", "smallint", "bigint", "boolean"},+ "character": {"integer", "numeric", "real", "double precision", "smallint", "bigint", "boolean"},+ "jsonb": {"text", "character varying", "character"},+ "json": {"text", "character varying", "character"},+ "integer[]": {"text", "character varying", "character"},+ "text[]": {"text", "character varying", "character"},+ "bigint": {"smallint", "integer"}, // Potential overflow+ "double precision": {"real"}, // Precision loss+ "timestamp with time zone": {"date"}, // Time component loss+ "timestamp without time zone": {"date"}, // Time component loss+ "numeric": {"integer", "smallint", "bigint", "real", "double precision"}, // When precision specified+ }++ if targets, exists := incompatibleConversions[oldBaseType]; exists {+ for _, target := range targets {+ if target == newBaseType {+ return true+ }+ }+ }++ return false+}++// extractBaseType removes precision/scale parameters from PostgreSQL types+func extractBaseType(typeName string) string {+ // Handle common patterns: numeric(10,2) -> numeric, varchar(100) -> character varying+ if idx := strings.Index(typeName, "("); idx != -1 {+ return strings.TrimSpace(typeName[:idx])+ }+ return typeName+}++// requiresUsingForSameType checks if same base type requires USING (e.g., precision reductions)+func requiresUsingForSameType(oldType, newType string) bool {+ oldBase := extractBaseType(oldType)+ newBase := extractBaseType(newType)++ if oldBase != newBase {+ return false+ }++ // For character varying, check if reducing length significantly+ if strings.Contains(oldType, "character varying") {+ oldLen := extractLength(oldType)+ newLen := extractLength(newType)+ if oldLen > 0 && newLen > 0 && oldLen > newLen*2 {+ return true // Significant reduction might truncate data+ }+ }++ return false+}++// extractLength extracts length parameter from varchar(n) or char(n)+func extractLength(typeName string) int {+ start := strings.Index(typeName, "(")+ end := strings.Index(typeName, ")")+ if start == -1 || end == -1 || end <= start {+ return 0+ }++ lengthStr := strings.TrimSpace(typeName[start+1 : end])+ if length, err := strconv.Atoi(lengthStr); err == nil {+ return length+ }+ return 0+}++func writeAlterColumnType(out *strings.Builder, schema, table, column, oldType, newType string) {_, _ = out.WriteString(`ALTER TABLE "`)_, _ = out.WriteString(schema)_, _ = out.WriteString(`"."`)@@ -1236,6 +1342,15 @@ func writeAlterColumnType(out *strings.Builder, schema, table, column, newType s_, _ = out.WriteString(column)_, _ = out.WriteString(`" TYPE `)_, _ = out.WriteString(newType)++ // Add USING clause for incompatible type conversions+ if requiresExplicitCasting(oldType, newType) {+ _, _ = out.WriteString(` USING "`)+ _, _ = out.WriteString(column)+ _, _ = out.WriteString(`"::`)+ _, _ = out.WriteString(newType)+ }+_, _ = out.WriteString(`;`)_, _ = out.WriteString("\n")}diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.goindex a943ed736a..70940a18b5 100644--- a/backend/plugin/schema/pg/get_database_metadata.go+++ b/backend/plugin/schema/pg/get_database_metadata.go@@ -325,7 +325,7 @@ func (e *metadataExtractor) extractSchemaAndTableName(ctx parser.IQualified_namereturn e.currentSchema, ""}- // Debug: try direct text extraction first, since normalize functions seem problematic+ // Try direct text extraction for reliable parsingrawText := ctx.GetText()if rawText != "" {// Handle schema.table format@@ -471,7 +471,7 @@ func extractTypeName(ctx parser.ITypenameContext) string {// Convert to lowercase to match sync.go outputtypeName = strings.ToLower(typeName)- return normalizePostgreSQLType(typeName)+ return NormalizePostgreSQLType(typeName)}// getPostgreSQLArrayTypeName maps base types to their PostgreSQL internal array type names@@ -635,7 +635,7 @@ func getPostgreSQLArrayTypeName(baseType string) string {}// normalizePostgreSQLType normalizes PostgreSQL type names to match sync.go output-func normalizePostgreSQLType(typeName string) string {+func NormalizePostgreSQLType(typeName string) string {// Remove extra whitespacetypeName = strings.TrimSpace(typeName)@@ -656,7 +656,7 @@ func normalizePostgreSQLType(typeName string) string {}// For unknown types, use the old logic as fallback- normalizedBase := normalizePostgreSQLType(baseType)+ normalizedBase := NormalizePostgreSQLType(baseType)return "_" + normalizedBase}@@ -682,13 +682,40 @@ func normalizePostgreSQLType(typeName string) string {// Handle timestamp without explicit timezoneif typeName == "timestamp" {- return "timestamp without time zone"+ return "timestamp(6) without time zone" // PostgreSQL default precision is 6+ }+ // Handle timestamp with time zone (no precision specified)+ if typeName == "timestamp with time zone" {+ return "timestamp(6) with time zone" // PostgreSQL default precision is 6+ }+ // Handle timestamp with precision (preserve precision but add timezone info)+ if strings.HasPrefix(typeName, "timestamp(") && strings.HasSuffix(typeName, ")") {+ // Extract precision part: timestamp(3) -> (3)+ precision := typeName[9:] // Get "(3)" part+ return "timestamp" + precision + " without time zone"+ }+ // Handle time without explicit timezone (PostgreSQL default)+ if typeName == "time" {+ return "time(6) without time zone" // PostgreSQL default precision is 6+ }+ // Handle time with time zone (no precision specified)+ if typeName == "time with time zone" {+ return "time(6) with time zone" // PostgreSQL default precision is 6+ }+ // Handle time with precision (preserve precision but add timezone info)+ if strings.HasPrefix(typeName, "time(") && strings.HasSuffix(typeName, ")") {+ // Extract precision part: time(6) -> (6)+ precision := typeName[4:] // Get "(6)" part+ return "time" + precision + " without time zone"}- // Handle decimal -> numeric (sync.go reports decimal as numeric without precision)+ // Handle decimal -> numeric (preserve precision information)if strings.HasPrefix(typeName, "decimal(") {- // sync.go returns just "numeric" without precision for decimal types- return "numeric"+ // Convert decimal(p,s) to numeric(p,s) while preserving precision+ // Also normalize spacing to match sync.go format (remove spaces around commas)+ precisionPart := typeName[7:] // Get "(p, s)" or "(p,s)" part+ precisionPart = strings.ReplaceAll(precisionPart, " ", "") // Remove all spaces to match sync.go format+ return "numeric" + precisionPart}if typeName == "decimal" {return "numeric"@@ -711,9 +738,11 @@ func normalizePostgreSQLType(typeName string) string {case "char":return "character"case "timestamptz":- return "timestamp with time zone"+ return "timestamp(6) with time zone" // PostgreSQL default precision is 6case "timetz":- return "time with time zone"+ return "time(6) with time zone" // PostgreSQL default precision is 6+ case "varbit":+ return "bit varying"default:// Return type as-is for unrecognized types}@@ -723,6 +752,19 @@ func normalizePostgreSQLType(typeName string) string {return "character" + typeName[4:]}+ // Handle varbit with precision: varbit(n) -> bit varying(n)+ if strings.HasPrefix(typeName, "varbit(") {+ return "bit varying" + typeName[6:] // Replace "varbit" with "bit varying"+ }++ // For all remaining types with precision/scale parameters, normalize spacing to match sync.go format+ // This handles cases like "numeric(10, 2)" -> "numeric(10,2)" to match database sync output+ if strings.Contains(typeName, "(") && strings.Contains(typeName, ")") {+ // Remove spaces around commas in type specifications to match sync.go format+ typeName = strings.ReplaceAll(typeName, ", ", ",")+ typeName = strings.ReplaceAll(typeName, " ,", ",")+ }+return typeName}@@ -738,15 +780,15 @@ func (*metadataExtractor) extractTypeNameWithSchema(ctx parser.ITypenameContext,// Check if this is a built-in PostgreSQL type or an array type before normalization// Array types should always go through normalization regardless of their base type- if isBuiltInType(rawTypeName) || isBuiltInType(normalizePostgreSQLType(rawTypeName)) || strings.HasSuffix(rawTypeName, "[]") {+ if isBuiltInType(rawTypeName) || isBuiltInType(NormalizePostgreSQLType(rawTypeName)) || strings.HasSuffix(rawTypeName, "[]") {// For built-in types and array types, return the normalized version- return normalizePostgreSQLType(rawTypeName)+ return NormalizePostgreSQLType(rawTypeName)}// Check if the type already has a schema prefixif strings.Contains(rawTypeName, ".") {// It's already schema-qualified, just normalize it- return normalizePostgreSQLType(rawTypeName)+ return NormalizePostgreSQLType(rawTypeName)}// For custom types (like enums), add the schema prefix to the raw type name@@ -820,7 +862,7 @@ func isBuiltInType(typeName string) bool {"bytea": true,// Bit string types- "bit": true, "bit varying": true,+ "bit": true, "bit varying": true, "varbit": true,// Network address types"inet": true, "cidr": true, "macaddr": true, "macaddr8": true,@@ -1084,8 +1126,14 @@ func (e *metadataExtractor) extractTableConstraint(ctx parser.ITableconstraintCocase constraintElem.CHECK() != nil:// Check constraint- check := &storepb.CheckConstraintMetadata{- Name: constraintName,+ check := &storepb.CheckConstraintMetadata{}+ // Generate constraint name if not provided (PostgreSQL auto-generates names)+ if constraintName != "" {+ check.Name = constraintName+ } else {+ // For table-level check constraints, use {table}_check_{index} format+ checkIndex := len(table.CheckConstraints) + 1+ check.Name = fmt.Sprintf("%s_check_%d", table.Name, checkIndex)}if expr := constraintElem.A_expr(); expr != nil {rawExpression := ctx.GetParser().GetTokenStream().GetTextFromRuleContext(expr)diff --git a/backend/plugin/schema/pg/index_comparer.go b/backend/plugin/schema/pg/index_comparer.gonew file mode 100644index 0000000000..458b0c5f8d--- /dev/null+++ b/backend/plugin/schema/pg/index_comparer.go@@ -0,0 +1,234 @@+package pg++import (+ "strings"++ "github.com/antlr4-go/antlr/v4"+ pgparser "github.com/bytebase/parser/postgresql"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+)++func init() {+ // Register PostgreSQL-specific index comparer+ schema.RegisterIndexComparer(storepb.Engine_POSTGRES, &PostgreSQLIndexComparer{})+}++// PostgreSQLIndexComparer provides PostgreSQL-specific index comparison logic.+type PostgreSQLIndexComparer struct{}++// Ensure PostgreSQLIndexComparer implements the IndexComparer interface+var _ schema.IndexComparer = &PostgreSQLIndexComparer{}++// CompareIndexWhereConditions compares WHERE conditions from PostgreSQL index definitions using AST parsing.+func (c *PostgreSQLIndexComparer) CompareIndexWhereConditions(def1, def2 string) bool {+ whereClause1 := c.ExtractWhereClauseFromIndexDef(def1)+ whereClause2 := c.ExtractWhereClauseFromIndexDef(def2)++ // If both have no WHERE clause, they're equal+ if whereClause1 == "" && whereClause2 == "" {+ return true+ }++ // If only one has WHERE clause, they're different+ if whereClause1 == "" || whereClause2 == "" {+ return false+ }++ // Use expression comparer for semantic comparison+ return schema.CompareExpressionsSemantically(storepb.Engine_POSTGRES, whereClause1, whereClause2)+}++// ExtractWhereClauseFromIndexDef extracts the WHERE clause from a CREATE INDEX statement using ANTLR AST parsing.+func (*PostgreSQLIndexComparer) ExtractWhereClauseFromIndexDef(definition string) string {+ if definition == "" {+ return ""+ }++ // Parse the CREATE INDEX statement using ANTLR parser+ inputStream := antlr.NewInputStream(definition)+ lexer := pgparser.NewPostgreSQLLexer(inputStream)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)+ parser := pgparser.NewPostgreSQLParser(stream)++ // Disable error reporting for cleaner parsing+ parser.RemoveErrorListeners()++ // Parse as root statement+ tree := parser.Root()++ // Use visitor to extract WHERE clause from IndexStmt+ extractor := &indexWhereExtractor{}+ extractor.Visit(tree)++ return extractor.whereClause+}++// indexWhereExtractor is a visitor that extracts WHERE clauses from CREATE INDEX statements.+type indexWhereExtractor struct {+ *pgparser.BasePostgreSQLParserVisitor+ whereClause string+}++// Visit implements the visitor pattern to walk the AST.+func (e *indexWhereExtractor) Visit(tree antlr.ParseTree) {+ switch ctx := tree.(type) {+ case *pgparser.IndexstmtContext:+ e.visitIndexStmt(ctx)+ default:+ // Recursively visit children+ if tree != nil {+ for i := 0; i < tree.GetChildCount(); i++ {+ child := tree.GetChild(i)+ if parseTree, ok := child.(antlr.ParseTree); ok {+ e.Visit(parseTree)+ }+ }+ }+ }+}++// visitIndexStmt extracts the WHERE clause from an IndexStmt AST node.+func (e *indexWhereExtractor) visitIndexStmt(ctx *pgparser.IndexstmtContext) {+ if ctx == nil {+ return+ }++ // Get the WHERE clause from the IndexStmt+ whereClauseCtx := ctx.Where_clause()+ if whereClauseCtx == nil {+ e.whereClause = ""+ return+ }++ // Extract the expression from the WHERE clause (excluding the WHERE keyword)+ aExprCtx := whereClauseCtx.A_expr()+ if aExprCtx == nil {+ e.whereClause = ""+ return+ }++ // Get the original text of the expression+ e.whereClause = e.getTextFromContext(aExprCtx)+}++// getTextFromContext extracts the original source text from a parse tree context.+func (*indexWhereExtractor) getTextFromContext(ctx antlr.ParserRuleContext) string {+ if ctx == nil {+ return ""+ }++ start := ctx.GetStart()+ stop := ctx.GetStop()+ if start == nil || stop == nil {+ return ""+ }++ input := start.GetInputStream()+ if input == nil {+ return ""+ }++ startIndex := start.GetStart()+ stopIndex := stop.GetStop()++ if startIndex < 0 || stopIndex < 0 || stopIndex < startIndex {+ return ""+ }++ // Extract the original text from the input stream+ return input.GetText(startIndex, stopIndex)+}++// IndexDefinition represents the parsed structure of a CREATE INDEX statement.+type IndexDefinition struct {+ IndexName string+ TableName string+ Unique bool+ Method string // btree, gin, gist, etc.+ Expressions []string+ WhereClause string+}++// ParseIndexDefinition parses a complete CREATE INDEX statement and returns structured information.+func (c *PostgreSQLIndexComparer) ParseIndexDefinition(definition string) (*IndexDefinition, error) {+ if definition == "" {+ return nil, nil+ }++ result := &IndexDefinition{+ WhereClause: c.ExtractWhereClauseFromIndexDef(definition),+ }++ // Parse the CREATE INDEX statement using ANTLR parser+ inputStream := antlr.NewInputStream(definition)+ lexer := pgparser.NewPostgreSQLLexer(inputStream)+ stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)+ parser := pgparser.NewPostgreSQLParser(stream)++ // Disable error reporting for cleaner parsing+ parser.RemoveErrorListeners()++ // Parse as root statement+ tree := parser.Root()++ // Use visitor to extract structured information from IndexStmt+ extractor := &indexDefinitionExtractor{result: result}+ extractor.Visit(tree)++ return result, nil+}++// indexDefinitionExtractor is a visitor that extracts structured information from CREATE INDEX statements.+type indexDefinitionExtractor struct {+ *pgparser.BasePostgreSQLParserVisitor+ result *IndexDefinition+}++// Visit implements the visitor pattern to walk the AST.+func (e *indexDefinitionExtractor) Visit(tree antlr.ParseTree) {+ switch ctx := tree.(type) {+ case *pgparser.IndexstmtContext:+ e.visitIndexStmtForDefinition(ctx)+ default:+ // Recursively visit children+ if tree != nil {+ for i := 0; i < tree.GetChildCount(); i++ {+ child := tree.GetChild(i)+ if parseTree, ok := child.(antlr.ParseTree); ok {+ e.Visit(parseTree)+ }+ }+ }+ }+}++// visitIndexStmtForDefinition extracts structured information from an IndexStmt AST node.+func (e *indexDefinitionExtractor) visitIndexStmtForDefinition(ctx *pgparser.IndexstmtContext) {+ if ctx == nil || e.result == nil {+ return+ }++ // Extract UNIQUE flag+ if ctx.Opt_unique() != nil {+ e.result.Unique = true+ }++ // Extract index name+ if ctx.Name() != nil {+ e.result.IndexName = ctx.Name().GetText()+ }++ // Extract table name from relation_expr+ if ctx.Relation_expr() != nil {+ e.result.TableName = ctx.Relation_expr().GetText()+ }++ // Extract access method+ if ctx.Access_method_clause() != nil {+ e.result.Method = strings.ToLower(ctx.Access_method_clause().GetText())+ }++ // WHERE clause is already extracted in the result initialization+}diff --git a/backend/plugin/schema/pg/index_comparer_test.go b/backend/plugin/schema/pg/index_comparer_test.gonew file mode 100644index 0000000000..ffa5430124--- /dev/null+++ b/backend/plugin/schema/pg/index_comparer_test.go@@ -0,0 +1,165 @@+package pg++import (+ "testing"+)++func TestPostgreSQLIndexComparer_ExtractWhereClauseFromIndexDef(t *testing.T) {+ comparer := &PostgreSQLIndexComparer{}++ tests := []struct {+ name string+ indexDef string+ expectedWhere string+ }{+ {+ name: "Index with simple WHERE clause",+ indexDef: "CREATE INDEX idx_users_active ON users (email) WHERE active = true",+ expectedWhere: "active = true",+ },+ {+ name: "Index with complex WHERE clause",+ indexDef: "CREATE INDEX idx_orders_status ON orders (customer_id) WHERE status IN ('pending', 'processing')",+ expectedWhere: "status IN ('pending', 'processing')",+ },+ {+ name: "Index with function in WHERE clause",+ indexDef: `CREATE INDEX idx_text_search ON articles (title) WHERE "length"(content) > 100`,+ expectedWhere: `"length"(content) > 100`,+ },+ {+ name: "Index without WHERE clause",+ indexDef: "CREATE INDEX idx_users_email ON users (email)",+ expectedWhere: "",+ },+ {+ name: "UNIQUE index with WHERE clause",+ indexDef: "CREATE UNIQUE INDEX idx_users_email_active ON users (email) WHERE active = true",+ expectedWhere: "active = true",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result := comparer.ExtractWhereClauseFromIndexDef(tt.indexDef)+ if result != tt.expectedWhere {+ t.Errorf("ExtractWhereClauseFromIndexDef() = %q, want %q", result, tt.expectedWhere)+ }+ })+ }+}++func TestPostgreSQLIndexComparer_CompareIndexWhereConditions(t *testing.T) {+ comparer := &PostgreSQLIndexComparer{}++ tests := []struct {+ name string+ def1 string+ def2 string+ expected bool+ }{+ {+ name: "Same WHERE conditions",+ def1: "CREATE INDEX idx1 ON table1 (col1) WHERE active = true",+ def2: "CREATE INDEX idx2 ON table2 (col2) WHERE active = true",+ expected: true,+ },+ {+ name: "Different WHERE conditions",+ def1: "CREATE INDEX idx1 ON table1 (col1) WHERE active = true",+ def2: "CREATE INDEX idx2 ON table2 (col2) WHERE status = 'pending'",+ expected: false,+ },+ {+ name: "Both without WHERE clause",+ def1: "CREATE INDEX idx1 ON table1 (col1)",+ def2: "CREATE INDEX idx2 ON table2 (col2)",+ expected: true,+ },+ {+ name: "One with WHERE, one without",+ def1: "CREATE INDEX idx1 ON table1 (col1) WHERE active = true",+ def2: "CREATE INDEX idx2 ON table2 (col2)",+ expected: false,+ },+ {+ name: "Function names with different quoting should be equal",+ def1: `CREATE INDEX idx1 ON table1 (LEFT(text_col, 50)) WHERE active = true`,+ def2: `CREATE INDEX idx2 ON table2 ("left"(text_col, 50)) WHERE active = true`,+ expected: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result := comparer.CompareIndexWhereConditions(tt.def1, tt.def2)+ if result != tt.expected {+ t.Errorf("CompareIndexWhereConditions() = %v, want %v", result, tt.expected)+ }+ })+ }+}++func TestPostgreSQLIndexComparer_ParseIndexDefinition(t *testing.T) {+ comparer := &PostgreSQLIndexComparer{}++ tests := []struct {+ name string+ indexDef string+ expectError bool+ expected *IndexDefinition+ }{+ {+ name: "Simple index",+ indexDef: "CREATE INDEX idx_users_email ON users (email)",+ expectError: false,+ expected: &IndexDefinition{+ IndexName: "idx_users_email",+ TableName: "users",+ Unique: false,+ WhereClause: "",+ },+ },+ {+ name: "UNIQUE index with WHERE clause",+ indexDef: "CREATE UNIQUE INDEX idx_users_email_active ON users (email) WHERE active = true",+ expectError: false,+ expected: &IndexDefinition{+ IndexName: "idx_users_email_active",+ TableName: "users",+ Unique: true,+ WhereClause: "active = true",+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result, err := comparer.ParseIndexDefinition(tt.indexDef)++ if tt.expectError && err == nil {+ t.Error("ParseIndexDefinition() expected error, but got none")+ return+ }+ if !tt.expectError && err != nil {+ t.Errorf("ParseIndexDefinition() unexpected error: %v", err)+ return+ }++ if tt.expected != nil {+ if result.IndexName != tt.expected.IndexName {+ t.Errorf("ParseIndexDefinition() IndexName = %q, want %q", result.IndexName, tt.expected.IndexName)+ }+ if result.TableName != tt.expected.TableName {+ t.Errorf("ParseIndexDefinition() TableName = %q, want %q", result.TableName, tt.expected.TableName)+ }+ if result.Unique != tt.expected.Unique {+ t.Errorf("ParseIndexDefinition() Unique = %v, want %v", result.Unique, tt.expected.Unique)+ }+ if result.WhereClause != tt.expected.WhereClause {+ t.Errorf("ParseIndexDefinition() WhereClause = %q, want %q", result.WhereClause, tt.expected.WhereClause)+ }+ }+ })+ }+}diff --git a/backend/plugin/schema/pg/sdl_comprehensive_test.go b/backend/plugin/schema/pg/sdl_comprehensive_test.gonew file mode 100644index 0000000000..3bf4777e49--- /dev/null+++ b/backend/plugin/schema/pg/sdl_comprehensive_test.go@@ -0,0 +1,509 @@+package pg++import (+ "context"+ "database/sql"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/stdlib"+ "github.com/pkg/errors"+ "github.com/stretchr/testify/require"+ "github.com/testcontainers/testcontainers-go"+ "github.com/testcontainers/testcontainers-go/modules/postgres"+ "github.com/testcontainers/testcontainers-go/wait"+)++// TestScenario represents a complete test scenario with all required files+type TestScenario struct {+ Name string+ Category string+ Description string+ InitialSchema string+ ExpectedSchema string+ ExpectedDiff string+ ExpectedMigration string+}++// TestSDLComprehensiveValidation runs comprehensive SDL validation tests organized by categories+func TestSDLComprehensiveValidation(t *testing.T) {+ ctx := context.Background()++ // Start PostgreSQL container+ pgContainer, err := postgres.Run(ctx,+ "postgres:16-alpine",+ postgres.WithDatabase("test_db"),+ postgres.WithUsername("postgres"),+ postgres.WithPassword("test"),+ testcontainers.WithWaitStrategy(+ wait.ForLog("database system is ready to accept connections").+ WithOccurrence(2).+ WithStartupTimeout(5*time.Minute),+ ),+ )+ require.NoError(t, err)+ defer func() {+ if err := pgContainer.Terminate(ctx); err != nil {+ t.Logf("failed to terminate container: %s", err)+ }+ }()++ // Get connection string+ connectionString, err := pgContainer.ConnectionString(ctx, "sslmode=disable")+ require.NoError(t, err)++ // Connect to the database+ connConfig, err := pgx.ParseConfig(connectionString)+ require.NoError(t, err)+ db := stdlib.OpenDB(*connConfig)+ defer db.Close()++ // Load test scenarios from organized files+ testScenarios, err := loadTestScenarios()+ require.NoError(t, err)+ require.NotEmpty(t, testScenarios, "No test scenarios found")++ // Group scenarios by category for better organization+ categorizedTests := make(map[string][]TestScenario)+ for _, scenario := range testScenarios {+ categorizedTests[scenario.Category] = append(categorizedTests[scenario.Category], scenario)+ }++ // Run tests by category+ for category, scenarios := range categorizedTests {+ t.Run(category, func(t *testing.T) {+ for _, scenario := range scenarios {+ t.Run(scenario.Name, func(t *testing.T) {+ runSDLTestScenario(ctx, t, connConfig, db, scenario)+ })+ }+ })+ }+}++// loadTestScenarios loads all test scenarios from the sdl_testdata directory+func loadTestScenarios() ([]TestScenario, error) {+ var scenarios []TestScenario++ testDataDir := "sdl_testdata"+ if _, err := os.Stat(testDataDir); os.IsNotExist(err) {+ // Return some built-in scenarios for initial testing+ return getBuiltinTestScenarios(), nil+ }++ err := filepath.Walk(testDataDir, func(path string, info os.FileInfo, err error) error {+ if err != nil {+ return err+ }++ // Look for test_description.md files to identify complete test scenarios+ if info.Name() == "test_description.md" {+ scenario, err := loadTestScenario(filepath.Dir(path))+ if err != nil {+ return errors.Wrapf(err, "failed to load scenario from %s", path)+ }+ scenarios = append(scenarios, scenario)+ }+ return nil+ })++ if err != nil {+ return nil, err+ }++ // If no scenarios found in files, return built-in scenarios+ if len(scenarios) == 0 {+ return getBuiltinTestScenarios(), nil+ }++ return scenarios, nil+}++// loadTestScenario loads a single test scenario from a directory+func loadTestScenario(scenarioDir string) (TestScenario, error) {+ var scenario TestScenario++ // Extract category and name from path+ relativePath, err := filepath.Rel("sdl_testdata", scenarioDir)+ if err != nil {+ return scenario, err+ }++ pathParts := strings.Split(relativePath, string(filepath.Separator))+ scenario.Category = pathParts[0]+ scenario.Name = strings.Join(pathParts[1:], "_")++ // Load description+ descPath := filepath.Join(scenarioDir, "test_description.md")+ if descData, err := os.ReadFile(descPath); err == nil {+ scenario.Description = string(descData)+ }++ // Load initial schema+ initialPath := filepath.Join(scenarioDir, "initial_schema.sql")+ if initialData, err := os.ReadFile(initialPath); err == nil {+ scenario.InitialSchema = string(initialData)+ }++ // Load expected schema+ expectedPath := filepath.Join(scenarioDir, "expected_schema.sql")+ if expectedData, err := os.ReadFile(expectedPath); err == nil {+ scenario.ExpectedSchema = string(expectedData)+ } else {+ return scenario, errors.New("expected_schema.sql is required")+ }++ // Load expected diff (optional)+ diffPath := filepath.Join(scenarioDir, "diff.json")+ if diffData, err := os.ReadFile(diffPath); err == nil {+ scenario.ExpectedDiff = string(diffData)+ }++ // Load expected migration (optional)+ migrationPath := filepath.Join(scenarioDir, "ddl.sql")+ if migrationData, err := os.ReadFile(migrationPath); err == nil {+ scenario.ExpectedMigration = string(migrationData)+ }++ return scenario, nil+}++// runSDLTestScenario executes a single SDL test scenario+func runSDLTestScenario(ctx context.Context, t *testing.T, connConfig *pgx.ConnConfig, mainDB *sql.DB, scenario TestScenario) {+ t.Logf("Running SDL test scenario: %s - %s", scenario.Category, scenario.Name)+ if scenario.Description != "" {+ t.Logf("Description: %s", strings.TrimSpace(scenario.Description))+ }++ // Create a unique database for this test+ dbName := fmt.Sprintf("sdl_test_%s_%s",+ strings.ReplaceAll(scenario.Category, "/", "_"),+ strings.ReplaceAll(scenario.Name, "/", "_"))+ dbName = strings.ReplaceAll(dbName, "-", "_") // Replace hyphens with underscores+ dbName = strings.ToLower(dbName)++ _, err := mainDB.Exec(fmt.Sprintf("CREATE DATABASE %s", dbName))+ require.NoError(t, err)+ defer func() {+ _, _ = mainDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbName))+ }()++ // Connect to the test database+ testConnConfig := *connConfig+ testConnConfig.Database = dbName+ testDB := stdlib.OpenDB(testConnConfig)+ defer testDB.Close()++ // Execute the enhanced SDL validation process+ err = executeEnhancedSDLValidation(ctx, t, &testConnConfig, testDB, dbName, scenario)+ require.NoError(t, err, "SDL validation failed for scenario: %s/%s", scenario.Category, scenario.Name)+}++// executeEnhancedSDLValidation implements the enhanced 5-step SDL validation with diff comparison+func executeEnhancedSDLValidation(ctx context.Context, t *testing.T, connConfig *pgx.ConnConfig, testDB *sql.DB, dbName string, scenario TestScenario) error {+ t.Log("=== Step 1: Apply initial schema to database ===")+ if strings.TrimSpace(scenario.InitialSchema) != "" {+ _, err := testDB.Exec(scenario.InitialSchema)+ if err != nil {+ return errors.Wrapf(err, "failed to apply initial schema")+ }+ t.Logf("✓ Applied initial schema (%d characters)", len(scenario.InitialSchema))+ } else {+ t.Log("✓ Starting with empty database")+ }++ t.Log("=== Step 2: Sync to get current schema metadata (Schema B) ===")+ schemaB, err := getSyncMetadataForSDL(ctx, connConfig, dbName)+ if err != nil {+ return errors.Wrapf(err, "failed to sync schema B")+ }+ t.Log("✓ Synced current schema metadata")++ t.Log("=== Step 3: Get expected schema metadata and generate migration DDL ===")+ schemaCMetadata, err := GetDatabaseMetadata(scenario.ExpectedSchema)+ if err != nil {+ return errors.Wrapf(err, "failed to get expected schema C metadata")+ }+ t.Log("✓ Parsed expected schema metadata")++ // Generate migration DDL from schema B to schema C using the existing function+ migrationDDL, schemaDiff, err := generateMigrationDDLFromMetadata(schemaB, schemaCMetadata)+ require.NoError(t, err, "Failed to generate migration DDL from metadata")++ // Compare with expected diff if provided+ if scenario.ExpectedDiff != "" {+ err := validateSchemaDiff(t, schemaDiff, scenario.ExpectedDiff)+ if err != nil {+ t.Logf("WARNING: Schema diff validation failed: %v", err)+ // Note: This is a warning for now, can be made stricter later+ } else {+ t.Log("✓ Generated schema diff matches expected")+ }+ }++ t.Logf("✓ Generated migration DDL (%d characters)", len(migrationDDL))+ if migrationDDL != "" {+ t.Logf("Migration DDL preview (first 200 chars):\n%s",+ truncateString(migrationDDL, 200))+ }++ // Compare with expected migration DDL if provided+ if scenario.ExpectedMigration != "" {+ normalizedGenerated := normalizeSQLString(migrationDDL)+ normalizedExpected := normalizeSQLString(scenario.ExpectedMigration)+ if normalizedGenerated != normalizedExpected {+ t.Log("Generated migration DDL differs from expected:")+ t.Logf("Expected:\n%s", scenario.ExpectedMigration)+ t.Logf("Generated:\n%s", migrationDDL)++ // For comprehensive testing, we can make this a hard requirement+ if strings.TrimSpace(normalizedExpected) != "" {+ require.Equal(t, normalizedExpected, normalizedGenerated,+ "Generated migration DDL does not match expected DDL")+ }+ } else {+ t.Log("✓ Generated migration DDL matches expected")+ }+ }++ t.Log("=== Step 4: Apply migration DDL and sync final schema ===")+ if strings.TrimSpace(migrationDDL) != "" {+ _, err := testDB.Exec(migrationDDL)+ if err != nil {+ return errors.Wrapf(err, "failed to apply migration DDL: %s", migrationDDL)+ }+ t.Log("✓ Applied migration DDL")+ } else {+ t.Log("✓ No migration DDL needed (schemas already match)")+ }++ // Sync to get final schema D+ schemaD, err := getSyncMetadataForSDL(ctx, connConfig, dbName)+ if err != nil {+ return errors.Wrapf(err, "failed to sync schema D after migration")+ }+ t.Log("✓ Synced final schema metadata")++ t.Log("=== Step 5: Validate schema consistency ===")+ err = validateSchemaConsistency(schemaD, schemaCMetadata)+ if err != nil {+ return errors.Wrapf(err, "schema validation failed")+ }+ t.Log("✓ Final schema matches expected schema perfectly")++ return nil+}++// getBuiltinTestScenarios returns built-in test scenarios for immediate testing+func getBuiltinTestScenarios() []TestScenario {+ return []TestScenario{+ {+ Name: "basic_table_creation",+ Category: "data_types/basic_types",+ Description: "Test basic table creation with various data types",+ InitialSchema: ``,+ ExpectedSchema: `+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL UNIQUE,+ email VARCHAR(100) NOT NULL,+ age INTEGER,+ salary DECIMAL(10,2),+ is_active BOOLEAN DEFAULT true,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ profile JSONB,+ tags TEXT[]+);++CREATE INDEX idx_users_email ON public.users(email);+CREATE INDEX idx_users_created_at ON public.users(created_at);+`,+ },+ {+ Name: "add_foreign_key_table",+ Category: "constraints_indexes/foreign_keys",+ Description: "Test adding table with foreign key constraint",+ InitialSchema: `+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL UNIQUE,+ email VARCHAR(100) NOT NULL+);+`,+ ExpectedSchema: `+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL UNIQUE,+ email VARCHAR(100) NOT NULL+);++CREATE TABLE public.posts (+ id SERIAL PRIMARY KEY,+ user_id INTEGER NOT NULL,+ title VARCHAR(200) NOT NULL,+ content TEXT,+ published BOOLEAN DEFAULT false,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE+);++CREATE INDEX idx_posts_user_id ON public.posts(user_id);+CREATE INDEX idx_posts_published ON public.posts(published) WHERE published = true;+`,+ },+ {+ Name: "enum_and_custom_types",+ Category: "schema_objects/custom_types",+ Description: "Test enum and custom type creation",+ InitialSchema: ``,+ ExpectedSchema: `+CREATE TYPE public.status_enum AS ENUM ('pending', 'active', 'inactive');+CREATE TYPE public.user_role AS ENUM ('admin', 'user', 'guest');++CREATE TABLE public.accounts (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL,+ status status_enum DEFAULT 'pending',+ role user_role DEFAULT 'user',+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++CREATE INDEX idx_accounts_status ON public.accounts(status);+CREATE INDEX idx_accounts_role ON public.accounts(role);+`,+ },+ {+ Name: "view_and_function",+ Category: "schema_objects/views",+ Description: "Test view and function creation",+ InitialSchema: `+CREATE TABLE public.employees (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ department VARCHAR(50),+ salary DECIMAL(10, 2),+ hire_date DATE DEFAULT CURRENT_DATE+);+`,+ ExpectedSchema: `+CREATE TABLE public.employees (+ id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ department VARCHAR(50),+ salary DECIMAL(10, 2),+ hire_date DATE DEFAULT CURRENT_DATE+);++CREATE OR REPLACE VIEW public.active_employees AS+SELECT id, name, department, salary+FROM employees+WHERE department IS NOT NULL;++CREATE OR REPLACE FUNCTION public.get_employee_count(dept VARCHAR)+RETURNS INTEGER AS $$+BEGIN+ RETURN (SELECT COUNT(*) FROM employees WHERE department = dept);+END;+$$ LANGUAGE plpgsql;+`,+ },+ {+ Name: "drop_objects",+ Category: "edge_cases/complex_scenarios",+ Description: "Test dropping all objects from database",+ InitialSchema: `+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL UNIQUE,+ email VARCHAR(100) NOT NULL+);++CREATE TABLE public.posts (+ id SERIAL PRIMARY KEY,+ user_id INTEGER NOT NULL,+ title VARCHAR(200) NOT NULL,+ FOREIGN KEY (user_id) REFERENCES users(id)+);++CREATE INDEX idx_posts_user_id ON public.posts(user_id);+`,+ ExpectedSchema: ``, // Empty - expect all objects to be dropped+ },+ }+}++// normalizeSQLString normalizes SQL for comparison by removing extra whitespace and standardizing formatting+func normalizeSQLString(sql string) string {+ // Remove extra whitespace and normalize line endings+ lines := strings.Split(sql, "\n")+ var normalizedLines []string+ for _, line := range lines {+ trimmed := strings.TrimSpace(line)+ if trimmed != "" {+ normalizedLines = append(normalizedLines, trimmed)+ }+ }+ return strings.Join(normalizedLines, "\n")+}++// truncateString truncates a string to maxLength characters+func truncateString(s string, maxLength int) string {+ if len(s) <= maxLength {+ return s+ }+ return s[:maxLength] + "..."+}++// validateSchemaDiff validates that the generated schema diff matches the expected diff+func validateSchemaDiff(t *testing.T, actualDiff any, expectedDiffJSON string) error {+ // For now, we'll do basic validation by comparing the string representations+ // In the future, this could be enhanced to do structured JSON comparison++ actualJSON, err := marshalDiffToJSON(actualDiff)+ if err != nil {+ return errors.Wrap(err, "failed to marshal actual diff to JSON")+ }++ // Normalize both JSON strings for comparison+ actualNormalized := normalizeJSONString(actualJSON)+ expectedNormalized := normalizeJSONString(expectedDiffJSON)++ if actualNormalized != expectedNormalized {+ t.Log("Schema diff comparison:")+ t.Logf("Expected diff:\n%s", expectedDiffJSON)+ t.Logf("Actual diff:\n%s", actualJSON)+ return errors.New("schema diff does not match expected")+ }++ return nil+}++// marshalDiffToJSON marshals a schema diff object to JSON string+func marshalDiffToJSON(diff any) (string, error) {+ // Convert the diff object to JSON+ jsonBytes, err := json.MarshalIndent(diff, "", " ")+ if err != nil {+ return "", errors.Wrap(err, "failed to marshal diff to JSON")+ }+ return string(jsonBytes), nil+}++// normalizeJSONString normalizes JSON for comparison+func normalizeJSONString(jsonStr string) string {+ // Remove extra whitespace and normalize formatting+ lines := strings.Split(jsonStr, "\n")+ var normalizedLines []string+ for _, line := range lines {+ trimmed := strings.TrimSpace(line)+ if trimmed != "" {+ normalizedLines = append(normalizedLines, trimmed)+ }+ }+ return strings.Join(normalizedLines, "\n")+}diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sqlnew file mode 100644index 0000000000..7dd6c65520--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/ddl.sql@@ -0,0 +1,29 @@+CREATE SEQUENCE "public"."analytics_analysis_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."analytics" (+ "analysis_id" integer NOT NULL DEFAULT nextval('public.analytics_analysis_id_seq'::regclass),+ "data_points" _numeric NOT NULL,+ "categories" _text NOT NULL,+ "timestamps" _timestamptz NOT NULL,+ "user_ids" _uuid,+ "scores" _float4 DEFAULT ARRAY[]::REAL[],+ "flags" _bool DEFAULT ARRAY[]::BOOLEAN[]+);+ALTER TABLE "public"."analytics" ADD CONSTRAINT "analytics_pkey" PRIMARY KEY (analysis_id);+CREATE INDEX idx_analytics_categories ON public.analytics USING gin (categories);++ALTER TABLE "public"."events" ADD COLUMN "capacities" _int4;+ALTER TABLE "public"."events" ADD COLUMN "locations" _text DEFAULT ARRAY[]::TEXT[] NOT NULL;+ALTER TABLE "public"."events" ADD COLUMN "metadata" _jsonb DEFAULT ARRAY[]::JSONB[];+ALTER TABLE "public"."events" ADD COLUMN "schedules" _timestamp;+ALTER TABLE "public"."products" ADD COLUMN "features" _jsonb;+ALTER TABLE "public"."products" ADD COLUMN "ratings" _int4 DEFAULT ARRAY[0,0,0,0,0];+ALTER TABLE "public"."products" ADD COLUMN "variants" _text;+ALTER TABLE "public"."events" ALTER COLUMN "event_dates" TYPE _timestamptz;+CREATE INDEX idx_events_locations ON public.events USING gin (locations);+CREATE INDEX idx_events_participants ON public.events USING gin (participant_ids);++ALTER TABLE "public"."products" ALTER COLUMN "category_ids" TYPE _int8;+ALTER TABLE "public"."products" ALTER COLUMN "tags" SET DEFAULT ARRAY[]::TEXT[];+CREATE INDEX idx_products_categories ON public.products USING gin (category_ids);+CREATE INDEX idx_products_tags ON public.products USING gin (tags);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/diff.jsonnew file mode 100644index 0000000000..296cd48b08--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/diff.json@@ -0,0 +1,218 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 3, Sequence changes: 1",+ "tableChanges": 3,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "analytics",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "events",+ "columnChanges": 5,+ "indexChanges": 2,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "capacities",+ "newColumn": {+ "name": "capacities",+ "type": "_int4",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "event_dates",+ "oldColumn": {+ "name": "event_dates",+ "type": "_timestamp",+ "nullable": true+ },+ "newColumn": {+ "name": "event_dates",+ "type": "_timestamptz",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "locations",+ "newColumn": {+ "name": "locations",+ "type": "_text",+ "nullable": false,+ "defaultValue": "ARRAY[]::TEXT[]"+ }+ },+ {+ "action": "CREATE",+ "name": "metadata",+ "newColumn": {+ "name": "metadata",+ "type": "_jsonb",+ "nullable": true,+ "defaultValue": "ARRAY[]::JSONB[]"+ }+ },+ {+ "action": "CREATE",+ "name": "schedules",+ "newColumn": {+ "name": "schedules",+ "type": "_timestamp",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_events_locations",+ "newIndex": {+ "name": "idx_events_locations",+ "type": "gin",+ "unique": false,+ "expressions": [+ "locations"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_events_participants",+ "newIndex": {+ "name": "idx_events_participants",+ "type": "gin",+ "unique": false,+ "expressions": [+ "participant_ids"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "products",+ "columnChanges": 5,+ "indexChanges": 2,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "category_ids",+ "oldColumn": {+ "name": "category_ids",+ "type": "_int4",+ "nullable": true+ },+ "newColumn": {+ "name": "category_ids",+ "type": "_int8",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "features",+ "newColumn": {+ "name": "features",+ "type": "_jsonb",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "ratings",+ "newColumn": {+ "name": "ratings",+ "type": "_int4",+ "nullable": true,+ "defaultValue": "ARRAY[0,0,0,0,0]"+ }+ },+ {+ "action": "ALTER",+ "name": "tags",+ "oldColumn": {+ "name": "tags",+ "type": "_text",+ "nullable": true+ },+ "newColumn": {+ "name": "tags",+ "type": "_text",+ "nullable": true,+ "defaultValue": "ARRAY[]::TEXT[]"+ }+ },+ {+ "action": "CREATE",+ "name": "variants",+ "newColumn": {+ "name": "variants",+ "type": "_text",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_products_categories",+ "newIndex": {+ "name": "idx_products_categories",+ "type": "gin",+ "unique": false,+ "expressions": [+ "category_ids"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_products_tags",+ "newIndex": {+ "name": "idx_products_tags",+ "type": "gin",+ "unique": false,+ "expressions": [+ "tags"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/expected_schema.sqlnew file mode 100644index 0000000000..5aa807353f--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/expected_schema.sql@@ -0,0 +1,39 @@+-- Enhanced schema with comprehensive array type usage+CREATE TABLE public.products (+ product_id SERIAL PRIMARY KEY,+ name VARCHAR(200) NOT NULL,+ tags TEXT[] DEFAULT ARRAY[]::TEXT[], -- Added default empty array+ category_ids BIGINT[], -- Changed from INTEGER[] to BIGINT[]+ prices NUMERIC(12,4)[], -- Increased precision+ variants TEXT[][], -- New multidimensional array+ ratings INTEGER[] DEFAULT ARRAY[0,0,0,0,0], -- New array with default values+ features JSONB[] -- New JSONB array+);++CREATE TABLE public.events (+ event_id SERIAL PRIMARY KEY,+ title VARCHAR(200) NOT NULL,+ participant_ids UUID[],+ event_dates TIMESTAMP WITH TIME ZONE[], -- Added timezone+ locations TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[], -- New required array with default+ capacities INTEGER[], -- New integer array+ schedules TIMESTAMP[][], -- New multidimensional timestamp array+ metadata JSONB[] DEFAULT ARRAY[]::JSONB[] -- New JSONB array with default+);++CREATE TABLE public.analytics (+ analysis_id SERIAL PRIMARY KEY,+ data_points NUMERIC(15,6)[] NOT NULL,+ categories TEXT[] NOT NULL,+ timestamps TIMESTAMP WITH TIME ZONE[] NOT NULL,+ user_ids UUID[],+ scores REAL[] DEFAULT ARRAY[]::REAL[],+ flags BOOLEAN[] DEFAULT ARRAY[]::BOOLEAN[]+);++-- Add GIN indexes for array operations+CREATE INDEX idx_products_tags ON public.products USING GIN(tags);+CREATE INDEX idx_products_categories ON public.products USING GIN(category_ids);+CREATE INDEX idx_events_participants ON public.events USING GIN(participant_ids);+CREATE INDEX idx_events_locations ON public.events USING GIN(locations);+CREATE INDEX idx_analytics_categories ON public.analytics USING GIN(categories);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/initial_schema.sqlnew file mode 100644index 0000000000..3f09f3b429--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/initial_schema.sql@@ -0,0 +1,15 @@+-- Initial schema with basic array types+CREATE TABLE public.products (+ product_id SERIAL PRIMARY KEY,+ name VARCHAR(200) NOT NULL,+ tags TEXT[],+ category_ids INTEGER[],+ prices NUMERIC(10,2)[]+);++CREATE TABLE public.events (+ event_id SERIAL PRIMARY KEY,+ title VARCHAR(200) NOT NULL,+ participant_ids UUID[],+ event_dates TIMESTAMP[]+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/test_description.mdnew file mode 100644index 0000000000..f6da75e513--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/array_types/test_description.md@@ -0,0 +1,11 @@+# Array Data Types Test++This test validates the SDL migration handling of PostgreSQL array types:+- **INTEGER[]**: Integer arrays+- **TEXT[]**: Text arrays+- **NUMERIC[]**: Numeric arrays+- **TIMESTAMP[]**: Timestamp arrays+- **UUID[]**: UUID arrays+- **Multidimensional arrays**: INTEGER[][], TEXT[][]++Tests creation, modification, and indexing of array columns with various constraints and default values.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sqlnew file mode 100644index 0000000000..f234db9a27--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/ddl.sql@@ -0,0 +1,25 @@+ALTER TABLE "public"."documents" ADD COLUMN "checksum" bytea;+ALTER TABLE "public"."documents" ADD COLUMN "file_info" jsonb DEFAULT '{}';+ALTER TABLE "public"."documents" ADD COLUMN "updated_at" timestamp(6) without time zone;+CREATE TABLE "public"."files" (+ "file_id" uuid NOT NULL DEFAULT gen_random_uuid(),+ "filename" character varying(255) NOT NULL,+ "content" bytea NOT NULL,+ "mime_type" character varying(100),+ "metadata" jsonb DEFAULT '{}',+ "size_bytes" integer,+ "upload_time" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP+);+ALTER TABLE "public"."files" ADD CONSTRAINT "files_pkey" PRIMARY KEY (file_id);+CREATE INDEX idx_files_metadata ON public.files USING gin (metadata);+CREATE INDEX idx_files_mime_type ON public.files USING btree (mime_type);++ALTER TABLE "public"."sessions" ADD COLUMN "last_accessed" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP;+ALTER TABLE "public"."sessions" ADD COLUMN "settings" jsonb DEFAULT '{"theme": "default"}'::jsonb;+ALTER TABLE "public"."documents" ALTER COLUMN "metadata" TYPE jsonb;+CREATE INDEX idx_documents_metadata ON public.documents USING gin (metadata);++ALTER TABLE "public"."sessions" ALTER COLUMN "session_id" SET DEFAULT gen_random_uuid();+CREATE INDEX idx_sessions_data ON public.sessions USING gin (data);+CREATE INDEX idx_sessions_settings ON public.sessions USING gin (settings);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/diff.jsonnew file mode 100644index 0000000000..157d9e7342--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/diff.json@@ -0,0 +1,171 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 3",+ "tableChanges": 3,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 0,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "documents",+ "columnChanges": 4,+ "indexChanges": 1,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "checksum",+ "newColumn": {+ "name": "checksum",+ "type": "bytea",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "file_info",+ "newColumn": {+ "name": "file_info",+ "type": "jsonb",+ "nullable": true,+ "defaultValue": "'{}'"+ }+ },+ {+ "action": "ALTER",+ "name": "metadata",+ "oldColumn": {+ "name": "metadata",+ "type": "json",+ "nullable": true+ },+ "newColumn": {+ "name": "metadata",+ "type": "jsonb",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "updated_at",+ "newColumn": {+ "name": "updated_at",+ "type": "timestamp(6) without time zone",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_documents_metadata",+ "newIndex": {+ "name": "idx_documents_metadata",+ "type": "gin",+ "unique": false,+ "expressions": [+ "metadata"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "files",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "sessions",+ "columnChanges": 3,+ "indexChanges": 2,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "last_accessed",+ "newColumn": {+ "name": "last_accessed",+ "type": "timestamp(6) without time zone",+ "nullable": true,+ "defaultValue": "CURRENT_TIMESTAMP"+ }+ },+ {+ "action": "ALTER",+ "name": "session_id",+ "oldColumn": {+ "name": "session_id",+ "type": "uuid",+ "nullable": false+ },+ "newColumn": {+ "name": "session_id",+ "type": "uuid",+ "nullable": false,+ "defaultValue": "gen_random_uuid()"+ }+ },+ {+ "action": "CREATE",+ "name": "settings",+ "newColumn": {+ "name": "settings",+ "type": "jsonb",+ "nullable": true,+ "defaultValue": "'{\"theme\": \"default\"}'::jsonb"+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_sessions_data",+ "newIndex": {+ "name": "idx_sessions_data",+ "type": "gin",+ "unique": false,+ "expressions": [+ "data"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_sessions_settings",+ "newIndex": {+ "name": "idx_sessions_settings",+ "type": "gin",+ "unique": false,+ "expressions": [+ "settings"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/expected_schema.sqlnew file mode 100644index 0000000000..7b8b800ebc--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/expected_schema.sql@@ -0,0 +1,37 @@+-- Enhanced schema with full advanced type usage+CREATE TABLE public.documents (+ doc_id SERIAL PRIMARY KEY,+ title VARCHAR(200) NOT NULL,+ content BYTEA,+ metadata JSONB, -- Changed from JSON to JSONB+ checksum BYTEA, -- New binary column+ file_info JSONB DEFAULT '{}', -- New JSONB with default+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP+);++CREATE TABLE public.sessions (+ session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Added default UUID generation+ user_id INTEGER NOT NULL,+ data JSONB,+ settings JSONB DEFAULT '{"theme": "default"}'::jsonb, -- New JSONB with default+ expires_at TIMESTAMP NOT NULL,+ last_accessed TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- New timestamp column+);++CREATE TABLE public.files (+ file_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ filename VARCHAR(255) NOT NULL,+ content BYTEA NOT NULL,+ mime_type VARCHAR(100),+ metadata JSONB DEFAULT '{}',+ size_bytes INTEGER,+ upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++-- Add indexes for JSON queries+CREATE INDEX idx_documents_metadata ON public.documents USING GIN(metadata);+CREATE INDEX idx_sessions_data ON public.sessions USING GIN(data);+CREATE INDEX idx_sessions_settings ON public.sessions USING GIN(settings);+CREATE INDEX idx_files_metadata ON public.files USING GIN(metadata);+CREATE INDEX idx_files_mime_type ON public.files(mime_type);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/initial_schema.sqlnew file mode 100644index 0000000000..d376da1944--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/initial_schema.sql@@ -0,0 +1,15 @@+-- Initial schema with basic versions of advanced types+CREATE TABLE public.documents (+ doc_id SERIAL PRIMARY KEY,+ title VARCHAR(200) NOT NULL,+ content BYTEA,+ metadata JSON,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++CREATE TABLE public.sessions (+ session_id UUID PRIMARY KEY,+ user_id INTEGER NOT NULL,+ data JSONB,+ expires_at TIMESTAMP NOT NULL+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/test_description.mdnew file mode 100644index 0000000000..59b8e72ec2--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/binary_json_uuid/test_description.md@@ -0,0 +1,9 @@+# Binary Data, JSON, and UUID Types Test++This test validates the SDL migration handling of advanced data types:+- **BYTEA**: Binary data storage and manipulation+- **JSON**: Standard JSON data type+- **JSONB**: Binary JSON with indexing capabilities+- **UUID**: Universal unique identifiers++Tests creation, modification, and indexing of these advanced data types along with their constraints and default values.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sqlnew file mode 100644index 0000000000..bc25c4b141--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/ddl.sql@@ -0,0 +1,44 @@+CREATE SEQUENCE "public"."permissions_matrix_permission_id_seq" START WITH 1 INCREMENT BY 1;+CREATE SEQUENCE "public"."scheduling_schedule_id_seq" START WITH 1 INCREMENT BY 1;+ALTER TABLE "public"."bookings" ADD COLUMN "age_range" int4range;+ALTER TABLE "public"."bookings" ADD COLUMN "booking_dates" daterange NOT NULL;+ALTER TABLE "public"."bookings" ADD COLUMN "discount_range" numrange DEFAULT '[0,100)'::NUMRANGE;+ALTER TABLE "public"."bookings" ADD COLUMN "duration_range" int8range;+ALTER TABLE "public"."bookings" ADD COLUMN "valid_periods" _tstzrange;+CREATE TABLE "public"."permissions_matrix" (+ "permission_id" integer NOT NULL DEFAULT nextval('public.permissions_matrix_permission_id_seq'::regclass),+ "user_role" character varying(50) NOT NULL,+ "read_permissions" bit(64) NOT NULL DEFAULT B'0000000000000000000000000000000000000000000000000000000000000000',+ "write_permissions" bit(64) NOT NULL DEFAULT B'0000000000000000000000000000000000000000000000000000000000000000',+ "admin_flags" bit(128) DEFAULT B'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',+ "feature_access" bit(8) DEFAULT B'11111111'+);+ALTER TABLE "public"."permissions_matrix" ADD CONSTRAINT "permissions_matrix_pkey" PRIMARY KEY (permission_id);++CREATE TABLE "public"."scheduling" (+ "schedule_id" integer NOT NULL DEFAULT nextval('public.scheduling_schedule_id_seq'::regclass),+ "schedule_name" character varying(100) NOT NULL,+ "working_hours" _tsrange NOT NULL DEFAULT ARRAY[]::TSRANGE[],+ "available_dates" _daterange DEFAULT ARRAY[]::DATERANGE[],+ "capacity_ranges" _int4range DEFAULT ARRAY[]::INT4RANGE[],+ "budget_ranges" _numrange DEFAULT ARRAY[]::NUMRANGE[],+ "holiday_periods" daterange NOT NULL DEFAULT '[2000-01-01,2000-01-02)'::DATERANGE+);+ALTER TABLE "public"."scheduling" ADD CONSTRAINT "scheduling_pkey" PRIMARY KEY (schedule_id);+CREATE INDEX idx_scheduling_hours ON public.scheduling USING gin (working_hours);+CREATE INDEX idx_scheduling_dates ON public.scheduling USING gin (available_dates);++ALTER TABLE "public"."system_flags" ADD COLUMN "access_mask" bit(64);+ALTER TABLE "public"."system_flags" ADD COLUMN "feature_flags" bit(32) DEFAULT B'00000000000000000000000000000000';+ALTER TABLE "public"."system_flags" ADD COLUMN "system_state" bit(128);+ALTER TABLE "public"."bookings" ALTER COLUMN "booking_period" SET NOT NULL;+CREATE INDEX idx_bookings_dates ON public.bookings USING gist (booking_dates);+CREATE INDEX idx_bookings_period ON public.bookings USING gist (booking_period);+CREATE INDEX idx_bookings_price ON public.bookings USING gist (price_range);++ALTER TABLE "public"."system_flags" ALTER COLUMN "bit_flags" TYPE bit(16);+ALTER TABLE "public"."system_flags" ALTER COLUMN "bit_flags" SET NOT NULL;+ALTER TABLE "public"."system_flags" ALTER COLUMN "bit_flags" SET DEFAULT B'0000000000000000';+ALTER TABLE "public"."system_flags" ALTER COLUMN "permissions" TYPE bit(32);+ALTER TABLE "public"."system_flags" ALTER COLUMN "permissions" SET DEFAULT B'00000000000000000000000000000000';+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/diff.jsonnew file mode 100644index 0000000000..6ef2bf12fe--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/diff.json@@ -0,0 +1,219 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 4, Sequence changes: 2",+ "tableChanges": 4,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 2,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "bookings",+ "columnChanges": 6,+ "indexChanges": 3,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "age_range",+ "newColumn": {+ "name": "age_range",+ "type": "int4range",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "booking_dates",+ "newColumn": {+ "name": "booking_dates",+ "type": "daterange",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "booking_period",+ "oldColumn": {+ "name": "booking_period",+ "type": "tsrange",+ "nullable": true+ },+ "newColumn": {+ "name": "booking_period",+ "type": "tsrange",+ "nullable": false+ }+ },+ {+ "action": "CREATE",+ "name": "discount_range",+ "newColumn": {+ "name": "discount_range",+ "type": "numrange",+ "nullable": true,+ "defaultValue": "'[0,100)'::NUMRANGE"+ }+ },+ {+ "action": "CREATE",+ "name": "duration_range",+ "newColumn": {+ "name": "duration_range",+ "type": "int8range",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "valid_periods",+ "newColumn": {+ "name": "valid_periods",+ "type": "_tstzrange",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_bookings_dates",+ "newIndex": {+ "name": "idx_bookings_dates",+ "type": "gist",+ "unique": false,+ "expressions": [+ "booking_dates"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_bookings_period",+ "newIndex": {+ "name": "idx_bookings_period",+ "type": "gist",+ "unique": false,+ "expressions": [+ "booking_period"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_bookings_price",+ "newIndex": {+ "name": "idx_bookings_price",+ "type": "gist",+ "unique": false,+ "expressions": [+ "price_range"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "permissions_matrix",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "scheduling",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "system_flags",+ "columnChanges": 5,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "access_mask",+ "newColumn": {+ "name": "access_mask",+ "type": "bit(64)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "bit_flags",+ "oldColumn": {+ "name": "bit_flags",+ "type": "bit(8)",+ "nullable": true+ },+ "newColumn": {+ "name": "bit_flags",+ "type": "bit(16)",+ "nullable": false,+ "defaultValue": "B'0000000000000000'"+ }+ },+ {+ "action": "CREATE",+ "name": "feature_flags",+ "newColumn": {+ "name": "feature_flags",+ "type": "bit(32)",+ "nullable": true,+ "defaultValue": "B'00000000000000000000000000000000'"+ }+ },+ {+ "action": "ALTER",+ "name": "permissions",+ "oldColumn": {+ "name": "permissions",+ "type": "bit(16)",+ "nullable": true+ },+ "newColumn": {+ "name": "permissions",+ "type": "bit(32)",+ "nullable": true,+ "defaultValue": "B'00000000000000000000000000000000'"+ }+ },+ {+ "action": "CREATE",+ "name": "system_state",+ "newColumn": {+ "name": "system_state",+ "type": "bit(128)",+ "nullable": true+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/expected_schema.sqlnew file mode 100644index 0000000000..bbf171fdc2--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/expected_schema.sql@@ -0,0 +1,47 @@+-- Enhanced schema with comprehensive bit and range types+CREATE TABLE public.system_flags (+ flag_id SERIAL PRIMARY KEY,+ flag_name VARCHAR(50) NOT NULL,+ bit_flags BIT(16) NOT NULL DEFAULT B'0000000000000000', -- Expanded from BIT(8)+ permissions BIT(32) DEFAULT B'00000000000000000000000000000000', -- Expanded from BIT(16) to BIT(32)+ feature_flags BIT(32) DEFAULT B'00000000000000000000000000000000', -- New bit column+ access_mask BIT(64), -- New fixed bit column+ system_state BIT(128) -- New fixed bit column+);++CREATE TABLE public.bookings (+ booking_id SERIAL PRIMARY KEY,+ booking_period TSRANGE NOT NULL, -- Keep as TSRANGE for compatibility+ price_range NUMRANGE,+ discount_range NUMRANGE DEFAULT '[0,100)'::NUMRANGE, -- New range with default+ age_range INT4RANGE, -- New integer range+ duration_range INT8RANGE, -- New bigint range+ booking_dates DATERANGE NOT NULL, -- New date range+ valid_periods TSTZRANGE[] -- Array of timestamp ranges+);++CREATE TABLE public.scheduling (+ schedule_id SERIAL PRIMARY KEY,+ schedule_name VARCHAR(100) NOT NULL,+ working_hours TSRANGE[] NOT NULL DEFAULT ARRAY[]::TSRANGE[],+ available_dates DATERANGE[] DEFAULT ARRAY[]::DATERANGE[],+ capacity_ranges INT4RANGE[] DEFAULT ARRAY[]::INT4RANGE[],+ budget_ranges NUMRANGE[] DEFAULT ARRAY[]::NUMRANGE[],+ holiday_periods DATERANGE NOT NULL DEFAULT '[2000-01-01,2000-01-02)'::DATERANGE+);++CREATE TABLE public.permissions_matrix (+ permission_id SERIAL PRIMARY KEY,+ user_role VARCHAR(50) NOT NULL,+ read_permissions BIT(64) NOT NULL DEFAULT B'0000000000000000000000000000000000000000000000000000000000000000',+ write_permissions BIT(64) NOT NULL DEFAULT B'0000000000000000000000000000000000000000000000000000000000000000',+ admin_flags BIT(128) DEFAULT B'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',+ feature_access BIT(8) DEFAULT B'11111111'+);++-- Add specialized indexes for range operations+CREATE INDEX idx_bookings_period ON public.bookings USING GIST(booking_period);+CREATE INDEX idx_bookings_price ON public.bookings USING GIST(price_range);+CREATE INDEX idx_bookings_dates ON public.bookings USING GIST(booking_dates);+CREATE INDEX idx_scheduling_hours ON public.scheduling USING GIN(working_hours);+CREATE INDEX idx_scheduling_dates ON public.scheduling USING GIN(available_dates);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/initial_schema.sqlnew file mode 100644index 0000000000..22e9799ab7--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/initial_schema.sql@@ -0,0 +1,13 @@+-- Initial schema with basic bit and range types+CREATE TABLE public.system_flags (+ flag_id SERIAL PRIMARY KEY,+ flag_name VARCHAR(50) NOT NULL,+ bit_flags BIT(8),+ permissions BIT(16)+);++CREATE TABLE public.bookings (+ booking_id SERIAL PRIMARY KEY,+ booking_period TSRANGE,+ price_range NUMRANGE+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/test_description.mdnew file mode 100644index 0000000000..6a54da1675--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/bit_range_types/test_description.md@@ -0,0 +1,17 @@+# Bit and Range Data Types Test++This test validates the SDL migration handling of bit manipulation and range data types:++**Bit Types**:+- **BIT**: Fixed-length bit strings+- **BIT VARYING (VARBIT)**: Variable-length bit strings++**Range Types**:+- **INT4RANGE**: Integer ranges+- **INT8RANGE**: Bigint ranges+- **NUMRANGE**: Numeric ranges+- **TSRANGE**: Timestamp ranges+- **TSTZRANGE**: Timestamp with timezone ranges+- **DATERANGE**: Date ranges++Tests creation, constraints, indexing, and range operations for these specialized data types.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sqlnew file mode 100644index 0000000000..e34e5b0ce8--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/ddl.sql@@ -0,0 +1,45 @@+CREATE SEQUENCE "public"."geographic_features_feature_id_seq" START WITH 1 INCREMENT BY 1;+CREATE SEQUENCE "public"."network_topology_topology_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."geographic_features" (+ "feature_id" integer NOT NULL DEFAULT nextval('public.geographic_features_feature_id_seq'::regclass),+ "feature_name" character varying(200) NOT NULL,+ "center_point" point NOT NULL,+ "bounding_box" box NOT NULL,+ "area_polygon" polygon,+ "coverage_circle" circle,+ "primary_line" lseg,+ "reference_paths" _path,+ "key_points" _point NOT NULL DEFAULT ARRAY[]::point[]+);+ALTER TABLE "public"."geographic_features" ADD CONSTRAINT "geographic_features_pkey" PRIMARY KEY (feature_id);+CREATE INDEX idx_features_center ON public.geographic_features USING gist (center_point);+CREATE INDEX idx_features_polygon ON public.geographic_features USING gist (area_polygon);++ALTER TABLE "public"."locations" ADD COLUMN "boundary_box" box;+ALTER TABLE "public"."locations" ADD COLUMN "center_point" point;+ALTER TABLE "public"."locations" ADD COLUMN "coverage_polygon" polygon;+ALTER TABLE "public"."locations" ADD COLUMN "route_path" path;+ALTER TABLE "public"."locations" ADD COLUMN "service_area" circle;+ALTER TABLE "public"."network_devices" ADD COLUMN "backup_mac" macaddr;+ALTER TABLE "public"."network_devices" ADD COLUMN "gateway" inet;+ALTER TABLE "public"."network_devices" ADD COLUMN "network_range" cidr;+ALTER TABLE "public"."network_devices" ADD COLUMN "subnet_mask" inet;+CREATE TABLE "public"."network_topology" (+ "topology_id" integer NOT NULL DEFAULT nextval('public.network_topology_topology_id_seq'::regclass),+ "network_name" character varying(100) NOT NULL,+ "network_cidr" cidr NOT NULL,+ "gateway_ip" inet NOT NULL,+ "dns_servers" _inet DEFAULT ARRAY[]::inet[],+ "device_macs" _macaddr DEFAULT ARRAY[]::macaddr[],+ "subnet_ranges" _cidr+);+ALTER TABLE "public"."network_topology" ADD CONSTRAINT "network_topology_pkey" PRIMARY KEY (topology_id);+ALTER TABLE "public"."network_topology" ADD CONSTRAINT "network_topology_network_cidr_key" UNIQUE (network_cidr);++ALTER TABLE "public"."locations" ALTER COLUMN "coordinates" SET NOT NULL;+CREATE INDEX idx_locations_boundary ON public.locations USING gist (boundary_box);+CREATE INDEX idx_locations_coordinates ON public.locations USING gist (coordinates);++ALTER TABLE "public"."network_devices" ALTER COLUMN "ip_address" SET NOT NULL;+ALTER TABLE "public"."network_devices" ADD CONSTRAINT "network_devices_mac_address_key" UNIQUE (mac_address);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/diff.jsonnew file mode 100644index 0000000000..03cc58f8a7--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/diff.json@@ -0,0 +1,212 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 4, Sequence changes: 2",+ "tableChanges": 4,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 2,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "geographic_features",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "locations",+ "columnChanges": 6,+ "indexChanges": 2,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "boundary_box",+ "newColumn": {+ "name": "boundary_box",+ "type": "box",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "center_point",+ "newColumn": {+ "name": "center_point",+ "type": "point",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "coordinates",+ "oldColumn": {+ "name": "coordinates",+ "type": "point",+ "nullable": true+ },+ "newColumn": {+ "name": "coordinates",+ "type": "point",+ "nullable": false+ }+ },+ {+ "action": "CREATE",+ "name": "coverage_polygon",+ "newColumn": {+ "name": "coverage_polygon",+ "type": "polygon",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "route_path",+ "newColumn": {+ "name": "route_path",+ "type": "path",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "service_area",+ "newColumn": {+ "name": "service_area",+ "type": "circle",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_locations_boundary",+ "newIndex": {+ "name": "idx_locations_boundary",+ "type": "gist",+ "unique": false,+ "expressions": [+ "boundary_box"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_locations_coordinates",+ "newIndex": {+ "name": "idx_locations_coordinates",+ "type": "gist",+ "unique": false,+ "expressions": [+ "coordinates"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "network_devices",+ "columnChanges": 5,+ "indexChanges": 1,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "CREATE",+ "name": "backup_mac",+ "newColumn": {+ "name": "backup_mac",+ "type": "macaddr",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "gateway",+ "newColumn": {+ "name": "gateway",+ "type": "inet",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "ip_address",+ "oldColumn": {+ "name": "ip_address",+ "type": "inet",+ "nullable": true+ },+ "newColumn": {+ "name": "ip_address",+ "type": "inet",+ "nullable": false+ }+ },+ {+ "action": "CREATE",+ "name": "network_range",+ "newColumn": {+ "name": "network_range",+ "type": "cidr",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "subnet_mask",+ "newColumn": {+ "name": "subnet_mask",+ "type": "inet",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "network_devices_mac_address_key",+ "newIndex": {+ "name": "network_devices_mac_address_key",+ "type": "btree",+ "unique": true,+ "expressions": [+ "mac_address"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "network_topology",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/expected_schema.sqlnew file mode 100644index 0000000000..236b88a9c8--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/expected_schema.sql@@ -0,0 +1,50 @@+-- Enhanced schema with comprehensive network and geometric types+CREATE TABLE public.network_devices (+ device_id SERIAL PRIMARY KEY,+ device_name VARCHAR(100) NOT NULL,+ ip_address INET NOT NULL, -- Made required+ network_range CIDR, -- New network range column+ mac_address MACADDR UNIQUE, -- Made unique+ backup_mac MACADDR, -- New MAC address column+ subnet_mask INET, -- New subnet information+ gateway INET -- New gateway address+);++CREATE TABLE public.locations (+ location_id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ coordinates POINT NOT NULL, -- Made required+ center_point POINT, -- New point column+ boundary_box BOX, -- New box geometric type+ service_area CIRCLE, -- New circle type+ coverage_polygon POLYGON, -- New polygon type+ route_path PATH -- New path type+);++CREATE TABLE public.geographic_features (+ feature_id SERIAL PRIMARY KEY,+ feature_name VARCHAR(200) NOT NULL,+ center_point POINT NOT NULL,+ bounding_box BOX NOT NULL,+ area_polygon POLYGON,+ coverage_circle CIRCLE,+ primary_line LSEG, -- Line segment+ reference_paths PATH[], -- Array of paths+ key_points POINT[] NOT NULL DEFAULT ARRAY[]::point[]+);++CREATE TABLE public.network_topology (+ topology_id SERIAL PRIMARY KEY,+ network_name VARCHAR(100) NOT NULL,+ network_cidr CIDR NOT NULL UNIQUE,+ gateway_ip INET NOT NULL,+ dns_servers INET[] DEFAULT ARRAY[]::inet[],+ device_macs MACADDR[] DEFAULT ARRAY[]::macaddr[],+ subnet_ranges CIDR[]+);++-- Add specialized indexes (GIST indexes for geometric types)+CREATE INDEX idx_locations_coordinates ON public.locations USING GIST(coordinates);+CREATE INDEX idx_locations_boundary ON public.locations USING GIST(boundary_box);+CREATE INDEX idx_features_center ON public.geographic_features USING GIST(center_point);+CREATE INDEX idx_features_polygon ON public.geographic_features USING GIST(area_polygon);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/initial_schema.sqlnew file mode 100644index 0000000000..87b9a72311--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/initial_schema.sql@@ -0,0 +1,13 @@+-- Initial schema with basic network and geometric types+CREATE TABLE public.network_devices (+ device_id SERIAL PRIMARY KEY,+ device_name VARCHAR(100) NOT NULL,+ ip_address INET,+ mac_address MACADDR+);++CREATE TABLE public.locations (+ location_id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ coordinates POINT+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/test_description.mdnew file mode 100644index 0000000000..bc4428dda0--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/advanced_types/network_geometric/test_description.md@@ -0,0 +1,19 @@+# Network and Geometric Data Types Test++This test validates the SDL migration handling of specialized PostgreSQL data types:++**Network Address Types**:+- **INET**: IPv4 and IPv6 addresses with optional netmask+- **CIDR**: Network addresses+- **MACADDR**: MAC addresses++**Geometric Types**:+- **POINT**: Points in 2D space+- **LINE**: Infinite lines+- **LSEG**: Line segments+- **BOX**: Rectangular boxes+- **PATH**: Geometric paths+- **POLYGON**: Closed geometric paths+- **CIRCLE**: Circles++Tests creation, indexing, and constraints for these specialized data types.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/ddl.sqlnew file mode 100644index 0000000000..1868f7dbc4--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/ddl.sql@@ -0,0 +1,9 @@+ALTER TABLE "public"."users" ADD COLUMN "last_login" timestamp(6) without time zone;+ALTER TABLE "public"."users" ADD COLUMN "middle_name" character varying(50);+ALTER TABLE "public"."users" ALTER COLUMN "age" TYPE bigint;+ALTER TABLE "public"."users" ALTER COLUMN "balance" TYPE numeric(12,4);+ALTER TABLE "public"."users" ALTER COLUMN "balance" DROP DEFAULT;+ALTER TABLE "public"."users" ALTER COLUMN "balance" SET DEFAULT 0.0000;+ALTER TABLE "public"."users" ALTER COLUMN "email" SET NOT NULL;+ALTER TABLE "public"."users" ALTER COLUMN "username" TYPE character varying(100);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/diff.jsonnew file mode 100644index 0000000000..b3ca9f6abe--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/diff.json@@ -0,0 +1,101 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 1",+ "tableChanges": 1,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 0,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "users",+ "columnChanges": 6,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "age",+ "oldColumn": {+ "name": "age",+ "type": "integer",+ "nullable": true+ },+ "newColumn": {+ "name": "age",+ "type": "bigint",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "balance",+ "oldColumn": {+ "name": "balance",+ "type": "numeric(10,2)",+ "nullable": true,+ "defaultValue": "0.00"+ },+ "newColumn": {+ "name": "balance",+ "type": "numeric(12,4)",+ "nullable": true,+ "defaultValue": "0.0000"+ }+ },+ {+ "action": "ALTER",+ "name": "email",+ "oldColumn": {+ "name": "email",+ "type": "character varying(100)",+ "nullable": true+ },+ "newColumn": {+ "name": "email",+ "type": "character varying(100)",+ "nullable": false+ }+ },+ {+ "action": "CREATE",+ "name": "last_login",+ "newColumn": {+ "name": "last_login",+ "type": "timestamp(6) without time zone",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "middle_name",+ "newColumn": {+ "name": "middle_name",+ "type": "character varying(50)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "username",+ "oldColumn": {+ "name": "username",+ "type": "character varying(50)",+ "nullable": false+ },+ "newColumn": {+ "name": "username",+ "type": "character varying(100)",+ "nullable": false+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/expected_schema.sqlnew file mode 100644index 0000000000..8a7c36d9bd--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/expected_schema.sql@@ -0,0 +1,16 @@+-- Modified table with altered column types+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY, -- Keep SERIAL to avoid sequence dependency issues+ username VARCHAR(100) NOT NULL, -- Expanded from VARCHAR(50) to VARCHAR(100)+ email VARCHAR(100) NOT NULL, -- Changed from nullable to NOT NULL+ age BIGINT, -- Changed from INTEGER to BIGINT+ balance DECIMAL(12,4) DEFAULT 0.0000, -- Expanded precision from (10,2) to (12,4)+ is_active BOOLEAN DEFAULT true,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ last_login TIMESTAMP, -- New nullable column+ middle_name VARCHAR(50) -- New nullable column+);++-- Keep existing indexes+CREATE UNIQUE INDEX idx_users_username ON public.users(username);+CREATE INDEX idx_users_email ON public.users(email);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/initial_schema.sqlnew file mode 100644index 0000000000..a3abaa083b--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/initial_schema.sql@@ -0,0 +1,14 @@+-- Initial table with basic column types+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL,+ email VARCHAR(100),+ age INTEGER,+ balance DECIMAL(10,2) DEFAULT 0.00,+ is_active BOOLEAN DEFAULT true,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++-- Sample data constraints+CREATE UNIQUE INDEX idx_users_username ON public.users(username);+CREATE INDEX idx_users_email ON public.users(email);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/test_description.mdnew file mode 100644index 0000000000..c9d5910017--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/alter_column_types/test_description.md@@ -0,0 +1,10 @@+# ALTER Column Types Test++This test validates the SDL migration handling of column type alterations:+- Expanding varchar length (VARCHAR(50) → VARCHAR(100))+- Compatible type conversions (INTEGER → BIGINT)+- Adding nullable columns to existing tables+- Modifying column default values+- Changing column nullability constraints++Tests proper handling of data-preserving schema alterations and their DDL generation.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sqlnew file mode 100644index 0000000000..899e747ce0--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/ddl.sql@@ -0,0 +1,26 @@+ALTER TABLE "public"."orders" ADD COLUMN "customer_phone" character varying(20);+ALTER TABLE "public"."orders" ADD COLUMN "notes" text;+ALTER TABLE "public"."orders" ADD COLUMN "shipping_address" jsonb;+ALTER TABLE "public"."orders" ADD COLUMN "tax_amount" numeric(15,4) DEFAULT 0.0000;+ALTER TABLE "public"."products" ADD COLUMN "dimensions" jsonb;+ALTER TABLE "public"."products" ADD COLUMN "tags" _text;+ALTER TABLE "public"."products" ADD COLUMN "updated_at" timestamp(6) with time zone;+ALTER TABLE "public"."products" ADD COLUMN "weight" numeric(6,3);+ALTER TABLE "public"."orders" ALTER COLUMN "customer_email" TYPE character varying(150);+ALTER TABLE "public"."orders" ALTER COLUMN "order_date" TYPE timestamp(6) with time zone;+ALTER TABLE "public"."orders" ALTER COLUMN "order_date" DROP DEFAULT;+ALTER TABLE "public"."orders" ALTER COLUMN "order_date" SET DEFAULT CURRENT_TIMESTAMP;+ALTER TABLE "public"."orders" ALTER COLUMN "status" TYPE character varying(30);+ALTER TABLE "public"."orders" ALTER COLUMN "status" DROP DEFAULT;+ALTER TABLE "public"."orders" ALTER COLUMN "status" SET DEFAULT 'pending';+ALTER TABLE "public"."orders" ALTER COLUMN "total_amount" TYPE numeric(15,4);+CREATE INDEX idx_orders_status ON public.orders USING btree (status);++ALTER TABLE "public"."products" ALTER COLUMN "category_ids" TYPE _int8;+ALTER TABLE "public"."products" ALTER COLUMN "created_at" TYPE timestamp(6) with time zone;+ALTER TABLE "public"."products" ALTER COLUMN "created_at" SET DEFAULT CURRENT_TIMESTAMP;+ALTER TABLE "public"."products" ALTER COLUMN "name" TYPE character varying(200);+ALTER TABLE "public"."products" ALTER COLUMN "price" TYPE numeric(12,4);+CREATE INDEX idx_products_tags ON public.products USING gin (tags);+CREATE INDEX idx_products_weight ON public.products USING btree (weight);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/diff.jsonnew file mode 100644index 0000000000..11f430539f--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/diff.json@@ -0,0 +1,275 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 2",+ "tableChanges": 2,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 0,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "orders",+ "columnChanges": 8,+ "indexChanges": 1,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "customer_email",+ "oldColumn": {+ "name": "customer_email",+ "type": "character varying(100)",+ "nullable": false+ },+ "newColumn": {+ "name": "customer_email",+ "type": "character varying(150)",+ "nullable": false+ }+ },+ {+ "action": "CREATE",+ "name": "customer_phone",+ "newColumn": {+ "name": "customer_phone",+ "type": "character varying(20)",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "notes",+ "newColumn": {+ "name": "notes",+ "type": "text",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "order_date",+ "oldColumn": {+ "name": "order_date",+ "type": "date",+ "nullable": false,+ "defaultValue": "CURRENT_DATE"+ },+ "newColumn": {+ "name": "order_date",+ "type": "timestamp(6) with time zone",+ "nullable": false,+ "defaultValue": "CURRENT_TIMESTAMP"+ }+ },+ {+ "action": "CREATE",+ "name": "shipping_address",+ "newColumn": {+ "name": "shipping_address",+ "type": "jsonb",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "status",+ "oldColumn": {+ "name": "status",+ "type": "character varying(20)",+ "nullable": true,+ "defaultValue": "'pending'::character varying"+ },+ "newColumn": {+ "name": "status",+ "type": "character varying(30)",+ "nullable": true,+ "defaultValue": "'pending'"+ }+ },+ {+ "action": "CREATE",+ "name": "tax_amount",+ "newColumn": {+ "name": "tax_amount",+ "type": "numeric(15,4)",+ "nullable": true,+ "defaultValue": "0.0000"+ }+ },+ {+ "action": "ALTER",+ "name": "total_amount",+ "oldColumn": {+ "name": "total_amount",+ "type": "numeric(10,2)",+ "nullable": true+ },+ "newColumn": {+ "name": "total_amount",+ "type": "numeric(15,4)",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_orders_status",+ "newIndex": {+ "name": "idx_orders_status",+ "type": "btree",+ "unique": false,+ "expressions": [+ "status"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "products",+ "columnChanges": 8,+ "indexChanges": 2,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "category_ids",+ "oldColumn": {+ "name": "category_ids",+ "type": "_int4",+ "nullable": true+ },+ "newColumn": {+ "name": "category_ids",+ "type": "_int8",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "created_at",+ "oldColumn": {+ "name": "created_at",+ "type": "timestamp(6) without time zone",+ "nullable": true+ },+ "newColumn": {+ "name": "created_at",+ "type": "timestamp(6) with time zone",+ "nullable": true,+ "defaultValue": "CURRENT_TIMESTAMP"+ }+ },+ {+ "action": "CREATE",+ "name": "dimensions",+ "newColumn": {+ "name": "dimensions",+ "type": "jsonb",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "name",+ "oldColumn": {+ "name": "name",+ "type": "character varying(100)",+ "nullable": false+ },+ "newColumn": {+ "name": "name",+ "type": "character varying(200)",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "price",+ "oldColumn": {+ "name": "price",+ "type": "numeric(8,2)",+ "nullable": false+ },+ "newColumn": {+ "name": "price",+ "type": "numeric(12,4)",+ "nullable": false+ }+ },+ {+ "action": "CREATE",+ "name": "tags",+ "newColumn": {+ "name": "tags",+ "type": "_text",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "updated_at",+ "newColumn": {+ "name": "updated_at",+ "type": "timestamp(6) with time zone",+ "nullable": true+ }+ },+ {+ "action": "CREATE",+ "name": "weight",+ "newColumn": {+ "name": "weight",+ "type": "numeric(6,3)",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "idx_products_tags",+ "newIndex": {+ "name": "idx_products_tags",+ "type": "gin",+ "unique": false,+ "expressions": [+ "tags"+ ],+ "descending": [+ false+ ]+ }+ },+ {+ "action": "CREATE",+ "name": "idx_products_weight",+ "newIndex": {+ "name": "idx_products_weight",+ "type": "btree",+ "unique": false,+ "expressions": [+ "weight"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/expected_schema.sqlnew file mode 100644index 0000000000..877bbbe450--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/expected_schema.sql@@ -0,0 +1,39 @@+-- Expected schema with complex alterations applied+CREATE TABLE public.products (+ product_id SERIAL PRIMARY KEY, -- Keep SERIAL to avoid sequence issues+ name VARCHAR(200) NOT NULL, -- Expanded from VARCHAR(100) to VARCHAR(200)+ description TEXT,+ price DECIMAL(12,4) NOT NULL, -- Expanded from DECIMAL(8,2) to DECIMAL(12,4)+ category_ids BIGINT[], -- Changed from INTEGER[] to BIGINT[]+ attributes JSONB,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, -- Added timezone and default+ updated_at TIMESTAMP WITH TIME ZONE, -- New column+ is_featured BOOLEAN DEFAULT false,+ weight DECIMAL(6,3), -- New column for product weight+ dimensions JSONB, -- New column for product dimensions+ tags TEXT[] -- New column for product tags+);++CREATE TABLE public.orders (+ order_id BIGSERIAL PRIMARY KEY, -- Keep BIGSERIAL to avoid sequence issues+ customer_email VARCHAR(150) NOT NULL, -- Expanded from VARCHAR(100)+ customer_phone VARCHAR(20), -- New nullable column+ order_date TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Changed from DATE to TIMESTAMPTZ+ total_amount NUMERIC(15,4), -- Expanded precision from NUMERIC(10,2)+ tax_amount NUMERIC(15,4) DEFAULT 0.0000, -- New column+ status VARCHAR(30) DEFAULT 'pending', -- Expanded from VARCHAR(20)+ shipping_address JSONB, -- New column for shipping details+ notes TEXT -- New column for order notes+);++-- Keep existing indexes with potentially updated column types+CREATE INDEX idx_products_name ON public.products(name);+CREATE INDEX idx_products_price ON public.products(price);+CREATE INDEX idx_products_attributes ON public.products USING GIN(attributes);+CREATE INDEX idx_orders_customer ON public.orders(customer_email);+CREATE INDEX idx_orders_date ON public.orders(order_date);++-- New indexes for new columns+CREATE INDEX idx_products_weight ON public.products(weight);+CREATE INDEX idx_products_tags ON public.products USING GIN(tags);+CREATE INDEX idx_orders_status ON public.orders(status);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/initial_schema.sqlnew file mode 100644index 0000000000..b06e8311a6--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/initial_schema.sql@@ -0,0 +1,26 @@+-- Initial schema with various data types+CREATE TABLE public.products (+ product_id SERIAL PRIMARY KEY,+ name VARCHAR(100) NOT NULL,+ description TEXT,+ price DECIMAL(8,2) NOT NULL,+ category_ids INTEGER[],+ attributes JSONB,+ created_at TIMESTAMP,+ is_featured BOOLEAN DEFAULT false+);++CREATE TABLE public.orders (+ order_id BIGSERIAL PRIMARY KEY,+ customer_email VARCHAR(100) NOT NULL,+ order_date DATE NOT NULL DEFAULT CURRENT_DATE,+ total_amount NUMERIC(10,2),+ status VARCHAR(20) DEFAULT 'pending'+);++-- Indexes that may be affected by column changes+CREATE INDEX idx_products_name ON public.products(name);+CREATE INDEX idx_products_price ON public.products(price);+CREATE INDEX idx_products_attributes ON public.products USING GIN(attributes);+CREATE INDEX idx_orders_customer ON public.orders(customer_email);+CREATE INDEX idx_orders_date ON public.orders(order_date);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/test_description.mdnew file mode 100644index 0000000000..6acaeebe9d--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/complex_alterations/test_description.md@@ -0,0 +1,10 @@+# Complex Data Type Alterations Test++This test validates the SDL migration handling of complex column alterations:+- Multiple column type changes in a single table+- Adding new columns with constraints and defaults+- Modifying existing column constraints and defaults+- Handling array data types and JSONB modifications+- Date/time precision changes and timezone conversions++Tests comprehensive schema evolution scenarios that combine multiple alteration types.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/ddl.sqlnew file mode 100644index 0000000000..f500702efb--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/ddl.sql@@ -0,0 +1,24 @@+CREATE SEQUENCE "public"."datetime_types_test_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."datetime_types_test" (+ "id" integer NOT NULL DEFAULT nextval('public.datetime_types_test_id_seq'::regclass),+ "date_col" date DEFAULT CURRENT_DATE,+ "date_birth" date NOT NULL,+ "time_col" time(6) without time zone,+ "time_with_tz" time(6) with time zone,+ "time_precise" time(6) without time zone DEFAULT CURRENT_TIME,+ "timestamp_col" timestamp(6) without time zone,+ "timestamp_with_tz" timestamp(6) with time zone DEFAULT CURRENT_TIMESTAMP,+ "timestamp_created" timestamp(6) without time zone DEFAULT NOW(),+ "timestamp_precise" timestamp(3) without time zone NOT NULL,+ "interval_col" interval,+ "interval_default" interval DEFAULT '1 day',+ CONSTRAINT "datetime_types_test_check_1" CHECK (date_birth <= CURRENT_DATE),+ CONSTRAINT "datetime_types_test_check_2" CHECK (timestamp_precise >= '2020-01-01'::timestamp),+ CONSTRAINT "datetime_types_test_check_3" CHECK (interval_col IS NULL OR interval_col >= '0 seconds'::interval)+);+ALTER TABLE "public"."datetime_types_test" ADD CONSTRAINT "datetime_types_test_pkey" PRIMARY KEY (id);+CREATE INDEX idx_datetime_date ON public.datetime_types_test USING btree (date_col);+CREATE INDEX idx_datetime_timestamp_tz ON public.datetime_types_test USING btree (timestamp_with_tz);+CREATE INDEX idx_datetime_created_desc ON public.datetime_types_test USING btree (timestamp_created DESC);+CREATE INDEX idx_datetime_birth_year ON public.datetime_types_test USING btree (EXTRACT(YEAR FROM date_birth));+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/diff.jsonnew file mode 100644index 0000000000..118a282ac1--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/diff.json@@ -0,0 +1,23 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 1, Sequence changes: 1",+ "tableChanges": 1,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "datetime_types_test",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/expected_schema.sqlnew file mode 100644index 0000000000..8735d3bb85--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/expected_schema.sql@@ -0,0 +1,34 @@+-- Test all PostgreSQL date and time data types+CREATE TABLE public.datetime_types_test (+ id SERIAL PRIMARY KEY,++ -- Date types+ date_col DATE DEFAULT CURRENT_DATE,+ date_birth DATE NOT NULL,++ -- Time types+ time_col TIME,+ time_with_tz TIME WITH TIME ZONE,+ time_precise TIME(6) DEFAULT CURRENT_TIME,++ -- Timestamp types+ timestamp_col TIMESTAMP,+ timestamp_with_tz TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,+ timestamp_created TIMESTAMP DEFAULT NOW(),+ timestamp_precise TIMESTAMP(3) NOT NULL,++ -- Interval type+ interval_col INTERVAL,+ interval_default INTERVAL DEFAULT '1 day',++ -- Constraints+ CHECK (date_birth <= CURRENT_DATE),+ CHECK (timestamp_precise >= '2020-01-01'::timestamp),+ CHECK (interval_col IS NULL OR interval_col >= '0 seconds'::interval)+);++-- Indexes on datetime columns+CREATE INDEX idx_datetime_date ON public.datetime_types_test(date_col);+CREATE INDEX idx_datetime_timestamp_tz ON public.datetime_types_test(timestamp_with_tz);+CREATE INDEX idx_datetime_created_desc ON public.datetime_types_test(timestamp_created DESC);+CREATE INDEX idx_datetime_birth_year ON public.datetime_types_test(EXTRACT(YEAR FROM date_birth));\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/initial_schema.sqlnew file mode 100644index 0000000000..e576ba21f6--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/initial_schema.sql@@ -0,0 +1 @@+-- Empty initial schema\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/test_description.mdnew file mode 100644index 0000000000..6c39d9d649--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/datetime_types/test_description.md@@ -0,0 +1,9 @@+# DateTime Data Types Test++This test validates the SDL migration handling of PostgreSQL date and time data types:+- DATE for date values+- TIME and TIME WITH TIME ZONE+- TIMESTAMP and TIMESTAMP WITH TIME ZONE (TIMESTAMPTZ)+- INTERVAL for time intervals++Tests creation with various defaults and constraints.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/ddl.sqlnew file mode 100644index 0000000000..a72bf0b822--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/ddl.sql@@ -0,0 +1,8 @@+DROP TABLE IF EXISTS "public"."temp_data";+DROP INDEX IF EXISTS "public"."idx_users_first_last";+DROP INDEX IF EXISTS "public"."idx_users_metadata";+ALTER TABLE "public"."users" DROP COLUMN IF EXISTS "first_name";+ALTER TABLE "public"."users" DROP COLUMN IF EXISTS "last_name";+ALTER TABLE "public"."users" DROP COLUMN IF EXISTS "metadata";+DROP SEQUENCE IF EXISTS "public"."temp_data_temp_id_seq";+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/diff.jsonnew file mode 100644index 0000000000..a50f21daae--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/diff.json@@ -0,0 +1,95 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 2, Sequence changes: 1",+ "tableChanges": 2,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "DROP",+ "schemaName": "public",+ "tableName": "temp_data",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "users",+ "columnChanges": 3,+ "indexChanges": 2,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "DROP",+ "name": "first_name",+ "oldColumn": {+ "name": "first_name",+ "type": "character varying(50)",+ "nullable": true+ }+ },+ {+ "action": "DROP",+ "name": "last_name",+ "oldColumn": {+ "name": "last_name",+ "type": "character varying(50)",+ "nullable": true+ }+ },+ {+ "action": "DROP",+ "name": "metadata",+ "oldColumn": {+ "name": "metadata",+ "type": "jsonb",+ "nullable": true+ }+ }+ ],+ "indexes": [+ {+ "action": "DROP",+ "name": "idx_users_first_last",+ "oldIndex": {+ "name": "idx_users_first_last",+ "type": "btree",+ "unique": false,+ "expressions": [+ "first_name",+ "last_name"+ ],+ "descending": [+ false,+ false+ ]+ }+ },+ {+ "action": "DROP",+ "name": "idx_users_metadata",+ "oldIndex": {+ "name": "idx_users_metadata",+ "type": "gin",+ "unique": false,+ "expressions": [+ "metadata"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/expected_schema.sqlnew file mode 100644index 0000000000..1373cf0614--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/expected_schema.sql@@ -0,0 +1,24 @@+-- Expected schema after dropping columns and table+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL UNIQUE,+ email VARCHAR(100) NOT NULL,+ -- first_name and last_name columns dropped+ age INTEGER,+ balance DECIMAL(10,2) DEFAULT 0.00,+ is_active BOOLEAN DEFAULT true,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP+ -- metadata column dropped (along with its GIN index)+);++CREATE TABLE public.user_sessions (+ session_id UUID PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES users(id),+ session_data JSONB,+ expires_at TIMESTAMP NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++-- temp_data table completely dropped+-- All related indexes and sequences should be cleaned up automatically\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/initial_schema.sqlnew file mode 100644index 0000000000..6250af4662--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/initial_schema.sql@@ -0,0 +1,36 @@+-- Initial schema with multiple tables and various data types+CREATE TABLE public.users (+ id SERIAL PRIMARY KEY,+ username VARCHAR(50) NOT NULL UNIQUE,+ email VARCHAR(100) NOT NULL,+ first_name VARCHAR(50),+ last_name VARCHAR(50),+ age INTEGER,+ balance DECIMAL(10,2) DEFAULT 0.00,+ is_active BOOLEAN DEFAULT true,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP,+ metadata JSONB+);++CREATE TABLE public.user_sessions (+ session_id UUID PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES users(id),+ session_data JSONB,+ expires_at TIMESTAMP NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++-- Table that will be completely dropped+CREATE TABLE public.temp_data (+ temp_id SERIAL PRIMARY KEY,+ temp_value TEXT,+ temp_number NUMERIC(15,5),+ temp_date DATE,+ temp_boolean BOOLEAN DEFAULT false+);++-- Indexes on columns that will be dropped+CREATE INDEX idx_users_first_last ON public.users(first_name, last_name);+CREATE INDEX idx_users_metadata ON public.users USING GIN(metadata);+CREATE INDEX idx_temp_value ON public.temp_data(temp_value);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/test_description.mdnew file mode 100644index 0000000000..5de07ab562--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/drop_columns_table/test_description.md@@ -0,0 +1,9 @@+# DROP Columns and Table Test++This test validates the SDL migration handling of DROP operations:+- Dropping individual columns from existing tables+- Dropping entire tables with various data types+- Handling dependencies (indexes, constraints) when dropping columns+- Proper cleanup of sequences and related objects++Tests proper DDL generation for destructive schema operations and dependency management.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/ddl.sqlnew file mode 100644index 0000000000..c217894c0b--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/ddl.sql@@ -0,0 +1,22 @@+CREATE SEQUENCE "public"."numeric_types_test_big_serial_col_seq" START WITH 1 INCREMENT BY 1;+CREATE SEQUENCE "public"."numeric_types_test_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."numeric_types_test" (+ "id" integer NOT NULL DEFAULT nextval('public.numeric_types_test_id_seq'::regclass),+ "small_int_col" smallint NOT NULL,+ "int_col" integer DEFAULT 0,+ "big_int_col" bigint,+ "decimal_col" numeric(10,2) NOT NULL,+ "numeric_col" numeric(15,3),+ "numeric_no_scale" numeric(8),+ "real_col" real,+ "double_col" double precision,+ "big_serial_col" bigint NOT NULL DEFAULT nextval('public.numeric_types_test_big_serial_col_seq'::regclass),+ CONSTRAINT "numeric_types_test_check_1" CHECK (small_int_col > 0),+ CONSTRAINT "numeric_types_test_check_2" CHECK (decimal_col >= 0)+);+ALTER TABLE "public"."numeric_types_test" ADD CONSTRAINT "numeric_types_test_pkey" PRIMARY KEY (id);+ALTER TABLE "public"."numeric_types_test" ADD CONSTRAINT "numeric_types_test_int_col_big_int_col_key" UNIQUE (int_col, big_int_col);+CREATE INDEX idx_numeric_decimal ON public.numeric_types_test USING btree (decimal_col);+CREATE INDEX idx_numeric_big_int ON public.numeric_types_test USING btree (big_int_col) WHERE big_int_col IS NOT NULL;+CREATE INDEX idx_numeric_composite ON public.numeric_types_test USING btree (int_col, real_col);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/diff.jsonnew file mode 100644index 0000000000..c1e2cecef4--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/diff.json@@ -0,0 +1,23 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 1, Sequence changes: 2",+ "tableChanges": 1,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 2,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "numeric_types_test",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/expected_schema.sqlnew file mode 100644index 0000000000..625abf9480--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/expected_schema.sql@@ -0,0 +1,29 @@+-- Test all PostgreSQL numeric data types+CREATE TABLE public.numeric_types_test (+ id SERIAL PRIMARY KEY,+ small_int_col SMALLINT NOT NULL,+ int_col INTEGER DEFAULT 0,+ big_int_col BIGINT,++ -- Decimal with different precision and scale+ decimal_col DECIMAL(10,2) NOT NULL,+ numeric_col NUMERIC(15,3),+ numeric_no_scale NUMERIC(8),++ -- Floating point types+ real_col REAL,+ double_col DOUBLE PRECISION,++ -- Auto-increment columns+ big_serial_col BIGSERIAL NOT NULL,++ -- Constraints+ CHECK (small_int_col > 0),+ CHECK (decimal_col >= 0),+ UNIQUE (int_col, big_int_col)+);++-- Indexes on numeric columns+CREATE INDEX idx_numeric_decimal ON public.numeric_types_test(decimal_col);+CREATE INDEX idx_numeric_big_int ON public.numeric_types_test(big_int_col) WHERE big_int_col IS NOT NULL;+CREATE INDEX idx_numeric_composite ON public.numeric_types_test(int_col, real_col);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/initial_schema.sqlnew file mode 100644index 0000000000..797fecfd78--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/initial_schema.sql@@ -0,0 +1 @@+-- Empty initial schema - start from scratch\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/test_description.mdnew file mode 100644index 0000000000..223a42eb74--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/numeric_types/test_description.md@@ -0,0 +1,9 @@+# Numeric Data Types Test++This test validates the SDL migration handling of all PostgreSQL numeric data types:+- SMALLINT, INTEGER, BIGINT+- DECIMAL, NUMERIC with various precision/scale+- REAL, DOUBLE PRECISION+- SERIAL, BIGSERIAL++Tests both creation and modification of numeric columns with different constraints.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/ddl.sqlnew file mode 100644index 0000000000..e4e0fbda5b--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/ddl.sql@@ -0,0 +1,9 @@+CREATE SEQUENCE "public"."simple_test_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."simple_test" (+ "id" integer NOT NULL DEFAULT nextval('public.simple_test_id_seq'::regclass),+ "name" character varying(50) NOT NULL,+ "age" integer,+ "active" boolean DEFAULT true+);+ALTER TABLE "public"."simple_test" ADD CONSTRAINT "simple_test_pkey" PRIMARY KEY (id);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/diff.jsonnew file mode 100644index 0000000000..f9d30c8a59--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/diff.json@@ -0,0 +1,23 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 1, Sequence changes: 1",+ "tableChanges": 1,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "simple_test",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/expected_schema.sqlnew file mode 100644index 0000000000..729c370d45--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/expected_schema.sql@@ -0,0 +1,7 @@+-- Simple table with basic types+CREATE TABLE public.simple_test (+ id SERIAL PRIMARY KEY,+ name VARCHAR(50) NOT NULL,+ age INTEGER,+ active BOOLEAN DEFAULT true+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/initial_schema.sqlnew file mode 100644index 0000000000..e576ba21f6--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/initial_schema.sql@@ -0,0 +1 @@+-- Empty initial schema\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/test_description.mdnew file mode 100644index 0000000000..8dc0fe74cc--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/simple_table/test_description.md@@ -0,0 +1,3 @@+# Simple Table Test++Test basic table creation with simple column types to validate the SDL framework.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/ddl.sqlnew file mode 100644index 0000000000..59dd3c2d06--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/ddl.sql@@ -0,0 +1,18 @@+CREATE SEQUENCE "public"."string_types_test_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."string_types_test" (+ "id" integer NOT NULL DEFAULT nextval('public.string_types_test_id_seq'::regclass),+ "char_col" character(10),+ "char_default" character(1) DEFAULT 'A',+ "varchar_short" character varying(50) NOT NULL,+ "varchar_long" character varying(500),+ "varchar_no_limit" character varying,+ "text_col" text,+ "text_with_default" text DEFAULT 'default text',+ CONSTRAINT "string_types_test_check_1" CHECK (LENGTH(text_col) > 0 OR text_col IS NULL)+);+ALTER TABLE "public"."string_types_test" ADD CONSTRAINT "string_types_test_pkey" PRIMARY KEY (id);+ALTER TABLE "public"."string_types_test" ADD CONSTRAINT "string_types_test_varchar_short_key" UNIQUE (varchar_short);+CREATE INDEX idx_string_varchar_short ON public.string_types_test USING btree (varchar_short);+CREATE INDEX idx_string_text_prefix ON public.string_types_test USING btree (LEFT(text_col, 50)) WHERE text_col IS NOT NULL;+CREATE INDEX idx_string_char_col ON public.string_types_test USING btree (char_col) WHERE char_col IS NOT NULL;+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/diff.jsonnew file mode 100644index 0000000000..c099e85d32--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/diff.json@@ -0,0 +1,23 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 1, Sequence changes: 1",+ "tableChanges": 1,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "string_types_test",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/expected_schema.sqlnew file mode 100644index 0000000000..c1b0f192a2--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/expected_schema.sql@@ -0,0 +1,32 @@+-- Expanded table with comprehensive string types+CREATE TABLE public.basic_strings (+ id SERIAL PRIMARY KEY,+ short_name VARCHAR(20) NOT NULL,+ description TEXT+);++CREATE TABLE public.string_types_test (+ id SERIAL PRIMARY KEY,++ -- Fixed length character types+ char_col CHAR(10),+ char_default CHAR(1) DEFAULT 'A',++ -- Variable length character types+ varchar_short VARCHAR(50) NOT NULL,+ varchar_long VARCHAR(500),+ varchar_no_limit VARCHAR,++ -- Unlimited text+ text_col TEXT,+ text_with_default TEXT DEFAULT 'default text',++ -- Constraints and indexes+ UNIQUE (varchar_short),+ CHECK (LENGTH(text_col) > 0 OR text_col IS NULL)+);++-- Create indexes on string columns+CREATE INDEX idx_string_varchar_short ON public.string_types_test(varchar_short);+CREATE INDEX idx_string_text_prefix ON public.string_types_test(LEFT(text_col, 50)) WHERE text_col IS NOT NULL;+CREATE INDEX idx_string_char_col ON public.string_types_test(char_col) WHERE char_col IS NOT NULL;\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/initial_schema.sqlnew file mode 100644index 0000000000..787b69830c--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/initial_schema.sql@@ -0,0 +1,6 @@+-- Basic table with some string types+CREATE TABLE public.basic_strings (+ id SERIAL PRIMARY KEY,+ short_name VARCHAR(20) NOT NULL,+ description TEXT+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/test_description.mdnew file mode 100644index 0000000000..9efbe32115--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/basic_types/string_types/test_description.md@@ -0,0 +1,8 @@+# String Data Types Test++This test validates the SDL migration handling of PostgreSQL string data types:+- CHAR, VARCHAR with different lengths+- TEXT and unlimited text+- CITEXT for case-insensitive text++Tests both creation and modification of string columns with length changes.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/ddl.sqlnew file mode 100644index 0000000000..6131c54add--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/ddl.sql@@ -0,0 +1,32 @@+CREATE SEQUENCE "public"."analytics_record_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."analytics" (+ "record_id" bigint NOT NULL DEFAULT nextval('public.analytics_record_id_seq'::regclass),+ "metric_name" character varying(200) NOT NULL,+ "value_small" bigint,+ "value_int" numeric(20,6),+ "description" text,+ "measured_at" timestamp(6) with time zone DEFAULT CURRENT_TIMESTAMP,+ "precision_value" double precision+);+ALTER TABLE "public"."analytics" ADD CONSTRAINT "analytics_pkey" PRIMARY KEY (record_id);++ALTER TABLE "public"."customers" ALTER COLUMN "credit_limit" TYPE numeric(12,4);+ALTER TABLE "public"."customers" ALTER COLUMN "credit_limit" DROP DEFAULT;+ALTER TABLE "public"."customers" ALTER COLUMN "credit_limit" SET DEFAULT 1000.0000;+ALTER TABLE "public"."customers" ALTER COLUMN "customer_id" TYPE bigint;+ALTER TABLE "public"."customers" ALTER COLUMN "email" TYPE text;+ALTER TABLE "public"."customers" ALTER COLUMN "last_login" TYPE timestamp(6) with time zone;+ALTER TABLE "public"."customers" ALTER COLUMN "signup_date" TYPE timestamp(6) with time zone;+ALTER TABLE "public"."customers" ALTER COLUMN "username" TYPE character varying(50);++ALTER TABLE "public"."products" ALTER COLUMN "created_date" TYPE timestamp(6) without time zone;+ALTER TABLE "public"."products" ALTER COLUMN "created_date" DROP DEFAULT;+ALTER TABLE "public"."products" ALTER COLUMN "created_date" SET DEFAULT CURRENT_TIMESTAMP;+ALTER TABLE "public"."products" ALTER COLUMN "description" TYPE text;+ALTER TABLE "public"."products" ALTER COLUMN "name" TYPE character varying(100);+ALTER TABLE "public"."products" ALTER COLUMN "price" TYPE double precision;+ALTER TABLE "public"."products" ALTER COLUMN "product_id" TYPE bigint;+ALTER TABLE "public"."products" ALTER COLUMN "quantity" TYPE bigint;+ALTER TABLE "public"."products" ALTER COLUMN "rating" TYPE numeric(5,2);+ALTER TABLE "public"."products" ALTER COLUMN "updated_time" TYPE time(6) with time zone;+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/diff.jsonnew file mode 100644index 0000000000..0ed31b3b54--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/diff.json@@ -0,0 +1,249 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 3, Sequence changes: 1",+ "tableChanges": 3,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "analytics",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "customers",+ "columnChanges": 6,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "credit_limit",+ "oldColumn": {+ "name": "credit_limit",+ "type": "numeric(8,2)",+ "nullable": true,+ "defaultValue": "1000.00"+ },+ "newColumn": {+ "name": "credit_limit",+ "type": "numeric(12,4)",+ "nullable": true,+ "defaultValue": "1000.0000"+ }+ },+ {+ "action": "ALTER",+ "name": "customer_id",+ "oldColumn": {+ "name": "customer_id",+ "type": "integer",+ "nullable": false+ },+ "newColumn": {+ "name": "customer_id",+ "type": "bigint",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "email",+ "oldColumn": {+ "name": "email",+ "type": "character varying(100)",+ "nullable": false+ },+ "newColumn": {+ "name": "email",+ "type": "text",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "last_login",+ "oldColumn": {+ "name": "last_login",+ "type": "timestamp(6) without time zone",+ "nullable": true+ },+ "newColumn": {+ "name": "last_login",+ "type": "timestamp(6) with time zone",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "signup_date",+ "oldColumn": {+ "name": "signup_date",+ "type": "date",+ "nullable": false+ },+ "newColumn": {+ "name": "signup_date",+ "type": "timestamp(6) with time zone",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "username",+ "oldColumn": {+ "name": "username",+ "type": "character varying(30)",+ "nullable": false+ },+ "newColumn": {+ "name": "username",+ "type": "character varying(50)",+ "nullable": false+ }+ }+ ]+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "products",+ "columnChanges": 8,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "created_date",+ "oldColumn": {+ "name": "created_date",+ "type": "date",+ "nullable": true,+ "defaultValue": "CURRENT_DATE"+ },+ "newColumn": {+ "name": "created_date",+ "type": "timestamp(6) without time zone",+ "nullable": true,+ "defaultValue": "CURRENT_TIMESTAMP"+ }+ },+ {+ "action": "ALTER",+ "name": "description",+ "oldColumn": {+ "name": "description",+ "type": "character varying(200)",+ "nullable": true+ },+ "newColumn": {+ "name": "description",+ "type": "text",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "name",+ "oldColumn": {+ "name": "name",+ "type": "character(50)",+ "nullable": false+ },+ "newColumn": {+ "name": "name",+ "type": "character varying(100)",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "price",+ "oldColumn": {+ "name": "price",+ "type": "real",+ "nullable": false+ },+ "newColumn": {+ "name": "price",+ "type": "double precision",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "product_id",+ "oldColumn": {+ "name": "product_id",+ "type": "smallint",+ "nullable": false+ },+ "newColumn": {+ "name": "product_id",+ "type": "bigint",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "quantity",+ "oldColumn": {+ "name": "quantity",+ "type": "integer",+ "nullable": true,+ "defaultValue": "0"+ },+ "newColumn": {+ "name": "quantity",+ "type": "bigint",+ "nullable": true,+ "defaultValue": "0"+ }+ },+ {+ "action": "ALTER",+ "name": "rating",+ "oldColumn": {+ "name": "rating",+ "type": "numeric(3,1)",+ "nullable": true+ },+ "newColumn": {+ "name": "rating",+ "type": "numeric(5,2)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "updated_time",+ "oldColumn": {+ "name": "updated_time",+ "type": "time(6) without time zone",+ "nullable": true,+ "defaultValue": "CURRENT_TIME"+ },+ "newColumn": {+ "name": "updated_time",+ "type": "time(6) with time zone",+ "nullable": true,+ "defaultValue": "CURRENT_TIME"+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/expected_schema.sqlnew file mode 100644index 0000000000..e65d80f45c--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/expected_schema.sql@@ -0,0 +1,30 @@+-- Enhanced schema with compatible type promotions+CREATE TABLE public.products (+ product_id BIGINT PRIMARY KEY, -- SMALLINT → BIGINT+ name VARCHAR(100) NOT NULL, -- CHAR(50) → VARCHAR(100)+ description TEXT, -- VARCHAR(200) → TEXT+ price DOUBLE PRECISION NOT NULL, -- REAL → DOUBLE PRECISION+ quantity BIGINT DEFAULT 0, -- INTEGER → BIGINT+ rating NUMERIC(5,2), -- NUMERIC(3,1) → NUMERIC(5,2) expanded precision+ created_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- DATE → TIMESTAMP+ updated_time TIME WITH TIME ZONE DEFAULT CURRENT_TIME -- TIME → TIME WITH TIME ZONE+);++CREATE TABLE public.customers (+ customer_id BIGINT PRIMARY KEY, -- INTEGER → BIGINT+ username VARCHAR(50) UNIQUE NOT NULL, -- VARCHAR(30) → VARCHAR(50)+ email TEXT NOT NULL, -- VARCHAR(100) → TEXT+ credit_limit NUMERIC(12,4) DEFAULT 1000.0000, -- NUMERIC(8,2) → NUMERIC(12,4)+ signup_date TIMESTAMP WITH TIME ZONE NOT NULL, -- DATE → TIMESTAMP WITH TIME ZONE+ last_login TIMESTAMP WITH TIME ZONE -- TIMESTAMP → TIMESTAMP WITH TIME ZONE+);++CREATE TABLE public.analytics (+ record_id BIGSERIAL PRIMARY KEY,+ metric_name VARCHAR(200) NOT NULL,+ value_small BIGINT, -- For SMALLINT → BIGINT conversion+ value_int NUMERIC(20,6), -- For INTEGER → NUMERIC conversion+ description TEXT, -- For various string → TEXT conversions+ measured_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ precision_value DOUBLE PRECISION -- For REAL → DOUBLE PRECISION+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/initial_schema.sqlnew file mode 100644index 0000000000..c0d0ef2713--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/initial_schema.sql@@ -0,0 +1,20 @@+-- Initial schema with types that can be safely converted+CREATE TABLE public.products (+ product_id SMALLINT PRIMARY KEY,+ name CHAR(50) NOT NULL,+ description VARCHAR(200),+ price REAL NOT NULL,+ quantity INTEGER DEFAULT 0,+ rating NUMERIC(3,1),+ created_date DATE DEFAULT CURRENT_DATE,+ updated_time TIME DEFAULT CURRENT_TIME+);++CREATE TABLE public.customers (+ customer_id INTEGER PRIMARY KEY,+ username VARCHAR(30) UNIQUE NOT NULL,+ email VARCHAR(100) NOT NULL,+ credit_limit NUMERIC(8,2) DEFAULT 1000.00,+ signup_date DATE NOT NULL,+ last_login TIMESTAMP+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/test_description.mdnew file mode 100644index 0000000000..7129415226--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/compatible_conversions/test_description.md@@ -0,0 +1,22 @@+# Compatible Data Type Conversions Test++This test validates the SDL migration handling of safe, compatible data type conversions:++**Numeric Type Promotions**:+- SMALLINT → INTEGER → BIGINT+- INTEGER → NUMERIC/DECIMAL+- REAL → DOUBLE PRECISION+- NUMERIC precision expansion++**String Type Extensions**:+- CHAR(n) → VARCHAR(m) where m >= n+- VARCHAR(n) → VARCHAR(m) where m > n+- VARCHAR(n) → TEXT+- TEXT → CITEXT++**Temporal Type Enhancements**:+- DATE → TIMESTAMP+- TIMESTAMP → TIMESTAMP WITH TIME ZONE+- TIME → TIME WITH TIME ZONE++Tests data-preserving conversions that should execute without data loss.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/ddl.sqlnew file mode 100644index 0000000000..ad594b7121--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/ddl.sql@@ -0,0 +1,15 @@+ALTER TABLE "public"."data_conflicts" ALTER COLUMN "default_change" DROP DEFAULT;+ALTER TABLE "public"."data_conflicts" ALTER COLUMN "default_change" SET DEFAULT 999;+ALTER TABLE "public"."data_conflicts" ALTER COLUMN "nullable_required" SET NOT NULL;+ALTER TABLE "public"."data_conflicts" ALTER COLUMN "type_change" TYPE integer USING "type_change"::integer;+ALTER TABLE "public"."data_conflicts" ALTER COLUMN "wide_varchar" TYPE character varying(10) USING "wide_varchar"::character varying(10);+ALTER TABLE "public"."data_conflicts" ADD CONSTRAINT "data_conflicts_unique_field_key" UNIQUE (unique_field);++ALTER TABLE "public"."risky_conversions" ALTER COLUMN "array_field" TYPE text;+ALTER TABLE "public"."risky_conversions" ALTER COLUMN "high_precision" TYPE real USING "high_precision"::real;+ALTER TABLE "public"."risky_conversions" ALTER COLUMN "json_field" TYPE text USING "json_field"::text;+ALTER TABLE "public"."risky_conversions" ALTER COLUMN "large_int" TYPE smallint USING "large_int"::smallint;+ALTER TABLE "public"."risky_conversions" ALTER COLUMN "numeric_text" TYPE integer USING "numeric_text"::integer;+ALTER TABLE "public"."risky_conversions" ALTER COLUMN "text_to_numeric" TYPE numeric(10,2) USING "text_to_numeric"::numeric(10,2);+ALTER TABLE "public"."risky_conversions" ALTER COLUMN "timestamp_field" TYPE date;+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/diff.jsonnew file mode 100644index 0000000000..a0ee94b871--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/diff.json@@ -0,0 +1,209 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 2",+ "tableChanges": 2,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 0,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "data_conflicts",+ "columnChanges": 4,+ "indexChanges": 1,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "default_change",+ "oldColumn": {+ "name": "default_change",+ "type": "integer",+ "nullable": true,+ "defaultValue": "100"+ },+ "newColumn": {+ "name": "default_change",+ "type": "integer",+ "nullable": true,+ "defaultValue": "999"+ }+ },+ {+ "action": "ALTER",+ "name": "nullable_required",+ "oldColumn": {+ "name": "nullable_required",+ "type": "character varying(100)",+ "nullable": true+ },+ "newColumn": {+ "name": "nullable_required",+ "type": "character varying(100)",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "type_change",+ "oldColumn": {+ "name": "type_change",+ "type": "text",+ "nullable": true+ },+ "newColumn": {+ "name": "type_change",+ "type": "integer",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "wide_varchar",+ "oldColumn": {+ "name": "wide_varchar",+ "type": "character varying(500)",+ "nullable": false+ },+ "newColumn": {+ "name": "wide_varchar",+ "type": "character varying(10)",+ "nullable": false+ }+ }+ ],+ "indexes": [+ {+ "action": "CREATE",+ "name": "data_conflicts_unique_field_key",+ "newIndex": {+ "name": "data_conflicts_unique_field_key",+ "type": "btree",+ "unique": true,+ "expressions": [+ "unique_field"+ ],+ "descending": [+ false+ ]+ }+ }+ ]+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "risky_conversions",+ "columnChanges": 7,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "array_field",+ "oldColumn": {+ "name": "array_field",+ "type": "_int4",+ "nullable": true+ },+ "newColumn": {+ "name": "array_field",+ "type": "text",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "high_precision",+ "oldColumn": {+ "name": "high_precision",+ "type": "double precision",+ "nullable": true+ },+ "newColumn": {+ "name": "high_precision",+ "type": "real",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "json_field",+ "oldColumn": {+ "name": "json_field",+ "type": "jsonb",+ "nullable": true+ },+ "newColumn": {+ "name": "json_field",+ "type": "text",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "large_int",+ "oldColumn": {+ "name": "large_int",+ "type": "bigint",+ "nullable": true+ },+ "newColumn": {+ "name": "large_int",+ "type": "smallint",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "numeric_text",+ "oldColumn": {+ "name": "numeric_text",+ "type": "text",+ "nullable": true+ },+ "newColumn": {+ "name": "numeric_text",+ "type": "integer",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "text_to_numeric",+ "oldColumn": {+ "name": "text_to_numeric",+ "type": "character varying(100)",+ "nullable": false+ },+ "newColumn": {+ "name": "text_to_numeric",+ "type": "numeric(10,2)",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "timestamp_field",+ "oldColumn": {+ "name": "timestamp_field",+ "type": "timestamp(6) with time zone",+ "nullable": true+ },+ "newColumn": {+ "name": "timestamp_field",+ "type": "date",+ "nullable": true+ }+ }+ ]+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/expected_schema.sqlnew file mode 100644index 0000000000..cd80abbc38--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/expected_schema.sql@@ -0,0 +1,29 @@+-- Schema with potentially incompatible type conversions+CREATE TABLE public.risky_conversions (+ conversion_id SERIAL PRIMARY KEY,+ text_to_numeric NUMERIC(10,2) NOT NULL, -- VARCHAR(100) → NUMERIC(10,2) (data validation required)+ large_int SMALLINT, -- BIGINT → SMALLINT (potential overflow)+ high_precision REAL, -- DOUBLE PRECISION → REAL (precision loss)+ timestamp_field DATE, -- TIMESTAMP WITH TIME ZONE → DATE (time component lost)+ json_field TEXT, -- JSONB → TEXT (structure lost)+ array_field TEXT, -- INTEGER[] → TEXT (array structure lost)+ numeric_text INTEGER -- TEXT → INTEGER (parsing required)+);++CREATE TABLE public.data_conflicts (+ conflict_id SERIAL PRIMARY KEY,+ wide_varchar VARCHAR(10) NOT NULL, -- VARCHAR(500) → VARCHAR(10) (truncation risk)+ nullable_required VARCHAR(100) NOT NULL, -- Added NOT NULL constraint (existing nulls problem)+ unique_field VARCHAR(100) UNIQUE, -- Added UNIQUE constraint (duplicate values problem)+ default_change INTEGER DEFAULT 999, -- Changed default: 100 → 999+ type_change INTEGER -- TEXT → INTEGER (parsing validation required)+);++-- These conversions represent various incompatibility scenarios:+-- 1. Data validation failures (text that can't convert to numeric)+-- 2. Data truncation (large values that don't fit in smaller types)+-- 3. Precision loss (high precision to low precision)+-- 4. Information loss (timestamp to date, structured to text)+-- 5. Constraint violations (nulls where NOT NULL required)+-- 6. Uniqueness violations (duplicates where UNIQUE required)+-- 7. Format validation failures (invalid integer strings)\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/initial_schema.sqlnew file mode 100644index 0000000000..07d80c5840--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/initial_schema.sql@@ -0,0 +1,20 @@+-- Initial schema with types that will be converted incompatibly+CREATE TABLE public.risky_conversions (+ conversion_id SERIAL PRIMARY KEY,+ text_to_numeric VARCHAR(100) NOT NULL, -- Will convert to NUMERIC+ large_int BIGINT, -- Will convert to SMALLINT (lossy)+ high_precision DOUBLE PRECISION, -- Will convert to REAL (precision loss)+ timestamp_field TIMESTAMP WITH TIME ZONE, -- Will convert to DATE (time loss)+ json_field JSONB, -- Will convert to TEXT+ array_field INTEGER[], -- Will convert to TEXT+ numeric_text TEXT -- Contains numeric data, will convert to INTEGER+);++CREATE TABLE public.data_conflicts (+ conflict_id SERIAL PRIMARY KEY,+ wide_varchar VARCHAR(500) NOT NULL, -- Will reduce to VARCHAR(10)+ nullable_required VARCHAR(100), -- Will become NOT NULL+ unique_field VARCHAR(100), -- Will add UNIQUE constraint+ default_change INTEGER DEFAULT 100, -- Will change default value+ type_change TEXT -- Will change to completely different type+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/test_description.mdnew file mode 100644index 0000000000..d20278466a--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/incompatible_conversions/test_description.md@@ -0,0 +1,25 @@+# Incompatible Data Type Conversions Test++This test validates the SDL migration handling of potentially incompatible type conversions that may require data validation or cause data loss:++**High Risk Conversions**:+- VARCHAR(100) → NUMERIC(10,2) - Text to numeric conversion requiring validation+- BIGINT → SMALLINT - Potential integer overflow+- DOUBLE PRECISION → REAL - Precision loss in floating point+- TIMESTAMP WITH TIME ZONE → DATE - Time component loss++**Data Structure Loss**:+- JSONB → TEXT - Structured data becomes plain text+- INTEGER[] → TEXT - Array structure becomes string representation+- TEXT → INTEGER - String parsing with potential failures++**Constraint Conflicts**:+- VARCHAR(500) → VARCHAR(10) - Potential data truncation+- NULL allowed → NOT NULL - Existing null values become invalid+- No constraint → UNIQUE - Existing duplicates become invalid+- Default value changes - May affect application behavior++**Format Validation**:+- TEXT → INTEGER - String parsing validation required++These conversions typically require careful data migration planning and validation to ensure no data loss or constraint violations occur during the schema evolution.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sqlnew file mode 100644index 0000000000..0e9d27df2a--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/ddl.sql@@ -0,0 +1,37 @@+CREATE SEQUENCE "public"."precision_test_test_id_seq" START WITH 1 INCREMENT BY 1;+CREATE TABLE "public"."precision_test" (+ "test_id" integer NOT NULL DEFAULT nextval('public.precision_test_test_id_seq'::regclass),+ "expand_varchar" character varying(500),+ "reduce_varchar" character varying(25),+ "expand_numeric" numeric(25,10),+ "reduce_numeric" numeric(4,1),+ "expand_char" character(50),+ "reduce_char" character(5),+ "expand_bits" bit(128),+ "reduce_bits" bit(4),+ "expand_varbits" bit varying(256),+ "reduce_varbits" bit varying(8)+);+ALTER TABLE "public"."precision_test" ADD CONSTRAINT "precision_test_pkey" PRIMARY KEY (test_id);++ALTER TABLE "public"."data_samples" ALTER COLUMN "bit_flags" TYPE bit(32);+ALTER TABLE "public"."data_samples" ALTER COLUMN "bit_flags" DROP DEFAULT;+ALTER TABLE "public"."data_samples" ALTER COLUMN "bit_flags" SET DEFAULT B'00000000000000000000000000000000';+ALTER TABLE "public"."data_samples" ALTER COLUMN "fixed_char" TYPE character(20);+ALTER TABLE "public"."data_samples" ALTER COLUMN "long_text" TYPE character varying(150);+ALTER TABLE "public"."data_samples" ALTER COLUMN "precise_decimal" TYPE numeric(16,6);+ALTER TABLE "public"."data_samples" ALTER COLUMN "precise_decimal" DROP DEFAULT;+ALTER TABLE "public"."data_samples" ALTER COLUMN "precise_decimal" SET DEFAULT 0.000000;+ALTER TABLE "public"."data_samples" ALTER COLUMN "short_text" TYPE character varying(100);+ALTER TABLE "public"."data_samples" ALTER COLUMN "simple_decimal" TYPE numeric(5,1);+ALTER TABLE "public"."data_samples" ALTER COLUMN "simple_decimal" DROP DEFAULT;+ALTER TABLE "public"."data_samples" ALTER COLUMN "simple_decimal" SET DEFAULT 0.0;+ALTER TABLE "public"."data_samples" ALTER COLUMN "var_bits" TYPE bit varying(16);++ALTER TABLE "public"."measurements" ALTER COLUMN "device_name" TYPE character varying(150);+ALTER TABLE "public"."measurements" ALTER COLUMN "location_code" TYPE character(15);+ALTER TABLE "public"."measurements" ALTER COLUMN "metadata_bits" TYPE bit varying(32);+ALTER TABLE "public"."measurements" ALTER COLUMN "status_bits" TYPE bit(64);+ALTER TABLE "public"."measurements" ALTER COLUMN "value_high_precision" TYPE numeric(20,12);+ALTER TABLE "public"."measurements" ALTER COLUMN "value_low_precision" TYPE numeric(6,2);+diff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/diff.json b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/diff.jsonnew file mode 100644index 0000000000..93aafaf6e3--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/diff.json@@ -0,0 +1,233 @@+{+ "hasDifferences": true,+ "summary": "Table changes: 3, Sequence changes: 1",+ "tableChanges": 3,+ "viewChanges": 0,+ "functionChanges": 0,+ "schemaChanges": 0,+ "sequenceChanges": 1,+ "enumTypeChanges": 0,+ "details": {+ "tables": [+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "data_samples",+ "columnChanges": 7,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "bit_flags",+ "oldColumn": {+ "name": "bit_flags",+ "type": "bit(16)",+ "nullable": true,+ "defaultValue": "'0000000000000000'::\"bit\""+ },+ "newColumn": {+ "name": "bit_flags",+ "type": "bit(32)",+ "nullable": true,+ "defaultValue": "B'00000000000000000000000000000000'"+ }+ },+ {+ "action": "ALTER",+ "name": "fixed_char",+ "oldColumn": {+ "name": "fixed_char",+ "type": "character(10)",+ "nullable": true+ },+ "newColumn": {+ "name": "fixed_char",+ "type": "character(20)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "long_text",+ "oldColumn": {+ "name": "long_text",+ "type": "character varying(200)",+ "nullable": true+ },+ "newColumn": {+ "name": "long_text",+ "type": "character varying(150)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "precise_decimal",+ "oldColumn": {+ "name": "precise_decimal",+ "type": "numeric(12,4)",+ "nullable": true,+ "defaultValue": "0.0000"+ },+ "newColumn": {+ "name": "precise_decimal",+ "type": "numeric(16,6)",+ "nullable": true,+ "defaultValue": "0.000000"+ }+ },+ {+ "action": "ALTER",+ "name": "short_text",+ "oldColumn": {+ "name": "short_text",+ "type": "character varying(50)",+ "nullable": false+ },+ "newColumn": {+ "name": "short_text",+ "type": "character varying(100)",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "simple_decimal",+ "oldColumn": {+ "name": "simple_decimal",+ "type": "numeric(6,2)",+ "nullable": true,+ "defaultValue": "0.00"+ },+ "newColumn": {+ "name": "simple_decimal",+ "type": "numeric(5,1)",+ "nullable": true,+ "defaultValue": "0.0"+ }+ },+ {+ "action": "ALTER",+ "name": "var_bits",+ "oldColumn": {+ "name": "var_bits",+ "type": "bit varying(32)",+ "nullable": true+ },+ "newColumn": {+ "name": "var_bits",+ "type": "bit varying(16)",+ "nullable": true+ }+ }+ ]+ },+ {+ "action": "ALTER",+ "schemaName": "public",+ "tableName": "measurements",+ "columnChanges": 6,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0,+ "columns": [+ {+ "action": "ALTER",+ "name": "device_name",+ "oldColumn": {+ "name": "device_name",+ "type": "character varying(100)",+ "nullable": false+ },+ "newColumn": {+ "name": "device_name",+ "type": "character varying(150)",+ "nullable": false+ }+ },+ {+ "action": "ALTER",+ "name": "location_code",+ "oldColumn": {+ "name": "location_code",+ "type": "character(20)",+ "nullable": true+ },+ "newColumn": {+ "name": "location_code",+ "type": "character(15)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "metadata_bits",+ "oldColumn": {+ "name": "metadata_bits",+ "type": "bit varying(64)",+ "nullable": true+ },+ "newColumn": {+ "name": "metadata_bits",+ "type": "bit varying(32)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "status_bits",+ "oldColumn": {+ "name": "status_bits",+ "type": "bit(32)",+ "nullable": true+ },+ "newColumn": {+ "name": "status_bits",+ "type": "bit(64)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "value_high_precision",+ "oldColumn": {+ "name": "value_high_precision",+ "type": "numeric(15,8)",+ "nullable": true+ },+ "newColumn": {+ "name": "value_high_precision",+ "type": "numeric(20,12)",+ "nullable": true+ }+ },+ {+ "action": "ALTER",+ "name": "value_low_precision",+ "oldColumn": {+ "name": "value_low_precision",+ "type": "numeric(8,3)",+ "nullable": true+ },+ "newColumn": {+ "name": "value_low_precision",+ "type": "numeric(6,2)",+ "nullable": true+ }+ }+ ]+ },+ {+ "action": "CREATE",+ "schemaName": "public",+ "tableName": "precision_test",+ "columnChanges": 0,+ "indexChanges": 0,+ "constraintChanges": 0,+ "foreignKeyChanges": 0+ }+ ]+ }+}\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/expected_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/expected_schema.sqlnew file mode 100644index 0000000000..8951c88b8f--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/expected_schema.sql@@ -0,0 +1,35 @@+-- Schema with mixed precision changes (both expansions and reductions)+CREATE TABLE public.data_samples (+ sample_id SERIAL PRIMARY KEY,+ short_text VARCHAR(100) NOT NULL, -- Expanded: VARCHAR(50) → VARCHAR(100)+ long_text VARCHAR(150), -- Reduced: VARCHAR(200) → VARCHAR(150)+ fixed_char CHAR(20), -- Expanded: CHAR(10) → CHAR(20)+ precise_decimal NUMERIC(16,6) DEFAULT 0.000000, -- Expanded: NUMERIC(12,4) → NUMERIC(16,6)+ simple_decimal NUMERIC(5,1) DEFAULT 0.0, -- Reduced: NUMERIC(6,2) → NUMERIC(5,1)+ bit_flags BIT(32) DEFAULT B'00000000000000000000000000000000', -- Expanded: BIT(16) → BIT(32)+ var_bits VARBIT(16) -- Reduced: VARBIT(32) → VARBIT(16)+);++CREATE TABLE public.measurements (+ measurement_id SERIAL PRIMARY KEY,+ device_name VARCHAR(150) NOT NULL, -- Expanded: VARCHAR(100) → VARCHAR(150)+ location_code CHAR(15), -- Reduced: CHAR(20) → CHAR(15)+ value_high_precision NUMERIC(20,12), -- Expanded: NUMERIC(15,8) → NUMERIC(20,12)+ value_low_precision NUMERIC(6,2), -- Reduced: NUMERIC(8,3) → NUMERIC(6,2)+ status_bits BIT(64), -- Expanded: BIT(32) → BIT(64)+ metadata_bits VARBIT(32) -- Reduced: VARBIT(64) → VARBIT(32)+);++CREATE TABLE public.precision_test (+ test_id SERIAL PRIMARY KEY,+ expand_varchar VARCHAR(500), -- New expanded varchar+ reduce_varchar VARCHAR(25), -- New reduced varchar+ expand_numeric NUMERIC(25,10), -- New high precision numeric+ reduce_numeric NUMERIC(4,1), -- New low precision numeric+ expand_char CHAR(50), -- New expanded char+ reduce_char CHAR(5), -- New reduced char+ expand_bits BIT(128), -- New expanded bit+ reduce_bits BIT(4), -- New reduced bit+ expand_varbits VARBIT(256), -- New expanded varbit+ reduce_varbits VARBIT(8) -- New reduced varbit+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/initial_schema.sql b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/initial_schema.sqlnew file mode 100644index 0000000000..86f2fe1401--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/initial_schema.sql@@ -0,0 +1,21 @@+-- Initial schema with various precisions+CREATE TABLE public.data_samples (+ sample_id SERIAL PRIMARY KEY,+ short_text VARCHAR(50) NOT NULL,+ long_text VARCHAR(200),+ fixed_char CHAR(10),+ precise_decimal NUMERIC(12,4) DEFAULT 0.0000,+ simple_decimal NUMERIC(6,2) DEFAULT 0.00,+ bit_flags BIT(16) DEFAULT B'0000000000000000',+ var_bits VARBIT(32)+);++CREATE TABLE public.measurements (+ measurement_id SERIAL PRIMARY KEY,+ device_name VARCHAR(100) NOT NULL,+ location_code CHAR(20),+ value_high_precision NUMERIC(15,8),+ value_low_precision NUMERIC(8,3),+ status_bits BIT(32),+ metadata_bits VARBIT(64)+);\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/test_description.md b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/test_description.mdnew file mode 100644index 0000000000..71cc544aed--- /dev/null+++ b/backend/plugin/schema/pg/sdl_testdata/data_types/type_conversions/precision_changes/test_description.md@@ -0,0 +1,18 @@+# Data Type Precision Changes Test++This test validates the SDL migration handling of precision modifications:++**Expanding Precision (Safe)**:+- VARCHAR(50) → VARCHAR(100)+- NUMERIC(8,2) → NUMERIC(12,4)+- CHAR(10) → CHAR(20)+- BIT(8) → BIT(16)+- VARBIT(16) → VARBIT(32)++**Reducing Precision (Potentially Unsafe)**:+- VARCHAR(100) → VARCHAR(50)+- NUMERIC(12,4) → NUMERIC(8,2)+- CHAR(20) → CHAR(10)+- BIT(16) → BIT(8)++Tests both safe precision expansions and potentially risky precision reductions that may require data validation.\ No newline at end of filediff --git a/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go b/backend/plugin/schema/pg/sdl_validation_testcontainer_test.goindex a4cb727251..4e976dabed 100644--- a/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go+++ b/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go@@ -2,7 +2,10 @@ package pgimport ("context"+ "encoding/json""fmt"+ "os"+ "path/filepath""strings""testing""time"@@ -963,10 +966,17 @@ func executeSDLValidationProcess(ctx context.Context, t *testing.T, connConfig *}// Generate migration DDL from schema B to schema C using the differ- migrationDDL, err := generateMigrationDDLFromMetadata(schemaB, schemaCMetadata)+ migrationDDL, actualDiff, err := generateMigrationDDLFromMetadata(schemaB, schemaCMetadata)require.NoError(t, err, "Failed to generate migration DDL from metadata")- t.Logf("Generated migration DDL (%d characters)", len(migrationDDL))+ t.Logf("Generated migration DDL (%d characters):\n%s", len(migrationDDL), migrationDDL)++ // Save or validate the actual diff (B to C) and DDL files+ testName := strings.ReplaceAll(t.Name(), "/", "_")+ err = validateOrSaveTestFiles(t, actualDiff, testName, migrationDDL)+ if err != nil {+ return errors.Wrapf(err, "test file validation/creation failed")+ }// Step 4: Apply generated DDL to database, then sync to get schema Dt.Log("Step 4: Apply generated DDL to database, then sync to get schema D")@@ -1039,7 +1049,7 @@ func getSyncMetadataForSDL(ctx context.Context, connConfig *pgx.ConnConfig, dbNa}// generateMigrationDDLFromMetadata generates migration DDL from schema B to schema C using schema.differ-func generateMigrationDDLFromMetadata(schemaB, schemaC *storepb.DatabaseSchemaMetadata) (string, error) {+func generateMigrationDDLFromMetadata(schemaB, schemaC *storepb.DatabaseSchemaMetadata) (string, *schema.MetadataDiff, error) {// Create model.DatabaseSchema objects for comparisonmodelSchemaB := model.NewDatabaseSchema(schemaB, nil, nil, storepb.Engine_POSTGRES, true)modelSchemaC := model.NewDatabaseSchema(schemaC, nil, nil, storepb.Engine_POSTGRES, true)@@ -1047,17 +1057,17 @@ func generateMigrationDDLFromMetadata(schemaB, schemaC *storepb.DatabaseSchemaMe// Use the schema differ to compute differencesdiff, err := schema.GetDatabaseSchemaDiff(storepb.Engine_POSTGRES, modelSchemaB, modelSchemaC)if err != nil {- return "", errors.Wrapf(err, "failed to compute schema difference")+ return "", nil, errors.Wrapf(err, "failed to compute schema difference")}// Convert the metadata diff to DDL using schema.GenerateMigration// This generates the actual migration DDL from the computed differencesmigrationDDL, err := schema.GenerateMigration(storepb.Engine_POSTGRES, diff)if err != nil {- return "", errors.Wrapf(err, "failed to generate migration DDL from schema diff")+ return "", nil, errors.Wrapf(err, "failed to generate migration DDL from schema diff")}- return migrationDDL, nil+ return migrationDDL, diff, nil}// validateSchemaConsistency compares two schema metadata objects to ensure they are equivalent@@ -1073,6 +1083,8 @@ func validateSchemaConsistency(schemaD, schemaC *storepb.DatabaseSchemaMetadata)return errors.Wrapf(err, "failed to compute schema difference")}+ // Note: diff files are saved earlier in the process with the actual B to C differences+// Check if there are any differencesif diff != nil {var diffDetails []string@@ -1083,6 +1095,64 @@ func validateSchemaConsistency(schemaD, schemaC *storepb.DatabaseSchemaMetadata)}if len(diff.TableChanges) > 0 {diffDetails = append(diffDetails, fmt.Sprintf("TableChanges: %d", len(diff.TableChanges)))+ // Add detailed table changes for debugging+ for i, tableDiff := range diff.TableChanges {+ diffDetails = append(diffDetails, fmt.Sprintf(" Table[%d]: %s table %s.%s (columns: %d, indexes: %d, checkConstraints: %d, foreignKeys: %d, triggers: %d)",+ i, tableDiff.Action, tableDiff.SchemaName, tableDiff.TableName,+ len(tableDiff.ColumnChanges), len(tableDiff.IndexChanges), len(tableDiff.CheckConstraintChanges), len(tableDiff.ForeignKeyChanges), len(tableDiff.TriggerChanges)))++ // Add column change details+ for j, columnDiff := range tableDiff.ColumnChanges {+ columnName := ""+ if columnDiff.OldColumn != nil {+ columnName = columnDiff.OldColumn.Name+ } else if columnDiff.NewColumn != nil {+ columnName = columnDiff.NewColumn.Name+ }+ diffDetails = append(diffDetails, fmt.Sprintf(" Column[%d]: %s column %s", j, columnDiff.Action, columnName))+ }++ // Add index change details+ for j, indexDiff := range tableDiff.IndexChanges {+ indexName := ""+ if indexDiff.OldIndex != nil {+ indexName = indexDiff.OldIndex.Name+ } else if indexDiff.NewIndex != nil {+ indexName = indexDiff.NewIndex.Name+ }+ diffDetails = append(diffDetails, fmt.Sprintf(" Index[%d]: %s index %s", j, indexDiff.Action, indexName))++ // Show more details for debugging+ if indexDiff.OldIndex != nil && indexDiff.NewIndex != nil {+ oldExpr := ""+ newExpr := ""+ if len(indexDiff.OldIndex.Expressions) > 0 {+ oldExpr = strings.Join(indexDiff.OldIndex.Expressions, ", ")+ }+ if len(indexDiff.NewIndex.Expressions) > 0 {+ newExpr = strings.Join(indexDiff.NewIndex.Expressions, ", ")+ }+ diffDetails = append(diffDetails, fmt.Sprintf(" Old: expr=%s type=%s unique=%v primary=%v", oldExpr, indexDiff.OldIndex.Type, indexDiff.OldIndex.Unique, indexDiff.OldIndex.Primary))+ diffDetails = append(diffDetails, fmt.Sprintf(" Old def: %s", indexDiff.OldIndex.Definition))+ diffDetails = append(diffDetails, fmt.Sprintf(" New: expr=%s type=%s unique=%v primary=%v", newExpr, indexDiff.NewIndex.Type, indexDiff.NewIndex.Unique, indexDiff.NewIndex.Primary))+ diffDetails = append(diffDetails, fmt.Sprintf(" New def: %s", indexDiff.NewIndex.Definition))+ } else if indexDiff.OldIndex != nil {+ oldExpr := ""+ if len(indexDiff.OldIndex.Expressions) > 0 {+ oldExpr = strings.Join(indexDiff.OldIndex.Expressions, ", ")+ }+ diffDetails = append(diffDetails, fmt.Sprintf(" Old: expr=%s type=%s unique=%v primary=%v", oldExpr, indexDiff.OldIndex.Type, indexDiff.OldIndex.Unique, indexDiff.OldIndex.Primary))+ diffDetails = append(diffDetails, fmt.Sprintf(" Old def: %s", indexDiff.OldIndex.Definition))+ } else if indexDiff.NewIndex != nil {+ newExpr := ""+ if len(indexDiff.NewIndex.Expressions) > 0 {+ newExpr = strings.Join(indexDiff.NewIndex.Expressions, ", ")+ }+ diffDetails = append(diffDetails, fmt.Sprintf(" New: expr=%s type=%s unique=%v primary=%v", newExpr, indexDiff.NewIndex.Type, indexDiff.NewIndex.Unique, indexDiff.NewIndex.Primary))+ diffDetails = append(diffDetails, fmt.Sprintf(" New def: %s", indexDiff.NewIndex.Definition))+ }+ }+ }}if len(diff.ViewChanges) > 0 {diffDetails = append(diffDetails, fmt.Sprintf("ViewChanges: %d", len(diff.ViewChanges)))@@ -1113,3 +1183,532 @@ func validateSchemaConsistency(schemaD, schemaC *storepb.DatabaseSchemaMetadata)return nil}++// DiffSummary represents the structure for JSON serialization of schema differences+type DiffSummary struct {+ HasDifferences bool `json:"hasDifferences"`+ Summary string `json:"summary"`+ TableChanges int `json:"tableChanges"`+ ViewChanges int `json:"viewChanges"`+ FunctionChanges int `json:"functionChanges"`+ SchemaChanges int `json:"schemaChanges"`+ SequenceChanges int `json:"sequenceChanges"`+ EnumTypeChanges int `json:"enumTypeChanges"`+ Details *DiffDetails `json:"details,omitempty"`+}++// DiffDetails provides detailed information about the differences+type DiffDetails struct {+ Tables []TableChangeSummary `json:"tables,omitempty"`+ Views []ViewChangeSummary `json:"views,omitempty"`+ Functions []FunctionChangeSummary `json:"functions,omitempty"`+ Schemas []SchemaChangeSummary `json:"schemas,omitempty"`+}++// TableChangeSummary summarizes table changes with detailed information+type TableChangeSummary struct {+ Action string `json:"action"`+ SchemaName string `json:"schemaName"`+ TableName string `json:"tableName"`+ ColumnChanges int `json:"columnChanges"`+ IndexChanges int `json:"indexChanges"`+ ConstraintChanges int `json:"constraintChanges"`+ ForeignKeyChanges int `json:"foreignKeyChanges"`+ // Detailed changes+ Columns []ColumnChangeDetail `json:"columns,omitempty"`+ Indexes []IndexChangeDetail `json:"indexes,omitempty"`+ Constraints []ConstraintChangeDetail `json:"constraints,omitempty"`+ ForeignKeys []ForeignKeyChangeDetail `json:"foreignKeys,omitempty"`+}++// ViewChangeSummary summarizes view changes+type ViewChangeSummary struct {+ Action string `json:"action"`+ SchemaName string `json:"schemaName"`+ ViewName string `json:"viewName"`+}++// FunctionChangeSummary summarizes function changes+type FunctionChangeSummary struct {+ Action string `json:"action"`+ SchemaName string `json:"schemaName"`+ FunctionName string `json:"functionName"`+}++// SchemaChangeSummary summarizes schema changes+type SchemaChangeSummary struct {+ Action string `json:"action"`+ SchemaName string `json:"schemaName"`+}++// ColumnChangeDetail provides detailed information about column changes+type ColumnChangeDetail struct {+ Action string `json:"action"`+ Name string `json:"name"`+ OldColumn *ColumnInfo `json:"oldColumn,omitempty"`+ NewColumn *ColumnInfo `json:"newColumn,omitempty"`+}++// ColumnInfo represents column metadata+type ColumnInfo struct {+ Name string `json:"name"`+ Type string `json:"type"`+ Nullable bool `json:"nullable"`+ DefaultValue string `json:"defaultValue,omitempty"`+ Comment string `json:"comment,omitempty"`+}++// IndexChangeDetail provides detailed information about index changes+type IndexChangeDetail struct {+ Action string `json:"action"`+ Name string `json:"name"`+ OldIndex *IndexInfo `json:"oldIndex,omitempty"`+ NewIndex *IndexInfo `json:"newIndex,omitempty"`+}++// IndexInfo represents index metadata+type IndexInfo struct {+ Name string `json:"name"`+ Type string `json:"type,omitempty"`+ Unique bool `json:"unique"`+ Expressions []string `json:"expressions"`+ KeyLength []int64 `json:"keyLength,omitempty"`+ Descending []bool `json:"descending,omitempty"`+}++// ConstraintChangeDetail provides detailed information about constraint changes+type ConstraintChangeDetail struct {+ Action string `json:"action"`+ Name string `json:"name"`+ OldConstraint *ConstraintInfo `json:"oldConstraint,omitempty"`+ NewConstraint *ConstraintInfo `json:"newConstraint,omitempty"`+}++// ConstraintInfo represents constraint metadata+type ConstraintInfo struct {+ Name string `json:"name"`+ Type string `json:"type"`+ Expression string `json:"expression,omitempty"`+}++// ForeignKeyChangeDetail provides detailed information about foreign key changes+type ForeignKeyChangeDetail struct {+ Action string `json:"action"`+ Name string `json:"name"`+ OldForeignKey *ForeignKeyInfo `json:"oldForeignKey,omitempty"`+ NewForeignKey *ForeignKeyInfo `json:"newForeignKey,omitempty"`+}++// ForeignKeyInfo represents foreign key metadata+type ForeignKeyInfo struct {+ Name string `json:"name"`+ Columns []string `json:"columns"`+ ReferencedSchema string `json:"referencedSchema"`+ ReferencedTable string `json:"referencedTable"`+ ReferencedColumns []string `json:"referencedColumns"`+ OnUpdate string `json:"onUpdate,omitempty"`+ OnDelete string `json:"onDelete,omitempty"`+ MatchType string `json:"matchType,omitempty"`+}++// createDiffSummary creates a structured summary from MetadataDiff+func createDiffSummary(diff *schema.MetadataDiff) *DiffSummary {+ if diff == nil {+ return &DiffSummary{+ HasDifferences: false,+ Summary: "No schema differences found - schemas match perfectly!",+ }+ }++ // Check if there are actually any differences+ hasDifferences := len(diff.TableChanges) > 0 || len(diff.ViewChanges) > 0 ||+ len(diff.FunctionChanges) > 0 || len(diff.SchemaChanges) > 0 ||+ len(diff.SequenceChanges) > 0 || len(diff.EnumTypeChanges) > 0++ summary := &DiffSummary{+ HasDifferences: hasDifferences,+ TableChanges: len(diff.TableChanges),+ ViewChanges: len(diff.ViewChanges),+ FunctionChanges: len(diff.FunctionChanges),+ SchemaChanges: len(diff.SchemaChanges),+ SequenceChanges: len(diff.SequenceChanges),+ EnumTypeChanges: len(diff.EnumTypeChanges),+ }++ if !hasDifferences {+ summary.Summary = "No schema differences found - schemas match perfectly!"+ return summary+ }++ // Create summary text+ var summaryParts []string+ if summary.TableChanges > 0 {+ summaryParts = append(summaryParts, fmt.Sprintf("Table changes: %d", summary.TableChanges))+ }+ if summary.ViewChanges > 0 {+ summaryParts = append(summaryParts, fmt.Sprintf("View changes: %d", summary.ViewChanges))+ }+ if summary.FunctionChanges > 0 {+ summaryParts = append(summaryParts, fmt.Sprintf("Function changes: %d", summary.FunctionChanges))+ }+ if summary.SchemaChanges > 0 {+ summaryParts = append(summaryParts, fmt.Sprintf("Schema changes: %d", summary.SchemaChanges))+ }+ if summary.SequenceChanges > 0 {+ summaryParts = append(summaryParts, fmt.Sprintf("Sequence changes: %d", summary.SequenceChanges))+ }+ if summary.EnumTypeChanges > 0 {+ summaryParts = append(summaryParts, fmt.Sprintf("Enum type changes: %d", summary.EnumTypeChanges))+ }++ summary.Summary = strings.Join(summaryParts, ", ")++ // Add detailed information+ details := &DiffDetails{}++ // Add table changes details+ for _, tableChange := range diff.TableChanges {+ tableSummary := TableChangeSummary{+ Action: string(tableChange.Action),+ SchemaName: tableChange.SchemaName,+ TableName: tableChange.TableName,+ ColumnChanges: len(tableChange.ColumnChanges),+ IndexChanges: len(tableChange.IndexChanges),+ ConstraintChanges: len(tableChange.CheckConstraintChanges),+ ForeignKeyChanges: len(tableChange.ForeignKeyChanges),+ }++ // Add detailed column changes+ for _, colChange := range tableChange.ColumnChanges {+ columnDetail := ColumnChangeDetail{+ Action: string(colChange.Action),+ Name: getColumnName(colChange),+ }+ if colChange.OldColumn != nil {+ columnDetail.OldColumn = &ColumnInfo{+ Name: colChange.OldColumn.Name,+ Type: colChange.OldColumn.Type,+ Nullable: colChange.OldColumn.Nullable,+ DefaultValue: colChange.OldColumn.Default,+ Comment: colChange.OldColumn.Comment,+ }+ }+ if colChange.NewColumn != nil {+ columnDetail.NewColumn = &ColumnInfo{+ Name: colChange.NewColumn.Name,+ Type: colChange.NewColumn.Type,+ Nullable: colChange.NewColumn.Nullable,+ DefaultValue: colChange.NewColumn.Default,+ Comment: colChange.NewColumn.Comment,+ }+ }+ tableSummary.Columns = append(tableSummary.Columns, columnDetail)+ }++ // Add detailed index changes+ for _, indexChange := range tableChange.IndexChanges {+ indexDetail := IndexChangeDetail{+ Action: string(indexChange.Action),+ Name: getIndexName(indexChange),+ }+ if indexChange.OldIndex != nil {+ indexDetail.OldIndex = &IndexInfo{+ Name: indexChange.OldIndex.Name,+ Type: indexChange.OldIndex.Type,+ Unique: indexChange.OldIndex.Unique,+ Expressions: indexChange.OldIndex.Expressions,+ KeyLength: indexChange.OldIndex.KeyLength,+ Descending: indexChange.OldIndex.Descending,+ }+ }+ if indexChange.NewIndex != nil {+ indexDetail.NewIndex = &IndexInfo{+ Name: indexChange.NewIndex.Name,+ Type: indexChange.NewIndex.Type,+ Unique: indexChange.NewIndex.Unique,+ Expressions: indexChange.NewIndex.Expressions,+ KeyLength: indexChange.NewIndex.KeyLength,+ Descending: indexChange.NewIndex.Descending,+ }+ }+ tableSummary.Indexes = append(tableSummary.Indexes, indexDetail)+ }++ // Add detailed constraint changes+ for _, constraintChange := range tableChange.CheckConstraintChanges {+ constraintDetail := ConstraintChangeDetail{+ Action: string(constraintChange.Action),+ Name: getConstraintName(constraintChange),+ }+ if constraintChange.OldCheckConstraint != nil {+ constraintDetail.OldConstraint = &ConstraintInfo{+ Name: constraintChange.OldCheckConstraint.Name,+ Type: "CHECK",+ Expression: constraintChange.OldCheckConstraint.Expression,+ }+ }+ if constraintChange.NewCheckConstraint != nil {+ constraintDetail.NewConstraint = &ConstraintInfo{+ Name: constraintChange.NewCheckConstraint.Name,+ Type: "CHECK",+ Expression: constraintChange.NewCheckConstraint.Expression,+ }+ }+ tableSummary.Constraints = append(tableSummary.Constraints, constraintDetail)+ }++ // Add detailed foreign key changes+ for _, fkChange := range tableChange.ForeignKeyChanges {+ fkDetail := ForeignKeyChangeDetail{+ Action: string(fkChange.Action),+ Name: getForeignKeyName(fkChange),+ }+ if fkChange.OldForeignKey != nil {+ fkDetail.OldForeignKey = &ForeignKeyInfo{+ Name: fkChange.OldForeignKey.Name,+ Columns: fkChange.OldForeignKey.Columns,+ ReferencedSchema: fkChange.OldForeignKey.ReferencedSchema,+ ReferencedTable: fkChange.OldForeignKey.ReferencedTable,+ ReferencedColumns: fkChange.OldForeignKey.ReferencedColumns,+ OnUpdate: fkChange.OldForeignKey.OnUpdate,+ OnDelete: fkChange.OldForeignKey.OnDelete,+ MatchType: fkChange.OldForeignKey.MatchType,+ }+ }+ if fkChange.NewForeignKey != nil {+ fkDetail.NewForeignKey = &ForeignKeyInfo{+ Name: fkChange.NewForeignKey.Name,+ Columns: fkChange.NewForeignKey.Columns,+ ReferencedSchema: fkChange.NewForeignKey.ReferencedSchema,+ ReferencedTable: fkChange.NewForeignKey.ReferencedTable,+ ReferencedColumns: fkChange.NewForeignKey.ReferencedColumns,+ OnUpdate: fkChange.NewForeignKey.OnUpdate,+ OnDelete: fkChange.NewForeignKey.OnDelete,+ MatchType: fkChange.NewForeignKey.MatchType,+ }+ }+ tableSummary.ForeignKeys = append(tableSummary.ForeignKeys, fkDetail)+ }++ details.Tables = append(details.Tables, tableSummary)+ }++ // Add view changes details+ for _, viewChange := range diff.ViewChanges {+ details.Views = append(details.Views, ViewChangeSummary{+ Action: string(viewChange.Action),+ SchemaName: viewChange.SchemaName,+ ViewName: viewChange.ViewName,+ })+ }++ // Add function changes details+ for _, funcChange := range diff.FunctionChanges {+ details.Functions = append(details.Functions, FunctionChangeSummary{+ Action: string(funcChange.Action),+ SchemaName: funcChange.SchemaName,+ FunctionName: funcChange.FunctionName,+ })+ }++ // Add schema changes details+ for _, schemaChange := range diff.SchemaChanges {+ details.Schemas = append(details.Schemas, SchemaChangeSummary{+ Action: string(schemaChange.Action),+ SchemaName: schemaChange.SchemaName,+ })+ }++ if len(details.Tables) > 0 || len(details.Views) > 0 || len(details.Functions) > 0 || len(details.Schemas) > 0 {+ summary.Details = details+ }++ return summary+}++// Helper functions to extract names from diff structures+func getColumnName(colChange *schema.ColumnDiff) string {+ if colChange.NewColumn != nil {+ return colChange.NewColumn.Name+ }+ if colChange.OldColumn != nil {+ return colChange.OldColumn.Name+ }+ return ""+}++func getIndexName(indexChange *schema.IndexDiff) string {+ if indexChange.NewIndex != nil {+ return indexChange.NewIndex.Name+ }+ if indexChange.OldIndex != nil {+ return indexChange.OldIndex.Name+ }+ return ""+}++func getConstraintName(constraintChange *schema.CheckConstraintDiff) string {+ if constraintChange.NewCheckConstraint != nil {+ return constraintChange.NewCheckConstraint.Name+ }+ if constraintChange.OldCheckConstraint != nil {+ return constraintChange.OldCheckConstraint.Name+ }+ return ""+}++func getForeignKeyName(fkChange *schema.ForeignKeyDiff) string {+ if fkChange.NewForeignKey != nil {+ return fkChange.NewForeignKey.Name+ }+ if fkChange.OldForeignKey != nil {+ return fkChange.OldForeignKey.Name+ }+ return ""+}++// validateOrSaveTestFiles validates existing test files or creates new ones based on UPDATE_TEST_FILES environment variable+func validateOrSaveTestFiles(t *testing.T, diff *schema.MetadataDiff, testName string, ddlContent string) error {+ // Check if we should update test files+ updateFiles := os.Getenv("UPDATE_TEST_FILES") == "true"++ testDir := getTestDataDirectory(testName)+ if testDir == "" {+ // For hardcoded tests (TestSDLValidationWithTestcontainer), skip file validation+ // Only TestSDLValidationFromTestData tests should have corresponding test data files+ if strings.Contains(testName, "TestSDLValidationWithTestcontainer") {+ t.Logf("Skipping file validation for hardcoded test: %s", testName)+ return nil+ }+ return errors.Errorf("could not determine test data directory for test %s", testName)+ }++ diffFilename := filepath.Join(testDir, "diff.json")+ ddlFilename := filepath.Join(testDir, "ddl.sql")++ // Generate current content+ currentDiffJSON, err := generateDiffJSON(diff)+ if err != nil {+ return errors.Wrapf(err, "failed to generate diff JSON")+ }++ if updateFiles {+ // Update mode: create/overwrite files+ t.Logf("Updating test files in %s", testDir)++ // Save diff JSON file+ if err := os.WriteFile(diffFilename, []byte(currentDiffJSON), 0644); err != nil {+ return errors.Wrapf(err, "failed to write diff.json file")+ }++ // Save DDL file+ if err := os.WriteFile(ddlFilename, []byte(ddlContent), 0644); err != nil {+ return errors.Wrapf(err, "failed to write ddl.sql file")+ }++ t.Logf("Test files updated: %s (diff.json, ddl.sql)", testDir)+ return nil+ }++ // Validation mode: check if existing files match current content+ t.Logf("Validating test files in %s", testDir)++ // Validate diff.json+ if err := validateFileContent(diffFilename, currentDiffJSON, "diff.json"); err != nil {+ return err+ }++ // Validate ddl.sql+ if err := validateFileContent(ddlFilename, ddlContent, "ddl.sql"); err != nil {+ return err+ }++ t.Logf("✓ Test files validated successfully: %s", testDir)+ return nil+}++// generateDiffJSON generates JSON content from MetadataDiff+func generateDiffJSON(diff *schema.MetadataDiff) (string, error) {+ diffSummary := createDiffSummary(diff)+ jsonData, err := json.MarshalIndent(diffSummary, "", " ")+ if err != nil {+ return "", errors.Wrapf(err, "failed to marshal diff to JSON")+ }+ return string(jsonData), nil+}++// validateFileContent validates that the file content matches expected content+func validateFileContent(filename, expectedContent, fileType string) error {+ if _, err := os.Stat(filename); os.IsNotExist(err) {+ return errors.Errorf("%s file does not exist: %s. Run with UPDATE_TEST_FILES=true to create it", fileType, filename)+ }++ actualContent, err := os.ReadFile(filename)+ if err != nil {+ return errors.Wrapf(err, "failed to read %s file: %s", fileType, filename)+ }++ actualStr := strings.TrimSpace(string(actualContent))+ expectedStr := strings.TrimSpace(expectedContent)++ if actualStr != expectedStr {+ return errors.Errorf("%s content mismatch in %s.\nExpected:\n%s\n\nActual:\n%s\n\nRun with UPDATE_TEST_FILES=true to update the file",+ fileType, filename, expectedStr, actualStr)+ }++ return nil+}++// getTestDataDirectory converts a test name to the corresponding test data directory path+func getTestDataDirectory(testName string) string {+ // Remove "TestSDLValidationFromTestData_" prefix+ if !strings.HasPrefix(testName, "TestSDLValidationFromTestData_") {+ return ""+ }++ // Extract the path part after the prefix+ pathPart := strings.TrimPrefix(testName, "TestSDLValidationFromTestData_")++ // Convert from test name format to directory format+ // TestSDLValidationFromTestData_data_types_basic_types_datetime_types -> data_types/basic_types/datetime_types++ // Based on the known test structure, parse the path correctly:+ // data_types_basic_types_datetime_types+ // schema_objects_views_complex_views+ // constraints_indexes_foreign_keys_cascade_actions++ var testDataPath string+ switch {+ case strings.HasPrefix(pathPart, "data_types_basic_types_"):+ // data_types_basic_types_datetime_types -> data_types/basic_types/datetime_types+ suffix := strings.TrimPrefix(pathPart, "data_types_basic_types_")+ testDataPath = filepath.Join("data_types", "basic_types", suffix)+ case strings.HasPrefix(pathPart, "data_types_advanced_types_"):+ // data_types_advanced_types_binary_json_uuid -> data_types/advanced_types/binary_json_uuid+ suffix := strings.TrimPrefix(pathPart, "data_types_advanced_types_")+ testDataPath = filepath.Join("data_types", "advanced_types", suffix)+ case strings.HasPrefix(pathPart, "data_types_type_conversions_"):+ // data_types_type_conversions_compatible_conversions -> data_types/type_conversions/compatible_conversions+ suffix := strings.TrimPrefix(pathPart, "data_types_type_conversions_")+ testDataPath = filepath.Join("data_types", "type_conversions", suffix)+ case strings.HasPrefix(pathPart, "schema_objects_views_"):+ // schema_objects_views_complex_views -> schema_objects/views/complex_views+ suffix := strings.TrimPrefix(pathPart, "schema_objects_views_")+ testDataPath = filepath.Join("schema_objects", "views", suffix)+ case strings.HasPrefix(pathPart, "constraints_indexes_foreign_keys_"):+ // constraints_indexes_foreign_keys_cascade_actions -> constraints_indexes/foreign_keys/cascade_actions+ suffix := strings.TrimPrefix(pathPart, "constraints_indexes_foreign_keys_")+ testDataPath = filepath.Join("constraints_indexes", "foreign_keys", suffix)+ default:+ // Fallback: try to split intelligently+ parts := strings.Split(pathPart, "_")+ if len(parts) >= 3 {+ // Take first 2 parts as category, rest as test name+ testDataPath = filepath.Join(strings.Join(parts[:2], "/"), strings.Join(parts[2:], "_"))+ } else {+ testDataPath = strings.ReplaceAll(pathPart, "_", "/")+ }+ }++ return filepath.Join("sdl_testdata", testDataPath)+}