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 index for SDL (#17412)
rebelicefd66f93ca029
diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex 40801f2670..5f7f33906a 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -77,9 +77,15 @@ type TableDiff struct {// Column changesColumnChanges []*ColumnDiff- // Index changes+ // Index changes (excluding PK and UK which are handled separately)IndexChanges []*IndexDiff+ // Primary key changes+ PrimaryKeyChanges []*PrimaryKeyDiff++ // Unique constraint changes+ UniqueConstraintChanges []*UniqueConstraintDiff+// Foreign key changesForeignKeyChanges []*ForeignKeyDiff@@ -131,6 +137,24 @@ type CheckConstraintDiff struct {NewASTNode any // AST node for new check constraint}+// PrimaryKeyDiff represents changes to a primary key constraint.+type PrimaryKeyDiff struct {+ Action MetadataDiffAction+ OldPrimaryKey *storepb.IndexMetadata+ NewPrimaryKey *storepb.IndexMetadata+ OldASTNode any // AST node for old primary key constraint+ NewASTNode any // AST node for new primary key constraint+}++// UniqueConstraintDiff represents changes to a unique constraint.+type UniqueConstraintDiff struct {+ Action MetadataDiffAction+ OldUniqueConstraint *storepb.IndexMetadata+ NewUniqueConstraint *storepb.IndexMetadata+ OldASTNode any // AST node for old unique constraint+ NewASTNode any // AST node for new unique constraint+}+// TriggerDiff represents changes to a trigger.type TriggerDiff struct {Action MetadataDiffAction@@ -2274,6 +2298,50 @@ func sortTableSubObjectChanges(tableDiff *TableDiff) {return strings.Compare(string(a.Action), string(b.Action))})+ // Sort primary key changes by constraint name, then action+ slices.SortFunc(tableDiff.PrimaryKeyChanges, func(a, b *PrimaryKeyDiff) int {+ aName := ""+ if a.NewPrimaryKey != nil {+ aName = a.NewPrimaryKey.Name+ } else if a.OldPrimaryKey != nil {+ aName = a.OldPrimaryKey.Name+ }++ bName := ""+ if b.NewPrimaryKey != nil {+ bName = b.NewPrimaryKey.Name+ } else if b.OldPrimaryKey != nil {+ bName = b.OldPrimaryKey.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })++ // Sort unique constraint changes by constraint name, then action+ slices.SortFunc(tableDiff.UniqueConstraintChanges, func(a, b *UniqueConstraintDiff) int {+ aName := ""+ if a.NewUniqueConstraint != nil {+ aName = a.NewUniqueConstraint.Name+ } else if a.OldUniqueConstraint != nil {+ aName = a.OldUniqueConstraint.Name+ }++ bName := ""+ if b.NewUniqueConstraint != nil {+ bName = b.NewUniqueConstraint.Name+ } else if b.OldUniqueConstraint != nil {+ bName = b.OldUniqueConstraint.Name+ }++ if aName != bName {+ return strings.Compare(aName, bName)+ }+ return strings.Compare(string(a.Action), string(b.Action))+ })+// Sort partition changes by partition name, then actionslices.SortFunc(tableDiff.PartitionChanges, func(a, b *PartitionDiff) int {aName := ""diff --git a/backend/plugin/schema/pg/column_sdl_diff_test.go b/backend/plugin/schema/pg/column_sdl_diff_test.goindex 7471822751..9235be0c19 100644--- a/backend/plugin/schema/pg/column_sdl_diff_test.go+++ b/backend/plugin/schema/pg/column_sdl_diff_test.go@@ -373,12 +373,12 @@ func TestColumnSDLDiff(t *testing.T) {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)+ assert.Len(t, tableDiff.UniqueConstraintChanges, 1, "Should have 1 unique constraint change")+ uniqueChange := tableDiff.UniqueConstraintChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, uniqueChange.Action)// AST node should be present for created unique constraint- assert.NotNil(t, indexChange.NewASTNode)- assert.Nil(t, indexChange.OldASTNode)+ assert.NotNil(t, uniqueChange.NewASTNode)+ assert.Nil(t, uniqueChange.OldASTNode)},},}diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex e90cd6ec3f..24561161f3 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -49,6 +49,9 @@ func GetSDLDiff(currentSDLText, previousUserSDLText string, currentSchema, previreturn nil, errors.Wrap(err, "failed to process table changes")}+ // Process index changes (standalone CREATE INDEX statements)+ processStandaloneIndexChanges(currentChunks, previousChunks, diff)+return diff, nil}@@ -216,20 +219,22 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currencolumnChanges := processColumnChanges(oldASTNode, newASTNode)foreignKeyChanges := processForeignKeyChanges(oldASTNode, newASTNode)checkConstraintChanges := processCheckConstraintChanges(oldASTNode, newASTNode)- indexChanges := processIndexChanges(oldASTNode, newASTNode)+ primaryKeyChanges := processPrimaryKeyChanges(oldASTNode, newASTNode)+ uniqueConstraintChanges := processUniqueConstraintChanges(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,- ForeignKeyChanges: foreignKeyChanges,- CheckConstraintChanges: checkConstraintChanges,- IndexChanges: indexChanges,+ 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,+ PrimaryKeyChanges: primaryKeyChanges,+ UniqueConstraintChanges: uniqueConstraintChanges,}diff.TableChanges = append(diff.TableChanges, tableDiff)}@@ -676,59 +681,108 @@ func processCheckConstraintChanges(oldTable, newTable *parser.CreatestmtContext)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 {+// processPrimaryKeyChanges analyzes primary key constraint changes between old and new table definitions+func processPrimaryKeyChanges(oldTable, newTable *parser.CreatestmtContext) []*schema.PrimaryKeyDiff {if oldTable == nil || newTable == nil {- return []*schema.IndexDiff{}+ return []*schema.PrimaryKeyDiff{}}- // Step 1: Extract all index/unique constraint definitions with their AST nodes for text comparison- oldIndexMap := extractIndexDefinitionsWithAST(oldTable)- newIndexMap := extractIndexDefinitionsWithAST(newTable)+ // Step 1: Extract all primary key constraint definitions with their AST nodes for text comparison+ oldPKMap := extractPrimaryKeyDefinitionsWithAST(oldTable)+ newPKMap := extractPrimaryKeyDefinitionsWithAST(newTable)- var indexDiffs []*schema.IndexDiff+ var pkDiffs []*schema.PrimaryKeyDiff- // 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)+ // Step 2: Process current primary keys to find created and modified primary keys+ for pkName, newPKDef := range newPKMap {+ if oldPKDef, exists := oldPKMap[pkName]; exists {+ // PK exists in both - check if modified by comparing text first+ currentText := getIndexText(newPKDef.ASTNode)+ previousText := getIndexText(oldPKDef.ASTNode)if currentText != previousText {- // Index was modified - store AST nodes only- // Drop and recreate for modifications (PostgreSQL pattern)- indexDiffs = append(indexDiffs, &schema.IndexDiff{+ // PK was modified - store AST nodes only+ pkDiffs = append(pkDiffs, &schema.PrimaryKeyDiff{Action: schema.MetadataDiffActionDrop,- OldASTNode: oldIndexDef.ASTNode,+ OldASTNode: oldPKDef.ASTNode,})- indexDiffs = append(indexDiffs, &schema.IndexDiff{+ pkDiffs = append(pkDiffs, &schema.PrimaryKeyDiff{Action: schema.MetadataDiffActionCreate,- NewASTNode: newIndexDef.ASTNode,+ NewASTNode: newPKDef.ASTNode,})}- // If text is identical, skip - no changes detected} else {- // New index - store AST node only- indexDiffs = append(indexDiffs, &schema.IndexDiff{+ // New PK - store AST node only+ pkDiffs = append(pkDiffs, &schema.PrimaryKeyDiff{Action: schema.MetadataDiffActionCreate,- NewASTNode: newIndexDef.ASTNode,+ NewASTNode: newPKDef.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{+ // Step 3: Process old primary keys to find dropped ones+ for pkName, oldPKDef := range oldPKMap {+ if _, exists := newPKMap[pkName]; !exists {+ // PK was dropped - store AST node only+ pkDiffs = append(pkDiffs, &schema.PrimaryKeyDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: oldPKDef.ASTNode,+ })+ }+ }++ return pkDiffs+}++// processUniqueConstraintChanges analyzes unique constraint changes between old and new table definitions+func processUniqueConstraintChanges(oldTable, newTable *parser.CreatestmtContext) []*schema.UniqueConstraintDiff {+ if oldTable == nil || newTable == nil {+ return []*schema.UniqueConstraintDiff{}+ }++ // Step 1: Extract all unique constraint definitions with their AST nodes for text comparison+ oldUKMap := extractUniqueConstraintDefinitionsWithAST(oldTable)+ newUKMap := extractUniqueConstraintDefinitionsWithAST(newTable)++ 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 {+ // 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.MetadataDiffActionDrop,+ OldASTNode: oldUKDef.ASTNode,+ })+ ukDiffs = append(ukDiffs, &schema.UniqueConstraintDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newUKDef.ASTNode,+ })+ }+ } else {+ // New UK - store AST node only+ ukDiffs = append(ukDiffs, &schema.UniqueConstraintDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newUKDef.ASTNode,+ })+ }+ }++ // 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: oldIndexDef.ASTNode,+ OldASTNode: oldUKDef.ASTNode,})}}- return indexDiffs+ return ukDiffs}// extractForeignKeyDefinitionsWithAST extracts foreign key constraints with their AST nodes for text comparison@@ -827,17 +881,17 @@ func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContereturn 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)+// 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 indexMap+ return pkMap}tableElementList := createStmt.Opttableelementlist().Tableelementlist()if tableElementList == nil {- return indexMap+ return pkMap}for _, element := range tableElementList.AllTableelement() {@@ -845,12 +899,11 @@ func extractIndexDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[stconstraint := element.Tableconstraint()if constraint.Constraintelem() != nil {elem := constraint.Constraintelem()- // Check for PRIMARY KEY or UNIQUE constraints+ // Check for PRIMARY KEY constraintsisPrimary := elem.PRIMARY() != nil && elem.KEY() != nil- isUnique := elem.UNIQUE() != nil- if isPrimary || isUnique {- // This is a primary key or unique constraint+ if isPrimary {+ // This is a primary key constraintname := ""if constraint.Name() != nil {name = pgparser.NormalizePostgreSQLName(constraint.Name())@@ -867,7 +920,7 @@ func extractIndexDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[stname = constraint.GetText() // Final fallback}}- indexMap[name] = &IndexDefWithAST{+ pkMap[name] = &IndexDefWithAST{Name: name,ASTNode: constraint,}@@ -876,7 +929,58 @@ func extractIndexDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[st}}- return indexMap+ return pkMap+}++// extractUniqueConstraintDefinitionsWithAST extracts unique constraints with their AST nodes+func extractUniqueConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*IndexDefWithAST {+ ukMap := make(map[string]*IndexDefWithAST)++ if createStmt == nil || createStmt.Opttableelementlist() == nil {+ return ukMap+ }++ tableElementList := createStmt.Opttableelementlist().Tableelementlist()+ if tableElementList == nil {+ return ukMap+ }++ for _, element := range tableElementList.AllTableelement() {+ if element.Tableconstraint() != nil {+ 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)++ if isUnique {+ // This is a 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+ }+ }+ ukMap[name] = &IndexDefWithAST{+ Name: name,+ ASTNode: constraint,+ }+ }+ }+ }+ }++ return ukMap}// getForeignKeyText returns the text representation of a foreign key constraint for comparison@@ -941,3 +1045,141 @@ func getIndexText(constraintAST parser.ITableconstraintContext) string {// Fallback to GetText() if tokens are not availablereturn constraintAST.GetText()}++// processStandaloneIndexChanges analyzes standalone CREATE INDEX statement changes+// and adds them to the appropriate table's IndexChanges+func processStandaloneIndexChanges(currentChunks, previousChunks *schema.SDLChunks, diff *schema.MetadataDiff) {+ if currentChunks == nil || previousChunks == nil {+ return+ }++ // Initialize map with all existing table diffs for efficient lookups+ affectedTables := make(map[string]*schema.TableDiff, len(diff.TableChanges))+ for _, tableDiff := range diff.TableChanges {+ affectedTables[tableDiff.TableName] = tableDiff+ }++ // Step 1: Process current indexes to find created and modified indexes+ for indexName, currentChunk := range currentChunks.Indexes {+ tableName := extractTableNameFromIndex(currentChunk.ASTNode)+ if tableName == "" {+ continue // Skip if we can't determine the table name+ }++ if previousChunk, exists := previousChunks.Indexes[indexName]; exists {+ // Index exists in both - check if modified by comparing text first+ currentText := getStandaloneIndexText(currentChunk.ASTNode)+ previousText := getStandaloneIndexText(previousChunk.ASTNode)+ if currentText != previousText {+ // Index was modified - use drop and recreate pattern (PostgreSQL standard)+ tableDiff := getOrCreateTableDiff(diff, tableName, affectedTables)+ tableDiff.IndexChanges = append(tableDiff.IndexChanges, &schema.IndexDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: previousChunk.ASTNode,+ })+ tableDiff.IndexChanges = append(tableDiff.IndexChanges, &schema.IndexDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: currentChunk.ASTNode,+ })+ }+ // If text is identical, skip - no changes detected+ } else {+ // New index - store AST node only+ tableDiff := getOrCreateTableDiff(diff, tableName, affectedTables)+ tableDiff.IndexChanges = append(tableDiff.IndexChanges, &schema.IndexDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: currentChunk.ASTNode,+ })+ }+ }++ // Step 2: Process previous indexes to find dropped ones+ for indexName, previousChunk := range previousChunks.Indexes {+ if _, exists := currentChunks.Indexes[indexName]; !exists {+ // Index was dropped - store AST node only+ tableName := extractTableNameFromIndex(previousChunk.ASTNode)+ if tableName == "" {+ continue // Skip if we can't determine the table name+ }++ tableDiff := getOrCreateTableDiff(diff, tableName, affectedTables)+ tableDiff.IndexChanges = append(tableDiff.IndexChanges, &schema.IndexDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: previousChunk.ASTNode,+ })+ }+ }+}++// getStandaloneIndexText returns the text representation of a standalone CREATE INDEX statement for comparison+func getStandaloneIndexText(astNode any) string {+ indexStmt, ok := astNode.(*parser.IndexstmtContext)+ if !ok || indexStmt == nil {+ return ""+ }++ // Get tokens from the parser for precise text extraction with original spacing+ if parser := indexStmt.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := indexStmt.GetStart()+ stop := indexStmt.GetStop()+ if start != nil && stop != nil {+ return tokenStream.GetTextFromTokens(start, stop)+ }+ }+ }++ // Fallback to GetText() if tokens are not available+ return indexStmt.GetText()+}++// extractTableNameFromIndex extracts the table name from a CREATE INDEX statement+func extractTableNameFromIndex(astNode any) string {+ indexStmt, ok := astNode.(*parser.IndexstmtContext)+ if !ok || indexStmt == nil {+ return ""+ }++ // Extract table name from relation_expr in CREATE INDEX ... ON table_name+ if relationExpr := indexStmt.Relation_expr(); relationExpr != nil {+ if qualifiedName := relationExpr.Qualified_name(); qualifiedName != nil {+ // Extract qualified name and return the table name (without schema)+ qualifiedNameParts := pgparser.NormalizePostgreSQLQualifiedName(qualifiedName)+ if len(qualifiedNameParts) > 0 {+ return qualifiedNameParts[len(qualifiedNameParts)-1] // Return the last part (table name)+ }+ }+ }++ return ""+}++// getOrCreateTableDiff finds an existing table diff or creates a new one for the given table+func getOrCreateTableDiff(diff *schema.MetadataDiff, tableName string, affectedTables map[string]*schema.TableDiff) *schema.TableDiff {+ // Check if we already have this table in our map+ if tableDiff, exists := affectedTables[tableName]; exists {+ return tableDiff+ }++ // Create a new table diff for standalone index changes+ // We set Action to ALTER since we're modifying an existing table by adding/removing indexes+ newTableDiff := &schema.TableDiff{+ Action: schema.MetadataDiffActionAlter,+ SchemaName: "public", // Default schema for PostgreSQL+ 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: nil, // No table-level AST changes for standalone indexes+ NewASTNode: nil, // No table-level AST changes for standalone indexes+ ColumnChanges: []*schema.ColumnDiff{},+ IndexChanges: []*schema.IndexDiff{},+ PrimaryKeyChanges: []*schema.PrimaryKeyDiff{},+ UniqueConstraintChanges: []*schema.UniqueConstraintDiff{},+ ForeignKeyChanges: []*schema.ForeignKeyDiff{},+ CheckConstraintChanges: []*schema.CheckConstraintDiff{},+ }++ diff.TableChanges = append(diff.TableChanges, newTableDiff)+ affectedTables[tableName] = newTableDiff+ return newTableDiff+}diff --git a/backend/plugin/schema/pg/standalone_index_test.go b/backend/plugin/schema/pg/standalone_index_test.gonew file mode 100644index 0000000000..5db6b72891--- /dev/null+++ b/backend/plugin/schema/pg/standalone_index_test.go@@ -0,0 +1,381 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/plugin/schema"+)++func TestStandaloneCreateIndexSupport(t *testing.T) {+ tests := []struct {+ name string+ previousUserSDL string+ currentSDL string+ expectedIndexDiffs int+ expectedActions []schema.MetadataDiffAction+ }{+ {+ name: "Create new index",+ previousUserSDL: ``,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE+ );++ CREATE INDEX idx_users_email ON users(email);+ `,+ expectedIndexDiffs: 1,+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ {+ name: "Drop index",+ previousUserSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE+ );++ CREATE INDEX idx_users_email ON users(email);+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE+ );+ `,+ expectedIndexDiffs: 1,+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop},+ },+ {+ name: "Modify index (drop and recreate)",+ previousUserSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE,+ name VARCHAR(100)+ );++ CREATE INDEX idx_users_email ON users(email);+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE,+ name VARCHAR(100)+ );++ CREATE INDEX idx_users_email ON users(email, name);+ `,+ expectedIndexDiffs: 2, // Drop + Create+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionDrop, schema.MetadataDiffActionCreate},+ },+ {+ name: "No changes to index",+ previousUserSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE+ );++ CREATE INDEX idx_users_email ON users(email);+ `,+ currentSDL: `+ CREATE TABLE users (+ id SERIAL PRIMARY KEY,+ email VARCHAR(255) UNIQUE+ );++ CREATE INDEX idx_users_email ON users(email);+ `,+ expectedIndexDiffs: 0,+ expectedActions: []schema.MetadataDiffAction{},+ },+ {+ name: "Complex index with WHERE clause",+ previousUserSDL: `+ CREATE TABLE orders (+ id SERIAL PRIMARY KEY,+ status VARCHAR(50),+ customer_id INTEGER+ );+ `,+ currentSDL: `+ CREATE TABLE orders (+ id SERIAL PRIMARY KEY,+ status VARCHAR(50),+ customer_id INTEGER+ );++ CREATE INDEX idx_orders_active ON orders(customer_id) WHERE status = 'active';+ `,+ expectedIndexDiffs: 1,+ expectedActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Count total index diffs across all table changes+ var allIndexDiffs []*schema.IndexDiff+ for _, tableChange := range diff.TableChanges {+ allIndexDiffs = append(allIndexDiffs, tableChange.IndexChanges...)+ }++ assert.Equal(t, tt.expectedIndexDiffs, len(allIndexDiffs), "Expected %d index diffs, got %d", tt.expectedIndexDiffs, len(allIndexDiffs))++ // Check that the actions match expectations+ var actualActions []schema.MetadataDiffAction+ for _, indexDiff := range allIndexDiffs {+ actualActions = append(actualActions, indexDiff.Action)+ }++ // Handle nil vs empty slice comparison+ if len(tt.expectedActions) == 0 && len(actualActions) == 0 {+ // Both are effectively empty - test passes+ t.Log("Both expected and actual actions are empty")+ } else {+ assert.Equal(t, tt.expectedActions, actualActions, "Expected actions %v, got %v", tt.expectedActions, actualActions)+ }++ // Verify AST nodes are properly set+ for i, indexDiff := range allIndexDiffs {+ switch indexDiff.Action {+ case schema.MetadataDiffActionCreate:+ assert.NotNil(t, indexDiff.NewASTNode, "Index diff %d should have NewASTNode for CREATE action", i)+ assert.Nil(t, indexDiff.OldASTNode, "Index diff %d should not have OldASTNode for CREATE action", i)+ case schema.MetadataDiffActionDrop:+ assert.NotNil(t, indexDiff.OldASTNode, "Index diff %d should have OldASTNode for DROP action", i)+ assert.Nil(t, indexDiff.NewASTNode, "Index diff %d should not have NewASTNode for DROP action", i)+ default:+ t.Errorf("Unexpected action %v for index diff %d", indexDiff.Action, i)+ }+ }+ })+ }+}++func TestGetStandaloneIndexText(t *testing.T) {+ // This test validates that the text extraction works correctly+ sdlText := `CREATE INDEX idx_users_email ON users(email);`++ chunks, err := ChunkSDLText(sdlText)+ require.NoError(t, err)+ require.NotNil(t, chunks)++ // Should have exactly one index chunk+ assert.Equal(t, 1, len(chunks.Indexes))++ // Get the index chunk+ var indexChunk *schema.SDLChunk+ for _, chunk := range chunks.Indexes {+ indexChunk = chunk+ break+ }+ require.NotNil(t, indexChunk)++ // Test text extraction+ text := getStandaloneIndexText(indexChunk.ASTNode)+ assert.Contains(t, text, "CREATE INDEX")+ assert.Contains(t, text, "idx_users_email")+ assert.Contains(t, text, "users(email)")+}++// TestStandaloneIndexIntegrationWithTableChanges tests integration with table changes+func TestStandaloneIndexIntegrationWithTableChanges(t *testing.T) {+ tests := []struct {+ name string+ previousUserSDL string+ currentSDL string+ expectedTableChanges int+ expectedTableName string+ expectedTableAction schema.MetadataDiffAction+ expectedIndexChanges int+ expectedIndexActions []schema.MetadataDiffAction+ }{+ {+ name: "Standalone index on existing table (no table changes)",+ previousUserSDL: `CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));`,+ currentSDL: `+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));+ CREATE INDEX idx_users_email ON users(email);+ `,+ expectedTableChanges: 1, // One table affected by index change+ expectedTableName: "users",+ expectedTableAction: schema.MetadataDiffActionAlter,+ expectedIndexChanges: 1,+ expectedIndexActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ {+ name: "Table change and index change combined",+ previousUserSDL: `+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));+ CREATE INDEX idx_users_email ON users(email);+ `,+ currentSDL: `+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255), name VARCHAR(100));+ CREATE INDEX idx_users_email_name ON users(email, name);+ `,+ expectedTableChanges: 1, // Same table with both column and index changes+ expectedTableName: "users",+ expectedTableAction: schema.MetadataDiffActionAlter,+ expectedIndexChanges: 2, // Create new index + drop old index (different names)+ expectedIndexActions: []schema.MetadataDiffAction{+ schema.MetadataDiffActionCreate, // New index idx_users_email_name+ schema.MetadataDiffActionDrop, // Old index idx_users_email+ },+ },+ {+ name: "Multiple tables with index changes",+ previousUserSDL: `+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));+ CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INTEGER);+ CREATE INDEX idx_users_email ON users(email);+ `,+ currentSDL: `+ CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255));+ CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INTEGER);+ CREATE INDEX idx_users_email ON users(email);+ CREATE INDEX idx_orders_user_id ON orders(user_id);+ `,+ expectedTableChanges: 1, // Only orders table affected by new index+ expectedTableName: "orders",+ expectedTableAction: schema.MetadataDiffActionAlter,+ expectedIndexChanges: 1,+ expectedIndexActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ {+ name: "Index on non-primary schema table", // Testing schema extraction+ previousUserSDL: `+ CREATE SCHEMA test_schema;+ CREATE TABLE test_schema.products (id SERIAL PRIMARY KEY, name VARCHAR(255));+ `,+ currentSDL: `+ CREATE SCHEMA test_schema;+ CREATE TABLE test_schema.products (id SERIAL PRIMARY KEY, name VARCHAR(255));+ CREATE INDEX idx_products_name ON test_schema.products(name);+ `,+ expectedTableChanges: 1,+ expectedTableName: "products", // Table name without schema prefix+ expectedTableAction: schema.MetadataDiffActionAlter,+ expectedIndexChanges: 1,+ expectedIndexActions: []schema.MetadataDiffAction{schema.MetadataDiffActionCreate},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ diff, err := GetSDLDiff(tt.currentSDL, tt.previousUserSDL, nil, nil)+ require.NoError(t, err)+ require.NotNil(t, diff)++ assert.Equal(t, tt.expectedTableChanges, len(diff.TableChanges),+ "Expected %d table changes, got %d", tt.expectedTableChanges, len(diff.TableChanges))++ if tt.expectedTableChanges > 0 {+ // Find the table change we're interested in+ var targetTableChange *schema.TableDiff+ for _, tableChange := range diff.TableChanges {+ if tableChange.TableName == tt.expectedTableName {+ targetTableChange = tableChange+ break+ }+ }++ require.NotNil(t, targetTableChange, "Expected to find table change for %s", tt.expectedTableName)+ assert.Equal(t, tt.expectedTableAction, targetTableChange.Action,+ "Expected table action %v, got %v", tt.expectedTableAction, targetTableChange.Action)++ // Check index changes within this table+ assert.Equal(t, tt.expectedIndexChanges, len(targetTableChange.IndexChanges),+ "Expected %d index changes in table %s, got %d",+ tt.expectedIndexChanges, tt.expectedTableName, len(targetTableChange.IndexChanges))++ // Verify index actions+ var actualIndexActions []schema.MetadataDiffAction+ for _, indexChange := range targetTableChange.IndexChanges {+ actualIndexActions = append(actualIndexActions, indexChange.Action)+ }+ assert.Equal(t, tt.expectedIndexActions, actualIndexActions,+ "Expected index actions %v, got %v", tt.expectedIndexActions, actualIndexActions)++ // Verify AST nodes are properly set+ for i, indexChange := range targetTableChange.IndexChanges {+ switch indexChange.Action {+ case schema.MetadataDiffActionCreate:+ assert.NotNil(t, indexChange.NewASTNode,+ "Index change %d should have NewASTNode for CREATE", i)+ assert.Nil(t, indexChange.OldASTNode,+ "Index change %d should not have OldASTNode for CREATE", i)+ case schema.MetadataDiffActionDrop:+ assert.NotNil(t, indexChange.OldASTNode,+ "Index change %d should have OldASTNode for DROP", i)+ assert.Nil(t, indexChange.NewASTNode,+ "Index change %d should not have NewASTNode for DROP", i)+ default:+ t.Errorf("Unexpected index action %v for change %d", indexChange.Action, i)+ }+ }+ }+ })+ }+}++// TestIndexTableNameExtraction specifically tests the table name extraction logic+func TestIndexTableNameExtraction(t *testing.T) {+ tests := []struct {+ name string+ indexSQL string+ expectedName string+ }{+ {+ name: "Simple table name",+ indexSQL: "CREATE INDEX idx_test ON users(email);",+ expectedName: "users",+ },+ {+ name: "Qualified table name",+ indexSQL: "CREATE INDEX idx_test ON public.users(email);",+ expectedName: "users",+ },+ {+ name: "Custom schema",+ indexSQL: "CREATE INDEX idx_test ON myschema.products(name);",+ expectedName: "products",+ },+ {+ name: "Complex index with WHERE clause",+ indexSQL: "CREATE INDEX idx_active_users ON public.users(email) WHERE active = true;",+ expectedName: "users",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ // Parse the index statement+ chunks, err := ChunkSDLText(tt.indexSQL)+ require.NoError(t, err)+ require.Equal(t, 1, len(chunks.Indexes), "Should have exactly one index")++ // Get the index chunk+ var indexChunk *schema.SDLChunk+ for _, chunk := range chunks.Indexes {+ indexChunk = chunk+ break+ }+ require.NotNil(t, indexChunk)++ // Test table name extraction+ tableName := extractTableNameFromIndex(indexChunk.ASTNode)+ assert.Equal(t, tt.expectedName, tableName,+ "Expected table name '%s', got '%s'", tt.expectedName, tableName)+ })+ }+}diff --git a/backend/plugin/schema/pg/table_constraints_test.go b/backend/plugin/schema/pg/table_constraints_test.goindex 67a26ba67b..3db6e5c44c 100644--- a/backend/plugin/schema/pg/table_constraints_test.go+++ b/backend/plugin/schema/pg/table_constraints_test.go@@ -32,12 +32,12 @@ func TestTableConstraintsSDLDiff(t *testing.T) {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)+ assert.Len(t, tableDiff.PrimaryKeyChanges, 1)+ pkChange := tableDiff.PrimaryKeyChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, pkChange.Action)// AST node should be present for created primary key- assert.NotNil(t, indexChange.NewASTNode)- assert.Nil(t, indexChange.OldASTNode)+ assert.NotNil(t, pkChange.NewASTNode)+ assert.Nil(t, pkChange.OldASTNode)},},{@@ -130,8 +130,11 @@ func TestTableConstraintsSDLDiff(t *testing.T) {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 primary key change+ assert.Len(t, tableDiff.PrimaryKeyChanges, 1)++ // Should have 1 unique constraint change+ assert.Len(t, tableDiff.UniqueConstraintChanges, 1)// Should have 1 foreign key changeassert.Len(t, tableDiff.ForeignKeyChanges, 1)@@ -189,12 +192,12 @@ func TestTableConstraintsSDLDiff(t *testing.T) {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)+ assert.Len(t, tableDiff.UniqueConstraintChanges, 1)+ ukChange := tableDiff.UniqueConstraintChanges[0]+ assert.Equal(t, schema.MetadataDiffActionCreate, ukChange.Action)// AST node should be present for created unique constraint- assert.NotNil(t, indexChange.NewASTNode)- assert.Nil(t, indexChange.OldASTNode)+ assert.NotNil(t, ukChange.NewASTNode)+ assert.Nil(t, ukChange.OldASTNode)},},}