Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: support generate pg table constraint migration for ast-only (#17455)

rebelice9e012ab05b9b
diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.go
index badc235c44..aea43ced7a 100644
--- a/backend/plugin/schema/pg/generate_migration.go
+++ b/backend/plugin/schema/pg/generate_migration.go
@@ -212,7 +212,15 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
if tableDiff.Action == schema.MetadataDiffActionAlter {
for _, fkDiff := range tableDiff.ForeignKeyChanges {
if fkDiff.Action == schema.MetadataDiffActionDrop {
- writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.OldForeignKey.Name)
+ if fkDiff.OldForeignKey != nil {
+ // Metadata mode: use constraint metadata
+ writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.OldForeignKey.Name)
+ } else if fkDiff.OldASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := fkDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {
+ writeDropForeignKeyFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)
+ }
+ }
}
}
}
@@ -262,7 +270,29 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
// Drop check constraints
for _, checkDiff := range tableDiff.CheckConstraintChanges {
if checkDiff.Action == schema.MetadataDiffActionDrop {
- writeDropCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.OldCheckConstraint.Name)
+ if checkDiff.OldCheckConstraint != nil {
+ // Metadata mode: use constraint metadata
+ writeDropCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.OldCheckConstraint.Name)
+ } else if checkDiff.OldASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := checkDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {
+ writeDropCheckConstraintFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)
+ }
+ }
+ }
+ }
+ // Drop primary key constraints
+ for _, pkDiff := range tableDiff.PrimaryKeyChanges {
+ if pkDiff.Action == schema.MetadataDiffActionDrop {
+ if pkDiff.OldPrimaryKey != nil {
+ // Metadata mode: use constraint metadata
+ writeDropConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, pkDiff.OldPrimaryKey.Name)
+ } else if pkDiff.OldASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := pkDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {
+ writeDropPrimaryKeyFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)
+ }
+ }
}
}
@@ -298,7 +328,15 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
// Drop foreign keys first
for _, fkDiff := range tableDiff.ForeignKeyChanges {
if fkDiff.Action == schema.MetadataDiffActionDrop {
- writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.OldForeignKey.Name)
+ if fkDiff.OldForeignKey != nil {
+ // Metadata mode: use constraint metadata
+ writeDropForeignKey(buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.OldForeignKey.Name)
+ } else if fkDiff.OldASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := fkDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {
+ writeDropForeignKeyFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)
+ }
+ }
}
}
}
@@ -337,7 +375,29 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {
// Drop check constraints
for _, checkDiff := range tableDiff.CheckConstraintChanges {
if checkDiff.Action == schema.MetadataDiffActionDrop {
- writeDropCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.OldCheckConstraint.Name)
+ if checkDiff.OldCheckConstraint != nil {
+ // Metadata mode: use constraint metadata
+ writeDropCheckConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.OldCheckConstraint.Name)
+ } else if checkDiff.OldASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := checkDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {
+ writeDropCheckConstraintFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)
+ }
+ }
+ }
+ }
+ // Drop primary key constraints
+ for _, pkDiff := range tableDiff.PrimaryKeyChanges {
+ if pkDiff.Action == schema.MetadataDiffActionDrop {
+ if pkDiff.OldPrimaryKey != nil {
+ // Metadata mode: use constraint metadata
+ writeDropConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, pkDiff.OldPrimaryKey.Name)
+ } else if pkDiff.OldASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := pkDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {
+ writeDropPrimaryKeyFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)
+ }
+ }
}
}
@@ -1072,7 +1132,54 @@ func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdd
// Add check constraints
for _, checkDiff := range tableDiff.CheckConstraintChanges {
if checkDiff.Action == schema.MetadataDiffActionCreate {
- writeAddCheckConstraint(&buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.NewCheckConstraint)
+ if checkDiff.NewCheckConstraint != nil {
+ // Metadata mode: use constraint metadata
+ writeAddCheckConstraint(&buf, tableDiff.SchemaName, tableDiff.TableName, checkDiff.NewCheckConstraint)
+ } else if checkDiff.NewASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := checkDiff.NewASTNode.(pgparser.ITableconstraintContext); ok {
+ if err := writeAddCheckConstraintFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST); err != nil {
+ // If AST extraction fails, log error but continue (non-fatal)
+ _, _ = buf.WriteString(fmt.Sprintf("-- Error adding check constraint: %v\n", err))
+ }
+ }
+ }
+ }
+ }
+
+ // Add unique constraints
+ for _, uniqueDiff := range tableDiff.UniqueConstraintChanges {
+ if uniqueDiff.Action == schema.MetadataDiffActionCreate {
+ if uniqueDiff.NewUniqueConstraint != nil {
+ // Metadata mode: use constraint metadata
+ writeMigrationUniqueKey(&buf, tableDiff.SchemaName, tableDiff.TableName, uniqueDiff.NewUniqueConstraint)
+ } else if uniqueDiff.NewASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := uniqueDiff.NewASTNode.(pgparser.ITableconstraintContext); ok {
+ if err := writeAddUniqueConstraintFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST); err != nil {
+ // If AST extraction fails, log error but continue (non-fatal)
+ _, _ = buf.WriteString(fmt.Sprintf("-- Error adding unique constraint: %v\n", err))
+ }
+ }
+ }
+ }
+ }
+
+ // Add primary key constraints
+ for _, pkDiff := range tableDiff.PrimaryKeyChanges {
+ if pkDiff.Action == schema.MetadataDiffActionCreate {
+ if pkDiff.NewPrimaryKey != nil {
+ // Metadata mode: use constraint metadata
+ writeMigrationPrimaryKey(&buf, tableDiff.SchemaName, tableDiff.TableName, pkDiff.NewPrimaryKey)
+ } else if pkDiff.NewASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := pkDiff.NewASTNode.(pgparser.ITableconstraintContext); ok {
+ if err := writeAddPrimaryKeyFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST); err != nil {
+ // If AST extraction fails, log error but continue (non-fatal)
+ _, _ = buf.WriteString(fmt.Sprintf("-- Error adding primary key constraint: %v\n", err))
+ }
+ }
+ }
}
}
@@ -1085,8 +1192,19 @@ func generateAlterTableForeignKeys(tableDiff *schema.TableDiff) (string, error)
for _, fkDiff := range tableDiff.ForeignKeyChanges {
if fkDiff.Action == schema.MetadataDiffActionCreate {
- if err := writeMigrationForeignKey(&buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.NewForeignKey); err != nil {
- return "", err
+ if fkDiff.NewForeignKey != nil {
+ // Metadata mode: use constraint metadata
+ if err := writeMigrationForeignKey(&buf, tableDiff.SchemaName, tableDiff.TableName, fkDiff.NewForeignKey); err != nil {
+ return "", err
+ }
+ } else if fkDiff.NewASTNode != nil {
+ // AST-only mode: extract from AST node
+ if constraintAST, ok := fkDiff.NewASTNode.(pgparser.ITableconstraintContext); ok {
+ if err := writeAddForeignKeyFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST); err != nil {
+ // If AST extraction fails, log error but continue (non-fatal)
+ _, _ = buf.WriteString(fmt.Sprintf("-- Error adding foreign key constraint: %v\n", err))
+ }
+ }
}
}
}
@@ -1373,6 +1491,17 @@ func writeDropConstraint(out *strings.Builder, schema, table, constraint string)
_, _ = out.WriteString("\n")
}
+func writeDropPrimaryKey(out *strings.Builder, schema, table, constraint string) {
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" DROP CONSTRAINT IF EXISTS "`)
+ _, _ = out.WriteString(constraint)
+ _, _ = out.WriteString(`";`)
+ _, _ = out.WriteString("\n")
+}
+
func writeDropIndex(out *strings.Builder, schema, index string) {
_, _ = out.WriteString(`DROP INDEX IF EXISTS "`)
_, _ = out.WriteString(schema)
@@ -3008,3 +3137,229 @@ func getTextFromAST(ctx antlr.ParseTree) string {
// Fallback to GetText() if tokens are not available
return ctx.GetText()
}
+
+// extractConstraintNameFromAST extracts constraint name from table constraint AST node
+func extractConstraintNameFromAST(constraintAST pgparser.ITableconstraintContext) string {
+ if constraintAST == nil {
+ return ""
+ }
+
+ if constraintAST.Name() != nil {
+ return pgpluginparser.NormalizePostgreSQLName(constraintAST.Name())
+ }
+
+ // If no explicit name, generate one based on constraint type and content
+ if constraintAST.Constraintelem() != nil {
+ elem := constraintAST.Constraintelem()
+
+ // For CHECK constraints, try to generate a meaningful name
+ if elem.CHECK() != nil {
+ // Extract table name from context if possible, otherwise use a generic name
+ return "check_constraint"
+ }
+
+ // For FOREIGN KEY constraints
+ if elem.FOREIGN() != nil && elem.KEY() != nil {
+ return "foreign_key_constraint"
+ }
+
+ // For UNIQUE constraints
+ if elem.UNIQUE() != nil {
+ return "unique_constraint"
+ }
+
+ // For PRIMARY KEY constraints
+ if elem.PRIMARY() != nil && elem.KEY() != nil {
+ return "primary_key_constraint"
+ }
+ }
+
+ // Fallback: use the full constraint text as identifier
+ return getTextFromAST(constraintAST)
+}
+
+// writeDropCheckConstraintFromAST drops a check constraint using AST node
+func writeDropCheckConstraintFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) {
+ constraintName := extractConstraintNameFromAST(constraintAST)
+ if constraintName == "" {
+ // If we can't extract a name, use the constraint text as fallback
+ constraintName = getTextFromAST(constraintAST)
+ }
+ writeDropCheckConstraint(out, schema, table, constraintName)
+}
+
+// writeDropForeignKeyFromAST drops a foreign key constraint using AST node
+func writeDropForeignKeyFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) {
+ constraintName := extractConstraintNameFromAST(constraintAST)
+ if constraintName == "" {
+ // If we can't extract a name, use the constraint text as fallback
+ constraintName = getTextFromAST(constraintAST)
+ }
+ writeDropForeignKey(out, schema, table, constraintName)
+}
+
+// writeDropPrimaryKeyFromAST drops a primary key constraint using AST node
+func writeDropPrimaryKeyFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) {
+ constraintName := extractConstraintNameFromAST(constraintAST)
+ if constraintName == "" {
+ // If we can't extract a name, generate a default primary key name
+ constraintName = fmt.Sprintf("%s_pkey", table)
+ }
+ writeDropPrimaryKey(out, schema, table, constraintName)
+}
+
+// writeAddCheckConstraintFromAST adds a check constraint using AST node
+func writeAddCheckConstraintFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) error {
+ if constraintAST == nil {
+ return errors.New("constraint AST node is nil")
+ }
+
+ constraintName := extractConstraintNameFromAST(constraintAST)
+
+ // Extract CHECK expression
+ if constraintAST.Constraintelem() != nil {
+ elem := constraintAST.Constraintelem()
+ if elem.CHECK() != nil && elem.A_expr() != nil {
+ checkExpr := getTextFromAST(elem.A_expr())
+
+ // Generate constraint name if not provided
+ if constraintName == "" || constraintName == "check_constraint" {
+ constraintName = fmt.Sprintf("%s_check", table)
+ }
+
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(constraintName)
+ _, _ = out.WriteString(`" CHECK (`)
+ _, _ = out.WriteString(checkExpr)
+ _, _ = out.WriteString(`);`)
+ _, _ = out.WriteString("\n")
+ return nil
+ }
+ }
+
+ return errors.New("could not extract CHECK constraint from AST node")
+}
+
+// writeAddForeignKeyFromAST adds a foreign key constraint using AST node
+func writeAddForeignKeyFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) error {
+ if constraintAST == nil {
+ return errors.New("constraint AST node is nil")
+ }
+
+ constraintName := extractConstraintNameFromAST(constraintAST)
+
+ // Extract FOREIGN KEY definition
+ if constraintAST.Constraintelem() != nil {
+ elem := constraintAST.Constraintelem()
+ if elem.FOREIGN() != nil && elem.KEY() != nil {
+ // Generate constraint name if not provided
+ if constraintName == "" || constraintName == "foreign_key_constraint" {
+ constraintName = fmt.Sprintf("%s_fkey", table)
+ }
+
+ // Extract the FOREIGN KEY part from the full constraint
+ // This is a simplified approach - we'll use the original constraint text
+ // but replace the constraint name if needed
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(constraintName)
+ _, _ = out.WriteString(`" `)
+
+ // Extract just the FOREIGN KEY part (after constraint name)
+ if constraintAST.Constraintelem() != nil {
+ fkElem := constraintAST.Constraintelem()
+ fkText := getTextFromAST(fkElem)
+ _, _ = out.WriteString(fkText)
+ }
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+ }
+ }
+
+ return errors.New("could not extract FOREIGN KEY constraint from AST node")
+}
+
+// writeAddUniqueConstraintFromAST adds a unique constraint using AST node
+func writeAddUniqueConstraintFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) error {
+ if constraintAST == nil {
+ return errors.New("constraint AST node is nil")
+ }
+
+ constraintName := extractConstraintNameFromAST(constraintAST)
+
+ // Extract UNIQUE definition
+ if constraintAST.Constraintelem() != nil {
+ elem := constraintAST.Constraintelem()
+ if elem.UNIQUE() != nil {
+ // Generate constraint name if not provided
+ if constraintName == "" || constraintName == "unique_constraint" {
+ constraintName = fmt.Sprintf("%s_unique", table)
+ }
+
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(constraintName)
+ _, _ = out.WriteString(`" `)
+
+ // Extract the UNIQUE part
+ uniqueText := getTextFromAST(elem)
+ _, _ = out.WriteString(uniqueText)
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+ }
+ }
+
+ return errors.New("could not extract UNIQUE constraint from AST node")
+}
+
+// writeAddPrimaryKeyFromAST adds a primary key constraint using AST node
+func writeAddPrimaryKeyFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) error {
+ if constraintAST == nil {
+ return errors.New("constraint AST node is nil")
+ }
+
+ constraintName := extractConstraintNameFromAST(constraintAST)
+
+ // Extract PRIMARY KEY definition
+ if constraintAST.Constraintelem() != nil {
+ elem := constraintAST.Constraintelem()
+ if elem.PRIMARY() != nil && elem.KEY() != nil {
+ // Generate constraint name if not provided
+ if constraintName == "" || constraintName == "primary_key_constraint" {
+ constraintName = fmt.Sprintf("%s_pkey", table)
+ }
+
+ _, _ = out.WriteString(`ALTER TABLE "`)
+ _, _ = out.WriteString(schema)
+ _, _ = out.WriteString(`"."`)
+ _, _ = out.WriteString(table)
+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)
+ _, _ = out.WriteString(constraintName)
+ _, _ = out.WriteString(`" `)
+
+ // Extract the PRIMARY KEY part
+ pkText := getTextFromAST(elem)
+ _, _ = out.WriteString(pkText)
+
+ _, _ = out.WriteString(`;`)
+ _, _ = out.WriteString("\n")
+ return nil
+ }
+ }
+
+ return errors.New("could not extract PRIMARY KEY constraint from AST node")
+}
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.go
index 6bb706b571..a059bda7d2 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -622,24 +622,52 @@ func processForeignKeyChanges(oldTable, newTable *parser.CreatestmtContext) []*s
}
// Step 1: Extract all foreign key definitions with their AST nodes for text comparison
- oldFKMap := extractForeignKeyDefinitionsWithAST(oldTable)
- newFKMap := extractForeignKeyDefinitionsWithAST(newTable)
+ oldFKList := extractForeignKeyDefinitionsInOrder(oldTable)
+ newFKList := extractForeignKeyDefinitionsInOrder(newTable)
+
+ // Create maps for quick lookup
+ oldFKMap := make(map[string]*ForeignKeyDefWithAST)
+ for _, def := range oldFKList {
+ oldFKMap[def.Name] = def
+ }
+ newFKMap := make(map[string]*ForeignKeyDefWithAST)
+ for _, def := range newFKList {
+ newFKMap[def.Name] = def
+ }
var fkDiffs []*schema.ForeignKeyDiff
- // Step 2: Process current foreign keys to find created and modified foreign keys
- for fkName, newFKDef := range newFKMap {
- if oldFKDef, exists := oldFKMap[fkName]; exists {
+ // Step 2: Process old foreign keys in reverse order for DROP operations
+ for i := len(oldFKList) - 1; i >= 0; i-- {
+ oldFKDef := oldFKList[i]
+ if newFKDef, exists := newFKMap[oldFKDef.Name]; exists {
// FK exists in both - check if modified by comparing text first
currentText := getForeignKeyText(newFKDef.ASTNode)
previousText := getForeignKeyText(oldFKDef.ASTNode)
if currentText != previousText {
// FK was modified - store AST nodes only
- // Drop and recreate for modifications (PostgreSQL pattern)
fkDiffs = append(fkDiffs, &schema.ForeignKeyDiff{
Action: schema.MetadataDiffActionDrop,
OldASTNode: oldFKDef.ASTNode,
})
+ }
+ } else {
+ // Foreign key was dropped - store AST node only
+ fkDiffs = append(fkDiffs, &schema.ForeignKeyDiff{
+ Action: schema.MetadataDiffActionDrop,
+ OldASTNode: oldFKDef.ASTNode,
+ })
+ }
+ }
+
+ // Step 3: Process new foreign keys in order for CREATE operations
+ for _, newFKDef := range newFKList {
+ if oldFKDef, exists := oldFKMap[newFKDef.Name]; exists {
+ // FK exists in both - check if modified by comparing text first
+ currentText := getForeignKeyText(newFKDef.ASTNode)
+ previousText := getForeignKeyText(oldFKDef.ASTNode)
+ if currentText != previousText {
+ // FK was modified - store AST nodes only
fkDiffs = append(fkDiffs, &schema.ForeignKeyDiff{
Action: schema.MetadataDiffActionCreate,
NewASTNode: newFKDef.ASTNode,
@@ -655,17 +683,6 @@ func processForeignKeyChanges(oldTable, newTable *parser.CreatestmtContext) []*s
}
}
- // Step 3: Process old foreign keys to find dropped ones
- for fkName, oldFKDef := range oldFKMap {
- if _, exists := newFKMap[fkName]; !exists {
- // Foreign key was dropped - store AST node only
- fkDiffs = append(fkDiffs, &schema.ForeignKeyDiff{
- Action: schema.MetadataDiffActionDrop,
- OldASTNode: oldFKDef.ASTNode,
- })
- }
- }
-
return fkDiffs
}
@@ -677,14 +694,25 @@ func processCheckConstraintChanges(oldTable, newTable *parser.CreatestmtContext)
}
// Step 1: Extract all check constraint definitions with their AST nodes for text comparison
- oldCheckMap := extractCheckConstraintDefinitionsWithAST(oldTable)
- newCheckMap := extractCheckConstraintDefinitionsWithAST(newTable)
+ oldCheckList := extractCheckConstraintDefinitionsInOrder(oldTable)
+ newCheckList := extractCheckConstraintDefinitionsInOrder(newTable)
+
+ // Create maps for quick lookup
+ oldCheckMap := make(map[string]*CheckConstraintDefWithAST)
+ for _, def := range oldCheckList {
+ oldCheckMap[def.Name] = def
+ }
+ newCheckMap := make(map[string]*CheckConstraintDefWithAST)
+ for _, def := range newCheckList {
+ newCheckMap[def.Name] = def
+ }
var checkDiffs []*schema.CheckConstraintDiff
- // Step 2: Process current check constraints to find created and modified constraints
- for checkName, newCheckDef := range newCheckMap {
- if oldCheckDef, exists := oldCheckMap[checkName]; exists {
+ // Step 2: Process old constraints in reverse order for DROP operations
+ for i := len(oldCheckList) - 1; i >= 0; i-- {
+ oldCheckDef := oldCheckList[i]
+ if newCheckDef, exists := newCheckMap[oldCheckDef.Name]; exists {
// Check constraint exists in both - check if modified by comparing text first
currentText := getCheckConstraintText(newCheckDef.ASTNode)
previousText := getCheckConstraintText(oldCheckDef.ASTNode)
@@ -695,6 +723,24 @@ func processCheckConstraintChanges(oldTable, newTable *parser.CreatestmtContext)
Action: schema.MetadataDiffActionDrop,
OldASTNode: oldCheckDef.ASTNode,
})
+ }
+ } else {
+ // Check constraint was dropped - store AST node only
+ checkDiffs = append(checkDiffs, &schema.CheckConstraintDiff{
+ Action: schema.MetadataDiffActionDrop,
+ OldASTNode: oldCheckDef.ASTNode,
+ })
+ }
+ }
+
+ // Step 3: Process new constraints in order for CREATE operations
+ for _, newCheckDef := range newCheckList {
+ if oldCheckDef, exists := oldCheckMap[newCheckDef.Name]; exists {
+ // Check constraint exists in both - check if modified by comparing text first
+ currentText := getCheckConstraintText(newCheckDef.ASTNode)
+ previousText := getCheckConstraintText(oldCheckDef.ASTNode)
+ if currentText != previousText {
+ // Check constraint was modified - store AST nodes only
checkDiffs = append(checkDiffs, &schema.CheckConstraintDiff{
Action: schema.MetadataDiffActionCreate,
NewASTNode: newCheckDef.ASTNode,
@@ -710,17 +756,6 @@ func processCheckConstraintChanges(oldTable, newTable *parser.CreatestmtContext)
}
}
- // Step 3: Process old check constraints to find dropped ones
- for checkName, oldCheckDef := range oldCheckMap {
- if _, exists := newCheckMap[checkName]; !exists {
- // Check constraint was dropped - store AST node only
- checkDiffs = append(checkDiffs, &schema.CheckConstraintDiff{
- Action: schema.MetadataDiffActionDrop,
- OldASTNode: oldCheckDef.ASTNode,
- })
- }
- }
-
return checkDiffs
}
@@ -783,14 +818,25 @@ func processUniqueConstraintChanges(oldTable, newTable *parser.CreatestmtContext
}
// Step 1: Extract all unique constraint definitions with their AST nodes for text comparison
- oldUKMap := extractUniqueConstraintDefinitionsWithAST(oldTable)
- newUKMap := extractUniqueConstraintDefinitionsWithAST(newTable)
+ oldUKList := extractUniqueConstraintDefinitionsInOrder(oldTable)
+ newUKList := extractUniqueConstraintDefinitionsInOrder(newTable)
+
+ // Create maps for quick lookup
+ oldUKMap := make(map[string]*IndexDefWithAST)
+ for _, def := range oldUKList {
+ oldUKMap[def.Name] = def
+ }
+ newUKMap := make(map[string]*IndexDefWithAST)
+ for _, def := range newUKList {
+ newUKMap[def.Name] = def
+ }
var ukDiffs []*schema.UniqueConstraintDiff
- // Step 2: Process current unique constraints to find created and modified unique constraints
- for ukName, newUKDef := range newUKMap {
- if oldUKDef, exists := oldUKMap[ukName]; exists {
+ // Step 2: Process old constraints in reverse order for DROP operations
+ for i := len(oldUKList) - 1; i >= 0; i-- {
+ oldUKDef := oldUKList[i]
+ if newUKDef, exists := newUKMap[oldUKDef.Name]; exists {
// UK exists in both - check if modified by comparing text first
currentText := getIndexText(newUKDef.ASTNode)
previousText := getIndexText(oldUKDef.ASTNode)
@@ -800,11 +846,30 @@ func processUniqueConstraintChanges(oldTable, newTable *parser.CreatestmtContext
Action: schema.MetadataDiffActionDrop,
OldASTNode: oldUKDef.ASTNode,
})
+ }
+ } else {
+ // UK was dropped - store AST node only
+ ukDiffs = append(ukDiffs, &schema.UniqueConstraintDiff{
+ Action: schema.MetadataDiffActionDrop,
+ OldASTNode: oldUKDef.ASTNode,
+ })
+ }
+ }
+
+ // Step 3: Process new constraints in order for CREATE operations
+ for _, newUKDef := range newUKList {
+ if oldUKDef, exists := oldUKMap[newUKDef.Name]; exists {
+ // UK exists in both - check if modified by comparing text first
+ currentText := getIndexText(newUKDef.ASTNode)
+ previousText := getIndexText(oldUKDef.ASTNode)
+ if currentText != previousText {
+ // UK was modified - store AST nodes only
ukDiffs = append(ukDiffs, &schema.UniqueConstraintDiff{
Action: schema.MetadataDiffActionCreate,
NewASTNode: newUKDef.ASTNode,
})
}
+ // If text is identical, skip - no changes detected
} else {
// New UK - store AST node only
ukDiffs = append(ukDiffs, &schema.UniqueConstraintDiff{
@@ -814,31 +879,20 @@ func processUniqueConstraintChanges(oldTable, newTable *parser.CreatestmtContext
}
}
- // Step 3: Process old unique constraints to find dropped ones
- for ukName, oldUKDef := range oldUKMap {
- if _, exists := newUKMap[ukName]; !exists {
- // UK was dropped - store AST node only
- ukDiffs = append(ukDiffs, &schema.UniqueConstraintDiff{
- Action: schema.MetadataDiffActionDrop,
- OldASTNode: oldUKDef.ASTNode,
- })
- }
- }
-
return ukDiffs
}
-// extractForeignKeyDefinitionsWithAST extracts foreign key constraints with their AST nodes for text comparison
-func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*ForeignKeyDefWithAST {
- fkMap := make(map[string]*ForeignKeyDefWithAST)
+// extractUniqueConstraintDefinitionsInOrder extracts unique constraints with their AST nodes in SQL order
+func extractUniqueConstraintDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*IndexDefWithAST {
+ var ukList []*IndexDefWithAST
if createStmt == nil || createStmt.Opttableelementlist() == nil {
- return fkMap
+ return ukList
}
tableElementList := createStmt.Opttableelementlist().Tableelementlist()
if tableElementList == nil {
- return fkMap
+ return ukList
}
for _, element := range tableElementList.AllTableelement() {
@@ -846,8 +900,11 @@ func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) m
constraint := element.Tableconstraint()
if constraint.Constraintelem() != nil {
elem := constraint.Constraintelem()
- if elem.FOREIGN() != nil && elem.KEY() != nil {
- // This is a foreign key constraint
+ // Check for UNIQUE constraints (but not PRIMARY KEY)
+ isUnique := elem.UNIQUE() != nil && (elem.PRIMARY() == nil || elem.KEY() == nil)
+
+ if isUnique {
+ // This is a unique constraint
name := ""
if constraint.Name() != nil {
name = pgparser.NormalizePostgreSQLName(constraint.Name())
@@ -864,29 +921,29 @@ func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) m
name = constraint.GetText() // Final fallback
}
}
- fkMap[name] = &ForeignKeyDefWithAST{
+ ukList = append(ukList, &IndexDefWithAST{
Name: name,
ASTNode: constraint,
- }
+ })
}
}
}
}
- return fkMap
+ return ukList
}
-// extractCheckConstraintDefinitionsWithAST extracts check constraints with their AST nodes for text comparison
-func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*CheckConstraintDefWithAST {
- checkMap := make(map[string]*CheckConstraintDefWithAST)
+// extractForeignKeyDefinitionsInOrder extracts foreign key constraints with their AST nodes in SQL order
+func extractForeignKeyDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*ForeignKeyDefWithAST {
+ var fkList []*ForeignKeyDefWithAST
if createStmt == nil || createStmt.Opttableelementlist() == nil {
- return checkMap
+ return fkList
}
tableElementList := createStmt.Opttableelementlist().Tableelementlist()
if tableElementList == nil {
- return checkMap
+ return fkList
}
for _, element := range tableElementList.AllTableelement() {
@@ -894,8 +951,8 @@ func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtConte
constraint := element.Tableconstraint()
if constraint.Constraintelem() != nil {
elem := constraint.Constraintelem()
- if elem.CHECK() != nil {
- // This is a check constraint
+ if elem.FOREIGN() != nil && elem.KEY() != nil {
+ // This is a foreign key constraint
name := ""
if constraint.Name() != nil {
name = pgparser.NormalizePostgreSQLName(constraint.Name())
@@ -912,29 +969,29 @@ func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtConte
name = constraint.GetText() // Final fallback
}
}
- checkMap[name] = &CheckConstraintDefWithAST{
+ fkList = append(fkList, &ForeignKeyDefWithAST{
Name: name,
ASTNode: constraint,
- }
+ })
}
}
}
}
- return checkMap
+ return fkList
}
-// extractPrimaryKeyDefinitionsWithAST extracts primary key constraints with their AST nodes
-func extractPrimaryKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*IndexDefWithAST {
- pkMap := make(map[string]*IndexDefWithAST)
+// extractCheckConstraintDefinitionsInOrder extracts check constraints with their AST nodes in SQL order
+func extractCheckConstraintDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*CheckConstraintDefWithAST {
+ var checkList []*CheckConstraintDefWithAST
if createStmt == nil || createStmt.Opttableelementlist() == nil {
- return pkMap
+ return checkList
}
tableElementList := createStmt.Opttableelementlist().Tableelementlist()
if tableElementList == nil {
- return pkMap
+ return checkList
}
for _, element := range tableElementList.AllTableelement() {
@@ -942,11 +999,8 @@ func extractPrimaryKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) m
constraint := element.Tableconstraint()
if constraint.Constraintelem() != nil {
elem := constraint.Constraintelem()
- // Check for PRIMARY KEY constraints
- isPrimary := elem.PRIMARY() != nil && elem.KEY() != nil
-
- if isPrimary {
- // This is a primary key constraint
+ if elem.CHECK() != nil {
+ // This is a check constraint
name := ""
if constraint.Name() != nil {
name = pgparser.NormalizePostgreSQLName(constraint.Name())
@@ -963,29 +1017,29 @@ func extractPrimaryKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) m
name = constraint.GetText() // Final fallback
}
}
- pkMap[name] = &IndexDefWithAST{
+ checkList = append(checkList, &CheckConstraintDefWithAST{
Name: name,
ASTNode: constraint,
- }
+ })
}
}
}
}
- return pkMap
+ return checkList
}
-// extractUniqueConstraintDefinitionsWithAST extracts unique constraints with their AST nodes
-func extractUniqueConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*IndexDefWithAST {
- ukMap := make(map[string]*IndexDefWithAST)
+// extractPrimaryKeyDefinitionsWithAST extracts primary key constraints with their AST nodes
+func extractPrimaryKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*IndexDefWithAST {
+ pkMap := make(map[string]*IndexDefWithAST)
if createStmt == nil || createStmt.Opttableelementlist() == nil {
- return ukMap
+ return pkMap
}
tableElementList := createStmt.Opttableelementlist().Tableelementlist()
if tableElementList == nil {
- return ukMap
+ return pkMap
}
for _, element := range tableElementList.AllTableelement() {
@@ -993,11 +1047,11 @@ func extractUniqueConstraintDefinitionsWithAST(createStmt *parser.CreatestmtCont
constraint := element.Tableconstraint()
if constraint.Constraintelem() != nil {
elem := constraint.Constraintelem()
- // Check for UNIQUE constraints (but not PRIMARY KEY)
- isUnique := elem.UNIQUE() != nil && (elem.PRIMARY() == nil || elem.KEY() == nil)
+ // Check for PRIMARY KEY constraints
+ isPrimary := elem.PRIMARY() != nil && elem.KEY() != nil
- if isUnique {
- // This is a unique constraint
+ if isPrimary {
+ // This is a primary key constraint
name := ""
if constraint.Name() != nil {
name = pgparser.NormalizePostgreSQLName(constraint.Name())
@@ -1014,7 +1068,7 @@ func extractUniqueConstraintDefinitionsWithAST(createStmt *parser.CreatestmtCont
name = constraint.GetText() // Final fallback
}
}
- ukMap[name] = &IndexDefWithAST{
+ pkMap[name] = &IndexDefWithAST{
Name: name,
ASTNode: constraint,
}
@@ -1023,7 +1077,7 @@ func extractUniqueConstraintDefinitionsWithAST(createStmt *parser.CreatestmtCont
}
}
- return ukMap
+ return pkMap
}
// getForeignKeyText returns the text representation of a foreign key constraint for comparison
diff --git a/backend/plugin/schema/pg/table_migration_integration_test.go b/backend/plugin/schema/pg/table_migration_integration_test.go
index 48fbf2ee64..d9e0b07ccb 100644
--- a/backend/plugin/schema/pg/table_migration_integration_test.go
+++ b/backend/plugin/schema/pg/table_migration_integration_test.go
@@ -334,6 +334,582 @@ func TestComplexTableWithConstraintsAndIndexes(t *testing.T) {
assert.Contains(t, migrationSQL, "CONSTRAINT unique_customer_date UNIQUE")
}
+func TestTableConstraintSDLDiffAndMigrationIntegration(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedMigration string
+ }{
+ {
+ name: "Add CHECK constraint",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" ADD CONSTRAINT "chk_price" CHECK (price > 0);`,
+ },
+ {
+ name: "Add FOREIGN KEY constraint",
+ previousSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."orders" ADD CONSTRAINT "fk_customer" FOREIGN KEY (customer_id) REFERENCES customers(id);`,
+ },
+ {
+ name: "Add UNIQUE constraint",
+ previousSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL,
+ CONSTRAINT unique_email UNIQUE (email)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ADD CONSTRAINT "unique_email" UNIQUE (email);`,
+ },
+ {
+ name: "Drop CHECK constraint",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" DROP CONSTRAINT IF EXISTS "chk_price";`,
+ },
+ {
+ name: "Drop FOREIGN KEY constraint",
+ previousSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."orders" DROP CONSTRAINT IF EXISTS "fk_customer";`,
+ },
+ {
+ name: "Modify CHECK constraint",
+ previousSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price >= 0)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."products" DROP CONSTRAINT IF EXISTS "chk_price";
+
+ALTER TABLE "public"."products" ADD CONSTRAINT "chk_price" CHECK (price >= 0);`,
+ },
+ {
+ name: "Add PRIMARY KEY constraint",
+ previousSDL: `
+ CREATE TABLE users (
+ id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ CONSTRAINT pk_users PRIMARY KEY (id)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" ADD CONSTRAINT "pk_users" PRIMARY KEY (id);`,
+ },
+ {
+ name: "Drop PRIMARY KEY constraint",
+ previousSDL: `
+ CREATE TABLE users (
+ id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ CONSTRAINT pk_users PRIMARY KEY (id)
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE users (
+ id INTEGER NOT NULL,
+ name VARCHAR(255) NOT NULL
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."users" DROP CONSTRAINT IF EXISTS "pk_users";`,
+ },
+ {
+ name: "Add multiple constraints",
+ previousSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending'
+ );
+ `,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending',
+ CONSTRAINT chk_total_amount CHECK (total_amount >= 0),
+ CONSTRAINT chk_status CHECK (status IN ('pending', 'confirmed', 'shipped')),
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id),
+ CONSTRAINT unique_customer_status UNIQUE (customer_id, status)
+ );
+ `,
+ expectedMigration: `ALTER TABLE "public"."orders" ADD CONSTRAINT "chk_total_amount" CHECK (total_amount >= 0);
+ALTER TABLE "public"."orders" ADD CONSTRAINT "chk_status" CHECK (status IN ('pending', 'confirmed', 'shipped'));
+ALTER TABLE "public"."orders" ADD CONSTRAINT "unique_customer_status" UNIQUE (customer_id, status);
+
+ALTER TABLE "public"."orders" ADD CONSTRAINT "fk_customer" FOREIGN KEY (customer_id) REFERENCES customers(id);`,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ // Get diff in AST-only mode (nil schemas for AST-only)
+ diff, err := GetSDLDiff(test.currentSDL, test.previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Should have one table change
+ require.Len(t, diff.TableChanges, 1)
+ tableDiff := diff.TableChanges[0]
+
+ // Verify it's an ALTER action for constraint changes
+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)
+
+ // Verify AST-only mode properties
+ assert.Nil(t, tableDiff.NewTable, "AST-only mode should not extract metadata")
+ assert.Nil(t, tableDiff.OldTable, "AST-only mode should not extract metadata")
+ assert.NotNil(t, tableDiff.NewASTNode, "New AST node should be present")
+ assert.NotNil(t, tableDiff.OldASTNode, "Old AST node should be present")
+
+ // Verify constraint changes are detected
+ hasConstraintChanges := len(tableDiff.CheckConstraintChanges) > 0 ||
+ len(tableDiff.ForeignKeyChanges) > 0 ||
+ len(tableDiff.UniqueConstraintChanges) > 0 ||
+ len(tableDiff.PrimaryKeyChanges) > 0
+
+ assert.True(t, hasConstraintChanges, "Should detect constraint changes")
+
+ // Generate migration SQL
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+
+ // Normalize whitespace for comparison
+ normalizedMigration := strings.TrimSpace(migrationSQL)
+ normalizedExpected := strings.TrimSpace(test.expectedMigration)
+
+ assert.Equal(t, normalizedExpected, normalizedMigration,
+ "Migration SQL should match expected output")
+ })
+ }
+}
+
+func TestTableConstraintComplexChanges(t *testing.T) {
+ // Test a complex scenario with constraint additions, modifications, and drops
+ previousSDL := `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL UNIQUE,
+ age INTEGER CHECK (age >= 18),
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ amount DECIMAL(10,2) NOT NULL,
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id)
+ );
+ `
+
+ currentSDL := `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) NOT NULL,
+ age INTEGER CHECK (age >= 16),
+ phone VARCHAR(20) UNIQUE,
+ created_at TIMESTAMP DEFAULT NOW()
+ );
+
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ amount DECIMAL(10,2) NOT NULL CHECK (amount > 0),
+ status VARCHAR(20) DEFAULT 'pending',
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ CONSTRAINT unique_user_amount UNIQUE (user_id, amount)
+ );
+ `
+
+ // Get diff in AST-only mode
+ diff, err := GetSDLDiff(currentSDL, previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Should have changes for both tables
+ assert.Len(t, diff.TableChanges, 2)
+
+ // Check that each table has the expected constraint changes
+ for _, tableDiff := range diff.TableChanges {
+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)
+
+ // Verify AST-only mode properties
+ assert.Nil(t, tableDiff.NewTable, "AST-only mode should not extract metadata")
+ assert.Nil(t, tableDiff.OldTable, "AST-only mode should not extract metadata")
+ assert.NotNil(t, tableDiff.NewASTNode, "New AST node should be present")
+ assert.NotNil(t, tableDiff.OldASTNode, "Old AST node should be present")
+
+ // Verify constraint or column changes are detected
+ hasConstraintChanges := len(tableDiff.CheckConstraintChanges) > 0 ||
+ len(tableDiff.ForeignKeyChanges) > 0 ||
+ len(tableDiff.UniqueConstraintChanges) > 0 ||
+ len(tableDiff.PrimaryKeyChanges) > 0 ||
+ len(tableDiff.ColumnChanges) > 0
+
+ if tableDiff.TableName == "users" || tableDiff.TableName == "orders" {
+ assert.True(t, hasConstraintChanges, "Should detect constraint or column changes for %s", tableDiff.TableName)
+ }
+ }
+
+ // Generate migration SQL
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+ assert.NotEmpty(t, migrationSQL, "Migration SQL should not be empty")
+
+ // Verify the migration handles both tables
+ assert.Contains(t, migrationSQL, "users")
+ assert.Contains(t, migrationSQL, "orders")
+}
+
+func TestCreateTableWithTableConstraintsIntegration(t *testing.T) {
+ tests := []struct {
+ name string
+ previousSDL string
+ currentSDL string
+ expectedMigration string
+ }{
+ {
+ name: "Create table with CHECK constraint",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+ `,
+ expectedMigration: `CREATE TABLE products (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_price CHECK (price > 0)
+ );
+
+`,
+ },
+ {
+ name: "Create table with FOREIGN KEY constraint",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ order_date DATE DEFAULT CURRENT_DATE,
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
+ );
+ `,
+ expectedMigration: `CREATE TABLE orders (
+ id SERIAL PRIMARY KEY,
+ customer_id INTEGER NOT NULL,
+ order_date DATE DEFAULT CURRENT_DATE,
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
+ );
+
+`,
+ },
+ {
+ name: "Create table with UNIQUE constraint",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320) NOT NULL,
+ username VARCHAR(50) NOT NULL,
+ CONSTRAINT unique_email UNIQUE (email),
+ CONSTRAINT unique_username UNIQUE (username)
+ );
+ `,
+ expectedMigration: `CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(320) NOT NULL,
+ username VARCHAR(50) NOT NULL,
+ CONSTRAINT unique_email UNIQUE (email),
+ CONSTRAINT unique_username UNIQUE (username)
+ );
+
+`,
+ },
+ {
+ name: "Create table with PRIMARY KEY constraint",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE composite_key_table (
+ tenant_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ data TEXT,
+ CONSTRAINT pk_composite PRIMARY KEY (tenant_id, user_id)
+ );
+ `,
+ expectedMigration: `CREATE TABLE composite_key_table (
+ tenant_id INTEGER NOT NULL,
+ user_id INTEGER NOT NULL,
+ data TEXT,
+ CONSTRAINT pk_composite PRIMARY KEY (tenant_id, user_id)
+ );
+
+`,
+ },
+ {
+ name: "Create table with multiple constraints",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE orders (
+ id SERIAL,
+ customer_id INTEGER NOT NULL,
+ order_date DATE DEFAULT CURRENT_DATE,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending',
+ created_at TIMESTAMP DEFAULT NOW(),
+ CONSTRAINT pk_orders PRIMARY KEY (id),
+ CONSTRAINT chk_total_amount CHECK (total_amount >= 0),
+ CONSTRAINT chk_status CHECK (status IN ('pending', 'confirmed', 'shipped', 'delivered')),
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE,
+ CONSTRAINT unique_customer_date UNIQUE (customer_id, order_date)
+ );
+ `,
+ expectedMigration: `CREATE TABLE orders (
+ id SERIAL,
+ customer_id INTEGER NOT NULL,
+ order_date DATE DEFAULT CURRENT_DATE,
+ total_amount DECIMAL(12,2) NOT NULL,
+ status VARCHAR(20) DEFAULT 'pending',
+ created_at TIMESTAMP DEFAULT NOW(),
+ CONSTRAINT pk_orders PRIMARY KEY (id),
+ CONSTRAINT chk_total_amount CHECK (total_amount >= 0),
+ CONSTRAINT chk_status CHECK (status IN ('pending', 'confirmed', 'shipped', 'delivered')),
+ CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE,
+ CONSTRAINT unique_customer_date UNIQUE (customer_id, order_date)
+ );
+
+`,
+ },
+ {
+ name: "Create table with complex CHECK constraints",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ first_name VARCHAR(50) NOT NULL,
+ last_name VARCHAR(50) NOT NULL,
+ email VARCHAR(320) NOT NULL,
+ salary DECIMAL(10,2),
+ hire_date DATE DEFAULT CURRENT_DATE,
+ department_id INTEGER,
+ CONSTRAINT chk_salary CHECK (salary IS NULL OR salary > 0),
+ CONSTRAINT chk_email_format CHECK (email ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),
+ CONSTRAINT chk_hire_date CHECK (hire_date >= '2000-01-01'),
+ CONSTRAINT chk_name_not_empty CHECK (LENGTH(TRIM(first_name)) > 0 AND LENGTH(TRIM(last_name)) > 0),
+ CONSTRAINT unique_email UNIQUE (email),
+ CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(id)
+ );
+ `,
+ expectedMigration: `CREATE TABLE employees (
+ id SERIAL PRIMARY KEY,
+ first_name VARCHAR(50) NOT NULL,
+ last_name VARCHAR(50) NOT NULL,
+ email VARCHAR(320) NOT NULL,
+ salary DECIMAL(10,2),
+ hire_date DATE DEFAULT CURRENT_DATE,
+ department_id INTEGER,
+ CONSTRAINT chk_salary CHECK (salary IS NULL OR salary > 0),
+ CONSTRAINT chk_email_format CHECK (email ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'),
+ CONSTRAINT chk_hire_date CHECK (hire_date >= '2000-01-01'),
+ CONSTRAINT chk_name_not_empty CHECK (LENGTH(TRIM(first_name)) > 0 AND LENGTH(TRIM(last_name)) > 0),
+ CONSTRAINT unique_email UNIQUE (email),
+ CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(id)
+ );
+
+`,
+ },
+ {
+ name: "Create table with FOREIGN KEY and referential actions",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE order_items (
+ id SERIAL PRIMARY KEY,
+ order_id INTEGER NOT NULL,
+ product_id INTEGER NOT NULL,
+ quantity INTEGER NOT NULL DEFAULT 1,
+ unit_price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_quantity CHECK (quantity > 0),
+ CONSTRAINT chk_unit_price CHECK (unit_price > 0),
+ CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT unique_order_product UNIQUE (order_id, product_id)
+ );
+ `,
+ expectedMigration: `CREATE TABLE order_items (
+ id SERIAL PRIMARY KEY,
+ order_id INTEGER NOT NULL,
+ product_id INTEGER NOT NULL,
+ quantity INTEGER NOT NULL DEFAULT 1,
+ unit_price DECIMAL(10,2) NOT NULL,
+ CONSTRAINT chk_quantity CHECK (quantity > 0),
+ CONSTRAINT chk_unit_price CHECK (unit_price > 0),
+ CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT fk_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT unique_order_product UNIQUE (order_id, product_id)
+ );
+
+`,
+ },
+ {
+ name: "Create table with schema-qualified constraint references",
+ previousSDL: ``,
+ currentSDL: `
+ CREATE TABLE audit.user_actions (
+ id BIGSERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ action_type VARCHAR(50) NOT NULL,
+ table_name VARCHAR(100) NOT NULL,
+ record_id INTEGER,
+ action_timestamp TIMESTAMP DEFAULT NOW(),
+ CONSTRAINT chk_action_type CHECK (action_type IN ('INSERT', 'UPDATE', 'DELETE')),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE,
+ CONSTRAINT unique_user_action_time UNIQUE (user_id, action_timestamp)
+ );
+ `,
+ expectedMigration: `CREATE TABLE audit.user_actions (
+ id BIGSERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ action_type VARCHAR(50) NOT NULL,
+ table_name VARCHAR(100) NOT NULL,
+ record_id INTEGER,
+ action_timestamp TIMESTAMP DEFAULT NOW(),
+ CONSTRAINT chk_action_type CHECK (action_type IN ('INSERT', 'UPDATE', 'DELETE')),
+ CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE,
+ CONSTRAINT unique_user_action_time UNIQUE (user_id, action_timestamp)
+ );
+
+`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Step 1: Get SDL diff using AST-only mode (no metadata extraction)
+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousSDL, nil, nil)
+ require.NoError(t, err)
+ require.NotNil(t, diff)
+
+ // Step 2: Verify that diff contains table creation with AST nodes
+ require.Len(t, diff.TableChanges, 1)
+ tableDiff := diff.TableChanges[0]
+
+ assert.Equal(t, schema.MetadataDiffActionCreate, tableDiff.Action,
+ "Should be a CREATE action")
+ assert.NotNil(t, tableDiff.NewASTNode,
+ "Create action should have NewASTNode")
+ assert.Nil(t, tableDiff.OldASTNode,
+ "Create action should not have OldASTNode")
+ // Verify that no metadata was extracted (AST-only mode)
+ assert.Nil(t, tableDiff.NewTable,
+ "AST-only mode should not have metadata")
+
+ // Step 3: Generate migration SQL using AST nodes
+ migrationSQL, err := generateMigration(diff)
+ require.NoError(t, err)
+
+ // Step 4: Verify the generated migration matches expectations
+ assert.Equal(t, tt.expectedMigration, migrationSQL,
+ "Generated migration SQL should match expected output")
+
+ // Step 5: Verify the migration contains expected constraint keywords
+ if tt.expectedMigration != "" {
+ if containsTableString(tt.expectedMigration, "CHECK") {
+ assert.Contains(t, migrationSQL, "CHECK",
+ "Migration should contain CHECK constraint")
+ }
+ if containsTableString(tt.expectedMigration, "FOREIGN KEY") {
+ assert.Contains(t, migrationSQL, "FOREIGN KEY",
+ "Migration should contain FOREIGN KEY constraint")
+ }
+ if containsTableString(tt.expectedMigration, "UNIQUE") {
+ assert.Contains(t, migrationSQL, "UNIQUE",
+ "Migration should contain UNIQUE constraint")
+ }
+ if containsTableString(tt.expectedMigration, "PRIMARY KEY") {
+ assert.Contains(t, migrationSQL, "PRIMARY KEY",
+ "Migration should contain PRIMARY KEY constraint")
+ }
+ if containsTableString(tt.expectedMigration, "CONSTRAINT") {
+ assert.Contains(t, migrationSQL, "CONSTRAINT",
+ "Migration should contain CONSTRAINT keyword")
+ }
+ }
+ })
+ }
+}
+
// Helper function to check if a string contains a substring (table tests)
func containsTableString(s, substr string) bool {
return strings.Contains(s, substr)