Skip to content

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

feat: handle index drift in SDL workflow (#17512)

rebelicec7351a637bc4
diff --git a/backend/plugin/schema/pg/constraint_rewrite_test.go b/backend/plugin/schema/pg/constraint_rewrite_test.go
index 03efeef1e6..2f92024b67 100644
--- a/backend/plugin/schema/pg/constraint_rewrite_test.go
+++ b/backend/plugin/schema/pg/constraint_rewrite_test.go
@@ -215,7 +215,7 @@ func TestConstraintRewriteOperations(t *testing.T) {
expectedSDL: `CREATE TABLE orders (
"id" INTEGER NOT NULL,
"order_number" VARCHAR(50),
- CONSTRAINT "pk_orders" PRIMARY KEY ("id")
+ CONSTRAINT "pk_orders" PRIMARY KEY (id)
);`,
description: "Should add primary key constraint to existing table",
},
@@ -253,7 +253,7 @@ func TestConstraintRewriteOperations(t *testing.T) {
expectedSDL: `CREATE TABLE users (
"id" INTEGER NOT NULL,
"email" VARCHAR(255),
- CONSTRAINT "uk_users_email" UNIQUE ("email")
+ CONSTRAINT "uk_users_email" UNIQUE (email)
);`,
description: "Should add unique constraint to existing table",
},
@@ -301,8 +301,8 @@ func TestConstraintRewriteOperations(t *testing.T) {
"id" INTEGER NOT NULL,
"email" VARCHAR(255),
"phone" VARCHAR(20),
- CONSTRAINT "pk_customers" PRIMARY KEY ("id"),
- CONSTRAINT "uk_customers_email" UNIQUE ("email")
+ CONSTRAINT "pk_customers" PRIMARY KEY (id),
+ CONSTRAINT "uk_customers_email" UNIQUE (email)
);`,
description: "Should add both primary key and unique constraints",
},
@@ -505,7 +505,7 @@ func TestConstraintRewriteOperations(t *testing.T) {
"id" INTEGER NOT NULL,
"tenant_id" INTEGER NOT NULL,
"name" VARCHAR(255),
- CONSTRAINT "pk_composite_new" PRIMARY KEY ("id", "tenant_id")
+ CONSTRAINT "pk_composite_new" PRIMARY KEY (id, tenant_id)
);`,
description: "Should modify primary key constraint to include multiple columns",
},
@@ -554,7 +554,7 @@ func TestConstraintRewriteOperations(t *testing.T) {
"id" INTEGER NOT NULL,
"email" VARCHAR(255),
"username" VARCHAR(100),
- CONSTRAINT "uk_users_email_username" UNIQUE ("email", "username")
+ CONSTRAINT "uk_users_email_username" UNIQUE (email, username)
);`,
description: "Should modify unique constraint to include multiple columns",
},
@@ -658,8 +658,8 @@ func TestConstraintRewriteOperations(t *testing.T) {
"id" INTEGER NOT NULL,
"session_id" VARCHAR(255) NOT NULL,
"timestamp" TIMESTAMP,
- CONSTRAINT "pk_logs_session_timestamp" PRIMARY KEY ("session_id", "timestamp"),
- CONSTRAINT "uk_logs_id" UNIQUE ("id")
+ CONSTRAINT "pk_logs_session_timestamp" PRIMARY KEY (session_id, timestamp),
+ CONSTRAINT "uk_logs_id" UNIQUE (id)
);`,
description: "Should replace primary key constraint and add unique constraint",
},
diff --git a/backend/plugin/schema/pg/get_database_definition.go b/backend/plugin/schema/pg/get_database_definition.go
index 7b45a58cfd..24ee4167e4 100644
--- a/backend/plugin/schema/pg/get_database_definition.go
+++ b/backend/plugin/schema/pg/get_database_definition.go
@@ -1147,15 +1147,9 @@ func writePrimaryKeyConstraintSDL(out io.Writer, index *storepb.IndexMetadata) e
return err
}
}
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
if _, err := io.WriteString(out, expression); err != nil {
return err
}
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
}
if _, err := io.WriteString(out, ")"); err != nil {
return err
@@ -1184,15 +1178,9 @@ func writeUniqueKeyConstraintSDL(out io.Writer, index *storepb.IndexMetadata) er
return err
}
}
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
if _, err := io.WriteString(out, expression); err != nil {
return err
}
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
}
if _, err := io.WriteString(out, ")"); err != nil {
return err
@@ -1581,47 +1569,7 @@ func writePartitionIndex(out io.Writer, schema string, partition *storepb.TableP
}
func writeIndex(out io.Writer, schema string, table string, index *storepb.IndexMetadata) error {
- if index.Unique {
- if _, err := io.WriteString(out, `CREATE UNIQUE INDEX "`); err != nil {
- return err
- }
- } else {
- if _, err := io.WriteString(out, `CREATE INDEX "`); err != nil {
- return err
- }
- }
- if _, err := io.WriteString(out, index.Name); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `" ON ONLY "`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, schema); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `"."`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, table); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `" `); err != nil {
- return err
- }
- if err := writeIndexKeyList(out, index); err != nil {
- return err
- }
- if _, err := io.WriteString(out, ";\n\n"); err != nil {
- return err
- }
-
- if len(index.Comment) > 0 {
- if err := writeIndexComment(out, schema, index); err != nil {
- return err
- }
- }
-
- return nil
+ return writeIndexInternal(out, schema, table, index, true, true)
}
func writeIndexKeyList(out io.Writer, index *storepb.IndexMetadata) error {
@@ -1728,15 +1676,9 @@ func writeUniqueKey(out io.Writer, schema string, table string, index *storepb.I
return err
}
}
- if _, err := io.WriteString(out, "\""); err != nil {
- return err
- }
if _, err := io.WriteString(out, expression); err != nil {
return err
}
- if _, err := io.WriteString(out, "\""); err != nil {
- return err
- }
}
if _, err := io.WriteString(out, ");\n\n"); err != nil {
return err
@@ -1796,15 +1738,9 @@ func writePrimaryKey(out io.Writer, schema string, table string, index *storepb.
return err
}
}
- if _, err := io.WriteString(out, "\""); err != nil {
- return err
- }
if _, err := io.WriteString(out, expression); err != nil {
return err
}
- if _, err := io.WriteString(out, "\""); err != nil {
- return err
- }
}
if _, err := io.WriteString(out, ");\n\n"); err != nil {
return err
@@ -2342,6 +2278,11 @@ func writeIndexesSDL(out io.Writer, schemaName string, table *storepb.TableMetad
}
func writeIndexSDL(out io.Writer, schemaName string, tableName string, index *storepb.IndexMetadata) error {
+ return writeIndexInternal(out, schemaName, tableName, index, true, false)
+}
+
+// writeIndexInternal is the core index writing function with options for different modes
+func writeIndexInternal(out io.Writer, schema string, table string, index *storepb.IndexMetadata, useOnlyClause bool, includeTerminatorAndComment bool) error {
if index.Unique {
if _, err := io.WriteString(out, `CREATE UNIQUE INDEX "`); err != nil {
return err
@@ -2351,60 +2292,60 @@ func writeIndexSDL(out io.Writer, schemaName string, tableName string, index *st
return err
}
}
-
if _, err := io.WriteString(out, index.Name); err != nil {
return err
}
- if _, err := io.WriteString(out, `" ON "`); err != nil {
- return err
+ if useOnlyClause {
+ if _, err := io.WriteString(out, `" ON ONLY "`); err != nil {
+ return err
+ }
+ } else {
+ if _, err := io.WriteString(out, `" ON "`); err != nil {
+ return err
+ }
}
- if _, err := io.WriteString(out, schemaName); err != nil {
+ if _, err := io.WriteString(out, schema); err != nil {
return err
}
-
if _, err := io.WriteString(out, `"."`); err != nil {
return err
}
-
- if _, err := io.WriteString(out, tableName); err != nil {
+ if _, err := io.WriteString(out, table); err != nil {
return err
}
-
- if _, err := io.WriteString(out, `" (`); err != nil {
+ if _, err := io.WriteString(out, `"`); err != nil {
return err
}
- for i, expression := range index.Expressions {
- if i > 0 {
- if _, err := io.WriteString(out, ", "); err != nil {
- return err
- }
- }
-
- if _, err := io.WriteString(out, `"`); err != nil {
+ // Add USING clause for non-btree indexes
+ if index.Type != "" && index.Type != "btree" {
+ if _, err := fmt.Fprintf(out, " USING %s", strings.ToUpper(index.Type)); err != nil {
return err
}
+ }
- if _, err := io.WriteString(out, expression); err != nil {
- return err
- }
+ if _, err := io.WriteString(out, ` `); err != nil {
+ return err
+ }
+ if err := writeIndexKeyList(out, index); err != nil {
+ return err
+ }
- if _, err := io.WriteString(out, `"`); err != nil {
+ if includeTerminatorAndComment {
+ if _, err := io.WriteString(out, ";\n\n"); err != nil {
return err
}
- // Add DESC if this column is marked as descending
- if i < len(index.Descending) && index.Descending[i] {
- if _, err := io.WriteString(out, " DESC"); err != nil {
+ if len(index.Comment) > 0 {
+ if err := writeIndexComment(out, schema, index); err != nil {
return err
}
}
}
- _, err := io.WriteString(out, ")")
- return err
+ return nil
}
func writeViewSDL(out io.Writer, schemaName string, view *storepb.ViewMetadata) error {
diff --git a/backend/plugin/schema/pg/get_database_definition_sdl_test.go b/backend/plugin/schema/pg/get_database_definition_sdl_test.go
index 713328d510..ae52c06168 100644
--- a/backend/plugin/schema/pg/get_database_definition_sdl_test.go
+++ b/backend/plugin/schema/pg/get_database_definition_sdl_test.go
@@ -156,8 +156,8 @@ func TestGetDatabaseDefinitionSDLFormat(t *testing.T) {
"id" SERIAL NOT NULL,
"email" VARCHAR(320) NOT NULL,
"age" INTEGER,
- CONSTRAINT "users_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "users_email_key" UNIQUE ("email"),
+ CONSTRAINT "users_pkey" PRIMARY KEY (id),
+ CONSTRAINT "users_email_key" UNIQUE (email),
CONSTRAINT "users_age_check" CHECK (age >= 0)
);
@@ -210,7 +210,7 @@ func TestGetDatabaseDefinitionSDLFormat(t *testing.T) {
expected: `CREATE TABLE "public"."orders" (
"id" SERIAL NOT NULL,
"user_id" INTEGER NOT NULL,
- CONSTRAINT "orders_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "orders_pkey" PRIMARY KEY (id),
CONSTRAINT "orders_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "public"."users" ("id") ON DELETE CASCADE
);
@@ -332,14 +332,14 @@ CREATE TABLE "public"."products" (
"name" VARCHAR(255) NOT NULL,
"category_id" INTEGER,
"price" DECIMAL(10,2) NOT NULL,
- CONSTRAINT "products_pkey" PRIMARY KEY ("id")
+ CONSTRAINT "products_pkey" PRIMARY KEY (id)
);
-CREATE INDEX "idx_products_name" ON "public"."products" ("name");
+CREATE INDEX "idx_products_name" ON ONLY "public"."products" (name);
-CREATE INDEX "idx_products_category_price" ON "public"."products" ("category_id", "price" DESC);
+CREATE INDEX "idx_products_category_price" ON ONLY "public"."products" (category_id, price DESC);
-CREATE UNIQUE INDEX "idx_products_name_unique" ON "public"."products" ("name");
+CREATE UNIQUE INDEX "idx_products_name_unique" ON ONLY "public"."products" (name);
`,
},
@@ -438,14 +438,14 @@ GROUP BY u.id, u.name`,
"name" VARCHAR(255) NOT NULL,
"email" VARCHAR(320) NOT NULL,
"active" BOOLEAN DEFAULT true NOT NULL,
- CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+ CONSTRAINT "users_pkey" PRIMARY KEY (id)
);
CREATE TABLE "public"."orders" (
"id" SERIAL NOT NULL,
"user_id" INTEGER NOT NULL,
"total" DECIMAL(10,2) NOT NULL,
- CONSTRAINT "orders_pkey" PRIMARY KEY ("id")
+ CONSTRAINT "orders_pkey" PRIMARY KEY (id)
);
CREATE VIEW "public"."active_users" AS SELECT id, name, email
@@ -542,7 +542,7 @@ $$`,
"id" SERIAL NOT NULL,
"name" VARCHAR(255) NOT NULL,
"created_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
- CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+ CONSTRAINT "users_pkey" PRIMARY KEY (id)
);
CREATE FUNCTION "public"."get_user_count"() RETURNS integer
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.go
index e93e565045..b5507043ed 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -1681,6 +1681,12 @@ func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchema
}
}
+ // Process standalone index changes: apply minimal changes to index chunks
+ err := applyStandaloneIndexChangesToChunks(previousChunks, currentSchema, previousSchema)
+ if err != nil {
+ return errors.Wrap(err, "failed to apply standalone index changes")
+ }
+
return nil
}
@@ -2640,3 +2646,241 @@ func generateUniqueKeyConstraintSDL(constraint *storepb.IndexMetadata) string {
}
return buf.String()
}
+
+// extendedIndexMetadata stores index metadata with table and schema context
+type extendedIndexMetadata struct {
+ *storepb.IndexMetadata
+ SchemaName string
+ TableName string
+}
+
+// applyStandaloneIndexChangesToChunks applies minimal changes to standalone CREATE INDEX chunks
+// This handles creation, modification, and deletion of independent index statements
+func applyStandaloneIndexChangesToChunks(previousChunks *schema.SDLChunks, currentSchema, previousSchema *model.DatabaseSchema) error {
+ if currentSchema == nil || previousSchema == nil || previousChunks == nil {
+ return nil
+ }
+
+ // Get index differences by comparing schema metadata
+ currentMetadata := currentSchema.GetMetadata()
+ previousMetadata := previousSchema.GetMetadata()
+ if currentMetadata == nil || previousMetadata == nil {
+ return nil
+ }
+
+ // Build index maps for current and previous schemas
+ currentIndexes := make(map[string]*extendedIndexMetadata)
+ previousIndexes := make(map[string]*extendedIndexMetadata)
+
+ // Collect all standalone indexes from current schema (only non-constraint indexes)
+ for _, schema := range currentMetadata.Schemas {
+ for _, table := range schema.Tables {
+ for _, index := range table.Indexes {
+ // Only include standalone indexes (not constraints like PRIMARY KEY, UNIQUE CONSTRAINT)
+ if !index.IsConstraint && !index.Primary {
+ indexKey := formatIndexKey(schema.Name, index.Name)
+ // Store extended index metadata with table/schema context
+ extendedIndex := &extendedIndexMetadata{
+ IndexMetadata: index,
+ SchemaName: schema.Name,
+ TableName: table.Name,
+ }
+ currentIndexes[indexKey] = extendedIndex
+ }
+ }
+ }
+ }
+
+ // Collect all standalone indexes from previous schema
+ for _, schema := range previousMetadata.Schemas {
+ for _, table := range schema.Tables {
+ for _, index := range table.Indexes {
+ // Only include standalone indexes (not constraints)
+ if !index.IsConstraint && !index.Primary {
+ indexKey := formatIndexKey(schema.Name, index.Name)
+ extendedIndex := &extendedIndexMetadata{
+ IndexMetadata: index,
+ SchemaName: schema.Name,
+ TableName: table.Name,
+ }
+ previousIndexes[indexKey] = extendedIndex
+ }
+ }
+ }
+ }
+
+ // Process index additions: create new index chunks
+ for indexKey, currentIndex := range currentIndexes {
+ if _, exists := previousIndexes[indexKey]; !exists {
+ // New index - create a chunk for it
+ err := createIndexChunk(previousChunks, currentIndex, indexKey)
+ if err != nil {
+ return errors.Wrapf(err, "failed to create index chunk for %s", indexKey)
+ }
+ }
+ }
+
+ // Process index modifications: update existing chunks
+ for indexKey, currentIndex := range currentIndexes {
+ if previousIndex, exists := previousIndexes[indexKey]; exists {
+ // Index exists in both - check if it needs modification
+ err := updateIndexChunkIfNeeded(previousChunks, currentIndex, previousIndex, indexKey)
+ if err != nil {
+ return errors.Wrapf(err, "failed to update index chunk for %s", indexKey)
+ }
+ }
+ }
+
+ // Process index deletions: remove dropped index chunks
+ for indexKey := range previousIndexes {
+ if _, exists := currentIndexes[indexKey]; !exists {
+ // Index was dropped - remove it from chunks
+ deleteIndexChunk(previousChunks, indexKey)
+ }
+ }
+
+ return nil
+}
+
+// formatIndexKey creates a consistent key for index identification
+func formatIndexKey(schemaName, indexName string) string {
+ if schemaName == "" {
+ schemaName = "public"
+ }
+ return schemaName + "." + indexName
+}
+
+// createIndexChunk creates a new CREATE INDEX chunk and adds it to the chunks
+func createIndexChunk(chunks *schema.SDLChunks, extIndex *extendedIndexMetadata, indexKey string) error {
+ if extIndex == nil || extIndex.IndexMetadata == nil || chunks == nil {
+ return nil
+ }
+
+ // Generate SDL text for the index
+ indexSDL := generateCreateIndexSDL(extIndex)
+ if indexSDL == "" {
+ return errors.New("failed to generate SDL for index")
+ }
+
+ // Parse the SDL to get AST node
+ parseResult, err := pgparser.ParsePostgreSQL(indexSDL)
+ if err != nil {
+ return errors.Wrapf(err, "failed to parse generated index SDL: %s", indexSDL)
+ }
+
+ // Extract the CREATE INDEX AST node
+ var indexASTNode *parser.IndexstmtContext
+ antlr.ParseTreeWalkerDefault.Walk(&indexExtractor{
+ result: &indexASTNode,
+ }, parseResult.Tree)
+
+ if indexASTNode == nil {
+ return errors.New("failed to extract CREATE INDEX AST node")
+ }
+
+ // Create and add the chunk
+ chunk := &schema.SDLChunk{
+ Identifier: indexKey,
+ ASTNode: indexASTNode,
+ }
+
+ if chunks.Indexes == nil {
+ chunks.Indexes = make(map[string]*schema.SDLChunk)
+ }
+ chunks.Indexes[indexKey] = chunk
+
+ return nil
+}
+
+// updateIndexChunkIfNeeded updates an existing index chunk if the index definition has changed
+func updateIndexChunkIfNeeded(chunks *schema.SDLChunks, currentIndex, previousIndex *extendedIndexMetadata, indexKey string) error {
+ if currentIndex == nil || previousIndex == nil || chunks == nil {
+ return nil
+ }
+
+ // Check if the index definition has changed
+ if !indexDefinitionsEqual(currentIndex.IndexMetadata, previousIndex.IndexMetadata) {
+ // Index has changed - regenerate the chunk
+ err := createIndexChunk(chunks, currentIndex, indexKey)
+ if err != nil {
+ return errors.Wrapf(err, "failed to recreate index chunk for %s", indexKey)
+ }
+ }
+
+ return nil
+}
+
+// deleteIndexChunk removes an index chunk from the chunks
+func deleteIndexChunk(chunks *schema.SDLChunks, indexKey string) {
+ if chunks != nil && chunks.Indexes != nil {
+ delete(chunks.Indexes, indexKey)
+ }
+}
+
+// indexDefinitionsEqual compares two index definitions to see if they are equivalent
+func indexDefinitionsEqual(index1, index2 *storepb.IndexMetadata) bool {
+ if index1 == nil || index2 == nil {
+ return false
+ }
+
+ // Compare basic properties
+ if index1.Name != index2.Name ||
+ index1.Unique != index2.Unique ||
+ index1.Type != index2.Type ||
+ len(index1.Expressions) != len(index2.Expressions) ||
+ len(index1.Descending) != len(index2.Descending) {
+ return false
+ }
+
+ // Compare expressions
+ for i, expr := range index1.Expressions {
+ if i >= len(index2.Expressions) || expr != index2.Expressions[i] {
+ return false
+ }
+ }
+
+ // Compare descending flags
+ for i, desc := range index1.Descending {
+ if i >= len(index2.Descending) || desc != index2.Descending[i] {
+ return false
+ }
+ }
+
+ // Note: PostgreSQL IndexMetadata doesn't have a Where field in the current schema
+ // Index WHERE clauses are handled differently in the system
+ // For now, we'll consider indexes equal if all other fields match
+
+ return true
+}
+
+// generateCreateIndexSDL generates SDL text for a CREATE INDEX statement using writeIndexSDL
+func generateCreateIndexSDL(extIndex *extendedIndexMetadata) string {
+ if extIndex == nil || extIndex.IndexMetadata == nil {
+ return ""
+ }
+
+ var buf strings.Builder
+ schemaName := extIndex.SchemaName
+ if schemaName == "" {
+ schemaName = "public"
+ }
+
+ // Use the existing writeIndexSDL function from get_database_definition.go
+ if err := writeIndexSDL(&buf, schemaName, extIndex.TableName, extIndex.IndexMetadata); err != nil {
+ return ""
+ }
+
+ return buf.String()
+}
+
+// indexExtractor is a walker to extract CREATE INDEX AST nodes
+type indexExtractor struct {
+ parser.BasePostgreSQLParserListener
+ result **parser.IndexstmtContext
+}
+
+func (e *indexExtractor) EnterIndexstmt(ctx *parser.IndexstmtContext) {
+ if e.result != nil && *e.result == nil {
+ *e.result = ctx
+ }
+}
diff --git a/backend/plugin/schema/pg/index_rewrite_test.go b/backend/plugin/schema/pg/index_rewrite_test.go
new file mode 100644
index 0000000000..06c243ba83
--- /dev/null
+++ b/backend/plugin/schema/pg/index_rewrite_test.go
@@ -0,0 +1,441 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+// TestIndexRewriteOperations tests the ANTLR TokenStreamRewriter functionality
+// for standalone CREATE INDEX operations including add, modify, delete
+func TestIndexRewriteOperations(t *testing.T) {
+ testCases := []struct {
+ name string
+ originalSDL string
+ currentIndexes []*extendedIndexMetadata
+ previousIndexes []*extendedIndexMetadata
+ expectedIndexCount int
+ description string
+ }{
+ {
+ name: "Add new standalone index",
+ originalSDL: `CREATE TABLE users (
+ id INTEGER NOT NULL,
+ email VARCHAR(255) NOT NULL
+);`,
+ currentIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_users_email",
+ Expressions: []string{"email"},
+ Type: "btree",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "users",
+ },
+ },
+ previousIndexes: []*extendedIndexMetadata{},
+ expectedIndexCount: 1,
+ description: "Should add new standalone index to chunks",
+ },
+ {
+ name: "Add unique index",
+ originalSDL: `CREATE TABLE products (
+ id INTEGER NOT NULL,
+ code VARCHAR(50) NOT NULL
+);`,
+ currentIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_products_code_unique",
+ Expressions: []string{"code"},
+ Type: "btree",
+ Unique: true,
+ },
+ SchemaName: "public",
+ TableName: "products",
+ },
+ },
+ previousIndexes: []*extendedIndexMetadata{},
+ expectedIndexCount: 1,
+ description: "Should add new unique index to chunks",
+ },
+ {
+ name: "Drop standalone index",
+ originalSDL: `CREATE TABLE users (
+ id INTEGER NOT NULL,
+ email VARCHAR(255) NOT NULL
+);
+
+CREATE INDEX idx_users_email ON users(email);`,
+ currentIndexes: []*extendedIndexMetadata{},
+ previousIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_users_email",
+ Expressions: []string{"email"},
+ Type: "btree",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "users",
+ },
+ },
+ expectedIndexCount: 0,
+ description: "Should remove standalone index from chunks",
+ },
+ {
+ name: "Modify index (change type)",
+ originalSDL: `CREATE TABLE documents (
+ id INTEGER NOT NULL,
+ content TEXT
+);
+
+CREATE INDEX idx_documents_content ON documents(content);`,
+ currentIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_documents_content",
+ Expressions: []string{"content"},
+ Type: "gin",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "documents",
+ },
+ },
+ previousIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_documents_content",
+ Expressions: []string{"content"},
+ Type: "btree",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "documents",
+ },
+ },
+ expectedIndexCount: 1,
+ description: "Should modify existing index when type changes",
+ },
+ {
+ name: "Multiple index operations",
+ originalSDL: `CREATE TABLE orders (
+ id INTEGER NOT NULL,
+ customer_id INTEGER,
+ total DECIMAL(10,2),
+ status VARCHAR(20)
+);
+
+CREATE INDEX idx_orders_customer ON orders(customer_id);`,
+ currentIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_orders_total",
+ Expressions: []string{"total"},
+ Type: "btree",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "orders",
+ },
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_orders_status",
+ Expressions: []string{"status"},
+ Type: "btree",
+ Unique: true,
+ },
+ SchemaName: "public",
+ TableName: "orders",
+ },
+ },
+ previousIndexes: []*extendedIndexMetadata{
+ {
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_orders_customer",
+ Expressions: []string{"customer_id"},
+ Type: "btree",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "orders",
+ },
+ },
+ expectedIndexCount: 2,
+ description: "Should handle multiple index operations (drop old, add new)",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Parse the original SDL to create chunks
+ chunks, err := ChunkSDLText(tc.originalSDL)
+ require.NoError(t, err, "Failed to parse original SDL")
+
+ // Create index maps for simulation
+ currentIndexes := make(map[string]*extendedIndexMetadata)
+ previousIndexes := make(map[string]*extendedIndexMetadata)
+
+ for _, idx := range tc.currentIndexes {
+ key := formatIndexKey(idx.SchemaName, idx.Name)
+ currentIndexes[key] = idx
+ }
+
+ for _, idx := range tc.previousIndexes {
+ key := formatIndexKey(idx.SchemaName, idx.Name)
+ previousIndexes[key] = idx
+ }
+
+ // Apply index changes directly to test the core logic
+ err = applyStandaloneIndexChangesInternal(chunks, currentIndexes, previousIndexes)
+ require.NoError(t, err, "Failed to apply index changes")
+
+ // Verify the expected number of indexes
+ assert.Len(t, chunks.Indexes, tc.expectedIndexCount,
+ "Expected %d indexes, got %d", tc.expectedIndexCount, len(chunks.Indexes))
+
+ // Verify each current index is present
+ for key, extIdx := range currentIndexes {
+ chunk, exists := chunks.Indexes[key]
+ assert.True(t, exists, "Expected index %s not found in chunks", key)
+ if exists {
+ assert.NotNil(t, chunk.ASTNode, "Index chunk should have AST node")
+ // Verify we can get text from the chunk
+ text := chunk.GetText()
+ assert.NotEmpty(t, text, "Index chunk should have non-empty text")
+ assert.Contains(t, text, "CREATE", "Index text should contain CREATE")
+ assert.Contains(t, text, "INDEX", "Index text should contain INDEX")
+ assert.Contains(t, text, extIdx.Name, "Index text should contain index name")
+ }
+ }
+
+ // Verify previous indexes that shouldn't exist are removed
+ for key := range previousIndexes {
+ if _, stillExists := currentIndexes[key]; !stillExists {
+ _, exists := chunks.Indexes[key]
+ assert.False(t, exists, "Index %s should have been removed from chunks", key)
+ }
+ }
+
+ t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
+ })
+ }
+}
+
+// applyStandaloneIndexChangesInternal is a test helper that directly applies index changes to chunks
+func applyStandaloneIndexChangesInternal(chunks *schema.SDLChunks, currentIndexes, previousIndexes map[string]*extendedIndexMetadata) error {
+ if chunks == nil {
+ return nil
+ }
+
+ // Process index additions: create new index chunks
+ for indexKey, currentIndex := range currentIndexes {
+ if _, exists := previousIndexes[indexKey]; !exists {
+ // New index - create a chunk for it
+ err := createIndexChunk(chunks, currentIndex, indexKey)
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ // Process index modifications: update existing chunks
+ for indexKey, currentIndex := range currentIndexes {
+ if previousIndex, exists := previousIndexes[indexKey]; exists {
+ // Index exists in both - check if it needs modification
+ err := updateIndexChunkIfNeeded(chunks, currentIndex, previousIndex, indexKey)
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ // Process index deletions: remove dropped index chunks
+ for indexKey := range previousIndexes {
+ if _, exists := currentIndexes[indexKey]; !exists {
+ // Index was dropped - remove it from chunks
+ deleteIndexChunk(chunks, indexKey)
+ }
+ }
+
+ return nil
+}
+
+// TestGenerateCreateIndexSDL tests the SDL generation for CREATE INDEX statements
+func TestGenerateCreateIndexSDL(t *testing.T) {
+ testCases := []struct {
+ name string
+ extIndex *extendedIndexMetadata
+ expectedSDL string
+ }{
+ {
+ name: "Simple btree index",
+ extIndex: &extendedIndexMetadata{
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_users_email",
+ Expressions: []string{"email"},
+ Type: "btree",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "users",
+ },
+ expectedSDL: `CREATE INDEX "idx_users_email" ON ONLY "public"."users" (email)`,
+ },
+ {
+ name: "Unique index",
+ extIndex: &extendedIndexMetadata{
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_products_code",
+ Expressions: []string{"code"},
+ Type: "btree",
+ Unique: true,
+ },
+ SchemaName: "public",
+ TableName: "products",
+ },
+ expectedSDL: `CREATE UNIQUE INDEX "idx_products_code" ON ONLY "public"."products" (code)`,
+ },
+ {
+ name: "GIN index",
+ extIndex: &extendedIndexMetadata{
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_documents_content",
+ Expressions: []string{"content"},
+ Type: "gin",
+ Unique: false,
+ },
+ SchemaName: "public",
+ TableName: "documents",
+ },
+ expectedSDL: `CREATE INDEX "idx_documents_content" ON ONLY "public"."documents" USING GIN (content)`,
+ },
+ {
+ name: "Multi-column index with DESC",
+ extIndex: &extendedIndexMetadata{
+ IndexMetadata: &storepb.IndexMetadata{
+ Name: "idx_orders_complex",
+ Expressions: []string{"customer_id", "created_at", "total"},
+ Type: "btree",
+ Unique: false,
+ Descending: []bool{false, true, false},
+ },
+ SchemaName: "public",
+ TableName: "orders",
+ },
+ expectedSDL: `CREATE INDEX "idx_orders_complex" ON ONLY "public"."orders" (customer_id, created_at DESC, total)`,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ result := generateCreateIndexSDL(tc.extIndex)
+ assert.Equal(t, tc.expectedSDL, result)
+ })
+ }
+}
+
+// TestIndexDefinitionsEqual tests the index comparison logic
+func TestIndexDefinitionsEqual(t *testing.T) {
+ testCases := []struct {
+ name string
+ index1 *storepb.IndexMetadata
+ index2 *storepb.IndexMetadata
+ expected bool
+ }{
+ {
+ name: "Identical indexes",
+ index1: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ index2: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ expected: true,
+ },
+ {
+ name: "Different names",
+ index1: &storepb.IndexMetadata{
+ Name: "idx_test1",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ index2: &storepb.IndexMetadata{
+ Name: "idx_test2",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ expected: false,
+ },
+ {
+ name: "Different types",
+ index1: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ index2: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "gin",
+ Unique: false,
+ },
+ expected: false,
+ },
+ {
+ name: "Different uniqueness",
+ index1: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ index2: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: true,
+ },
+ expected: false,
+ },
+ {
+ name: "Different expressions",
+ index1: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col1"},
+ Type: "btree",
+ Unique: false,
+ },
+ index2: &storepb.IndexMetadata{
+ Name: "idx_test",
+ Expressions: []string{"col2"},
+ Type: "btree",
+ Unique: false,
+ },
+ expected: false,
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ result := indexDefinitionsEqual(tc.index1, tc.index2)
+ assert.Equal(t, tc.expected, result)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go b/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go
index ff3b9d1ae5..4641b28bf6 100644
--- a/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go
+++ b/backend/plugin/schema/pg/sdl_validation_testcontainer_test.go
@@ -108,7 +108,7 @@ CREATE TABLE "public"."audit" (
ALTER SEQUENCE "public"."audit_id_seq" OWNED BY "public"."audit"."id";
-ALTER TABLE ONLY "public"."audit" ADD CONSTRAINT "audit_pkey" PRIMARY KEY ("id");
+ALTER TABLE ONLY "public"."audit" ADD CONSTRAINT "audit_pkey" PRIMARY KEY (id);
CREATE INDEX "idx_audit_changed_at" ON ONLY "public"."audit" (changed_at);
@@ -121,7 +121,7 @@ CREATE TABLE "public"."department" (
"dept_name" text NOT NULL
);
-ALTER TABLE ONLY "public"."department" ADD CONSTRAINT "department_pkey" PRIMARY KEY ("dept_no");
+ALTER TABLE ONLY "public"."department" ADD CONSTRAINT "department_pkey" PRIMARY KEY (dept_no);
ALTER TABLE ONLY "public"."department" ADD CONSTRAINT "department_dept_name_key" UNIQUE ("dept_name");
@@ -132,7 +132,7 @@ CREATE TABLE "public"."dept_emp" (
"to_date" date NOT NULL
);
-ALTER TABLE ONLY "public"."dept_emp" ADD CONSTRAINT "dept_emp_pkey" PRIMARY KEY ("emp_no", "dept_no");
+ALTER TABLE ONLY "public"."dept_emp" ADD CONSTRAINT "dept_emp_pkey" PRIMARY KEY (emp_no, dept_no);
CREATE TABLE "public"."dept_manager" (
"emp_no" integer NOT NULL,
@@ -141,7 +141,7 @@ CREATE TABLE "public"."dept_manager" (
"to_date" date NOT NULL
);
-ALTER TABLE ONLY "public"."dept_manager" ADD CONSTRAINT "dept_manager_pkey" PRIMARY KEY ("emp_no", "dept_no");
+ALTER TABLE ONLY "public"."dept_manager" ADD CONSTRAINT "dept_manager_pkey" PRIMARY KEY (emp_no, dept_no);
CREATE SEQUENCE "public"."employee_emp_no_seq"
AS integer
@@ -163,7 +163,7 @@ CREATE TABLE "public"."employee" (
ALTER SEQUENCE "public"."employee_emp_no_seq" OWNED BY "public"."employee"."emp_no";
-ALTER TABLE ONLY "public"."employee" ADD CONSTRAINT "employee_pkey" PRIMARY KEY ("emp_no");
+ALTER TABLE ONLY "public"."employee" ADD CONSTRAINT "employee_pkey" PRIMARY KEY (emp_no);
CREATE INDEX "idx_employee_hire_date" ON ONLY "public"."employee" (hire_date);
@@ -197,7 +197,7 @@ CREATE TABLE "public"."salary" (
"to_date" date NOT NULL
);
-ALTER TABLE ONLY "public"."salary" ADD CONSTRAINT "salary_pkey" PRIMARY KEY ("emp_no", "from_date");
+ALTER TABLE ONLY "public"."salary" ADD CONSTRAINT "salary_pkey" PRIMARY KEY (emp_no, from_date);
CREATE INDEX "idx_salary_amount" ON ONLY "public"."salary" (amount);
@@ -208,7 +208,7 @@ CREATE TABLE "public"."title" (
"to_date" date
);
-ALTER TABLE ONLY "public"."title" ADD CONSTRAINT "title_pkey" PRIMARY KEY ("emp_no", "title", "from_date");
+ALTER TABLE ONLY "public"."title" ADD CONSTRAINT "title_pkey" PRIMARY KEY (emp_no, title, from_date);
CREATE VIEW "public"."dept_emp_latest_date" AS
SELECT emp_no,