Skip to content

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

feat: handle table constraint drift in SDL workflow (#17511)

rebelice788f0655e5a8
diff --git a/backend/plugin/schema/pg/column_rewrite_test.go b/backend/plugin/schema/pg/column_rewrite_test.go
index 2ea788da4c..2365a2418f 100644
--- a/backend/plugin/schema/pg/column_rewrite_test.go
+++ b/backend/plugin/schema/pg/column_rewrite_test.go
@@ -315,12 +315,12 @@ func TestColumnRewriteOperations(t *testing.T) {
}
// Apply column changes
- err = applyColumnChangesToChunk(chunk, tc.currentTable, tc.previousTable)
+ err = applyTableChangesToChunk(chunk, tc.currentTable, tc.previousTable)
if tc.expectedSDL == "" {
// For cases where we don't specify expected SDL, we just want to ensure no error
- assert.NoError(t, err, "applyColumnChangesToChunk should not return error")
+ assert.NoError(t, err, "applyTableChangesToChunk should not return error")
} else {
- require.NoError(t, err, "applyColumnChangesToChunk failed")
+ require.NoError(t, err, "applyTableChangesToChunk failed")
// Get the modified SDL text by recreating the chunk text
// Since we don't have a direct way to get text from AST, we'll validate the structure instead
@@ -453,7 +453,7 @@ func TestColumnRewriteWithCollation(t *testing.T) {
ASTNode: createTableNode,
}
- err = applyColumnChangesToChunk(chunk, currentTable, previousTable)
+ err = applyTableChangesToChunk(chunk, currentTable, previousTable)
assert.NoError(t, err, "Should handle collation changes without error")
}
diff --git a/backend/plugin/schema/pg/constraint_rewrite_test.go b/backend/plugin/schema/pg/constraint_rewrite_test.go
new file mode 100644
index 0000000000..03efeef1e6
--- /dev/null
+++ b/backend/plugin/schema/pg/constraint_rewrite_test.go
@@ -0,0 +1,771 @@
+package pg
+
+import (
+ "testing"
+
+ "github.com/antlr4-go/antlr/v4"
+ parser "github.com/bytebase/parser/postgresql"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ pgparser "github.com/bytebase/bytebase/backend/plugin/parser/pg"
+ "github.com/bytebase/bytebase/backend/plugin/schema"
+)
+
+// TestConstraintRewriteOperations tests the ANTLR TokenStreamRewriter functionality
+// for constraint operations including add, modify, delete with various edge cases
+func TestConstraintRewriteOperations(t *testing.T) {
+ testCases := []struct {
+ name string
+ originalSDL string
+ currentTable *storepb.TableMetadata
+ previousTable *storepb.TableMetadata
+ expectedSDL string
+ description string
+ }{
+ // Single Check Constraint Add Tests
+ {
+ name: "Add check constraint to table",
+ originalSDL: `CREATE TABLE test (
+ id INTEGER NOT NULL,
+ age INTEGER
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "age", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{
+ {Name: "chk_age_positive", Expression: "age > 0"},
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "age", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{},
+ },
+ expectedSDL: `CREATE TABLE test (
+ "id" INTEGER NOT NULL,
+ "age" INTEGER,
+ CONSTRAINT "chk_age_positive" CHECK (age > 0)
+);`,
+ description: "Should add check constraint to existing table",
+ },
+
+ // Check Constraint Drop Tests
+ {
+ name: "Drop check constraint from table",
+ originalSDL: `CREATE TABLE test (
+ id INTEGER NOT NULL,
+ age INTEGER,
+ CONSTRAINT chk_age_positive CHECK (age > 0)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "age", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{},
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "age", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{
+ {Name: "chk_age_positive", Expression: "age > 0"},
+ },
+ },
+ expectedSDL: `CREATE TABLE test (
+ "id" INTEGER NOT NULL,
+ "age" INTEGER
+);`,
+ description: "Should drop check constraint from table",
+ },
+
+ // Foreign Key Constraint Add Tests
+ {
+ name: "Add foreign key constraint to table",
+ originalSDL: `CREATE TABLE orders (
+ id INTEGER NOT NULL,
+ customer_id INTEGER
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "customer_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "fk_customer",
+ Columns: []string{"customer_id"},
+ ReferencedSchema: "public",
+ ReferencedTable: "customers",
+ ReferencedColumns: []string{"id"},
+ OnDelete: "CASCADE",
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "customer_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{},
+ },
+ expectedSDL: `CREATE TABLE orders (
+ "id" INTEGER NOT NULL,
+ "customer_id" INTEGER,
+ CONSTRAINT "fk_customer" FOREIGN KEY ("customer_id") REFERENCES "customers" ("id") ON DELETE CASCADE
+);`,
+ description: "Should add foreign key constraint to existing table",
+ },
+
+ // Complex Multi-Operation Tests
+ {
+ name: "Add check constraint and foreign key constraint",
+ originalSDL: `CREATE TABLE products (
+ id INTEGER NOT NULL,
+ name VARCHAR(100),
+ price DECIMAL,
+ category_id INTEGER
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "products",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "name", Type: "VARCHAR(100)", Nullable: true},
+ {Name: "price", Type: "DECIMAL", Nullable: true},
+ {Name: "category_id", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{
+ {Name: "chk_price_positive", Expression: "price > 0"},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "fk_category",
+ Columns: []string{"category_id"},
+ ReferencedSchema: "public",
+ ReferencedTable: "categories",
+ ReferencedColumns: []string{"id"},
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "products",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "name", Type: "VARCHAR(100)", Nullable: true},
+ {Name: "price", Type: "DECIMAL", Nullable: true},
+ {Name: "category_id", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{},
+ ForeignKeys: []*storepb.ForeignKeyMetadata{},
+ },
+ expectedSDL: `CREATE TABLE products (
+ "id" INTEGER NOT NULL,
+ "name" VARCHAR(100),
+ "price" DECIMAL,
+ "category_id" INTEGER,
+ CONSTRAINT "chk_price_positive" CHECK (price > 0),
+ CONSTRAINT "fk_category" FOREIGN KEY ("category_id") REFERENCES "categories" ("id")
+);`,
+ description: "Should add both check and foreign key constraints",
+ },
+
+ // Primary Key Constraint Tests
+ {
+ name: "Add primary key constraint to table",
+ originalSDL: `CREATE TABLE orders (
+ id INTEGER NOT NULL,
+ order_number VARCHAR(50)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "order_number", Type: "VARCHAR(50)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_orders",
+ Primary: true,
+ Expressions: []string{"id"},
+ IsConstraint: true,
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "order_number", Type: "VARCHAR(50)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{},
+ },
+ expectedSDL: `CREATE TABLE orders (
+ "id" INTEGER NOT NULL,
+ "order_number" VARCHAR(50),
+ CONSTRAINT "pk_orders" PRIMARY KEY ("id")
+);`,
+ description: "Should add primary key constraint to existing table",
+ },
+
+ // Unique Constraint Tests
+ {
+ name: "Add unique constraint to table",
+ originalSDL: `CREATE TABLE users (
+ id INTEGER NOT NULL,
+ email VARCHAR(255)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "users",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "uk_users_email",
+ Unique: true,
+ Expressions: []string{"email"},
+ IsConstraint: true,
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "users",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{},
+ },
+ expectedSDL: `CREATE TABLE users (
+ "id" INTEGER NOT NULL,
+ "email" VARCHAR(255),
+ CONSTRAINT "uk_users_email" UNIQUE ("email")
+);`,
+ description: "Should add unique constraint to existing table",
+ },
+
+ // Combined Constraint Tests
+ {
+ name: "Add primary key and unique constraints together",
+ originalSDL: `CREATE TABLE customers (
+ id INTEGER NOT NULL,
+ email VARCHAR(255),
+ phone VARCHAR(20)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "customers",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ {Name: "phone", Type: "VARCHAR(20)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_customers",
+ Primary: true,
+ Expressions: []string{"id"},
+ IsConstraint: true,
+ },
+ {
+ Name: "uk_customers_email",
+ Unique: true,
+ Expressions: []string{"email"},
+ IsConstraint: true,
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "customers",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ {Name: "phone", Type: "VARCHAR(20)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{},
+ },
+ expectedSDL: `CREATE TABLE customers (
+ "id" INTEGER NOT NULL,
+ "email" VARCHAR(255),
+ "phone" VARCHAR(20),
+ CONSTRAINT "pk_customers" PRIMARY KEY ("id"),
+ CONSTRAINT "uk_customers_email" UNIQUE ("email")
+);`,
+ description: "Should add both primary key and unique constraints",
+ },
+
+ // Test that FK always includes schema name (even for public schema)
+ {
+ name: "Add foreign key constraint with public schema reference",
+ originalSDL: `CREATE TABLE orders (
+ id INTEGER NOT NULL,
+ customer_id INTEGER
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "customer_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "fk_customer_public",
+ Columns: []string{"customer_id"},
+ ReferencedSchema: "public",
+ ReferencedTable: "customers",
+ ReferencedColumns: []string{"id"},
+ OnDelete: "CASCADE",
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "orders",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "customer_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{},
+ },
+ expectedSDL: `CREATE TABLE orders (
+ "id" INTEGER NOT NULL,
+ "customer_id" INTEGER,
+ CONSTRAINT "fk_customer_public" FOREIGN KEY ("customer_id") REFERENCES "public"."customers" ("id") ON DELETE CASCADE
+);`,
+ description: "Should always include schema name in FK references (even for public schema)",
+ },
+
+ // Drop Constraint Tests
+ {
+ name: "Drop primary key constraint from table",
+ originalSDL: `CREATE TABLE users (
+ id INTEGER NOT NULL,
+ email VARCHAR(255),
+ CONSTRAINT pk_users PRIMARY KEY (id)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "users",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{},
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "users",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_users",
+ Primary: true,
+ Expressions: []string{"id"},
+ IsConstraint: true,
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE users (
+ "id" INTEGER NOT NULL,
+ "email" VARCHAR(255)
+);`,
+ description: "Should drop primary key constraint from table",
+ },
+
+ {
+ name: "Drop unique constraint from table",
+ originalSDL: `CREATE TABLE products (
+ id INTEGER NOT NULL,
+ code VARCHAR(50),
+ CONSTRAINT uk_products_code UNIQUE (code)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "products",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "code", Type: "VARCHAR(50)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{},
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "products",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "code", Type: "VARCHAR(50)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "uk_products_code",
+ Unique: true,
+ Expressions: []string{"code"},
+ IsConstraint: true,
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE products (
+ "id" INTEGER NOT NULL,
+ "code" VARCHAR(50)
+);`,
+ description: "Should drop unique constraint from table",
+ },
+
+ {
+ name: "Drop foreign key constraint from table",
+ originalSDL: `CREATE TABLE order_items (
+ id INTEGER NOT NULL,
+ order_id INTEGER,
+ CONSTRAINT fk_order_items_order FOREIGN KEY (order_id) REFERENCES "public"."orders" (id)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "order_items",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "order_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{},
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "order_items",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "order_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "fk_order_items_order",
+ Columns: []string{"order_id"},
+ ReferencedSchema: "public",
+ ReferencedTable: "orders",
+ ReferencedColumns: []string{"id"},
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE order_items (
+ "id" INTEGER NOT NULL,
+ "order_id" INTEGER
+);`,
+ description: "Should drop foreign key constraint from table",
+ },
+
+ // Modify Constraint Tests
+ {
+ name: "Modify primary key constraint (change columns)",
+ originalSDL: `CREATE TABLE composite_pk (
+ id INTEGER NOT NULL,
+ tenant_id INTEGER NOT NULL,
+ name VARCHAR(255),
+ CONSTRAINT pk_composite_old PRIMARY KEY (id)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "composite_pk",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "tenant_id", Type: "INTEGER", Nullable: false},
+ {Name: "name", Type: "VARCHAR(255)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_composite_new",
+ Primary: true,
+ Expressions: []string{"id", "tenant_id"},
+ IsConstraint: true,
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "composite_pk",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "tenant_id", Type: "INTEGER", Nullable: false},
+ {Name: "name", Type: "VARCHAR(255)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_composite_old",
+ Primary: true,
+ Expressions: []string{"id"},
+ IsConstraint: true,
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE composite_pk (
+ "id" INTEGER NOT NULL,
+ "tenant_id" INTEGER NOT NULL,
+ "name" VARCHAR(255),
+ CONSTRAINT "pk_composite_new" PRIMARY KEY ("id", "tenant_id")
+);`,
+ description: "Should modify primary key constraint to include multiple columns",
+ },
+
+ {
+ name: "Modify unique constraint (change columns)",
+ originalSDL: `CREATE TABLE users_unique (
+ id INTEGER NOT NULL,
+ email VARCHAR(255),
+ username VARCHAR(100),
+ CONSTRAINT uk_users_email_only UNIQUE (email)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "users_unique",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ {Name: "username", Type: "VARCHAR(100)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "uk_users_email_username",
+ Unique: true,
+ Expressions: []string{"email", "username"},
+ IsConstraint: true,
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "users_unique",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "email", Type: "VARCHAR(255)", Nullable: true},
+ {Name: "username", Type: "VARCHAR(100)", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "uk_users_email_only",
+ Unique: true,
+ Expressions: []string{"email"},
+ IsConstraint: true,
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE users_unique (
+ "id" INTEGER NOT NULL,
+ "email" VARCHAR(255),
+ "username" VARCHAR(100),
+ CONSTRAINT "uk_users_email_username" UNIQUE ("email", "username")
+);`,
+ description: "Should modify unique constraint to include multiple columns",
+ },
+
+ {
+ name: "Modify foreign key constraint (change referenced table)",
+ originalSDL: `CREATE TABLE comments (
+ id INTEGER NOT NULL,
+ author_id INTEGER,
+ CONSTRAINT fk_comments_author FOREIGN KEY (author_id) REFERENCES "public"."users" (id)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "comments",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "author_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "fk_comments_author",
+ Columns: []string{"author_id"},
+ ReferencedSchema: "public",
+ ReferencedTable: "authors",
+ ReferencedColumns: []string{"id"},
+ OnDelete: "SET NULL",
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "comments",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "author_id", Type: "INTEGER", Nullable: true},
+ },
+ ForeignKeys: []*storepb.ForeignKeyMetadata{
+ {
+ Name: "fk_comments_author",
+ Columns: []string{"author_id"},
+ ReferencedSchema: "public",
+ ReferencedTable: "users",
+ ReferencedColumns: []string{"id"},
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE comments (
+ "id" INTEGER NOT NULL,
+ "author_id" INTEGER,
+ CONSTRAINT "fk_comments_author" FOREIGN KEY ("author_id") REFERENCES "public"."authors" ("id") ON DELETE SET NULL
+);`,
+ description: "Should modify foreign key constraint to reference different table and add ON DELETE",
+ },
+
+ // Complex Mixed Operations
+ {
+ name: "Replace primary key and add unique constraint",
+ originalSDL: `CREATE TABLE logs (
+ id INTEGER NOT NULL,
+ session_id VARCHAR(255) NOT NULL,
+ timestamp TIMESTAMP,
+ CONSTRAINT pk_logs_id PRIMARY KEY (id)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "logs",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "session_id", Type: "VARCHAR(255)", Nullable: false},
+ {Name: "timestamp", Type: "TIMESTAMP", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_logs_session_timestamp",
+ Primary: true,
+ Expressions: []string{"session_id", "timestamp"},
+ IsConstraint: true,
+ },
+ {
+ Name: "uk_logs_id",
+ Unique: true,
+ Expressions: []string{"id"},
+ IsConstraint: true,
+ },
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "logs",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "session_id", Type: "VARCHAR(255)", Nullable: false},
+ {Name: "timestamp", Type: "TIMESTAMP", Nullable: true},
+ },
+ Indexes: []*storepb.IndexMetadata{
+ {
+ Name: "pk_logs_id",
+ Primary: true,
+ Expressions: []string{"id"},
+ IsConstraint: true,
+ },
+ },
+ },
+ expectedSDL: `CREATE TABLE logs (
+ "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")
+);`,
+ description: "Should replace primary key constraint and add unique constraint",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Parse the original SDL to create an AST chunk
+ parseResult, err := pgparser.ParsePostgreSQL(tc.originalSDL)
+ require.NoError(t, err, "Failed to parse original SDL")
+
+ // Extract the CREATE TABLE AST node
+ var createTableNode *parser.CreatestmtContext
+ antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
+ result: &createTableNode,
+ }, parseResult.Tree)
+ require.NotNil(t, createTableNode, "Failed to extract CREATE TABLE AST node")
+
+ // Create a mock chunk
+ chunk := &schema.SDLChunk{
+ Identifier: "public." + tc.currentTable.Name,
+ ASTNode: createTableNode,
+ }
+
+ // Apply constraint changes
+ err = applyTableChangesToChunk(chunk, tc.currentTable, tc.previousTable)
+ if tc.expectedSDL == "" {
+ // For cases where we don't specify expected SDL, we just want to ensure no error
+ assert.NoError(t, err, "applyTableChangesToChunk should not return error")
+ } else {
+ require.NoError(t, err, "applyTableChangesToChunk failed")
+
+ // Get the modified SDL text by recreating the chunk text
+ // Since we don't have a direct way to get text from AST, we'll validate the structure instead
+ // This is a limitation - in a real scenario, we'd want to validate the actual SDL output
+ assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil after modification")
+ t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
+ }
+ })
+ }
+}
+
+// TestConstraintModificationOperations tests constraint modification operations
+func TestConstraintModificationOperations(t *testing.T) {
+ testCases := []struct {
+ name string
+ originalSDL string
+ currentTable *storepb.TableMetadata
+ previousTable *storepb.TableMetadata
+ description string
+ }{
+ {
+ name: "Modify check constraint expression",
+ originalSDL: `CREATE TABLE test (
+ id INTEGER NOT NULL,
+ age INTEGER,
+ CONSTRAINT chk_age_positive CHECK (age > 0)
+);`,
+ currentTable: &storepb.TableMetadata{
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "age", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{
+ {Name: "chk_age_positive", Expression: "age >= 0"},
+ },
+ },
+ previousTable: &storepb.TableMetadata{
+ Name: "test",
+ Columns: []*storepb.ColumnMetadata{
+ {Name: "id", Type: "INTEGER", Nullable: false},
+ {Name: "age", Type: "INTEGER", Nullable: true},
+ },
+ CheckConstraints: []*storepb.CheckConstraintMetadata{
+ {Name: "chk_age_positive", Expression: "age > 0"},
+ },
+ },
+ description: "Should modify check constraint expression",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Parse the original SDL to create an AST chunk
+ parseResult, err := pgparser.ParsePostgreSQL(tc.originalSDL)
+ require.NoError(t, err, "Failed to parse original SDL")
+
+ // Extract the CREATE TABLE AST node
+ var createTableNode *parser.CreatestmtContext
+ antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
+ result: &createTableNode,
+ }, parseResult.Tree)
+ require.NotNil(t, createTableNode, "Failed to extract CREATE TABLE AST node")
+
+ // Create a mock chunk
+ chunk := &schema.SDLChunk{
+ Identifier: "public." + tc.currentTable.Name,
+ ASTNode: createTableNode,
+ }
+
+ // Apply constraint changes
+ err = applyTableChangesToChunk(chunk, tc.currentTable, tc.previousTable)
+ assert.NoError(t, err, "applyTableChangesToChunk should not return error")
+ assert.NotNil(t, chunk.ASTNode, "Chunk AST node should not be nil after modification")
+ t.Logf("Test case '%s' passed: %s", tc.name, tc.description)
+ })
+ }
+}
diff --git a/backend/plugin/schema/pg/get_database_definition.go b/backend/plugin/schema/pg/get_database_definition.go
index d1ff1a0c92..7b45a58cfd 100644
--- a/backend/plugin/schema/pg/get_database_definition.go
+++ b/backend/plugin/schema/pg/get_database_definition.go
@@ -1126,6 +1126,80 @@ func getObjectID(schema string, object string) string {
return buf.String()
}
+// writePrimaryKeyConstraintSDL writes a single primary key constraint SDL
+func writePrimaryKeyConstraintSDL(out io.Writer, index *storepb.IndexMetadata) error {
+ if index == nil || !index.Primary {
+ return errors.New("invalid primary key constraint")
+ }
+
+ if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, index.Name); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `" PRIMARY KEY (`); 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 {
+ 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
+ }
+ return nil
+}
+
+// writeUniqueKeyConstraintSDL writes a single unique key constraint SDL
+func writeUniqueKeyConstraintSDL(out io.Writer, index *storepb.IndexMetadata) error {
+ if index == nil || !index.Unique || index.Primary || !index.IsConstraint {
+ return errors.New("invalid unique key constraint")
+ }
+
+ if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, index.Name); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `" UNIQUE (`); 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 {
+ 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
+ }
+ return nil
+}
+
func writeCreateTable(out io.Writer, schema string, tableName string, columns []*storepb.ColumnMetadata, checks []*storepb.CheckConstraintMetadata) error {
if _, err := io.WriteString(out, `CREATE TABLE "`); err != nil {
return err
@@ -2207,32 +2281,7 @@ func writeTableConstraintsSDL(out io.Writer, table *storepb.TableMetadata) error
if _, err := io.WriteString(out, ",\n "); err != nil {
return err
}
- if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, index.Name); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `" PRIMARY KEY (`); 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 {
- 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 {
+ if err := writePrimaryKeyConstraintSDL(out, index); err != nil {
return err
}
}
@@ -2244,32 +2293,7 @@ func writeTableConstraintsSDL(out io.Writer, table *storepb.TableMetadata) error
if _, err := io.WriteString(out, ",\n "); err != nil {
return err
}
- if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, index.Name); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `" UNIQUE (`); 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 {
- 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 {
+ if err := writeUniqueKeyConstraintSDL(out, index); err != nil {
return err
}
}
@@ -2280,16 +2304,7 @@ func writeTableConstraintsSDL(out io.Writer, table *storepb.TableMetadata) error
if _, err := io.WriteString(out, ",\n "); err != nil {
return err
}
- if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, check.Name); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `" CHECK `); err != nil {
- return err
- }
- if _, err := io.WriteString(out, check.Expression); err != nil {
+ if err := writeCheckConstraintSDL(out, check); err != nil {
return err
}
}
@@ -2299,85 +2314,9 @@ func writeTableConstraintsSDL(out io.Writer, table *storepb.TableMetadata) error
if _, err := io.WriteString(out, ",\n "); err != nil {
return err
}
- if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, fk.Name); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `" FOREIGN KEY (`); err != nil {
- return err
- }
- for i, column := range fk.Columns {
- if i > 0 {
- if _, err := io.WriteString(out, ", "); err != nil {
- return err
- }
- }
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, column); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
- }
- if _, err := io.WriteString(out, ") REFERENCES \""); err != nil {
- return err
- }
- if _, err := io.WriteString(out, fk.ReferencedSchema); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `"."`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, fk.ReferencedTable); err != nil {
- return err
- }
- if _, err := io.WriteString(out, "\" ("); err != nil {
- return err
- }
- for i, column := range fk.ReferencedColumns {
- if i > 0 {
- if _, err := io.WriteString(out, ", "); err != nil {
- return err
- }
- }
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
- if _, err := io.WriteString(out, column); err != nil {
- return err
- }
- if _, err := io.WriteString(out, `"`); err != nil {
- return err
- }
- }
- if _, err := io.WriteString(out, ")"); err != nil {
+ if err := writeForeignKeyConstraintSDL(out, fk); err != nil {
return err
}
-
- // Add ON DELETE clause if specified
- if fk.OnDelete != "" && fk.OnDelete != "NO ACTION" {
- if _, err := io.WriteString(out, " ON DELETE "); err != nil {
- return err
- }
- if _, err := io.WriteString(out, fk.OnDelete); err != nil {
- return err
- }
- }
-
- // Add ON UPDATE clause if specified
- if fk.OnUpdate != "" && fk.OnUpdate != "NO ACTION" {
- if _, err := io.WriteString(out, " ON UPDATE "); err != nil {
- return err
- }
- if _, err := io.WriteString(out, fk.OnUpdate); err != nil {
- return err
- }
- }
}
return nil
@@ -2579,3 +2518,118 @@ func writeSchema(out io.Writer, schema *storepb.SchemaMetadata) error {
_, err := io.WriteString(out, "\n\n")
return err
}
+
+// writeCheckConstraintSDL writes a single check constraint SDL
+func writeCheckConstraintSDL(out io.Writer, check *storepb.CheckConstraintMetadata) error {
+ if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, check.Name); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `" CHECK (`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, check.Expression); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, ")"); err != nil {
+ return err
+ }
+ return nil
+}
+
+// writeForeignKeyConstraintSDL writes a single foreign key constraint SDL
+func writeForeignKeyConstraintSDL(out io.Writer, fk *storepb.ForeignKeyMetadata) error {
+ if _, err := io.WriteString(out, `CONSTRAINT "`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, fk.Name); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `" FOREIGN KEY (`); err != nil {
+ return err
+ }
+ for i, column := range fk.Columns {
+ if i > 0 {
+ if _, err := io.WriteString(out, ", "); err != nil {
+ return err
+ }
+ }
+ if _, err := io.WriteString(out, `"`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, column); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `"`); err != nil {
+ return err
+ }
+ }
+ if _, err := io.WriteString(out, ") REFERENCES "); err != nil {
+ return err
+ }
+
+ // Always add schema qualifier according to project principle
+ if fk.ReferencedSchema != "" {
+ if _, err := io.WriteString(out, `"`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, fk.ReferencedSchema); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `".`); err != nil {
+ return err
+ }
+ }
+
+ if _, err := io.WriteString(out, `"`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, fk.ReferencedTable); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, "\" ("); err != nil {
+ return err
+ }
+ for i, column := range fk.ReferencedColumns {
+ if i > 0 {
+ if _, err := io.WriteString(out, ", "); err != nil {
+ return err
+ }
+ }
+ if _, err := io.WriteString(out, `"`); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, column); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, `"`); err != nil {
+ return err
+ }
+ }
+ if _, err := io.WriteString(out, ")"); err != nil {
+ return err
+ }
+
+ // Add ON DELETE clause if specified
+ if fk.OnDelete != "" && fk.OnDelete != "NO ACTION" {
+ if _, err := io.WriteString(out, " ON DELETE "); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, fk.OnDelete); err != nil {
+ return err
+ }
+ }
+
+ // Add ON UPDATE clause if specified
+ if fk.OnUpdate != "" && fk.OnUpdate != "NO ACTION" {
+ if _, err := io.WriteString(out, " ON UPDATE "); err != nil {
+ return err
+ }
+ if _, err := io.WriteString(out, fk.OnUpdate); err != nil {
+ return err
+ }
+ }
+ return nil
+}
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 00d254b905..713328d510 100644
--- a/backend/plugin/schema/pg/get_database_definition_sdl_test.go
+++ b/backend/plugin/schema/pg/get_database_definition_sdl_test.go
@@ -144,7 +144,7 @@ func TestGetDatabaseDefinitionSDLFormat(t *testing.T) {
CheckConstraints: []*storepb.CheckConstraintMetadata{
{
Name: "users_age_check",
- Expression: "(age >= 0)",
+ Expression: "age >= 0",
},
},
},
diff --git a/backend/plugin/schema/pg/get_sdl_diff.go b/backend/plugin/schema/pg/get_sdl_diff.go
index 58b9e95282..e93e565045 100644
--- a/backend/plugin/schema/pg/get_sdl_diff.go
+++ b/backend/plugin/schema/pg/get_sdl_diff.go
@@ -1659,10 +1659,10 @@ func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchema
// Table exists in both schemas - check for column differences
if existingKey, chunkExists := existingChunkKeys[tableKey]; chunkExists {
if chunk := previousChunks.Tables[existingKey]; chunk != nil {
- // Apply column-level changes to the existing chunk
- err := applyColumnChangesToChunk(chunk, currentTable, previousTable)
+ // Apply both column and constraint changes to the existing chunk using a single rewriter
+ err := applyTableChangesToChunk(chunk, currentTable, previousTable)
if err != nil {
- return errors.Wrapf(err, "failed to apply column changes to table %s", tableKey)
+ return errors.Wrapf(err, "failed to apply table changes to table %s", tableKey)
}
}
}
@@ -1684,8 +1684,8 @@ func applyMinimalChangesToChunks(previousChunks *schema.SDLChunks, currentSchema
return nil
}
-// applyColumnChangesToChunk applies minimal column changes to an existing CREATE TABLE chunk using ANTLR rewrite
-func applyColumnChangesToChunk(chunk *schema.SDLChunk, currentTable, previousTable *storepb.TableMetadata) error {
+// applyTableChangesToChunk applies minimal column and constraint changes to an existing CREATE TABLE chunk using a single ANTLR rewriter
+func applyTableChangesToChunk(chunk *schema.SDLChunk, currentTable, previousTable *storepb.TableMetadata) error {
if chunk == nil || chunk.ASTNode == nil || currentTable == nil || previousTable == nil {
return nil
}
@@ -1695,7 +1695,7 @@ func applyColumnChangesToChunk(chunk *schema.SDLChunk, currentTable, previousTab
return errors.New("chunk AST node is not a CREATE TABLE statement")
}
- // Get the token stream and create a rewriter
+ // Get the token stream and create a single rewriter for both column and constraint changes
ctxParser := createStmt.GetParser()
if ctxParser == nil {
return errors.New("parser not available for AST node")
@@ -1708,6 +1708,45 @@ func applyColumnChangesToChunk(chunk *schema.SDLChunk, currentTable, previousTab
rewriter := antlr.NewTokenStreamRewriter(tokenStream)
+ // Apply column changes using the shared rewriter
+ err := applyColumnChanges(rewriter, createStmt, currentTable, previousTable)
+ if err != nil {
+ return errors.Wrapf(err, "failed to apply column changes")
+ }
+
+ // Apply constraint changes using the same rewriter
+ err = applyConstraintChanges(rewriter, createStmt, currentTable, previousTable)
+ if err != nil {
+ return errors.Wrapf(err, "failed to apply constraint changes")
+ }
+
+ // Apply all changes and update the chunk with a single parse
+ modifiedSQL := rewriter.GetTextDefault()
+
+ // Parse the modified SQL to get the new AST (only once for both column and constraint changes)
+ parseResult, err := pgparser.ParsePostgreSQL(modifiedSQL)
+ if err != nil {
+ return errors.Wrapf(err, "failed to parse modified SQL: %s", modifiedSQL)
+ }
+
+ // Extract the new CREATE TABLE AST node
+ var newCreateTableNode *parser.CreatestmtContext
+ antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
+ result: &newCreateTableNode,
+ }, parseResult.Tree)
+
+ if newCreateTableNode == nil {
+ return errors.New("failed to extract CREATE TABLE AST node from modified text")
+ }
+
+ // Update the chunk with the new AST node
+ chunk.ASTNode = newCreateTableNode
+
+ return nil
+}
+
+// applyColumnChanges applies column changes using the provided rewriter without parsing SQL
+func applyColumnChanges(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, currentTable, previousTable *storepb.TableMetadata) error {
// Create column maps for efficient lookups
currentColumns := make(map[string]*storepb.ColumnMetadata)
previousColumns := make(map[string]*storepb.ColumnMetadata)
@@ -1762,27 +1801,221 @@ func applyColumnChangesToChunk(chunk *schema.SDLChunk, currentTable, previousTab
}
}
- // Apply the changes and update the chunk
- modifiedText := rewriter.GetTextDefault()
+ return nil
+}
- // Parse the modified text to create a new AST node
- parseResult, err := pgparser.ParsePostgreSQL(modifiedText)
- if err != nil {
- return errors.Wrap(err, "failed to parse modified CREATE TABLE statement")
+// applyConstraintChanges applies constraint changes using the provided rewriter without parsing SQL
+func applyConstraintChanges(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, currentTable, previousTable *storepb.TableMetadata) error {
+ // Create constraint maps for efficient lookups
+ currentCheckConstraints := make(map[string]*storepb.CheckConstraintMetadata)
+ previousCheckConstraints := make(map[string]*storepb.CheckConstraintMetadata)
+ currentFKConstraints := make(map[string]*storepb.ForeignKeyMetadata)
+ previousFKConstraints := make(map[string]*storepb.ForeignKeyMetadata)
+ currentPKConstraints := make(map[string]*storepb.IndexMetadata)
+ previousPKConstraints := make(map[string]*storepb.IndexMetadata)
+ currentUKConstraints := make(map[string]*storepb.IndexMetadata)
+ previousUKConstraints := make(map[string]*storepb.IndexMetadata)
+
+ // Build constraint maps from metadata
+ for _, constraint := range currentTable.CheckConstraints {
+ currentCheckConstraints[constraint.Name] = constraint
+ }
+ for _, constraint := range previousTable.CheckConstraints {
+ previousCheckConstraints[constraint.Name] = constraint
+ }
+ for _, constraint := range currentTable.ForeignKeys {
+ currentFKConstraints[constraint.Name] = constraint
+ }
+ for _, constraint := range previousTable.ForeignKeys {
+ previousFKConstraints[constraint.Name] = constraint
+ }
+ // Build primary key constraint maps
+ for _, index := range currentTable.Indexes {
+ if index.Primary {
+ currentPKConstraints[index.Name] = index
+ }
+ }
+ for _, index := range previousTable.Indexes {
+ if index.Primary {
+ previousPKConstraints[index.Name] = index
+ }
+ }
+ // Build unique key constraint maps (unique constraints, not just indexes)
+ for _, index := range currentTable.Indexes {
+ if index.Unique && !index.Primary && index.IsConstraint {
+ currentUKConstraints[index.Name] = index
+ }
+ }
+ for _, index := range previousTable.Indexes {
+ if index.Unique && !index.Primary && index.IsConstraint {
+ previousUKConstraints[index.Name] = index
+ }
}
- // Extract the new CREATE TABLE AST node
- var newCreateTableNode *parser.CreatestmtContext
- antlr.ParseTreeWalkerDefault.Walk(&createTableExtractor{
- result: &newCreateTableNode,
- }, parseResult.Tree)
+ // Extract constraint definitions with AST nodes for precise manipulation
+ currentCheckDefs := extractCheckConstraintDefinitionsWithAST(createStmt)
+ currentFKDefs := extractForeignKeyDefinitionsWithAST(createStmt)
+ currentPKDefs := extractPrimaryKeyDefinitionsInOrder(createStmt)
+ currentUKDefs := extractUniqueKeyDefinitionsInOrder(createStmt)
- if newCreateTableNode == nil {
- return errors.New("failed to extract CREATE TABLE AST node from modified text")
+ // Phase 1: Handle constraint deletions (reverse order for stability)
+ // Delete check constraints
+ for i := len(currentCheckDefs) - 1; i >= 0; i-- {
+ checkDef := currentCheckDefs[i]
+ if _, exists := currentCheckConstraints[checkDef.Name]; !exists {
+ // Constraint was dropped
+ err := deleteConstraintFromAST(rewriter, checkDef.ASTNode, createStmt)
+ if err != nil {
+ return errors.Wrapf(err, "failed to delete check constraint %s", checkDef.Name)
+ }
+ }
}
- // Update the chunk with the new AST node
- chunk.ASTNode = newCreateTableNode
+ // Delete foreign key constraints
+ for i := len(currentFKDefs) - 1; i >= 0; i-- {
+ fkDef := currentFKDefs[i]
+ if _, exists := currentFKConstraints[fkDef.Name]; !exists {
+ // Constraint was dropped
+ err := deleteConstraintFromAST(rewriter, fkDef.ASTNode, createStmt)
+ if err != nil {
+ return errors.Wrapf(err, "failed to delete foreign key constraint %s", fkDef.Name)
+ }
+ }
+ }
+
+ // Delete primary key constraints
+ for i := len(currentPKDefs) - 1; i >= 0; i-- {
+ pkDef := currentPKDefs[i]
+ if _, exists := currentPKConstraints[pkDef.Name]; !exists {
+ // Constraint was dropped
+ err := deleteConstraintFromAST(rewriter, pkDef.ASTNode, createStmt)
+ if err != nil {
+ return errors.Wrapf(err, "failed to delete primary key constraint %s", pkDef.Name)
+ }
+ }
+ }
+
+ // Delete unique key constraints
+ for i := len(currentUKDefs) - 1; i >= 0; i-- {
+ ukDef := currentUKDefs[i]
+ if _, exists := currentUKConstraints[ukDef.Name]; !exists {
+ // Constraint was dropped
+ err := deleteConstraintFromAST(rewriter, ukDef.ASTNode, createStmt)
+ if err != nil {
+ return errors.Wrapf(err, "failed to delete unique key constraint %s", ukDef.Name)
+ }
+ }
+ }
+
+ // Phase 2: Handle constraint modifications
+ // Modify check constraints
+ for _, checkDef := range currentCheckDefs {
+ if currentConstraint, exists := currentCheckConstraints[checkDef.Name]; exists {
+ if previousConstraint, wasPresent := previousCheckConstraints[checkDef.Name]; wasPresent {
+ // Check if constraint was modified by comparing text
+ if !constraintsEqual(currentConstraint, previousConstraint) {
+ err := modifyConstraintInAST(rewriter, checkDef.ASTNode, currentConstraint)
+ if err != nil {
+ return errors.Wrapf(err, "failed to modify check constraint %s", checkDef.Name)
+ }
+ }
+ }
+ }
+ }
+
+ // Modify foreign key constraints
+ for _, fkDef := range currentFKDefs {
+ if currentConstraint, exists := currentFKConstraints[fkDef.Name]; exists {
+ if previousConstraint, wasPresent := previousFKConstraints[fkDef.Name]; wasPresent {
+ // Check if constraint was modified
+ if !fkConstraintsEqual(currentConstraint, previousConstraint) {
+ err := modifyConstraintInAST(rewriter, fkDef.ASTNode, currentConstraint)
+ if err != nil {
+ return errors.Wrapf(err, "failed to modify foreign key constraint %s", fkDef.Name)
+ }
+ }
+ }
+ }
+ }
+
+ // Modify primary key constraints
+ for _, pkDef := range currentPKDefs {
+ if currentConstraint, exists := currentPKConstraints[pkDef.Name]; exists {
+ if previousConstraint, wasPresent := previousPKConstraints[pkDef.Name]; wasPresent {
+ // Check if constraint was modified
+ if !pkConstraintsEqual(currentConstraint, previousConstraint) {
+ err := modifyConstraintInAST(rewriter, pkDef.ASTNode, currentConstraint)
+ if err != nil {
+ return errors.Wrapf(err, "failed to modify primary key constraint %s", pkDef.Name)
+ }
+ }
+ }
+ }
+ }
+
+ // Modify unique key constraints
+ for _, ukDef := range currentUKDefs {
+ if currentConstraint, exists := currentUKConstraints[ukDef.Name]; exists {
+ if previousConstraint, wasPresent := previousUKConstraints[ukDef.Name]; wasPresent {
+ // Check if constraint was modified
+ if !ukConstraintsEqual(currentConstraint, previousConstraint) {
+ err := modifyConstraintInAST(rewriter, ukDef.ASTNode, currentConstraint)
+ if err != nil {
+ return errors.Wrapf(err, "failed to modify unique key constraint %s", ukDef.Name)
+ }
+ }
+ }
+ }
+ }
+
+ // Phase 3: Handle constraint additions
+ // Add new check constraints
+ for _, currentConstraint := range currentTable.CheckConstraints {
+ if _, existed := previousCheckConstraints[currentConstraint.Name]; !existed {
+ // New check constraint
+ err := addConstraintToAST(rewriter, createStmt, currentConstraint)
+ if err != nil {
+ return errors.Wrapf(err, "failed to add check constraint %s", currentConstraint.Name)
+ }
+ }
+ }
+
+ // Add new foreign key constraints
+ for _, currentConstraint := range currentTable.ForeignKeys {
+ if _, existed := previousFKConstraints[currentConstraint.Name]; !existed {
+ // New foreign key constraint
+ err := addConstraintToAST(rewriter, createStmt, currentConstraint)
+ if err != nil {
+ return errors.Wrapf(err, "failed to add foreign key constraint %s", currentConstraint.Name)
+ }
+ }
+ }
+
+ // Add new primary key constraints
+ for _, currentIndex := range currentTable.Indexes {
+ if currentIndex.Primary {
+ if _, existed := previousPKConstraints[currentIndex.Name]; !existed {
+ // New primary key constraint
+ err := addConstraintToAST(rewriter, createStmt, currentIndex)
+ if err != nil {
+ return errors.Wrapf(err, "failed to add primary key constraint %s", currentIndex.Name)
+ }
+ }
+ }
+ }
+
+ // Add new unique key constraints
+ for _, currentIndex := range currentTable.Indexes {
+ if currentIndex.Unique && !currentIndex.Primary && currentIndex.IsConstraint {
+ if _, existed := previousUKConstraints[currentIndex.Name]; !existed {
+ // New unique key constraint
+ err := addConstraintToAST(rewriter, createStmt, currentIndex)
+ if err != nil {
+ return errors.Wrapf(err, "failed to add unique key constraint %s", currentIndex.Name)
+ }
+ }
+ }
+ }
return nil
}
@@ -1959,3 +2192,451 @@ func convertDatabaseSchemaToSDL(dbSchema *model.DatabaseSchema) (string, error)
// Use the existing getSDLFormat function from get_database_definition.go
return getSDLFormat(metadata)
}
+
+// deleteConstraintFromAST removes a constraint definition from the CREATE TABLE statement using token rewriter
+func deleteConstraintFromAST(rewriter *antlr.TokenStreamRewriter, constraintAST parser.ITableconstraintContext, _ *parser.CreatestmtContext) error {
+ if constraintAST == nil || rewriter == nil {
+ return errors.New("constraint AST or rewriter is nil")
+ }
+
+ // Get start and stop tokens for the constraint
+ startToken := constraintAST.GetStart()
+ stopToken := constraintAST.GetStop()
+
+ if startToken == nil || stopToken == nil {
+ return errors.New("unable to get constraint definition tokens")
+ }
+
+ // Strategy: Always try to remove the following comma first
+ // This handles cases where there are more constraints after this one
+ nextCommaIndex := -1
+ for i := stopToken.GetTokenIndex() + 1; i < rewriter.GetTokenStream().Size(); i++ {
+ token := rewriter.GetTokenStream().Get(i)
+ if token.GetTokenType() == parser.PostgreSQLParserCOMMA {
+ nextCommaIndex = i
+ break
+ }
+ // Skip whitespace and comments, but stop at other meaningful tokens
+ if token.GetChannel() == antlr.TokenDefaultChannel {
+ // Found a non-comma token on the default channel, stop searching
+ break
+ }
+ }
+
+ if nextCommaIndex != -1 {
+ // Found a following comma - remove constraint and the comma
+ rewriter.DeleteDefault(startToken.GetTokenIndex(), nextCommaIndex)
+ } else {
+ // No following comma found - this might be the last element
+ // Try to find a preceding comma to remove
+ prevCommaIndex := -1
+ for i := startToken.GetTokenIndex() - 1; i >= 0; i-- {
+ token := rewriter.GetTokenStream().Get(i)
+ if token.GetTokenType() == parser.PostgreSQLParserCOMMA {
+ prevCommaIndex = i
+ break
+ }
+ // Skip whitespace and comments, but stop at other meaningful tokens
+ if token.GetChannel() == antlr.TokenDefaultChannel {
+ break
+ }
+ }
+
+ if prevCommaIndex != -1 {
+ // Found a preceding comma - remove it along with the constraint
+ rewriter.DeleteDefault(prevCommaIndex, stopToken.GetTokenIndex())
+ } else {
+ // No comma found (single constraint case) - just remove the constraint
+ rewriter.DeleteDefault(startToken.GetTokenIndex(), stopToken.GetTokenIndex())
+ }
+ }
+
+ return nil
+}
+
+// modifyConstraintInAST modifies a constraint definition using token rewriter
+func modifyConstraintInAST(rewriter *antlr.TokenStreamRewriter, constraintAST parser.ITableconstraintContext, newConstraint any) error {
+ if constraintAST == nil || rewriter == nil || newConstraint == nil {
+ return errors.New("constraint AST, rewriter, or new constraint is nil")
+ }
+
+ // Get start and stop tokens for the constraint
+ startToken := constraintAST.GetStart()
+ stopToken := constraintAST.GetStop()
+
+ if startToken == nil || stopToken == nil {
+ return errors.New("unable to get constraint definition tokens")
+ }
+
+ // Generate the new constraint SDL
+ var newConstraintSDL string
+ switch constraint := newConstraint.(type) {
+ case *storepb.CheckConstraintMetadata:
+ newConstraintSDL = generateCheckConstraintSDL(constraint)
+ case *storepb.ForeignKeyMetadata:
+ newConstraintSDL = generateForeignKeyConstraintSDL(constraint)
+ case *storepb.IndexMetadata:
+ if constraint.Primary {
+ newConstraintSDL = generatePrimaryKeyConstraintSDL(constraint)
+ } else if constraint.Unique && constraint.IsConstraint {
+ newConstraintSDL = generateUniqueKeyConstraintSDL(constraint)
+ } else {
+ return errors.New("unsupported index constraint type")
+ }
+ default:
+ return errors.New("unsupported constraint type")
+ }
+
+ // Replace the entire constraint definition
+ rewriter.ReplaceDefault(startToken.GetTokenIndex(), stopToken.GetTokenIndex(), newConstraintSDL)
+
+ return nil
+}
+
+// addConstraintToAST adds a new constraint to the CREATE TABLE statement using token rewriter
+func addConstraintToAST(rewriter *antlr.TokenStreamRewriter, createStmt *parser.CreatestmtContext, newConstraint any) error {
+ if rewriter == nil || createStmt == nil || newConstraint == nil {
+ return errors.New("rewriter, create statement, or new constraint is nil")
+ }
+
+ // Generate the new constraint SDL
+ var newConstraintSDL string
+ switch constraint := newConstraint.(type) {
+ case *storepb.CheckConstraintMetadata:
+ newConstraintSDL = generateCheckConstraintSDL(constraint)
+ case *storepb.ForeignKeyMetadata:
+ newConstraintSDL = generateForeignKeyConstraintSDL(constraint)
+ case *storepb.IndexMetadata:
+ if constraint.Primary {
+ newConstraintSDL = generatePrimaryKeyConstraintSDL(constraint)
+ } else if constraint.Unique && constraint.IsConstraint {
+ newConstraintSDL = generateUniqueKeyConstraintSDL(constraint)
+ } else {
+ return errors.New("unsupported index constraint type")
+ }
+ default:
+ return errors.New("unsupported constraint type")
+ }
+
+ // Find the position to insert the constraint
+ // Look for the closing parenthesis of the CREATE TABLE statement
+ optTableElementList := createStmt.Opttableelementlist()
+ if optTableElementList == nil {
+ return errors.New("CREATE TABLE statement has no table element list")
+ }
+
+ tableElementList := optTableElementList.Tableelementlist()
+ if tableElementList == nil {
+ return errors.New("table element list is nil")
+ }
+
+ // Get all table elements to find the last one
+ tableElements := tableElementList.AllTableelement()
+ if len(tableElements) == 0 {
+ return errors.New("no table elements found")
+ }
+
+ // Get the last element (could be a column or constraint)
+ lastElement := tableElements[len(tableElements)-1]
+ stopToken := lastElement.GetStop()
+ if stopToken == nil {
+ return errors.New("unable to get last table element stop token")
+ }
+
+ // Generate constraint definition SDL with leading comma and proper indentation
+ constraintSDL := ",\n " + newConstraintSDL
+
+ // Insert after the last element
+ rewriter.InsertAfterDefault(stopToken.GetTokenIndex(), constraintSDL)
+
+ return nil
+}
+
+// generateCheckConstraintSDL generates SDL text for a check constraint using the existing writeCheckConstraintSDL function
+func generateCheckConstraintSDL(constraint *storepb.CheckConstraintMetadata) string {
+ if constraint == nil {
+ return ""
+ }
+
+ var buf strings.Builder
+ err := writeCheckConstraintSDL(&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()
+}
+
+// generateForeignKeyConstraintSDL generates SDL text for a foreign key constraint using the existing writeForeignKeyConstraintSDL function
+func generateForeignKeyConstraintSDL(constraint *storepb.ForeignKeyMetadata) string {
+ if constraint == nil {
+ return ""
+ }
+
+ var buf strings.Builder
+ err := writeForeignKeyConstraintSDL(&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 equality
+func constraintsEqual(a, b *storepb.CheckConstraintMetadata) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+
+ return a.Name == b.Name && a.Expression == b.Expression
+}
+
+// fkConstraintsEqual compares two foreign key constraint metadata objects for equality
+func fkConstraintsEqual(a, b *storepb.ForeignKeyMetadata) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+
+ // Compare basic properties
+ if a.Name != b.Name ||
+ a.ReferencedSchema != b.ReferencedSchema ||
+ a.ReferencedTable != b.ReferencedTable ||
+ a.OnDelete != b.OnDelete ||
+ a.OnUpdate != b.OnUpdate {
+ return false
+ }
+
+ // Compare columns arrays
+ if len(a.Columns) != len(b.Columns) ||
+ len(a.ReferencedColumns) != len(b.ReferencedColumns) {
+ return false
+ }
+
+ for i := range a.Columns {
+ if a.Columns[i] != b.Columns[i] {
+ return false
+ }
+ }
+
+ for i := range a.ReferencedColumns {
+ if a.ReferencedColumns[i] != b.ReferencedColumns[i] {
+ return false
+ }
+ }
+
+ return true
+}
+
+// extractCheckConstraintDefinitionsWithAST extracts check constraint definitions with their AST nodes
+// Note: This is a wrapper around the existing function with a different name for clarity
+func extractCheckConstraintDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*CheckConstraintDefWithAST {
+ return extractCheckConstraintDefinitionsInOrder(createStmt)
+}
+
+// extractForeignKeyDefinitionsWithAST extracts foreign key constraint definitions with their AST nodes
+// Note: This is a wrapper around the existing function with a different name for clarity
+func extractForeignKeyDefinitionsWithAST(createStmt *parser.CreatestmtContext) []*ForeignKeyDefWithAST {
+ return extractForeignKeyDefinitionsInOrder(createStmt)
+}
+
+// PrimaryKeyDefWithAST represents a primary key constraint definition with its AST node
+type PrimaryKeyDefWithAST struct {
+ Name string
+ ASTNode parser.ITableconstraintContext
+}
+
+// UniqueKeyDefWithAST represents a unique key constraint definition with its AST node
+type UniqueKeyDefWithAST struct {
+ Name string
+ ASTNode parser.ITableconstraintContext
+}
+
+// extractPrimaryKeyDefinitionsInOrder extracts primary key constraint definitions with their AST nodes
+func extractPrimaryKeyDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*PrimaryKeyDefWithAST {
+ var pkDefs []*PrimaryKeyDefWithAST
+
+ if createStmt == nil {
+ return pkDefs
+ }
+
+ // Navigate through the CREATE TABLE AST to find table constraints
+ optTableElementList := createStmt.Opttableelementlist()
+ if optTableElementList == nil {
+ return pkDefs
+ }
+
+ tableElementList := optTableElementList.(*parser.OpttableelementlistContext).Tableelementlist()
+ if tableElementList == nil {
+ return pkDefs
+ }
+
+ // Iterate through table elements to find constraints
+ for _, element := range tableElementList.(*parser.TableelementlistContext).AllTableelement() {
+ if tableConstraint := element.(*parser.TableelementContext).Tableconstraint(); tableConstraint != nil {
+ constraint, ok := tableConstraint.(*parser.TableconstraintContext)
+ if !ok {
+ continue
+ }
+
+ // Check if it's a primary key constraint
+ if constraint.Constraintelem() != nil {
+ elem, ok := constraint.Constraintelem().(*parser.ConstraintelemContext)
+ if !ok {
+ continue
+ }
+ if elem.PRIMARY() != nil && elem.KEY() != nil {
+ // Extract constraint name
+ constraintName := ""
+ if constraint.Name() != nil {
+ constraintName = pgparser.NormalizePostgreSQLName(constraint.Name())
+ }
+
+ if constraintName != "" {
+ pkDefs = append(pkDefs, &PrimaryKeyDefWithAST{
+ Name: constraintName,
+ ASTNode: constraint,
+ })
+ }
+ }
+ }
+ }
+ }
+
+ return pkDefs
+}
+
+// extractUniqueKeyDefinitionsInOrder extracts unique key constraint definitions with their AST nodes
+func extractUniqueKeyDefinitionsInOrder(createStmt *parser.CreatestmtContext) []*UniqueKeyDefWithAST {
+ var ukDefs []*UniqueKeyDefWithAST
+
+ if createStmt == nil {
+ return ukDefs
+ }
+
+ // Navigate through the CREATE TABLE AST to find table constraints
+ optTableElementList := createStmt.Opttableelementlist()
+ if optTableElementList == nil {
+ return ukDefs
+ }
+
+ tableElementList := optTableElementList.(*parser.OpttableelementlistContext).Tableelementlist()
+ if tableElementList == nil {
+ return ukDefs
+ }
+
+ // Iterate through table elements to find constraints
+ for _, element := range tableElementList.(*parser.TableelementlistContext).AllTableelement() {
+ if tableConstraint := element.(*parser.TableelementContext).Tableconstraint(); tableConstraint != nil {
+ constraint, ok := tableConstraint.(*parser.TableconstraintContext)
+ if !ok {
+ continue
+ }
+
+ // Check if it's a unique constraint
+ if constraint.Constraintelem() != nil {
+ elem, ok := constraint.Constraintelem().(*parser.ConstraintelemContext)
+ if !ok {
+ continue
+ }
+ if elem.UNIQUE() != nil {
+ // Extract constraint name
+ constraintName := ""
+ if constraint.Name() != nil {
+ constraintName = pgparser.NormalizePostgreSQLName(constraint.Name())
+ }
+
+ if constraintName != "" {
+ ukDefs = append(ukDefs, &UniqueKeyDefWithAST{
+ Name: constraintName,
+ ASTNode: constraint,
+ })
+ }
+ }
+ }
+ }
+ }
+
+ return ukDefs
+}
+
+// pkConstraintsEqual checks if two primary key constraints are equal
+func pkConstraintsEqual(a, b *storepb.IndexMetadata) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+
+ // Compare basic properties
+ if a.Name != b.Name || a.Primary != b.Primary {
+ return false
+ }
+
+ // Compare expressions (columns)
+ if len(a.Expressions) != len(b.Expressions) {
+ return false
+ }
+
+ for i := range a.Expressions {
+ if a.Expressions[i] != b.Expressions[i] {
+ return false
+ }
+ }
+
+ return true
+}
+
+// ukConstraintsEqual checks if two unique key constraints are equal
+func ukConstraintsEqual(a, b *storepb.IndexMetadata) bool {
+ if a == nil || b == nil {
+ return a == b
+ }
+
+ // Compare basic properties
+ if a.Name != b.Name || a.Unique != b.Unique || a.IsConstraint != b.IsConstraint {
+ return false
+ }
+
+ // Compare expressions (columns)
+ if len(a.Expressions) != len(b.Expressions) {
+ return false
+ }
+
+ for i := range a.Expressions {
+ if a.Expressions[i] != b.Expressions[i] {
+ return false
+ }
+ }
+
+ return true
+}
+
+// generatePrimaryKeyConstraintSDL generates SDL text for a primary key constraint
+func generatePrimaryKeyConstraintSDL(constraint *storepb.IndexMetadata) string {
+ if constraint == nil || !constraint.Primary {
+ return ""
+ }
+
+ var buf strings.Builder
+ err := writePrimaryKeyConstraintSDL(&buf, constraint)
+ if err != nil {
+ return ""
+ }
+ return buf.String()
+}
+
+// generateUniqueKeyConstraintSDL generates SDL text for a unique key constraint
+func generateUniqueKeyConstraintSDL(constraint *storepb.IndexMetadata) string {
+ if constraint == nil || !constraint.Unique || constraint.Primary || !constraint.IsConstraint {
+ return ""
+ }
+
+ var buf strings.Builder
+ err := writeUniqueKeyConstraintSDL(&buf, constraint)
+ if err != nil {
+ return ""
+ }
+ return buf.String()
+}