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 PostgreSQL EXCLUDE constraint and fix CREATE INDEX generation in SDL mode (#18153)
rebelice0b408f1aca80
diff --git a/backend/plugin/db/pg/sync.go b/backend/plugin/db/pg/sync.goindex d306acc42c..2b86323e55 100644--- a/backend/plugin/db/pg/sync.go+++ b/backend/plugin/db/pg/sync.go@@ -263,7 +263,8 @@ SELECT nsp.nspname, rel.relname, con.conname, pg_get_constraintdef(con.oid, trueINNER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespaceWHERE contype = 'c' and ` + fmt.Sprintf(`nsp.nspname NOT IN (%s)AND nsp.nspname NOT LIKE 'pg_temp%%'- AND nsp.nspname NOT LIKE 'pg_toast%%'`, pgparser.SystemSchemaWhereClause)+ AND nsp.nspname NOT LIKE 'pg_toast%%'+ ORDER BY nsp.nspname, rel.relname, con.conname`, pgparser.SystemSchemaWhereClause)func getChecks(txn *sql.Tx) (map[db.TableKey][]*storepb.CheckConstraintMetadata, error) {checksMap := make(map[db.TableKey][]*storepb.CheckConstraintMetadata)diff --git a/backend/plugin/schema/differ.go b/backend/plugin/schema/differ.goindex 0989411965..7e182e0980 100644--- a/backend/plugin/schema/differ.go+++ b/backend/plugin/schema/differ.go@@ -99,6 +99,9 @@ type TableDiff struct {// Check constraint changesCheckConstraintChanges []*CheckConstraintDiff+ // EXCLUDE constraint changes (PostgreSQL specific)+ ExcludeConstraintChanges []*ExcludeConstraintDiff+// Partition changesPartitionChanges []*PartitionDiff@@ -144,6 +147,15 @@ type CheckConstraintDiff struct {NewASTNode any // AST node for new check constraint}+// ExcludeConstraintDiff represents changes to an EXCLUDE constraint (PostgreSQL specific).+type ExcludeConstraintDiff struct {+ Action MetadataDiffAction+ OldExcludeConstraint *storepb.ExcludeConstraintMetadata+ NewExcludeConstraint *storepb.ExcludeConstraintMetadata+ OldASTNode any // AST node for old EXCLUDE constraint+ NewASTNode any // AST node for new EXCLUDE constraint+}+// PrimaryKeyDiff represents changes to a primary key constraint.type PrimaryKeyDiff struct {Action MetadataDiffActiondiff --git a/backend/plugin/schema/pg/check_constraint_order_test.go b/backend/plugin/schema/pg/check_constraint_order_test.gonew file mode 100644index 0000000000..22d9b66106--- /dev/null+++ b/backend/plugin/schema/pg/check_constraint_order_test.go@@ -0,0 +1,86 @@+package pg++import (+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/plugin/schema"+)++// TestCheckConstraintOrderStability tests that CHECK constraints maintain consistent order+// when generating SDL multiple times from the same metadata+func TestCheckConstraintOrderStability(t *testing.T) {+ t.Run("single_file", func(t *testing.T) {+ testCheckConstraintOrder(t, false)+ })+ t.Run("multi_file", func(t *testing.T) {+ testCheckConstraintOrder(t, true)+ })+}++func testCheckConstraintOrder(t *testing.T, multiFile bool) {+ // Simulate database metadata with multiple CHECK constraints+ // (similar to the packages_debian_group_distributions table shown in the screenshot)+ dbMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "packages_debian_group_distributions",+ Columns: []*storepb.ColumnMetadata{+ {Name: "id", Type: "bigint", Nullable: false},+ {Name: "suite", Type: "character varying(255)", Nullable: false},+ {Name: "codename", Type: "character varying(255)", Nullable: false},+ {Name: "signed_file", Type: "text", Nullable: true},+ {Name: "description", Type: "character varying(255)", Nullable: true},+ {Name: "origin", Type: "character varying(255)", Nullable: true},+ {Name: "file", Type: "character varying(255)", Nullable: true},+ {Name: "label", Type: "character varying(255)", Nullable: true},+ {Name: "version", Type: "character varying(255)", Nullable: true},+ {Name: "file_signature", Type: "character varying(4096)", Nullable: true},+ },+ CheckConstraints: []*storepb.CheckConstraintMetadata{+ {Name: "check_e7c928a24b", Expression: "(char_length((suite)::text) <= 255)"},+ {Name: "check_590e18405a", Expression: "(char_length((codename)::text) <= 255)"},+ {Name: "check_0007e0bf61", Expression: "(char_length(signed_file) <= 255)"},+ {Name: "check_310ac457b8", Expression: "(char_length((description)::text) <= 255)"},+ {Name: "check_3d6f87fc31", Expression: "(char_length((file_signature)::text) <= 4096)"},+ {Name: "check_3fdadf4a0c", Expression: "(char_length((version)::text) <= 255)"},+ {Name: "check_b057cd840a", Expression: "(char_length((origin)::text) <= 255)"},+ {Name: "check_be5ed8d307", Expression: "(char_length((file)::text) <= 255)"},+ {Name: "check_d3244bfc0b", Expression: "(char_length((label)::text) <= 255)"},+ },+ },+ },+ },+ },+ }++ ctx := schema.GetDefinitionContext{+ SkipBackupSchema: false,+ PrintHeader: false,+ SDLFormat: true,+ MultiFileFormat: multiFile,+ }++ // Generate SDL first time+ sdl1, err := GetDatabaseDefinition(ctx, dbMetadata)+ require.NoError(t, err)+ require.NotEmpty(t, sdl1)++ t.Logf("First SDL generation:\n%s", sdl1)++ // Generate SDL second time from the same metadata+ sdl2, err := GetDatabaseDefinition(ctx, dbMetadata)+ require.NoError(t, err)+ require.NotEmpty(t, sdl2)++ t.Logf("Second SDL generation:\n%s", sdl2)++ // The two SDL outputs should be identical+ require.Equal(t, sdl1, sdl2, "SDL generation should be deterministic - CHECK constraint order should be stable")+}diff --git a/backend/plugin/schema/pg/exclude_index_test.go b/backend/plugin/schema/pg/exclude_index_test.gonew file mode 100644index 0000000000..4de809046d--- /dev/null+++ b/backend/plugin/schema/pg/exclude_index_test.go@@ -0,0 +1,330 @@+package pg++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store/model"+)++// TestExcludeConstraintWithRegularIndexes tests that regular CREATE INDEX statements+// are properly executed alongside EXCLUDE constraints+func TestExcludeConstraintWithRegularIndexes(t *testing.T) {+ // Initial state: empty database+ previousSDL := ""++ // Current SDL: Table with EXCLUDE constraint and regular indexes+ currentSDL := `+-- Table with EXCLUDE constraint for employee shift assignments+CREATE TABLE "public"."employee_shifts" (+ "shift_id" bigserial,+ "employee_id" integer NOT NULL,+ "department_id" integer NOT NULL,+ "shift_start" timestamp(6) with time zone NOT NULL,+ "shift_end" timestamp(6) with time zone NOT NULL,+ "shift_type" character varying(50) DEFAULT 'regular',+ "created_at" timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT "pk_employee_shifts" PRIMARY KEY (shift_id),+ CONSTRAINT "chk_employee_shifts_time" CHECK (shift_end > shift_start),+ -- EXCLUDE constraint: same employee cannot have overlapping shifts+ CONSTRAINT "excl_employee_no_overlap" EXCLUDE USING gist (+ employee_id WITH =,+ tstzrange(shift_start, shift_end) WITH &&+ )+);++CREATE INDEX idx_employee_shifts_employee ON "public"."employee_shifts" (employee_id);+CREATE INDEX idx_employee_shifts_department ON "public"."employee_shifts" (department_id);+CREATE INDEX idx_employee_shifts_time ON "public"."employee_shifts" USING gist (tstzrange(shift_start, shift_end));+CREATE INDEX idx_employee_shifts_type ON "public"."employee_shifts" (shift_type);+`++ previousDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ currentDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)+ currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)++ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Debug: Check what's in the diff+ t.Logf("Number of table changes: %d", len(diff.TableChanges))+ for i, tc := range diff.TableChanges {+ t.Logf("Table %d: %s.%s - IndexChanges: %d", i, tc.SchemaName, tc.TableName, len(tc.IndexChanges))+ for j, ic := range tc.IndexChanges {+ t.Logf(" Index change %d: Action=%v, HasNewAST=%v, HasOldAST=%v",+ j, ic.Action, ic.NewASTNode != nil, ic.OldASTNode != nil)+ }+ }++ // Generate migration DDL+ ddl, err := generateMigration(diff)+ require.NoError(t, err)++ t.Logf("Generated DDL:\n%s", ddl)++ // Verify the migration includes:+ // 1. CREATE TABLE statement+ require.Contains(t, ddl, "CREATE TABLE", "Should create the table")+ require.Contains(t, ddl, "employee_shifts", "Should create employee_shifts table")++ // 2. EXCLUDE constraint in the CREATE TABLE+ require.Contains(t, ddl, "EXCLUDE USING gist", "Should include EXCLUDE constraint")+ require.Contains(t, ddl, "excl_employee_no_overlap", "Should include constraint name")++ // 3. Regular CREATE INDEX statements (THIS IS THE BUG - these might be missing)+ require.Contains(t, ddl, "CREATE INDEX idx_employee_shifts_employee", "Should create idx_employee_shifts_employee index")+ require.Contains(t, ddl, "CREATE INDEX idx_employee_shifts_department", "Should create idx_employee_shifts_department index")+ require.Contains(t, ddl, "CREATE INDEX idx_employee_shifts_time", "Should create idx_employee_shifts_time index")+ require.Contains(t, ddl, "CREATE INDEX idx_employee_shifts_type", "Should create idx_employee_shifts_type index")++ // 4. Should NOT create an index for the EXCLUDE constraint (it's auto-created)+ // The EXCLUDE constraint will create an index, but we shouldn't output a separate CREATE INDEX for it+}++// TestExcludeConstraintIndexNotDuplicated tests that EXCLUDE constraint indexes+// are not output as separate CREATE INDEX statements+func TestExcludeConstraintIndexNotDuplicated(t *testing.T) {+ previousSDL := ""++ currentSDL := `+CREATE TABLE "public"."meetings" (+ "meeting_id" serial PRIMARY KEY,+ "room_id" integer NOT NULL,+ "meeting_start" timestamp NOT NULL,+ "meeting_end" timestamp NOT NULL,+ CONSTRAINT "excl_room_no_overlap" EXCLUDE USING gist (+ room_id WITH =,+ tsrange(meeting_start, meeting_end, '[)') WITH &&+ )+);+`++ // Simulate database state where EXCLUDE constraint has created an index+ currentDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{+ {+ Name: "public",+ Tables: []*storepb.TableMetadata{+ {+ Name: "meetings",+ Columns: []*storepb.ColumnMetadata{+ {Name: "meeting_id", Type: "integer"},+ {Name: "room_id", Type: "integer"},+ {Name: "meeting_start", Type: "timestamp without time zone"},+ {Name: "meeting_end", Type: "timestamp without time zone"},+ },+ ExcludeConstraints: []*storepb.ExcludeConstraintMetadata{+ {+ Name: "excl_room_no_overlap",+ Expression: "EXCLUDE USING gist (room_id WITH =, tsrange(meeting_start, meeting_end, '[)') WITH &&)",+ },+ },+ Indexes: []*storepb.IndexMetadata{+ {+ Name: "excl_room_no_overlap",+ Expressions: []string{+ "room_id",+ "tsrange(meeting_start, meeting_end, '[)')",+ },+ Type: "gist",+ Unique: false,+ Primary: false,+ IsConstraint: true, // This index is created by EXCLUDE constraint+ },+ },+ },+ },+ },+ },+ }++ previousDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)+ currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)++ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)+ require.NoError(t, err)++ ddl, err := generateMigration(diff)+ require.NoError(t, err)++ t.Logf("Generated DDL:\n%s", ddl)++ // Should include EXCLUDE constraint+ require.Contains(t, ddl, "EXCLUDE USING gist", "Should include EXCLUDE constraint")++ // Should NOT include a separate CREATE INDEX for the constraint index+ // The index is automatically created by PostgreSQL when creating the EXCLUDE constraint+ require.NotContains(t, ddl, "CREATE INDEX excl_room_no_overlap", "Should NOT create separate index for EXCLUDE constraint")+}++// TestMaterializedViewWithRegularIndexes tests that regular CREATE INDEX statements+// are properly executed alongside materialized view creation+func TestMaterializedViewWithRegularIndexes(t *testing.T) {+ // Initial state: empty database+ previousSDL := ""++ // Current SDL: Materialized view with regular indexes+ currentSDL := `+CREATE TABLE "public"."orders" (+ "order_id" serial PRIMARY KEY,+ "customer_id" integer NOT NULL,+ "order_date" date NOT NULL,+ "total_amount" numeric(10,2) NOT NULL+);++CREATE MATERIALIZED VIEW "public"."order_summary" AS+SELECT+ customer_id,+ DATE_TRUNC('month', order_date) as order_month,+ COUNT(*) as order_count,+ SUM(total_amount) as total_sales+FROM "public"."orders"+GROUP BY customer_id, DATE_TRUNC('month', order_date);++CREATE INDEX idx_order_summary_customer ON "public"."order_summary" (customer_id);+CREATE INDEX idx_order_summary_month ON "public"."order_summary" (order_month);+CREATE UNIQUE INDEX idx_order_summary_unique ON "public"."order_summary" (customer_id, order_month);+`++ previousDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ currentDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)+ currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)++ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Debug: Check what's in the diff+ t.Logf("Number of materialized view changes: %d", len(diff.MaterializedViewChanges))+ for i, mvc := range diff.MaterializedViewChanges {+ t.Logf("MV %d: %s.%s - Action=%v, IndexChanges: %d", i, mvc.SchemaName, mvc.MaterializedViewName, mvc.Action, len(mvc.IndexChanges))+ for j, ic := range mvc.IndexChanges {+ t.Logf(" Index change %d: Action=%v, HasNewAST=%v, HasOldAST=%v",+ j, ic.Action, ic.NewASTNode != nil, ic.OldASTNode != nil)+ }+ }++ // Generate migration DDL+ ddl, err := generateMigration(diff)+ require.NoError(t, err)++ t.Logf("Generated DDL:\n%s", ddl)++ // Verify the migration includes:+ // 1. CREATE TABLE statement+ require.Contains(t, ddl, "CREATE TABLE", "Should create the orders table")+ require.Contains(t, ddl, "orders", "Should create orders table")++ // 2. CREATE MATERIALIZED VIEW statement+ require.Contains(t, ddl, "CREATE MATERIALIZED VIEW", "Should create materialized view")+ require.Contains(t, ddl, "order_summary", "Should create order_summary materialized view")++ // 3. Regular CREATE INDEX statements (THIS IS THE BUG - these might be missing)+ require.Contains(t, ddl, "CREATE INDEX idx_order_summary_customer", "Should create idx_order_summary_customer index")+ require.Contains(t, ddl, "CREATE INDEX idx_order_summary_month", "Should create idx_order_summary_month index")+ require.Contains(t, ddl, "CREATE UNIQUE INDEX idx_order_summary_unique", "Should create idx_order_summary_unique unique index")+}++// TestIndexCreatedBeforeForeignKey tests that indexes are created before foreign keys that might reference them+// This is important because FK performance benefits from indexes on referenced columns+func TestIndexCreatedBeforeForeignKey(t *testing.T) {+ // Initial state: empty database+ previousSDL := ""++ // Current SDL: Two tables where orders.customer_id references customers.id+ // customers.id has an index that should be created before the FK+ currentSDL := `+CREATE TABLE "public"."customers" (+ "id" serial PRIMARY KEY,+ "email" varchar(255) NOT NULL,+ "name" varchar(100) NOT NULL+);++CREATE INDEX idx_customers_id ON "public"."customers" (id);+CREATE INDEX idx_customers_email ON "public"."customers" (email);++CREATE TABLE "public"."orders" (+ "id" serial PRIMARY KEY,+ "customer_id" integer NOT NULL,+ "order_date" date NOT NULL,+ "total_amount" numeric(10,2) NOT NULL,+ CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES "public"."customers" (id)+);++CREATE INDEX idx_orders_customer ON "public"."orders" (customer_id);+`++ previousDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ currentDBMetadata := &storepb.DatabaseSchemaMetadata{+ Name: "testdb",+ Schemas: []*storepb.SchemaMetadata{},+ }++ previousSchema := model.NewDatabaseMetadata(previousDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)+ currentSchema := model.NewDatabaseMetadata(currentDBMetadata, nil, nil, storepb.Engine_POSTGRES, false)++ diff, err := GetSDLDiff(currentSDL, previousSDL, currentSchema, previousSchema)+ require.NoError(t, err)+ require.NotNil(t, diff)++ // Generate migration DDL+ ddl, err := generateMigration(diff)+ require.NoError(t, err)++ t.Logf("Generated DDL:\n%s", ddl)++ // Verify the migration includes all necessary statements+ require.Contains(t, ddl, "CREATE TABLE", "Should create tables")+ require.Contains(t, ddl, "customers", "Should create customers table")+ require.Contains(t, ddl, "orders", "Should create orders table")++ // Verify indexes are created+ require.Contains(t, ddl, "CREATE INDEX idx_customers_id", "Should create idx_customers_id index")+ require.Contains(t, ddl, "CREATE INDEX idx_customers_email", "Should create idx_customers_email index")+ require.Contains(t, ddl, "CREATE INDEX idx_orders_customer", "Should create idx_orders_customer index")++ // Verify FK is created+ require.Contains(t, ddl, "fk_orders_customer", "Should create foreign key")++ // CRITICAL: Verify that indexes on customers table are created BEFORE the foreign key+ // This is important for FK performance+ idxCustomersPos := strings.Index(ddl, "CREATE INDEX idx_customers_id")+ fkPos := strings.Index(ddl, "fk_orders_customer")++ require.NotEqual(t, -1, idxCustomersPos, "idx_customers_id index should exist")+ require.NotEqual(t, -1, fkPos, "fk_orders_customer should exist")+ require.Less(t, idxCustomersPos, fkPos,+ "Index on referenced column (customers.id) should be created BEFORE the foreign key that references it")+}diff --git a/backend/plugin/schema/pg/generate_migration.go b/backend/plugin/schema/pg/generate_migration.goindex 081e5857ce..23300a72b6 100644--- a/backend/plugin/schema/pg/generate_migration.go+++ b/backend/plugin/schema/pg/generate_migration.go@@ -327,6 +327,20 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {}}}+ // Drop EXCLUDE constraints+ for _, excludeDiff := range tableDiff.ExcludeConstraintChanges {+ if excludeDiff.Action == schema.MetadataDiffActionDrop {+ if excludeDiff.OldExcludeConstraint != nil {+ // Metadata mode: use constraint metadata+ writeDropConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, excludeDiff.OldExcludeConstraint.Name)+ } else if excludeDiff.OldASTNode != nil {+ // AST-only mode: extract from AST node+ if constraintAST, ok := excludeDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {+ writeDropExcludeConstraintFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)+ }+ }+ }+ }// Drop primary key constraintsfor _, pkDiff := range tableDiff.PrimaryKeyChanges {if pkDiff.Action == schema.MetadataDiffActionDrop {@@ -450,6 +464,20 @@ func dropObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) {}}}+ // Drop EXCLUDE constraints+ for _, excludeDiff := range tableDiff.ExcludeConstraintChanges {+ if excludeDiff.Action == schema.MetadataDiffActionDrop {+ if excludeDiff.OldExcludeConstraint != nil {+ // Metadata mode: use constraint metadata+ writeDropConstraint(buf, tableDiff.SchemaName, tableDiff.TableName, excludeDiff.OldExcludeConstraint.Name)+ } else if excludeDiff.OldASTNode != nil {+ // AST-only mode: extract from AST node+ if constraintAST, ok := excludeDiff.OldASTNode.(pgparser.ITableconstraintContext); ok {+ writeDropExcludeConstraintFromAST(buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST)+ }+ }+ }+ }// Drop primary key constraintsfor _, pkDiff := range tableDiff.PrimaryKeyChanges {if pkDiff.Action == schema.MetadataDiffActionDrop {@@ -937,6 +965,30 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error} else {return errors.Errorf("table CREATE action requires either NewTable metadata or NewASTNode for table %s.%s", tableDiff.SchemaName, tableDiff.TableName)}++ // Add indexes for newly created tables immediately after table creation+ // This is necessary because later tables might have FK that reference indexed columns+ for _, indexDiff := range tableDiff.IndexChanges {+ if indexDiff.Action == schema.MetadataDiffActionCreate {+ if indexDiff.NewIndex != nil {+ // Metadata mode: use index metadata+ if indexDiff.NewIndex.IsConstraint {+ // Skip constraint-based indexes (primary key, unique, exclude)+ // They are already included in CREATE TABLE statement+ continue+ }+ writeMigrationIndex(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)+ } else if indexDiff.NewASTNode != nil {+ // AST-only mode: extract from AST node+ if indexAST, ok := indexDiff.NewASTNode.(*pgparser.IndexstmtContext); ok {+ if err := writeCreateIndexFromAST(buf, indexAST); err != nil {+ // If AST extraction fails, log error but continue (non-fatal)+ _, _ = fmt.Fprintf(buf, "-- Error creating index: %v\n", err)+ }+ }+ }+ }+ }}}@@ -1066,6 +1118,30 @@ func createObjectsInOrder(diff *schema.MetadataDiff, buf *strings.Builder) error} else {return errors.Errorf("table CREATE action requires either NewTable metadata or NewASTNode for table %s.%s", tableDiff.SchemaName, tableDiff.TableName)}++ // Add indexes for newly created tables immediately after table creation+ // This is necessary because later tables might have FK that reference indexed columns+ for _, indexDiff := range tableDiff.IndexChanges {+ if indexDiff.Action == schema.MetadataDiffActionCreate {+ if indexDiff.NewIndex != nil {+ // Metadata mode: use index metadata+ if indexDiff.NewIndex.IsConstraint {+ // Skip constraint-based indexes (primary key, unique, exclude)+ // They are already included in CREATE TABLE statement+ continue+ }+ writeMigrationIndex(buf, tableDiff.SchemaName, tableDiff.TableName, indexDiff.NewIndex)+ } else if indexDiff.NewASTNode != nil {+ // AST-only mode: extract from AST node+ if indexAST, ok := indexDiff.NewASTNode.(*pgparser.IndexstmtContext); ok {+ if err := writeCreateIndexFromAST(buf, indexAST); err != nil {+ // If AST extraction fails, log error but continue (non-fatal)+ _, _ = fmt.Fprintf(buf, "-- Error creating index: %v\n", err)+ }+ }+ }+ }+ }case schema.MetadataDiffActionAlter:// Handle ALTER table operations with generateAlterTableWithOptions// Skip foreign keys in the first pass to avoid dependency issues@@ -1457,6 +1533,24 @@ func generateAlterTableWithOptions(tableDiff *schema.TableDiff, includeColumnAdd}}+ // Add EXCLUDE constraints+ for _, excludeDiff := range tableDiff.ExcludeConstraintChanges {+ if excludeDiff.Action == schema.MetadataDiffActionCreate {+ if excludeDiff.NewExcludeConstraint != nil {+ // Metadata mode: use constraint metadata+ writeAddExcludeConstraint(&buf, tableDiff.SchemaName, tableDiff.TableName, excludeDiff.NewExcludeConstraint)+ } else if excludeDiff.NewASTNode != nil {+ // AST-only mode: extract from AST node+ if constraintAST, ok := excludeDiff.NewASTNode.(pgparser.ITableconstraintContext); ok {+ if err := writeAddExcludeConstraintFromAST(&buf, tableDiff.SchemaName, tableDiff.TableName, constraintAST); err != nil {+ // If AST extraction fails, log error but continue (non-fatal)+ _, _ = buf.WriteString(fmt.Sprintf("-- Error adding EXCLUDE constraint: %v\n", err))+ }+ }+ }+ }+ }+// Add unique constraintsfor _, uniqueDiff := range tableDiff.UniqueConstraintChanges {if uniqueDiff.Action == schema.MetadataDiffActionCreate {@@ -4289,6 +4383,67 @@ func writeAddCheckConstraintFromAST(out *strings.Builder, schema, table string,return errors.New("could not extract CHECK constraint from AST node")}+// writeAddExcludeConstraint adds an EXCLUDE constraint using constraint metadata+func writeAddExcludeConstraint(out *strings.Builder, schema, table string, exclude *storepb.ExcludeConstraintMetadata) {+ _, _ = out.WriteString(`ALTER TABLE "`)+ _, _ = out.WriteString(schema)+ _, _ = out.WriteString(`"."`)+ _, _ = out.WriteString(table)+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)+ _, _ = out.WriteString(exclude.Name)+ _, _ = out.WriteString(`" `)+ _, _ = out.WriteString(exclude.Expression) // Already includes "EXCLUDE USING ..."+ _, _ = out.WriteString(`;`)+ _, _ = out.WriteString("\n")+}++// writeAddExcludeConstraintFromAST adds an EXCLUDE constraint using AST node+func writeAddExcludeConstraintFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) error {+ if constraintAST == nil {+ return errors.New("constraint AST node is nil")+ }++ constraintName := extractConstraintNameFromAST(constraintAST)++ // Extract EXCLUDE constraint definition+ if constraintAST.Constraintelem() != nil {+ elem := constraintAST.Constraintelem()+ if elem.EXCLUDE() != nil {+ // Get the full EXCLUDE expression (EXCLUDE USING ...)+ excludeExpr := getTextFromAST(elem)++ // Generate constraint name if not provided+ if constraintName == "" || constraintName == "exclude_constraint" {+ constraintName = fmt.Sprintf("%s_exclude", table)+ }++ _, _ = out.WriteString(`ALTER TABLE "`)+ _, _ = out.WriteString(schema)+ _, _ = out.WriteString(`"."`)+ _, _ = out.WriteString(table)+ _, _ = out.WriteString(`" ADD CONSTRAINT "`)+ _, _ = out.WriteString(constraintName)+ _, _ = out.WriteString(`" `)+ _, _ = out.WriteString(excludeExpr) // Full expression including "EXCLUDE USING ..."+ _, _ = out.WriteString(`;`)+ _, _ = out.WriteString("\n")+ return nil+ }+ }++ return errors.New("could not extract EXCLUDE constraint from AST node")+}++// writeDropExcludeConstraintFromAST drops an EXCLUDE constraint using AST node+func writeDropExcludeConstraintFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) {+ constraintName := extractConstraintNameFromAST(constraintAST)+ if constraintName == "" {+ // If we can't extract a name, use the constraint text as fallback+ constraintName = getTextFromAST(constraintAST)+ }+ writeDropConstraint(out, schema, table, constraintName)+}+// writeAddForeignKeyFromAST adds a foreign key constraint using AST nodefunc writeAddForeignKeyFromAST(out *strings.Builder, schema, table string, constraintAST pgparser.ITableconstraintContext) error {if constraintAST == nil {diff --git a/backend/plugin/schema/pg/get_database_definition.go b/backend/plugin/schema/pg/get_database_definition.goindex 3000fde325..190dfa09ec 100644--- a/backend/plugin/schema/pg/get_database_definition.go+++ b/backend/plugin/schema/pg/get_database_definition.go@@ -1302,7 +1302,7 @@ func writeUniqueKeyConstraintSDL(out io.Writer, index *storepb.IndexMetadata) erreturn nil}-func writeCreateTable(out io.Writer, schema string, tableName string, columns []*storepb.ColumnMetadata, checks []*storepb.CheckConstraintMetadata) error {+func writeCreateTable(out io.Writer, schema string, tableName string, columns []*storepb.ColumnMetadata, checks []*storepb.CheckConstraintMetadata, excludes []*storepb.ExcludeConstraintMetadata) error {if _, err := io.WriteString(out, `CREATE TABLE "`); err != nil {return err}@@ -1375,6 +1375,14 @@ func writeCreateTable(out io.Writer, schema string, tableName string, columns []_, _ = io.WriteString(out, check.Expression)}+ for _, exclude := range excludes {+ _, _ = io.WriteString(out, ",\n ")+ _, _ = io.WriteString(out, `CONSTRAINT "`)+ _, _ = io.WriteString(out, exclude.Name)+ _, _ = io.WriteString(out, `" `)+ _, _ = io.WriteString(out, exclude.Expression) // Already includes "EXCLUDE USING ..."+ }+_, err := io.WriteString(out, "\n)")return err}@@ -1442,7 +1450,7 @@ func splitSequencesByIdentityOrNot(table *storepb.TableMetadata, sequences []*stfunc writeTable(out io.Writer, schema string, table *storepb.TableMetadata, sequences []*storepb.SequenceMetadata) error {generationTypes, identitySequences, nonIdentitySequences := splitSequencesByIdentityOrNot(table, sequences)- if err := writeCreateTable(out, schema, table.Name, table.Columns, table.CheckConstraints); err != nil {+ if err := writeCreateTable(out, schema, table.Name, table.Columns, table.CheckConstraints, table.ExcludeConstraints); err != nil {return err}@@ -2052,7 +2060,7 @@ func writeAttachPartition(out io.Writer, schema string, tableName string, partit}func writePartitionTable(out io.Writer, schema string, columns []*storepb.ColumnMetadata, partition *storepb.TablePartitionMetadata) error {- if err := writeCreateTable(out, schema, partition.Name, columns, partition.CheckConstraints); err != nil {+ if err := writeCreateTable(out, schema, partition.Name, columns, partition.CheckConstraints, partition.ExcludeConstraints); err != nil {return err}@@ -2981,6 +2989,16 @@ func writeTableConstraintsSDL(out io.Writer, table *storepb.TableMetadata) error}}+ // Write EXCLUDE constraints+ for _, exclude := range table.ExcludeConstraints {+ if _, err := io.WriteString(out, ",\n "); err != nil {+ return err+ }+ if err := writeExcludeConstraintSDL(out, exclude); err != nil {+ return err+ }+ }+// Write foreign key constraintsfor _, fk := range table.ForeignKeys {if _, err := io.WriteString(out, ",\n "); err != nil {@@ -3254,6 +3272,23 @@ func writeCheckConstraintSDL(out io.Writer, check *storepb.CheckConstraintMetadareturn nil}+func writeExcludeConstraintSDL(out io.Writer, exclude *storepb.ExcludeConstraintMetadata) error {+ if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {+ return err+ }+ if _, err := io.WriteString(out, exclude.Name); err != nil {+ return err+ }+ if _, err := io.WriteString(out, `" `); err != nil {+ return err+ }+ // Expression already includes "EXCLUDE USING ..." prefix+ if _, err := io.WriteString(out, exclude.Expression); err != nil {+ return err+ }+ return nil+}+// writeForeignKeyConstraintSDL writes a single foreign key constraint SDLfunc writeForeignKeyConstraintSDL(out io.Writer, fk *storepb.ForeignKeyMetadata) error {if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {diff --git a/backend/plugin/schema/pg/get_database_metadata.go b/backend/plugin/schema/pg/get_database_metadata.goindex 69c5886587..757cda2f55 100644--- a/backend/plugin/schema/pg/get_database_metadata.go+++ b/backend/plugin/schema/pg/get_database_metadata.go@@ -1204,6 +1204,37 @@ func (e *metadataExtractor) extractTableConstraint(ctx parser.ITableconstraintCotable.ForeignKeys = []*storepb.ForeignKeyMetadata{}}table.ForeignKeys = append(table.ForeignKeys, fk)++ case constraintElem.EXCLUDE() != nil:+ // EXCLUDE constraint+ exclude := &storepb.ExcludeConstraintMetadata{}+ // Set constraint name+ if constraintName != "" {+ exclude.Name = constraintName+ } else {+ // Generate name if not provided (PostgreSQL auto-generates names)+ excludeIndex := len(table.ExcludeConstraints) + 1+ exclude.Name = fmt.Sprintf("%s_exclude_%d", table.Name, excludeIndex)+ }++ // Extract full EXCLUDE constraint expression from token stream+ // This includes "EXCLUDE USING gist (...)" format+ if parser := ctx.GetParser(); parser != nil {+ if tokenStream := parser.GetTokenStream(); tokenStream != nil {+ start := constraintElem.GetStart()+ stop := constraintElem.GetStop()+ if start != nil && stop != nil {+ rawExpression := tokenStream.GetTextFromTokens(start, stop)+ exclude.Expression = strings.TrimSpace(rawExpression)+ }+ }+ }++ if table.ExcludeConstraints == nil {+ table.ExcludeConstraints = []*storepb.ExcludeConstraintMetadata{}+ }+ table.ExcludeConstraints = append(table.ExcludeConstraints, exclude)+default:// Other constraint types not handled}diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.goindex fe0b445c65..cb15fa5e02 100644--- a/backend/plugin/schema/pg/get_sdl_diff.go+++ b/backend/plugin/schema/pg/get_sdl_diff.go@@ -847,22 +847,24 @@ func processTableChanges(currentChunks, previousChunks *schema.SDLChunks, currencolumnChanges := processColumnChanges(oldASTNode, newASTNode, currentSchema, previousSchema, currentDBSDLChunks, currentChunk.Identifier)foreignKeyChanges := processForeignKeyChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)checkConstraintChanges := processCheckConstraintChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)+ excludeConstraintChanges := processExcludeConstraintChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)primaryKeyChanges := processPrimaryKeyChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)uniqueConstraintChanges := processUniqueConstraintChanges(oldASTNode, newASTNode, currentDBSDLChunks, currentChunk.Identifier)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,- PrimaryKeyChanges: primaryKeyChanges,- UniqueConstraintChanges: uniqueConstraintChanges,+ 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,+ ExcludeConstraintChanges: excludeConstraintChanges,+ PrimaryKeyChanges: primaryKeyChanges,+ UniqueConstraintChanges: uniqueConstraintChanges,}diff.TableChanges = append(diff.TableChanges, tableDiff)}@@ -1399,6 +1401,12 @@ type CheckConstraintDefWithAST struct {ASTNode parser.ITableconstraintContext}+// ExcludeConstraintDefWithAST holds EXCLUDE constraint definition with its AST node for text comparison+type ExcludeConstraintDefWithAST struct {+ Name string+ ASTNode parser.ITableconstraintContext+}+// IndexDefWithAST holds index/unique constraint definition with its AST node for text comparisontype IndexDefWithAST struct {Name string@@ -1541,6 +1549,74 @@ func processCheckConstraintChanges(oldTable, newTable *parser.CreatestmtContext,return checkDiffs}+// processExcludeConstraintChanges analyzes EXCLUDE constraint changes between old and new table definitions+// Following the text-first comparison pattern for performance optimization+func processExcludeConstraintChanges(oldTable, newTable *parser.CreatestmtContext, currentDBSDLChunks *currentDatabaseSDLChunks, tableIdentifier string) []*schema.ExcludeConstraintDiff {+ if oldTable == nil || newTable == nil {+ return []*schema.ExcludeConstraintDiff{}+ }++ // Step 1: Extract all EXCLUDE constraint definitions with their AST nodes for text comparison+ oldExcludeList := extractExcludeConstraintDefinitionsInOrder(oldTable)+ newExcludeList := extractExcludeConstraintDefinitionsInOrder(newTable)++ // Create maps for quick lookup+ oldExcludeMap := make(map[string]*ExcludeConstraintDefWithAST)+ for _, def := range oldExcludeList {+ oldExcludeMap[def.Name] = def+ }+ newExcludeMap := make(map[string]*ExcludeConstraintDefWithAST)+ for _, def := range newExcludeList {+ newExcludeMap[def.Name] = def+ }++ var excludeDiffs []*schema.ExcludeConstraintDiff++ // Step 2: Process current EXCLUDE constraints to find created and modified EXCLUDE constraints+ for _, newExcludeDef := range newExcludeList {+ if oldExcludeDef, exists := oldExcludeMap[newExcludeDef.Name]; exists {+ // EXCLUDE constraint exists in both - check if modified by comparing text first+ currentText := getExcludeConstraintText(newExcludeDef.ASTNode)+ previousText := getExcludeConstraintText(oldExcludeDef.ASTNode)+ if currentText != previousText {+ // Apply constraint-level usability check: skip diff if current constraint matches database metadata SDL+ schemaName, tableName := parseIdentifier(tableIdentifier)+ if currentDBSDLChunks != nil && currentDBSDLChunks.shouldSkipConstraintDiffForUsability(currentText, schemaName, tableName, newExcludeDef.Name) {+ continue+ }+ // EXCLUDE constraint was modified - drop and recreate (PostgreSQL pattern)+ excludeDiffs = append(excludeDiffs, &schema.ExcludeConstraintDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: oldExcludeDef.ASTNode,+ })+ excludeDiffs = append(excludeDiffs, &schema.ExcludeConstraintDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newExcludeDef.ASTNode,+ })+ }+ } else {+ // New EXCLUDE constraint - store AST node only+ excludeDiffs = append(excludeDiffs, &schema.ExcludeConstraintDiff{+ Action: schema.MetadataDiffActionCreate,+ NewASTNode: newExcludeDef.ASTNode,+ })+ }+ }++ // Step 3: Process old EXCLUDE constraints to find dropped ones+ for _, oldExcludeDef := range oldExcludeList {+ if _, exists := newExcludeMap[oldExcludeDef.Name]; !exists {+ // EXCLUDE constraint was dropped - store AST node only+ excludeDiffs = append(excludeDiffs, &schema.ExcludeConstraintDiff{+ Action: schema.MetadataDiffActionDrop,+ OldASTNode: oldExcludeDef.ASTNode,+ })+ }+ }++ return excludeDiffs+}+// processPrimaryKeyChanges analyzes primary key constraint changes between old and new table definitionsfunc processPrimaryKeyChanges(oldTable, newTable *parser.CreatestmtContext, currentDBSDLChunks *currentDatabaseSDLChunks, tableIdentifier string) []*schema.PrimaryKeyDiff {if oldTable == nil || newTable == nil {@@ -1812,6 +1888,54 @@ func extractCheckConstraintDefinitionsInOrder(createStmt *parser.CreatestmtContereturn checkList}+// extractExcludeConstraintDefinitionsInOrder extracts EXCLUDE constraints in their original order with AST nodes+func extractExcludeConstraintDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*ExcludeConstraintDefWithAST {+ var excludeList []*ExcludeConstraintDefWithAST++ if createStmt == nil || createStmt.Opttableelementlist() == nil {+ return excludeList+ }++ tableElementList := createStmt.Opttableelementlist().Tableelementlist()+ if tableElementList == nil {+ return excludeList+ }++ for _, element := range tableElementList.AllTableelement() {+ if element.Tableconstraint() != nil {+ constraint := element.Tableconstraint()+ if constraint.Constraintelem() != nil {+ elem := constraint.Constraintelem()+ if elem.EXCLUDE() != nil {+ // This is an EXCLUDE 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+ }+ }+ excludeList = append(excludeList, &ExcludeConstraintDefWithAST{+ Name: name,+ ASTNode: constraint,+ })+ }+ }+ }+ }++ return excludeList+}+// extractPrimaryKeyDefinitionsWithAST extracts primary key constraints with their AST nodesfunc extractPrimaryKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) map[string]*IndexDefWithAST {pkMap := make(map[string]*IndexDefWithAST)@@ -1905,6 +2029,27 @@ func getCheckConstraintText(constraintAST parser.ITableconstraintContext) stringreturn constraintAST.GetText()}+// getExcludeConstraintText returns the text representation of an EXCLUDE constraint for comparison+func getExcludeConstraintText(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 comparisonfunc getIndexText(constraintAST parser.ITableconstraintContext) string {if constraintAST == nil {@@ -2140,19 +2285,20 @@ func getOrCreateTableDiff(diff *schema.MetadataDiff, tableName string, affectedT// Create a new table diff for standalone index changes// We set Action to ALTER since we're modifying an existing table by adding/removing indexesnewTableDiff := &schema.TableDiff{- Action: schema.MetadataDiffActionAlter,- SchemaName: schemaName,- TableName: tableNameOnly,- 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{},+ Action: schema.MetadataDiffActionAlter,+ SchemaName: schemaName,+ TableName: tableNameOnly,+ 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{},+ ExcludeConstraintChanges: []*schema.ExcludeConstraintDiff{},}diff.TableChanges = append(diff.TableChanges, newTableDiff)@@ -3076,6 +3222,8 @@ func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *parpreviousPKConstraints := make(map[string]*storepb.IndexMetadata)currentUKConstraints := make(map[string]*storepb.IndexMetadata)previousUKConstraints := make(map[string]*storepb.IndexMetadata)+ currentExcludeConstraints := make(map[string]*storepb.ExcludeConstraintMetadata)+ previousExcludeConstraints := make(map[string]*storepb.ExcludeConstraintMetadata)// Build constraint maps from metadatafor _, constraint := range currentTable.CheckConstraints {@@ -3112,12 +3260,20 @@ func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *parpreviousUKConstraints[index.Name] = index}}+ // Build EXCLUDE constraint maps+ for _, constraint := range currentTable.ExcludeConstraints {+ currentExcludeConstraints[constraint.Name] = constraint+ }+ for _, constraint := range previousTable.ExcludeConstraints {+ previousExcludeConstraints[constraint.Name] = constraint+ }// Extract constraint definitions with AST nodes for precise manipulationcurrentCheckDefs := extractCheckConstraintDefinitionsWithAST(createStmt)currentFKDefs := extractForeignKeyDefinitionsWithAST(createStmt)currentPKDefs := extractPrimaryKeyDefinitionsInOrder(createStmt)currentUKDefs := extractUniqueKeyDefinitionsInOrder(createStmt)+ currentExcludeDefs := extractExcludeConstraintDefinitionsWithAST(createStmt)// Phase 1: Handle constraint deletions (reverse order for stability)// Delete check constraints@@ -3168,6 +3324,18 @@ func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *par}}+ // Delete EXCLUDE constraints+ for i := len(currentExcludeDefs) - 1; i >= 0; i-- {+ excludeDef := currentExcludeDefs[i]+ if _, exists := currentExcludeConstraints[excludeDef.Name]; !exists {+ // Constraint was dropped+ err := deleteConstraintFromAST(rewriter, excludeDef.ASTNode, createStmt)+ if err != nil {+ return errors.Wrapf(err, "failed to delete exclude constraint %s", excludeDef.Name)+ }+ }+ }+// Phase 2: Handle constraint modifications// Modify check constraintsfor _, checkDef := range currentCheckDefs {@@ -3229,6 +3397,21 @@ func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *par}}+ // Modify EXCLUDE constraints+ for _, excludeDef := range currentExcludeDefs {+ if currentConstraint, exists := currentExcludeConstraints[excludeDef.Name]; exists {+ if previousConstraint, wasPresent := previousExcludeConstraints[excludeDef.Name]; wasPresent {+ // Check if constraint was modified+ if !excludeConstraintsEqual(currentConstraint, previousConstraint) {+ err := modifyConstraintInAST(rewriter, excludeDef.ASTNode, currentConstraint)+ if err != nil {+ return errors.Wrapf(err, "failed to modify exclude constraint %s", excludeDef.Name)+ }+ }+ }+ }+ }+// Phase 3: Handle constraint additions// Add new check constraintsfor _, currentConstraint := range currentTable.CheckConstraints {@@ -3278,6 +3461,17 @@ func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *par}}+ // Add new EXCLUDE constraints+ for _, currentConstraint := range currentTable.ExcludeConstraints {+ if _, existed := previousExcludeConstraints[currentConstraint.Name]; !existed {+ // New EXCLUDE constraint+ err := addConstraintToAST(rewriter, createStmt, currentConstraint)+ if err != nil {+ return errors.Wrapf(err, "failed to add exclude constraint %s", currentConstraint.Name)+ }+ }+ }+return nil}@@ -3885,6 +4079,8 @@ func modifyConstraintInAST(rewriter *antlr.TokenStreamRewriter, constraintAST pa} else {return errors.New("unsupported index constraint type")}+ case *storepb.ExcludeConstraintMetadata:+ newConstraintSDL = generateExcludeConstraintSDL(constraint)default:return errors.New("unsupported constraint type")}@@ -3916,6 +4112,8 @@ func addConstraintToAST(rewriter *antlr.TokenStreamRewriter, createStmt *parser.} else {return errors.New("unsupported index constraint type")}+ case *storepb.ExcludeConstraintMetadata:+ newConstraintSDL = generateExcludeConstraintSDL(constraint)default:return errors.New("unsupported constraint type")}@@ -3988,6 +4186,23 @@ func generateForeignKeyConstraintSDL(constraint *storepb.ForeignKeyMetadata) strreturn buf.String()}+// generateExcludeConstraintSDL generates SDL text for an EXCLUDE constraint using the existing writeExcludeConstraintSDL function+func generateExcludeConstraintSDL(constraint *storepb.ExcludeConstraintMetadata) string {+ if constraint == nil {+ return ""+ }++ var buf strings.Builder+ err := writeExcludeConstraintSDL(&buf, constraint)+ if err != nil {+ // If there's an error writing to the buffer, return empty string+ // This should rarely happen since we're writing to a strings.Builder+ return ""+ }++ return buf.String()+}+// constraintsEqual compares two check constraint metadata objects for equalityfunc constraintsEqual(a, b *storepb.CheckConstraintMetadata) bool {if a == nil || b == nil {@@ -4045,6 +4260,12 @@ func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) [return extractForeignKeyDefinitionsInOrder(createStmt)}+// extractExcludeConstraintDefinitionsWithAST extracts EXCLUDE constraint definitions with their AST nodes+// Note: This is a wrapper around the existing function with a different name for clarity+func extractExcludeConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*ExcludeConstraintDefWithAST {+ return extractExcludeConstraintDefinitionsInOrder(createStmt)+}+// PrimaryKeyDefWithAST represents a primary key constraint definition with its AST nodetype PrimaryKeyDefWithAST struct {Name string@@ -4215,6 +4436,15 @@ func ukConstraintsEqual(a, b *storepb.IndexMetadata) bool {return true}+// excludeConstraintsEqual compares two EXCLUDE constraint metadata objects for equality+func excludeConstraintsEqual(a, b *storepb.ExcludeConstraintMetadata) bool {+ if a == nil || b == nil {+ return a == b+ }++ return a.Name == b.Name && a.Expression == b.Expression+}+// generatePrimaryKeyConstraintSDL generates SDL text for a primary key constraintfunc generatePrimaryKeyConstraintSDL(constraint *storepb.IndexMetadata) string {if constraint == nil || !constraint.Primary {