Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support pg table constraints in SDL (#17410)
rebelicef59411dc6c73
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex 159bb3e234..40801f2670 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -106,9 +106,11 @@ type ColumnDiff struct {// IndexDiff represents changes to an index.type IndexDiff struct {- Action MetadataDiffAction- OldIndex *storepb.IndexMetadata- NewIndex *storepb.IndexMetadata+ Action MetadataDiffAction+ OldIndex *storepb.IndexMetadata+ NewIndex *storepb.IndexMetadata+ OldASTNode any // AST node for old index constraint+ NewASTNode any // AST node for new index constraint}// ForeignKeyDiff represents changes to a foreign key.@@ -116,6 +118,8 @@ type ForeignKeyDiff struct {Action MetadataDiffActionOldForeignKey *storepb.ForeignKeyMetadataNewForeignKey *storepb.ForeignKeyMetadata+ OldASTNode any // AST node for old foreign key constraint+ NewASTNode any // AST node for new foreign key constraint}// CheckConstraintDiff represents changes to a check constraint.@@ -123,6 +127,8 @@ type CheckConstraintDiff struct {Action MetadataDiffActionOldCheckConstraint *storepb.CheckConstraintMetadataNewCheckConstraint *storepb.CheckConstraintMetadata+ OldASTNode any // AST node for old check constraint+ NewASTNode any // AST node for new check constraint}// TriggerDiff represents changes to a trigger.diff --git a/backend/plugin/schema/pg/column_sdl_diff_test.go b/backend/plugin/schema/pg/column_sdl_diff_test.goindex 35fcb668f8..7471822751 100644--- a/backend/plugin/schema/pg/column_sdl_diff_test.go+++ b/backend/plugin/schema/pg/column_sdl_diff_test.go@@ -23,6 +23,7 @@ func TestColumnSDLDiff(t *testing.T) {expectedAlterColumns []stringexpectedDropColumns []stringvalidateColumnDiffs func(t *testing.T, columnDiffs []*schema.ColumnDiff)+ validateTableDiffs func(t *testing.T, tableDiffs []*schema.TableDiff)}{{name: "No column changes - identical tables",@@ -308,6 +309,78 @@ func TestColumnSDLDiff(t *testing.T) {assert.NotEqual(t, oldText, newText, "AST text should be different due to whitespace")},},+ {+ name: "Add foreign key constraint",+ currentSDL: `CREATE TABLE orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER,+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id)+ );`,+ previousSDL: `CREATE TABLE orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER+ );`,+ expectedTableChanges: 1,+ validateTableDiffs: func(t *testing.T, tableDiffs []*schema.TableDiff) {+ assert.Len(t, tableDiffs, 1, "Should have 1 table diff")+ tableDiff := tableDiffs[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)+ assert.Len(t, tableDiff.ForeignKeyChanges, 1, "Should have 1 FK change")+ fkChange := tableDiff.ForeignKeyChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, fkChange.Action)+ // AST node should be present for created FK+ assert.NotNil(t, fkChange.NewASTNode)+ assert.Nil(t, fkChange.OldASTNode)+ },+ },+ {+ name: "Add check constraint",+ currentSDL: `CREATE TABLE products (+ id INTEGER PRIMARY KEY,+ price DECIMAL(10,2),+ CONSTRAINT chk_positive_price CHECK (price > 0)+ );`,+ previousSDL: `CREATE TABLE products (+ id INTEGER PRIMARY KEY,+ price DECIMAL(10,2)+ );`,+ expectedTableChanges: 1,+ validateTableDiffs: func(t *testing.T, tableDiffs []*schema.TableDiff) {+ assert.Len(t, tableDiffs, 1, "Should have 1 table diff")+ tableDiff := tableDiffs[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)+ assert.Len(t, tableDiff.CheckConstraintChanges, 1, "Should have 1 check constraint change")+ checkChange := tableDiff.CheckConstraintChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, checkChange.Action)+ // AST node should be present for created check constraint+ assert.NotNil(t, checkChange.NewASTNode)+ assert.Nil(t, checkChange.OldASTNode)+ },+ },+ {+ name: "Add unique constraint",+ currentSDL: `CREATE TABLE users (+ id INTEGER PRIMARY KEY,+ email VARCHAR(255),+ CONSTRAINT uk_users_email UNIQUE (email)+ );`,+ previousSDL: `CREATE TABLE users (+ id INTEGER PRIMARY KEY,+ email VARCHAR(255)+ );`,+ expectedTableChanges: 1,+ validateTableDiffs: func(t *testing.T, tableDiffs []*schema.TableDiff) {+ assert.Len(t, tableDiffs, 1, "Should have 1 table diff")+ tableDiff := tableDiffs[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)+ assert.Len(t, tableDiff.IndexChanges, 1, "Should have 1 index change for UNIQUE constraint")+ indexChange := tableDiff.IndexChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, indexChange.Action)+ // AST node should be present for created unique constraint+ assert.NotNil(t, indexChange.NewASTNode)+ assert.Nil(t, indexChange.OldASTNode)+ },+ },}for _, tc := range testCases {@@ -361,6 +434,11 @@ func TestColumnSDLDiff(t *testing.T) {tc.validateColumnDiffs(t, tableDiff.ColumnChanges)}}++ // Run table-level validation+ if tc.validateTableDiffs != nil {+ tc.validateTableDiffs(t, diff.TableChanges)+ }})}}diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex ca6351b9fa..e90cd6ec3f 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -214,16 +214,22 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, curren}columnChanges := processColumnChanges(oldASTNode, newASTNode)+ foreignKeyChanges := processForeignKeyChanges(oldASTNode, newASTNode)+ checkConstraintChanges := processCheckConstraintChanges(oldASTNode, newASTNode)+ indexChanges := processIndexChanges(oldASTNode, newASTNode)tableDiff := &schema.TableDiff{- Action: schema.MetadataDiffActionAlter,- SchemaName: schemaName,- TableName: tableName,- OldTable: nil, // Will be populated when SDL drift detection is implemented- NewTable: nil, // Will be populated when SDL drift detection is implemented- OldASTNode: oldASTNode,- NewASTNode: newASTNode,- ColumnChanges: columnChanges,+ Action: schema.MetadataDiffActionAlter,+ SchemaName: schemaName,+ TableName: tableName,+ OldTable: nil, // Will be populated when SDL drift detection is implemented+ NewTable: nil, // Will be populated when SDL drift detection is implemented+ OldASTNode: oldASTNode,+ NewASTNode: newASTNode,+ ColumnChanges: columnChanges,+ ForeignKeyChanges: foreignKeyChanges,+ CheckConstraintChanges: checkConstraintChanges,+ IndexChanges: indexChanges,}diff.TableChanges = append(diff.TableChanges, tableDiff)}@@ -541,3 +547,397 @@ func extractAnyName(anyName parser.IAny_nameContext) string {// Fallback to GetText() if tokens are not availablereturn anyName.GetText()}++// ForeignKeyDefWithAST holds foreign key constraint definition with its AST node for text comparison+type ForeignKeyDefWithAST struct {+ Name string+ ASTNode parser.ITableconstraintContext+}++// CheckConstraintDefWithAST holds check constraint definition with its AST node for text comparison+type CheckConstraintDefWithAST struct {+ Name string+ ASTNode parser.ITableconstraintContext+}++// IndexDefWithAST holds index/unique constraint definition with its AST node for text comparison+type IndexDefWithAST struct {+ Name string+ ASTNode parser.ITableconstraintContext+}++// processForeignKeyChanges analyzes foreign key constraint changes between old and new table definitions+// Following the text-first comparison pattern for performance optimization+func processForeignKeyChanges(oldTable, newTable *parser.CreatestmtContext) []*schema.ForeignKeyDiff {+ if oldTable == nil || newTable == nil {+ return []*schema.ForeignKeyDiff{}+ }++ // Step 1: Extract all foreign key definitions with their AST nodes for text comparison+ oldFKMap := extractForeignKeyDefinitionsWithAST(oldTable)+ newFKMap := extractForeignKeyDefinitionsWithAST(newTable)++ 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 {+ // 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,+ })+ fkDiffs = append(fkDiffs, &schema.ForeignKeyDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newFKDef.ASTNode,+ })+ }+ // If text is identical, skip - no changes detected+ } else {+ // New foreign key - store AST node only+ fkDiffs = append(fkDiffs, &schema.ForeignKeyDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newFKDef.ASTNode,+ })+ }+ }++ // 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+}++// processCheckConstraintChanges analyzes check constraint changes between old and new table definitions+// Following the text-first comparison pattern for performance optimization+func processCheckConstraintChanges(oldTable, newTable *parser.CreatestmtContext) []*schema.CheckConstraintDiff {+ if oldTable == nil || newTable == nil {+ return []*schema.CheckConstraintDiff{}+ }++ // Step 1: Extract all check constraint definitions with their AST nodes for text comparison+ oldCheckMap := extractCheckConstraintDefinitionsWithAST(oldTable)+ newCheckMap := extractCheckConstraintDefinitionsWithAST(newTable)++ 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 {+ // 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+ // Drop and recreate for modifications (PostgreSQL pattern)+ checkDiffs = append(checkDiffs, &schema.CheckConstraintDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: oldCheckDef.ASTNode,+ })+ checkDiffs = append(checkDiffs, &schema.CheckConstraintDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newCheckDef.ASTNode,+ })+ }+ // If text is identical, skip - no changes detected+ } else {+ // New check constraint - store AST node only+ checkDiffs = append(checkDiffs, &schema.CheckConstraintDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newCheckDef.ASTNode,+ })+ }+ }++ // 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+}++// processIndexChanges analyzes index changes (including PK and UK) between old and new table definitions+// Following the text-first comparison pattern for performance optimization+func processIndexChanges(oldTable, newTable *parser.CreatestmtContext) []*schema.IndexDiff {+ if oldTable == nil || newTable == nil {+ return []*schema.IndexDiff{}+ }++ // Step 1: Extract all index/unique constraint definitions with their AST nodes for text comparison+ oldIndexMap := extractIndexDefinitionsWithAST(oldTable)+ newIndexMap := extractIndexDefinitionsWithAST(newTable)++ var indexDiffs []*schema.IndexDiff++ // Step 2: Process current indexes to find created and modified indexes+ for indexName, newIndexDef := range newIndexMap {+ if oldIndexDef, exists := oldIndexMap[indexName]; exists {+ // Index exists in both - check if modified by comparing text first+ currentText := getIndexText(newIndexDef.ASTNode)+ previousText := getIndexText(oldIndexDef.ASTNode)+ if currentText != previousText {+ // Index was modified - store AST nodes only+ // Drop and recreate for modifications (PostgreSQL pattern)+ indexDiffs = append(indexDiffs, &schema.IndexDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: oldIndexDef.ASTNode,+ })+ indexDiffs = append(indexDiffs, &schema.IndexDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newIndexDef.ASTNode,+ })+ }+ // If text is identical, skip - no changes detected+ } else {+ // New index - store AST node only+ indexDiffs = append(indexDiffs, &schema.IndexDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newIndexDef.ASTNode,+ })+ }+ }++ // Step 3: Process old indexes to find dropped ones+ for indexName, oldIndexDef := range oldIndexMap {+ if _, exists := newIndexMap[indexName]; !exists {+ // Index was dropped - store AST node only+ indexDiffs = append(indexDiffs, &schema.IndexDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: oldIndexDef.ASTNode,+ })+ }+ }++ return indexDiffs+}++// 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)++ if createStmt == nil || createStmt.Opttableelementlist() == nil {+ return fkMap+ }++ tableElementList := createStmt.Opttableelementlist().Tableelementlist()+ if tableElementList == nil {+ return fkMap+ }++ for _, element := range tableElementList.AllTableelement() {+ if element.Tableconstraint() != nil {+ constraint := element.Tableconstraint()+ if constraint.Constraintelem() != nil {+ elem := constraint.Constraintelem()+ if elem.FOREIGN() != nil && elem.KEY() != nil {+ // This is a foreign key constraint+ name := ""+ if constraint.Name() != nil {+ name = pgparser.NormalizePostgreSQLName(constraint.Name())+ }+ // Use constraint definition text as fallback key if name is empty+ if name == "" {+ // Get the full original text from tokens+ if parser := constraint.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ name = tokenStream.GetTextFromRuleContext(constraint)+ }+ }+ if name == "" {+ name = constraint.GetText() // Final fallback+ }+ }+ fkMap[name] = &ForeignKeyDefWithAST{+ Name: name,+ ASTNode: constraint,+ }+ }+ }+ }+ }++ return fkMap+}++// extractCheckConstraintDefinitionsWithAST extracts check constraints with their AST nodes for text comparison+func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*CheckConstraintDefWithAST {+ checkMap := make(map[string]*CheckConstraintDefWithAST)++ if createStmt == nil || createStmt.Opttableelementlist() == nil {+ return checkMap+ }++ tableElementList := createStmt.Opttableelementlist().Tableelementlist()+ if tableElementList == nil {+ return checkMap+ }++ for _, element := range tableElementList.AllTableelement() {+ if element.Tableconstraint() != nil {+ constraint := element.Tableconstraint()+ if constraint.Constraintelem() != nil {+ elem := constraint.Constraintelem()+ if elem.CHECK() != nil {+ // This is a check constraint+ name := ""+ if constraint.Name() != nil {+ name = pgparser.NormalizePostgreSQLName(constraint.Name())+ }+ // Use constraint definition text as fallback key if name is empty+ if name == "" {+ // Get the full original text from tokens+ if parser := constraint.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ name = tokenStream.GetTextFromRuleContext(constraint)+ }+ }+ if name == "" {+ name = constraint.GetText() // Final fallback+ }+ }+ checkMap[name] = &CheckConstraintDefWithAST{+ Name: name,+ ASTNode: constraint,+ }+ }+ }+ }+ }++ return checkMap+}++// extractIndexDefinitionsWithAST extracts index/unique constraints with their AST nodes for text comparison+func extractIndexDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*IndexDefWithAST {+ indexMap := make(map[string]*IndexDefWithAST)++ if createStmt == nil || createStmt.Opttableelementlist() == nil {+ return indexMap+ }++ tableElementList := createStmt.Opttableelementlist().Tableelementlist()+ if tableElementList == nil {+ return indexMap+ }++ for _, element := range tableElementList.AllTableelement() {+ if element.Tableconstraint() != nil {+ constraint := element.Tableconstraint()+ if constraint.Constraintelem() != nil {+ elem := constraint.Constraintelem()+ // Check for PRIMARY KEY or UNIQUE constraints+ isPrimary := elem.PRIMARY() != nil && elem.KEY() != nil+ isUnique := elem.UNIQUE() != nil++ if isPrimary || isUnique {+ // This is a primary key or unique constraint+ name := ""+ if constraint.Name() != nil {+ name = pgparser.NormalizePostgreSQLName(constraint.Name())+ }+ // Use constraint definition text as fallback key if name is empty+ if name == "" {+ // Get the full original text from tokens+ if parser := constraint.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ name = tokenStream.GetTextFromRuleContext(constraint)+ }+ }+ if name == "" {+ name = constraint.GetText() // Final fallback+ }+ }+ indexMap[name] = &IndexDefWithAST{+ Name: name,+ ASTNode: constraint,+ }+ }+ }+ }+ }++ return indexMap+}++// getForeignKeyText returns the text representation of a foreign key constraint for comparison+func getForeignKeyText(constraintAST parser.ITableconstraintContext) string {+ if constraintAST == nil {+ return ""+ }++ // Get tokens from the parser for precise text extraction+ if parser := constraintAST.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := constraintAST.GetStart()+ stop := constraintAST.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }++ // Fallback to GetText() if tokens are not available+ return constraintAST.GetText()+}++// getCheckConstraintText returns the text representation of a check constraint for comparison+func getCheckConstraintText(constraintAST parser.ITableconstraintContext) string {+ if constraintAST == nil {+ return ""+ }++ // Get tokens from the parser for precise text extraction+ if parser := constraintAST.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := constraintAST.GetStart()+ stop := constraintAST.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }++ // Fallback to GetText() if tokens are not available+ return constraintAST.GetText()+}++// getIndexText returns the text representation of an index/unique constraint for comparison+func getIndexText(constraintAST parser.ITableconstraintContext) string {+ if constraintAST == nil {+ return ""+ }++ // Get tokens from the parser for precise text extraction+ if parser := constraintAST.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := constraintAST.GetStart()+ stop := constraintAST.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }++ // Fallback to GetText() if tokens are not available+ return constraintAST.GetText()+}diff --git a/backend/plugin/schema/pg/table_constraints_test.go b/backend/plugin/schema/pg/table_constraints_test.gonew file mode 100644index 0000000000..67a26ba67b--- /dev/null+++ b/backend/plugin/schema/pg/table_constraints_test.go@@ -0,0 +1,209 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/plugin/schema"+)++// TestTableConstraintsSDLDiff tests all table constraint types (PK, UK, FK, Check)+func TestTableConstraintsSDLDiff(t *testing.T) {+ testCases := []struct {+ name string+ currentSDL string+ previousSDL string+ validate func(t *testing.T, diff *schema.MetadataDiff)+ }{+ {+ name: "Add primary key constraint",+ currentSDL: `CREATE TABLE users (+ id INTEGER,+ name VARCHAR(255),+ CONSTRAINT pk_users PRIMARY KEY (id)+ );`,+ previousSDL: `CREATE TABLE users (+ id INTEGER,+ name VARCHAR(255)+ );`,+ validate: func(t *testing.T, diff *schema.MetadataDiff) {+ assert.Len(t, diff.TableChanges, 1)+ tableDiff := diff.TableChanges[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)+ assert.Len(t, tableDiff.IndexChanges, 1)+ indexChange := tableDiff.IndexChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, indexChange.Action)+ // AST node should be present for created primary key+ assert.NotNil(t, indexChange.NewASTNode)+ assert.Nil(t, indexChange.OldASTNode)+ },+ },+ {+ name: "Drop foreign key constraint",+ currentSDL: `CREATE TABLE orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER+ );`,+ previousSDL: `CREATE TABLE orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER,+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id)+ );`,+ validate: func(t *testing.T, diff *schema.MetadataDiff) {+ assert.Len(t, diff.TableChanges, 1)+ tableDiff := diff.TableChanges[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)+ assert.Len(t, tableDiff.ForeignKeyChanges, 1)+ fkChange := tableDiff.ForeignKeyChanges[0]+ assert.Equal(t, schema.MetadataDiffActionDrop, fkChange.Action)+ // AST node should be present for dropped FK+ assert.NotNil(t, fkChange.OldASTNode)+ assert.Nil(t, fkChange.NewASTNode)+ },+ },+ {+ name: "Modify check constraint",+ currentSDL: `CREATE TABLE products (+ id INTEGER PRIMARY KEY,+ price DECIMAL(10,2),+ CONSTRAINT chk_price CHECK (price >= 0)+ );`,+ previousSDL: `CREATE TABLE products (+ id INTEGER PRIMARY KEY,+ price DECIMAL(10,2),+ CONSTRAINT chk_price CHECK (price > 0)+ );`,+ validate: func(t *testing.T, diff *schema.MetadataDiff) {+ assert.Len(t, diff.TableChanges, 1)+ tableDiff := diff.TableChanges[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)+ // Should drop old and create new for modifications+ assert.Len(t, tableDiff.CheckConstraintChanges, 2)++ // Find drop and create actions+ var dropChange, createChange *schema.CheckConstraintDiff+ for _, change := range tableDiff.CheckConstraintChanges {+ switch change.Action {+ case schema.MetadataDiffActionDrop:+ dropChange = change+ case schema.MetadataDiffActionCreate:+ createChange = change+ default:+ // Other actions not expected in this test+ }+ }++ assert.NotNil(t, dropChange)+ assert.NotNil(t, createChange)+ // AST nodes should be present for check constraint changes+ assert.NotNil(t, dropChange.OldASTNode)+ assert.Nil(t, dropChange.NewASTNode)+ assert.NotNil(t, createChange.NewASTNode)+ assert.Nil(t, createChange.OldASTNode)+ },+ },+ {+ name: "Multiple constraint types in one table",+ currentSDL: `CREATE TABLE orders (+ id INTEGER,+ customer_id INTEGER,+ order_date DATE,+ amount DECIMAL(10,2),+ status VARCHAR(20),+ CONSTRAINT pk_orders PRIMARY KEY (id),+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id),+ CONSTRAINT uk_orders_date_customer UNIQUE (order_date, customer_id),+ CONSTRAINT chk_positive_amount CHECK (amount > 0),+ CONSTRAINT chk_valid_status CHECK (status IN ('pending', 'completed', 'cancelled'))+ );`,+ previousSDL: `CREATE TABLE orders (+ id INTEGER,+ customer_id INTEGER,+ order_date DATE,+ amount DECIMAL(10,2),+ status VARCHAR(20)+ );`,+ validate: func(t *testing.T, diff *schema.MetadataDiff) {+ assert.Len(t, diff.TableChanges, 1)+ tableDiff := diff.TableChanges[0]+ assert.Equal(t, schema.MetadataDiffActionAlter, tableDiff.Action)++ // Should have 2 index changes (PK and UNIQUE)+ assert.Len(t, tableDiff.IndexChanges, 2)++ // Should have 1 foreign key change+ assert.Len(t, tableDiff.ForeignKeyChanges, 1)+ fkChange := tableDiff.ForeignKeyChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, fkChange.Action)+ // AST node should be present for created FK+ assert.NotNil(t, fkChange.NewASTNode)+ assert.Nil(t, fkChange.OldASTNode)++ // Should have 2 check constraint changes+ assert.Len(t, tableDiff.CheckConstraintChanges, 2)+ for _, checkChange := range tableDiff.CheckConstraintChanges {+ assert.Equal(t, schema.MetadataDiffActionCreate, checkChange.Action)+ // AST node should be present for created check constraints+ assert.NotNil(t, checkChange.NewASTNode)+ assert.Nil(t, checkChange.OldASTNode)+ }+ },+ },+ {+ name: "Complex foreign key with schema qualification",+ currentSDL: `CREATE TABLE orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER,+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES public.customers(id)+ );`,+ previousSDL: `CREATE TABLE orders (+ id INTEGER PRIMARY KEY,+ customer_id INTEGER+ );`,+ validate: func(t *testing.T, diff *schema.MetadataDiff) {+ assert.Len(t, diff.TableChanges, 1)+ tableDiff := diff.TableChanges[0]+ assert.Len(t, tableDiff.ForeignKeyChanges, 1)+ fkChange := tableDiff.ForeignKeyChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, fkChange.Action)+ // AST node should be present for created FK with schema qualification+ assert.NotNil(t, fkChange.NewASTNode)+ assert.Nil(t, fkChange.OldASTNode)+ },+ },+ {+ name: "Composite unique constraint",+ currentSDL: `CREATE TABLE user_sessions (+ user_id INTEGER,+ session_token VARCHAR(255),+ created_at TIMESTAMP,+ CONSTRAINT uk_user_sessions UNIQUE (user_id, session_token)+ );`,+ previousSDL: `CREATE TABLE user_sessions (+ user_id INTEGER,+ session_token VARCHAR(255),+ created_at TIMESTAMP+ );`,+ validate: func(t *testing.T, diff *schema.MetadataDiff) {+ assert.Len(t, diff.TableChanges, 1)+ tableDiff := diff.TableChanges[0]+ assert.Len(t, tableDiff.IndexChanges, 1)+ indexChange := tableDiff.IndexChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, indexChange.Action)+ // AST node should be present for created unique constraint+ assert.NotNil(t, indexChange.NewASTNode)+ assert.Nil(t, indexChange.OldASTNode)+ },+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ diff, err := GetSDLDiff(tc.currentSDL, tc.previousSDL, nil, nil)+ require.NoError(t, err, "GetSDLDiff should not return error")+ tc.validate(t, diff)+ })+ }+}